

Rust Documentation
==================

 *by Steve Klabnik and Carol Nichols, with contributions from the Rust Community*

 This version of the text assumes you’re using Rust 1.67.1 (released 2023-02-09) or later. See the [“Installation” section of Chapter 1](book/ch01-01-installation) to install or update Rust.

 The HTML format is available online at [https://doc.rust-lang.org/stable/book/](https://doc.rust-lang.org/stable/book/index.html) and offline with installations of Rust made with `rustup`; run `rustup docs --book` to open.

 Several community [translations](book/appendix-06-translation) are also available.

 This text is available in [paperback and ebook format from No Starch Press](https://nostarch.com/rust-programming-language-2nd-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>
> 
>  



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/index.html>

The Rust Programming Language
=============================

 *by Steve Klabnik and Carol Nichols, with contributions from the Rust Community*

 This version of the text assumes you’re using Rust 1.67.1 (released 2023-02-09) or later. See the [“Installation” section of Chapter 1](ch01-01-installation) to install or update Rust.

 The HTML format is available online at [https://doc.rust-lang.org/stable/book/](https://doc.rust-lang.org/stable/book/index.html) and offline with installations of Rust made with `rustup`; run `rustup docs --book` to open.

 Several community [translations](appendix-06-translation) are also available.

 This text is available in [paperback and ebook format from No Starch Press](https://nostarch.com/rust-programming-language-2nd-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>
> 
>  



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/title-page.html>

An Example Program Using Structs
================================

 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: 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 [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”](ch03-02-data-types#the-tuple-type) section of Chapter 3: by using tuples.

 ### Refactoring with 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: 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.

 ### Refactoring with Structs: Adding More Meaning

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

 ### Adding Useful Functionality with Derived Traits

 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](../std/macro.println) 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: 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 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: 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 [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 [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](../std/macro.dbg), 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 [“Writing Error Messages to Standard Error Instead of Standard Output” section in Chapter 12](ch12-06-writing-to-stderr-instead-of-stdout).
> 
>  

 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 [unoptimized + debuginfo] target(s) in 0.61s
     Running `target/debug/rectangles`
[src/main.rs:10] 30 * scale = 60
[src/main.rs:14] &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](appendix-03-derivable-traits). 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](../reference/attributes).

 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.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch05-02-example-structs.html>

Foreword
========

 It wasn’t always so clear, but the Rust programming language is fundamentally about *empowerment*: no matter what kind of code you are writing now, Rust empowers you to reach farther, to program with confidence in a wider variety of domains than you did before.

 Take, for example, “systems-level” work that deals with low-level details of memory management, data representation, and concurrency. Traditionally, this realm of programming is seen as arcane, accessible only to a select few who have devoted the necessary years learning to avoid its infamous pitfalls. And even those who practice it do so with caution, lest their code be open to exploits, crashes, or corruption.

 Rust breaks down these barriers by eliminating the old pitfalls and providing a friendly, polished set of tools to help you along the way. Programmers who need to “dip down” into lower-level control can do so with Rust, without taking on the customary risk of crashes or security holes, and without having to learn the fine points of a fickle toolchain. Better yet, the language is designed to guide you naturally towards reliable code that is efficient in terms of speed and memory usage.

 Programmers who are already working with low-level code can use Rust to raise their ambitions. For example, introducing parallelism in Rust is a relatively low-risk operation: the compiler will catch the classical mistakes for you. And you can tackle more aggressive optimizations in your code with the confidence that you won’t accidentally introduce crashes or vulnerabilities.

 But Rust isn’t limited to low-level systems programming. It’s expressive and ergonomic enough to make CLI apps, web servers, and many other kinds of code quite pleasant to write — you’ll find simple examples of both later in the book. Working with Rust allows you to build skills that transfer from one domain to another; you can learn Rust by writing a web app, then apply those same skills to target your Raspberry Pi.

 This book fully embraces the potential of Rust to empower its users. It’s a friendly and approachable text intended to help you level up not just your knowledge of Rust, but also your reach and confidence as a programmer in general. So dive in, get ready to learn—and welcome to the Rust community!

 — Nicholas Matsakis and Aaron Turon



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/foreword.html>

Introduction
============

 
>  Note: This edition of the book is the same as [The Rust Programming Language](https://nostarch.com/rust-programming-language-2nd-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.

 Who Rust Is For
---------------

 Rust is ideal for many people for a variety of reasons. Let’s look at a few of the most important groups.

 ### Teams of Developers

 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 be caught only 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 their 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.

 ### Students

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

 ### Companies

 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.

 ### Open Source Developers

 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.

 ### People Who Value Speed and Stability

 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.

 Who This Book Is For
--------------------

 This book assumes that you’ve written code in another programming language but 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.

 How to Use This Book
--------------------

 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. Chapters 2, 12, and 20 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. Chapter 3 covers Rust features that are similar to those of other programming languages, and in Chapter 4 you’ll learn about Rust’s ownership system. 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, returning to Chapter 2 when you’d like to work on a project applying the details you’ve learned.

 Chapter 5 discusses structs and methods, and Chapter 6 covers enums, `match` expressions, and the `if let` control flow construct. You’ll use structs and enums to make custom types in Rust.

 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, such as 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 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 to program in multiple threads fearlessly. Chapter 17 looks at how Rust idioms compare to object-oriented programming principles you might be familiar with.

 Chapter 18 is a reference on patterns and pattern matching, which are powerful ways of expressing ideas throughout Rust programs. Chapter 19 contains a smorgasbord of advanced topics of interest, including unsafe Rust, macros, and more about lifetimes, traits, types, functions, and closures.

 In Chapter 20, we’ll complete a project in which we’ll implement a low-level multithreaded web server!

 Finally, some appendices 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. Ferris will also help you distinguish code that isn’t meant to work:

 


| Ferris | Meaning |
| --- | --- |
| Ferris with a question mark | This code does not compile! |
| Ferris throwing up their hands | This code panics! |
| Ferris with one claw up, shrugging | 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.

 Source Code
-----------

 The source files from which this book is generated can be found on [GitHub](https://github.com/rust-lang/book/tree/main/src).



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch00-00-introduction.html>

Installation
============

 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.

 
>  ### Command Line Notation
> 
>  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 `$`.
> 
>  

 ### Installing `rustup` on Linux or macOS

 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.

 ### Installing `rustup` on Windows

 On Windows, go to <https://www.rust-lang.org/tools/install> and follow the instructions for installing Rust. At some point in the installation, you’ll receive a message explaining that you’ll also need the MSVC build tools for Visual Studio 2013 or later.

 To acquire the build tools, you’ll need to install [Visual Studio 2022](https://visualstudio.microsoft.com/downloads/). When asked which workloads to install, include:

 * “Desktop Development with C++”
* The Windows 10 or 11 SDK
* The English language pack component, along with any other language pack of your choosing

 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.

 ### Troubleshooting

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

 ### Updating and Uninstalling

 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

```
 ### Local Documentation

 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!



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch01-01-installation.html>

References and Borrowing
========================

 The issue with the tuple code in Listing 4-5 is that we have to return the `String` to the calling function so we can still use the `String` after the call to `calculate_length`, because the `String` was moved into `calculate_length`. Instead, we can provide a reference to the `String` value. A *reference* is like a pointer in that it’s an address we can follow to access the data stored at that address; that data is owned by some other variable. Unlike a pointer, a reference is guaranteed to point to a valid value of a particular type for the life of that reference.

 Here is how you would define and use a `calculate_length` function that has a reference to an object as a parameter instead of taking ownership of the value:

 Filename: src/main.rs

 
```
fn main() {
    let s1 = String::from("hello");

    let len = calculate_length(&s1);

    println!("The length of '{}' is {}.", s1, len);
}

fn calculate_length(s: &String) -> usize {
    s.len()
}
```
 First, notice that all the tuple code in the variable declaration and the function return value is gone. Second, note that we pass `&s1` into `calculate_length` and, in its definition, we take `&String` rather than `String`. These ampersands represent *references*, and they allow you to refer to some value without taking ownership of it. Figure 4-5 depicts this concept.

 ![Three tables: the table for s contains only a pointer to the table
for s1. The table for s1 contains the stack data for s1 and points to the
string data on the heap.]

 Figure 4-5: A diagram of `&String s` pointing at `String s1`

 
>  Note: The opposite of referencing by using `&` is *dereferencing*, which is accomplished with the dereference operator, `*`. We’ll see some uses of the dereference operator in Chapter 8 and discuss details of dereferencing in Chapter 15.
> 
>  

 Let’s take a closer look at the function call here:

 
```
fn main() {
    let s1 = String::from("hello");

    let len = calculate_length(&s1);

    println!("The length of '{}' is {}.", s1, len);
}

fn calculate_length(s: &String) -> usize {
    s.len()
}
```
 The `&s1` syntax lets us create a reference that *refers* to the value of `s1` but does not own it. Because it does not own it, the value it points to will not be dropped when the reference stops being used.

 Likewise, the signature of the function uses `&` to indicate that the type of the parameter `s` is a reference. Let’s add some explanatory annotations:

 
```
fn main() {
    let s1 = String::from("hello");

    let len = calculate_length(&s1);

    println!("The length of '{}' is {}.", s1, len);
}

fn calculate_length(s: &String) -> usize { // s is a reference to a String
    s.len()
} // Here, s goes out of scope. But because it does not have ownership of what
  // it refers to, it is not dropped.
```
 The scope in which the variable `s` is valid is the same as any function parameter’s scope, but the value pointed to by the reference is not dropped when `s` stops being used, because `s` doesn’t have ownership. When functions have references as parameters instead of the actual values, we won’t need to return the values in order to give back ownership, because we never had ownership.

 We call the action of creating a reference *borrowing*. As in real life, if a person owns something, you can borrow it from them. When you’re done, you have to give it back. You don’t own it.

 So, what happens if we try to modify something we’re borrowing? Try the code in Listing 4-6. Spoiler alert: it doesn’t work!

 Filename: src/main.rs

 
```
fn main() {
    let s = String::from("hello");

    change(&s);
}

fn change(some_string: &String) {
    some_string.push_str(", world");
}
```
 Listing 4-6: Attempting to modify a borrowed value

 Here’s the error:

 
```
$ cargo run
   Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0596]: cannot borrow `*some_string` as mutable, as it is behind a `&` reference
 --> src/main.rs:8:5
  |
7 | fn change(some_string: &String) {
  |                        ------- help: consider changing this to be a mutable reference: `&mut String`
8 |     some_string.push_str(", world");
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `some_string` is a `&` reference, so the data it refers to cannot be borrowed as mutable

For more information about this error, try `rustc --explain E0596`.
error: could not compile `ownership` due to previous error

```
 Just as variables are immutable by default, so are references. We’re not allowed to modify something we have a reference to.

 ### Mutable References

 We can fix the code from Listing 4-6 to allow us to modify a borrowed value with just a few small tweaks that use, instead, a *mutable reference*:

 Filename: src/main.rs

 
```
fn main() {
    let mut s = String::from("hello");

    change(&mut s);
}

fn change(some_string: &mut String) {
    some_string.push_str(", world");
}
```
 First we change `s` to be `mut`. Then we create a mutable reference with `&mut s` where we call the `change` function, and update the function signature to accept a mutable reference with `some_string: &mut String`. This makes it very clear that the `change` function will mutate the value it borrows.

 Mutable references have one big restriction: if you have a mutable reference to a value, you can have no other references to that value. This code that attempts to create two mutable references to `s` will fail:

 Filename: src/main.rs

 
```
fn main() {
    let mut s = String::from("hello");

    let r1 = &mut s;
    let r2 = &mut s;

    println!("{}, {}", r1, r2);
}
```
 Here’s the error:

 
```
$ cargo run
   Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0499]: cannot borrow `s` as mutable more than once at a time
 --> src/main.rs:5:14
  |
4 |     let r1 = &mut s;
  |              ------ first mutable borrow occurs here
5 |     let r2 = &mut s;
  |              ^^^^^^ second mutable borrow occurs here
6 |
7 |     println!("{}, {}", r1, r2);
  |                        -- first borrow later used here

For more information about this error, try `rustc --explain E0499`.
error: could not compile `ownership` due to previous error

```
 This error says that this code is invalid because we cannot borrow `s` as mutable more than once at a time. The first mutable borrow is in `r1` and must last until it’s used in the `println!`, but between the creation of that mutable reference and its usage, we tried to create another mutable reference in `r2` that borrows the same data as `r1`.

 The restriction preventing multiple mutable references to the same data at the same time allows for mutation but in a very controlled fashion. It’s something that new Rustaceans struggle with because most languages let you mutate whenever you’d like. The benefit of having this restriction is that Rust can prevent data races at compile time. A *data race* is similar to a race condition and happens when these three behaviors occur:

 * Two or more pointers access the same data at the same time.
* At least one of the pointers is being used to write to the data.
* There’s no mechanism being used to synchronize access to the data.

 Data races cause undefined behavior and can be difficult to diagnose and fix when you’re trying to track them down at runtime; Rust prevents this problem by refusing to compile code with data races!

 As always, we can use curly brackets to create a new scope, allowing for multiple mutable references, just not *simultaneous* ones:

 
```
fn main() {
    let mut s = String::from("hello");

    {
        let r1 = &mut s;
    } // r1 goes out of scope here, so we can make a new reference with no problems.

    let r2 = &mut s;
}
```
 Rust enforces a similar rule for combining mutable and immutable references. This code results in an error:

 
```
fn main() {
    let mut s = String::from("hello");

    let r1 = &s; // no problem
    let r2 = &s; // no problem
    let r3 = &mut s; // BIG PROBLEM

    println!("{}, {}, and {}", r1, r2, r3);
}
```
 Here’s the error:

 
```
$ cargo run
   Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
 --> src/main.rs:6:14
  |
4 |     let r1 = &s; // no problem
  |              -- immutable borrow occurs here
5 |     let r2 = &s; // no problem
6 |     let r3 = &mut s; // BIG PROBLEM
  |              ^^^^^^ mutable borrow occurs here
7 |
8 |     println!("{}, {}, and {}", r1, r2, r3);
  |                                -- immutable borrow later used here

For more information about this error, try `rustc --explain E0502`.
error: could not compile `ownership` due to previous error

```
 Whew! We *also* cannot have a mutable reference while we have an immutable one to the same value.

 Users of an immutable reference don’t expect the value to suddenly change out from under them! However, multiple immutable references are allowed because no one who is just reading the data has the ability to affect anyone else’s reading of the data.

 Note that a reference’s scope starts from where it is introduced and continues through the last time that reference is used. For instance, this code will compile because the last usage of the immutable references, the `println!`, occurs before the mutable reference is introduced:

 
```
fn main() {
    let mut s = String::from("hello");

    let r1 = &s; // no problem
    let r2 = &s; // no problem
    println!("{} and {}", r1, r2);
    // variables r1 and r2 will not be used after this point

    let r3 = &mut s; // no problem
    println!("{}", r3);
}
```
 The scopes of the immutable references `r1` and `r2` end after the `println!` where they are last used, which is before the mutable reference `r3` is created. These scopes don’t overlap, so this code is allowed: the compiler can tell that the reference is no longer being used at a point before the end of the scope.

 Even though borrowing errors may be frustrating at times, remember that it’s the Rust compiler pointing out a potential bug early (at compile time rather than at runtime) and showing you exactly where the problem is. Then you don’t have to track down why your data isn’t what you thought it was.

 ### Dangling References

 In languages with pointers, it’s easy to erroneously create a *dangling pointer*—a pointer that references a location in memory that may have been given to someone else—by freeing some memory while preserving a pointer to that memory. In Rust, by contrast, the compiler guarantees that references will never be dangling references: if you have a reference to some data, the compiler will ensure that the data will not go out of scope before the reference to the data does.

 Let’s try to create a dangling reference to see how Rust prevents them with a compile-time error:

 Filename: src/main.rs

 
```
fn main() {
    let reference_to_nothing = dangle();
}

fn dangle() -> &String {
    let s = String::from("hello");

    &s
}
```
 Here’s the error:

 
```
$ cargo run
   Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0106]: missing lifetime specifier
 --> src/main.rs:5:16
  |
5 | fn dangle() -> &String {
  |                ^ expected named lifetime parameter
  |
  = help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
help: consider using the `'static` lifetime
  |
5 | fn dangle() -> &'static String {
  |                 +++++++

For more information about this error, try `rustc --explain E0106`.
error: could not compile `ownership` due to previous error

```
 This error message refers to a feature we haven’t covered yet: lifetimes. We’ll discuss lifetimes in detail in Chapter 10. But, if you disregard the parts about lifetimes, the message does contain the key to why this code is a problem:

 
```
this function's return type contains a borrowed value, but there is no value
for it to be borrowed from

```
 Let’s take a closer look at exactly what’s happening at each stage of our `dangle` code:

 Filename: src/main.rs

 
```
fn main() {
    let reference_to_nothing = dangle();
}

fn dangle() -> &String { // dangle returns a reference to a String

    let s = String::from("hello"); // s is a new String

    &s // we return a reference to the String, s
} // Here, s goes out of scope, and is dropped. Its memory goes away.
  // Danger!
```
 Because `s` is created inside `dangle`, when the code of `dangle` is finished, `s` will be deallocated. But we tried to return a reference to it. That means this reference would be pointing to an invalid `String`. That’s no good! Rust won’t let us do this.

 The solution here is to return the `String` directly:

 
```
fn main() {
    let string = no_dangle();
}

fn no_dangle() -> String {
    let s = String::from("hello");

    s
}
```
 This works without any problems. Ownership is moved out, and nothing is deallocated.

 ### The Rules of References

 Let’s recap what we’ve discussed about references:

 * At any given time, you can have *either* one mutable reference *or* any number of immutable references.
* References must always be valid.

 Next, we’ll look at a different kind of reference: slices.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html>

The Slice Type
==============

 *Slices* let you reference a contiguous sequence of elements in a collection rather than the whole collection. A slice is a kind of reference, so it does not have ownership.

 Here’s a small programming problem: write a function that takes a string of words separated by spaces and returns the first word it finds in that string. If the function doesn’t find a space in the string, the whole string must be one word, so the entire string should be returned.

 Let’s work through how we’d write the signature of this function without using slices, to understand the problem that slices will solve:

 
```
fn first_word(s: &String) -> ?
```
 The `first_word` function has a `&String` as a parameter. We don’t want ownership, so this is fine. But what should we return? We don’t really have a way to talk about *part* of a string. However, we could return the index of the end of the word, indicated by a space. Let’s try that, as shown in Listing 4-7.

 Filename: src/main.rs

 
```
fn first_word(s: &String) -> usize {
    let bytes = s.as_bytes();

    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return i;
        }
    }

    s.len()
}

fn main() {}
```
 Listing 4-7: The `first_word` function that returns a byte index value into the `String` parameter

 Because we need to go through the `String` element by element and check whether a value is a space, we’ll convert our `String` to an array of bytes using the `as_bytes` method.

 
```
fn first_word(s: &String) -> usize {
    let bytes = s.as_bytes();

    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return i;
        }
    }

    s.len()
}

fn main() {}
```
 Next, we create an iterator over the array of bytes using the `iter` method:

 
```
fn first_word(s: &String) -> usize {
    let bytes = s.as_bytes();

    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return i;
        }
    }

    s.len()
}

fn main() {}
```
 We’ll discuss iterators in more detail in [Chapter 13](ch13-02-iterators). For now, know that `iter` is a method that returns each element in a collection and that `enumerate` wraps the result of `iter` and returns each element as part of a tuple instead. The first element of the tuple returned from `enumerate` is the index, and the second element is a reference to the element. This is a bit more convenient than calculating the index ourselves.

 Because the `enumerate` method returns a tuple, we can use patterns to destructure that tuple. We’ll be discussing patterns more in [Chapter 6](ch06-02-match#patterns-that-bind-to-values). In the `for` loop, we specify a pattern that has `i` for the index in the tuple and `&item` for the single byte in the tuple. Because we get a reference to the element from `.iter().enumerate()`, we use `&` in the pattern.

 Inside the `for` loop, we search for the byte that represents the space by using the byte literal syntax. If we find a space, we return the position. Otherwise, we return the length of the string by using `s.len()`.

 
```
fn first_word(s: &String) -> usize {
    let bytes = s.as_bytes();

    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return i;
        }
    }

    s.len()
}

fn main() {}
```
 We now have a way to find out the index of the end of the first word in the string, but there’s a problem. We’re returning a `usize` on its own, but it’s only a meaningful number in the context of the `&String`. In other words, because it’s a separate value from the `String`, there’s no guarantee that it will still be valid in the future. Consider the program in Listing 4-8 that uses the `first_word` function from Listing 4-7.

 Filename: src/main.rs

 
```
fn first_word(s: &String) -> usize {
    let bytes = s.as_bytes();

    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return i;
        }
    }

    s.len()
}

fn main() {
    let mut s = String::from("hello world");

    let word = first_word(&s); // word will get the value 5

    s.clear(); // this empties the String, making it equal to ""

    // word still has the value 5 here, but there's no more string that
    // we could meaningfully use the value 5 with. word is now totally invalid!
}
```
 Listing 4-8: Storing the result from calling the `first_word` function and then changing the `String` contents

 This program compiles without any errors and would also do so if we used `word` after calling `s.clear()`. Because `word` isn’t connected to the state of `s` at all, `word` still contains the value `5`. We could use that value `5` with the variable `s` to try to extract the first word out, but this would be a bug because the contents of `s` have changed since we saved `5` in `word`.

 Having to worry about the index in `word` getting out of sync with the data in `s` is tedious and error prone! Managing these indices is even more brittle if we write a `second_word` function. Its signature would have to look like this:

 
```
fn second_word(s: &String) -> (usize, usize) {
```
 Now we’re tracking a starting *and* an ending index, and we have even more values that were calculated from data in a particular state but aren’t tied to that state at all. We have three unrelated variables floating around that need to be kept in sync.

 Luckily, Rust has a solution to this problem: string slices.

 ### String Slices

 A *string slice* is a reference to part of a `String`, and it looks like this:

 
```
fn main() {
    let s = String::from("hello world");

    let hello = &s[0..5];
    let world = &s[6..11];
}
```
 Rather than a reference to the entire `String`, `hello` is a reference to a portion of the `String`, specified in the extra `[0..5]` bit. We create slices using a range within brackets by specifying `[starting_index..ending_index]`, where `starting_index` is the first position in the slice and `ending_index` is one more than the last position in the slice. Internally, the slice data structure stores the starting position and the length of the slice, which corresponds to `ending_index` minus `starting_index`. So, in the case of `let world = &s[6..11];`, `world` would be a slice that contains a pointer to the byte at index 6 of `s` with a length value of `5`.

 Figure 4-6 shows this in a diagram.

 ![Three tables: a table representing the stack data of s, which points
to the byte at index 0 in a table of the string data "hello world" on
the heap. The third table rep-resents the stack data of the slice world, which
has a length value of 5 and points to byte 6 of the heap data table.]

 Figure 4-6: String slice referring to part of a `String`

 With Rust’s `..` range syntax, if you want to start at index 0, you can drop the value before the two periods. In other words, these are equal:

 
```
#![allow(unused)]
fn main() {
let s = String::from("hello");

let slice = &s[0..2];
let slice = &s[..2];
}
```
 By the same token, if your slice includes the last byte of the `String`, you can drop the trailing number. That means these are equal:

 
```
#![allow(unused)]
fn main() {
let s = String::from("hello");

let len = s.len();

let slice = &s[3..len];
let slice = &s[3..];
}
```
 You can also drop both values to take a slice of the entire string. So these are equal:

 
```
#![allow(unused)]
fn main() {
let s = String::from("hello");

let len = s.len();

let slice = &s[0..len];
let slice = &s[..];
}
```
 
>  Note: String slice range indices must occur at valid UTF-8 character boundaries. If you attempt to create a string slice in the middle of a multibyte character, your program will exit with an error. For the purposes of introducing string slices, we are assuming ASCII only in this section; a more thorough discussion of UTF-8 handling is in the [“Storing UTF-8 Encoded Text with Strings”](ch08-02-strings#storing-utf-8-encoded-text-with-strings) section of Chapter 8.
> 
>  

 With all this information in mind, let’s rewrite `first_word` to return a slice. The type that signifies “string slice” is written as `&str`:

 Filename: src/main.rs

 
```
fn first_word(s: &String) -> &str {
    let bytes = s.as_bytes();

    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return &s[0..i];
        }
    }

    &s[..]
}

fn main() {}
```
 We get the index for the end of the word the same way we did in Listing 4-7, by looking for the first occurrence of a space. When we find a space, we return a string slice using the start of the string and the index of the space as the starting and ending indices.

 Now when we call `first_word`, we get back a single value that is tied to the underlying data. The value is made up of a reference to the starting point of the slice and the number of elements in the slice.

 Returning a slice would also work for a `second_word` function:

 
```
fn second_word(s: &String) -> &str {
```
 We now have a straightforward API that’s much harder to mess up because the compiler will ensure the references into the `String` remain valid. Remember the bug in the program in Listing 4-8, when we got the index to the end of the first word but then cleared the string so our index was invalid? That code was logically incorrect but didn’t show any immediate errors. The problems would show up later if we kept trying to use the first word index with an emptied string. Slices make this bug impossible and let us know we have a problem with our code much sooner. Using the slice version of `first_word` will throw a compile-time error:

 Filename: src/main.rs

 
```
fn first_word(s: &String) -> &str {
    let bytes = s.as_bytes();

    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return &s[0..i];
        }
    }

    &s[..]
}

fn main() {
    let mut s = String::from("hello world");

    let word = first_word(&s);

    s.clear(); // error!

    println!("the first word is: {}", word);
}
```
 Here’s the compiler error:

 
```
$ cargo run
   Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
  --> src/main.rs:18:5
   |
16 |     let word = first_word(&s);
   |                           -- immutable borrow occurs here
17 |
18 |     s.clear(); // error!
   |     ^^^^^^^^^ mutable borrow occurs here
19 |
20 |     println!("the first word is: {}", word);
   |                                       ---- immutable borrow later used here

For more information about this error, try `rustc --explain E0502`.
error: could not compile `ownership` due to previous error

```
 Recall from the borrowing rules that if we have an immutable reference to something, we cannot also take a mutable reference. Because `clear` needs to truncate the `String`, it needs to get a mutable reference. The `println!` after the call to `clear` uses the reference in `word`, so the immutable reference must still be active at that point. Rust disallows the mutable reference in `clear` and the immutable reference in `word` from existing at the same time, and compilation fails. Not only has Rust made our API easier to use, but it has also eliminated an entire class of errors at compile time!

 #### String Literals as Slices

 Recall that we talked about string literals being stored inside the binary. Now that we know about slices, we can properly understand string literals:

 
```
#![allow(unused)]
fn main() {
let s = "Hello, world!";
}
```
 The type of `s` here is `&str`: it’s a slice pointing to that specific point of the binary. This is also why string literals are immutable; `&str` is an immutable reference.

 #### String Slices as Parameters

 Knowing that you can take slices of literals and `String` values leads us to one more improvement on `first_word`, and that’s its signature:

 
```
fn first_word(s: &String) -> &str {
```
 A more experienced Rustacean would write the signature shown in Listing 4-9 instead because it allows us to use the same function on both `&String` values and `&str` values.

 
```
fn first_word(s: &str) -> &str {
    let bytes = s.as_bytes();

    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return &s[0..i];
        }
    }

    &s[..]
}

fn main() {
    let my_string = String::from("hello world");

    // `first_word` works on slices of `String`s, whether partial or whole
    let word = first_word(&my_string[0..6]);
    let word = first_word(&my_string[..]);
    // `first_word` also works on references to `String`s, which are equivalent
    // to whole slices of `String`s
    let word = first_word(&my_string);

    let my_string_literal = "hello world";

    // `first_word` works on slices of string literals, whether partial or whole
    let word = first_word(&my_string_literal[0..6]);
    let word = first_word(&my_string_literal[..]);

    // Because string literals *are* string slices already,
    // this works too, without the slice syntax!
    let word = first_word(my_string_literal);
}
```
 Listing 4-9: Improving the `first_word` function by using a string slice for the type of the `s` parameter

 If we have a string slice, we can pass that directly. If we have a `String`, we can pass a slice of the `String` or a reference to the `String`. This flexibility takes advantage of *deref coercions*, a feature we will cover in [“Implicit Deref Coercions with Functions and Methods”](ch15-02-deref#implicit-deref-coercions-with-functions-and-methods) section of Chapter 15.

 Defining a function to take a string slice instead of a reference to a `String` makes our API more general and useful without losing any functionality:

 Filename: src/main.rs

 
```
fn first_word(s: &str) -> &str {
    let bytes = s.as_bytes();

    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return &s[0..i];
        }
    }

    &s[..]
}

fn main() {
    let my_string = String::from("hello world");

    // `first_word` works on slices of `String`s, whether partial or whole
    let word = first_word(&my_string[0..6]);
    let word = first_word(&my_string[..]);
    // `first_word` also works on references to `String`s, which are equivalent
    // to whole slices of `String`s
    let word = first_word(&my_string);

    let my_string_literal = "hello world";

    // `first_word` works on slices of string literals, whether partial or whole
    let word = first_word(&my_string_literal[0..6]);
    let word = first_word(&my_string_literal[..]);

    // Because string literals *are* string slices already,
    // this works too, without the slice syntax!
    let word = first_word(my_string_literal);
}
```
 ### Other Slices

 String slices, as you might imagine, are specific to strings. But there’s a more general slice type too. Consider this array:

 
```
#![allow(unused)]
fn main() {
let a = [1, 2, 3, 4, 5];
}
```
 Just as we might want to refer to part of a string, we might want to refer to part of an array. We’d do so like this:

 
```
#![allow(unused)]
fn main() {
let a = [1, 2, 3, 4, 5];

let slice = &a[1..3];

assert_eq!(slice, &[2, 3]);
}
```
 This slice has the type `&[i32]`. It works the same way as string slices do, by storing a reference to the first element and a length. You’ll use this kind of slice for all sorts of other collections. We’ll discuss these collections in detail when we talk about vectors in Chapter 8.

 Summary
-------

 The concepts of ownership, borrowing, and slices ensure memory safety in Rust programs at compile time. The Rust language gives you control over your memory usage in the same way as other systems programming languages, but having the owner of data automatically clean up that data when the owner goes out of scope means you don’t have to write and debug extra code to get this control.

 Ownership affects how lots of other parts of Rust work, so we’ll talk about these concepts further throughout the rest of the book. Let’s move on to Chapter 5 and look at grouping pieces of data together in a `struct`.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch04-03-slices.html>

Using Structs to Structure Related Data
=======================================

 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.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch05-00-structs.html>

Defining and Instantiating Structs
==================================

 Structs are similar to tuples, discussed in [“The Tuple Type”](ch03-02-data-types#the-tuple-type) section, in that both hold multiple related values. Like tuples, the pieces of a struct can be different types. Unlike with tuples, in a struct you’ll name each piece of data so it’s clear what the values mean. Adding these names means that structs are more flexible than tuples: you don’t have to rely on the order of the data to specify or access the values of an instance.

 To define a struct, we enter the keyword `struct` and name the entire struct. A struct’s name should describe the significance of the pieces of data being grouped together. Then, inside curly brackets, we define the names and types of the pieces of data, which we call *fields*. For example, Listing 5-1 shows a struct that stores information about a user account.

 Filename: src/main.rs

 
```
struct User {
    active: bool,
    username: String,
    email: String,
    sign_in_count: u64,
}

fn main() {}
```
 Listing 5-1: A `User` struct definition

 To use a struct after we’ve defined it, we create an *instance* of that struct by specifying concrete values for each of the fields. We create an instance by stating the name of the struct and then add curly brackets containing *key: value* pairs, where the keys are the names of the fields and the values are the data we want to store in those fields. We don’t have to specify the fields in the same order in which we declared them in the struct. In other words, the struct definition is like a general template for the type, and instances fill in that template with particular data to create values of the type. For example, we can declare a particular user as shown in Listing 5-2.

 Filename: src/main.rs

 
```
struct User {
    active: bool,
    username: String,
    email: String,
    sign_in_count: u64,
}

fn main() {
    let user1 = User {
        active: true,
        username: String::from("someusername123"),
        email: String::from("someone@example.com"),
        sign_in_count: 1,
    };
}
```
 Listing 5-2: Creating an instance of the `User` struct

 To get a specific value from a struct, we use dot notation. For example, to access this user’s email address, we use `user1.email`. If the instance is mutable, we can change a value by using the dot notation and assigning into a particular field. Listing 5-3 shows how to change the value in the `email` field of a mutable `User` instance.

 Filename: src/main.rs

 
```
struct User {
    active: bool,
    username: String,
    email: String,
    sign_in_count: u64,
}

fn main() {
    let mut user1 = User {
        active: true,
        username: String::from("someusername123"),
        email: String::from("someone@example.com"),
        sign_in_count: 1,
    };

    user1.email = String::from("anotheremail@example.com");
}
```
 Listing 5-3: Changing the value in the `email` field of a `User` instance

 Note that the entire instance must be mutable; Rust doesn’t allow us to mark only certain fields as mutable. As with any expression, we can construct a new instance of the struct as the last expression in the function body to implicitly return that new instance.

 Listing 5-4 shows a `build_user` function that returns a `User` instance with the given email and username. The `active` field gets the value of `true`, and the `sign_in_count` gets a value of `1`.

 Filename: src/main.rs

 
```
struct User {
    active: bool,
    username: String,
    email: String,
    sign_in_count: u64,
}

fn build_user(email: String, username: String) -> User {
    User {
        active: true,
        username: username,
        email: email,
        sign_in_count: 1,
    }
}

fn main() {
    let user1 = build_user(
        String::from("someone@example.com"),
        String::from("someusername123"),
    );
}
```
 Listing 5-4: A `build_user` function that takes an email and username and returns a `User` instance

 It makes sense to name the function parameters with the same name as the struct fields, but having to repeat the `email` and `username` field names and variables is a bit tedious. If the struct had more fields, repeating each name would get even more annoying. Luckily, there’s a convenient shorthand!

 ### Using the Field Init Shorthand

 Because the parameter names and the struct field names are exactly the same in Listing 5-4, we can use the *field init shorthand* syntax to rewrite `build_user` so it behaves exactly the same but doesn’t have the repetition of `username` and `email`, as shown in Listing 5-5.

 Filename: src/main.rs

 
```
struct User {
    active: bool,
    username: String,
    email: String,
    sign_in_count: u64,
}

fn build_user(email: String, username: String) -> User {
    User {
        active: true,
        username,
        email,
        sign_in_count: 1,
    }
}

fn main() {
    let user1 = build_user(
        String::from("someone@example.com"),
        String::from("someusername123"),
    );
}
```
 Listing 5-5: A `build_user` function that uses field init shorthand because the `username` and `email` parameters have the same name as struct fields

 Here, we’re creating a new instance of the `User` struct, which has a field named `email`. We want to set the `email` field’s value to the value in the `email` parameter of the `build_user` function. Because the `email` field and the `email` parameter have the same name, we only need to write `email` rather than `email: email`.

 ### Creating Instances from Other Instances with Struct Update Syntax

 It’s often useful to create a new instance of a struct that includes most of the values from another instance, but changes some. You can do this using *struct update syntax*.

 First, in Listing 5-6 we show how to create a new `User` instance in `user2` regularly, without the update syntax. We set a new value for `email` but otherwise use the same values from `user1` that we created in Listing 5-2.

 Filename: src/main.rs

 
```
struct User {
    active: bool,
    username: String,
    email: String,
    sign_in_count: u64,
}

fn main() {
    // --snip--

    let user1 = User {
        email: String::from("someone@example.com"),
        username: String::from("someusername123"),
        active: true,
        sign_in_count: 1,
    };

    let user2 = User {
        active: user1.active,
        username: user1.username,
        email: String::from("another@example.com"),
        sign_in_count: user1.sign_in_count,
    };
}
```
 Listing 5-6: Creating a new `User` instance using one of the values from `user1`

 Using struct update syntax, we can achieve the same effect with less code, as shown in Listing 5-7. The syntax `..` specifies that the remaining fields not explicitly set should have the same value as the fields in the given instance.

 Filename: src/main.rs

 
```
struct User {
    active: bool,
    username: String,
    email: String,
    sign_in_count: u64,
}

fn main() {
    // --snip--

    let user1 = User {
        email: String::from("someone@example.com"),
        username: String::from("someusername123"),
        active: true,
        sign_in_count: 1,
    };

    let user2 = User {
        email: String::from("another@example.com"),
        ..user1
    };
}
```
 Listing 5-7: Using struct update syntax to set a new `email` value for a `User` instance but to use the rest of the values from `user1`

 The code in Listing 5-7 also creates an instance in `user2` that has a different value for `email` but has the same values for the `username`, `active`, and `sign_in_count` fields from `user1`. The `..user1` must come last to specify that any remaining fields should get their values from the corresponding fields in `user1`, but we can choose to specify values for as many fields as we want in any order, regardless of the order of the fields in the struct’s definition.

 Note that the struct update syntax uses `=` like an assignment; this is because it moves the data, just as we saw in the [“Variables and Data Interacting with Move”](ch04-01-what-is-ownership#variables-and-data-interacting-with-move) section. In this example, we can no longer use `user1` as a whole after creating `user2` because the `String` in the `username` field of `user1` was moved into `user2`. If we had given `user2` new `String` values for both `email` and `username`, and thus only used the `active` and `sign_in_count` values from `user1`, then `user1` would still be valid after creating `user2`. Both `active` and `sign_in_count` are types that implement the `Copy` trait, so the behavior we discussed in the [“Stack-Only Data: Copy”](ch04-01-what-is-ownership#stack-only-data-copy) section would apply.

 ### Using Tuple Structs Without Named Fields to Create Different Types

 Rust also supports structs that look similar to tuples, called *tuple structs*. Tuple structs have the added meaning the struct name provides but don’t have names associated with their fields; rather, they just have the types of the fields. Tuple structs are useful when you want to give the whole tuple a name and make the tuple a different type from other tuples, and when naming each field as in a regular struct would be verbose or redundant.

 To define a tuple struct, start with the `struct` keyword and the struct name followed by the types in the tuple. For example, here we define and use two tuple structs named `Color` and `Point`:

 Filename: src/main.rs

 
```
struct Color(i32, i32, i32);
struct Point(i32, i32, i32);

fn main() {
    let black = Color(0, 0, 0);
    let origin = Point(0, 0, 0);
}
```
 Note that the `black` and `origin` values are different types because they’re instances of different tuple structs. Each struct you define is its own type, even though the fields within the struct might have the same types. For example, a function that takes a parameter of type `Color` cannot take a `Point` as an argument, even though both types are made up of three `i32` values. Otherwise, tuple struct instances are similar to tuples in that you can destructure them into their individual pieces, and you can use a `.` followed by the index to access an individual value.

 ### Unit-Like Structs Without Any Fields

 You can also define structs that don’t have any fields! These are called *unit-like structs* because they behave similarly to `()`, the unit type that we mentioned in [“The Tuple Type”](ch03-02-data-types#the-tuple-type) section. Unit-like structs can be useful when you need to implement a trait on some type but don’t have any data that you want to store in the type itself. We’ll discuss traits in Chapter 10. Here’s an example of declaring and instantiating a unit struct named `AlwaysEqual`:

 Filename: src/main.rs

 
```
struct AlwaysEqual;

fn main() {
    let subject = AlwaysEqual;
}
```
 To define `AlwaysEqual`, we use the `struct` keyword, the name we want, and then a semicolon. No need for curly brackets or parentheses! Then we can get an instance of `AlwaysEqual` in the `subject` variable in a similar way: using the name we defined, without any curly brackets or parentheses. Imagine that later we’ll implement behavior for this type such that every instance of `AlwaysEqual` is always equal to every instance of any other type, perhaps to have a known result for testing purposes. We wouldn’t need any data to implement that behavior! You’ll see in Chapter 10 how to define traits and implement them on any type, including unit-like structs.

 
>  ### Ownership of Struct Data
> 
>  In the `User` struct definition in Listing 5-1, we used the owned `String` type rather than the `&str` string slice type. This is a deliberate choice because we want each instance of this struct to own all of its data and for that data to be valid for as long as the entire struct is valid.
> 
>  It’s also possible for structs to store references to data owned by something else, but to do so requires the use of *lifetimes*, a Rust feature that we’ll discuss in Chapter 10. Lifetimes ensure that the data referenced by a struct is valid for as long as the struct is. Let’s say you try to store a reference in a struct without specifying lifetimes, like the following; this won’t work:
> 
>  Filename: src/main.rs
> 
>  
> ```
> struct User {
>     active: bool,
>     username: &str,
>     email: &str,
>     sign_in_count: u64,
> }
> 
> fn main() {
>     let user1 = User {
>         active: true,
>         username: "someusername123",
>         email: "someone@example.com",
>         sign_in_count: 1,
>     };
> }
> ```
>  The compiler will complain that it needs lifetime specifiers:
> 
>  
> ```
> $ cargo run
>    Compiling structs v0.1.0 (file:///projects/structs)
> error[E0106]: missing lifetime specifier
>  --> src/main.rs:3:15
>   |
> 3 |     username: &str,
>   |               ^ expected named lifetime parameter
>   |
> help: consider introducing a named lifetime parameter
>   |
> 1 ~ struct User<'a> {
> 2 |     active: bool,
> 3 ~     username: &'a str,
>   |
> 
> error[E0106]: missing lifetime specifier
>  --> src/main.rs:4:12
>   |
> 4 |     email: &str,
>   |            ^ expected named lifetime parameter
>   |
> help: consider introducing a named lifetime parameter
>   |
> 1 ~ struct User<'a> {
> 2 |     active: bool,
> 3 |     username: &str,
> 4 ~     email: &'a str,
>   |
> 
> For more information about this error, try `rustc --explain E0106`.
> error: could not compile `structs` due to 2 previous errors
> 
> ```
>  In Chapter 10, we’ll discuss how to fix these errors so you can store references in structs, but for now, we’ll fix errors like these using owned types like `String` instead of references like `&str`.
> 
>  



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch05-01-defining-structs.html>

Method Syntax
=============

 *Methods* are similar to functions: we declare them with the `fn` keyword and a name, they can have parameters and a return value, and they contain some code that’s run when the method is called from somewhere else. Unlike functions, methods are defined within the context of a struct (or an enum or a trait object, which we cover in [Chapter 6](ch06-00-enums) and [Chapter 17](ch17-02-trait-objects), respectively), and their first parameter is always `self`, which represents the instance of the struct the method is being called on.

 ### Defining Methods

 Let’s change the `area` function that has a `Rectangle` instance as a parameter and instead make an `area` method defined on the `Rectangle` struct, as shown in Listing 5-13.

 Filename: src/main.rs

 
```
#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

fn main() {
    let rect1 = Rectangle {
        width: 30,
        height: 50,
    };

    println!(
        "The area of the rectangle is {} square pixels.",
        rect1.area()
    );
}
```
 Listing 5-13: Defining an `area` method on the `Rectangle` struct

 To define the function within the context of `Rectangle`, we start an `impl` (implementation) block for `Rectangle`. Everything within this `impl` block will be associated with the `Rectangle` type. Then we move the `area` function within the `impl` curly brackets and change the first (and in this case, only) parameter to be `self` in the signature and everywhere within the body. In `main`, where we called the `area` function and passed `rect1` as an argument, we can instead use *method syntax* to call the `area` method on our `Rectangle` instance. The method syntax goes after an instance: we add a dot followed by the method name, parentheses, and any arguments.

 In the signature for `area`, we use `&self` instead of `rectangle: &Rectangle`. The `&self` is actually short for `self: &Self`. Within an `impl` block, the type `Self` is an alias for the type that the `impl` block is for. Methods must have a parameter named `self` of type `Self` for their first parameter, so Rust lets you abbreviate this with only the name `self` in the first parameter spot. Note that we still need to use the `&` in front of the `self` shorthand to indicate that this method borrows the `Self` instance, just as we did in `rectangle: &Rectangle`. Methods can take ownership of `self`, borrow `self` immutably, as we’ve done here, or borrow `self` mutably, just as they can any other parameter.

 We chose `&self` here for the same reason we used `&Rectangle` in the function version: we don’t want to take ownership, and we just want to read the data in the struct, not write to it. If we wanted to change the instance that we’ve called the method on as part of what the method does, we’d use `&mut self` as the first parameter. Having a method that takes ownership of the instance by using just `self` as the first parameter is rare; this technique is usually used when the method transforms `self` into something else and you want to prevent the caller from using the original instance after the transformation.

 The main reason for using methods instead of functions, in addition to providing method syntax and not having to repeat the type of `self` in every method’s signature, is for organization. We’ve put all the things we can do with an instance of a type in one `impl` block rather than making future users of our code search for capabilities of `Rectangle` in various places in the library we provide.

 Note that we can choose to give a method the same name as one of the struct’s fields. For example, we can define a method on `Rectangle` that is also named `width`:

 Filename: src/main.rs

 
```
#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn width(&self) -> bool {
        self.width > 0
    }
}

fn main() {
    let rect1 = Rectangle {
        width: 30,
        height: 50,
    };

    if rect1.width() {
        println!("The rectangle has a nonzero width; it is {}", rect1.width);
    }
}
```
 Here, we’re choosing to make the `width` method return `true` if the value in the instance’s `width` field is greater than `0` and `false` if the value is `0`: we can use a field within a method of the same name for any purpose. In `main`, when we follow `rect1.width` with parentheses, Rust knows we mean the method `width`. When we don’t use parentheses, Rust knows we mean the field `width`.

 Often, but not always, when we give a method the same name as a field we want it to only return the value in the field and do nothing else. Methods like this are called *getters*, and Rust does not implement them automatically for struct fields as some other languages do. Getters are useful because you can make the field private but the method public, and thus enable read-only access to that field as part of the type’s public API. We will discuss what public and private are and how to designate a field or method as public or private in [Chapter 7](ch07-03-paths-for-referring-to-an-item-in-the-module-tree#exposing-paths-with-the-pub-keyword).

 
>  ### Where’s the `->` Operator?
> 
>  In C and C++, two different operators are used for calling methods: you use `.` if you’re calling a method on the object directly and `->` if you’re calling the method on a pointer to the object and need to dereference the pointer first. In other words, if `object` is a pointer, `object->something()` is similar to `(*object).something()`.
> 
>  Rust doesn’t have an equivalent to the `->` operator; instead, Rust has a feature called *automatic referencing and dereferencing*. Calling methods is one of the few places in Rust that has this behavior.
> 
>  Here’s how it works: when you call a method with `object.something()`, Rust automatically adds in `&`, `&mut`, or `*` so `object` matches the signature of the method. In other words, the following are the same:
> 
>  
> ```
> #![allow(unused)]
> fn main() {
> #[derive(Debug,Copy,Clone)]
> struct Point {
>     x: f64,
>     y: f64,
> }
> 
> impl Point {
>    fn distance(&self, other: &Point) -> f64 {
>        let x_squared = f64::powi(other.x - self.x, 2);
>        let y_squared = f64::powi(other.y - self.y, 2);
> 
>        f64::sqrt(x_squared + y_squared)
>    }
> }
> let p1 = Point { x: 0.0, y: 0.0 };
> let p2 = Point { x: 5.0, y: 6.5 };
> p1.distance(&p2);
> (&p1).distance(&p2);
> }
> ```
>  The first one looks much cleaner. This automatic referencing behavior works because methods have a clear receiver—the type of `self`. Given the receiver and name of a method, Rust can figure out definitively whether the method is reading (`&self`), mutating (`&mut self`), or consuming (`self`). The fact that Rust makes borrowing implicit for method receivers is a big part of making ownership ergonomic in practice.
> 
>  

 ### Methods with More Parameters

 Let’s practice using methods by implementing a second method on the `Rectangle` struct. This time we want an instance of `Rectangle` to take another instance of `Rectangle` and return `true` if the second `Rectangle` can fit completely within `self` (the first `Rectangle`); otherwise, it should return `false`. That is, once we’ve defined the `can_hold` method, we want to be able to write the program shown in Listing 5-14.

 Filename: src/main.rs

 
```
fn main() {
    let rect1 = Rectangle {
        width: 30,
        height: 50,
    };
    let rect2 = Rectangle {
        width: 10,
        height: 40,
    };
    let rect3 = Rectangle {
        width: 60,
        height: 45,
    };

    println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
    println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
}
```
 Listing 5-14: Using the as-yet-unwritten `can_hold` method

 The expected output would look like the following because both dimensions of `rect2` are smaller than the dimensions of `rect1`, but `rect3` is wider than `rect1`:

 
```
Can rect1 hold rect2? true
Can rect1 hold rect3? false

```
 We know we want to define a method, so it will be within the `impl Rectangle` block. The method name will be `can_hold`, and it will take an immutable borrow of another `Rectangle` as a parameter. We can tell what the type of the parameter will be by looking at the code that calls the method: `rect1.can_hold(&rect2)` passes in `&rect2`, which is an immutable borrow to `rect2`, an instance of `Rectangle`. This makes sense because we only need to read `rect2` (rather than write, which would mean we’d need a mutable borrow), and we want `main` to retain ownership of `rect2` so we can use it again after calling the `can_hold` method. The return value of `can_hold` will be a Boolean, and the implementation will check whether the width and height of `self` are greater than the width and height of the other `Rectangle`, respectively. Let’s add the new `can_hold` method to the `impl` block from Listing 5-13, shown in Listing 5-15.

 Filename: src/main.rs

 
```
#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }

    fn can_hold(&self, other: &Rectangle) -> bool {
        self.width > other.width && self.height > other.height
    }
}

fn main() {
    let rect1 = Rectangle {
        width: 30,
        height: 50,
    };
    let rect2 = Rectangle {
        width: 10,
        height: 40,
    };
    let rect3 = Rectangle {
        width: 60,
        height: 45,
    };

    println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
    println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
}
```
 Listing 5-15: Implementing the `can_hold` method on `Rectangle` that takes another `Rectangle` instance as a parameter

 When we run this code with the `main` function in Listing 5-14, we’ll get our desired output. Methods can take multiple parameters that we add to the signature after the `self` parameter, and those parameters work just like parameters in functions.

 ### Associated Functions

 All functions defined within an `impl` block are called *associated functions* because they’re associated with the type named after the `impl`. We can define associated functions that don’t have `self` as their first parameter (and thus are not methods) because they don’t need an instance of the type to work with. We’ve already used one function like this: the `String::from` function that’s defined on the `String` type.

 Associated functions that aren’t methods are often used for constructors that will return a new instance of the struct. These are often called `new`, but `new` isn’t a special name and isn’t built into the language. For example, we could choose to provide an associated function named `square` that would have one dimension parameter and use that as both width and height, thus making it easier to create a square `Rectangle` rather than having to specify the same value twice:

 Filename: src/main.rs

 
```
#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn square(size: u32) -> Self {
        Self {
            width: size,
            height: size,
        }
    }
}

fn main() {
    let sq = Rectangle::square(3);
}
```
 The `Self` keywords in the return type and in the body of the function are aliases for the type that appears after the `impl` keyword, which in this case is `Rectangle`.

 To call this associated function, we use the `::` syntax with the struct name; `let sq = Rectangle::square(3);` is an example. This function is namespaced by the struct: the `::` syntax is used for both associated functions and namespaces created by modules. We’ll discuss modules in [Chapter 7](ch07-02-defining-modules-to-control-scope-and-privacy).

 ### Multiple `impl` Blocks

 Each struct is allowed to have multiple `impl` blocks. For example, Listing 5-15 is equivalent to the code shown in Listing 5-16, which has each method in its own `impl` block.

 
```
#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

impl Rectangle {
    fn can_hold(&self, other: &Rectangle) -> bool {
        self.width > other.width && self.height > other.height
    }
}

fn main() {
    let rect1 = Rectangle {
        width: 30,
        height: 50,
    };
    let rect2 = Rectangle {
        width: 10,
        height: 40,
    };
    let rect3 = Rectangle {
        width: 60,
        height: 45,
    };

    println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
    println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
}
```
 Listing 5-16: Rewriting Listing 5-15 using multiple `impl` blocks

 There’s no reason to separate these methods into multiple `impl` blocks here, but this is valid syntax. We’ll see a case in which multiple `impl` blocks are useful in Chapter 10, where we discuss generic types and traits.

 Summary
-------

 Structs let you create custom types that are meaningful for your domain. By using structs, you can keep associated pieces of data connected to each other and name each piece to make your code clear. In `impl` blocks, you can define functions that are associated with your type, and methods are a kind of associated function that let you specify the behavior that instances of your structs have.

 But structs aren’t the only way you can create custom types: let’s turn to Rust’s enum feature to add another tool to your toolbox.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch05-03-method-syntax.html>

Enums and Pattern Matching
==========================

 In this chapter, we’ll look at *enumerations*, also referred to as *enums*. Enums allow you to define a type by enumerating its possible *variants*. First we’ll define and use an enum to show how an enum can encode meaning along with data. Next, we’ll explore a particularly useful enum, called `Option`, which expresses that a value can be either something or nothing. Then we’ll look at how pattern matching in the `match` expression makes it easy to run different code for different values of an enum. Finally, we’ll cover how the `if let` construct is another convenient and concise idiom available to handle enums in your code.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch06-00-enums.html>

Getting Started
===============

 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



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch01-00-getting-started.html>

Hello, World!
=============

 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 integrated development environment (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](appendix-04-useful-development-tools) for more details.
> 
>  

 ### Creating a Project Directory

 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

```
 ### Writing and Running a Rust Program

 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: 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.exe` instead of `./main`:

 
```
> rustc main.rs
> .\main.exe
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”](ch01-01-installation#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!

 ### Anatomy of a Rust Program

 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](appendix-04-useful-development-tools)). 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 four important details to notice here.

 First, Rust style is to indent with four spaces, not a tab.

 Second, `println!` calls a Rust macro. If it had called a function instead, it would be entered as `println` (without the `!`). We’ll discuss Rust macros in more detail in Chapter 19. 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.

 Third, you see the `"Hello, world!"` string. We pass this string as an argument to `println!`, and the string is printed to the screen.

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

 ### Compiling and Running Are Separate Steps

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



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch01-02-hello-world.html>

Common Programming Concepts
===========================

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

 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.

 
>  #### Keywords
> 
>  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 a list of the keywords in [Appendix A](appendix-01-keywords).
> 
>  



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch03-00-common-programming-concepts.html>

Hello, Cargo!
=============

 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”](ch01-01-installation#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.

 ### Creating a Project with Cargo

 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 = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

```
 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](appendix-05-editions).

 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.

 ### Building and Running a Cargo Project

 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.

 ### Building for Release

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

 ### Cargo as Convention

 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/index.html).

 Summary
-------

 You’re already off to a great start on your Rust journey! In this chapter, you’ve 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.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch01-03-hello-cargo.html>

Programming a Guessing Game
===========================

 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.

 Setting Up a New Project
------------------------

 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 = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[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 [unoptimized + debuginfo] target(s) in 1.50s
     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.

 Processing a Guess
------------------

 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: 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](../std/prelude/index).

 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.

 ### Storing Values with Variables

 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”](ch03-01-variables-and-mutability#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](ch03-04-comments).
> 
>  

 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`](../std/string/struct.string) 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!

 ### Receiving User Input

 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` library 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`](../std/io/struct.stdin), 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`](../std/io/struct.stdin#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 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.)

 ### Handling Potential Failure with `Result`

 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`](../std/result/enum.result) is an [*enumeration*](ch06-00-enums), 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](ch06-00-enums) 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 inside `Ok` is the successfully generated value. The `Err` variant means the operation failed, and `Err` 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](../std/result/enum.result#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 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

warning: `guessing_game` (bin "guessing_game") generated 1 warning
    Finished dev [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](ch09-02-recoverable-errors-with-result).

 ### Printing Values with `println!` Placeholders

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

 ### Testing the First Part

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

 Generating a Secret Number
--------------------------

 Next, we need to generate a secret number that the user will try to guess. The secret number should be different every time so the game is fun to play more than once. We’ll use a random number between 1 and 100 so 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.

 ### Using a Crate to Get More 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 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
  Downloaded rand v0.8.5
  Downloaded libc v0.2.127
  Downloaded getrandom v0.2.7
  Downloaded cfg-if v1.0.0
  Downloaded ppv-lite86 v0.2.16
  Downloaded rand_chacha v0.3.1
  Downloaded rand_core v0.6.3
   Compiling libc v0.2.127
   Compiling getrandom v0.2.7
   Compiling cfg-if v1.0.0
   Compiling ppv-lite86 v0.2.16
   Compiling rand_core v0.6.3
   Compiling rand_chacha v0.3.1
   Compiling rand v0.8.5
   Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
    Finished dev [unoptimized + debuginfo] target(s) in 2.53s

```
 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 [unoptimized + debuginfo] target(s) in 2.53 secs

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

 #### Ensuring Reproducible Builds with the *Cargo.lock* File

 Cargo has a mechanism that ensures 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.

 #### Updating a Crate to Get a New Version

 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
    Updating rand v0.8.5 -> v0.8.6

```
 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](http://doc.crates.io) and [its ecosystem](http://doc.crates.io/crates-io.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.

 ### Generating a Random Number

 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: 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 [unoptimized + debuginfo] target(s) in 2.53s
     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 [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!

 Comparing the Guess to the Secret Number
----------------------------------------

 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 rand::Rng;
use std::cmp::Ordering;
use std::io;

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: 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`](ch06-02-match) 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 18, 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:22:21
   |
22 |     match guess.cmp(&secret_number) {
   |                 --- ^^^^^^^^^^^^^^ expected struct `String`, found integer
   |                 |
   |                 arguments to this function are incorrect
   |
   = note: expected reference `&String`
              found reference `&{integer}`
note: associated function defined here
  --> /rustc/d5a82bbd26e1ad8b7401f6a718a9c57c96905483/library/core/src/cmp.rs:783:8

For more information about this error, try `rustc --explain E0308`.
error: could not compile `guessing_game` due to 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 real number type so 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 rand::Rng;
use std::cmp::Ordering;
use std::io;

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](ch03-01-variables-and-mutability#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 to be able to compare the string to the `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](../std/primitive.str#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](ch03-02-data-types#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`”](#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 [unoptimized + debuginfo] target(s) in 0.43s
     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!

 Allowing Multiple Guesses with Looping
--------------------------------------

 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 rand::Rng;
use std::cmp::Ordering;
use std::io;

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”](#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 [unoptimized + debuginfo] target(s) in 1.50s
     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 'Please type a number!: ParseIntError { kind: InvalidDigit }', src/main.rs:28:47
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.

 ### Quitting After a Correct Guess

 Let’s program the game to quit when the user wins by adding a `break` statement:

 Filename: src/main.rs

 
```
use rand::Rng;
use std::cmp::Ordering;
use std::io;

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

 ### Handling Invalid Input

 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 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 rand::Rng;
use std::cmp::Ordering;
use std::io;

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: 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 catchall 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 [unoptimized + debuginfo] target(s) in 4.45s
     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 rand::Rng;
use std::cmp::Ordering;
use std::io;

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: Complete guessing game code

 At this point, you’ve successfully built the guessing game. Congratulations!

 Summary
-------

 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.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html>

Variables and Mutability
========================

 As mentioned in the [“Storing Values with Variables”](ch02-00-guessing-game-tutorial#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`
  |         help: consider making this binding mutable: `mut x`
3 |     println!("The value of x is: {x}");
4 |     x = 6;
  |     ^^^^^ cannot assign twice to immutable variable

For more information about this error, try `rustc --explain E0384`.
error: could not compile `variables` due to 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](ch02-00-guessing-game-tutorial#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 [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.

 ### Constants

 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”](ch03-02-data-types#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](../reference/const_eval) 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 you would need to change if the hardcoded value needed to be updated in the future.

 ### Shadowing

 As you saw in the guessing game tutorial in [Chapter 2](ch02-00-guessing-game-tutorial#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 the value of `x` is then `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 [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 been 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` due to previous error

```
 Now that we’ve explored how variables work, let’s look at more data types they can have.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html>

Data Types
==========

 Every value in Rust is of a certain *data type*, which tells Rust what kind of data is being specified so 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”](ch02-00-guessing-game-tutorial#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[E0282]: type annotations needed
 --> src/main.rs:2:9
  |
2 |     let guess = "42".parse().expect("Not a number!");
  |         ^^^^^
  |
help: consider giving `guess` an explicit type
  |
2 |     let guess: _ = "42".parse().expect("Not a number!");
  |              +++

For more information about this error, try `rustc --explain E0282`.
error: could not compile `no_type_annotations` due to previous error

```
 You’ll see different type annotations for other data types.

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

 #### Integer Types

 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` |
| arch | `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, which is denoted in the table as “arch”: 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.

 
>  ##### Integer Overflow
> 
>  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!`”](ch09-01-unrecoverable-errors-with-panic) 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.
> 
>  

 #### Floating-Point Types

 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. The `f32` type is a single-precision float, and `f64` has double precision.

 #### Numeric Operations

 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](appendix-02-operators) contains a list of all operators that Rust provides.

 #### The Boolean Type

 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”](ch03-05-control-flow#control-flow) section.

 #### The Character Type

 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 quotes, as opposed to string literals, which use double quotes. Rust’s `char` type is four 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; emoji; 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”](ch08-02-strings#storing-utf-8-encoded-text-with-strings) in Chapter 8.

 ### Compound Types

 *Compound types* can group multiple values into one type. Rust has two primitive compound types: tuples and arrays.

 #### The Tuple Type

 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.

 #### The Array Type

 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 rather than the heap (we will discuss the stack and the heap more in [Chapter 4](ch04-01-what-is-ownership#the-stack-and-the-heap)) or when you want to ensure 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. If you’re unsure whether to use an array or a vector, chances are you should use a vector. [Chapter 8](ch08-01-vectors) 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.

 ##### Accessing Array Elements

 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.

 ##### Invalid Array Element Access

 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 'index out of bounds: the len is 5 but the index is 10', src/main.rs:19:19
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.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch03-02-data-types.html>

Functions
=========

 Functions are prevalent in Rust code. You’ve already seen one of the most important functions in the language: the `main` function, which is the entry point of many programs. You’ve also seen the `fn` keyword, which allows you to declare new functions.

 Rust code uses *snake case* as the conventional style for function and variable names, in which all letters are lowercase and underscores separate words. Here’s a program that contains an example function definition:

 Filename: src/main.rs

 
```
fn main() {
    println!("Hello, world!");

    another_function();
}

fn another_function() {
    println!("Another function.");
}
```
 We define a function in Rust by entering `fn` followed by a function name and a set of parentheses. The curly brackets tell the compiler where the function body begins and ends.

 We can call any function we’ve defined by entering its name followed by a set of parentheses. Because `another_function` is defined in the program, it can be called from inside the `main` function. Note that we defined `another_function` *after* the `main` function in the source code; we could have defined it before as well. Rust doesn’t care where you define your functions, only that they’re defined somewhere in a scope that can be seen by the caller.

 Let’s start a new binary project named *functions* to explore functions further. Place the `another_function` example in *src/main.rs* and run it. You should see the following output:

 
```
$ cargo run
   Compiling functions v0.1.0 (file:///projects/functions)
    Finished dev [unoptimized + debuginfo] target(s) in 0.28s
     Running `target/debug/functions`
Hello, world!
Another function.

```
 The lines execute in the order in which they appear in the `main` function. First the “Hello, world!” message prints, and then `another_function` is called and its message is printed.

 ### Parameters

 We can define functions to have *parameters*, which are special variables that are part of a function’s signature. When a function has parameters, you can provide it with concrete values for those parameters. Technically, the concrete values are called *arguments*, but in casual conversation, people tend to use the words *parameter* and *argument* interchangeably for either the variables in a function’s definition or the concrete values passed in when you call a function.

 In this version of `another_function` we add a parameter:

 Filename: src/main.rs

 
```
fn main() {
    another_function(5);
}

fn another_function(x: i32) {
    println!("The value of x is: {x}");
}
```
 Try running this program; you should get the following output:

 
```
$ cargo run
   Compiling functions v0.1.0 (file:///projects/functions)
    Finished dev [unoptimized + debuginfo] target(s) in 1.21s
     Running `target/debug/functions`
The value of x is: 5

```
 The declaration of `another_function` has one parameter named `x`. The type of `x` is specified as `i32`. When we pass `5` in to `another_function`, the `println!` macro puts `5` where the pair of curly brackets containing `x` was in the format string.

 In function signatures, you *must* declare the type of each parameter. This is a deliberate decision in Rust’s design: requiring type annotations in function definitions means the compiler almost never needs you to use them elsewhere in the code to figure out what type you mean. The compiler is also able to give more helpful error messages if it knows what types the function expects.

 When defining multiple parameters, separate the parameter declarations with commas, like this:

 Filename: src/main.rs

 
```
fn main() {
    print_labeled_measurement(5, 'h');
}

fn print_labeled_measurement(value: i32, unit_label: char) {
    println!("The measurement is: {value}{unit_label}");
}
```
 This example creates a function named `print_labeled_measurement` with two parameters. The first parameter is named `value` and is an `i32`. The second is named `unit_label` and is type `char`. The function then prints text containing both the `value` and the `unit_label`.

 Let’s try running this code. Replace the program currently in your *functions* project’s *src/main.rs* file with the preceding example and run it using `cargo run`:

 
```
$ cargo run
   Compiling functions v0.1.0 (file:///projects/functions)
    Finished dev [unoptimized + debuginfo] target(s) in 0.31s
     Running `target/debug/functions`
The measurement is: 5h

```
 Because we called the function with `5` as the value for `value` and `'h'` as the value for `unit_label`, the program output contains those values.

 ### Statements and Expressions

 Function bodies are made up of a series of statements optionally ending in an expression. So far, the functions we’ve covered haven’t included an ending expression, but you have seen an expression as part of a statement. Because Rust is an expression-based language, this is an important distinction to understand. Other languages don’t have the same distinctions, so let’s look at what statements and expressions are and how their differences affect the bodies of functions.

 * **Statements** are instructions that perform some action and do not return a value.
* **Expressions** evaluate to a resultant value. Let’s look at some examples.

 We’ve actually already used statements and expressions. Creating a variable and assigning a value to it with the `let` keyword is a statement. In Listing 3-1, `let y = 6;` is a statement.

 Filename: src/main.rs

 
```
fn main() {
    let y = 6;
}
```
 Listing 3-1: A `main` function declaration containing one statement

 Function definitions are also statements; the entire preceding example is a statement in itself.

 Statements do not return values. Therefore, you can’t assign a `let` statement to another variable, as the following code tries to do; you’ll get an error:

 Filename: src/main.rs

 
```
fn main() {
    let x = (let y = 6);
}
```
 When you run this program, the error you’ll get looks like this:

 
```
$ cargo run
   Compiling functions v0.1.0 (file:///projects/functions)
error: expected expression, found `let` statement
 --> src/main.rs:2:14
  |
2 |     let x = (let y = 6);
  |              ^^^

error: expected expression, found statement (`let`)
 --> src/main.rs:2:14
  |
2 |     let x = (let y = 6);
  |              ^^^^^^^^^
  |
  = note: variable declaration using `let` is a statement

error[E0658]: `let` expressions in this position are unstable
 --> src/main.rs:2:14
  |
2 |     let x = (let y = 6);
  |              ^^^^^^^^^
  |
  = note: see issue #53667 <https://github.com/rust-lang/rust/issues/53667> for more information

warning: unnecessary parentheses around assigned value
 --> src/main.rs:2:13
  |
2 |     let x = (let y = 6);
  |             ^         ^
  |
  = note: `#[warn(unused_parens)]` on by default
help: remove these parentheses
  |
2 -     let x = (let y = 6);
2 +     let x = let y = 6;
  |

For more information about this error, try `rustc --explain E0658`.
warning: `functions` (bin "functions") generated 1 warning
error: could not compile `functions` due to 3 previous errors; 1 warning emitted

```
 The `let y = 6` statement does not return a value, so there isn’t anything for `x` to bind to. This is different from what happens in other languages, such as C and Ruby, where the assignment returns the value of the assignment. In those languages, you can write `x = y = 6` and have both `x` and `y` have the value `6`; that is not the case in Rust.

 Expressions evaluate to a value and make up most of the rest of the code that you’ll write in Rust. Consider a math operation, such as `5 + 6`, which is an expression that evaluates to the value `11`. Expressions can be part of statements: in Listing 3-1, the `6` in the statement `let y = 6;` is an expression that evaluates to the value `6`. Calling a function is an expression. Calling a macro is an expression. A new scope block created with curly brackets is an expression, for example:

 Filename: src/main.rs

 
```
fn main() {
    let y = {
        let x = 3;
        x + 1
    };

    println!("The value of y is: {y}");
}
```
 This expression:

 
```
{
    let x = 3;
    x + 1
}
```
 is a block that, in this case, evaluates to `4`. That value gets bound to `y` as part of the `let` statement. Note that the `x + 1` line doesn’t have a semicolon at the end, which is unlike most of the lines you’ve seen so far. Expressions do not include ending semicolons. If you add a semicolon to the end of an expression, you turn it into a statement, and it will then not return a value. Keep this in mind as you explore function return values and expressions next.

 ### Functions with Return Values

 Functions can return values to the code that calls them. We don’t name return values, but we must declare their type after an arrow (`->`). In Rust, the return value of the function is synonymous with the value of the final expression in the block of the body of a function. You can return early from a function by using the `return` keyword and specifying a value, but most functions return the last expression implicitly. Here’s an example of a function that returns a value:

 Filename: src/main.rs

 
```
fn five() -> i32 {
    5
}

fn main() {
    let x = five();

    println!("The value of x is: {x}");
}
```
 There are no function calls, macros, or even `let` statements in the `five` function—just the number `5` by itself. That’s a perfectly valid function in Rust. Note that the function’s return type is specified too, as `-> i32`. Try running this code; the output should look like this:

 
```
$ cargo run
   Compiling functions v0.1.0 (file:///projects/functions)
    Finished dev [unoptimized + debuginfo] target(s) in 0.30s
     Running `target/debug/functions`
The value of x is: 5

```
 The `5` in `five` is the function’s return value, which is why the return type is `i32`. Let’s examine this in more detail. There are two important bits: first, the line `let x = five();` shows that we’re using the return value of a function to initialize a variable. Because the function `five` returns a `5`, that line is the same as the following:

 
```
#![allow(unused)]
fn main() {
let x = 5;
}
```
 Second, the `five` function has no parameters and defines the type of the return value, but the body of the function is a lonely `5` with no semicolon because it’s an expression whose value we want to return.

 Let’s look at another example:

 Filename: src/main.rs

 
```
fn main() {
    let x = plus_one(5);

    println!("The value of x is: {x}");
}

fn plus_one(x: i32) -> i32 {
    x + 1
}
```
 Running this code will print `The value of x is: 6`. But if we place a semicolon at the end of the line containing `x + 1`, changing it from an expression to a statement, we’ll get an error:

 Filename: src/main.rs

 
```
fn main() {
    let x = plus_one(5);

    println!("The value of x is: {x}");
}

fn plus_one(x: i32) -> i32 {
    x + 1;
}
```
 Compiling this code produces an error, as follows:

 
```
$ cargo run
   Compiling functions v0.1.0 (file:///projects/functions)
error[E0308]: mismatched types
 --> src/main.rs:7:24
  |
7 | fn plus_one(x: i32) -> i32 {
  |    --------            ^^^ expected `i32`, found `()`
  |    |
  |    implicitly returns `()` as its body has no tail or `return` expression
8 |     x + 1;
  |          - help: remove this semicolon to return this value

For more information about this error, try `rustc --explain E0308`.
error: could not compile `functions` due to previous error

```
 The main error message, `mismatched types`, reveals the core issue with this code. The definition of the function `plus_one` says that it will return an `i32`, but statements don’t evaluate to a value, which is expressed by `()`, the unit type. Therefore, nothing is returned, which contradicts the function definition and results in an error. In this output, Rust provides a message to possibly help rectify this issue: it suggests removing the semicolon, which would fix the error.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch03-03-how-functions-work.html>

Comments
========

 All programmers strive to make their code easy to understand, but sometimes extra explanation is warranted. In these cases, programmers leave *comments* in their source code that the compiler will ignore but people reading the source code may find useful.

 Here’s a simple comment:

 
```
#![allow(unused)]
fn main() {
// hello, world
}
```
 In Rust, the idiomatic comment style starts a comment with two slashes, and the comment continues until the end of the line. For comments that extend beyond a single line, you’ll need to include `//` on each line, like this:

 
```
#![allow(unused)]
fn main() {
// So we’re doing something complicated here, long enough that we need
// multiple lines of comments to do it! Whew! Hopefully, this comment will
// explain what’s going on.
}
```
 Comments can also be placed at the end of lines containing code:

 Filename: src/main.rs

 
```
fn main() {
    let lucky_number = 7; // I’m feeling lucky today
}
```
 But you’ll more often see them used in this format, with the comment on a separate line above the code it’s annotating:

 Filename: src/main.rs

 
```
fn main() {
    // I’m feeling lucky today
    let lucky_number = 7;
}
```
 Rust also has another kind of comment, documentation comments, which we’ll discuss in the [“Publishing a Crate to Crates.io”](ch14-02-publishing-to-crates-io) section of Chapter 14.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch03-04-comments.html>

Control Flow
============

 The ability to run some code depending on whether a condition is `true` and to run some code repeatedly while a condition is `true` are basic building blocks in most programming languages. The most common constructs that let you control the flow of execution of Rust code are `if` expressions and loops.

 ### 
`if` Expressions

 An `if` expression allows you to branch your code depending on conditions. You provide a condition and then state, “If this condition is met, run this block of code. If the condition is not met, do not run this block of code.”

 Create a new project called *branches* in your *projects* directory to explore the `if` expression. In the *src/main.rs* file, input the following:

 Filename: src/main.rs

 
```
fn main() {
    let number = 3;

    if number < 5 {
        println!("condition was true");
    } else {
        println!("condition was false");
    }
}
```
 All `if` expressions start with the keyword `if`, followed by a condition. In this case, the condition checks whether or not the variable `number` has a value less than 5. We place the block of code to execute if the condition is `true` immediately after the condition inside curly brackets. Blocks of code associated with the conditions in `if` expressions are sometimes called *arms*, just like the arms in `match` expressions that we discussed in the [“Comparing the Guess to the Secret Number”](ch02-00-guessing-game-tutorial#comparing-the-guess-to-the-secret-number) section of Chapter 2.

 Optionally, we can also include an `else` expression, which we chose to do here, to give the program an alternative block of code to execute should the condition evaluate to `false`. If you don’t provide an `else` expression and the condition is `false`, the program will just skip the `if` block and move on to the next bit of code.

 Try running this code; you should see the following output:

 
```
$ cargo run
   Compiling branches v0.1.0 (file:///projects/branches)
    Finished dev [unoptimized + debuginfo] target(s) in 0.31s
     Running `target/debug/branches`
condition was true

```
 Let’s try changing the value of `number` to a value that makes the condition `false` to see what happens:

 
```
fn main() {
    let number = 7;

    if number < 5 {
        println!("condition was true");
    } else {
        println!("condition was false");
    }
}
```
 Run the program again, and look at the output:

 
```
$ cargo run
   Compiling branches v0.1.0 (file:///projects/branches)
    Finished dev [unoptimized + debuginfo] target(s) in 0.31s
     Running `target/debug/branches`
condition was false

```
 It’s also worth noting that the condition in this code *must* be a `bool`. If the condition isn’t a `bool`, we’ll get an error. For example, try running the following code:

 Filename: src/main.rs

 
```
fn main() {
    let number = 3;

    if number {
        println!("number was three");
    }
}
```
 The `if` condition evaluates to a value of `3` this time, and Rust throws an error:

 
```
$ cargo run
   Compiling branches v0.1.0 (file:///projects/branches)
error[E0308]: mismatched types
 --> src/main.rs:4:8
  |
4 |     if number {
  |        ^^^^^^ expected `bool`, found integer

For more information about this error, try `rustc --explain E0308`.
error: could not compile `branches` due to previous error

```
 The error indicates that Rust expected a `bool` but got an integer. Unlike languages such as Ruby and JavaScript, Rust will not automatically try to convert non-Boolean types to a Boolean. You must be explicit and always provide `if` with a Boolean as its condition. If we want the `if` code block to run only when a number is not equal to `0`, for example, we can change the `if` expression to the following:

 Filename: src/main.rs

 
```
fn main() {
    let number = 3;

    if number != 0 {
        println!("number was something other than zero");
    }
}
```
 Running this code will print `number was something other than zero`.

 #### Handling Multiple Conditions with `else if`

 You can use multiple conditions by combining `if` and `else` in an `else if` expression. For example:

 Filename: src/main.rs

 
```
fn main() {
    let number = 6;

    if number % 4 == 0 {
        println!("number is divisible by 4");
    } else if number % 3 == 0 {
        println!("number is divisible by 3");
    } else if number % 2 == 0 {
        println!("number is divisible by 2");
    } else {
        println!("number is not divisible by 4, 3, or 2");
    }
}
```
 This program has four possible paths it can take. After running it, you should see the following output:

 
```
$ cargo run
   Compiling branches v0.1.0 (file:///projects/branches)
    Finished dev [unoptimized + debuginfo] target(s) in 0.31s
     Running `target/debug/branches`
number is divisible by 3

```
 When this program executes, it checks each `if` expression in turn and executes the first body for which the condition evaluates to `true`. Note that even though 6 is divisible by 2, we don’t see the output `number is divisible by 2`, nor do we see the `number is not divisible by 4, 3, or 2` text from the `else` block. That’s because Rust only executes the block for the first `true` condition, and once it finds one, it doesn’t even check the rest.

 Using too many `else if` expressions can clutter your code, so if you have more than one, you might want to refactor your code. Chapter 6 describes a powerful Rust branching construct called `match` for these cases.

 #### Using `if` in a `let` Statement

 Because `if` is an expression, we can use it on the right side of a `let` statement to assign the outcome to a variable, as in Listing 3-2.

 Filename: src/main.rs

 
```
fn main() {
    let condition = true;
    let number = if condition { 5 } else { 6 };

    println!("The value of number is: {number}");
}
```
 Listing 3-2: Assigning the result of an `if` expression to a variable

 The `number` variable will be bound to a value based on the outcome of the `if` expression. Run this code to see what happens:

 
```
$ cargo run
   Compiling branches v0.1.0 (file:///projects/branches)
    Finished dev [unoptimized + debuginfo] target(s) in 0.30s
     Running `target/debug/branches`
The value of number is: 5

```
 Remember that blocks of code evaluate to the last expression in them, and numbers by themselves are also expressions. In this case, the value of the whole `if` expression depends on which block of code executes. This means the values that have the potential to be results from each arm of the `if` must be the same type; in Listing 3-2, the results of both the `if` arm and the `else` arm were `i32` integers. If the types are mismatched, as in the following example, we’ll get an error:

 Filename: src/main.rs

 
```
fn main() {
    let condition = true;

    let number = if condition { 5 } else { "six" };

    println!("The value of number is: {number}");
}
```
 When we try to compile this code, we’ll get an error. The `if` and `else` arms have value types that are incompatible, and Rust indicates exactly where to find the problem in the program:

 
```
$ cargo run
   Compiling branches v0.1.0 (file:///projects/branches)
error[E0308]: `if` and `else` have incompatible types
 --> src/main.rs:4:44
  |
4 |     let number = if condition { 5 } else { "six" };
  |                                 -          ^^^^^ expected integer, found `&str`
  |                                 |
  |                                 expected because of this

For more information about this error, try `rustc --explain E0308`.
error: could not compile `branches` due to previous error

```
 The expression in the `if` block evaluates to an integer, and the expression in the `else` block evaluates to a string. This won’t work because variables must have a single type, and Rust needs to know at compile time what type the `number` variable is, definitively. Knowing the type of `number` lets the compiler verify the type is valid everywhere we use `number`. Rust wouldn’t be able to do that if the type of `number` was only determined at runtime; the compiler would be more complex and would make fewer guarantees about the code if it had to keep track of multiple hypothetical types for any variable.

 ### Repetition with Loops

 It’s often useful to execute a block of code more than once. For this task, Rust provides several *loops*, which will run through the code inside the loop body to the end and then start immediately back at the beginning. To experiment with loops, let’s make a new project called *loops*.

 Rust has three kinds of loops: `loop`, `while`, and `for`. Let’s try each one.

 #### Repeating Code with `loop`

 The `loop` keyword tells Rust to execute a block of code over and over again forever or until you explicitly tell it to stop.

 As an example, change the *src/main.rs* file in your *loops* directory to look like this:

 Filename: src/main.rs

 
```
fn main() {
    loop {
        println!("again!");
    }
}
```
 When we run this program, we’ll see `again!` printed over and over continuously until we stop the program manually. Most terminals support the keyboard shortcut ctrl-c to interrupt a program that is stuck in a continual loop. Give it a try:

 
```
$ cargo run
   Compiling loops v0.1.0 (file:///projects/loops)
    Finished dev [unoptimized + debuginfo] target(s) in 0.29s
     Running `target/debug/loops`
again!
again!
again!
again!
^Cagain!

```
 The symbol `^C` represents where you pressed ctrl-c. You may or may not see the word `again!` printed after the `^C`, depending on where the code was in the loop when it received the interrupt signal.

 Fortunately, Rust also provides a way to break out of a loop using code. You can place the `break` keyword within the loop to tell the program when to stop executing the loop. Recall that we did this in the guessing game in the [“Quitting After a Correct Guess”](ch02-00-guessing-game-tutorial#quitting-after-a-correct-guess) section of Chapter 2 to exit the program when the user won the game by guessing the correct number.

 We also used `continue` in the guessing game, which in a loop tells the program to skip over any remaining code in this iteration of the loop and go to the next iteration.

 #### Returning Values from Loops

 One of the uses of a `loop` is to retry an operation you know might fail, such as checking whether a thread has completed its job. You might also need to pass the result of that operation out of the loop to the rest of your code. To do this, you can add the value you want returned after the `break` expression you use to stop the loop; that value will be returned out of the loop so you can use it, as shown here:

 
```
fn main() {
    let mut counter = 0;

    let result = loop {
        counter += 1;

        if counter == 10 {
            break counter * 2;
        }
    };

    println!("The result is {result}");
}
```
 Before the loop, we declare a variable named `counter` and initialize it to `0`. Then we declare a variable named `result` to hold the value returned from the loop. On every iteration of the loop, we add `1` to the `counter` variable, and then check whether the `counter` is equal to `10`. When it is, we use the `break` keyword with the value `counter * 2`. After the loop, we use a semicolon to end the statement that assigns the value to `result`. Finally, we print the value in `result`, which in this case is `20`.

 #### Loop Labels to Disambiguate Between Multiple Loops

 If you have loops within loops, `break` and `continue` apply to the innermost loop at that point. You can optionally specify a *loop label* on a loop that you can then use with `break` or `continue` to specify that those keywords apply to the labeled loop instead of the innermost loop. Loop labels must begin with a single quote. Here’s an example with two nested loops:

 
```
fn main() {
    let mut count = 0;
    'counting_up: loop {
        println!("count = {count}");
        let mut remaining = 10;

        loop {
            println!("remaining = {remaining}");
            if remaining == 9 {
                break;
            }
            if count == 2 {
                break 'counting_up;
            }
            remaining -= 1;
        }

        count += 1;
    }
    println!("End count = {count}");
}
```
 The outer loop has the label `'counting_up`, and it will count up from 0 to 2. The inner loop without a label counts down from 10 to 9. The first `break` that doesn’t specify a label will exit the inner loop only. The `break 'counting_up;` statement will exit the outer loop. This code prints:

 
```
$ cargo run
   Compiling loops v0.1.0 (file:///projects/loops)
    Finished dev [unoptimized + debuginfo] target(s) in 0.58s
     Running `target/debug/loops`
count = 0
remaining = 10
remaining = 9
count = 1
remaining = 10
remaining = 9
count = 2
remaining = 10
End count = 2

```
 #### Conditional Loops with `while`

 A program will often need to evaluate a condition within a loop. While the condition is `true`, the loop runs. When the condition ceases to be `true`, the program calls `break`, stopping the loop. It’s possible to implement behavior like this using a combination of `loop`, `if`, `else`, and `break`; you could try that now in a program, if you’d like. However, this pattern is so common that Rust has a built-in language construct for it, called a `while` loop. In Listing 3-3, we use `while` to loop the program three times, counting down each time, and then, after the loop, print a message and exit.

 Filename: src/main.rs

 
```
fn main() {
    let mut number = 3;

    while number != 0 {
        println!("{number}!");

        number -= 1;
    }

    println!("LIFTOFF!!!");
}
```
 Listing 3-3: Using a `while` loop to run code while a condition holds true

 This construct eliminates a lot of nesting that would be necessary if you used `loop`, `if`, `else`, and `break`, and it’s clearer. While a condition evaluates to `true`, the code runs; otherwise, it exits the loop.

 #### Looping Through a Collection with `for`

 You can choose to use the `while` construct to loop over the elements of a collection, such as an array. For example, the loop in Listing 3-4 prints each element in the array `a`.

 Filename: src/main.rs

 
```
fn main() {
    let a = [10, 20, 30, 40, 50];
    let mut index = 0;

    while index < 5 {
        println!("the value is: {}", a[index]);

        index += 1;
    }
}
```
 Listing 3-4: Looping through each element of a collection using a `while` loop

 Here, the code counts up through the elements in the array. It starts at index `0`, and then loops until it reaches the final index in the array (that is, when `index < 5` is no longer `true`). Running this code will print every element in the array:

 
```
$ cargo run
   Compiling loops v0.1.0 (file:///projects/loops)
    Finished dev [unoptimized + debuginfo] target(s) in 0.32s
     Running `target/debug/loops`
the value is: 10
the value is: 20
the value is: 30
the value is: 40
the value is: 50

```
 All five array values appear in the terminal, as expected. Even though `index` will reach a value of `5` at some point, the loop stops executing before trying to fetch a sixth value from the array.

 However, this approach is error prone; we could cause the program to panic if the index value or test condition is incorrect. For example, if you changed the definition of the `a` array to have four elements but forgot to update the condition to `while index < 4`, the code would panic. It’s also slow, because the compiler adds runtime code to perform the conditional check of whether the index is within the bounds of the array on every iteration through the loop.

 As a more concise alternative, you can use a `for` loop and execute some code for each item in a collection. A `for` loop looks like the code in Listing 3-5.

 Filename: src/main.rs

 
```
fn main() {
    let a = [10, 20, 30, 40, 50];

    for element in a {
        println!("the value is: {element}");
    }
}
```
 Listing 3-5: Looping through each element of a collection using a `for` loop

 When we run this code, we’ll see the same output as in Listing 3-4. More importantly, we’ve now increased the safety of the code and eliminated the chance of bugs that might result from going beyond the end of the array or not going far enough and missing some items.

 Using the `for` loop, you wouldn’t need to remember to change any other code if you changed the number of values in the array, as you would with the method used in Listing 3-4.

 The safety and conciseness of `for` loops make them the most commonly used loop construct in Rust. Even in situations in which you want to run some code a certain number of times, as in the countdown example that used a `while` loop in Listing 3-3, most Rustaceans would use a `for` loop. The way to do that would be to use a `Range`, provided by the standard library, which generates all numbers in sequence starting from one number and ending before another number.

 Here’s what the countdown would look like using a `for` loop and another method we’ve not yet talked about, `rev`, to reverse the range:

 Filename: src/main.rs

 
```
fn main() {
    for number in (1..4).rev() {
        println!("{number}!");
    }
    println!("LIFTOFF!!!");
}
```
 This code is a bit nicer, isn’t it?

 Summary
-------

 You made it! This was a sizable chapter: you learned about variables, scalar and compound data types, functions, comments, `if` expressions, and loops! To practice with the concepts discussed in this chapter, try building programs to do the following:

 * Convert temperatures between Fahrenheit and Celsius.
* Generate the *n*th Fibonacci number.
* Print the lyrics to the Christmas carol “The Twelve Days of Christmas,” taking advantage of the repetition in the song.

 When you’re ready to move on, we’ll talk about a concept in Rust that *doesn’t* commonly exist in other programming languages: ownership.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch03-05-control-flow.html>

Understanding Ownership
=======================

 Ownership is Rust’s most unique feature and has deep implications for the rest of the language. It enables Rust to make memory safety guarantees without needing a garbage collector, so it’s important to understand how ownership works. In this chapter, we’ll talk about ownership as well as several related features: borrowing, slices, and how Rust lays data out in memory.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html>

What Is Ownership?
==================

 *Ownership* is a set of rules that govern how a Rust program manages memory. All programs have to manage the way they use a computer’s memory while running. Some languages have garbage collection that regularly looks for no-longer-used memory as the program runs; in other languages, the programmer must explicitly allocate and free the memory. Rust uses a third approach: memory is managed through a system of ownership with a set of rules that the compiler checks. If any of the rules are violated, the program won’t compile. None of the features of ownership will slow down your program while it’s running.

 Because ownership is a new concept for many programmers, it does take some time to get used to. The good news is that the more experienced you become with Rust and the rules of the ownership system, the easier you’ll find it to naturally develop code that is safe and efficient. Keep at it!

 When you understand ownership, you’ll have a solid foundation for understanding the features that make Rust unique. In this chapter, you’ll learn ownership by working through some examples that focus on a very common data structure: strings.

 
>  ### The Stack and the Heap
> 
>  Many programming languages don’t require you to think about the stack and the heap very often. But in a systems programming language like Rust, whether a value is on the stack or the heap affects how the language behaves and why you have to make certain decisions. Parts of ownership will be described in relation to the stack and the heap later in this chapter, so here is a brief explanation in preparation.
> 
>  Both the stack and the heap are parts of memory available to your code to use at runtime, but they are structured in different ways. The stack stores values in the order it gets them and removes the values in the opposite order. This is referred to as *last in, first out*. Think of a stack of plates: when you add more plates, you put them on top of the pile, and when you need a plate, you take one off the top. Adding or removing plates from the middle or bottom wouldn’t work as well! Adding data is called *pushing onto the stack*, and removing data is called *popping off the stack*. All data stored on the stack must have a known, fixed size. Data with an unknown size at compile time or a size that might change must be stored on the heap instead.
> 
>  The heap is less organized: when you put data on the heap, you request a certain amount of space. The memory allocator finds an empty spot in the heap that is big enough, marks it as being in use, and returns a *pointer*, which is the address of that location. This process is called *allocating on the heap* and is sometimes abbreviated as just *allocating* (pushing values onto the stack is not considered allocating). Because the pointer to the heap is a known, fixed size, you can store the pointer on the stack, but when you want the actual data, you must follow the pointer. Think of being seated at a restaurant. When you enter, you state the number of people in your group, and the host finds an empty table that fits everyone and leads you there. If someone in your group comes late, they can ask where you’ve been seated to find you.
> 
>  Pushing to the stack is faster than allocating on the heap because the allocator never has to search for a place to store new data; that location is always at the top of the stack. Comparatively, allocating space on the heap requires more work because the allocator must first find a big enough space to hold the data and then perform bookkeeping to prepare for the next allocation.
> 
>  Accessing data in the heap is slower than accessing data on the stack because you have to follow a pointer to get there. Contemporary processors are faster if they jump around less in memory. Continuing the analogy, consider a server at a restaurant taking orders from many tables. It’s most efficient to get all the orders at one table before moving on to the next table. Taking an order from table A, then an order from table B, then one from A again, and then one from B again would be a much slower process. By the same token, a processor can do its job better if it works on data that’s close to other data (as it is on the stack) rather than farther away (as it can be on the heap).
> 
>  When your code calls a function, the values passed into the function (including, potentially, pointers to data on the heap) and the function’s local variables get pushed onto the stack. When the function is over, those values get popped off the stack.
> 
>  Keeping track of what parts of code are using what data on the heap, minimizing the amount of duplicate data on the heap, and cleaning up unused data on the heap so you don’t run out of space are all problems that ownership addresses. Once you understand ownership, you won’t need to think about the stack and the heap very often, but knowing that the main purpose of ownership is to manage heap data can help explain why it works the way it does.
> 
>  

 ### Ownership Rules

 First, let’s take a look at the ownership rules. Keep these rules in mind as we work through the examples that illustrate them:

 * Each value in Rust has an *owner*.
* There can only be one owner at a time.
* When the owner goes out of scope, the value will be dropped.

 ### Variable Scope

 Now that we’re past basic Rust syntax, we won’t include all the `fn main() {` code in examples, so if you’re following along, make sure to put the following examples inside a `main` function manually. As a result, our examples will be a bit more concise, letting us focus on the actual details rather than boilerplate code.

 As a first example of ownership, we’ll look at the *scope* of some variables. A scope is the range within a program for which an item is valid. Take the following variable:

 
```
#![allow(unused)]
fn main() {
let s = "hello";
}
```
 The variable `s` refers to a string literal, where the value of the string is hardcoded into the text of our program. The variable is valid from the point at which it’s declared until the end of the current *scope*. Listing 4-1 shows a program with comments annotating where the variable `s` would be valid.

 
```
fn main() {
    {                      // s is not valid here, it’s not yet declared
        let s = "hello";   // s is valid from this point forward

        // do stuff with s
    }                      // this scope is now over, and s is no longer valid
}
```
 Listing 4-1: A variable and the scope in which it is valid

 In other words, there are two important points in time here:

 * When `s` comes *into* scope, it is valid.
* It remains valid until it goes *out of* scope.

 At this point, the relationship between scopes and when variables are valid is similar to that in other programming languages. Now we’ll build on top of this understanding by introducing the `String` type.

 ### The `String` Type

 To illustrate the rules of ownership, we need a data type that is more complex than those we covered in the [“Data Types”](ch03-02-data-types#data-types) section of Chapter 3. The types covered previously are of a known size, can be stored on the stack and popped off the stack when their scope is over, and can be quickly and trivially copied to make a new, independent instance if another part of code needs to use the same value in a different scope. But we want to look at data that is stored on the heap and explore how Rust knows when to clean up that data, and the `String` type is a great example.

 We’ll concentrate on the parts of `String` that relate to ownership. These aspects also apply to other complex data types, whether they are provided by the standard library or created by you. We’ll discuss `String` in more depth in [Chapter 8](ch08-02-strings).

 We’ve already seen string literals, where a string value is hardcoded into our program. String literals are convenient, but they aren’t suitable for every situation in which we may want to use text. One reason is that they’re immutable. Another is that not every string value can be known when we write our code: for example, what if we want to take user input and store it? For these situations, Rust has a second string type, `String`. This type manages data allocated on the heap and as such is able to store an amount of text that is unknown to us at compile time. You can create a `String` from a string literal using the `from` function, like so:

 
```
#![allow(unused)]
fn main() {
let s = String::from("hello");
}
```
 The double colon `::` operator allows us to namespace this particular `from` function under the `String` type rather than using some sort of name like `string_from`. We’ll discuss this syntax more in the [“Method Syntax”](ch05-03-method-syntax#method-syntax) section of Chapter 5, and when we talk about namespacing with modules in [“Paths for Referring to an Item in the Module Tree”](ch07-03-paths-for-referring-to-an-item-in-the-module-tree) in Chapter 7.

 This kind of string *can* be mutated:

 
```
fn main() {
    let mut s = String::from("hello");

    s.push_str(", world!"); // push_str() appends a literal to a String

    println!("{}", s); // This will print `hello, world!`
}
```
 So, what’s the difference here? Why can `String` be mutated but literals cannot? The difference is in how these two types deal with memory.

 ### Memory and Allocation

 In the case of a string literal, we know the contents at compile time, so the text is hardcoded directly into the final executable. This is why string literals are fast and efficient. But these properties only come from the string literal’s immutability. Unfortunately, we can’t put a blob of memory into the binary for each piece of text whose size is unknown at compile time and whose size might change while running the program.

 With the `String` type, in order to support a mutable, growable piece of text, we need to allocate an amount of memory on the heap, unknown at compile time, to hold the contents. This means:

 * The memory must be requested from the memory allocator at runtime.
* We need a way of returning this memory to the allocator when we’re done with our `String`.

 That first part is done by us: when we call `String::from`, its implementation requests the memory it needs. This is pretty much universal in programming languages.

 However, the second part is different. In languages with a *garbage collector (GC)*, the GC keeps track of and cleans up memory that isn’t being used anymore, and we don’t need to think about it. In most languages without a GC, it’s our responsibility to identify when memory is no longer being used and to call code to explicitly free it, just as we did to request it. Doing this correctly has historically been a difficult programming problem. If we forget, we’ll waste memory. If we do it too early, we’ll have an invalid variable. If we do it twice, that’s a bug too. We need to pair exactly one `allocate` with exactly one `free`.

 Rust takes a different path: the memory is automatically returned once the variable that owns it goes out of scope. Here’s a version of our scope example from Listing 4-1 using a `String` instead of a string literal:

 
```
fn main() {
    {
        let s = String::from("hello"); // s is valid from this point forward

        // do stuff with s
    }                                  // this scope is now over, and s is no
                                       // longer valid
}
```
 There is a natural point at which we can return the memory our `String` needs to the allocator: when `s` goes out of scope. When a variable goes out of scope, Rust calls a special function for us. This function is called [`drop`](../std/ops/trait.drop#tymethod.drop), and it’s where the author of `String` can put the code to return the memory. Rust calls `drop` automatically at the closing curly bracket.

 
>  Note: In C++, this pattern of deallocating resources at the end of an item’s lifetime is sometimes called *Resource Acquisition Is Initialization (RAII)*. The `drop` function in Rust will be familiar to you if you’ve used RAII patterns.
> 
>  

 This pattern has a profound impact on the way Rust code is written. It may seem simple right now, but the behavior of code can be unexpected in more complicated situations when we want to have multiple variables use the data we’ve allocated on the heap. Let’s explore some of those situations now.

 #### Variables and Data Interacting with Move

 Multiple variables can interact with the same data in different ways in Rust. Let’s look at an example using an integer in Listing 4-2.

 
```
fn main() {
    let x = 5;
    let y = x;
}
```
 Listing 4-2: Assigning the integer value of variable `x` to `y`

 We can probably guess what this is doing: “bind the value `5` to `x`; then make a copy of the value in `x` and bind it to `y`.” We now have two variables, `x` and `y`, and both equal `5`. This is indeed what is happening, because integers are simple values with a known, fixed size, and these two `5` values are pushed onto the stack.

 Now let’s look at the `String` version:

 
```
fn main() {
    let s1 = String::from("hello");
    let s2 = s1;
}
```
 This looks very similar, so we might assume that the way it works would be the same: that is, the second line would make a copy of the value in `s1` and bind it to `s2`. But this isn’t quite what happens.

 Take a look at Figure 4-1 to see what is happening to `String` under the covers. A `String` is made up of three parts, shown on the left: a pointer to the memory that holds the contents of the string, a length, and a capacity. This group of data is stored on the stack. On the right is the memory on the heap that holds the contents.

 ![Two tables: the first table contains the representation of s1 on the
stack, consisting of its length (5), capacity (5), and a pointer to the first
value in the second table. The second table contains the representation of the
string data on the heap, byte by byte.]

 Figure 4-1: Representation in memory of a `String` holding the value `"hello"` bound to `s1`

 The length is how much memory, in bytes, the contents of the `String` are currently using. The capacity is the total amount of memory, in bytes, that the `String` has received from the allocator. The difference between length and capacity matters, but not in this context, so for now, it’s fine to ignore the capacity.

 When we assign `s1` to `s2`, the `String` data is copied, meaning we copy the pointer, the length, and the capacity that are on the stack. We do not copy the data on the heap that the pointer refers to. In other words, the data representation in memory looks like Figure 4-2.

 ![Three tables: tables s1 and s2 representing those strings on the
stack, respectively, and both pointing to the same string data on the heap.]

 Figure 4-2: Representation in memory of the variable `s2` that has a copy of the pointer, length, and capacity of `s1`

 The representation does *not* look like Figure 4-3, which is what memory would look like if Rust instead copied the heap data as well. If Rust did this, the operation `s2 = s1` could be very expensive in terms of runtime performance if the data on the heap were large.

 ![Four tables: two tables representing the stack data for s1 and s2,
and each points to its own copy of string data on the heap.]

 Figure 4-3: Another possibility for what `s2 = s1` might do if Rust copied the heap data as well

 Earlier, we said that when a variable goes out of scope, Rust automatically calls the `drop` function and cleans up the heap memory for that variable. But Figure 4-2 shows both data pointers pointing to the same location. This is a problem: when `s2` and `s1` go out of scope, they will both try to free the same memory. This is known as a *double free* error and is one of the memory safety bugs we mentioned previously. Freeing memory twice can lead to memory corruption, which can potentially lead to security vulnerabilities.

 To ensure memory safety, after the line `let s2 = s1;`, Rust considers `s1` as no longer valid. Therefore, Rust doesn’t need to free anything when `s1` goes out of scope. Check out what happens when you try to use `s1` after `s2` is created; it won’t work:

 
```
fn main() {
    let s1 = String::from("hello");
    let s2 = s1;

    println!("{}, world!", s1);
}
```
 You’ll get an error like this because Rust prevents you from using the invalidated reference:

 
```
$ cargo run
   Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0382]: borrow of moved value: `s1`
 --> src/main.rs:5:28
  |
2 |     let s1 = String::from("hello");
  |         -- move occurs because `s1` has type `String`, which does not implement the `Copy` trait
3 |     let s2 = s1;
  |              -- value moved here
4 |
5 |     println!("{}, world!", s1);
  |                            ^^ value borrowed here after move
  |
  = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider cloning the value if the performance cost is acceptable
  |
3 |     let s2 = s1.clone();
  |                ++++++++

For more information about this error, try `rustc --explain E0382`.
error: could not compile `ownership` due to previous error

```
 If you’ve heard the terms *shallow copy* and *deep copy* while working with other languages, the concept of copying the pointer, length, and capacity without copying the data probably sounds like making a shallow copy. But because Rust also invalidates the first variable, instead of being called a shallow copy, it’s known as a *move*. In this example, we would say that `s1` was *moved* into `s2`. So, what actually happens is shown in Figure 4-4.

 ![Three tables: tables s1 and s2 representing those strings on the
stack, respectively, and both pointing to the same string data on the heap.
Table s1 is grayed out be-cause s1 is no longer valid; only s2 can be used to
access the heap data.]

 Figure 4-4: Representation in memory after `s1` has been invalidated

 That solves our problem! With only `s2` valid, when it goes out of scope it alone will free the memory, and we’re done.

 In addition, there’s a design choice that’s implied by this: Rust will never automatically create “deep” copies of your data. Therefore, any *automatic* copying can be assumed to be inexpensive in terms of runtime performance.

 #### Variables and Data Interacting with Clone

 If we *do* want to deeply copy the heap data of the `String`, not just the stack data, we can use a common method called `clone`. We’ll discuss method syntax in Chapter 5, but because methods are a common feature in many programming languages, you’ve probably seen them before.

 Here’s an example of the `clone` method in action:

 
```
fn main() {
    let s1 = String::from("hello");
    let s2 = s1.clone();

    println!("s1 = {}, s2 = {}", s1, s2);
}
```
 This works just fine and explicitly produces the behavior shown in Figure 4-3, where the heap data *does* get copied.

 When you see a call to `clone`, you know that some arbitrary code is being executed and that code may be expensive. It’s a visual indicator that something different is going on.

 #### Stack-Only Data: Copy

 There’s another wrinkle we haven’t talked about yet. This code using integers—part of which was shown in Listing 4-2—works and is valid:

 
```
fn main() {
    let x = 5;
    let y = x;

    println!("x = {}, y = {}", x, y);
}
```
 But this code seems to contradict what we just learned: we don’t have a call to `clone`, but `x` is still valid and wasn’t moved into `y`.

 The reason is that types such as integers that have a known size at compile time are stored entirely on the stack, so copies of the actual values are quick to make. That means there’s no reason we would want to prevent `x` from being valid after we create the variable `y`. In other words, there’s no difference between deep and shallow copying here, so calling `clone` wouldn’t do anything different from the usual shallow copying, and we can leave it out.

 Rust has a special annotation called the `Copy` trait that we can place on types that are stored on the stack, as integers are (we’ll talk more about traits in [Chapter 10](ch10-02-traits)). If a type implements the `Copy` trait, variables that use it do not move, but rather are trivially copied, making them still valid after assignment to another variable.

 Rust won’t let us annotate a type with `Copy` if the type, or any of its parts, has implemented the `Drop` trait. If the type needs something special to happen when the value goes out of scope and we add the `Copy` annotation to that type, we’ll get a compile-time error. To learn about how to add the `Copy` annotation to your type to implement the trait, see [“Derivable Traits”](appendix-03-derivable-traits) in Appendix C.

 So, what types implement the `Copy` trait? You can check the documentation for the given type to be sure, but as a general rule, any group of simple scalar values can implement `Copy`, and nothing that requires allocation or is some form of resource can implement `Copy`. Here are some of the types that implement `Copy`:

 * All the integer types, such as `u32`.
* The Boolean type, `bool`, with values `true` and `false`.
* All the floating-point types, such as `f64`.
* The character type, `char`.
* Tuples, if they only contain types that also implement `Copy`. For example, `(i32, i32)` implements `Copy`, but `(i32, String)` does not.

 ### Ownership and Functions

 The mechanics of passing a value to a function are similar to those when assigning a value to a variable. Passing a variable to a function will move or copy, just as assignment does. Listing 4-3 has an example with some annotations showing where variables go into and out of scope.

 Filename: src/main.rs

 
```
fn main() {
    let s = String::from("hello");  // s comes into scope

    takes_ownership(s);             // s's value moves into the function...
                                    // ... and so is no longer valid here

    let x = 5;                      // x comes into scope

    makes_copy(x);                  // x would move into the function,
                                    // but i32 is Copy, so it's okay to still
                                    // use x afterward

} // Here, x goes out of scope, then s. But because s's value was moved, nothing
  // special happens.

fn takes_ownership(some_string: String) { // some_string comes into scope
    println!("{}", some_string);
} // Here, some_string goes out of scope and `drop` is called. The backing
  // memory is freed.

fn makes_copy(some_integer: i32) { // some_integer comes into scope
    println!("{}", some_integer);
} // Here, some_integer goes out of scope. Nothing special happens.
```
 Listing 4-3: Functions with ownership and scope annotated

 If we tried to use `s` after the call to `takes_ownership`, Rust would throw a compile-time error. These static checks protect us from mistakes. Try adding code to `main` that uses `s` and `x` to see where you can use them and where the ownership rules prevent you from doing so.

 ### Return Values and Scope

 Returning values can also transfer ownership. Listing 4-4 shows an example of a function that returns some value, with similar annotations as those in Listing 4-3.

 Filename: src/main.rs

 
```
fn main() {
    let s1 = gives_ownership();         // gives_ownership moves its return
                                        // value into s1

    let s2 = String::from("hello");     // s2 comes into scope

    let s3 = takes_and_gives_back(s2);  // s2 is moved into
                                        // takes_and_gives_back, which also
                                        // moves its return value into s3
} // Here, s3 goes out of scope and is dropped. s2 was moved, so nothing
  // happens. s1 goes out of scope and is dropped.

fn gives_ownership() -> String {             // gives_ownership will move its
                                             // return value into the function
                                             // that calls it

    let some_string = String::from("yours"); // some_string comes into scope

    some_string                              // some_string is returned and
                                             // moves out to the calling
                                             // function
}

// This function takes a String and returns one
fn takes_and_gives_back(a_string: String) -> String { // a_string comes into
                                                      // scope

    a_string  // a_string is returned and moves out to the calling function
}
```
 Listing 4-4: Transferring ownership of return values

 The ownership of a variable follows the same pattern every time: assigning a value to another variable moves it. When a variable that includes data on the heap goes out of scope, the value will be cleaned up by `drop` unless ownership of the data has been moved to another variable.

 While this works, taking ownership and then returning ownership with every function is a bit tedious. What if we want to let a function use a value but not take ownership? It’s quite annoying that anything we pass in also needs to be passed back if we want to use it again, in addition to any data resulting from the body of the function that we might want to return as well.

 Rust does let us return multiple values using a tuple, as shown in Listing 4-5.

 Filename: src/main.rs

 
```
fn main() {
    let s1 = String::from("hello");

    let (s2, len) = calculate_length(s1);

    println!("The length of '{}' is {}.", s2, len);
}

fn calculate_length(s: String) -> (String, usize) {
    let length = s.len(); // len() returns the length of a String

    (s, length)
}
```
 Listing 4-5: Returning ownership of parameters

 But this is too much ceremony and a lot of work for a concept that should be common. Luckily for us, Rust has a feature for using a value without transferring ownership, called *references*.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html>

Defining an Enum
================

 Where structs give you a way of grouping together related fields and data, like a `Rectangle` with its `width` and `height`, enums give you a way of saying a value is one of a possible set of values. For example, we may want to say that `Rectangle` is one of a set of possible shapes that also includes `Circle` and `Triangle`. To do this, Rust allows us to encode these possibilities as an enum.

 Let’s look at a situation we might want to express in code and see why enums are useful and more appropriate than structs in this case. Say we need to work with IP addresses. Currently, two major standards are used for IP addresses: version four and version six. Because these are the only possibilities for an IP address that our program will come across, we can *enumerate* all possible variants, which is where enumeration gets its name.

 Any IP address can be either a version four or a version six address, but not both at the same time. That property of IP addresses makes the enum data structure appropriate because an enum value can only be one of its variants. Both version four and version six addresses are still fundamentally IP addresses, so they should be treated as the same type when the code is handling situations that apply to any kind of IP address.

 We can express this concept in code by defining an `IpAddrKind` enumeration and listing the possible kinds an IP address can be, `V4` and `V6`. These are the variants of the enum:

 
```
enum IpAddrKind {
    V4,
    V6,
}

fn main() {
    let four = IpAddrKind::V4;
    let six = IpAddrKind::V6;

    route(IpAddrKind::V4);
    route(IpAddrKind::V6);
}

fn route(ip_kind: IpAddrKind) {}
```
 `IpAddrKind` is now a custom data type that we can use elsewhere in our code.

 ### Enum Values

 We can create instances of each of the two variants of `IpAddrKind` like this:

 
```
enum IpAddrKind {
    V4,
    V6,
}

fn main() {
    let four = IpAddrKind::V4;
    let six = IpAddrKind::V6;

    route(IpAddrKind::V4);
    route(IpAddrKind::V6);
}

fn route(ip_kind: IpAddrKind) {}
```
 Note that the variants of the enum are namespaced under its identifier, and we use a double colon to separate the two. This is useful because now both values `IpAddrKind::V4` and `IpAddrKind::V6` are of the same type: `IpAddrKind`. We can then, for instance, define a function that takes any `IpAddrKind`:

 
```
enum IpAddrKind {
    V4,
    V6,
}

fn main() {
    let four = IpAddrKind::V4;
    let six = IpAddrKind::V6;

    route(IpAddrKind::V4);
    route(IpAddrKind::V6);
}

fn route(ip_kind: IpAddrKind) {}
```
 And we can call this function with either variant:

 
```
enum IpAddrKind {
    V4,
    V6,
}

fn main() {
    let four = IpAddrKind::V4;
    let six = IpAddrKind::V6;

    route(IpAddrKind::V4);
    route(IpAddrKind::V6);
}

fn route(ip_kind: IpAddrKind) {}
```
 Using enums has even more advantages. Thinking more about our IP address type, at the moment we don’t have a way to store the actual IP address *data*; we only know what *kind* it is. Given that you just learned about structs in Chapter 5, you might be tempted to tackle this problem with structs as shown in Listing 6-1.

 
```
fn main() {
    enum IpAddrKind {
        V4,
        V6,
    }

    struct IpAddr {
        kind: IpAddrKind,
        address: String,
    }

    let home = IpAddr {
        kind: IpAddrKind::V4,
        address: String::from("127.0.0.1"),
    };

    let loopback = IpAddr {
        kind: IpAddrKind::V6,
        address: String::from("::1"),
    };
}
```
 Listing 6-1: Storing the data and `IpAddrKind` variant of an IP address using a `struct`

 Here, we’ve defined a struct `IpAddr` that has two fields: a `kind` field that is of type `IpAddrKind` (the enum we defined previously) and an `address` field of type `String`. We have two instances of this struct. The first is `home`, and it has the value `IpAddrKind::V4` as its `kind` with associated address data of `127.0.0.1`. The second instance is `loopback`. It has the other variant of `IpAddrKind` as its `kind` value, `V6`, and has address `::1` associated with it. We’ve used a struct to bundle the `kind` and `address` values together, so now the variant is associated with the value.

 However, representing the same concept using just an enum is more concise: rather than an enum inside a struct, we can put data directly into each enum variant. This new definition of the `IpAddr` enum says that both `V4` and `V6` variants will have associated `String` values:

 
```
fn main() {
    enum IpAddr {
        V4(String),
        V6(String),
    }

    let home = IpAddr::V4(String::from("127.0.0.1"));

    let loopback = IpAddr::V6(String::from("::1"));
}
```
 We attach data to each variant of the enum directly, so there is no need for an extra struct. Here, it’s also easier to see another detail of how enums work: the name of each enum variant that we define also becomes a function that constructs an instance of the enum. That is, `IpAddr::V4()` is a function call that takes a `String` argument and returns an instance of the `IpAddr` type. We automatically get this constructor function defined as a result of defining the enum.

 There’s another advantage to using an enum rather than a struct: each variant can have different types and amounts of associated data. Version four IP addresses will always have four numeric components that will have values between 0 and 255. If we wanted to store `V4` addresses as four `u8` values but still express `V6` addresses as one `String` value, we wouldn’t be able to with a struct. Enums handle this case with ease:

 
```
fn main() {
    enum IpAddr {
        V4(u8, u8, u8, u8),
        V6(String),
    }

    let home = IpAddr::V4(127, 0, 0, 1);

    let loopback = IpAddr::V6(String::from("::1"));
}
```
 We’ve shown several different ways to define data structures to store version four and version six IP addresses. However, as it turns out, wanting to store IP addresses and encode which kind they are is so common that [the standard library has a definition we can use!](../std/net/enum.ipaddr) Let’s look at how the standard library defines `IpAddr`: it has the exact enum and variants that we’ve defined and used, but it embeds the address data inside the variants in the form of two different structs, which are defined differently for each variant:

 
```
#![allow(unused)]
fn main() {
struct Ipv4Addr {
    // --snip--
}

struct Ipv6Addr {
    // --snip--
}

enum IpAddr {
    V4(Ipv4Addr),
    V6(Ipv6Addr),
}
}
```
 This code illustrates that you can put any kind of data inside an enum variant: strings, numeric types, or structs, for example. You can even include another enum! Also, standard library types are often not much more complicated than what you might come up with.

 Note that even though the standard library contains a definition for `IpAddr`, we can still create and use our own definition without conflict because we haven’t brought the standard library’s definition into our scope. We’ll talk more about bringing types into scope in Chapter 7.

 Let’s look at another example of an enum in Listing 6-2: this one has a wide variety of types embedded in its variants.

 
```
enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}

fn main() {}
```
 Listing 6-2: A `Message` enum whose variants each store different amounts and types of values

 This enum has four variants with different types:

 * `Quit` has no data associated with it at all.
* `Move` has named fields, like a struct does.
* `Write` includes a single `String`.
* `ChangeColor` includes three `i32` values.

 Defining an enum with variants such as the ones in Listing 6-2 is similar to defining different kinds of struct definitions, except the enum doesn’t use the `struct` keyword and all the variants are grouped together under the `Message` type. The following structs could hold the same data that the preceding enum variants hold:

 
```
struct QuitMessage; // unit struct
struct MoveMessage {
    x: i32,
    y: i32,
}
struct WriteMessage(String); // tuple struct
struct ChangeColorMessage(i32, i32, i32); // tuple struct

fn main() {}
```
 But if we used the different structs, each of which has its own type, we couldn’t as easily define a function to take any of these kinds of messages as we could with the `Message` enum defined in Listing 6-2, which is a single type.

 There is one more similarity between enums and structs: just as we’re able to define methods on structs using `impl`, we’re also able to define methods on enums. Here’s a method named `call` that we could define on our `Message` enum:

 
```
fn main() {
    enum Message {
        Quit,
        Move { x: i32, y: i32 },
        Write(String),
        ChangeColor(i32, i32, i32),
    }

    impl Message {
        fn call(&self) {
            // method body would be defined here
        }
    }

    let m = Message::Write(String::from("hello"));
    m.call();
}
```
 The body of the method would use `self` to get the value that we called the method on. In this example, we’ve created a variable `m` that has the value `Message::Write(String::from("hello"))`, and that is what `self` will be in the body of the `call` method when `m.call()` runs.

 Let’s look at another enum in the standard library that is very common and useful: `Option`.

 ### The `Option` Enum and Its Advantages Over Null Values

 This section explores a case study of `Option`, which is another enum defined by the standard library. The `Option` type encodes the very common scenario in which a value could be something or it could be nothing.

 For example, if you request the first item in a non-empty list, you would get a value. If you request the first item in an empty list, you would get nothing. Expressing this concept in terms of the type system means the compiler can check whether you’ve handled all the cases you should be handling; this functionality can prevent bugs that are extremely common in other programming languages.

 Programming language design is often thought of in terms of which features you include, but the features you exclude are important too. Rust doesn’t have the null feature that many other languages have. *Null* is a value that means there is no value there. In languages with null, variables can always be in one of two states: null or not-null.

 In his 2009 presentation “Null References: The Billion Dollar Mistake,” Tony Hoare, the inventor of null, has this to say:

 
>  I call it my billion-dollar mistake. At that time, I was designing the first comprehensive type system for references in an object-oriented language. My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn’t resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.
> 
>  

 The problem with null values is that if you try to use a null value as a not-null value, you’ll get an error of some kind. Because this null or not-null property is pervasive, it’s extremely easy to make this kind of error.

 However, the concept that null is trying to express is still a useful one: a null is a value that is currently invalid or absent for some reason.

 The problem isn’t really with the concept but with the particular implementation. As such, Rust does not have nulls, but it does have an enum that can encode the concept of a value being present or absent. This enum is `Option<T>`, and it is [defined by the standard library](../std/option/enum.option) as follows:

 
```
#![allow(unused)]
fn main() {
enum Option<T> {
    None,
    Some(T),
}
}
```
 The `Option<T>` enum is so useful that it’s even included in the prelude; you don’t need to bring it into scope explicitly. Its variants are also included in the prelude: you can use `Some` and `None` directly without the `Option::` prefix. The `Option<T>` enum is still just a regular enum, and `Some(T)` and `None` are still variants of type `Option<T>`.

 The `<T>` syntax is a feature of Rust we haven’t talked about yet. It’s a generic type parameter, and we’ll cover generics in more detail in Chapter 10. For now, all you need to know is that `<T>` means that the `Some` variant of the `Option` enum can hold one piece of data of any type, and that each concrete type that gets used in place of `T` makes the overall `Option<T>` type a different type. Here are some examples of using `Option` values to hold number types and string types:

 
```
fn main() {
    let some_number = Some(5);
    let some_char = Some('e');

    let absent_number: Option<i32> = None;
}
```
 The type of `some_number` is `Option<i32>`. The type of `some_char` is `Option<char>`, which is a different type. Rust can infer these types because we’ve specified a value inside the `Some` variant. For `absent_number`, Rust requires us to annotate the overall `Option` type: the compiler can’t infer the type that the corresponding `Some` variant will hold by looking only at a `None` value. Here, we tell Rust that we mean for `absent_number` to be of type `Option<i32>`.

 When we have a `Some` value, we know that a value is present and the value is held within the `Some`. When we have a `None` value, in some sense it means the same thing as null: we don’t have a valid value. So why is having `Option<T>` any better than having null?

 In short, because `Option<T>` and `T` (where `T` can be any type) are different types, the compiler won’t let us use an `Option<T>` value as if it were definitely a valid value. For example, this code won’t compile, because it’s trying to add an `i8` to an `Option<i8>`:

 
```
fn main() {
    let x: i8 = 5;
    let y: Option<i8> = Some(5);

    let sum = x + y;
}
```
 If we run this code, we get an error message like this one:

 
```
$ cargo run
   Compiling enums v0.1.0 (file:///projects/enums)
error[E0277]: cannot add `Option<i8>` to `i8`
 --> src/main.rs:5:17
  |
5 |     let sum = x + y;
  |                 ^ no implementation for `i8 + Option<i8>`
  |
  = help: the trait `Add<Option<i8>>` is not implemented for `i8`
  = help: the following other types implement trait `Add<Rhs>`:
            <&'a i8 as Add<i8>>
            <&i8 as Add<&i8>>
            <i8 as Add<&i8>>
            <i8 as Add>

For more information about this error, try `rustc --explain E0277`.
error: could not compile `enums` due to previous error

```
 Intense! In effect, this error message means that Rust doesn’t understand how to add an `i8` and an `Option<i8>`, because they’re different types. When we have a value of a type like `i8` in Rust, the compiler will ensure that we always have a valid value. We can proceed confidently without having to check for null before using that value. Only when we have an `Option<i8>` (or whatever type of value we’re working with) do we have to worry about possibly not having a value, and the compiler will make sure we handle that case before using the value.

 In other words, you have to convert an `Option<T>` to a `T` before you can perform `T` operations with it. Generally, this helps catch one of the most common issues with null: assuming that something isn’t null when it actually is.

 Eliminating the risk of incorrectly assuming a not-null value helps you to be more confident in your code. In order to have a value that can possibly be null, you must explicitly opt in by making the type of that value `Option<T>`. Then, when you use that value, you are required to explicitly handle the case when the value is null. Everywhere that a value has a type that isn’t an `Option<T>`, you *can* safely assume that the value isn’t null. This was a deliberate design decision for Rust to limit null’s pervasiveness and increase the safety of Rust code.

 So how do you get the `T` value out of a `Some` variant when you have a value of type `Option<T>` so that you can use that value? The `Option<T>` enum has a large number of methods that are useful in a variety of situations; you can check them out in [its documentation](../std/option/enum.option). Becoming familiar with the methods on `Option<T>` will be extremely useful in your journey with Rust.

 In general, in order to use an `Option<T>` value, you want to have code that will handle each variant. You want some code that will run only when you have a `Some(T)` value, and this code is allowed to use the inner `T`. You want some other code to run only if you have a `None` value, and that code doesn’t have a `T` value available. The `match` expression is a control flow construct that does just this when used with enums: it will run different code depending on which variant of the enum it has, and that code can use the data inside the matching value.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html>

The `match` Control Flow Construct
----------------------------------

 Rust has an extremely powerful control flow construct called `match` that allows you to compare a value against a series of patterns and then execute code based on which pattern matches. Patterns can be made up of literal values, variable names, wildcards, and many other things; [Chapter 18](ch18-00-patterns) covers all the different kinds of patterns and what they do. The power of `match` comes from the expressiveness of the patterns and the fact that the compiler confirms that all possible cases are handled.

 Think of a `match` expression as being like a coin-sorting machine: coins slide down a track with variously sized holes along it, and each coin falls through the first hole it encounters that it fits into. In the same way, values go through each pattern in a `match`, and at the first pattern the value “fits,” the value falls into the associated code block to be used during execution.

 Speaking of coins, let’s use them as an example using `match`! We can write a function that takes an unknown US coin and, in a similar way as the counting machine, determines which coin it is and returns its value in cents, as shown in Listing 6-3.

 
```
enum Coin {
    Penny,
    Nickel,
    Dime,
    Quarter,
}

fn value_in_cents(coin: Coin) -> u8 {
    match coin {
        Coin::Penny => 1,
        Coin::Nickel => 5,
        Coin::Dime => 10,
        Coin::Quarter => 25,
    }
}

fn main() {}
```
 Listing 6-3: An enum and a `match` expression that has the variants of the enum as its patterns

 Let’s break down the `match` in the `value_in_cents` function. First we list the `match` keyword followed by an expression, which in this case is the value `coin`. This seems very similar to a conditional expression used with `if`, but there’s a big difference: with `if`, the condition needs to evaluate to a Boolean value, but here it can be any type. The type of `coin` in this example is the `Coin` enum that we defined on the first line.

 Next are the `match` arms. An arm has two parts: a pattern and some code. The first arm here has a pattern that is the value `Coin::Penny` and then the `=>` operator that separates the pattern and the code to run. The code in this case is just the value `1`. Each arm is separated from the next with a comma.

 When the `match` expression executes, it compares the resultant value against the pattern of each arm, in order. If a pattern matches the value, the code associated with that pattern is executed. If that pattern doesn’t match the value, execution continues to the next arm, much as in a coin-sorting machine. We can have as many arms as we need: in Listing 6-3, our `match` has four arms.

 The code associated with each arm is an expression, and the resultant value of the expression in the matching arm is the value that gets returned for the entire `match` expression.

 We don’t typically use curly brackets if the match arm code is short, as it is in Listing 6-3 where each arm just returns a value. If you want to run multiple lines of code in a match arm, you must use curly brackets, and the comma following the arm is then optional. For example, the following code prints “Lucky penny!” every time the method is called with a `Coin::Penny`, but still returns the last value of the block, `1`:

 
```
enum Coin {
    Penny,
    Nickel,
    Dime,
    Quarter,
}

fn value_in_cents(coin: Coin) -> u8 {
    match coin {
        Coin::Penny => {
            println!("Lucky penny!");
            1
        }
        Coin::Nickel => 5,
        Coin::Dime => 10,
        Coin::Quarter => 25,
    }
}

fn main() {}
```
 ### Patterns That Bind to Values

 Another useful feature of match arms is that they can bind to the parts of the values that match the pattern. This is how we can extract values out of enum variants.

 As an example, let’s change one of our enum variants to hold data inside it. From 1999 through 2008, the United States minted quarters with different designs for each of the 50 states on one side. No other coins got state designs, so only quarters have this extra value. We can add this information to our `enum` by changing the `Quarter` variant to include a `UsState` value stored inside it, which we’ve done in Listing 6-4.

 
```
#[derive(Debug)] // so we can inspect the state in a minute
enum UsState {
    Alabama,
    Alaska,
    // --snip--
}

enum Coin {
    Penny,
    Nickel,
    Dime,
    Quarter(UsState),
}

fn main() {}
```
 Listing 6-4: A `Coin` enum in which the `Quarter` variant also holds a `UsState` value

 Let’s imagine that a friend is trying to collect all 50 state quarters. While we sort our loose change by coin type, we’ll also call out the name of the state associated with each quarter so that if it’s one our friend doesn’t have, they can add it to their collection.

 In the match expression for this code, we add a variable called `state` to the pattern that matches values of the variant `Coin::Quarter`. When a `Coin::Quarter` matches, the `state` variable will bind to the value of that quarter’s state. Then we can use `state` in the code for that arm, like so:

 
```
#[derive(Debug)]
enum UsState {
    Alabama,
    Alaska,
    // --snip--
}

enum Coin {
    Penny,
    Nickel,
    Dime,
    Quarter(UsState),
}

fn value_in_cents(coin: Coin) -> u8 {
    match coin {
        Coin::Penny => 1,
        Coin::Nickel => 5,
        Coin::Dime => 10,
        Coin::Quarter(state) => {
            println!("State quarter from {:?}!", state);
            25
        }
    }
}

fn main() {
    value_in_cents(Coin::Quarter(UsState::Alaska));
}
```
 If we were to call `value_in_cents(Coin::Quarter(UsState::Alaska))`, `coin` would be `Coin::Quarter(UsState::Alaska)`. When we compare that value with each of the match arms, none of them match until we reach `Coin::Quarter(state)`. At that point, the binding for `state` will be the value `UsState::Alaska`. We can then use that binding in the `println!` expression, thus getting the inner state value out of the `Coin` enum variant for `Quarter`.

 ### Matching with `Option<T>`

 In the previous section, we wanted to get the inner `T` value out of the `Some` case when using `Option<T>`; we can also handle `Option<T>` using `match`, as we did with the `Coin` enum! Instead of comparing coins, we’ll compare the variants of `Option<T>`, but the way the `match` expression works remains the same.

 Let’s say we want to write a function that takes an `Option<i32>` and, if there’s a value inside, adds 1 to that value. If there isn’t a value inside, the function should return the `None` value and not attempt to perform any operations.

 This function is very easy to write, thanks to `match`, and will look like Listing 6-5.

 
```
fn main() {
    fn plus_one(x: Option<i32>) -> Option<i32> {
        match x {
            None => None,
            Some(i) => Some(i + 1),
        }
    }

    let five = Some(5);
    let six = plus_one(five);
    let none = plus_one(None);
}
```
 Listing 6-5: A function that uses a `match` expression on an `Option<i32>`

 Let’s examine the first execution of `plus_one` in more detail. When we call `plus_one(five)`, the variable `x` in the body of `plus_one` will have the value `Some(5)`. We then compare that against each match arm:

 
```
fn main() {
    fn plus_one(x: Option<i32>) -> Option<i32> {
        match x {
            None => None,
            Some(i) => Some(i + 1),
        }
    }

    let five = Some(5);
    let six = plus_one(five);
    let none = plus_one(None);
}
```
 The `Some(5)` value doesn’t match the pattern `None`, so we continue to the next arm:

 
```
fn main() {
    fn plus_one(x: Option<i32>) -> Option<i32> {
        match x {
            None => None,
            Some(i) => Some(i + 1),
        }
    }

    let five = Some(5);
    let six = plus_one(five);
    let none = plus_one(None);
}
```
 Does `Some(5)` match `Some(i)`? It does! We have the same variant. The `i` binds to the value contained in `Some`, so `i` takes the value `5`. The code in the match arm is then executed, so we add 1 to the value of `i` and create a new `Some` value with our total `6` inside.

 Now let’s consider the second call of `plus_one` in Listing 6-5, where `x` is `None`. We enter the `match` and compare to the first arm:

 
```
fn main() {
    fn plus_one(x: Option<i32>) -> Option<i32> {
        match x {
            None => None,
            Some(i) => Some(i + 1),
        }
    }

    let five = Some(5);
    let six = plus_one(five);
    let none = plus_one(None);
}
```
 It matches! There’s no value to add to, so the program stops and returns the `None` value on the right side of `=>`. Because the first arm matched, no other arms are compared.

 Combining `match` and enums is useful in many situations. You’ll see this pattern a lot in Rust code: `match` against an enum, bind a variable to the data inside, and then execute code based on it. It’s a bit tricky at first, but once you get used to it, you’ll wish you had it in all languages. It’s consistently a user favorite.

 ### Matches Are Exhaustive

 There’s one other aspect of `match` we need to discuss: the arms’ patterns must cover all possibilities. Consider this version of our `plus_one` function, which has a bug and won’t compile:

 
```
fn main() {
    fn plus_one(x: Option<i32>) -> Option<i32> {
        match x {
            Some(i) => Some(i + 1),
        }
    }

    let five = Some(5);
    let six = plus_one(five);
    let none = plus_one(None);
}
```
 We didn’t handle the `None` case, so this code will cause a bug. Luckily, it’s a bug Rust knows how to catch. If we try to compile this code, we’ll get this error:

 
```
$ cargo run
   Compiling enums v0.1.0 (file:///projects/enums)
error[E0004]: non-exhaustive patterns: `None` not covered
 --> src/main.rs:3:15
  |
3 |         match x {
  |               ^ pattern `None` not covered
  |
note: `Option<i32>` defined here
 --> /rustc/d5a82bbd26e1ad8b7401f6a718a9c57c96905483/library/core/src/option.rs:518:1
  |
  = note: 
/rustc/d5a82bbd26e1ad8b7401f6a718a9c57c96905483/library/core/src/option.rs:522:5: not covered
  = note: the matched value is of type `Option<i32>`
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
  |
4 ~             Some(i) => Some(i + 1),
5 ~             None => todo!(),
  |

For more information about this error, try `rustc --explain E0004`.
error: could not compile `enums` due to previous error

```
 Rust knows that we didn’t cover every possible case, and even knows which pattern we forgot! Matches in Rust are *exhaustive*: we must exhaust every last possibility in order for the code to be valid. Especially in the case of `Option<T>`, when Rust prevents us from forgetting to explicitly handle the `None` case, it protects us from assuming that we have a value when we might have null, thus making the billion-dollar mistake discussed earlier impossible.

 ### Catch-all Patterns and the `_` Placeholder

 Using enums, we can also take special actions for a few particular values, but for all other values take one default action. Imagine we’re implementing a game where, if you roll a 3 on a dice roll, your player doesn’t move, but instead gets a new fancy hat. If you roll a 7, your player loses a fancy hat. For all other values, your player moves that number of spaces on the game board. Here’s a `match` that implements that logic, with the result of the dice roll hardcoded rather than a random value, and all other logic represented by functions without bodies because actually implementing them is out of scope for this example:

 
```
fn main() {
    let dice_roll = 9;
    match dice_roll {
        3 => add_fancy_hat(),
        7 => remove_fancy_hat(),
        other => move_player(other),
    }

    fn add_fancy_hat() {}
    fn remove_fancy_hat() {}
    fn move_player(num_spaces: u8) {}
}
```
 For the first two arms, the patterns are the literal values `3` and `7`. For the last arm that covers every other possible value, the pattern is the variable we’ve chosen to name `other`. The code that runs for the `other` arm uses the variable by passing it to the `move_player` function.

 This code compiles, even though we haven’t listed all the possible values a `u8` can have, because the last pattern will match all values not specifically listed. This catch-all pattern meets the requirement that `match` must be exhaustive. Note that we have to put the catch-all arm last because the patterns are evaluated in order. If we put the catch-all arm earlier, the other arms would never run, so Rust will warn us if we add arms after a catch-all!

 Rust also has a pattern we can use when we want a catch-all but don’t want to *use* the value in the catch-all pattern: `_` is a special pattern that matches any value and does not bind to that value. This tells Rust we aren’t going to use the value, so Rust won’t warn us about an unused variable.

 Let’s change the rules of the game: now, if you roll anything other than a 3 or a 7, you must roll again. We no longer need to use the catch-all value, so we can change our code to use `_` instead of the variable named `other`:

 
```
fn main() {
    let dice_roll = 9;
    match dice_roll {
        3 => add_fancy_hat(),
        7 => remove_fancy_hat(),
        _ => reroll(),
    }

    fn add_fancy_hat() {}
    fn remove_fancy_hat() {}
    fn reroll() {}
}
```
 This example also meets the exhaustiveness requirement because we’re explicitly ignoring all other values in the last arm; we haven’t forgotten anything.

 Finally, we’ll change the rules of the game one more time so that nothing else happens on your turn if you roll anything other than a 3 or a 7. We can express that by using the unit value (the empty tuple type we mentioned in [“The Tuple Type”](ch03-02-data-types#the-tuple-type) section) as the code that goes with the `_` arm:

 
```
fn main() {
    let dice_roll = 9;
    match dice_roll {
        3 => add_fancy_hat(),
        7 => remove_fancy_hat(),
        _ => (),
    }

    fn add_fancy_hat() {}
    fn remove_fancy_hat() {}
}
```
 Here, we’re telling Rust explicitly that we aren’t going to use any other value that doesn’t match a pattern in an earlier arm, and we don’t want to run any code in this case.

 There’s more about patterns and matching that we’ll cover in [Chapter 18](ch18-00-patterns). For now, we’re going to move on to the `if let` syntax, which can be useful in situations where the `match` expression is a bit wordy.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch06-02-match.html>

Concise Control Flow with `if let`
==================================

 The `if let` syntax lets you combine `if` and `let` into a less verbose way to handle values that match one pattern while ignoring the rest. Consider the program in Listing 6-6 that matches on an `Option<u8>` value in the `config_max` variable but only wants to execute code if the value is the `Some` variant.

 
```
fn main() {
    let config_max = Some(3u8);
    match config_max {
        Some(max) => println!("The maximum is configured to be {}", max),
        _ => (),
    }
}
```
 Listing 6-6: A `match` that only cares about executing code when the value is `Some`

 If the value is `Some`, we print out the value in the `Some` variant by binding the value to the variable `max` in the pattern. We don’t want to do anything with the `None` value. To satisfy the `match` expression, we have to add `_ => ()` after processing just one variant, which is annoying boilerplate code to add.

 Instead, we could write this in a shorter way using `if let`. The following code behaves the same as the `match` in Listing 6-6:

 
```
fn main() {
    let config_max = Some(3u8);
    if let Some(max) = config_max {
        println!("The maximum is configured to be {}", max);
    }
}
```
 The syntax `if let` takes a pattern and an expression separated by an equal sign. It works the same way as a `match`, where the expression is given to the `match` and the pattern is its first arm. In this case, the pattern is `Some(max)`, and the `max` binds to the value inside the `Some`. We can then use `max` in the body of the `if let` block in the same way we used `max` in the corresponding `match` arm. The code in the `if let` block isn’t run if the value doesn’t match the pattern.

 Using `if let` means less typing, less indentation, and less boilerplate code. However, you lose the exhaustive checking that `match` enforces. Choosing between `match` and `if let` depends on what you’re doing in your particular situation and whether gaining conciseness is an appropriate trade-off for losing exhaustive checking.

 In other words, you can think of `if let` as syntax sugar for a `match` that runs code when the value matches one pattern and then ignores all other values.

 We can include an `else` with an `if let`. The block of code that goes with the `else` is the same as the block of code that would go with the `_` case in the `match` expression that is equivalent to the `if let` and `else`. Recall the `Coin` enum definition in Listing 6-4, where the `Quarter` variant also held a `UsState` value. If we wanted to count all non-quarter coins we see while also announcing the state of the quarters, we could do that with a `match` expression, like this:

 
```
#[derive(Debug)]
enum UsState {
    Alabama,
    Alaska,
    // --snip--
}

enum Coin {
    Penny,
    Nickel,
    Dime,
    Quarter(UsState),
}

fn main() {
    let coin = Coin::Penny;
    let mut count = 0;
    match coin {
        Coin::Quarter(state) => println!("State quarter from {:?}!", state),
        _ => count += 1,
    }
}
```
 Or we could use an `if let` and `else` expression, like this:

 
```
#[derive(Debug)]
enum UsState {
    Alabama,
    Alaska,
    // --snip--
}

enum Coin {
    Penny,
    Nickel,
    Dime,
    Quarter(UsState),
}

fn main() {
    let coin = Coin::Penny;
    let mut count = 0;
    if let Coin::Quarter(state) = coin {
        println!("State quarter from {:?}!", state);
    } else {
        count += 1;
    }
}
```
 If you have a situation in which your program has logic that is too verbose to express using a `match`, remember that `if let` is in your Rust toolbox as well.

 Summary
-------

 We’ve now covered how to use enums to create custom types that can be one of a set of enumerated values. We’ve shown how the standard library’s `Option<T>` type helps you use the type system to prevent errors. When enum values have data inside them, you can use `match` or `if let` to extract and use those values, depending on how many cases you need to handle.

 Your Rust programs can now express concepts in your domain using structs and enums. Creating custom types to use in your API ensures type safety: the compiler will make certain your functions only get values of the type each function expects.

 In order to provide a well-organized API to your users that is straightforward to use and only exposes exactly what your users will need, let’s now turn to Rust’s modules.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch06-03-if-let.html>

Managing Growing Projects with Packages, Crates, and Modules
============================================================

 As you write large programs, organizing your code will become increasingly important. By grouping related functionality and separating code with distinct features, you’ll clarify where to find code that implements a particular feature and where to go to change how a feature works.

 The programs we’ve written so far have been in one module in one file. As a project grows, you should organize code by splitting it into multiple modules and then multiple files. A package can contain multiple binary crates and optionally one library crate. As a package grows, you can extract parts into separate crates that become external dependencies. This chapter covers all these techniques. For very large projects comprising a set of interrelated packages that evolve together, Cargo provides *workspaces*, which we’ll cover in the [“Cargo Workspaces”](ch14-03-cargo-workspaces) section in Chapter 14.

 We’ll also discuss encapsulating implementation details, which lets you reuse code at a higher level: once you’ve implemented an operation, other code can call your code via its public interface without having to know how the implementation works. The way you write code defines which parts are public for other code to use and which parts are private implementation details that you reserve the right to change. This is another way to limit the amount of detail you have to keep in your head.

 A related concept is scope: the nested context in which code is written has a set of names that are defined as “in scope.” When reading, writing, and compiling code, programmers and compilers need to know whether a particular name at a particular spot refers to a variable, function, struct, enum, module, constant, or other item and what that item means. You can create scopes and change which names are in or out of scope. You can’t have two items with the same name in the same scope; tools are available to resolve name conflicts.

 Rust has a number of features that allow you to manage your code’s organization, including which details are exposed, which details are private, and what names are in each scope in your programs. These features, sometimes collectively referred to as the *module system*, include:

 * **Packages:** A Cargo feature that lets you build, test, and share crates
* **Crates:** A tree of modules that produces a library or executable
* **Modules** and **use:** Let you control the organization, scope, and privacy of paths
* **Paths:** A way of naming an item, such as a struct, function, or module

 In this chapter, we’ll cover all these features, discuss how they interact, and explain how to use them to manage scope. By the end, you should have a solid understanding of the module system and be able to work with scopes like a pro!



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch07-00-managing-growing-projects-with-packages-crates-and-modules.html>

Packages and Crates
===================

 The first parts of the module system we’ll cover are packages and crates.

 A *crate* is the smallest amount of code that the Rust compiler considers at a time. Even if you run `rustc` rather than `cargo` and pass a single source code file (as we did all the way back in the “Writing and Running a Rust Program” section of Chapter 1), the compiler considers that file to be a crate. Crates can contain modules, and the modules may be defined in other files that get compiled with the crate, as we’ll see in the coming sections.

 A crate can come in one of two forms: a binary crate or a library crate. *Binary crates* are programs you can compile to an executable that you can run, such as a command-line program or a server. Each must have a function called `main` that defines what happens when the executable runs. All the crates we’ve created so far have been binary crates.

 *Library crates* don’t have a `main` function, and they don’t compile to an executable. Instead, they define functionality intended to be shared with multiple projects. For example, the `rand` crate we used in [Chapter 2](ch02-00-guessing-game-tutorial#generating-a-random-number) provides functionality that generates random numbers. Most of the time when Rustaceans say “crate”, they mean library crate, and they use “crate” interchangeably with the general programming concept of a “library".

 The *crate root* is a source file that the Rust compiler starts from and makes up the root module of your crate (we’ll explain modules in depth in the [“Defining Modules to Control Scope and Privacy”](ch07-02-defining-modules-to-control-scope-and-privacy) section).

 A *package* is a bundle of one or more crates that provides a set of functionality. A package contains a *Cargo.toml* file that describes how to build those crates. Cargo is actually a package that contains the binary crate for the command-line tool you’ve been using to build your code. The Cargo package also contains a library crate that the binary crate depends on. Other projects can depend on the Cargo library crate to use the same logic the Cargo command-line tool uses.

 A package can contain as many binary crates as you like, but at most only one library crate. A package must contain at least one crate, whether that’s a library or binary crate.

 Let’s walk through what happens when we create a package. First, we enter the command `cargo new`:

 
```
$ cargo new my-project
     Created binary (application) `my-project` package
$ ls my-project
Cargo.toml
src
$ ls my-project/src
main.rs

```
 After we run `cargo new`, we use `ls` to see what Cargo creates. In the project directory, there’s a *Cargo.toml* file, giving us a package. There’s also a *src* directory that contains *main.rs*. Open *Cargo.toml* in your text editor, and note there’s no mention of *src/main.rs*. Cargo follows a convention that *src/main.rs* is the crate root of a binary crate with the same name as the package. Likewise, Cargo knows that if the package directory contains *src/lib.rs*, the package contains a library crate with the same name as the package, and *src/lib.rs* is its crate root. Cargo passes the crate root files to `rustc` to build the library or binary.

 Here, we have a package that only contains *src/main.rs*, meaning it only contains a binary crate named `my-project`. If a package contains *src/main.rs* and *src/lib.rs*, it has two crates: a binary and a library, both with the same name as the package. A package can have multiple binary crates by placing files in the *src/bin* directory: each file will be a separate binary crate.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch07-01-packages-and-crates.html>

Defining Modules to Control Scope and Privacy
=============================================

 In this section, we’ll talk about modules and other parts of the module system, namely *paths* that 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.

 First, we’re going to start with a list of rules for easy reference when you’re organizing your code in the future. Then we’ll explain each of the rules in detail.

 ### Modules Cheat Sheet

 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 or *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!

 ### Grouping Related Code in Modules

 *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. Here’s 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: 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: The module tree for the code in Listing 7-1

 This tree shows how some of the modules nest inside one another; for example, `hosting` nests inside `front_of_house`. The tree also shows that some modules are *siblings* to each other, 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.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch07-02-defining-modules-to-control-scope-and-privacy.html>

Paths for Referring to an Item in the Module Tree
=================================================

 To show Rust where to find an item in a module tree, we use a path in the same way we use a path when navigating a filesystem. To call a function, we need to know its path.

 A path can take two forms:

 * An *absolute path* is the full path starting from a crate root; for code from an external crate, the absolute path begins with the crate name, and for code from the current crate, it starts with the literal `crate`.
* A *relative path* starts from the current module and uses `self`, `super`, or an identifier in the current module.

 Both absolute and relative paths are followed by one or more identifiers separated by double colons (`::`).

 Returning to Listing 7-1, say we want to call the `add_to_waitlist` function. This is the same as asking: what’s the path of the `add_to_waitlist` function? Listing 7-3 contains Listing 7-1 with some of the modules and functions removed.

 We’ll show two ways to call the `add_to_waitlist` function from a new function `eat_at_restaurant` defined in the crate root. These paths are correct, but there’s another problem remaining that will prevent this example from compiling as-is. We’ll explain why in a bit.

 The `eat_at_restaurant` function is part of our library crate’s public API, so we mark it with the `pub` keyword. In the [“Exposing Paths with the `pub` Keyword”](ch07-03-paths-for-referring-to-an-item-in-the-module-tree#exposing-paths-with-the-pub-keyword) section, we’ll go into more detail about `pub`.

 Filename: src/lib.rs

 
```
mod front_of_house {
    mod hosting {
        fn add_to_waitlist() {}
    }
}

pub fn eat_at_restaurant() {
    // Absolute path
    crate::front_of_house::hosting::add_to_waitlist();

    // Relative path
    front_of_house::hosting::add_to_waitlist();
}
```
 Listing 7-3: Calling the `add_to_waitlist` function using absolute and relative paths

 The first time we call the `add_to_waitlist` function in `eat_at_restaurant`, we use an absolute path. The `add_to_waitlist` function is defined in the same crate as `eat_at_restaurant`, which means we can use the `crate` keyword to start an absolute path. We then include each of the successive modules until we make our way to `add_to_waitlist`. You can imagine a filesystem with the same structure: we’d specify the path `/front_of_house/hosting/add_to_waitlist` to run the `add_to_waitlist` program; using the `crate` name to start from the crate root is like using `/` to start from the filesystem root in your shell.

 The second time we call `add_to_waitlist` in `eat_at_restaurant`, we use a relative path. The path starts with `front_of_house`, the name of the module defined at the same level of the module tree as `eat_at_restaurant`. Here the filesystem equivalent would be using the path `front_of_house/hosting/add_to_waitlist`. Starting with a module name means that the path is relative.

 Choosing whether to use a relative or absolute path is a decision you’ll make based on your project, and depends on whether you’re more likely to move item definition code separately from or together with the code that uses the item. For example, if we move the `front_of_house` module and the `eat_at_restaurant` function into a module named `customer_experience`, we’d need to update the absolute path to `add_to_waitlist`, but the relative path would still be valid. However, if we moved the `eat_at_restaurant` function separately into a module named `dining`, the absolute path to the `add_to_waitlist` call would stay the same, but the relative path would need to be updated. Our preference in general is to specify absolute paths because it’s more likely we’ll want to move code definitions and item calls independently of each other.

 Let’s try to compile Listing 7-3 and find out why it won’t compile yet! The error we get is shown in Listing 7-4.

 
```
$ cargo build
   Compiling restaurant v0.1.0 (file:///projects/restaurant)
error[E0603]: module `hosting` is private
 --> src/lib.rs:9:28
  |
9 |     crate::front_of_house::hosting::add_to_waitlist();
  |                            ^^^^^^^ private module
  |
note: the module `hosting` is defined here
 --> src/lib.rs:2:5
  |
2 |     mod hosting {
  |     ^^^^^^^^^^^

error[E0603]: module `hosting` is private
  --> src/lib.rs:12:21
   |
12 |     front_of_house::hosting::add_to_waitlist();
   |                     ^^^^^^^ private module
   |
note: the module `hosting` is defined here
  --> src/lib.rs:2:5
   |
2  |     mod hosting {
   |     ^^^^^^^^^^^

For more information about this error, try `rustc --explain E0603`.
error: could not compile `restaurant` due to 2 previous errors

```
 Listing 7-4: Compiler errors from building the code in Listing 7-3

 The error messages say that module `hosting` is private. In other words, we have the correct paths for the `hosting` module and the `add_to_waitlist` function, but Rust won’t let us use them because it doesn’t have access to the private sections. In Rust, all items (functions, methods, structs, enums, modules, and constants) are private to parent modules by default. If you want to make an item like a function or struct private, you put it in a module.

 Items in a parent module can’t use the private items inside child modules, but items in child modules can use the items in their ancestor modules. This is because child modules wrap and hide their implementation details, but the child modules can see the context in which they’re defined. To continue with our metaphor, think of the privacy rules as being like the back office of a restaurant: what goes on in there is private to restaurant customers, but office managers can see and do everything in the restaurant they operate.

 Rust chose to have the module system function this way so that hiding inner implementation details is the default. That way, you know which parts of the inner code you can change without breaking outer code. However, Rust does give you the option to expose inner parts of child modules’ code to outer ancestor modules by using the `pub` keyword to make an item public.

 ### Exposing Paths with the `pub` Keyword

 Let’s return to the error in Listing 7-4 that told us the `hosting` module is private. We want the `eat_at_restaurant` function in the parent module to have access to the `add_to_waitlist` function in the child module, so we mark the `hosting` module with the `pub` keyword, as shown in Listing 7-5.

 Filename: src/lib.rs

 
```
mod front_of_house {
    pub mod hosting {
        fn add_to_waitlist() {}
    }
}

pub fn eat_at_restaurant() {
    // Absolute path
    crate::front_of_house::hosting::add_to_waitlist();

    // Relative path
    front_of_house::hosting::add_to_waitlist();
}
```
 Listing 7-5: Declaring the `hosting` module as `pub` to use it from `eat_at_restaurant`

 Unfortunately, the code in Listing 7-5 still results in an error, as shown in Listing 7-6.

 
```
$ cargo build
   Compiling restaurant v0.1.0 (file:///projects/restaurant)
error[E0603]: function `add_to_waitlist` is private
 --> src/lib.rs:9:37
  |
9 |     crate::front_of_house::hosting::add_to_waitlist();
  |                                     ^^^^^^^^^^^^^^^ private function
  |
note: the function `add_to_waitlist` is defined here
 --> src/lib.rs:3:9
  |
3 |         fn add_to_waitlist() {}
  |         ^^^^^^^^^^^^^^^^^^^^

error[E0603]: function `add_to_waitlist` is private
  --> src/lib.rs:12:30
   |
12 |     front_of_house::hosting::add_to_waitlist();
   |                              ^^^^^^^^^^^^^^^ private function
   |
note: the function `add_to_waitlist` is defined here
  --> src/lib.rs:3:9
   |
3  |         fn add_to_waitlist() {}
   |         ^^^^^^^^^^^^^^^^^^^^

For more information about this error, try `rustc --explain E0603`.
error: could not compile `restaurant` due to 2 previous errors

```
 Listing 7-6: Compiler errors from building the code in Listing 7-5

 What happened? Adding the `pub` keyword in front of `mod hosting` makes the module public. With this change, if we can access `front_of_house`, we can access `hosting`. But the *contents* of `hosting` are still private; making the module public doesn’t make its contents public. The `pub` keyword on a module only lets code in its ancestor modules refer to it, not access its inner code. Because modules are containers, there’s not much we can do by only making the module public; we need to go further and choose to make one or more of the items within the module public as well.

 The errors in Listing 7-6 say that the `add_to_waitlist` function is private. The privacy rules apply to structs, enums, functions, and methods as well as modules.

 Let’s also make the `add_to_waitlist` function public by adding the `pub` keyword before its definition, as in Listing 7-7.

 Filename: src/lib.rs

 
```
mod front_of_house {
    pub mod hosting {
        pub fn add_to_waitlist() {}
    }
}

pub fn eat_at_restaurant() {
    // Absolute path
    crate::front_of_house::hosting::add_to_waitlist();

    // Relative path
    front_of_house::hosting::add_to_waitlist();
}
```
 Listing 7-7: Adding the `pub` keyword to `mod hosting` and `fn add_to_waitlist` lets us call the function from `eat_at_restaurant`

 Now the code will compile! To see why adding the `pub` keyword lets us use these paths in `add_to_waitlist` with respect to the privacy rules, let’s look at the absolute and the relative paths.

 In the absolute path, we start with `crate`, the root of our crate’s module tree. The `front_of_house` module is defined in the crate root. While `front_of_house` isn’t public, because the `eat_at_restaurant` function is defined in the same module as `front_of_house` (that is, `eat_at_restaurant` and `front_of_house` are siblings), we can refer to `front_of_house` from `eat_at_restaurant`. Next is the `hosting` module marked with `pub`. We can access the parent module of `hosting`, so we can access `hosting`. Finally, the `add_to_waitlist` function is marked with `pub` and we can access its parent module, so this function call works!

 In the relative path, the logic is the same as the absolute path except for the first step: rather than starting from the crate root, the path starts from `front_of_house`. The `front_of_house` module is defined within the same module as `eat_at_restaurant`, so the relative path starting from the module in which `eat_at_restaurant` is defined works. Then, because `hosting` and `add_to_waitlist` are marked with `pub`, the rest of the path works, and this function call is valid!

 If you plan on sharing your library crate so other projects can use your code, your public API is your contract with users of your crate that determines how they can interact with your code. There are many considerations around managing changes to your public API to make it easier for people to depend on your crate. These considerations are out of the scope of this book; if you’re interested in this topic, see [The Rust API Guidelines](https://rust-lang.github.io/api-guidelines/).

 
>  #### Best Practices for Packages with a Binary and a Library
> 
>  We mentioned a package can contain both a *src/main.rs* binary crate root as well as a *src/lib.rs* library crate root, and both crates will have the package name by default. Typically, packages with this pattern of containing both a library and a binary crate will have just enough code in the binary crate to start an executable that calls code with the library crate. This lets other projects benefit from the most functionality that the package provides, because the library crate’s code can be shared.
> 
>  The module tree should be defined in *src/lib.rs*. Then, any public items can be used in the binary crate by starting paths with the name of the package. The binary crate becomes a user of the library crate just like a completely external crate would use the library crate: it can only use the public API. This helps you design a good API; not only are you the author, you’re also a client!
> 
>  In [Chapter 12](ch12-00-an-io-project), we’ll demonstrate this organizational practice with a command-line program that will contain both a binary crate and a library crate.
> 
>  

 ### Starting Relative Paths with `super`

 We can construct relative paths that begin in the parent module, rather than the current module or the crate root, by using `super` at the start of the path. This is like starting a filesystem path with the `..` syntax. Using `super` allows us to reference an item that we know is in the parent module, which can make rearranging the module tree easier when the module is closely related to the parent, but the parent might be moved elsewhere in the module tree someday.

 Consider the code in Listing 7-8 that models the situation in which a chef fixes an incorrect order and personally brings it out to the customer. The function `fix_incorrect_order` defined in the `back_of_house` module calls the function `deliver_order` defined in the parent module by specifying the path to `deliver_order` starting with `super`:

 Filename: src/lib.rs

 
```
fn deliver_order() {}

mod back_of_house {
    fn fix_incorrect_order() {
        cook_order();
        super::deliver_order();
    }

    fn cook_order() {}
}
```
 Listing 7-8: Calling a function using a relative path starting with `super`

 The `fix_incorrect_order` function is in the `back_of_house` module, so we can use `super` to go to the parent module of `back_of_house`, which in this case is `crate`, the root. From there, we look for `deliver_order` and find it. Success! We think the `back_of_house` module and the `deliver_order` function are likely to stay in the same relationship to each other and get moved together should we decide to reorganize the crate’s module tree. Therefore, we used `super` so we’ll have fewer places to update code in the future if this code gets moved to a different module.

 ### Making Structs and Enums Public

 We can also use `pub` to designate structs and enums as public, but there are a few details extra to the usage of `pub` with structs and enums. If we use `pub` before a struct definition, we make the struct public, but the struct’s fields will still be private. We can make each field public or not on a case-by-case basis. In Listing 7-9, we’ve defined a public `back_of_house::Breakfast` struct with a public `toast` field but a private `seasonal_fruit` field. This models the case in a restaurant where the customer can pick the type of bread that comes with a meal, but the chef decides which fruit accompanies the meal based on what’s in season and in stock. The available fruit changes quickly, so customers can’t choose the fruit or even see which fruit they’ll get.

 Filename: src/lib.rs

 
```
mod back_of_house {
    pub struct Breakfast {
        pub toast: String,
        seasonal_fruit: String,
    }

    impl Breakfast {
        pub fn summer(toast: &str) -> Breakfast {
            Breakfast {
                toast: String::from(toast),
                seasonal_fruit: String::from("peaches"),
            }
        }
    }
}

pub fn eat_at_restaurant() {
    // Order a breakfast in the summer with Rye toast
    let mut meal = back_of_house::Breakfast::summer("Rye");
    // Change our mind about what bread we'd like
    meal.toast = String::from("Wheat");
    println!("I'd like {} toast please", meal.toast);

    // The next line won't compile if we uncomment it; we're not allowed
    // to see or modify the seasonal fruit that comes with the meal
    // meal.seasonal_fruit = String::from("blueberries");
}
```
 Listing 7-9: A struct with some public fields and some private fields

 Because the `toast` field in the `back_of_house::Breakfast` struct is public, in `eat_at_restaurant` we can write and read to the `toast` field using dot notation. Notice that we can’t use the `seasonal_fruit` field in `eat_at_restaurant` because `seasonal_fruit` is private. Try uncommenting the line modifying the `seasonal_fruit` field value to see what error you get!

 Also, note that because `back_of_house::Breakfast` has a private field, the struct needs to provide a public associated function that constructs an instance of `Breakfast` (we’ve named it `summer` here). If `Breakfast` didn’t have such a function, we couldn’t create an instance of `Breakfast` in `eat_at_restaurant` because we couldn’t set the value of the private `seasonal_fruit` field in `eat_at_restaurant`.

 In contrast, if we make an enum public, all of its variants are then public. We only need the `pub` before the `enum` keyword, as shown in Listing 7-10.

 Filename: src/lib.rs

 
```
mod back_of_house {
    pub enum Appetizer {
        Soup,
        Salad,
    }
}

pub fn eat_at_restaurant() {
    let order1 = back_of_house::Appetizer::Soup;
    let order2 = back_of_house::Appetizer::Salad;
}
```
 Listing 7-10: Designating an enum as public makes all its variants public

 Because we made the `Appetizer` enum public, we can use the `Soup` and `Salad` variants in `eat_at_restaurant`.

 Enums aren’t very useful unless their variants are public; it would be annoying to have to annotate all enum variants with `pub` in every case, so the default for enum variants is to be public. Structs are often useful without their fields being public, so struct fields follow the general rule of everything being private by default unless annotated with `pub`.

 There’s one more situation involving `pub` that we haven’t covered, and that is our last module system feature: the `use` keyword. We’ll cover `use` by itself first, and then we’ll show how to combine `pub` and `use`.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html>

Bringing Paths into Scope with the `use` Keyword
================================================

 Having to write out the paths to call functions can feel inconvenient and repetitive. In Listing 7-7, whether we chose the absolute or relative path to the `add_to_waitlist` function, every time we wanted to call `add_to_waitlist` we had to specify `front_of_house` and `hosting` too. Fortunately, there’s a way to simplify this process: we can create a shortcut to a path with the `use` keyword once, and then use the shorter name everywhere else in the scope.

 In Listing 7-11, we bring the `crate::front_of_house::hosting` module into the scope of the `eat_at_restaurant` function so we only have to specify `hosting::add_to_waitlist` to call the `add_to_waitlist` function in `eat_at_restaurant`.

 Filename: src/lib.rs

 
```
mod front_of_house {
    pub mod hosting {
        pub fn add_to_waitlist() {}
    }
}

use crate::front_of_house::hosting;

pub fn eat_at_restaurant() {
    hosting::add_to_waitlist();
}
```
 Listing 7-11: Bringing a module into scope with `use`

 Adding `use` and a path in a scope is similar to creating a symbolic link in the filesystem. By adding `use crate::front_of_house::hosting` in the crate root, `hosting` is now a valid name in that scope, just as though the `hosting` module had been defined in the crate root. Paths brought into scope with `use` also check privacy, like any other paths.

 Note that `use` only creates the shortcut for the particular scope in which the `use` occurs. Listing 7-12 moves the `eat_at_restaurant` function into a new child module named `customer`, which is then a different scope than the `use` statement, so the function body won’t compile:

 Filename: src/lib.rs

 
```
mod front_of_house {
    pub mod hosting {
        pub fn add_to_waitlist() {}
    }
}

use crate::front_of_house::hosting;

mod customer {
    pub fn eat_at_restaurant() {
        hosting::add_to_waitlist();
    }
}
```
 Listing 7-12: A `use` statement only applies in the scope it’s in

 The compiler error shows that the shortcut no longer applies within the `customer` module:

 
```
$ cargo build
   Compiling restaurant v0.1.0 (file:///projects/restaurant)
warning: unused import: `crate::front_of_house::hosting`
 --> src/lib.rs:7:5
  |
7 | use crate::front_of_house::hosting;
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

error[E0433]: failed to resolve: use of undeclared crate or module `hosting`
  --> src/lib.rs:11:9
   |
11 |         hosting::add_to_waitlist();
   |         ^^^^^^^ use of undeclared crate or module `hosting`

For more information about this error, try `rustc --explain E0433`.
warning: `restaurant` (lib) generated 1 warning
error: could not compile `restaurant` due to previous error; 1 warning emitted

```
 Notice there’s also a warning that the `use` is no longer used in its scope! To fix this problem, move the `use` within the `customer` module too, or reference the shortcut in the parent module with `super::hosting` within the child `customer` module.

 ### Creating Idiomatic `use` Paths

 In Listing 7-11, you might have wondered why we specified `use crate::front_of_house::hosting` and then called `hosting::add_to_waitlist` in `eat_at_restaurant` rather than specifying the `use` path all the way out to the `add_to_waitlist` function to achieve the same result, as in Listing 7-13.

 Filename: src/lib.rs

 
```
mod front_of_house {
    pub mod hosting {
        pub fn add_to_waitlist() {}
    }
}

use crate::front_of_house::hosting::add_to_waitlist;

pub fn eat_at_restaurant() {
    add_to_waitlist();
}
```
 Listing 7-13: Bringing the `add_to_waitlist` function into scope with `use`, which is unidiomatic

 Although both Listing 7-11 and 7-13 accomplish the same task, Listing 7-11 is the idiomatic way to bring a function into scope with `use`. Bringing the function’s parent module into scope with `use` means we have to specify the parent module when calling the function. Specifying the parent module when calling the function makes it clear that the function isn’t locally defined while still minimizing repetition of the full path. The code in Listing 7-13 is unclear as to where `add_to_waitlist` is defined.

 On the other hand, when bringing in structs, enums, and other items with `use`, it’s idiomatic to specify the full path. Listing 7-14 shows the idiomatic way to bring the standard library’s `HashMap` struct into the scope of a binary crate.

 Filename: src/main.rs

 
```
use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();
    map.insert(1, 2);
}
```
 Listing 7-14: Bringing `HashMap` into scope in an idiomatic way

 There’s no strong reason behind this idiom: it’s just the convention that has emerged, and folks have gotten used to reading and writing Rust code this way.

 The exception to this idiom is if we’re bringing two items with the same name into scope with `use` statements, because Rust doesn’t allow that. Listing 7-15 shows how to bring two `Result` types into scope that have the same name but different parent modules and how to refer to them.

 Filename: src/lib.rs

 
```
use std::fmt;
use std::io;

fn function1() -> fmt::Result {
    // --snip--
    Ok(())
}

fn function2() -> io::Result<()> {
    // --snip--
    Ok(())
}
```
 Listing 7-15: Bringing two types with the same name into the same scope requires using their parent modules.

 As you can see, using the parent modules distinguishes the two `Result` types. If instead we specified `use std::fmt::Result` and `use std::io::Result`, we’d have two `Result` types in the same scope and Rust wouldn’t know which one we meant when we used `Result`.

 ### Providing New Names with the `as` Keyword

 There’s another solution to the problem of bringing two types of the same name into the same scope with `use`: after the path, we can specify `as` and a new local name, or *alias*, for the type. Listing 7-16 shows another way to write the code in Listing 7-15 by renaming one of the two `Result` types using `as`.

 Filename: src/lib.rs

 
```
use std::fmt::Result;
use std::io::Result as IoResult;

fn function1() -> Result {
    // --snip--
    Ok(())
}

fn function2() -> IoResult<()> {
    // --snip--
    Ok(())
}
```
 Listing 7-16: Renaming a type when it’s brought into scope with the `as` keyword

 In the second `use` statement, we chose the new name `IoResult` for the `std::io::Result` type, which won’t conflict with the `Result` from `std::fmt` that we’ve also brought into scope. Listing 7-15 and Listing 7-16 are considered idiomatic, so the choice is up to you!

 ### Re-exporting Names with `pub use`

 When we bring a name into scope with the `use` keyword, the name available in the new scope is private. To enable the code that calls our code to refer to that name as if it had been defined in that code’s scope, we can combine `pub` and `use`. This technique is called *re-exporting* because we’re bringing an item into scope but also making that item available for others to bring into their scope.

 Listing 7-17 shows the code in Listing 7-11 with `use` in the root module changed to `pub use`.

 Filename: src/lib.rs

 
```
mod front_of_house {
    pub mod hosting {
        pub fn add_to_waitlist() {}
    }
}

pub use crate::front_of_house::hosting;

pub fn eat_at_restaurant() {
    hosting::add_to_waitlist();
}
```
 Listing 7-17: Making a name available for any code to use from a new scope with `pub use`

 Before this change, external code would have to call the `add_to_waitlist` function by using the path `restaurant::front_of_house::hosting::add_to_waitlist()`. Now that this `pub use` has re-exported the `hosting` module from the root module, external code can now use the path `restaurant::hosting::add_to_waitlist()` instead.

 Re-exporting is useful when the internal structure of your code is different from how programmers calling your code would think about the domain. For example, in this restaurant metaphor, the people running the restaurant think about “front of house” and “back of house.” But customers visiting a restaurant probably won’t think about the parts of the restaurant in those terms. With `pub use`, we can write our code with one structure but expose a different structure. Doing so makes our library well organized for programmers working on the library and programmers calling the library. We’ll look at another example of `pub use` and how it affects your crate’s documentation in the [“Exporting a Convenient Public API with `pub use`”](ch14-02-publishing-to-crates-io#exporting-a-convenient-public-api-with-pub-use) section of Chapter 14.

 ### Using External Packages

 In Chapter 2, we programmed a guessing game project that used an external package called `rand` to get random numbers. To use `rand` in our project, we added this line to *Cargo.toml*:

 Filename: Cargo.toml

 
```
rand = "0.8.5"

```
 Adding `rand` as a dependency in *Cargo.toml* tells Cargo to download the `rand` package and any dependencies from [crates.io](https://crates.io/) and make `rand` available to our project.

 Then, to bring `rand` definitions into the scope of our package, we added a `use` line starting with the name of the crate, `rand`, and listed the items we wanted to bring into scope. Recall that in the [“Generating a Random Number”](ch02-00-guessing-game-tutorial#generating-a-random-number) section in Chapter 2, we brought the `Rng` trait into scope and called the `rand::thread_rng` function:

 
```
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}");
}
```
 Members of the Rust community have made many packages available at [crates.io](https://crates.io/), and pulling any of them into your package involves these same steps: listing them in your package’s *Cargo.toml* file and using `use` to bring items from their crates into scope.

 Note that the standard `std` library is also a crate that’s external to our package. Because the standard library is shipped with the Rust language, we don’t need to change *Cargo.toml* to include `std`. But we do need to refer to it with `use` to bring items from there into our package’s scope. For example, with `HashMap` we would use this line:

 
```
#![allow(unused)]
fn main() {
use std::collections::HashMap;
}
```
 This is an absolute path starting with `std`, the name of the standard library crate.

 ### Using Nested Paths to Clean Up Large `use` Lists

 If we’re using multiple items defined in the same crate or same module, listing each item on its own line can take up a lot of vertical space in our files. For example, these two `use` statements we had in the Guessing Game in Listing 2-4 bring items from `std` into scope:

 Filename: src/main.rs

 
```
use rand::Rng;
// --snip--
use std::cmp::Ordering;
use std::io;
// --snip--

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}");

    match guess.cmp(&secret_number) {
        Ordering::Less => println!("Too small!"),
        Ordering::Greater => println!("Too big!"),
        Ordering::Equal => println!("You win!"),
    }
}
```
 Instead, we can use nested paths to bring the same items into scope in one line. We do this by specifying the common part of the path, followed by two colons, and then curly brackets around a list of the parts of the paths that differ, as shown in Listing 7-18.

 Filename: src/main.rs

 
```
use rand::Rng;
// --snip--
use std::{cmp::Ordering, io};
// --snip--

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");

    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!"),
    }
}
```
 Listing 7-18: Specifying a nested path to bring multiple items with the same prefix into scope

 In bigger programs, bringing many items into scope from the same crate or module using nested paths can reduce the number of separate `use` statements needed by a lot!

 We can use a nested path at any level in a path, which is useful when combining two `use` statements that share a subpath. For example, Listing 7-19 shows two `use` statements: one that brings `std::io` into scope and one that brings `std::io::Write` into scope.

 Filename: src/lib.rs

 
```
use std::io;
use std::io::Write;
```
 Listing 7-19: Two `use` statements where one is a subpath of the other

 The common part of these two paths is `std::io`, and that’s the complete first path. To merge these two paths into one `use` statement, we can use `self` in the nested path, as shown in Listing 7-20.

 Filename: src/lib.rs

 
```
use std::io::{self, Write};
```
 Listing 7-20: Combining the paths in Listing 7-19 into one `use` statement

 This line brings `std::io` and `std::io::Write` into scope.

 ### The Glob Operator

 If we want to bring *all* public items defined in a path into scope, we can specify that path followed by the `*` glob operator:

 
```
#![allow(unused)]
fn main() {
use std::collections::*;
}
```
 This `use` statement brings all public items defined in `std::collections` into the current scope. Be careful when using the glob operator! Glob can make it harder to tell what names are in scope and where a name used in your program was defined.

 The glob operator is often used when testing to bring everything under test into the `tests` module; we’ll talk about that in the [“How to Write Tests”](ch11-01-writing-tests#how-to-write-tests) section in Chapter 11. The glob operator is also sometimes used as part of the prelude pattern: see [the standard library documentation](../std/prelude/index#other-preludes) for more information on that pattern.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.html>

Separating Modules into Different Files
=======================================

 So far, all the examples in this chapter defined multiple modules in one file. When modules get large, you might want to move their definitions to a separate file to make the code easier to navigate.

 For example, let’s start from the code in Listing 7-17 that had multiple restaurant modules. We’ll extract modules into files instead of having all the modules defined in the crate root file. In this case, the crate root file is *src/lib.rs*, but this procedure also works with binary crates whose crate root file is *src/main.rs*.

 First, we’ll extract the `front_of_house` module to its own file. Remove the code inside the curly brackets for the `front_of_house` module, leaving only the `mod front_of_house;` declaration, so that *src/lib.rs* contains the code shown in Listing 7-21. Note that this won’t compile until we create the *src/front\_of\_house.rs* file in Listing 7-22.

 Filename: src/lib.rs

 
```
mod front_of_house;

pub use crate::front_of_house::hosting;

pub fn eat_at_restaurant() {
    hosting::add_to_waitlist();
}
```
 Listing 7-21: Declaring the `front_of_house` module whose body will be in *src/front\_of\_house.rs*

 Next, place the code that was in the curly brackets into a new file named *src/front\_of\_house.rs*, as shown in Listing 7-22. The compiler knows to look in this file because it came across the module declaration in the crate root with the name `front_of_house`.

 Filename: src/front\_of\_house.rs

 
```
pub mod hosting {
    pub fn add_to_waitlist() {}
}
```
 Listing 7-22: Definitions inside the `front_of_house` module in *src/front\_of\_house.rs*

 Note that you only need to load a file using a `mod` declaration *once* in your module tree. Once the compiler knows the file is part of the project (and knows where in the module tree the code resides because of where you’ve put the `mod` statement), other files in your project should refer to the loaded file’s code using a path to where it was declared, as covered in the [“Paths for Referring to an Item in the Module Tree”](ch07-03-paths-for-referring-to-an-item-in-the-module-tree) section. In other words, `mod` is *not* an “include” operation that you may have seen in other programming languages.

 Next, we’ll extract the `hosting` module to its own file. The process is a bit different because `hosting` is a child module of `front_of_house`, not of the root module. We’ll place the file for `hosting` in a new directory that will be named for its ancestors in the module tree, in this case *src/front\_of\_house/*.

 To start moving `hosting`, we change *src/front\_of\_house.rs* to contain only the declaration of the `hosting` module:

 Filename: src/front\_of\_house.rs

 
```
pub mod hosting;
```
 Then we create a *src/front\_of\_house* directory and a file *hosting.rs* to contain the definitions made in the `hosting` module:

 Filename: src/front\_of\_house/hosting.rs

 
```
pub fn add_to_waitlist() {}
```
 If we instead put *hosting.rs* in the *src* directory, the compiler would expect the *hosting.rs* code to be in a `hosting` module declared in the crate root, and not declared as a child of the `front_of_house` module. The compiler’s rules for which files to check for which modules’ code means the directories and files more closely match the module tree.

 
>  ### Alternate File Paths
> 
>  So far we’ve covered the most idiomatic file paths the Rust compiler uses, but Rust also supports an older style of file path. For a module named `front_of_house` declared in the crate root, the compiler will look for the module’s code in:
> 
>  * *src/front\_of\_house.rs* (what we covered)
> * *src/front\_of\_house/mod.rs* (older style, still supported path)
> 
>  For a module named `hosting` that is a submodule of `front_of_house`, the compiler will look for the module’s code in:
> 
>  * *src/front\_of\_house/hosting.rs* (what we covered)
> * *src/front\_of\_house/hosting/mod.rs* (older style, still supported path)
> 
>  If you use both styles for the same module, you’ll get a compiler error. Using a mix of both styles for different modules in the same project is allowed, but might be confusing for people navigating your project.
> 
>  The main downside to the style that uses files named *mod.rs* is that your project can end up with many files named *mod.rs*, which can get confusing when you have them open in your editor at the same time.
> 
>  

 We’ve moved each module’s code to a separate file, and the module tree remains the same. The function calls in `eat_at_restaurant` will work without any modification, even though the definitions live in different files. This technique lets you move modules to new files as they grow in size.

 Note that the `pub use crate::front_of_house::hosting` statement in *src/lib.rs* also hasn’t changed, nor does `use` have any impact on what files are compiled as part of the crate. The `mod` keyword declares modules, and Rust looks in a file with the same name as the module for the code that goes into that module.

 Summary
-------

 Rust lets you split a package into multiple crates and a crate into modules so you can refer to items defined in one module from another module. You can do this by specifying absolute or relative paths. These paths can be brought into scope with a `use` statement so you can use a shorter path for multiple uses of the item in that scope. Module code is private by default, but you can make definitions public by adding the `pub` keyword.

 In the next chapter, we’ll look at some collection data structures in the standard library that you can use in your neatly organized code.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch07-05-separating-modules-into-different-files.html>

Common Collections
==================

 Rust’s standard library includes a number of very useful data structures called *collections*. Most other data types represent one specific value, but collections can contain multiple values. Unlike the built-in array and tuple types, the data these collections point to is stored on the heap, which means the amount of data does not need to be known at compile time and can grow or shrink as the program runs. Each kind of collection has different capabilities and costs, and choosing an appropriate one for your current situation is a skill you’ll develop over time. In this chapter, we’ll discuss three collections that are used very often in Rust programs:

 * A *vector* allows you to store a variable number of values next to each other.
* A *string* is a collection of characters. We’ve mentioned the `String` type previously, but in this chapter we’ll talk about it in depth.
* A *hash map* allows you to associate a value with a particular key. It’s a particular implementation of the more general data structure called a *map*.

 To learn about the other kinds of collections provided by the standard library, see [the documentation](../std/collections/index).

 We’ll discuss how to create and update vectors, strings, and hash maps, as well as what makes each special.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch08-00-common-collections.html>

Storing Lists of Values with Vectors
====================================

 The first collection type we’ll look at is `Vec<T>`, also known as a *vector*. Vectors allow you to store more than one value in a single data structure that puts all the values next to each other in memory. Vectors can only store values of the same type. They are useful when you have a list of items, such as the lines of text in a file or the prices of items in a shopping cart.

 ### Creating a New Vector

 To create a new empty vector, we call the `Vec::new` function, as shown in Listing 8-1.

 
```
fn main() {
    let v: Vec<i32> = Vec::new();
}
```
 Listing 8-1: Creating a new, empty vector to hold values of type `i32`

 Note that we added a type annotation here. Because we aren’t inserting any values into this vector, Rust doesn’t know what kind of elements we intend to store. This is an important point. Vectors are implemented using generics; we’ll cover how to use generics with your own types in Chapter 10. For now, know that the `Vec<T>` type provided by the standard library can hold any type. When we create a vector to hold a specific type, we can specify the type within angle brackets. In Listing 8-1, we’ve told Rust that the `Vec<T>` in `v` will hold elements of the `i32` type.

 More often, you’ll create a `Vec<T>` with initial values and Rust will infer the type of value you want to store, so you rarely need to do this type annotation. Rust conveniently provides the `vec!` macro, which will create a new vector that holds the values you give it. Listing 8-2 creates a new `Vec<i32>` that holds the values `1`, `2`, and `3`. The integer type is `i32` because that’s the default integer type, as we discussed in the [“Data Types”](ch03-02-data-types#data-types) section of Chapter 3.

 
```
fn main() {
    let v = vec![1, 2, 3];
}
```
 Listing 8-2: Creating a new vector containing values

 Because we’ve given initial `i32` values, Rust can infer that the type of `v` is `Vec<i32>`, and the type annotation isn’t necessary. Next, we’ll look at how to modify a vector.

 ### Updating a Vector

 To create a vector and then add elements to it, we can use the `push` method, as shown in Listing 8-3.

 
```
fn main() {
    let mut v = Vec::new();

    v.push(5);
    v.push(6);
    v.push(7);
    v.push(8);
}
```
 Listing 8-3: Using the `push` method to add values to a vector

 As with any variable, if we want to be able to change its value, we need to make it mutable using the `mut` keyword, as discussed in Chapter 3. The numbers we place inside are all of type `i32`, and Rust infers this from the data, so we don’t need the `Vec<i32>` annotation.

 ### Reading Elements of Vectors

 There are two ways to reference a value stored in a vector: via indexing or using the `get` method. In the following examples, we’ve annotated the types of the values that are returned from these functions for extra clarity.

 Listing 8-4 shows both methods of accessing a value in a vector, with indexing syntax and the `get` method.

 
```
fn main() {
    let v = vec![1, 2, 3, 4, 5];

    let third: &i32 = &v[2];
    println!("The third element is {third}");

    let third: Option<&i32> = v.get(2);
    match third {
        Some(third) => println!("The third element is {third}"),
        None => println!("There is no third element."),
    }
}
```
 Listing 8-4: Using indexing syntax or the `get` method to access an item in a vector

 Note a few details here. We use the index value of `2` to get the third element because vectors are indexed by number, starting at zero. Using `&` and `[]` gives us a reference to the element at the index value. When we use the `get` method with the index passed as an argument, we get an `Option<&T>` that we can use with `match`.

 The reason Rust provides these two ways to reference an element is so you can choose how the program behaves when you try to use an index value outside the range of existing elements. As an example, let’s see what happens when we have a vector of five elements and then we try to access an element at index 100 with each technique, as shown in Listing 8-5.

 
```
fn main() {
    let v = vec![1, 2, 3, 4, 5];

    let does_not_exist = &v[100];
    let does_not_exist = v.get(100);
}
```
 Listing 8-5: Attempting to access the element at index 100 in a vector containing five elements

 When we run this code, the first `[]` method will cause the program to panic because it references a nonexistent element. This method is best used when you want your program to crash if there’s an attempt to access an element past the end of the vector.

 When the `get` method is passed an index that is outside the vector, it returns `None` without panicking. You would use this method if accessing an element beyond the range of the vector may happen occasionally under normal circumstances. Your code will then have logic to handle having either `Some(&element)` or `None`, as discussed in Chapter 6. For example, the index could be coming from a person entering a number. If they accidentally enter a number that’s too large and the program gets a `None` value, you could tell the user how many items are in the current vector and give them another chance to enter a valid value. That would be more user-friendly than crashing the program due to a typo!

 When the program has a valid reference, the borrow checker enforces the ownership and borrowing rules (covered in Chapter 4) to ensure this reference and any other references to the contents of the vector remain valid. Recall the rule that states you can’t have mutable and immutable references in the same scope. That rule applies in Listing 8-6, where we hold an immutable reference to the first element in a vector and try to add an element to the end. This program won’t work if we also try to refer to that element later in the function:

 
```
fn main() {
    let mut v = vec![1, 2, 3, 4, 5];

    let first = &v[0];

    v.push(6);

    println!("The first element is: {first}");
}
```
 Listing 8-6: Attempting to add an element to a vector while holding a reference to an item

 Compiling this code will result in this error:

 
```
$ cargo run
   Compiling collections v0.1.0 (file:///projects/collections)
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
 --> src/main.rs:6:5
  |
4 |     let first = &v[0];
  |                  - immutable borrow occurs here
5 |
6 |     v.push(6);
  |     ^^^^^^^^^ mutable borrow occurs here
7 |
8 |     println!("The first element is: {first}");
  |                                      ----- immutable borrow later used here

For more information about this error, try `rustc --explain E0502`.
error: could not compile `collections` due to previous error

```
 The code in Listing 8-6 might look like it should work: why should a reference to the first element care about changes at the end of the vector? This error is due to the way vectors work: because vectors put the values next to each other in memory, adding a new element onto the end of the vector might require allocating new memory and copying the old elements to the new space, if there isn’t enough room to put all the elements next to each other where the vector is currently stored. In that case, the reference to the first element would be pointing to deallocated memory. The borrowing rules prevent programs from ending up in that situation.

 
>  Note: For more on the implementation details of the `Vec<T>` type, see [“The Rustonomicon”](https://doc.rust-lang.org/nomicon/vec/vec.html).
> 
>  

 ### Iterating over the Values in a Vector

 To access each element in a vector in turn, we would iterate through all of the elements rather than use indices to access one at a time. Listing 8-7 shows how to use a `for` loop to get immutable references to each element in a vector of `i32` values and print them.

 
```
fn main() {
    let v = vec![100, 32, 57];
    for i in &v {
        println!("{i}");
    }
}
```
 Listing 8-7: Printing each element in a vector by iterating over the elements using a `for` loop

 We can also iterate over mutable references to each element in a mutable vector in order to make changes to all the elements. The `for` loop in Listing 8-8 will add `50` to each element.

 
```
fn main() {
    let mut v = vec![100, 32, 57];
    for i in &mut v {
        *i += 50;
    }
}
```
 Listing 8-8: Iterating over mutable references to elements in a vector

 To change the value that the mutable reference refers to, we have to use the `*` dereference operator to get to the value in `i` before we can use the `+=` operator. We’ll talk more about the dereference operator in the [“Following the Pointer to the Value with the Dereference Operator”](ch15-02-deref#following-the-pointer-to-the-value-with-the-dereference-operator) section of Chapter 15.

 Iterating over a vector, whether immutably or mutably, is safe because of the borrow checker's rules. If we attempted to insert or remove items in the `for` loop bodies in Listing 8-7 and Listing 8-8, we would get a compiler error similar to the one we got with the code in Listing 8-6. The reference to the vector that the `for` loop holds prevents simultaneous modification of the whole vector.

 ### Using an Enum to Store Multiple Types

 Vectors can only store values that are the same type. This can be inconvenient; there are definitely use cases for needing to store a list of items of different types. Fortunately, the variants of an enum are defined under the same enum type, so when we need one type to represent elements of different types, we can define and use an enum!

 For example, say we want to get values from a row in a spreadsheet in which some of the columns in the row contain integers, some floating-point numbers, and some strings. We can define an enum whose variants will hold the different value types, and all the enum variants will be considered the same type: that of the enum. Then we can create a vector to hold that enum and so, ultimately, holds different types. We’ve demonstrated this in Listing 8-9.

 
```
fn main() {
    enum SpreadsheetCell {
        Int(i32),
        Float(f64),
        Text(String),
    }

    let row = vec![
        SpreadsheetCell::Int(3),
        SpreadsheetCell::Text(String::from("blue")),
        SpreadsheetCell::Float(10.12),
    ];
}
```
 Listing 8-9: Defining an `enum` to store values of different types in one vector

 Rust needs to know what types will be in the vector at compile time so it knows exactly how much memory on the heap will be needed to store each element. We must also be explicit about what types are allowed in this vector. If Rust allowed a vector to hold any type, there would be a chance that one or more of the types would cause errors with the operations performed on the elements of the vector. Using an enum plus a `match` expression means that Rust will ensure at compile time that every possible case is handled, as discussed in Chapter 6.

 If you don’t know the exhaustive set of types a program will get at runtime to store in a vector, the enum technique won’t work. Instead, you can use a trait object, which we’ll cover in Chapter 17.

 Now that we’ve discussed some of the most common ways to use vectors, be sure to review [the API documentation](../std/vec/struct.vec) for all the many useful methods defined on `Vec<T>` by the standard library. For example, in addition to `push`, a `pop` method removes and returns the last element.

 ### Dropping a Vector Drops Its Elements

 Like any other `struct`, a vector is freed when it goes out of scope, as annotated in Listing 8-10.

 
```
fn main() {
    {
        let v = vec![1, 2, 3, 4];

        // do stuff with v
    } // <- v goes out of scope and is freed here
}
```
 Listing 8-10: Showing where the vector and its elements are dropped

 When the vector gets dropped, all of its contents are also dropped, meaning the integers it holds will be cleaned up. The borrow checker ensures that any references to contents of a vector are only used while the vector itself is valid.

 Let’s move on to the next collection type: `String`!



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch08-01-vectors.html>

Storing UTF-8 Encoded Text with Strings
=======================================

 We talked about strings in Chapter 4, but we’ll look at them in more depth now. New Rustaceans commonly get stuck on strings for a combination of three reasons: Rust’s propensity for exposing possible errors, strings being a more complicated data structure than many programmers give them credit for, and UTF-8. These factors combine in a way that can seem difficult when you’re coming from other programming languages.

 We discuss strings in the context of collections because strings are implemented as a collection of bytes, plus some methods to provide useful functionality when those bytes are interpreted as text. In this section, we’ll talk about the operations on `String` that every collection type has, such as creating, updating, and reading. We’ll also discuss the ways in which `String` is different from the other collections, namely how indexing into a `String` is complicated by the differences between how people and computers interpret `String` data.

 ### What Is a String?

 We’ll first define what we mean by the term *string*. Rust has only one string type in the core language, which is the string slice `str` that is usually seen in its borrowed form `&str`. In Chapter 4, we talked about *string slices*, which are references to some UTF-8 encoded string data stored elsewhere. String literals, for example, are stored in the program’s binary and are therefore string slices.

 The `String` type, which is provided by Rust’s standard library rather than coded into the core language, is a growable, mutable, owned, UTF-8 encoded string type. When Rustaceans refer to “strings” in Rust, they might be referring to either the `String` or the string slice `&str` types, not just one of those types. Although this section is largely about `String`, both types are used heavily in Rust’s standard library, and both `String` and string slices are UTF-8 encoded.

 ### Creating a New String

 Many of the same operations available with `Vec<T>` are available with `String` as well, because `String` is actually implemented as a wrapper around a vector of bytes with some extra guarantees, restrictions, and capabilities. An example of a function that works the same way with `Vec<T>` and `String` is the `new` function to create an instance, shown in Listing 8-11.

 
```
fn main() {
    let mut s = String::new();
}
```
 Listing 8-11: Creating a new, empty `String`

 This line creates a new empty string called `s`, which we can then load data into. Often, we’ll have some initial data that we want to start the string with. For that, we use the `to_string` method, which is available on any type that implements the `Display` trait, as string literals do. Listing 8-12 shows two examples.

 
```
fn main() {
    let data = "initial contents";

    let s = data.to_string();

    // the method also works on a literal directly:
    let s = "initial contents".to_string();
}
```
 Listing 8-12: Using the `to_string` method to create a `String` from a string literal

 This code creates a string containing `initial contents`.

 We can also use the function `String::from` to create a `String` from a string literal. The code in Listing 8-13 is equivalent to the code from Listing 8-12 that uses `to_string`.

 
```
fn main() {
    let s = String::from("initial contents");
}
```
 Listing 8-13: Using the `String::from` function to create a `String` from a string literal

 Because strings are used for so many things, we can use many different generic APIs for strings, providing us with a lot of options. Some of them can seem redundant, but they all have their place! In this case, `String::from` and `to_string` do the same thing, so which you choose is a matter of style and readability.

 Remember that strings are UTF-8 encoded, so we can include any properly encoded data in them, as shown in Listing 8-14.

 
```
fn main() {
    let hello = String::from("السلام عليكم");
    let hello = String::from("Dobrý den");
    let hello = String::from("Hello");
    let hello = String::from("שָׁלוֹם");
    let hello = String::from("नमस्ते");
    let hello = String::from("こんにちは");
    let hello = String::from("안녕하세요");
    let hello = String::from("你好");
    let hello = String::from("Olá");
    let hello = String::from("Здравствуйте");
    let hello = String::from("Hola");
}
```
 Listing 8-14: Storing greetings in different languages in strings

 All of these are valid `String` values.

 ### Updating a String

 A `String` can grow in size and its contents can change, just like the contents of a `Vec<T>`, if you push more data into it. In addition, you can conveniently use the `+` operator or the `format!` macro to concatenate `String` values.

 #### Appending to a String with `push_str` and `push`

 We can grow a `String` by using the `push_str` method to append a string slice, as shown in Listing 8-15.

 
```
fn main() {
    let mut s = String::from("foo");
    s.push_str("bar");
}
```
 Listing 8-15: Appending a string slice to a `String` using the `push_str` method

 After these two lines, `s` will contain `foobar`. The `push_str` method takes a string slice because we don’t necessarily want to take ownership of the parameter. For example, in the code in Listing 8-16, we want to be able to use `s2` after appending its contents to `s1`.

 
```
fn main() {
    let mut s1 = String::from("foo");
    let s2 = "bar";
    s1.push_str(s2);
    println!("s2 is {s2}");
}
```
 Listing 8-16: Using a string slice after appending its contents to a `String`

 If the `push_str` method took ownership of `s2`, we wouldn’t be able to print its value on the last line. However, this code works as we’d expect!

 The `push` method takes a single character as a parameter and adds it to the `String`. Listing 8-17 adds the letter “l” to a `String` using the `push` method.

 
```
fn main() {
    let mut s = String::from("lo");
    s.push('l');
}
```
 Listing 8-17: Adding one character to a `String` value using `push`

 As a result, `s` will contain `lol`.

 #### Concatenation with the `+` Operator or the `format!` Macro

 Often, you’ll want to combine two existing strings. One way to do so is to use the `+` operator, as shown in Listing 8-18.

 
```
fn main() {
    let s1 = String::from("Hello, ");
    let s2 = String::from("world!");
    let s3 = s1 + &s2; // note s1 has been moved here and can no longer be used
}
```
 Listing 8-18: Using the `+` operator to combine two `String` values into a new `String` value

 The string `s3` will contain `Hello, world!`. The reason `s1` is no longer valid after the addition, and the reason we used a reference to `s2`, has to do with the signature of the method that’s called when we use the `+` operator. The `+` operator uses the `add` method, whose signature looks something like this:

 
```
fn add(self, s: &str) -> String {
```
 In the standard library, you'll see `add` defined using generics and associated types. Here, we’ve substituted in concrete types, which is what happens when we call this method with `String` values. We’ll discuss generics in Chapter 10. This signature gives us the clues we need to understand the tricky bits of the `+` operator.

 First, `s2` has an `&`, meaning that we’re adding a *reference* of the second string to the first string. This is because of the `s` parameter in the `add` function: we can only add a `&str` to a `String`; we can’t add two `String` values together. But wait—the type of `&s2` is `&String`, not `&str`, as specified in the second parameter to `add`. So why does Listing 8-18 compile?

 The reason we’re able to use `&s2` in the call to `add` is that the compiler can *coerce* the `&String` argument into a `&str`. When we call the `add` method, Rust uses a *deref coercion*, which here turns `&s2` into `&s2[..]`. We’ll discuss deref coercion in more depth in Chapter 15. Because `add` does not take ownership of the `s` parameter, `s2` will still be a valid `String` after this operation.

 Second, we can see in the signature that `add` takes ownership of `self`, because `self` does *not* have an `&`. This means `s1` in Listing 8-18 will be moved into the `add` call and will no longer be valid after that. So although `let s3 = s1 + &s2;` looks like it will copy both strings and create a new one, this statement actually takes ownership of `s1`, appends a copy of the contents of `s2`, and then returns ownership of the result. In other words, it looks like it’s making a lot of copies but isn’t; the implementation is more efficient than copying.

 If we need to concatenate multiple strings, the behavior of the `+` operator gets unwieldy:

 
```
fn main() {
    let s1 = String::from("tic");
    let s2 = String::from("tac");
    let s3 = String::from("toe");

    let s = s1 + "-" + &s2 + "-" + &s3;
}
```
 At this point, `s` will be `tic-tac-toe`. With all of the `+` and `"` characters, it’s difficult to see what’s going on. For more complicated string combining, we can instead use the `format!` macro:

 
```
fn main() {
    let s1 = String::from("tic");
    let s2 = String::from("tac");
    let s3 = String::from("toe");

    let s = format!("{s1}-{s2}-{s3}");
}
```
 This code also sets `s` to `tic-tac-toe`. The `format!` macro works like `println!`, but instead of printing the output to the screen, it returns a `String` with the contents. The version of the code using `format!` is much easier to read, and the code generated by the `format!` macro uses references so that this call doesn’t take ownership of any of its parameters.

 ### Indexing into Strings

 In many other programming languages, accessing individual characters in a string by referencing them by index is a valid and common operation. However, if you try to access parts of a `String` using indexing syntax in Rust, you’ll get an error. Consider the invalid code in Listing 8-19.

 
```
fn main() {
    let s1 = String::from("hello");
    let h = s1[0];
}
```
 Listing 8-19: Attempting to use indexing syntax with a String

 This code will result in the following error:

 
```
$ cargo run
   Compiling collections v0.1.0 (file:///projects/collections)
error[E0277]: the type `String` cannot be indexed by `{integer}`
 --> src/main.rs:3:13
  |
3 |     let h = s1[0];
  |             ^^^^^ `String` cannot be indexed by `{integer}`
  |
  = help: the trait `Index<{integer}>` is not implemented for `String`
  = help: the following other types implement trait `Index<Idx>`:
            <String as Index<RangeFrom<usize>>>
            <String as Index<RangeFull>>
            <String as Index<RangeInclusive<usize>>>
            <String as Index<RangeTo<usize>>>
            <String as Index<RangeToInclusive<usize>>>
            <String as Index<std::ops::Range<usize>>>

For more information about this error, try `rustc --explain E0277`.
error: could not compile `collections` due to previous error

```
 The error and the note tell the story: Rust strings don’t support indexing. But why not? To answer that question, we need to discuss how Rust stores strings in memory.

 #### Internal Representation

 A `String` is a wrapper over a `Vec<u8>`. Let’s look at some of our properly encoded UTF-8 example strings from Listing 8-14. First, this one:

 
```
fn main() {
    let hello = String::from("السلام عليكم");
    let hello = String::from("Dobrý den");
    let hello = String::from("Hello");
    let hello = String::from("שָׁלוֹם");
    let hello = String::from("नमस्ते");
    let hello = String::from("こんにちは");
    let hello = String::from("안녕하세요");
    let hello = String::from("你好");
    let hello = String::from("Olá");
    let hello = String::from("Здравствуйте");
    let hello = String::from("Hola");
}
```
 In this case, `len` will be 4, which means the vector storing the string “Hola” is 4 bytes long. Each of these letters takes 1 byte when encoded in UTF-8. The following line, however, may surprise you. (Note that this string begins with the capital Cyrillic letter Ze, not the Arabic number 3.)

 
```
fn main() {
    let hello = String::from("السلام عليكم");
    let hello = String::from("Dobrý den");
    let hello = String::from("Hello");
    let hello = String::from("שָׁלוֹם");
    let hello = String::from("नमस्ते");
    let hello = String::from("こんにちは");
    let hello = String::from("안녕하세요");
    let hello = String::from("你好");
    let hello = String::from("Olá");
    let hello = String::from("Здравствуйте");
    let hello = String::from("Hola");
}
```
 Asked how long the string is, you might say 12. In fact, Rust’s answer is 24: that’s the number of bytes it takes to encode “Здравствуйте” in UTF-8, because each Unicode scalar value in that string takes 2 bytes of storage. Therefore, an index into the string’s bytes will not always correlate to a valid Unicode scalar value. To demonstrate, consider this invalid Rust code:

 
```
let hello = "Здравствуйте";
let answer = &hello[0];
```
 You already know that `answer` will not be `З`, the first letter. When encoded in UTF-8, the first byte of `З` is `208` and the second is `151`, so it would seem that `answer` should in fact be `208`, but `208` is not a valid character on its own. Returning `208` is likely not what a user would want if they asked for the first letter of this string; however, that’s the only data that Rust has at byte index 0. Users generally don’t want the byte value returned, even if the string contains only Latin letters: if `&"hello"[0]` were valid code that returned the byte value, it would return `104`, not `h`.

 The answer, then, is that to avoid returning an unexpected value and causing bugs that might not be discovered immediately, Rust doesn’t compile this code at all and prevents misunderstandings early in the development process.

 #### Bytes and Scalar Values and Grapheme Clusters! Oh My!

 Another point about UTF-8 is that there are actually three relevant ways to look at strings from Rust’s perspective: as bytes, scalar values, and grapheme clusters (the closest thing to what we would call *letters*).

 If we look at the Hindi word “नमस्ते” written in the Devanagari script, it is stored as a vector of `u8` values that looks like this:

 
```
[224, 164, 168, 224, 164, 174, 224, 164, 184, 224, 165, 141, 224, 164, 164,
224, 165, 135]

```
 That’s 18 bytes and is how computers ultimately store this data. If we look at them as Unicode scalar values, which are what Rust’s `char` type is, those bytes look like this:

 
```
['न', 'म', 'स', '्', 'त', 'े']

```
 There are six `char` values here, but the fourth and sixth are not letters: they’re diacritics that don’t make sense on their own. Finally, if we look at them as grapheme clusters, we’d get what a person would call the four letters that make up the Hindi word:

 
```
["न", "म", "स्", "ते"]

```
 Rust provides different ways of interpreting the raw string data that computers store so that each program can choose the interpretation it needs, no matter what human language the data is in.

 A final reason Rust doesn’t allow us to index into a `String` to get a character is that indexing operations are expected to always take constant time (O(1)). But it isn’t possible to guarantee that performance with a `String`, because Rust would have to walk through the contents from the beginning to the index to determine how many valid characters there were.

 ### Slicing Strings

 Indexing into a string is often a bad idea because it’s not clear what the return type of the string-indexing operation should be: a byte value, a character, a grapheme cluster, or a string slice. If you really need to use indices to create string slices, therefore, Rust asks you to be more specific.

 Rather than indexing using `[]` with a single number, you can use `[]` with a range to create a string slice containing particular bytes:

 
```
#![allow(unused)]
fn main() {
let hello = "Здравствуйте";

let s = &hello[0..4];
}
```
 Here, `s` will be a `&str` that contains the first 4 bytes of the string. Earlier, we mentioned that each of these characters was 2 bytes, which means `s` will be `Зд`.

 If we were to try to slice only part of a character’s bytes with something like `&hello[0..1]`, Rust would panic at runtime in the same way as if an invalid index were accessed in a vector:

 
```
$ cargo run
   Compiling collections v0.1.0 (file:///projects/collections)
    Finished dev [unoptimized + debuginfo] target(s) in 0.43s
     Running `target/debug/collections`
thread 'main' panicked at 'byte index 1 is not a char boundary; it is inside 'З' (bytes 0..2) of `Здравствуйте`', src/main.rs:4:14
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

```
 You should use ranges to create string slices with caution, because doing so can crash your program.

 ### Methods for Iterating Over Strings

 The best way to operate on pieces of strings is to be explicit about whether you want characters or bytes. For individual Unicode scalar values, use the `chars` method. Calling `chars` on “Зд” separates out and returns two values of type `char`, and you can iterate over the result to access each element:

 
```
#![allow(unused)]
fn main() {
for c in "Зд".chars() {
    println!("{c}");
}
}
```
 This code will print the following:

 
```
З
д

```
 Alternatively, the `bytes` method returns each raw byte, which might be appropriate for your domain:

 
```
#![allow(unused)]
fn main() {
for b in "Зд".bytes() {
    println!("{b}");
}
}
```
 This code will print the four bytes that make up this string:

 
```
208
151
208
180

```
 But be sure to remember that valid Unicode scalar values may be made up of more than 1 byte.

 Getting grapheme clusters from strings as with the Devanagari script is complex, so this functionality is not provided by the standard library. Crates are available on [crates.io](https://crates.io/) if this is the functionality you need.

 ### Strings Are Not So Simple

 To summarize, strings are complicated. Different programming languages make different choices about how to present this complexity to the programmer. Rust has chosen to make the correct handling of `String` data the default behavior for all Rust programs, which means programmers have to put more thought into handling UTF-8 data upfront. This trade-off exposes more of the complexity of strings than is apparent in other programming languages, but it prevents you from having to handle errors involving non-ASCII characters later in your development life cycle.

 The good news is that the standard library offers a lot of functionality built off the `String` and `&str` types to help handle these complex situations correctly. Be sure to check out the documentation for useful methods like `contains` for searching in a string and `replace` for substituting parts of a string with another string.

 Let’s switch to something a bit less complex: hash maps!



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch08-02-strings.html>

Storing Keys with Associated Values in Hash Maps
================================================

 The last of our common collections is the *hash map*. The type `HashMap<K, V>` stores a mapping of keys of type `K` to values of type `V` using a *hashing function*, which determines how it places these keys and values into memory. Many programming languages support this kind of data structure, but they often use a different name, such as hash, map, object, hash table, dictionary, or associative array, just to name a few.

 Hash maps are useful when you want to look up data not by using an index, as you can with vectors, but by using a key that can be of any type. For example, in a game, you could keep track of each team’s score in a hash map in which each key is a team’s name and the values are each team’s score. Given a team name, you can retrieve its score.

 We’ll go over the basic API of hash maps in this section, but many more goodies are hiding in the functions defined on `HashMap<K, V>` by the standard library. As always, check the standard library documentation for more information.

 ### Creating a New Hash Map

 One way to create an empty hash map is using `new` and adding elements with `insert`. In Listing 8-20, we’re keeping track of the scores of two teams whose names are *Blue* and *Yellow*. The Blue team starts with 10 points, and the Yellow team starts with 50.

 
```
fn main() {
    use std::collections::HashMap;

    let mut scores = HashMap::new();

    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);
}
```
 Listing 8-20: Creating a new hash map and inserting some keys and values

 Note that we need to first `use` the `HashMap` from the collections portion of the standard library. Of our three common collections, this one is the least often used, so it’s not included in the features brought into scope automatically in the prelude. Hash maps also have less support from the standard library; there’s no built-in macro to construct them, for example.

 Just like vectors, hash maps store their data on the heap. This `HashMap` has keys of type `String` and values of type `i32`. Like vectors, hash maps are homogeneous: all of the keys must have the same type as each other, and all of the values must have the same type.

 ### Accessing Values in a Hash Map

 We can get a value out of the hash map by providing its key to the `get` method, as shown in Listing 8-21.

 
```
fn main() {
    use std::collections::HashMap;

    let mut scores = HashMap::new();

    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);

    let team_name = String::from("Blue");
    let score = scores.get(&team_name).copied().unwrap_or(0);
}
```
 Listing 8-21: Accessing the score for the Blue team stored in the hash map

 Here, `score` will have the value that’s associated with the Blue team, and the result will be `10`. The `get` method returns an `Option<&V>`; if there’s no value for that key in the hash map, `get` will return `None`. This program handles the `Option` by calling `copied` to get an `Option<i32>` rather than an `Option<&i32>`, then `unwrap_or` to set `score` to zero if `scores` doesn't have an entry for the key.

 We can iterate over each key/value pair in a hash map in a similar manner as we do with vectors, using a `for` loop:

 
```
fn main() {
    use std::collections::HashMap;

    let mut scores = HashMap::new();

    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);

    for (key, value) in &scores {
        println!("{key}: {value}");
    }
}
```
 This code will print each pair in an arbitrary order:

 
```
Yellow: 50
Blue: 10

```
 ### Hash Maps and Ownership

 For types that implement the `Copy` trait, like `i32`, the values are copied into the hash map. For owned values like `String`, the values will be moved and the hash map will be the owner of those values, as demonstrated in Listing 8-22.

 
```
fn main() {
    use std::collections::HashMap;

    let field_name = String::from("Favorite color");
    let field_value = String::from("Blue");

    let mut map = HashMap::new();
    map.insert(field_name, field_value);
    // field_name and field_value are invalid at this point, try using them and
    // see what compiler error you get!
}
```
 Listing 8-22: Showing that keys and values are owned by the hash map once they’re inserted

 We aren’t able to use the variables `field_name` and `field_value` after they’ve been moved into the hash map with the call to `insert`.

 If we insert references to values into the hash map, the values won’t be moved into the hash map. The values that the references point to must be valid for at least as long as the hash map is valid. We’ll talk more about these issues in the [“Validating References with Lifetimes”](ch10-03-lifetime-syntax#validating-references-with-lifetimes) section in Chapter 10.

 ### Updating a Hash Map

 Although the number of key and value pairs is growable, each unique key can only have one value associated with it at a time (but not vice versa: for example, both the Blue team and the Yellow team could have value 10 stored in the `scores` hash map).

 When you want to change the data in a hash map, you have to decide how to handle the case when a key already has a value assigned. You could replace the old value with the new value, completely disregarding the old value. You could keep the old value and ignore the new value, only adding the new value if the key *doesn’t* already have a value. Or you could combine the old value and the new value. Let’s look at how to do each of these!

 #### Overwriting a Value

 If we insert a key and a value into a hash map and then insert that same key with a different value, the value associated with that key will be replaced. Even though the code in Listing 8-23 calls `insert` twice, the hash map will only contain one key/value pair because we’re inserting the value for the Blue team’s key both times.

 
```
fn main() {
    use std::collections::HashMap;

    let mut scores = HashMap::new();

    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Blue"), 25);

    println!("{:?}", scores);
}
```
 Listing 8-23: Replacing a value stored with a particular key

 This code will print `{"Blue": 25}`. The original value of `10` has been overwritten.

 #### Adding a Key and Value Only If a Key Isn’t Present

 It’s common to check whether a particular key already exists in the hash map with a value then take the following actions: if the key does exist in the hash map, the existing value should remain the way it is. If the key doesn’t exist, insert it and a value for it.

 Hash maps have a special API for this called `entry` that takes the key you want to check as a parameter. The return value of the `entry` method is an enum called `Entry` that represents a value that might or might not exist. Let’s say we want to check whether the key for the Yellow team has a value associated with it. If it doesn’t, we want to insert the value 50, and the same for the Blue team. Using the `entry` API, the code looks like Listing 8-24.

 
```
fn main() {
    use std::collections::HashMap;

    let mut scores = HashMap::new();
    scores.insert(String::from("Blue"), 10);

    scores.entry(String::from("Yellow")).or_insert(50);
    scores.entry(String::from("Blue")).or_insert(50);

    println!("{:?}", scores);
}
```
 Listing 8-24: Using the `entry` method to only insert if the key does not already have a value

 The `or_insert` method on `Entry` is defined to return a mutable reference to the value for the corresponding `Entry` key if that key exists, and if not, inserts the parameter as the new value for this key and returns a mutable reference to the new value. This technique is much cleaner than writing the logic ourselves and, in addition, plays more nicely with the borrow checker.

 Running the code in Listing 8-24 will print `{"Yellow": 50, "Blue": 10}`. The first call to `entry` will insert the key for the Yellow team with the value 50 because the Yellow team doesn’t have a value already. The second call to `entry` will not change the hash map because the Blue team already has the value 10.

 #### Updating a Value Based on the Old Value

 Another common use case for hash maps is to look up a key’s value and then update it based on the old value. For instance, Listing 8-25 shows code that counts how many times each word appears in some text. We use a hash map with the words as keys and increment the value to keep track of how many times we’ve seen that word. If it’s the first time we’ve seen a word, we’ll first insert the value 0.

 
```
fn main() {
    use std::collections::HashMap;

    let text = "hello world wonderful world";

    let mut map = HashMap::new();

    for word in text.split_whitespace() {
        let count = map.entry(word).or_insert(0);
        *count += 1;
    }

    println!("{:?}", map);
}
```
 Listing 8-25: Counting occurrences of words using a hash map that stores words and counts

 This code will print `{"world": 2, "hello": 1, "wonderful": 1}`. You might see the same key/value pairs printed in a different order: recall from the [“Accessing Values in a Hash Map”](#accessing-values-in-a-hash-map) section that iterating over a hash map happens in an arbitrary order.

 The `split_whitespace` method returns an iterator over sub-slices, separated by whitespace, of the value in `text`. The `or_insert` method returns a mutable reference (`&mut V`) to the value for the specified key. Here we store that mutable reference in the `count` variable, so in order to assign to that value, we must first dereference `count` using the asterisk (`*`). The mutable reference goes out of scope at the end of the `for` loop, so all of these changes are safe and allowed by the borrowing rules.

 ### Hashing Functions

 By default, `HashMap` uses a hashing function called *SipHash* that can provide resistance to Denial of Service (DoS) attacks involving hash tables[1](#siphash). This is not the fastest hashing algorithm available, but the trade-off for better security that comes with the drop in performance is worth it. If you profile your code and find that the default hash function is too slow for your purposes, you can switch to another function by specifying a different hasher. A *hasher* is a type that implements the `BuildHasher` trait. We’ll talk about traits and how to implement them in Chapter 10. You don’t necessarily have to implement your own hasher from scratch; [crates.io](https://crates.io/) has libraries shared by other Rust users that provide hashers implementing many common hashing algorithms.

 
1 <https://en.wikipedia.org/wiki/SipHash>

  Summary
-------

 Vectors, strings, and hash maps will provide a large amount of functionality necessary in programs when you need to store, access, and modify data. Here are some exercises you should now be equipped to solve:

 * Given a list of integers, use a vector and return the median (when sorted, the value in the middle position) and mode (the value that occurs most often; a hash map will be helpful here) of the list.
* Convert strings to pig latin. The first consonant of each word is moved to the end of the word and “ay” is added, so “first” becomes “irst-fay.” Words that start with a vowel have “hay” added to the end instead (“apple” becomes “apple-hay”). Keep in mind the details about UTF-8 encoding!
* Using a hash map and vectors, create a text interface to allow a user to add employee names to a department in a company. For example, “Add Sally to Engineering” or “Add Amir to Sales.” Then let the user retrieve a list of all people in a department or all people in the company by department, sorted alphabetically.

 The standard library API documentation describes methods that vectors, strings, and hash maps have that will be helpful for these exercises!

 We’re getting into more complex programs in which operations can fail, so, it’s a perfect time to discuss error handling. We’ll do that next!



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch08-03-hash-maps.html>

Error Handling
==============

 Errors are a fact of life in software, so Rust has a number of features for handling situations in which something goes wrong. In many cases, Rust requires you to acknowledge the possibility of an error and take some action before your code will compile. This requirement makes your program more robust by ensuring that you’ll discover errors and handle them appropriately before you’ve deployed your code to production!

 Rust groups errors into two major categories: *recoverable* and *unrecoverable* errors. For a recoverable error, such as a *file not found* error, we most likely just want to report the problem to the user and retry the operation. Unrecoverable errors are always symptoms of bugs, like trying to access a location beyond the end of an array, and so we want to immediately stop the program.

 Most languages don’t distinguish between these two kinds of errors and handle both in the same way, using mechanisms such as exceptions. Rust doesn’t have exceptions. Instead, it has the type `Result<T, E>` for recoverable errors and the `panic!` macro that stops execution when the program encounters an unrecoverable error. This chapter covers calling `panic!` first and then talks about returning `Result<T, E>` values. Additionally, we’ll explore considerations when deciding whether to try to recover from an error or to stop execution.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch09-00-error-handling.html>

Unrecoverable Errors with `panic!`
==================================

 Sometimes, bad things happen in your code, and there’s nothing you can do about it. In these cases, Rust has the `panic!` macro. There are two ways to cause a panic in practice: by taking an action that causes our code to panic (such as accessing an array past the end) or by explicitly calling the `panic!` macro. In both cases, we cause a panic in our program. By default, these panics will print a failure message, unwind, clean up the stack, and quit. Via an environment variable, you can also have Rust display the call stack when a panic occurs to make it easier to track down the source of the panic.

 
>  ### Unwinding the Stack or Aborting in Response to a Panic
> 
>  By default, when a panic occurs, the program starts *unwinding*, which means Rust walks back up the stack and cleans up the data from each function it encounters. However, this walking back and cleanup is a lot of work. Rust, therefore, allows you to choose the alternative of immediately *aborting*, which ends the program without cleaning up.
> 
>  Memory that the program was using will then need to be cleaned up by the operating system. If in your project you need to make the resulting binary as small as possible, you can switch from unwinding to aborting upon a panic by adding `panic = 'abort'` to the appropriate `[profile]` sections in your *Cargo.toml* file. For example, if you want to abort on panic in release mode, add this:
> 
>  
> ```
> [profile.release]
> panic = 'abort'
> 
> ```
>  

 Let’s try calling `panic!` in a simple program:

 Filename: src/main.rs

 
```
fn main() {
    panic!("crash and burn");
}
```
 When you run the program, you’ll see something like this:

 
```
$ cargo run
   Compiling panic v0.1.0 (file:///projects/panic)
    Finished dev [unoptimized + debuginfo] target(s) in 0.25s
     Running `target/debug/panic`
thread 'main' panicked at 'crash and burn', src/main.rs:2:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

```
 The call to `panic!` causes the error message contained in the last two lines. The first line shows our panic message and the place in our source code where the panic occurred: *src/main.rs:2:5* indicates that it’s the second line, fifth character of our *src/main.rs* file.

 In this case, the line indicated is part of our code, and if we go to that line, we see the `panic!` macro call. In other cases, the `panic!` call might be in code that our code calls, and the filename and line number reported by the error message will be someone else’s code where the `panic!` macro is called, not the line of our code that eventually led to the `panic!` call. We can use the backtrace of the functions the `panic!` call came from to figure out the part of our code that is causing the problem. We’ll discuss backtraces in more detail next.

 ### Using a `panic!` Backtrace

 Let’s look at another example to see what it’s like when a `panic!` call comes from a library because of a bug in our code instead of from our code calling the macro directly. Listing 9-1 has some code that attempts to access an index in a vector beyond the range of valid indexes.

 Filename: src/main.rs

 
```
fn main() {
    let v = vec![1, 2, 3];

    v[99];
}
```
 Listing 9-1: Attempting to access an element beyond the end of a vector, which will cause a call to `panic!`

 Here, we’re attempting to access the 100th element of our vector (which is at index 99 because indexing starts at zero), but the vector has only 3 elements. In this situation, Rust will panic. Using `[]` is supposed to return an element, but if you pass an invalid index, there’s no element that Rust could return here that would be correct.

 In C, attempting to read beyond the end of a data structure is undefined behavior. You might get whatever is at the location in memory that would correspond to that element in the data structure, even though the memory doesn’t belong to that structure. This is called a *buffer overread* and can lead to security vulnerabilities if an attacker is able to manipulate the index in such a way as to read data they shouldn’t be allowed to that is stored after the data structure.

 To protect your program from this sort of vulnerability, if you try to read an element at an index that doesn’t exist, Rust will stop execution and refuse to continue. Let’s try it and see:

 
```
$ cargo run
   Compiling panic v0.1.0 (file:///projects/panic)
    Finished dev [unoptimized + debuginfo] target(s) in 0.27s
     Running `target/debug/panic`
thread 'main' panicked at 'index out of bounds: the len is 3 but the index is 99', src/main.rs:4:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

```
 This error points at line 4 of our `main.rs` where we attempt to access index 99. The next note line tells us that we can set the `RUST_BACKTRACE` environment variable to get a backtrace of exactly what happened to cause the error. A *backtrace* is a list of all the functions that have been called to get to this point. Backtraces in Rust work as they do in other languages: the key to reading the backtrace is to start from the top and read until you see files you wrote. That’s the spot where the problem originated. The lines above that spot are code that your code has called; the lines below are code that called your code. These before-and-after lines might include core Rust code, standard library code, or crates that you’re using. Let’s try getting a backtrace by setting the `RUST_BACKTRACE` environment variable to any value except 0. Listing 9-2 shows output similar to what you’ll see.

 
```
$ RUST_BACKTRACE=1 cargo run
thread 'main' panicked at 'index out of bounds: the len is 3 but the index is 99', src/main.rs:4:5
stack backtrace:
   0: rust_begin_unwind
             at /rustc/e092d0b6b43f2de967af0887873151bb1c0b18d3/library/std/src/panicking.rs:584:5
   1: core::panicking::panic_fmt
             at /rustc/e092d0b6b43f2de967af0887873151bb1c0b18d3/library/core/src/panicking.rs:142:14
   2: core::panicking::panic_bounds_check
             at /rustc/e092d0b6b43f2de967af0887873151bb1c0b18d3/library/core/src/panicking.rs:84:5
   3: <usize as core::slice::index::SliceIndex<[T]>>::index
             at /rustc/e092d0b6b43f2de967af0887873151bb1c0b18d3/library/core/src/slice/index.rs:242:10
   4: core::slice::index::<impl core::ops::index::Index<I> for [T]>::index
             at /rustc/e092d0b6b43f2de967af0887873151bb1c0b18d3/library/core/src/slice/index.rs:18:9
   5: <alloc::vec::Vec<T,A> as core::ops::index::Index<I>>::index
             at /rustc/e092d0b6b43f2de967af0887873151bb1c0b18d3/library/alloc/src/vec/mod.rs:2591:9
   6: panic::main
             at ./src/main.rs:4:5
   7: core::ops::function::FnOnce::call_once
             at /rustc/e092d0b6b43f2de967af0887873151bb1c0b18d3/library/core/src/ops/function.rs:248:5
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.

```
 Listing 9-2: The backtrace generated by a call to `panic!` displayed when the environment variable `RUST_BACKTRACE` is set

 That’s a lot of output! The exact output you see might be different depending on your operating system and Rust version. In order to get backtraces with this information, debug symbols must be enabled. Debug symbols are enabled by default when using `cargo build` or `cargo run` without the `--release` flag, as we have here.

 In the output in Listing 9-2, line 6 of the backtrace points to the line in our project that’s causing the problem: line 4 of *src/main.rs*. If we don’t want our program to panic, we should start our investigation at the location pointed to by the first line mentioning a file we wrote. In Listing 9-1, where we deliberately wrote code that would panic, the way to fix the panic is to not request an element beyond the range of the vector indexes. When your code panics in the future, you’ll need to figure out what action the code is taking with what values to cause the panic and what the code should do instead.

 We’ll come back to `panic!` and when we should and should not use `panic!` to handle error conditions in the [“To `panic!` or Not to `panic!`”](ch09-03-to-panic-or-not-to-panic#to-panic-or-not-to-panic) section later in this chapter. Next, we’ll look at how to recover from an error using `Result`.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch09-01-unrecoverable-errors-with-panic.html>

To `panic!` or Not to `panic!`
==============================

 So how do you decide when you should call `panic!` and when you should return `Result`? When code panics, there’s no way to recover. You could call `panic!` for any error situation, whether there’s a possible way to recover or not, but then you’re making the decision that a situation is unrecoverable on behalf of the calling code. When you choose to return a `Result` value, you give the calling code options. The calling code could choose to attempt to recover in a way that’s appropriate for its situation, or it could decide that an `Err` value in this case is unrecoverable, so it can call `panic!` and turn your recoverable error into an unrecoverable one. Therefore, returning `Result` is a good default choice when you’re defining a function that might fail.

 In situations such as examples, prototype code, and tests, it’s more appropriate to write code that panics instead of returning a `Result`. Let’s explore why, then discuss situations in which the compiler can’t tell that failure is impossible, but you as a human can. The chapter will conclude with some general guidelines on how to decide whether to panic in library code.

 ### Examples, Prototype Code, and Tests

 When you’re writing an example to illustrate some concept, also including robust error-handling code can make the example less clear. In examples, it’s understood that a call to a method like `unwrap` that could panic is meant as a placeholder for the way you’d want your application to handle errors, which can differ based on what the rest of your code is doing.

 Similarly, the `unwrap` and `expect` methods are very handy when prototyping, before you’re ready to decide how to handle errors. They leave clear markers in your code for when you’re ready to make your program more robust.

 If a method call fails in a test, you’d want the whole test to fail, even if that method isn’t the functionality under test. Because `panic!` is how a test is marked as a failure, calling `unwrap` or `expect` is exactly what should happen.

 ### Cases in Which You Have More Information Than the Compiler

 It would also be appropriate to call `unwrap` or `expect` when you have some other logic that ensures the `Result` will have an `Ok` value, but the logic isn’t something the compiler understands. You’ll still have a `Result` value that you need to handle: whatever operation you’re calling still has the possibility of failing in general, even though it’s logically impossible in your particular situation. If you can ensure by manually inspecting the code that you’ll never have an `Err` variant, it’s perfectly acceptable to call `unwrap`, and even better to document the reason you think you’ll never have an `Err` variant in the `expect` text. Here’s an example:

 
```
fn main() {
    use std::net::IpAddr;

    let home: IpAddr = "127.0.0.1"
        .parse()
        .expect("Hardcoded IP address should be valid");
}
```
 We’re creating an `IpAddr` instance by parsing a hardcoded string. We can see that `127.0.0.1` is a valid IP address, so it’s acceptable to use `expect` here. However, having a hardcoded, valid string doesn’t change the return type of the `parse` method: we still get a `Result` value, and the compiler will still make us handle the `Result` as if the `Err` variant is a possibility because the compiler isn’t smart enough to see that this string is always a valid IP address. If the IP address string came from a user rather than being hardcoded into the program and therefore *did* have a possibility of failure, we’d definitely want to handle the `Result` in a more robust way instead. Mentioning the assumption that this IP address is hardcoded will prompt us to change `expect` to better error handling code if in the future, we need to get the IP address from some other source instead.

 ### Guidelines for Error Handling

 It’s advisable to have your code panic when it’s possible that your code could end up in a bad state. In this context, a *bad state* is when some assumption, guarantee, contract, or invariant has been broken, such as when invalid values, contradictory values, or missing values are passed to your code—plus one or more of the following:

 * The bad state is something that is unexpected, as opposed to something that will likely happen occasionally, like a user entering data in the wrong format.
* Your code after this point needs to rely on not being in this bad state, rather than checking for the problem at every step.
* There’s not a good way to encode this information in the types you use. We’ll work through an example of what we mean in the [“Encoding States and Behavior as Types”](ch17-03-oo-design-patterns#encoding-states-and-behavior-as-types) section of Chapter 17.

 If someone calls your code and passes in values that don’t make sense, it’s best to return an error if you can so the user of the library can decide what they want to do in that case. However, in cases where continuing could be insecure or harmful, the best choice might be to call `panic!` and alert the person using your library to the bug in their code so they can fix it during development. Similarly, `panic!` is often appropriate if you’re calling external code that is out of your control and it returns an invalid state that you have no way of fixing.

 However, when failure is expected, it’s more appropriate to return a `Result` than to make a `panic!` call. Examples include a parser being given malformed data or an HTTP request returning a status that indicates you have hit a rate limit. In these cases, returning a `Result` indicates that failure is an expected possibility that the calling code must decide how to handle.

 When your code performs an operation that could put a user at risk if it’s called using invalid values, your code should verify the values are valid first and panic if the values aren’t valid. This is mostly for safety reasons: attempting to operate on invalid data can expose your code to vulnerabilities. This is the main reason the standard library will call `panic!` if you attempt an out-of-bounds memory access: trying to access memory that doesn’t belong to the current data structure is a common security problem. Functions often have *contracts*: their behavior is only guaranteed if the inputs meet particular requirements. Panicking when the contract is violated makes sense because a contract violation always indicates a caller-side bug and it’s not a kind of error you want the calling code to have to explicitly handle. In fact, there’s no reasonable way for calling code to recover; the calling *programmers* need to fix the code. Contracts for a function, especially when a violation will cause a panic, should be explained in the API documentation for the function.

 However, having lots of error checks in all of your functions would be verbose and annoying. Fortunately, you can use Rust’s type system (and thus the type checking done by the compiler) to do many of the checks for you. If your function has a particular type as a parameter, you can proceed with your code’s logic knowing that the compiler has already ensured you have a valid value. For example, if you have a type rather than an `Option`, your program expects to have *something* rather than *nothing*. Your code then doesn’t have to handle two cases for the `Some` and `None` variants: it will only have one case for definitely having a value. Code trying to pass nothing to your function won’t even compile, so your function doesn’t have to check for that case at runtime. Another example is using an unsigned integer type such as `u32`, which ensures the parameter is never negative.

 ### Creating Custom Types for Validation

 Let’s take the idea of using Rust’s type system to ensure we have a valid value one step further and look at creating a custom type for validation. Recall the guessing game in Chapter 2 in which our code asked the user to guess a number between 1 and 100. We never validated that the user’s guess was between those numbers before checking it against our secret number; we only validated that the guess was positive. In this case, the consequences were not very dire: our output of “Too high” or “Too low” would still be correct. But it would be a useful enhancement to guide the user toward valid guesses and have different behavior when a user guesses a number that’s out of range versus when a user types, for example, letters instead.

 One way to do this would be to parse the guess as an `i32` instead of only a `u32` to allow potentially negative numbers, and then add a check for the number being in range, like so:

 
```
use rand::Rng;
use std::cmp::Ordering;
use std::io;

fn main() {
    println!("Guess the number!");

    let secret_number = rand::thread_rng().gen_range(1..=100);

    loop {
        // --snip--

        println!("Please input your guess.");

        let mut guess = String::new();

        io::stdin()
            .read_line(&mut guess)
            .expect("Failed to read line");

        let guess: i32 = match guess.trim().parse() {
            Ok(num) => num,
            Err(_) => continue,
        };

        if guess < 1 || guess > 100 {
            println!("The secret number will be between 1 and 100.");
            continue;
        }

        match guess.cmp(&secret_number) {
            // --snip--
            Ordering::Less => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal => {
                println!("You win!");
                break;
            }
        }
    }
}
```
 The `if` expression checks whether our value is out of range, tells the user about the problem, and calls `continue` to start the next iteration of the loop and ask for another guess. After the `if` expression, we can proceed with the comparisons between `guess` and the secret number knowing that `guess` is between 1 and 100.

 However, this is not an ideal solution: if it was absolutely critical that the program only operated on values between 1 and 100, and it had many functions with this requirement, having a check like this in every function would be tedious (and might impact performance).

 Instead, we can make a new type and put the validations in a function to create an instance of the type rather than repeating the validations everywhere. That way, it’s safe for functions to use the new type in their signatures and confidently use the values they receive. Listing 9-13 shows one way to define a `Guess` type that will only create an instance of `Guess` if the `new` function receives a value between 1 and 100.

 
```
#![allow(unused)]
fn main() {
pub struct Guess {
    value: i32,
}

impl Guess {
    pub fn new(value: i32) -> Guess {
        if value < 1 || value > 100 {
            panic!("Guess value must be between 1 and 100, got {}.", value);
        }

        Guess { value }
    }

    pub fn value(&self) -> i32 {
        self.value
    }
}
}
```
 Listing 9-13: A `Guess` type that will only continue with values between 1 and 100

 First, we define a struct named `Guess` that has a field named `value` that holds an `i32`. This is where the number will be stored.

 Then we implement an associated function named `new` on `Guess` that creates instances of `Guess` values. The `new` function is defined to have one parameter named `value` of type `i32` and to return a `Guess`. The code in the body of the `new` function tests `value` to make sure it’s between 1 and 100. If `value` doesn’t pass this test, we make a `panic!` call, which will alert the programmer who is writing the calling code that they have a bug they need to fix, because creating a `Guess` with a `value` outside this range would violate the contract that `Guess::new` is relying on. The conditions in which `Guess::new` might panic should be discussed in its public-facing API documentation; we’ll cover documentation conventions indicating the possibility of a `panic!` in the API documentation that you create in Chapter 14. If `value` does pass the test, we create a new `Guess` with its `value` field set to the `value` parameter and return the `Guess`.

 Next, we implement a method named `value` that borrows `self`, doesn’t have any other parameters, and returns an `i32`. This kind of method is sometimes called a *getter*, because its purpose is to get some data from its fields and return it. This public method is necessary because the `value` field of the `Guess` struct is private. It’s important that the `value` field be private so code using the `Guess` struct is not allowed to set `value` directly: code outside the module *must* use the `Guess::new` function to create an instance of `Guess`, thereby ensuring there’s no way for a `Guess` to have a `value` that hasn’t been checked by the conditions in the `Guess::new` function.

 A function that has a parameter or returns only numbers between 1 and 100 could then declare in its signature that it takes or returns a `Guess` rather than an `i32` and wouldn’t need to do any additional checks in its body.

 Summary
-------

 Rust’s error handling features are designed to help you write more robust code. The `panic!` macro signals that your program is in a state it can’t handle and lets you tell the process to stop instead of trying to proceed with invalid or incorrect values. The `Result` enum uses Rust’s type system to indicate that operations might fail in a way that your code could recover from. You can use `Result` to tell code that calls your code that it needs to handle potential success or failure as well. Using `panic!` and `Result` in the appropriate situations will make your code more reliable in the face of inevitable problems.

 Now that you’ve seen useful ways that the standard library uses generics with the `Option` and `Result` enums, we’ll talk about how generics work and how you can use them in your code.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch09-03-to-panic-or-not-to-panic.html>

Generic Types, Traits, and Lifetimes
====================================

 Every programming language has tools for effectively handling the duplication of concepts. In Rust, one such tool is *generics*: abstract stand-ins for concrete types or other properties. We can express the behavior of generics or how they relate to other generics without knowing what will be in their place when compiling and running the code.

 Functions can take parameters of some generic type, instead of a concrete type like `i32` or `String`, in the same way a function takes parameters with unknown values to run the same code on multiple concrete values. In fact, we’ve already used generics in Chapter 6 with `Option<T>`, Chapter 8 with `Vec<T>` and `HashMap<K, V>`, and Chapter 9 with `Result<T, E>`. In this chapter, you’ll explore how to define your own types, functions, and methods with generics!

 First, we’ll review how to extract a function to reduce code duplication. We’ll then use the same technique to make a generic function from two functions that differ only in the types of their parameters. We’ll also explain how to use generic types in struct and enum definitions.

 Then you’ll learn how to use *traits* to define behavior in a generic way. You can combine traits with generic types to constrain a generic type to accept only those types that have a particular behavior, as opposed to just any type.

 Finally, we’ll discuss *lifetimes*: a variety of generics that give the compiler information about how references relate to each other. Lifetimes allow us to give the compiler enough information about borrowed values so that it can ensure references will be valid in more situations than it could without our help.

 Removing Duplication by Extracting a Function
---------------------------------------------

 Generics allow us to replace specific types with a placeholder that represents multiple types to remove code duplication. Before diving into generics syntax, then, let’s first look at how to remove duplication in a way that doesn’t involve generic types by extracting a function that replaces specific values with a placeholder that represents multiple values. Then we’ll apply the same technique to extract a generic function! By looking at how to recognize duplicated code you can extract into a function, you’ll start to recognize duplicated code that can use generics.

 We begin with the short program in Listing 10-1 that finds the largest number in a list.

 Filename: src/main.rs

 
```
fn main() {
    let number_list = vec![34, 50, 25, 100, 65];

    let mut largest = &number_list[0];

    for number in &number_list {
        if number > largest {
            largest = number;
        }
    }

    println!("The largest number is {}", largest);
    assert_eq!(*largest, 100);
}
```
 Listing 10-1: Finding the largest number in a list of numbers

 We store a list of integers in the variable `number_list` and place a reference to the first number in the list in a variable named `largest`. We then iterate through all the numbers in the list, and if the current number is greater than the number stored in `largest`, replace the reference in that variable. However, if the current number is less than or equal to the largest number seen so far, the variable doesn’t change, and the code moves on to the next number in the list. After considering all the numbers in the list, `largest` should refer to the largest number, which in this case is 100.

 We've now been tasked with finding the largest number in two different lists of numbers. To do so, we can choose to duplicate the code in Listing 10-1 and use the same logic at two different places in the program, as shown in Listing 10-2.

 Filename: src/main.rs

 
```
fn main() {
    let number_list = vec![34, 50, 25, 100, 65];

    let mut largest = &number_list[0];

    for number in &number_list {
        if number > largest {
            largest = number;
        }
    }

    println!("The largest number is {}", largest);

    let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8];

    let mut largest = &number_list[0];

    for number in &number_list {
        if number > largest {
            largest = number;
        }
    }

    println!("The largest number is {}", largest);
}
```
 Listing 10-2: Code to find the largest number in *two* lists of numbers

 Although this code works, duplicating code is tedious and error prone. We also have to remember to update the code in multiple places when we want to change it.

 To eliminate this duplication, we’ll create an abstraction by defining a function that operates on any list of integers passed in a parameter. This solution makes our code clearer and lets us express the concept of finding the largest number in a list abstractly.

 In Listing 10-3, we extract the code that finds the largest number into a function named `largest`. Then we call the function to find the largest number in the two lists from Listing 10-2. We could also use the function on any other list of `i32` values we might have in the future.

 Filename: src/main.rs

 
```
fn largest(list: &[i32]) -> &i32 {
    let mut largest = &list[0];

    for item in list {
        if item > largest {
            largest = item;
        }
    }

    largest
}

fn main() {
    let number_list = vec![34, 50, 25, 100, 65];

    let result = largest(&number_list);
    println!("The largest number is {}", result);
    assert_eq!(*result, 100);

    let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8];

    let result = largest(&number_list);
    println!("The largest number is {}", result);
    assert_eq!(*result, 6000);
}
```
 Listing 10-3: Abstracted code to find the largest number in two lists

 The `largest` function has a parameter called `list`, which represents any concrete slice of `i32` values we might pass into the function. As a result, when we call the function, the code runs on the specific values that we pass in.

 In summary, here are the steps we took to change the code from Listing 10-2 to Listing 10-3:

 1. Identify duplicate code.
2. Extract the duplicate code into the body of the function and specify the inputs and return values of that code in the function signature.
3. Update the two instances of duplicated code to call the function instead.

 Next, we’ll use these same steps with generics to reduce code duplication. In the same way that the function body can operate on an abstract `list` instead of specific values, generics allow code to operate on abstract types.

 For example, say we had two functions: one that finds the largest item in a slice of `i32` values and one that finds the largest item in a slice of `char` values. How would we eliminate that duplication? Let’s find out!



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch10-00-generics.html>

Generic Data Types
==================

 We use generics to create definitions for items like function signatures or structs, which we can then use with many different concrete data types. Let’s first look at how to define functions, structs, enums, and methods using generics. Then we’ll discuss how generics affect code performance.

 ### In Function Definitions

 When defining a function that uses generics, we place the generics in the signature of the function where we would usually specify the data types of the parameters and return value. Doing so makes our code more flexible and provides more functionality to callers of our function while preventing code duplication.

 Continuing with our `largest` function, Listing 10-4 shows two functions that both find the largest value in a slice. We'll then combine these into a single function that uses generics.

 Filename: src/main.rs

 
```
fn largest_i32(list: &[i32]) -> &i32 {
    let mut largest = &list[0];

    for item in list {
        if item > largest {
            largest = item;
        }
    }

    largest
}

fn largest_char(list: &[char]) -> &char {
    let mut largest = &list[0];

    for item in list {
        if item > largest {
            largest = item;
        }
    }

    largest
}

fn main() {
    let number_list = vec![34, 50, 25, 100, 65];

    let result = largest_i32(&number_list);
    println!("The largest number is {}", result);
    assert_eq!(*result, 100);

    let char_list = vec!['y', 'm', 'a', 'q'];

    let result = largest_char(&char_list);
    println!("The largest char is {}", result);
    assert_eq!(*result, 'y');
}
```
 Listing 10-4: Two functions that differ only in their names and the types in their signatures

 The `largest_i32` function is the one we extracted in Listing 10-3 that finds the largest `i32` in a slice. The `largest_char` function finds the largest `char` in a slice. The function bodies have the same code, so let’s eliminate the duplication by introducing a generic type parameter in a single function.

 To parameterize the types in a new single function, we need to name the type parameter, just as we do for the value parameters to a function. You can use any identifier as a type parameter name. But we’ll use `T` because, by convention, type parameter names in Rust are short, often just a letter, and Rust’s type-naming convention is UpperCamelCase. Short for “type,” `T` is the default choice of most Rust programmers.

 When we use a parameter in the body of the function, we have to declare the parameter name in the signature so the compiler knows what that name means. Similarly, when we use a type parameter name in a function signature, we have to declare the type parameter name before we use it. To define the generic `largest` function, place type name declarations inside angle brackets, `<>`, between the name of the function and the parameter list, like this:

 
```
fn largest<T>(list: &[T]) -> &T {
```
 We read this definition as: the function `largest` is generic over some type `T`. This function has one parameter named `list`, which is a slice of values of type `T`. The `largest` function will return a reference to a value of the same type `T`.

 Listing 10-5 shows the combined `largest` function definition using the generic data type in its signature. The listing also shows how we can call the function with either a slice of `i32` values or `char` values. Note that this code won’t compile yet, but we’ll fix it later in this chapter.

 Filename: src/main.rs

 
```
fn largest<T>(list: &[T]) -> &T {
    let mut largest = &list[0];

    for item in list {
        if item > largest {
            largest = item;
        }
    }

    largest
}

fn main() {
    let number_list = vec![34, 50, 25, 100, 65];

    let result = largest(&number_list);
    println!("The largest number is {}", result);

    let char_list = vec!['y', 'm', 'a', 'q'];

    let result = largest(&char_list);
    println!("The largest char is {}", result);
}
```
 Listing 10-5: The `largest` function using generic type parameters; this doesn’t yet compile

 If we compile this code right now, we’ll get this error:

 
```
$ cargo run
   Compiling chapter10 v0.1.0 (file:///projects/chapter10)
error[E0369]: binary operation `>` cannot be applied to type `&T`
 --> src/main.rs:5:17
  |
5 |         if item > largest {
  |            ---- ^ ------- &T
  |            |
  |            &T
  |
help: consider restricting type parameter `T`
  |
1 | fn largest<T: std::cmp::PartialOrd>(list: &[T]) -> &T {
  |             ++++++++++++++++++++++

For more information about this error, try `rustc --explain E0369`.
error: could not compile `chapter10` due to previous error

```
 The help text mentions `std::cmp::PartialOrd`, which is a *trait*, and we’re going to talk about traits in the next section. For now, know that this error states that the body of `largest` won’t work for all possible types that `T` could be. Because we want to compare values of type `T` in the body, we can only use types whose values can be ordered. To enable comparisons, the standard library has the `std::cmp::PartialOrd` trait that you can implement on types (see Appendix C for more on this trait). By following the help text's suggestion, we restrict the types valid for `T` to only those that implement `PartialOrd` and this example will compile, because the standard library implements `PartialOrd` on both `i32` and `char`.

 ### In Struct Definitions

 We can also define structs to use a generic type parameter in one or more fields using the `<>` syntax. Listing 10-6 defines a `Point<T>` struct to hold `x` and `y` coordinate values of any type.

 Filename: src/main.rs

 
```
struct Point<T> {
    x: T,
    y: T,
}

fn main() {
    let integer = Point { x: 5, y: 10 };
    let float = Point { x: 1.0, y: 4.0 };
}
```
 Listing 10-6: A `Point<T>` struct that holds `x` and `y` values of type `T`

 The syntax for using generics in struct definitions is similar to that used in function definitions. First, we declare the name of the type parameter inside angle brackets just after the name of the struct. Then we use the generic type in the struct definition where we would otherwise specify concrete data types.

 Note that because we’ve used only one generic type to define `Point<T>`, this definition says that the `Point<T>` struct is generic over some type `T`, and the fields `x` and `y` are *both* that same type, whatever that type may be. If we create an instance of a `Point<T>` that has values of different types, as in Listing 10-7, our code won’t compile.

 Filename: src/main.rs

 
```
struct Point<T> {
    x: T,
    y: T,
}

fn main() {
    let wont_work = Point { x: 5, y: 4.0 };
}
```
 Listing 10-7: The fields `x` and `y` must be the same type because both have the same generic data type `T`.

 In this example, when we assign the integer value 5 to `x`, we let the compiler know that the generic type `T` will be an integer for this instance of `Point<T>`. Then when we specify 4.0 for `y`, which we’ve defined to have the same type as `x`, we’ll get a type mismatch error like this:

 
```
$ cargo run
   Compiling chapter10 v0.1.0 (file:///projects/chapter10)
error[E0308]: mismatched types
 --> src/main.rs:7:38
  |
7 |     let wont_work = Point { x: 5, y: 4.0 };
  |                                      ^^^ expected integer, found floating-point number

For more information about this error, try `rustc --explain E0308`.
error: could not compile `chapter10` due to previous error

```
 To define a `Point` struct where `x` and `y` are both generics but could have different types, we can use multiple generic type parameters. For example, in Listing 10-8, we change the definition of `Point` to be generic over types `T` and `U` where `x` is of type `T` and `y` is of type `U`.

 Filename: src/main.rs

 
```
struct Point<T, U> {
    x: T,
    y: U,
}

fn main() {
    let both_integer = Point { x: 5, y: 10 };
    let both_float = Point { x: 1.0, y: 4.0 };
    let integer_and_float = Point { x: 5, y: 4.0 };
}
```
 Listing 10-8: A `Point<T, U>` generic over two types so that `x` and `y` can be values of different types

 Now all the instances of `Point` shown are allowed! You can use as many generic type parameters in a definition as you want, but using more than a few makes your code hard to read. If you're finding you need lots of generic types in your code, it could indicate that your code needs restructuring into smaller pieces.

 ### In Enum Definitions

 As we did with structs, we can define enums to hold generic data types in their variants. Let’s take another look at the `Option<T>` enum that the standard library provides, which we used in Chapter 6:

 
```
#![allow(unused)]
fn main() {
enum Option<T> {
    Some(T),
    None,
}
}
```
 This definition should now make more sense to you. As you can see, the `Option<T>` enum is generic over type `T` and has two variants: `Some`, which holds one value of type `T`, and a `None` variant that doesn’t hold any value. By using the `Option<T>` enum, we can express the abstract concept of an optional value, and because `Option<T>` is generic, we can use this abstraction no matter what the type of the optional value is.

 Enums can use multiple generic types as well. The definition of the `Result` enum that we used in Chapter 9 is one example:

 
```
#![allow(unused)]
fn main() {
enum Result<T, E> {
    Ok(T),
    Err(E),
}
}
```
 The `Result` enum is generic over two types, `T` and `E`, and has two variants: `Ok`, which holds a value of type `T`, and `Err`, which holds a value of type `E`. This definition makes it convenient to use the `Result` enum anywhere we have an operation that might succeed (return a value of some type `T`) or fail (return an error of some type `E`). In fact, this is what we used to open a file in Listing 9-3, where `T` was filled in with the type `std::fs::File` when the file was opened successfully and `E` was filled in with the type `std::io::Error` when there were problems opening the file.

 When you recognize situations in your code with multiple struct or enum definitions that differ only in the types of the values they hold, you can avoid duplication by using generic types instead.

 ### In Method Definitions

 We can implement methods on structs and enums (as we did in Chapter 5) and use generic types in their definitions, too. Listing 10-9 shows the `Point<T>` struct we defined in Listing 10-6 with a method named `x` implemented on it.

 Filename: src/main.rs

 
```
struct Point<T> {
    x: T,
    y: T,
}

impl<T> Point<T> {
    fn x(&self) -> &T {
        &self.x
    }
}

fn main() {
    let p = Point { x: 5, y: 10 };

    println!("p.x = {}", p.x());
}
```
 Listing 10-9: Implementing a method named `x` on the `Point<T>` struct that will return a reference to the `x` field of type `T`

 Here, we’ve defined a method named `x` on `Point<T>` that returns a reference to the data in the field `x`.

 Note that we have to declare `T` just after `impl` so we can use `T` to specify that we’re implementing methods on the type `Point<T>`. By declaring `T` as a generic type after `impl`, Rust can identify that the type in the angle brackets in `Point` is a generic type rather than a concrete type. We could have chosen a different name for this generic parameter than the generic parameter declared in the struct definition, but using the same name is conventional. Methods written within an `impl` that declares the generic type will be defined on any instance of the type, no matter what concrete type ends up substituting for the generic type.

 We can also specify constraints on generic types when defining methods on the type. We could, for example, implement methods only on `Point<f32>` instances rather than on `Point<T>` instances with any generic type. In Listing 10-10 we use the concrete type `f32`, meaning we don’t declare any types after `impl`.

 Filename: src/main.rs

 
```
struct Point<T> {
    x: T,
    y: T,
}

impl<T> Point<T> {
    fn x(&self) -> &T {
        &self.x
    }
}

impl Point<f32> {
    fn distance_from_origin(&self) -> f32 {
        (self.x.powi(2) + self.y.powi(2)).sqrt()
    }
}

fn main() {
    let p = Point { x: 5, y: 10 };

    println!("p.x = {}", p.x());
}
```
 Listing 10-10: An `impl` block that only applies to a struct with a particular concrete type for the generic type parameter `T`

 This code means the type `Point<f32>` will have a `distance_from_origin` method; other instances of `Point<T>` where `T` is not of type `f32` will not have this method defined. The method measures how far our point is from the point at coordinates (0.0, 0.0) and uses mathematical operations that are available only for floating point types.

 Generic type parameters in a struct definition aren’t always the same as those you use in that same struct’s method signatures. Listing 10-11 uses the generic types `X1` and `Y1` for the `Point` struct and `X2` `Y2` for the `mixup` method signature to make the example clearer. The method creates a new `Point` instance with the `x` value from the `self` `Point` (of type `X1`) and the `y` value from the passed-in `Point` (of type `Y2`).

 Filename: src/main.rs

 
```
struct Point<X1, Y1> {
    x: X1,
    y: Y1,
}

impl<X1, Y1> Point<X1, Y1> {
    fn mixup<X2, Y2>(self, other: Point<X2, Y2>) -> Point<X1, Y2> {
        Point {
            x: self.x,
            y: other.y,
        }
    }
}

fn main() {
    let p1 = Point { x: 5, y: 10.4 };
    let p2 = Point { x: "Hello", y: 'c' };

    let p3 = p1.mixup(p2);

    println!("p3.x = {}, p3.y = {}", p3.x, p3.y);
}
```
 Listing 10-11: A method that uses generic types different from its struct’s definition

 In `main`, we’ve defined a `Point` that has an `i32` for `x` (with value `5`) and an `f64` for `y` (with value `10.4`). The `p2` variable is a `Point` struct that has a string slice for `x` (with value `"Hello"`) and a `char` for `y` (with value `c`). Calling `mixup` on `p1` with the argument `p2` gives us `p3`, which will have an `i32` for `x`, because `x` came from `p1`. The `p3` variable will have a `char` for `y`, because `y` came from `p2`. The `println!` macro call will print `p3.x = 5, p3.y = c`.

 The purpose of this example is to demonstrate a situation in which some generic parameters are declared with `impl` and some are declared with the method definition. Here, the generic parameters `X1` and `Y1` are declared after `impl` because they go with the struct definition. The generic parameters `X2` and `Y2` are declared after `fn mixup`, because they’re only relevant to the method.

 ### Performance of Code Using Generics

 You might be wondering whether there is a runtime cost when using generic type parameters. The good news is that using generic types won't make your program run any slower than it would with concrete types.

 Rust accomplishes this by performing monomorphization of the code using generics at compile time. *Monomorphization* is the process of turning generic code into specific code by filling in the concrete types that are used when compiled. In this process, the compiler does the opposite of the steps we used to create the generic function in Listing 10-5: the compiler looks at all the places where generic code is called and generates code for the concrete types the generic code is called with.

 Let’s look at how this works by using the standard library’s generic `Option<T>` enum:

 
```
#![allow(unused)]
fn main() {
let integer = Some(5);
let float = Some(5.0);
}
```
 When Rust compiles this code, it performs monomorphization. During that process, the compiler reads the values that have been used in `Option<T>` instances and identifies two kinds of `Option<T>`: one is `i32` and the other is `f64`. As such, it expands the generic definition of `Option<T>` into two definitions specialized to `i32` and `f64`, thereby replacing the generic definition with the specific ones.

 The monomorphized version of the code looks similar to the following (the compiler uses different names than what we’re using here for illustration):

 Filename: src/main.rs

 
```
enum Option_i32 {
    Some(i32),
    None,
}

enum Option_f64 {
    Some(f64),
    None,
}

fn main() {
    let integer = Option_i32::Some(5);
    let float = Option_f64::Some(5.0);
}
```
 The generic `Option<T>` is replaced with the specific definitions created by the compiler. Because Rust compiles generic code into code that specifies the type in each instance, we pay no runtime cost for using generics. When the code runs, it performs just as it would if we had duplicated each definition by hand. The process of monomorphization makes Rust’s generics extremely efficient at runtime.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch10-01-syntax.html>

Validating References with Lifetimes
====================================

 Lifetimes are another kind of generic that we’ve already been using. Rather than ensuring that a type has the behavior we want, lifetimes ensure that references are valid as long as we need them to be.

 One detail we didn’t discuss in the [“References and Borrowing”](ch04-02-references-and-borrowing#references-and-borrowing) section in Chapter 4 is that every reference in Rust has a *lifetime*, which is the scope for which that reference is valid. Most of the time, lifetimes are implicit and inferred, just like most of the time, types are inferred. We only must annotate types when multiple types are possible. In a similar way, we must annotate lifetimes when the lifetimes of references could be related in a few different ways. Rust requires us to annotate the relationships using generic lifetime parameters to ensure the actual references used at runtime will definitely be valid.

 Annotating lifetimes is not even a concept most other programming languages have, so this is going to feel unfamiliar. Although we won’t cover lifetimes in their entirety in this chapter, we’ll discuss common ways you might encounter lifetime syntax so you can get comfortable with the concept.

 ### Preventing Dangling References with Lifetimes

 The main aim of lifetimes is to prevent *dangling references*, which cause a program to reference data other than the data it’s intended to reference. Consider the program in Listing 10-16, which has an outer scope and an inner scope.

 
```
fn main() {
    let r;

    {
        let x = 5;
        r = &x;
    }

    println!("r: {}", r);
}
```
 Listing 10-16: An attempt to use a reference whose value has gone out of scope

 
>  Note: The examples in Listings 10-16, 10-17, and 10-23 declare variables without giving them an initial value, so the variable name exists in the outer scope. At first glance, this might appear to be in conflict with Rust’s having no null values. However, if we try to use a variable before giving it a value, we’ll get a compile-time error, which shows that Rust indeed does not allow null values.
> 
>  

 The outer scope declares a variable named `r` with no initial value, and the inner scope declares a variable named `x` with the initial value of 5. Inside the inner scope, we attempt to set the value of `r` as a reference to `x`. Then the inner scope ends, and we attempt to print the value in `r`. This code won’t compile because the value `r` is referring to has gone out of scope before we try to use it. Here is the error message:

 
```
$ cargo run
   Compiling chapter10 v0.1.0 (file:///projects/chapter10)
error[E0597]: `x` does not live long enough
 --> src/main.rs:6:13
  |
6 |         r = &x;
  |             ^^ borrowed value does not live long enough
7 |     }
  |     - `x` dropped here while still borrowed
8 |
9 |     println!("r: {}", r);
  |                       - borrow later used here

For more information about this error, try `rustc --explain E0597`.
error: could not compile `chapter10` due to previous error

```
 The variable `x` doesn’t “live long enough.” The reason is that `x` will be out of scope when the inner scope ends on line 7. But `r` is still valid for the outer scope; because its scope is larger, we say that it “lives longer.” If Rust allowed this code to work, `r` would be referencing memory that was deallocated when `x` went out of scope, and anything we tried to do with `r` wouldn’t work correctly. So how does Rust determine that this code is invalid? It uses a borrow checker.

 ### The Borrow Checker

 The Rust compiler has a *borrow checker* that compares scopes to determine whether all borrows are valid. Listing 10-17 shows the same code as Listing 10-16 but with annotations showing the lifetimes of the variables.

 
```
fn main() {
    let r;                // ---------+-- 'a
                          //          |
    {                     //          |
        let x = 5;        // -+-- 'b  |
        r = &x;           //  |       |
    }                     // -+       |
                          //          |
    println!("r: {}", r); //          |
}                         // ---------+
```
 Listing 10-17: Annotations of the lifetimes of `r` and `x`, named `'a` and `'b`, respectively

 Here, we’ve annotated the lifetime of `r` with `'a` and the lifetime of `x` with `'b`. As you can see, the inner `'b` block is much smaller than the outer `'a` lifetime block. At compile time, Rust compares the size of the two lifetimes and sees that `r` has a lifetime of `'a` but that it refers to memory with a lifetime of `'b`. The program is rejected because `'b` is shorter than `'a`: the subject of the reference doesn’t live as long as the reference.

 Listing 10-18 fixes the code so it doesn’t have a dangling reference and compiles without any errors.

 
```
fn main() {
    let x = 5;            // ----------+-- 'b
                          //           |
    let r = &x;           // --+-- 'a  |
                          //   |       |
    println!("r: {}", r); //   |       |
                          // --+       |
}                         // ----------+
```
 Listing 10-18: A valid reference because the data has a longer lifetime than the reference

 Here, `x` has the lifetime `'b`, which in this case is larger than `'a`. This means `r` can reference `x` because Rust knows that the reference in `r` will always be valid while `x` is valid.

 Now that you know where the lifetimes of references are and how Rust analyzes lifetimes to ensure references will always be valid, let’s explore generic lifetimes of parameters and return values in the context of functions.

 ### Generic Lifetimes in Functions

 We’ll write a function that returns the longer of two string slices. This function will take two string slices and return a single string slice. After we’ve implemented the `longest` function, the code in Listing 10-19 should print `The longest string is abcd`.

 Filename: src/main.rs

 
```
fn main() {
    let string1 = String::from("abcd");
    let string2 = "xyz";

    let result = longest(string1.as_str(), string2);
    println!("The longest string is {}", result);
}
```
 Listing 10-19: A `main` function that calls the `longest` function to find the longer of two string slices

 Note that we want the function to take string slices, which are references, rather than strings, because we don’t want the `longest` function to take ownership of its parameters. Refer to the [“String Slices as Parameters”](ch04-03-slices#string-slices-as-parameters) section in Chapter 4 for more discussion about why the parameters we use in Listing 10-19 are the ones we want.

 If we try to implement the `longest` function as shown in Listing 10-20, it won’t compile.

 Filename: src/main.rs

 
```
fn main() {
    let string1 = String::from("abcd");
    let string2 = "xyz";

    let result = longest(string1.as_str(), string2);
    println!("The longest string is {}", result);
}

fn longest(x: &str, y: &str) -> &str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}
```
 Listing 10-20: An implementation of the `longest` function that returns the longer of two string slices but does not yet compile

 Instead, we get the following error that talks about lifetimes:

 
```
$ cargo run
   Compiling chapter10 v0.1.0 (file:///projects/chapter10)
error[E0106]: missing lifetime specifier
 --> src/main.rs:9:33
  |
9 | fn longest(x: &str, y: &str) -> &str {
  |               ----     ----     ^ expected named lifetime parameter
  |
  = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `x` or `y`
help: consider introducing a named lifetime parameter
  |
9 | fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
  |           ++++     ++          ++          ++

For more information about this error, try `rustc --explain E0106`.
error: could not compile `chapter10` due to previous error

```
 The help text reveals that the return type needs a generic lifetime parameter on it because Rust can’t tell whether the reference being returned refers to `x` or `y`. Actually, we don’t know either, because the `if` block in the body of this function returns a reference to `x` and the `else` block returns a reference to `y`!

 When we’re defining this function, we don’t know the concrete values that will be passed into this function, so we don’t know whether the `if` case or the `else` case will execute. We also don’t know the concrete lifetimes of the references that will be passed in, so we can’t look at the scopes as we did in Listings 10-17 and 10-18 to determine whether the reference we return will always be valid. The borrow checker can’t determine this either, because it doesn’t know how the lifetimes of `x` and `y` relate to the lifetime of the return value. To fix this error, we’ll add generic lifetime parameters that define the relationship between the references so the borrow checker can perform its analysis.

 ### Lifetime Annotation Syntax

 Lifetime annotations don’t change how long any of the references live. Rather, they describe the relationships of the lifetimes of multiple references to each other without affecting the lifetimes. Just as functions can accept any type when the signature specifies a generic type parameter, functions can accept references with any lifetime by specifying a generic lifetime parameter.

 Lifetime annotations have a slightly unusual syntax: the names of lifetime parameters must start with an apostrophe (`'`) and are usually all lowercase and very short, like generic types. Most people use the name `'a` for the first lifetime annotation. We place lifetime parameter annotations after the `&` of a reference, using a space to separate the annotation from the reference’s type.

 Here are some examples: a reference to an `i32` without a lifetime parameter, a reference to an `i32` that has a lifetime parameter named `'a`, and a mutable reference to an `i32` that also has the lifetime `'a`.

 
```
&i32        // a reference
&'a i32     // a reference with an explicit lifetime
&'a mut i32 // a mutable reference with an explicit lifetime
```
 One lifetime annotation by itself doesn’t have much meaning, because the annotations are meant to tell Rust how generic lifetime parameters of multiple references relate to each other. Let’s examine how the lifetime annotations relate to each other in the context of the `longest` function.

 ### Lifetime Annotations in Function Signatures

 To use lifetime annotations in function signatures, we need to declare the generic *lifetime* parameters inside angle brackets between the function name and the parameter list, just as we did with generic *type* parameters.

 We want the signature to express the following constraint: the returned reference will be valid as long as both the parameters are valid. This is the relationship between lifetimes of the parameters and the return value. We’ll name the lifetime `'a` and then add it to each reference, as shown in Listing 10-21.

 Filename: src/main.rs

 
```
fn main() {
    let string1 = String::from("abcd");
    let string2 = "xyz";

    let result = longest(string1.as_str(), string2);
    println!("The longest string is {}", result);
}

fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}
```
 Listing 10-21: The `longest` function definition specifying that all the references in the signature must have the same lifetime `'a`

 This code should compile and produce the result we want when we use it with the `main` function in Listing 10-19.

 The function signature now tells Rust that for some lifetime `'a`, the function takes two parameters, both of which are string slices that live at least as long as lifetime `'a`. The function signature also tells Rust that the string slice returned from the function will live at least as long as lifetime `'a`. In practice, it means that the lifetime of the reference returned by the `longest` function is the same as the smaller of the lifetimes of the values referred to by the function arguments. These relationships are what we want Rust to use when analyzing this code.

 Remember, when we specify the lifetime parameters in this function signature, we’re not changing the lifetimes of any values passed in or returned. Rather, we’re specifying that the borrow checker should reject any values that don’t adhere to these constraints. Note that the `longest` function doesn’t need to know exactly how long `x` and `y` will live, only that some scope can be substituted for `'a` that will satisfy this signature.

 When annotating lifetimes in functions, the annotations go in the function signature, not in the function body. The lifetime annotations become part of the contract of the function, much like the types in the signature. Having function signatures contain the lifetime contract means the analysis the Rust compiler does can be simpler. If there’s a problem with the way a function is annotated or the way it is called, the compiler errors can point to the part of our code and the constraints more precisely. If, instead, the Rust compiler made more inferences about what we intended the relationships of the lifetimes to be, the compiler might only be able to point to a use of our code many steps away from the cause of the problem.

 When we pass concrete references to `longest`, the concrete lifetime that is substituted for `'a` is the part of the scope of `x` that overlaps with the scope of `y`. In other words, the generic lifetime `'a` will get the concrete lifetime that is equal to the smaller of the lifetimes of `x` and `y`. Because we’ve annotated the returned reference with the same lifetime parameter `'a`, the returned reference will also be valid for the length of the smaller of the lifetimes of `x` and `y`.

 Let’s look at how the lifetime annotations restrict the `longest` function by passing in references that have different concrete lifetimes. Listing 10-22 is a straightforward example.

 Filename: src/main.rs

 
```
fn main() {
    let string1 = String::from("long string is long");

    {
        let string2 = String::from("xyz");
        let result = longest(string1.as_str(), string2.as_str());
        println!("The longest string is {}", result);
    }
}

fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}
```
 Listing 10-22: Using the `longest` function with references to `String` values that have different concrete lifetimes

 In this example, `string1` is valid until the end of the outer scope, `string2` is valid until the end of the inner scope, and `result` references something that is valid until the end of the inner scope. Run this code, and you’ll see that the borrow checker approves; it will compile and print `The longest string is long string is long`.

 Next, let’s try an example that shows that the lifetime of the reference in `result` must be the smaller lifetime of the two arguments. We’ll move the declaration of the `result` variable outside the inner scope but leave the assignment of the value to the `result` variable inside the scope with `string2`. Then we’ll move the `println!` that uses `result` to outside the inner scope, after the inner scope has ended. The code in Listing 10-23 will not compile.

 Filename: src/main.rs

 
```
fn main() {
    let string1 = String::from("long string is long");
    let result;
    {
        let string2 = String::from("xyz");
        result = longest(string1.as_str(), string2.as_str());
    }
    println!("The longest string is {}", result);
}

fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}
```
 Listing 10-23: Attempting to use `result` after `string2` has gone out of scope

 When we try to compile this code, we get this error:

 
```
$ cargo run
   Compiling chapter10 v0.1.0 (file:///projects/chapter10)
error[E0597]: `string2` does not live long enough
 --> src/main.rs:6:44
  |
6 |         result = longest(string1.as_str(), string2.as_str());
  |                                            ^^^^^^^^^^^^^^^^ borrowed value does not live long enough
7 |     }
  |     - `string2` dropped here while still borrowed
8 |     println!("The longest string is {}", result);
  |                                          ------ borrow later used here

For more information about this error, try `rustc --explain E0597`.
error: could not compile `chapter10` due to previous error

```
 The error shows that for `result` to be valid for the `println!` statement, `string2` would need to be valid until the end of the outer scope. Rust knows this because we annotated the lifetimes of the function parameters and return values using the same lifetime parameter `'a`.

 As humans, we can look at this code and see that `string1` is longer than `string2` and therefore `result` will contain a reference to `string1`. Because `string1` has not gone out of scope yet, a reference to `string1` will still be valid for the `println!` statement. However, the compiler can’t see that the reference is valid in this case. We’ve told Rust that the lifetime of the reference returned by the `longest` function is the same as the smaller of the lifetimes of the references passed in. Therefore, the borrow checker disallows the code in Listing 10-23 as possibly having an invalid reference.

 Try designing more experiments that vary the values and lifetimes of the references passed in to the `longest` function and how the returned reference is used. Make hypotheses about whether or not your experiments will pass the borrow checker before you compile; then check to see if you’re right!

 ### Thinking in Terms of Lifetimes

 The way in which you need to specify lifetime parameters depends on what your function is doing. For example, if we changed the implementation of the `longest` function to always return the first parameter rather than the longest string slice, we wouldn’t need to specify a lifetime on the `y` parameter. The following code will compile:

 Filename: src/main.rs

 
```
fn main() {
    let string1 = String::from("abcd");
    let string2 = "efghijklmnopqrstuvwxyz";

    let result = longest(string1.as_str(), string2);
    println!("The longest string is {}", result);
}

fn longest<'a>(x: &'a str, y: &str) -> &'a str {
    x
}
```
 We’ve specified a lifetime parameter `'a` for the parameter `x` and the return type, but not for the parameter `y`, because the lifetime of `y` does not have any relationship with the lifetime of `x` or the return value.

 When returning a reference from a function, the lifetime parameter for the return type needs to match the lifetime parameter for one of the parameters. If the reference returned does *not* refer to one of the parameters, it must refer to a value created within this function. However, this would be a dangling reference because the value will go out of scope at the end of the function. Consider this attempted implementation of the `longest` function that won’t compile:

 Filename: src/main.rs

 
```
fn main() {
    let string1 = String::from("abcd");
    let string2 = "xyz";

    let result = longest(string1.as_str(), string2);
    println!("The longest string is {}", result);
}

fn longest<'a>(x: &str, y: &str) -> &'a str {
    let result = String::from("really long string");
    result.as_str()
}
```
 Here, even though we’ve specified a lifetime parameter `'a` for the return type, this implementation will fail to compile because the return value lifetime is not related to the lifetime of the parameters at all. Here is the error message we get:

 
```
$ cargo run
   Compiling chapter10 v0.1.0 (file:///projects/chapter10)
error[E0515]: cannot return reference to local variable `result`
  --> src/main.rs:11:5
   |
11 |     result.as_str()
   |     ^^^^^^^^^^^^^^^ returns a reference to data owned by the current function

For more information about this error, try `rustc --explain E0515`.
error: could not compile `chapter10` due to previous error

```
 The problem is that `result` goes out of scope and gets cleaned up at the end of the `longest` function. We’re also trying to return a reference to `result` from the function. There is no way we can specify lifetime parameters that would change the dangling reference, and Rust won’t let us create a dangling reference. In this case, the best fix would be to return an owned data type rather than a reference so the calling function is then responsible for cleaning up the value.

 Ultimately, lifetime syntax is about connecting the lifetimes of various parameters and return values of functions. Once they’re connected, Rust has enough information to allow memory-safe operations and disallow operations that would create dangling pointers or otherwise violate memory safety.

 ### Lifetime Annotations in Struct Definitions

 So far, the structs we’ve defined all hold owned types. We can define structs to hold references, but in that case we would need to add a lifetime annotation on every reference in the struct’s definition. Listing 10-24 has a struct named `ImportantExcerpt` that holds a string slice.

 Filename: src/main.rs

 
```
struct ImportantExcerpt<'a> {
    part: &'a str,
}

fn main() {
    let novel = String::from("Call me Ishmael. Some years ago...");
    let first_sentence = novel.split('.').next().expect("Could not find a '.'");
    let i = ImportantExcerpt {
        part: first_sentence,
    };
}
```
 Listing 10-24: A struct that holds a reference, requiring a lifetime annotation

 This struct has the single field `part` that holds a string slice, which is a reference. As with generic data types, we declare the name of the generic lifetime parameter inside angle brackets after the name of the struct so we can use the lifetime parameter in the body of the struct definition. This annotation means an instance of `ImportantExcerpt` can’t outlive the reference it holds in its `part` field.

 The `main` function here creates an instance of the `ImportantExcerpt` struct that holds a reference to the first sentence of the `String` owned by the variable `novel`. The data in `novel` exists before the `ImportantExcerpt` instance is created. In addition, `novel` doesn’t go out of scope until after the `ImportantExcerpt` goes out of scope, so the reference in the `ImportantExcerpt` instance is valid.

 ### Lifetime Elision

 You’ve learned that every reference has a lifetime and that you need to specify lifetime parameters for functions or structs that use references. However, in Chapter 4 we had a function in Listing 4-9, shown again in Listing 10-25, that compiled without lifetime annotations.

 Filename: src/lib.rs

 
```
fn first_word(s: &str) -> &str {
    let bytes = s.as_bytes();

    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return &s[0..i];
        }
    }

    &s[..]
}

fn main() {
    let my_string = String::from("hello world");

    // first_word works on slices of `String`s
    let word = first_word(&my_string[..]);

    let my_string_literal = "hello world";

    // first_word works on slices of string literals
    let word = first_word(&my_string_literal[..]);

    // Because string literals *are* string slices already,
    // this works too, without the slice syntax!
    let word = first_word(my_string_literal);
}
```
 Listing 10-25: A function we defined in Listing 4-9 that compiled without lifetime annotations, even though the parameter and return type are references

 The reason this function compiles without lifetime annotations is historical: in early versions (pre-1.0) of Rust, this code wouldn’t have compiled because every reference needed an explicit lifetime. At that time, the function signature would have been written like this:

 
```
fn first_word<'a>(s: &'a str) -> &'a str {
```
 After writing a lot of Rust code, the Rust team found that Rust programmers were entering the same lifetime annotations over and over in particular situations. These situations were predictable and followed a few deterministic patterns. The developers programmed these patterns into the compiler’s code so the borrow checker could infer the lifetimes in these situations and wouldn’t need explicit annotations.

 This piece of Rust history is relevant because it’s possible that more deterministic patterns will emerge and be added to the compiler. In the future, even fewer lifetime annotations might be required.

 The patterns programmed into Rust’s analysis of references are called the *lifetime elision rules*. These aren’t rules for programmers to follow; they’re a set of particular cases that the compiler will consider, and if your code fits these cases, you don’t need to write the lifetimes explicitly.

 The elision rules don’t provide full inference. If Rust deterministically applies the rules but there is still ambiguity as to what lifetimes the references have, the compiler won’t guess what the lifetime of the remaining references should be. Instead of guessing, the compiler will give you an error that you can resolve by adding the lifetime annotations.

 Lifetimes on function or method parameters are called *input lifetimes*, and lifetimes on return values are called *output lifetimes*.

 The compiler uses three rules to figure out the lifetimes of the references when there aren’t explicit annotations. The first rule applies to input lifetimes, and the second and third rules apply to output lifetimes. If the compiler gets to the end of the three rules and there are still references for which it can’t figure out lifetimes, the compiler will stop with an error. These rules apply to `fn` definitions as well as `impl` blocks.

 The first rule is that the compiler assigns a lifetime parameter to each parameter that’s a reference. In other words, a function with one parameter gets one lifetime parameter: `fn foo<'a>(x: &'a i32)`; a function with two parameters gets two separate lifetime parameters: `fn foo<'a, 'b>(x: &'a i32, y: &'b i32)`; and so on.

 The second rule is that, if there is exactly one input lifetime parameter, that lifetime is assigned to all output lifetime parameters: `fn foo<'a>(x: &'a i32) -> &'a i32`.

 The third rule is that, if there are multiple input lifetime parameters, but one of them is `&self` or `&mut self` because this is a method, the lifetime of `self` is assigned to all output lifetime parameters. This third rule makes methods much nicer to read and write because fewer symbols are necessary.

 Let’s pretend we’re the compiler. We’ll apply these rules to figure out the lifetimes of the references in the signature of the `first_word` function in Listing 10-25. The signature starts without any lifetimes associated with the references:

 
```
fn first_word(s: &str) -> &str {
```
 Then the compiler applies the first rule, which specifies that each parameter gets its own lifetime. We’ll call it `'a` as usual, so now the signature is this:

 
```
fn first_word<'a>(s: &'a str) -> &str {
```
 The second rule applies because there is exactly one input lifetime. The second rule specifies that the lifetime of the one input parameter gets assigned to the output lifetime, so the signature is now this:

 
```
fn first_word<'a>(s: &'a str) -> &'a str {
```
 Now all the references in this function signature have lifetimes, and the compiler can continue its analysis without needing the programmer to annotate the lifetimes in this function signature.

 Let’s look at another example, this time using the `longest` function that had no lifetime parameters when we started working with it in Listing 10-20:

 
```
fn longest(x: &str, y: &str) -> &str {
```
 Let’s apply the first rule: each parameter gets its own lifetime. This time we have two parameters instead of one, so we have two lifetimes:

 
```
fn longest<'a, 'b>(x: &'a str, y: &'b str) -> &str {
```
 You can see that the second rule doesn’t apply because there is more than one input lifetime. The third rule doesn’t apply either, because `longest` is a function rather than a method, so none of the parameters are `self`. After working through all three rules, we still haven’t figured out what the return type’s lifetime is. This is why we got an error trying to compile the code in Listing 10-20: the compiler worked through the lifetime elision rules but still couldn’t figure out all the lifetimes of the references in the signature.

 Because the third rule really only applies in method signatures, we’ll look at lifetimes in that context next to see why the third rule means we don’t have to annotate lifetimes in method signatures very often.

 ### Lifetime Annotations in Method Definitions

 When we implement methods on a struct with lifetimes, we use the same syntax as that of generic type parameters shown in Listing 10-11. Where we declare and use the lifetime parameters depends on whether they’re related to the struct fields or the method parameters and return values.

 Lifetime names for struct fields always need to be declared after the `impl` keyword and then used after the struct’s name, because those lifetimes are part of the struct’s type.

 In method signatures inside the `impl` block, references might be tied to the lifetime of references in the struct’s fields, or they might be independent. In addition, the lifetime elision rules often make it so that lifetime annotations aren’t necessary in method signatures. Let’s look at some examples using the struct named `ImportantExcerpt` that we defined in Listing 10-24.

 First, we’ll use a method named `level` whose only parameter is a reference to `self` and whose return value is an `i32`, which is not a reference to anything:

 
```
struct ImportantExcerpt<'a> {
    part: &'a str,
}

impl<'a> ImportantExcerpt<'a> {
    fn level(&self) -> i32 {
        3
    }
}

impl<'a> ImportantExcerpt<'a> {
    fn announce_and_return_part(&self, announcement: &str) -> &str {
        println!("Attention please: {}", announcement);
        self.part
    }
}

fn main() {
    let novel = String::from("Call me Ishmael. Some years ago...");
    let first_sentence = novel.split('.').next().expect("Could not find a '.'");
    let i = ImportantExcerpt {
        part: first_sentence,
    };
}
```
 The lifetime parameter declaration after `impl` and its use after the type name are required, but we’re not required to annotate the lifetime of the reference to `self` because of the first elision rule.

 Here is an example where the third lifetime elision rule applies:

 
```
struct ImportantExcerpt<'a> {
    part: &'a str,
}

impl<'a> ImportantExcerpt<'a> {
    fn level(&self) -> i32 {
        3
    }
}

impl<'a> ImportantExcerpt<'a> {
    fn announce_and_return_part(&self, announcement: &str) -> &str {
        println!("Attention please: {}", announcement);
        self.part
    }
}

fn main() {
    let novel = String::from("Call me Ishmael. Some years ago...");
    let first_sentence = novel.split('.').next().expect("Could not find a '.'");
    let i = ImportantExcerpt {
        part: first_sentence,
    };
}
```
 There are two input lifetimes, so Rust applies the first lifetime elision rule and gives both `&self` and `announcement` their own lifetimes. Then, because one of the parameters is `&self`, the return type gets the lifetime of `&self`, and all lifetimes have been accounted for.

 ### The Static Lifetime

 One special lifetime we need to discuss is `'static`, which denotes that the affected reference *can* live for the entire duration of the program. All string literals have the `'static` lifetime, which we can annotate as follows:

 
```
#![allow(unused)]
fn main() {
let s: &'static str = "I have a static lifetime.";
}
```
 The text of this string is stored directly in the program’s binary, which is always available. Therefore, the lifetime of all string literals is `'static`.

 You might see suggestions to use the `'static` lifetime in error messages. But before specifying `'static` as the lifetime for a reference, think about whether the reference you have actually lives the entire lifetime of your program or not, and whether you want it to. Most of the time, an error message suggesting the `'static` lifetime results from attempting to create a dangling reference or a mismatch of the available lifetimes. In such cases, the solution is fixing those problems, not specifying the `'static` lifetime.

 Generic Type Parameters, Trait Bounds, and Lifetimes Together
-------------------------------------------------------------

 Let’s briefly look at the syntax of specifying generic type parameters, trait bounds, and lifetimes all in one function!

 
```
fn main() {
    let string1 = String::from("abcd");
    let string2 = "xyz";

    let result = longest_with_an_announcement(
        string1.as_str(),
        string2,
        "Today is someone's birthday!",
    );
    println!("The longest string is {}", result);
}

use std::fmt::Display;

fn longest_with_an_announcement<'a, T>(
    x: &'a str,
    y: &'a str,
    ann: T,
) -> &'a str
where
    T: Display,
{
    println!("Announcement! {}", ann);
    if x.len() > y.len() {
        x
    } else {
        y
    }
}
```
 This is the `longest` function from Listing 10-21 that returns the longer of two string slices. But now it has an extra parameter named `ann` of the generic type `T`, which can be filled in by any type that implements the `Display` trait as specified by the `where` clause. This extra parameter will be printed using `{}`, which is why the `Display` trait bound is necessary. Because lifetimes are a type of generic, the declarations of the lifetime parameter `'a` and the generic type parameter `T` go in the same list inside the angle brackets after the function name.

 Summary
-------

 We covered a lot in this chapter! Now that you know about generic type parameters, traits and trait bounds, and generic lifetime parameters, you’re ready to write code without repetition that works in many different situations. Generic type parameters let you apply the code to different types. Traits and trait bounds ensure that even though the types are generic, they’ll have the behavior the code needs. You learned how to use lifetime annotations to ensure that this flexible code won’t have any dangling references. And all of this analysis happens at compile time, which doesn’t affect runtime performance!

 Believe it or not, there is much more to learn on the topics we discussed in this chapter: Chapter 17 discusses trait objects, which are another way to use traits. There are also more complex scenarios involving lifetime annotations that you will only need in very advanced scenarios; for those, you should read the [Rust Reference](../reference/index). But next, you’ll learn how to write tests in Rust so you can make sure your code is working the way it should.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html>

Writing Automated Tests
=======================

 In his 1972 essay “The Humble Programmer,” Edsger W. Dijkstra said that “Program testing can be a very effective way to show the presence of bugs, but it is hopelessly inadequate for showing their absence.” That doesn’t mean we shouldn’t try to test as much as we can!

 Correctness in our programs is the extent to which our code does what we intend it to do. Rust is designed with a high degree of concern about the correctness of programs, but correctness is complex and not easy to prove. Rust’s type system shoulders a huge part of this burden, but the type system cannot catch everything. As such, Rust includes support for writing automated software tests.

 Say we write a function `add_two` that adds 2 to whatever number is passed to it. This function’s signature accepts an integer as a parameter and returns an integer as a result. When we implement and compile that function, Rust does all the type checking and borrow checking that you’ve learned so far to ensure that, for instance, we aren’t passing a `String` value or an invalid reference to this function. But Rust *can’t* check that this function will do precisely what we intend, which is return the parameter plus 2 rather than, say, the parameter plus 10 or the parameter minus 50! That’s where tests come in.

 We can write tests that assert, for example, that when we pass `3` to the `add_two` function, the returned value is `5`. We can run these tests whenever we make changes to our code to make sure any existing correct behavior has not changed.

 Testing is a complex skill: although we can’t cover every detail about how to write good tests in one chapter, we’ll discuss the mechanics of Rust’s testing facilities. We’ll talk about the annotations and macros available to you when writing your tests, the default behavior and options provided for running your tests, and how to organize tests into unit tests and integration tests.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch11-00-testing.html>

How to Write Tests
==================

 Tests are Rust functions that verify that the non-test code is functioning in the expected manner. The bodies of test functions typically perform these three actions:

 1. Set up any needed data or state.
2. Run the code you want to test.
3. Assert the results are what you expect.

 Let’s look at the features Rust provides specifically for writing tests that take these actions, which include the `test` attribute, a few macros, and the `should_panic` attribute.

 ### The Anatomy of a Test Function

 At its simplest, a test in Rust is a function that’s annotated with the `test` attribute. Attributes are metadata about pieces of Rust code; one example is the `derive` attribute we used with structs in Chapter 5. To change a function into a test function, add `#[test]` on the line before `fn`. When you run your tests with the `cargo test` command, Rust builds a test runner binary that runs the annotated functions and reports on whether each test function passes or fails.

 Whenever we make a new library project with Cargo, a test module with a test function in it is automatically generated for us. This module gives you a template for writing your tests so you don’t have to look up the exact structure and syntax every time you start a new project. You can add as many additional test functions and as many test modules as you want!

 We’ll explore some aspects of how tests work by experimenting with the template test before we actually test any code. Then we’ll write some real-world tests that call some code that we’ve written and assert that its behavior is correct.

 Let’s create a new library project called `adder` that will add two numbers:

 
```
$ cargo new adder --lib
     Created library `adder` project
$ cd adder

```
 The contents of the *src/lib.rs* file in your `adder` library should look like Listing 11-1.

 Filename: src/lib.rs

 
```
#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        let result = 2 + 2;
        assert_eq!(result, 4);
    }
}
```
 Listing 11-1: The test module and function generated automatically by `cargo new`

 For now, let’s ignore the top two lines and focus on the function. Note the `#[test]` annotation: this attribute indicates this is a test function, so the test runner knows to treat this function as a test. We might also have non-test functions in the `tests` module to help set up common scenarios or perform common operations, so we always need to indicate which functions are tests.

 The example function body uses the `assert_eq!` macro to assert that `result`, which contains the result of adding 2 and 2, equals 4. This assertion serves as an example of the format for a typical test. Let’s run it to see that this test passes.

 The `cargo test` command runs all tests in our project, as shown in Listing 11-2.

 
```
$ cargo test
   Compiling adder v0.1.0 (file:///projects/adder)
    Finished test [unoptimized + debuginfo] target(s) in 0.57s
     Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)

running 1 test
test tests::it_works ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests adder

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s


```
 Listing 11-2: The output from running the automatically generated test

 Cargo compiled and ran the test. We see the line `running 1 test`. The next line shows the name of the generated test function, called `it_works`, and that the result of running that test is `ok`. The overall summary `test result: ok.` means that all the tests passed, and the portion that reads `1 passed; 0 failed` totals the number of tests that passed or failed.

 It’s possible to mark a test as ignored so it doesn’t run in a particular instance; we’ll cover that in the [“Ignoring Some Tests Unless Specifically Requested”](ch11-02-running-tests#ignoring-some-tests-unless-specifically-requested) section later in this chapter. Because we haven’t done that here, the summary shows `0 ignored`. We can also pass an argument to the `cargo test` command to run only tests whose name matches a string; this is called *filtering* and we’ll cover that in the [“Running a Subset of Tests by Name”](ch11-02-running-tests#running-a-subset-of-tests-by-name) section. We also haven’t filtered the tests being run, so the end of the summary shows `0 filtered out`.

 The `0 measured` statistic is for benchmark tests that measure performance. Benchmark tests are, as of this writing, only available in nightly Rust. See [the documentation about benchmark tests](https://doc.rust-lang.org/unstable-book/library-features/test.html) to learn more.

 The next part of the test output starting at `Doc-tests adder` is for the results of any documentation tests. We don’t have any documentation tests yet, but Rust can compile any code examples that appear in our API documentation. This feature helps keep your docs and your code in sync! We’ll discuss how to write documentation tests in the [“Documentation Comments as Tests”](ch14-02-publishing-to-crates-io#documentation-comments-as-tests) section of Chapter 14. For now, we’ll ignore the `Doc-tests` output.

 Let’s start to customize the test to our own needs. First change the name of the `it_works` function to a different name, such as `exploration`, like so:

 Filename: src/lib.rs

 
```
#[cfg(test)]
mod tests {
    #[test]
    fn exploration() {
        assert_eq!(2 + 2, 4);
    }
}
```
 Then run `cargo test` again. The output now shows `exploration` instead of `it_works`:

 
```
$ cargo test
   Compiling adder v0.1.0 (file:///projects/adder)
    Finished test [unoptimized + debuginfo] target(s) in 0.59s
     Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)

running 1 test
test tests::exploration ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests adder

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s


```
 Now we’ll add another test, but this time we’ll make a test that fails! Tests fail when something in the test function panics. Each test is run in a new thread, and when the main thread sees that a test thread has died, the test is marked as failed. In Chapter 9, we talked about how the simplest way to panic is to call the `panic!` macro. Enter the new test as a function named `another`, so your *src/lib.rs* file looks like Listing 11-3.

 Filename: src/lib.rs

 
```
#[cfg(test)]
mod tests {
    #[test]
    fn exploration() {
        assert_eq!(2 + 2, 4);
    }

    #[test]
    fn another() {
        panic!("Make this test fail");
    }
}
```
 Listing 11-3: Adding a second test that will fail because we call the `panic!` macro

 Run the tests again using `cargo test`. The output should look like Listing 11-4, which shows that our `exploration` test passed and `another` failed.

 
```
$ cargo test
   Compiling adder v0.1.0 (file:///projects/adder)
    Finished test [unoptimized + debuginfo] target(s) in 0.72s
     Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)

running 2 tests
test tests::another ... FAILED
test tests::exploration ... ok

failures:

---- tests::another stdout ----
thread 'tests::another' panicked at 'Make this test fail', src/lib.rs:10:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace


failures:
    tests::another

test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

error: test failed, to rerun pass `--lib`

```
 Listing 11-4: Test results when one test passes and one test fails

 Instead of `ok`, the line `test tests::another` shows `FAILED`. Two new sections appear between the individual results and the summary: the first displays the detailed reason for each test failure. In this case, we get the details that `another` failed because it `panicked at 'Make this test fail'` on line 10 in the *src/lib.rs* file. The next section lists just the names of all the failing tests, which is useful when there are lots of tests and lots of detailed failing test output. We can use the name of a failing test to run just that test to more easily debug it; we’ll talk more about ways to run tests in the [“Controlling How Tests Are Run”](ch11-02-running-tests#controlling-how-tests-are-run) section.

 The summary line displays at the end: overall, our test result is `FAILED`. We had one test pass and one test fail.

 Now that you’ve seen what the test results look like in different scenarios, let’s look at some macros other than `panic!` that are useful in tests.

 ### Checking Results with the `assert!` Macro

 The `assert!` macro, provided by the standard library, is useful when you want to ensure that some condition in a test evaluates to `true`. We give the `assert!` macro an argument that evaluates to a Boolean. If the value is `true`, nothing happens and the test passes. If the value is `false`, the `assert!` macro calls `panic!` to cause the test to fail. Using the `assert!` macro helps us check that our code is functioning in the way we intend.

 In Chapter 5, Listing 5-15, we used a `Rectangle` struct and a `can_hold` method, which are repeated here in Listing 11-5. Let’s put this code in the *src/lib.rs* file, then write some tests for it using the `assert!` macro.

 Filename: src/lib.rs

 
```
#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn can_hold(&self, other: &Rectangle) -> bool {
        self.width > other.width && self.height > other.height
    }
}
```
 Listing 11-5: Using the `Rectangle` struct and its `can_hold` method from Chapter 5

 The `can_hold` method returns a Boolean, which means it’s a perfect use case for the `assert!` macro. In Listing 11-6, we write a test that exercises the `can_hold` method by creating a `Rectangle` instance that has a width of 8 and a height of 7 and asserting that it can hold another `Rectangle` instance that has a width of 5 and a height of 1.

 Filename: src/lib.rs

 
```
#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn can_hold(&self, other: &Rectangle) -> bool {
        self.width > other.width && self.height > other.height
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn larger_can_hold_smaller() {
        let larger = Rectangle {
            width: 8,
            height: 7,
        };
        let smaller = Rectangle {
            width: 5,
            height: 1,
        };

        assert!(larger.can_hold(&smaller));
    }
}
```
 Listing 11-6: A test for `can_hold` that checks whether a larger rectangle can indeed hold a smaller rectangle

 Note that we’ve added a new line inside the `tests` module: `use super::*;`. The `tests` module is a regular module that follows the usual visibility rules we covered in Chapter 7 in the [“Paths for Referring to an Item in the Module Tree”](ch07-03-paths-for-referring-to-an-item-in-the-module-tree) section. Because the `tests` module is an inner module, we need to bring the code under test in the outer module into the scope of the inner module. We use a glob here so anything we define in the outer module is available to this `tests` module.

 We’ve named our test `larger_can_hold_smaller`, and we’ve created the two `Rectangle` instances that we need. Then we called the `assert!` macro and passed it the result of calling `larger.can_hold(&smaller)`. This expression is supposed to return `true`, so our test should pass. Let’s find out!

 
```
$ cargo test
   Compiling rectangle v0.1.0 (file:///projects/rectangle)
    Finished test [unoptimized + debuginfo] target(s) in 0.66s
     Running unittests src/lib.rs (target/debug/deps/rectangle-6584c4561e48942e)

running 1 test
test tests::larger_can_hold_smaller ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests rectangle

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s


```
 It does pass! Let’s add another test, this time asserting that a smaller rectangle cannot hold a larger rectangle:

 Filename: src/lib.rs

 
```
#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn can_hold(&self, other: &Rectangle) -> bool {
        self.width > other.width && self.height > other.height
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn larger_can_hold_smaller() {
        // --snip--
        let larger = Rectangle {
            width: 8,
            height: 7,
        };
        let smaller = Rectangle {
            width: 5,
            height: 1,
        };

        assert!(larger.can_hold(&smaller));
    }

    #[test]
    fn smaller_cannot_hold_larger() {
        let larger = Rectangle {
            width: 8,
            height: 7,
        };
        let smaller = Rectangle {
            width: 5,
            height: 1,
        };

        assert!(!smaller.can_hold(&larger));
    }
}
```
 Because the correct result of the `can_hold` function in this case is `false`, we need to negate that result before we pass it to the `assert!` macro. As a result, our test will pass if `can_hold` returns `false`:

 
```
$ cargo test
   Compiling rectangle v0.1.0 (file:///projects/rectangle)
    Finished test [unoptimized + debuginfo] target(s) in 0.66s
     Running unittests src/lib.rs (target/debug/deps/rectangle-6584c4561e48942e)

running 2 tests
test tests::larger_can_hold_smaller ... ok
test tests::smaller_cannot_hold_larger ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests rectangle

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s


```
 Two tests that pass! Now let’s see what happens to our test results when we introduce a bug in our code. We’ll change the implementation of the `can_hold` method by replacing the greater-than sign with a less-than sign when it compares the widths:

 
```
#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

// --snip--
impl Rectangle {
    fn can_hold(&self, other: &Rectangle) -> bool {
        self.width < other.width && self.height > other.height
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn larger_can_hold_smaller() {
        let larger = Rectangle {
            width: 8,
            height: 7,
        };
        let smaller = Rectangle {
            width: 5,
            height: 1,
        };

        assert!(larger.can_hold(&smaller));
    }

    #[test]
    fn smaller_cannot_hold_larger() {
        let larger = Rectangle {
            width: 8,
            height: 7,
        };
        let smaller = Rectangle {
            width: 5,
            height: 1,
        };

        assert!(!smaller.can_hold(&larger));
    }
}
```
 Running the tests now produces the following:

 
```
$ cargo test
   Compiling rectangle v0.1.0 (file:///projects/rectangle)
    Finished test [unoptimized + debuginfo] target(s) in 0.66s
     Running unittests src/lib.rs (target/debug/deps/rectangle-6584c4561e48942e)

running 2 tests
test tests::larger_can_hold_smaller ... FAILED
test tests::smaller_cannot_hold_larger ... ok

failures:

---- tests::larger_can_hold_smaller stdout ----
thread 'tests::larger_can_hold_smaller' panicked at 'assertion failed: larger.can_hold(&smaller)', src/lib.rs:28:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace


failures:
    tests::larger_can_hold_smaller

test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

error: test failed, to rerun pass `--lib`

```
 Our tests caught the bug! Because `larger.width` is 8 and `smaller.width` is 5, the comparison of the widths in `can_hold` now returns `false`: 8 is not less than 5.

 ### Testing Equality with the `assert_eq!` and `assert_ne!` Macros

 A common way to verify functionality is to test for equality between the result of the code under test and the value you expect the code to return. You could do this using the `assert!` macro and passing it an expression using the `==` operator. However, this is such a common test that the standard library provides a pair of macros—`assert_eq!` and `assert_ne!`—to perform this test more conveniently. These macros compare two arguments for equality or inequality, respectively. They’ll also print the two values if the assertion fails, which makes it easier to see *why* the test failed; conversely, the `assert!` macro only indicates that it got a `false` value for the `==` expression, without printing the values that led to the `false` value.

 In Listing 11-7, we write a function named `add_two` that adds `2` to its parameter, then we test this function using the `assert_eq!` macro.

 Filename: src/lib.rs

 
```
pub fn add_two(a: i32) -> i32 {
    a + 2
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_adds_two() {
        assert_eq!(4, add_two(2));
    }
}
```
 Listing 11-7: Testing the function `add_two` using the `assert_eq!` macro

 Let’s check that it passes!

 
```
$ cargo test
   Compiling adder v0.1.0 (file:///projects/adder)
    Finished test [unoptimized + debuginfo] target(s) in 0.58s
     Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)

running 1 test
test tests::it_adds_two ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests adder

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s


```
 We pass `4` as the argument to `assert_eq!`, which is equal to the result of calling `add_two(2)`. The line for this test is `test tests::it_adds_two ... ok`, and the `ok` text indicates that our test passed!

 Let’s introduce a bug into our code to see what `assert_eq!` looks like when it fails. Change the implementation of the `add_two` function to instead add `3`:

 
```
pub fn add_two(a: i32) -> i32 {
    a + 3
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_adds_two() {
        assert_eq!(4, add_two(2));
    }
}
```
 Run the tests again:

 
```
$ cargo test
   Compiling adder v0.1.0 (file:///projects/adder)
    Finished test [unoptimized + debuginfo] target(s) in 0.61s
     Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)

running 1 test
test tests::it_adds_two ... FAILED

failures:

---- tests::it_adds_two stdout ----
thread 'tests::it_adds_two' panicked at 'assertion failed: `(left == right)`
  left: `4`,
 right: `5`', src/lib.rs:11:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace


failures:
    tests::it_adds_two

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

error: test failed, to rerun pass `--lib`

```
 Our test caught the bug! The `it_adds_two` test failed, and the message tells us that the assertion that fails was `assertion failed: `(left == right)`` and what the `left` and `right` values are. This message helps us start debugging: the `left` argument was `4` but the `right` argument, where we had `add_two(2)`, was `5`. You can imagine that this would be especially helpful when we have a lot of tests going on.

 Note that in some languages and test frameworks, the parameters to equality assertion functions are called `expected` and `actual`, and the order in which we specify the arguments matters. However, in Rust, they’re called `left` and `right`, and the order in which we specify the value we expect and the value the code produces doesn’t matter. We could write the assertion in this test as `assert_eq!(add_two(2), 4)`, which would result in the same failure message that displays `assertion failed: `(left == right)``.

 The `assert_ne!` macro will pass if the two values we give it are not equal and fail if they’re equal. This macro is most useful for cases when we’re not sure what a value *will* be, but we know what the value definitely *shouldn’t* be. For example, if we’re testing a function that is guaranteed to change its input in some way, but the way in which the input is changed depends on the day of the week that we run our tests, the best thing to assert might be that the output of the function is not equal to the input.

 Under the surface, the `assert_eq!` and `assert_ne!` macros use the operators `==` and `!=`, respectively. When the assertions fail, these macros print their arguments using debug formatting, which means the values being compared must implement the `PartialEq` and `Debug` traits. All primitive types and most of the standard library types implement these traits. For structs and enums that you define yourself, you’ll need to implement `PartialEq` to assert equality of those types. You’ll also need to implement `Debug` to print the values when the assertion fails. Because both traits are derivable traits, as mentioned in Listing 5-12 in Chapter 5, this is usually as straightforward as adding the `#[derive(PartialEq, Debug)]` annotation to your struct or enum definition. See Appendix C, [“Derivable Traits,”](appendix-03-derivable-traits) for more details about these and other derivable traits.

 ### Adding Custom Failure Messages

 You can also add a custom message to be printed with the failure message as optional arguments to the `assert!`, `assert_eq!`, and `assert_ne!` macros. Any arguments specified after the required arguments are passed along to the `format!` macro (discussed in Chapter 8 in the [“Concatenation with the `+` Operator or the `format!` Macro”](ch08-02-strings#concatenation-with-the--operator-or-the-format-macro) section), so you can pass a format string that contains `{}` placeholders and values to go in those placeholders. Custom messages are useful for documenting what an assertion means; when a test fails, you’ll have a better idea of what the problem is with the code.

 For example, let’s say we have a function that greets people by name and we want to test that the name we pass into the function appears in the output:

 Filename: src/lib.rs

 
```
pub fn greeting(name: &str) -> String {
    format!("Hello {}!", name)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn greeting_contains_name() {
        let result = greeting("Carol");
        assert!(result.contains("Carol"));
    }
}
```
 The requirements for this program haven’t been agreed upon yet, and we’re pretty sure the `Hello` text at the beginning of the greeting will change. We decided we don’t want to have to update the test when the requirements change, so instead of checking for exact equality to the value returned from the `greeting` function, we’ll just assert that the output contains the text of the input parameter.

 Now let’s introduce a bug into this code by changing `greeting` to exclude `name` to see what the default test failure looks like:

 
```
pub fn greeting(name: &str) -> String {
    String::from("Hello!")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn greeting_contains_name() {
        let result = greeting("Carol");
        assert!(result.contains("Carol"));
    }
}
```
 Running this test produces the following:

 
```
$ cargo test
   Compiling greeter v0.1.0 (file:///projects/greeter)
    Finished test [unoptimized + debuginfo] target(s) in 0.91s
     Running unittests src/lib.rs (target/debug/deps/greeter-170b942eb5bf5e3a)

running 1 test
test tests::greeting_contains_name ... FAILED

failures:

---- tests::greeting_contains_name stdout ----
thread 'tests::greeting_contains_name' panicked at 'assertion failed: result.contains(\"Carol\")', src/lib.rs:12:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace


failures:
    tests::greeting_contains_name

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

error: test failed, to rerun pass `--lib`

```
 This result just indicates that the assertion failed and which line the assertion is on. A more useful failure message would print the value from the `greeting` function. Let’s add a custom failure message composed of a format string with a placeholder filled in with the actual value we got from the `greeting` function:

 
```
pub fn greeting(name: &str) -> String {
    String::from("Hello!")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn greeting_contains_name() {
        let result = greeting("Carol");
        assert!(
            result.contains("Carol"),
            "Greeting did not contain name, value was `{}`",
            result
        );
    }
}
```
 Now when we run the test, we’ll get a more informative error message:

 
```
$ cargo test
   Compiling greeter v0.1.0 (file:///projects/greeter)
    Finished test [unoptimized + debuginfo] target(s) in 0.93s
     Running unittests src/lib.rs (target/debug/deps/greeter-170b942eb5bf5e3a)

running 1 test
test tests::greeting_contains_name ... FAILED

failures:

---- tests::greeting_contains_name stdout ----
thread 'tests::greeting_contains_name' panicked at 'Greeting did not contain name, value was `Hello!`', src/lib.rs:12:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace


failures:
    tests::greeting_contains_name

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

error: test failed, to rerun pass `--lib`

```
 We can see the value we actually got in the test output, which would help us debug what happened instead of what we were expecting to happen.

 ### Checking for Panics with `should_panic`

 In addition to checking return values, it’s important to check that our code handles error conditions as we expect. For example, consider the `Guess` type that we created in Chapter 9, Listing 9-13. Other code that uses `Guess` depends on the guarantee that `Guess` instances will contain only values between 1 and 100. We can write a test that ensures that attempting to create a `Guess` instance with a value outside that range panics.

 We do this by adding the attribute `should_panic` to our test function. The test passes if the code inside the function panics; the test fails if the code inside the function doesn’t panic.

 Listing 11-8 shows a test that checks that the error conditions of `Guess::new` happen when we expect them to.

 Filename: src/lib.rs

 
```
pub struct Guess {
    value: i32,
}

impl Guess {
    pub fn new(value: i32) -> Guess {
        if value < 1 || value > 100 {
            panic!("Guess value must be between 1 and 100, got {}.", value);
        }

        Guess { value }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    #[should_panic]
    fn greater_than_100() {
        Guess::new(200);
    }
}
```
 Listing 11-8: Testing that a condition will cause a `panic!`

 We place the `#[should_panic]` attribute after the `#[test]` attribute and before the test function it applies to. Let’s look at the result when this test passes:

 
```
$ cargo test
   Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
    Finished test [unoptimized + debuginfo] target(s) in 0.58s
     Running unittests src/lib.rs (target/debug/deps/guessing_game-57d70c3acb738f4d)

running 1 test
test tests::greater_than_100 - should panic ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests guessing_game

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s


```
 Looks good! Now let’s introduce a bug in our code by removing the condition that the `new` function will panic if the value is greater than 100:

 
```
pub struct Guess {
    value: i32,
}

// --snip--
impl Guess {
    pub fn new(value: i32) -> Guess {
        if value < 1 {
            panic!("Guess value must be between 1 and 100, got {}.", value);
        }

        Guess { value }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    #[should_panic]
    fn greater_than_100() {
        Guess::new(200);
    }
}
```
 When we run the test in Listing 11-8, it will fail:

 
```
$ cargo test
   Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
    Finished test [unoptimized + debuginfo] target(s) in 0.62s
     Running unittests src/lib.rs (target/debug/deps/guessing_game-57d70c3acb738f4d)

running 1 test
test tests::greater_than_100 - should panic ... FAILED

failures:

---- tests::greater_than_100 stdout ----
note: test did not panic as expected

failures:
    tests::greater_than_100

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

error: test failed, to rerun pass `--lib`

```
 We don’t get a very helpful message in this case, but when we look at the test function, we see that it’s annotated with `#[should_panic]`. The failure we got means that the code in the test function did not cause a panic.

 Tests that use `should_panic` can be imprecise. A `should_panic` test would pass even if the test panics for a different reason from the one we were expecting. To make `should_panic` tests more precise, we can add an optional `expected` parameter to the `should_panic` attribute. The test harness will make sure that the failure message contains the provided text. For example, consider the modified code for `Guess` in Listing 11-9 where the `new` function panics with different messages depending on whether the value is too small or too large.

 Filename: src/lib.rs

 
```
pub struct Guess {
    value: i32,
}

// --snip--

impl Guess {
    pub fn new(value: i32) -> Guess {
        if value < 1 {
            panic!(
                "Guess value must be greater than or equal to 1, got {}.",
                value
            );
        } else if value > 100 {
            panic!(
                "Guess value must be less than or equal to 100, got {}.",
                value
            );
        }

        Guess { value }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    #[should_panic(expected = "less than or equal to 100")]
    fn greater_than_100() {
        Guess::new(200);
    }
}
```
 Listing 11-9: Testing for a `panic!` with a panic message containing a specified substring

 This test will pass because the value we put in the `should_panic` attribute’s `expected` parameter is a substring of the message that the `Guess::new` function panics with. We could have specified the entire panic message that we expect, which in this case would be `Guess value must be less than or equal to 100, got 200.` What you choose to specify depends on how much of the panic message is unique or dynamic and how precise you want your test to be. In this case, a substring of the panic message is enough to ensure that the code in the test function executes the `else if value > 100` case.

 To see what happens when a `should_panic` test with an `expected` message fails, let’s again introduce a bug into our code by swapping the bodies of the `if value < 1` and the `else if value > 100` blocks:

 
```
pub struct Guess {
    value: i32,
}

impl Guess {
    pub fn new(value: i32) -> Guess {
        if value < 1 {
            panic!(
                "Guess value must be less than or equal to 100, got {}.",
                value
            );
        } else if value > 100 {
            panic!(
                "Guess value must be greater than or equal to 1, got {}.",
                value
            );
        }

        Guess { value }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    #[should_panic(expected = "less than or equal to 100")]
    fn greater_than_100() {
        Guess::new(200);
    }
}
```
 This time when we run the `should_panic` test, it will fail:

 
```
$ cargo test
   Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
    Finished test [unoptimized + debuginfo] target(s) in 0.66s
     Running unittests src/lib.rs (target/debug/deps/guessing_game-57d70c3acb738f4d)

running 1 test
test tests::greater_than_100 - should panic ... FAILED

failures:

---- tests::greater_than_100 stdout ----
thread 'tests::greater_than_100' panicked at 'Guess value must be greater than or equal to 1, got 200.', src/lib.rs:13:13
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
note: panic did not contain expected string
      panic message: `"Guess value must be greater than or equal to 1, got 200."`,
 expected substring: `"less than or equal to 100"`

failures:
    tests::greater_than_100

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

error: test failed, to rerun pass `--lib`

```
 The failure message indicates that this test did indeed panic as we expected, but the panic message did not include the expected string `'Guess value must be less than or equal to 100'`. The panic message that we did get in this case was `Guess value must be greater than or equal to 1, got 200.` Now we can start figuring out where our bug is!

 ### Using `Result<T, E>` in Tests

 Our tests so far all panic when they fail. We can also write tests that use `Result<T, E>`! Here’s the test from Listing 11-1, rewritten to use `Result<T, E>` and return an `Err` instead of panicking:

 
```
#[cfg(test)]
mod tests {
    #[test]
    fn it_works() -> Result<(), String> {
        if 2 + 2 == 4 {
            Ok(())
        } else {
            Err(String::from("two plus two does not equal four"))
        }
    }
}
```
 The `it_works` function now has the `Result<(), String>` return type. In the body of the function, rather than calling the `assert_eq!` macro, we return `Ok(())` when the test passes and an `Err` with a `String` inside when the test fails.

 Writing tests so they return a `Result<T, E>` enables you to use the question mark operator in the body of tests, which can be a convenient way to write tests that should fail if any operation within them returns an `Err` variant.

 You can’t use the `#[should_panic]` annotation on tests that use `Result<T, E>`. To assert that an operation returns an `Err` variant, *don’t* use the question mark operator on the `Result<T, E>` value. Instead, use `assert!(value.is_err())`.

 Now that you know several ways to write tests, let’s look at what is happening when we run our tests and explore the different options we can use with `cargo test`.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch11-01-writing-tests.html>

Controlling How Tests Are Run
=============================

 Just as `cargo run` compiles your code and then runs the resulting binary, `cargo test` compiles your code in test mode and runs the resulting test binary. The default behavior of the binary produced by `cargo test` is to run all the tests in parallel and capture output generated during test runs, preventing the output from being displayed and making it easier to read the output related to the test results. You can, however, specify command line options to change this default behavior.

 Some command line options go to `cargo test`, and some go to the resulting test binary. To separate these two types of arguments, you list the arguments that go to `cargo test` followed by the separator `--` and then the ones that go to the test binary. Running `cargo test --help` displays the options you can use with `cargo test`, and running `cargo test -- --help` displays the options you can use after the separator.

 ### Running Tests in Parallel or Consecutively

 When you run multiple tests, by default they run in parallel using threads, meaning they finish running faster and you get feedback quicker. Because the tests are running at the same time, you must make sure your tests don’t depend on each other or on any shared state, including a shared environment, such as the current working directory or environment variables.

 For example, say each of your tests runs some code that creates a file on disk named *test-output.txt* and writes some data to that file. Then each test reads the data in that file and asserts that the file contains a particular value, which is different in each test. Because the tests run at the same time, one test might overwrite the file in the time between another test writing and reading the file. The second test will then fail, not because the code is incorrect but because the tests have interfered with each other while running in parallel. One solution is to make sure each test writes to a different file; another solution is to run the tests one at a time.

 If you don’t want to run the tests in parallel or if you want more fine-grained control over the number of threads used, you can send the `--test-threads` flag and the number of threads you want to use to the test binary. Take a look at the following example:

 
```
$ cargo test -- --test-threads=1

```
 We set the number of test threads to `1`, telling the program not to use any parallelism. Running the tests using one thread will take longer than running them in parallel, but the tests won’t interfere with each other if they share state.

 ### Showing Function Output

 By default, if a test passes, Rust’s test library captures anything printed to standard output. For example, if we call `println!` in a test and the test passes, we won’t see the `println!` output in the terminal; we’ll see only the line that indicates the test passed. If a test fails, we’ll see whatever was printed to standard output with the rest of the failure message.

 As an example, Listing 11-10 has a silly function that prints the value of its parameter and returns 10, as well as a test that passes and a test that fails.

 Filename: src/lib.rs

 
```
fn prints_and_returns_10(a: i32) -> i32 {
    println!("I got the value {}", a);
    10
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn this_test_will_pass() {
        let value = prints_and_returns_10(4);
        assert_eq!(10, value);
    }

    #[test]
    fn this_test_will_fail() {
        let value = prints_and_returns_10(8);
        assert_eq!(5, value);
    }
}
```
 Listing 11-10: Tests for a function that calls `println!`

 When we run these tests with `cargo test`, we’ll see the following output:

 
```
$ cargo test
   Compiling silly-function v0.1.0 (file:///projects/silly-function)
    Finished test [unoptimized + debuginfo] target(s) in 0.58s
     Running unittests src/lib.rs (target/debug/deps/silly_function-160869f38cff9166)

running 2 tests
test tests::this_test_will_fail ... FAILED
test tests::this_test_will_pass ... ok

failures:

---- tests::this_test_will_fail stdout ----
I got the value 8
thread 'tests::this_test_will_fail' panicked at 'assertion failed: `(left == right)`
  left: `5`,
 right: `10`', src/lib.rs:19:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace


failures:
    tests::this_test_will_fail

test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

error: test failed, to rerun pass `--lib`

```
 Note that nowhere in this output do we see `I got the value 4`, which is what is printed when the test that passes runs. That output has been captured. The output from the test that failed, `I got the value 8`, appears in the section of the test summary output, which also shows the cause of the test failure.

 If we want to see printed values for passing tests as well, we can tell Rust to also show the output of successful tests with `--show-output`.

 
```
$ cargo test -- --show-output

```
 When we run the tests in Listing 11-10 again with the `--show-output` flag, we see the following output:

 
```
$ cargo test -- --show-output
   Compiling silly-function v0.1.0 (file:///projects/silly-function)
    Finished test [unoptimized + debuginfo] target(s) in 0.60s
     Running unittests src/lib.rs (target/debug/deps/silly_function-160869f38cff9166)

running 2 tests
test tests::this_test_will_fail ... FAILED
test tests::this_test_will_pass ... ok

successes:

---- tests::this_test_will_pass stdout ----
I got the value 4


successes:
    tests::this_test_will_pass

failures:

---- tests::this_test_will_fail stdout ----
I got the value 8
thread 'tests::this_test_will_fail' panicked at 'assertion failed: `(left == right)`
  left: `5`,
 right: `10`', src/lib.rs:19:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace


failures:
    tests::this_test_will_fail

test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

error: test failed, to rerun pass `--lib`

```
 ### Running a Subset of Tests by Name

 Sometimes, running a full test suite can take a long time. If you’re working on code in a particular area, you might want to run only the tests pertaining to that code. You can choose which tests to run by passing `cargo test` the name or names of the test(s) you want to run as an argument.

 To demonstrate how to run a subset of tests, we’ll first create three tests for our `add_two` function, as shown in Listing 11-11, and choose which ones to run.

 Filename: src/lib.rs

 
```
pub fn add_two(a: i32) -> i32 {
    a + 2
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn add_two_and_two() {
        assert_eq!(4, add_two(2));
    }

    #[test]
    fn add_three_and_two() {
        assert_eq!(5, add_two(3));
    }

    #[test]
    fn one_hundred() {
        assert_eq!(102, add_two(100));
    }
}
```
 Listing 11-11: Three tests with three different names

 If we run the tests without passing any arguments, as we saw earlier, all the tests will run in parallel:

 
```
$ cargo test
   Compiling adder v0.1.0 (file:///projects/adder)
    Finished test [unoptimized + debuginfo] target(s) in 0.62s
     Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)

running 3 tests
test tests::add_three_and_two ... ok
test tests::add_two_and_two ... ok
test tests::one_hundred ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests adder

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s


```
 #### Running Single Tests

 We can pass the name of any test function to `cargo test` to run only that test:

 
```
$ cargo test one_hundred
   Compiling adder v0.1.0 (file:///projects/adder)
    Finished test [unoptimized + debuginfo] target(s) in 0.69s
     Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)

running 1 test
test tests::one_hundred ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 2 filtered out; finished in 0.00s


```
 Only the test with the name `one_hundred` ran; the other two tests didn’t match that name. The test output lets us know we had more tests that didn’t run by displaying `2 filtered out` at the end.

 We can’t specify the names of multiple tests in this way; only the first value given to `cargo test` will be used. But there is a way to run multiple tests.

 #### Filtering to Run Multiple Tests

 We can specify part of a test name, and any test whose name matches that value will be run. For example, because two of our tests’ names contain `add`, we can run those two by running `cargo test add`:

 
```
$ cargo test add
   Compiling adder v0.1.0 (file:///projects/adder)
    Finished test [unoptimized + debuginfo] target(s) in 0.61s
     Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)

running 2 tests
test tests::add_three_and_two ... ok
test tests::add_two_and_two ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out; finished in 0.00s


```
 This command ran all tests with `add` in the name and filtered out the test named `one_hundred`. Also note that the module in which a test appears becomes part of the test’s name, so we can run all the tests in a module by filtering on the module’s name.

 ### Ignoring Some Tests Unless Specifically Requested

 Sometimes a few specific tests can be very time-consuming to execute, so you might want to exclude them during most runs of `cargo test`. Rather than listing as arguments all tests you do want to run, you can instead annotate the time-consuming tests using the `ignore` attribute to exclude them, as shown here:

 Filename: src/lib.rs

 
```
#[test]
fn it_works() {
    assert_eq!(2 + 2, 4);
}

#[test]
#[ignore]
fn expensive_test() {
    // code that takes an hour to run
}
```
 After `#[test]` we add the `#[ignore]` line to the test we want to exclude. Now when we run our tests, `it_works` runs, but `expensive_test` doesn’t:

 
```
$ cargo test
   Compiling adder v0.1.0 (file:///projects/adder)
    Finished test [unoptimized + debuginfo] target(s) in 0.60s
     Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)

running 2 tests
test expensive_test ... ignored
test it_works ... ok

test result: ok. 1 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests adder

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s


```
 The `expensive_test` function is listed as `ignored`. If we want to run only the ignored tests, we can use `cargo test -- --ignored`:

 
```
$ cargo test -- --ignored
   Compiling adder v0.1.0 (file:///projects/adder)
    Finished test [unoptimized + debuginfo] target(s) in 0.61s
     Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)

running 1 test
test expensive_test ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out; finished in 0.00s

   Doc-tests adder

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s


```
 By controlling which tests run, you can make sure your `cargo test` results will be fast. When you’re at a point where it makes sense to check the results of the `ignored` tests and you have time to wait for the results, you can run `cargo test -- --ignored` instead. If you want to run all tests whether they’re ignored or not, you can run `cargo test -- --include-ignored`.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch11-02-running-tests.html>

Test Organization
=================

 As mentioned at the start of the chapter, testing is a complex discipline, and different people use different terminology and organization. The Rust community thinks about tests in terms of two main categories: unit tests and integration tests. *Unit tests* are small and more focused, testing one module in isolation at a time, and can test private interfaces. *Integration tests* are entirely external to your library and use your code in the same way any other external code would, using only the public interface and potentially exercising multiple modules per test.

 Writing both kinds of tests is important to ensure that the pieces of your library are doing what you expect them to, separately and together.

 ### Unit Tests

 The purpose of unit tests is to test each unit of code in isolation from the rest of the code to quickly pinpoint where code is and isn’t working as expected. You’ll put unit tests in the *src* directory in each file with the code that they’re testing. The convention is to create a module named `tests` in each file to contain the test functions and to annotate the module with `cfg(test)`.

 #### The Tests Module and `#[cfg(test)]`

 The `#[cfg(test)]` annotation on the tests module tells Rust to compile and run the test code only when you run `cargo test`, not when you run `cargo build`. This saves compile time when you only want to build the library and saves space in the resulting compiled artifact because the tests are not included. You’ll see that because integration tests go in a different directory, they don’t need the `#[cfg(test)]` annotation. However, because unit tests go in the same files as the code, you’ll use `#[cfg(test)]` to specify that they shouldn’t be included in the compiled result.

 Recall that when we generated the new `adder` project in the first section of this chapter, Cargo generated this code for us:

 Filename: src/lib.rs

 
```
#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        let result = 2 + 2;
        assert_eq!(result, 4);
    }
}
```
 This code is the automatically generated test module. The attribute `cfg` stands for *configuration* and tells Rust that the following item should only be included given a certain configuration option. In this case, the configuration option is `test`, which is provided by Rust for compiling and running tests. By using the `cfg` attribute, Cargo compiles our test code only if we actively run the tests with `cargo test`. This includes any helper functions that might be within this module, in addition to the functions annotated with `#[test]`.

 #### Testing Private Functions

 There’s debate within the testing community about whether or not private functions should be tested directly, and other languages make it difficult or impossible to test private functions. Regardless of which testing ideology you adhere to, Rust’s privacy rules do allow you to test private functions. Consider the code in Listing 11-12 with the private function `internal_adder`.

 Filename: src/lib.rs

 
```
pub fn add_two(a: i32) -> i32 {
    internal_adder(a, 2)
}

fn internal_adder(a: i32, b: i32) -> i32 {
    a + b
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn internal() {
        assert_eq!(4, internal_adder(2, 2));
    }
}
```
 Listing 11-12: Testing a private function

 Note that the `internal_adder` function is not marked as `pub`. Tests are just Rust code, and the `tests` module is just another module. As we discussed in the [“Paths for Referring to an Item in the Module Tree”](ch07-03-paths-for-referring-to-an-item-in-the-module-tree) section, items in child modules can use the items in their ancestor modules. In this test, we bring all of the `test` module’s parent’s items into scope with `use super::*`, and then the test can call `internal_adder`. If you don’t think private functions should be tested, there’s nothing in Rust that will compel you to do so.

 ### Integration Tests

 In Rust, integration tests are entirely external to your library. They use your library in the same way any other code would, which means they can only call functions that are part of your library’s public API. Their purpose is to test whether many parts of your library work together correctly. Units of code that work correctly on their own could have problems when integrated, so test coverage of the integrated code is important as well. To create integration tests, you first need a *tests* directory.

 #### The *tests* Directory

 We create a *tests* directory at the top level of our project directory, next to *src*. Cargo knows to look for integration test files in this directory. We can then make as many test files as we want, and Cargo will compile each of the files as an individual crate.

 Let’s create an integration test. With the code in Listing 11-12 still in the *src/lib.rs* file, make a *tests* directory, and create a new file named *tests/integration\_test.rs*. Your directory structure should look like this:

 
```
adder
├── Cargo.lock
├── Cargo.toml
├── src
│   └── lib.rs
└── tests
    └── integration_test.rs

```
 Enter the code in Listing 11-13 into the *tests/integration\_test.rs* file:

 Filename: tests/integration\_test.rs

 
```
use adder;

#[test]
fn it_adds_two() {
    assert_eq!(4, adder::add_two(2));
}
```
 Listing 11-13: An integration test of a function in the `adder` crate

 Each file in the `tests` directory is a separate crate, so we need to bring our library into each test crate’s scope. For that reason we add `use adder` at the top of the code, which we didn’t need in the unit tests.

 We don’t need to annotate any code in *tests/integration\_test.rs* with `#[cfg(test)]`. Cargo treats the `tests` directory specially and compiles files in this directory only when we run `cargo test`. Run `cargo test` now:

 
```
$ cargo test
   Compiling adder v0.1.0 (file:///projects/adder)
    Finished test [unoptimized + debuginfo] target(s) in 1.31s
     Running unittests src/lib.rs (target/debug/deps/adder-1082c4b063a8fbe6)

running 1 test
test tests::internal ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

     Running tests/integration_test.rs (target/debug/deps/integration_test-1082c4b063a8fbe6)

running 1 test
test it_adds_two ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests adder

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s


```
 The three sections of output include the unit tests, the integration test, and the doc tests. Note that if any test in a section fails, the following sections will not be run. For example, if a unit test fails, there won’t be any output for integration and doc tests because those tests will only be run if all unit tests are passing.

 The first section for the unit tests is the same as we’ve been seeing: one line for each unit test (one named `internal` that we added in Listing 11-12) and then a summary line for the unit tests.

 The integration tests section starts with the line `Running tests/integration_test.rs`. Next, there is a line for each test function in that integration test and a summary line for the results of the integration test just before the `Doc-tests adder` section starts.

 Each integration test file has its own section, so if we add more files in the *tests* directory, there will be more integration test sections.

 We can still run a particular integration test function by specifying the test function’s name as an argument to `cargo test`. To run all the tests in a particular integration test file, use the `--test` argument of `cargo test` followed by the name of the file:

 
```
$ cargo test --test integration_test
   Compiling adder v0.1.0 (file:///projects/adder)
    Finished test [unoptimized + debuginfo] target(s) in 0.64s
     Running tests/integration_test.rs (target/debug/deps/integration_test-82e7799c1bc62298)

running 1 test
test it_adds_two ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s


```
 This command runs only the tests in the *tests/integration\_test.rs* file.

 #### Submodules in Integration Tests

 As you add more integration tests, you might want to make more files in the *tests* directory to help organize them; for example, you can group the test functions by the functionality they’re testing. As mentioned earlier, each file in the *tests* directory is compiled as its own separate crate, which is useful for creating separate scopes to more closely imitate the way end users will be using your crate. However, this means files in the *tests* directory don’t share the same behavior as files in *src* do, as you learned in Chapter 7 regarding how to separate code into modules and files.

 The different behavior of *tests* directory files is most noticeable when you have a set of helper functions to use in multiple integration test files and you try to follow the steps in the [“Separating Modules into Different Files”](ch07-05-separating-modules-into-different-files) section of Chapter 7 to extract them into a common module. For example, if we create *tests/common.rs* and place a function named `setup` in it, we can add some code to `setup` that we want to call from multiple test functions in multiple test files:

 Filename: tests/common.rs

 
```
pub fn setup() {
    // setup code specific to your library's tests would go here
}
```
 When we run the tests again, we’ll see a new section in the test output for the *common.rs* file, even though this file doesn’t contain any test functions nor did we call the `setup` function from anywhere:

 
```
$ cargo test
   Compiling adder v0.1.0 (file:///projects/adder)
    Finished test [unoptimized + debuginfo] target(s) in 0.89s
     Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)

running 1 test
test tests::internal ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

     Running tests/common.rs (target/debug/deps/common-92948b65e88960b4)

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

     Running tests/integration_test.rs (target/debug/deps/integration_test-92948b65e88960b4)

running 1 test
test it_adds_two ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests adder

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s


```
 Having `common` appear in the test results with `running 0 tests` displayed for it is not what we wanted. We just wanted to share some code with the other integration test files.

 To avoid having `common` appear in the test output, instead of creating *tests/common.rs*, we’ll create *tests/common/mod.rs*. The project directory now looks like this:

 
```
├── Cargo.lock
├── Cargo.toml
├── src
│   └── lib.rs
└── tests
    ├── common
    │   └── mod.rs
    └── integration_test.rs

```
 This is the older naming convention that Rust also understands that we mentioned in the [“Alternate File Paths”](ch07-05-separating-modules-into-different-files#alternate-file-paths) section of Chapter 7. Naming the file this way tells Rust not to treat the `common` module as an integration test file. When we move the `setup` function code into *tests/common/mod.rs* and delete the *tests/common.rs* file, the section in the test output will no longer appear. Files in subdirectories of the *tests* directory don’t get compiled as separate crates or have sections in the test output.

 After we’ve created *tests/common/mod.rs*, we can use it from any of the integration test files as a module. Here’s an example of calling the `setup` function from the `it_adds_two` test in *tests/integration\_test.rs*:

 Filename: tests/integration\_test.rs

 
```
use adder;

mod common;

#[test]
fn it_adds_two() {
    common::setup();
    assert_eq!(4, adder::add_two(2));
}
```
 Note that the `mod common;` declaration is the same as the module declaration we demonstrated in Listing 7-21. Then in the test function, we can call the `common::setup()` function.

 #### Integration Tests for Binary Crates

 If our project is a binary crate that only contains a *src/main.rs* file and doesn’t have a *src/lib.rs* file, we can’t create integration tests in the *tests* directory and bring functions defined in the *src/main.rs* file into scope with a `use` statement. Only library crates expose functions that other crates can use; binary crates are meant to be run on their own.

 This is one of the reasons Rust projects that provide a binary have a straightforward *src/main.rs* file that calls logic that lives in the *src/lib.rs* file. Using that structure, integration tests *can* test the library crate with `use` to make the important functionality available. If the important functionality works, the small amount of code in the *src/main.rs* file will work as well, and that small amount of code doesn’t need to be tested.

 Summary
-------

 Rust’s testing features provide a way to specify how code should function to ensure it continues to work as you expect, even as you make changes. Unit tests exercise different parts of a library separately and can test private implementation details. Integration tests check that many parts of the library work together correctly, and they use the library’s public API to test the code in the same way external code will use it. Even though Rust’s type system and ownership rules help prevent some kinds of bugs, tests are still important to reduce logic bugs having to do with how your code is expected to behave.

 Let’s combine the knowledge you learned in this chapter and in previous chapters to work on a project!



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch11-03-test-organization.html>

An I/O Project: Building a Command Line Program
===============================================

 This chapter is a recap of the many skills you’ve learned so far and an exploration of a few more standard library features. We’ll build a command line tool that interacts with file and command line input/output to practice some of the Rust concepts you now have under your belt.

 Rust’s speed, safety, single binary output, and cross-platform support make it an ideal language for creating command line tools, so for our project, we’ll make our own version of the classic command line search tool `grep` (**g**lobally search a **r**egular **e**xpression and **p**rint). In the simplest use case, `grep` searches a specified file for a specified string. To do so, `grep` takes as its arguments a file path and a string. Then it reads the file, finds lines in that file that contain the string argument, and prints those lines.

 Along the way, we’ll show how to make our command line tool use the terminal features that many other command line tools use. We’ll read the value of an environment variable to allow the user to configure the behavior of our tool. We’ll also print error messages to the standard error console stream (`stderr`) instead of standard output (`stdout`), so, for example, the user can redirect successful output to a file while still seeing error messages onscreen.

 One Rust community member, Andrew Gallant, has already created a fully featured, very fast version of `grep`, called `ripgrep`. By comparison, our version will be fairly simple, but this chapter will give you some of the background knowledge you need to understand a real-world project such as `ripgrep`.

 Our `grep` project will combine a number of concepts you’ve learned so far:

 * Organizing code (using what you learned about modules in [Chapter 7](ch07-00-managing-growing-projects-with-packages-crates-and-modules))
* Using vectors and strings (collections, [Chapter 8](ch08-00-common-collections))
* Handling errors ([Chapter 9](ch09-00-error-handling))
* Using traits and lifetimes where appropriate ([Chapter 10](ch10-00-generics))
* Writing tests ([Chapter 11](ch11-00-testing))

 We’ll also briefly introduce closures, iterators, and trait objects, which Chapters [13](ch13-00-functional-features) and [17](ch17-00-oop) will cover in detail.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch12-00-an-io-project.html>

Accepting Command Line Arguments
================================

 Let’s create a new project with, as always, `cargo new`. We’ll call our project `minigrep` to distinguish it from the `grep` tool that you might already have on your system.

 
```
$ cargo new minigrep
     Created binary (application) `minigrep` project
$ cd minigrep

```
 The first task is to make `minigrep` accept its two command line arguments: the file path and a string to search for. That is, we want to be able to run our program with `cargo run`, two hyphens to indicate the following arguments are for our program rather than for `cargo`, a string to search for, and a path to a file to search in, like so:

 
```
$ cargo run -- searchstring example-filename.txt

```
 Right now, the program generated by `cargo new` cannot process arguments we give it. Some existing libraries on [crates.io](https://crates.io/) can help with writing a program that accepts command line arguments, but because you’re just learning this concept, let’s implement this capability ourselves.

 ### Reading the Argument Values

 To enable `minigrep` to read the values of command line arguments we pass to it, we’ll need the `std::env::args` function provided in Rust’s standard library. This function returns an iterator of the command line arguments passed to `minigrep`. We’ll cover iterators fully in [Chapter 13](ch13-00-functional-features). For now, you only need to know two details about iterators: iterators produce a series of values, and we can call the `collect` method on an iterator to turn it into a collection, such as a vector, that contains all the elements the iterator produces.

 The code in Listing 12-1 allows your `minigrep` program to read any command line arguments passed to it and then collect the values into a vector.

 Filename: src/main.rs

 
```
use std::env;

fn main() {
    let args: Vec<String> = env::args().collect();
    dbg!(args);
}
```
 Listing 12-1: Collecting the command line arguments into a vector and printing them

 First, we bring the `std::env` module into scope with a `use` statement so we can use its `args` function. Notice that the `std::env::args` function is nested in two levels of modules. As we discussed in [Chapter 7](ch07-04-bringing-paths-into-scope-with-the-use-keyword#creating-idiomatic-use-paths), in cases where the desired function is nested in more than one module, we’ve chosen to bring the parent module into scope rather than the function. By doing so, we can easily use other functions from `std::env`. It’s also less ambiguous than adding `use std::env::args` and then calling the function with just `args`, because `args` might easily be mistaken for a function that’s defined in the current module.

 
>  ### The `args` Function and Invalid Unicode
> 
>  Note that `std::env::args` will panic if any argument contains invalid Unicode. If your program needs to accept arguments containing invalid Unicode, use `std::env::args_os` instead. That function returns an iterator that produces `OsString` values instead of `String` values. We’ve chosen to use `std::env::args` here for simplicity, because `OsString` values differ per platform and are more complex to work with than `String` values.
> 
>  

 On the first line of `main`, we call `env::args`, and we immediately use `collect` to turn the iterator into a vector containing all the values produced by the iterator. We can use the `collect` function to create many kinds of collections, so we explicitly annotate the type of `args` to specify that we want a vector of strings. Although we very rarely need to annotate types in Rust, `collect` is one function you do often need to annotate because Rust isn’t able to infer the kind of collection you want.

 Finally, we print the vector using the debug macro. Let’s try running the code first with no arguments and then with two arguments:

 
```
$ cargo run
   Compiling minigrep v0.1.0 (file:///projects/minigrep)
    Finished dev [unoptimized + debuginfo] target(s) in 0.61s
     Running `target/debug/minigrep`
[src/main.rs:5] args = [
    "target/debug/minigrep",
]

```
 
```
$ cargo run -- needle haystack
   Compiling minigrep v0.1.0 (file:///projects/minigrep)
    Finished dev [unoptimized + debuginfo] target(s) in 1.57s
     Running `target/debug/minigrep needle haystack`
[src/main.rs:5] args = [
    "target/debug/minigrep",
    "needle",
    "haystack",
]

```
 Notice that the first value in the vector is `"target/debug/minigrep"`, which is the name of our binary. This matches the behavior of the arguments list in C, letting programs use the name by which they were invoked in their execution. It’s often convenient to have access to the program name in case you want to print it in messages or change behavior of the program based on what command line alias was used to invoke the program. But for the purposes of this chapter, we’ll ignore it and save only the two arguments we need.

 ### Saving the Argument Values in Variables

 The program is currently able to access the values specified as command line arguments. Now we need to save the values of the two arguments in variables so we can use the values throughout the rest of the program. We do that in Listing 12-2.

 Filename: src/main.rs

 
```
use std::env;

fn main() {
    let args: Vec<String> = env::args().collect();

    let query = &args[1];
    let file_path = &args[2];

    println!("Searching for {}", query);
    println!("In file {}", file_path);
}
```
 Listing 12-2: Creating variables to hold the query argument and file path argument

 As we saw when we printed the vector, the program’s name takes up the first value in the vector at `args[0]`, so we’re starting arguments at index `1`. The first argument `minigrep` takes is the string we’re searching for, so we put a reference to the first argument in the variable `query`. The second argument will be the file path, so we put a reference to the second argument in the variable `file_path`.

 We temporarily print the values of these variables to prove that the code is working as we intend. Let’s run this program again with the arguments `test` and `sample.txt`:

 
```
$ cargo run -- test sample.txt
   Compiling minigrep v0.1.0 (file:///projects/minigrep)
    Finished dev [unoptimized + debuginfo] target(s) in 0.0s
     Running `target/debug/minigrep test sample.txt`
Searching for test
In file sample.txt

```
 Great, the program is working! The values of the arguments we need are being saved into the right variables. Later we’ll add some error handling to deal with certain potential erroneous situations, such as when the user provides no arguments; for now, we’ll ignore that situation and work on adding file-reading capabilities instead.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch12-01-accepting-command-line-arguments.html>

Reading a File
==============

 Now we’ll add functionality to read the file specified in the `file_path` argument. First, we need a sample file to test it with: we’ll use a file with a small amount of text over multiple lines with some repeated words. Listing 12-3 has an Emily Dickinson poem that will work well! Create a file called *poem.txt* at the root level of your project, and enter the poem “I’m Nobody! Who are you?”

 Filename: poem.txt

 
```
I'm nobody! Who are you?
Are you nobody, too?
Then there's a pair of us - don't tell!
They'd banish us, you know.

How dreary to be somebody!
How public, like a frog
To tell your name the livelong day
To an admiring bog!

```
 Listing 12-3: A poem by Emily Dickinson makes a good test case

 With the text in place, edit *src/main.rs* and add code to read the file, as shown in Listing 12-4.

 Filename: src/main.rs

 
```
use std::env;
use std::fs;

fn main() {
    // --snip--
    let args: Vec<String> = env::args().collect();

    let query = &args[1];
    let file_path = &args[2];

    println!("Searching for {}", query);
    println!("In file {}", file_path);

    let contents = fs::read_to_string(file_path)
        .expect("Should have been able to read the file");

    println!("With text:\n{contents}");
}
```
 Listing 12-4: Reading the contents of the file specified by the second argument

 First, we bring in a relevant part of the standard library with a `use` statement: we need `std::fs` to handle files.

 In `main`, the new statement `fs::read_to_string` takes the `file_path`, opens that file, and returns a `std::io::Result<String>` of the file’s contents.

 After that, we again add a temporary `println!` statement that prints the value of `contents` after the file is read, so we can check that the program is working so far.

 Let’s run this code with any string as the first command line argument (because we haven’t implemented the searching part yet) and the *poem.txt* file as the second argument:

 
```
$ cargo run -- the poem.txt
   Compiling minigrep v0.1.0 (file:///projects/minigrep)
    Finished dev [unoptimized + debuginfo] target(s) in 0.0s
     Running `target/debug/minigrep the poem.txt`
Searching for the
In file poem.txt
With text:
I'm nobody! Who are you?
Are you nobody, too?
Then there's a pair of us - don't tell!
They'd banish us, you know.

How dreary to be somebody!
How public, like a frog
To tell your name the livelong day
To an admiring bog!


```
 Great! The code read and then printed the contents of the file. But the code has a few flaws. At the moment, the `main` function has multiple responsibilities: generally, functions are clearer and easier to maintain if each function is responsible for only one idea. The other problem is that we’re not handling errors as well as we could. The program is still small, so these flaws aren’t a big problem, but as the program grows, it will be harder to fix them cleanly. It’s good practice to begin refactoring early on when developing a program, because it’s much easier to refactor smaller amounts of code. We’ll do that next.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch12-02-reading-a-file.html>

Recoverable Errors with `Result`
================================

 Most errors aren’t serious enough to require the program to stop entirely. Sometimes, when a function fails, it’s for a reason that you can easily interpret and respond to. For example, if you try to open a file and that operation fails because the file doesn’t exist, you might want to create the file instead of terminating the process.

 Recall from [“Handling Potential Failure with `Result`”](ch02-00-guessing-game-tutorial#handling-potential-failure-with-result) in Chapter 2 that the `Result` enum is defined as having two variants, `Ok` and `Err`, as follows:

 
```
#![allow(unused)]
fn main() {
enum Result<T, E> {
    Ok(T),
    Err(E),
}
}
```
 The `T` and `E` are generic type parameters: we’ll discuss generics in more detail in Chapter 10. What you need to know right now is that `T` represents the type of the value that will be returned in a success case within the `Ok` variant, and `E` represents the type of the error that will be returned in a failure case within the `Err` variant. Because `Result` has these generic type parameters, we can use the `Result` type and the functions defined on it in many different situations where the successful value and error value we want to return may differ.

 Let’s call a function that returns a `Result` value because the function could fail. In Listing 9-3 we try to open a file.

 Filename: src/main.rs

 
```
use std::fs::File;

fn main() {
    let greeting_file_result = File::open("hello.txt");
}
```
 Listing 9-3: Opening a file

 The return type of `File::open` is a `Result<T, E>`. The generic parameter `T` has been filled in by the implementation of `File::open` with the type of the success value, `std::fs::File`, which is a file handle. The type of `E` used in the error value is `std::io::Error`. This return type means the call to `File::open` might succeed and return a file handle that we can read from or write to. The function call also might fail: for example, the file might not exist, or we might not have permission to access the file. The `File::open` function needs to have a way to tell us whether it succeeded or failed and at the same time give us either the file handle or error information. This information is exactly what the `Result` enum conveys.

 In the case where `File::open` succeeds, the value in the variable `greeting_file_result` will be an instance of `Ok` that contains a file handle. In the case where it fails, the value in `greeting_file_result` will be an instance of `Err` that contains more information about the kind of error that happened.

 We need to add to the code in Listing 9-3 to take different actions depending on the value `File::open` returns. Listing 9-4 shows one way to handle the `Result` using a basic tool, the `match` expression that we discussed in Chapter 6.

 Filename: src/main.rs

 
```
use std::fs::File;

fn main() {
    let greeting_file_result = File::open("hello.txt");

    let greeting_file = match greeting_file_result {
        Ok(file) => file,
        Err(error) => panic!("Problem opening the file: {:?}", error),
    };
}
```
 Listing 9-4: Using a `match` expression to handle the `Result` variants that might be returned

 Note that, like the `Option` enum, the `Result` enum and its variants have been brought into scope by the prelude, so we don’t need to specify `Result::` before the `Ok` and `Err` variants in the `match` arms.

 When the result is `Ok`, this code will return the inner `file` value out of the `Ok` variant, and we then assign that file handle value to the variable `greeting_file`. After the `match`, we can use the file handle for reading or writing.

 The other arm of the `match` handles the case where we get an `Err` value from `File::open`. In this example, we’ve chosen to call the `panic!` macro. If there’s no file named *hello.txt* in our current directory and we run this code, we’ll see the following output from the `panic!` macro:

 
```
$ cargo run
   Compiling error-handling v0.1.0 (file:///projects/error-handling)
    Finished dev [unoptimized + debuginfo] target(s) in 0.73s
     Running `target/debug/error-handling`
thread 'main' panicked at 'Problem opening the file: Os { code: 2, kind: NotFound, message: "No such file or directory" }', src/main.rs:8:23
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

```
 As usual, this output tells us exactly what has gone wrong.

 ### Matching on Different Errors

 The code in Listing 9-4 will `panic!` no matter why `File::open` failed. However, we want to take different actions for different failure reasons: if `File::open` failed because the file doesn’t exist, we want to create the file and return the handle to the new file. If `File::open` failed for any other reason—for example, because we didn’t have permission to open the file—we still want the code to `panic!` in the same way as it did in Listing 9-4. For this we add an inner `match` expression, shown in Listing 9-5.

 Filename: src/main.rs

 
```
use std::fs::File;
use std::io::ErrorKind;

fn main() {
    let greeting_file_result = File::open("hello.txt");

    let greeting_file = match greeting_file_result {
        Ok(file) => file,
        Err(error) => match error.kind() {
            ErrorKind::NotFound => match File::create("hello.txt") {
                Ok(fc) => fc,
                Err(e) => panic!("Problem creating the file: {:?}", e),
            },
            other_error => {
                panic!("Problem opening the file: {:?}", other_error);
            }
        },
    };
}
```
 Listing 9-5: Handling different kinds of errors in different ways

 The type of the value that `File::open` returns inside the `Err` variant is `io::Error`, which is a struct provided by the standard library. This struct has a method `kind` that we can call to get an `io::ErrorKind` value. The enum `io::ErrorKind` is provided by the standard library and has variants representing the different kinds of errors that might result from an `io` operation. The variant we want to use is `ErrorKind::NotFound`, which indicates the file we’re trying to open doesn’t exist yet. So we match on `greeting_file_result`, but we also have an inner match on `error.kind()`.

 The condition we want to check in the inner match is whether the value returned by `error.kind()` is the `NotFound` variant of the `ErrorKind` enum. If it is, we try to create the file with `File::create`. However, because `File::create` could also fail, we need a second arm in the inner `match` expression. When the file can’t be created, a different error message is printed. The second arm of the outer `match` stays the same, so the program panics on any error besides the missing file error.

 
>  ### Alternatives to Using `match` with `Result<T, E>`
> 
>  That’s a lot of `match`! The `match` expression is very useful but also very much a primitive. In Chapter 13, you’ll learn about closures, which are used with many of the methods defined on `Result<T, E>`. These methods can be more concise than using `match` when handling `Result<T, E>` values in your code.
> 
>  For example, here’s another way to write the same logic as shown in Listing 9-5, this time using closures and the `unwrap_or_else` method:
> 
>  
> ```
> use std::fs::File;
> use std::io::ErrorKind;
> 
> fn main() {
>     let greeting_file = File::open("hello.txt").unwrap_or_else(|error| {
>         if error.kind() == ErrorKind::NotFound {
>             File::create("hello.txt").unwrap_or_else(|error| {
>                 panic!("Problem creating the file: {:?}", error);
>             })
>         } else {
>             panic!("Problem opening the file: {:?}", error);
>         }
>     });
> }
> ```
>  Although this code has the same behavior as Listing 9-5, it doesn’t contain any `match` expressions and is cleaner to read. Come back to this example after you’ve read Chapter 13, and look up the `unwrap_or_else` method in the standard library documentation. Many more of these methods can clean up huge nested `match` expressions when you’re dealing with errors.
> 
>  

 ### Shortcuts for Panic on Error: `unwrap` and `expect`

 Using `match` works well enough, but it can be a bit verbose and doesn’t always communicate intent well. The `Result<T, E>` type has many helper methods defined on it to do various, more specific tasks. The `unwrap` method is a shortcut method implemented just like the `match` expression we wrote in Listing 9-4. If the `Result` value is the `Ok` variant, `unwrap` will return the value inside the `Ok`. If the `Result` is the `Err` variant, `unwrap` will call the `panic!` macro for us. Here is an example of `unwrap` in action:

 Filename: src/main.rs

 
```
use std::fs::File;

fn main() {
    let greeting_file = File::open("hello.txt").unwrap();
}
```
 If we run this code without a *hello.txt* file, we’ll see an error message from the `panic!` call that the `unwrap` method makes:

 
```
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Os {
code: 2, kind: NotFound, message: "No such file or directory" }',
src/main.rs:4:49

```
 Similarly, the `expect` method lets us also choose the `panic!` error message. Using `expect` instead of `unwrap` and providing good error messages can convey your intent and make tracking down the source of a panic easier. The syntax of `expect` looks like this:

 Filename: src/main.rs

 
```
use std::fs::File;

fn main() {
    let greeting_file = File::open("hello.txt")
        .expect("hello.txt should be included in this project");
}
```
 We use `expect` in the same way as `unwrap`: to return the file handle or call the `panic!` macro. The error message used by `expect` in its call to `panic!` will be the parameter that we pass to `expect`, rather than the default `panic!` message that `unwrap` uses. Here’s what it looks like:

 
```
thread 'main' panicked at 'hello.txt should be included in this project: Os {
code: 2, kind: NotFound, message: "No such file or directory" }',
src/main.rs:5:10

```
 In production-quality code, most Rustaceans choose `expect` rather than `unwrap` and give more context about why the operation is expected to always succeed. That way, if your assumptions are ever proven wrong, you have more information to use in debugging.

 ### Propagating Errors

 When a function’s implementation calls something that might fail, instead of handling the error within the function itself, you can return the error to the calling code so that it can decide what to do. This is known as *propagating* the error and gives more control to the calling code, where there might be more information or logic that dictates how the error should be handled than what you have available in the context of your code.

 For example, Listing 9-6 shows a function that reads a username from a file. If the file doesn’t exist or can’t be read, this function will return those errors to the code that called the function.

 Filename: src/main.rs

 
```
#![allow(unused)]
fn main() {
use std::fs::File;
use std::io::{self, Read};

fn read_username_from_file() -> Result<String, io::Error> {
    let username_file_result = File::open("hello.txt");

    let mut username_file = match username_file_result {
        Ok(file) => file,
        Err(e) => return Err(e),
    };

    let mut username = String::new();

    match username_file.read_to_string(&mut username) {
        Ok(_) => Ok(username),
        Err(e) => Err(e),
    }
}
}
```
 Listing 9-6: A function that returns errors to the calling code using `match`

 This function can be written in a much shorter way, but we’re going to start by doing a lot of it manually in order to explore error handling; at the end, we’ll show the shorter way. Let’s look at the return type of the function first: `Result<String, io::Error>`. This means the function is returning a value of the type `Result<T, E>` where the generic parameter `T` has been filled in with the concrete type `String`, and the generic type `E` has been filled in with the concrete type `io::Error`.

 If this function succeeds without any problems, the code that calls this function will receive an `Ok` value that holds a `String`—the username that this function read from the file. If this function encounters any problems, the calling code will receive an `Err` value that holds an instance of `io::Error` that contains more information about what the problems were. We chose `io::Error` as the return type of this function because that happens to be the type of the error value returned from both of the operations we’re calling in this function’s body that might fail: the `File::open` function and the `read_to_string` method.

 The body of the function starts by calling the `File::open` function. Then we handle the `Result` value with a `match` similar to the `match` in Listing 9-4. If `File::open` succeeds, the file handle in the pattern variable `file` becomes the value in the mutable variable `username_file` and the function continues. In the `Err` case, instead of calling `panic!`, we use the `return` keyword to return early out of the function entirely and pass the error value from `File::open`, now in the pattern variable `e`, back to the calling code as this function’s error value.

 So if we have a file handle in `username_file`, the function then creates a new `String` in variable `username` and calls the `read_to_string` method on the file handle in `username_file` to read the contents of the file into `username`. The `read_to_string` method also returns a `Result` because it might fail, even though `File::open` succeeded. So we need another `match` to handle that `Result`: if `read_to_string` succeeds, then our function has succeeded, and we return the username from the file that’s now in `username` wrapped in an `Ok`. If `read_to_string` fails, we return the error value in the same way that we returned the error value in the `match` that handled the return value of `File::open`. However, we don’t need to explicitly say `return`, because this is the last expression in the function.

 The code that calls this code will then handle getting either an `Ok` value that contains a username or an `Err` value that contains an `io::Error`. It’s up to the calling code to decide what to do with those values. If the calling code gets an `Err` value, it could call `panic!` and crash the program, use a default username, or look up the username from somewhere other than a file, for example. We don’t have enough information on what the calling code is actually trying to do, so we propagate all the success or error information upward for it to handle appropriately.

 This pattern of propagating errors is so common in Rust that Rust provides the question mark operator `?` to make this easier.

 #### A Shortcut for Propagating Errors: the `?` Operator

 Listing 9-7 shows an implementation of `read_username_from_file` that has the same functionality as in Listing 9-6, but this implementation uses the `?` operator.

 Filename: src/main.rs

 
```
#![allow(unused)]
fn main() {
use std::fs::File;
use std::io::{self, Read};

fn read_username_from_file() -> Result<String, io::Error> {
    let mut username_file = File::open("hello.txt")?;
    let mut username = String::new();
    username_file.read_to_string(&mut username)?;
    Ok(username)
}
}
```
 Listing 9-7: A function that returns errors to the calling code using the `?` operator

 The `?` placed after a `Result` value is defined to work in almost the same way as the `match` expressions we defined to handle the `Result` values in Listing 9-6. If the value of the `Result` is an `Ok`, the value inside the `Ok` will get returned from this expression, and the program will continue. If the value is an `Err`, the `Err` will be returned from the whole function as if we had used the `return` keyword so the error value gets propagated to the calling code.

 There is a difference between what the `match` expression from Listing 9-6 does and what the `?` operator does: error values that have the `?` operator called on them go through the `from` function, defined in the `From` trait in the standard library, which is used to convert values from one type into another. When the `?` operator calls the `from` function, the error type received is converted into the error type defined in the return type of the current function. This is useful when a function returns one error type to represent all the ways a function might fail, even if parts might fail for many different reasons.

 For example, we could change the `read_username_from_file` function in Listing 9-7 to return a custom error type named `OurError` that we define. If we also define `impl From<io::Error> for OurError` to construct an instance of `OurError` from an `io::Error`, then the `?` operator calls in the body of `read_username_from_file` will call `from` and convert the error types without needing to add any more code to the function.

 In the context of Listing 9-7, the `?` at the end of the `File::open` call will return the value inside an `Ok` to the variable `username_file`. If an error occurs, the `?` operator will return early out of the whole function and give any `Err` value to the calling code. The same thing applies to the `?` at the end of the `read_to_string` call.

 The `?` operator eliminates a lot of boilerplate and makes this function’s implementation simpler. We could even shorten this code further by chaining method calls immediately after the `?`, as shown in Listing 9-8.

 Filename: src/main.rs

 
```
#![allow(unused)]
fn main() {
use std::fs::File;
use std::io::{self, Read};

fn read_username_from_file() -> Result<String, io::Error> {
    let mut username = String::new();

    File::open("hello.txt")?.read_to_string(&mut username)?;

    Ok(username)
}
}
```
 Listing 9-8: Chaining method calls after the `?` operator

 We’ve moved the creation of the new `String` in `username` to the beginning of the function; that part hasn’t changed. Instead of creating a variable `username_file`, we’ve chained the call to `read_to_string` directly onto the result of `File::open("hello.txt")?`. We still have a `?` at the end of the `read_to_string` call, and we still return an `Ok` value containing `username` when both `File::open` and `read_to_string` succeed rather than returning errors. The functionality is again the same as in Listing 9-6 and Listing 9-7; this is just a different, more ergonomic way to write it.

 Listing 9-9 shows a way to make this even shorter using `fs::read_to_string`.

 Filename: src/main.rs

 
```
#![allow(unused)]
fn main() {
use std::fs;
use std::io;

fn read_username_from_file() -> Result<String, io::Error> {
    fs::read_to_string("hello.txt")
}
}
```
 Listing 9-9: Using `fs::read_to_string` instead of opening and then reading the file

 Reading a file into a string is a fairly common operation, so the standard library provides the convenient `fs::read_to_string` function that opens the file, creates a new `String`, reads the contents of the file, puts the contents into that `String`, and returns it. Of course, using `fs::read_to_string` doesn’t give us the opportunity to explain all the error handling, so we did it the longer way first.

 #### Where The `?` Operator Can Be Used

 The `?` operator can only be used in functions whose return type is compatible with the value the `?` is used on. This is because the `?` operator is defined to perform an early return of a value out of the function, in the same manner as the `match` expression we defined in Listing 9-6. In Listing 9-6, the `match` was using a `Result` value, and the early return arm returned an `Err(e)` value. The return type of the function has to be a `Result` so that it’s compatible with this `return`.

 In Listing 9-10, let’s look at the error we’ll get if we use the `?` operator in a `main` function with a return type incompatible with the type of the value we use `?` on:

 Filename: src/main.rs

 
```
use std::fs::File;

fn main() {
    let greeting_file = File::open("hello.txt")?;
}
```
 Listing 9-10: Attempting to use the `?` in the `main` function that returns `()` won’t compile

 This code opens a file, which might fail. The `?` operator follows the `Result` value returned by `File::open`, but this `main` function has the return type of `()`, not `Result`. When we compile this code, we get the following error message:

 
```
$ cargo run
   Compiling error-handling v0.1.0 (file:///projects/error-handling)
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)
 --> src/main.rs:4:48
  |
3 | fn main() {
  | --------- this function should return `Result` or `Option` to accept `?`
4 |     let greeting_file = File::open("hello.txt")?;
  |                                                ^ cannot use the `?` operator in a function that returns `()`
  |
  = help: the trait `FromResidual<Result<Infallible, std::io::Error>>` is not implemented for `()`

For more information about this error, try `rustc --explain E0277`.
error: could not compile `error-handling` due to previous error

```
 This error points out that we’re only allowed to use the `?` operator in a function that returns `Result`, `Option`, or another type that implements `FromResidual`.

 To fix the error, you have two choices. One choice is to change the return type of your function to be compatible with the value you’re using the `?` operator on as long as you have no restrictions preventing that. The other technique is to use a `match` or one of the `Result<T, E>` methods to handle the `Result<T, E>` in whatever way is appropriate.

 The error message also mentioned that `?` can be used with `Option<T>` values as well. As with using `?` on `Result`, you can only use `?` on `Option` in a function that returns an `Option`. The behavior of the `?` operator when called on an `Option<T>` is similar to its behavior when called on a `Result<T, E>`: if the value is `None`, the `None` will be returned early from the function at that point. If the value is `Some`, the value inside the `Some` is the resulting value of the expression and the function continues. Listing 9-11 has an example of a function that finds the last character of the first line in the given text:

 
```
fn last_char_of_first_line(text: &str) -> Option<char> {
    text.lines().next()?.chars().last()
}

fn main() {
    assert_eq!(
        last_char_of_first_line("Hello, world\nHow are you today?"),
        Some('d')
    );

    assert_eq!(last_char_of_first_line(""), None);
    assert_eq!(last_char_of_first_line("\nhi"), None);
}
```
 Listing 9-11: Using the `?` operator on an `Option<T>` value

 This function returns `Option<char>` because it’s possible that there is a character there, but it’s also possible that there isn’t. This code takes the `text` string slice argument and calls the `lines` method on it, which returns an iterator over the lines in the string. Because this function wants to examine the first line, it calls `next` on the iterator to get the first value from the iterator. If `text` is the empty string, this call to `next` will return `None`, in which case we use `?` to stop and return `None` from `last_char_of_first_line`. If `text` is not the empty string, `next` will return a `Some` value containing a string slice of the first line in `text`.

 The `?` extracts the string slice, and we can call `chars` on that string slice to get an iterator of its characters. We’re interested in the last character in this first line, so we call `last` to return the last item in the iterator. This is an `Option` because it’s possible that the first line is the empty string, for example if `text` starts with a blank line but has characters on other lines, as in `"\nhi"`. However, if there is a last character on the first line, it will be returned in the `Some` variant. The `?` operator in the middle gives us a concise way to express this logic, allowing us to implement the function in one line. If we couldn’t use the `?` operator on `Option`, we’d have to implement this logic using more method calls or a `match` expression.

 Note that you can use the `?` operator on a `Result` in a function that returns `Result`, and you can use the `?` operator on an `Option` in a function that returns `Option`, but you can’t mix and match. The `?` operator won’t automatically convert a `Result` to an `Option` or vice versa; in those cases, you can use methods like the `ok` method on `Result` or the `ok_or` method on `Option` to do the conversion explicitly.

 So far, all the `main` functions we’ve used return `()`. The `main` function is special because it’s the entry and exit point of executable programs, and there are restrictions on what its return type can be for the programs to behave as expected.

 Luckily, `main` can also return a `Result<(), E>`. Listing 9-12 has the code from Listing 9-10 but we’ve changed the return type of `main` to be `Result<(), Box<dyn Error>>` and added a return value `Ok(())` to the end. This code will now compile:

 
```
use std::error::Error;
use std::fs::File;

fn main() -> Result<(), Box<dyn Error>> {
    let greeting_file = File::open("hello.txt")?;

    Ok(())
}
```
 Listing 9-12: Changing `main` to return `Result<(), E>` allows the use of the `?` operator on `Result` values

 The `Box<dyn Error>` type is a *trait object*, which we’ll talk about in the [“Using Trait Objects that Allow for Values of Different Types”](ch17-02-trait-objects#using-trait-objects-that-allow-for-values-of-different-types) section in Chapter 17. For now, you can read `Box<dyn Error>` to mean “any kind of error.” Using `?` on a `Result` value in a `main` function with the error type `Box<dyn Error>` is allowed, because it allows any `Err` value to be returned early. Even though the body of this `main` function will only ever return errors of type `std::io::Error`, by specifying `Box<dyn Error>`, this signature will continue to be correct even if more code that returns other errors is added to the body of `main`.

 When a `main` function returns a `Result<(), E>`, the executable will exit with a value of `0` if `main` returns `Ok(())` and will exit with a nonzero value if `main` returns an `Err` value. Executables written in C return integers when they exit: programs that exit successfully return the integer `0`, and programs that error return some integer other than `0`. Rust also returns integers from executables to be compatible with this convention.

 The `main` function may return any types that implement [the `std::process::Termination` trait](../std/process/trait.termination), which contains a function `report` that returns an `ExitCode`. Consult the standard library documentation for more information on implementing the `Termination` trait for your own types.

 Now that we’ve discussed the details of calling `panic!` or returning `Result`, let’s return to the topic of how to decide which is appropriate to use in which cases.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html>

Traits: Defining Shared Behavior
================================

 A *trait* defines functionality a particular type has and can share with other types. We can use traits to define shared behavior in an abstract way. We can use *trait bounds* to specify that a generic type can be any type that has certain behavior.

 
>  Note: Traits are similar to a feature often called *interfaces* in other languages, although with some differences.
> 
>  

 ### Defining a Trait

 A type’s behavior consists of the methods we can call on that type. Different types share the same behavior if we can call the same methods on all of those types. Trait definitions are a way to group method signatures together to define a set of behaviors necessary to accomplish some purpose.

 For example, let’s say we have multiple structs that hold various kinds and amounts of text: a `NewsArticle` struct that holds a news story filed in a particular location and a `Tweet` that can have at most 280 characters along with metadata that indicates whether it was a new tweet, a retweet, or a reply to another tweet.

 We want to make a media aggregator library crate named `aggregator` that can display summaries of data that might be stored in a `NewsArticle` or `Tweet` instance. To do this, we need a summary from each type, and we’ll request that summary by calling a `summarize` method on an instance. Listing 10-12 shows the definition of a public `Summary` trait that expresses this behavior.

 Filename: src/lib.rs

 
```
pub trait Summary {
    fn summarize(&self) -> String;
}
```
 Listing 10-12: A `Summary` trait that consists of the behavior provided by a `summarize` method

 Here, we declare a trait using the `trait` keyword and then the trait’s name, which is `Summary` in this case. We’ve also declared the trait as `pub` so that crates depending on this crate can make use of this trait too, as we’ll see in a few examples. Inside the curly brackets, we declare the method signatures that describe the behaviors of the types that implement this trait, which in this case is `fn summarize(&self) -> String`.

 After the method signature, instead of providing an implementation within curly brackets, we use a semicolon. Each type implementing this trait must provide its own custom behavior for the body of the method. The compiler will enforce that any type that has the `Summary` trait will have the method `summarize` defined with this signature exactly.

 A trait can have multiple methods in its body: the method signatures are listed one per line and each line ends in a semicolon.

 ### Implementing a Trait on a Type

 Now that we’ve defined the desired signatures of the `Summary` trait’s methods, we can implement it on the types in our media aggregator. Listing 10-13 shows an implementation of the `Summary` trait on the `NewsArticle` struct that uses the headline, the author, and the location to create the return value of `summarize`. For the `Tweet` struct, we define `summarize` as the username followed by the entire text of the tweet, assuming that tweet content is already limited to 280 characters.

 Filename: src/lib.rs

 
```
pub trait Summary {
    fn summarize(&self) -> String;
}

pub struct NewsArticle {
    pub headline: String,
    pub location: String,
    pub author: String,
    pub content: String,
}

impl Summary for NewsArticle {
    fn summarize(&self) -> String {
        format!("{}, by {} ({})", self.headline, self.author, self.location)
    }
}

pub struct Tweet {
    pub username: String,
    pub content: String,
    pub reply: bool,
    pub retweet: bool,
}

impl Summary for Tweet {
    fn summarize(&self) -> String {
        format!("{}: {}", self.username, self.content)
    }
}
```
 Listing 10-13: Implementing the `Summary` trait on the `NewsArticle` and `Tweet` types

 Implementing a trait on a type is similar to implementing regular methods. The difference is that after `impl`, we put the trait name we want to implement, then use the `for` keyword, and then specify the name of the type we want to implement the trait for. Within the `impl` block, we put the method signatures that the trait definition has defined. Instead of adding a semicolon after each signature, we use curly brackets and fill in the method body with the specific behavior that we want the methods of the trait to have for the particular type.

 Now that the library has implemented the `Summary` trait on `NewsArticle` and `Tweet`, users of the crate can call the trait methods on instances of `NewsArticle` and `Tweet` in the same way we call regular methods. The only difference is that the user must bring the trait into scope as well as the types. Here’s an example of how a binary crate could use our `aggregator` library crate:

 
```
use aggregator::{Summary, Tweet};

fn main() {
    let tweet = Tweet {
        username: String::from("horse_ebooks"),
        content: String::from(
            "of course, as you probably already know, people",
        ),
        reply: false,
        retweet: false,
    };

    println!("1 new tweet: {}", tweet.summarize());
}
```
 This code prints `1 new tweet: horse_ebooks: of course, as you probably already know, people`.

 Other crates that depend on the `aggregator` crate can also bring the `Summary` trait into scope to implement `Summary` on their own types. One restriction to note is that we can implement a trait on a type only if at least one of the trait or the type is local to our crate. For example, we can implement standard library traits like `Display` on a custom type like `Tweet` as part of our `aggregator` crate functionality, because the type `Tweet` is local to our `aggregator` crate. We can also implement `Summary` on `Vec<T>` in our `aggregator` crate, because the trait `Summary` is local to our `aggregator` crate.

 But we can’t implement external traits on external types. For example, we can’t implement the `Display` trait on `Vec<T>` within our `aggregator` crate, because `Display` and `Vec<T>` are both defined in the standard library and aren’t local to our `aggregator` crate. This restriction is part of a property called *coherence*, and more specifically the *orphan rule*, so named because the parent type is not present. This rule ensures that other people’s code can’t break your code and vice versa. Without the rule, two crates could implement the same trait for the same type, and Rust wouldn’t know which implementation to use.

 ### Default Implementations

 Sometimes it’s useful to have default behavior for some or all of the methods in a trait instead of requiring implementations for all methods on every type. Then, as we implement the trait on a particular type, we can keep or override each method’s default behavior.

 In Listing 10-14 we specify a default string for the `summarize` method of the `Summary` trait instead of only defining the method signature, as we did in Listing 10-12.

 Filename: src/lib.rs

 
```
pub trait Summary {
    fn summarize(&self) -> String {
        String::from("(Read more...)")
    }
}

pub struct NewsArticle {
    pub headline: String,
    pub location: String,
    pub author: String,
    pub content: String,
}

impl Summary for NewsArticle {}

pub struct Tweet {
    pub username: String,
    pub content: String,
    pub reply: bool,
    pub retweet: bool,
}

impl Summary for Tweet {
    fn summarize(&self) -> String {
        format!("{}: {}", self.username, self.content)
    }
}
```
 Listing 10-14: Defining a `Summary` trait with a default implementation of the `summarize` method

 To use a default implementation to summarize instances of `NewsArticle`, we specify an empty `impl` block with `impl Summary for NewsArticle {}`.

 Even though we’re no longer defining the `summarize` method on `NewsArticle` directly, we’ve provided a default implementation and specified that `NewsArticle` implements the `Summary` trait. As a result, we can still call the `summarize` method on an instance of `NewsArticle`, like this:

 
```
use aggregator::{self, NewsArticle, Summary};

fn main() {
    let article = NewsArticle {
        headline: String::from("Penguins win the Stanley Cup Championship!"),
        location: String::from("Pittsburgh, PA, USA"),
        author: String::from("Iceburgh"),
        content: String::from(
            "The Pittsburgh Penguins once again are the best \
             hockey team in the NHL.",
        ),
    };

    println!("New article available! {}", article.summarize());
}
```
 This code prints `New article available! (Read more...)`.

 Creating a default implementation doesn’t require us to change anything about the implementation of `Summary` on `Tweet` in Listing 10-13. The reason is that the syntax for overriding a default implementation is the same as the syntax for implementing a trait method that doesn’t have a default implementation.

 Default implementations can call other methods in the same trait, even if those other methods don’t have a default implementation. In this way, a trait can provide a lot of useful functionality and only require implementors to specify a small part of it. For example, we could define the `Summary` trait to have a `summarize_author` method whose implementation is required, and then define a `summarize` method that has a default implementation that calls the `summarize_author` method:

 
```
pub trait Summary {
    fn summarize_author(&self) -> String;

    fn summarize(&self) -> String {
        format!("(Read more from {}...)", self.summarize_author())
    }
}

pub struct Tweet {
    pub username: String,
    pub content: String,
    pub reply: bool,
    pub retweet: bool,
}

impl Summary for Tweet {
    fn summarize_author(&self) -> String {
        format!("@{}", self.username)
    }
}
```
 To use this version of `Summary`, we only need to define `summarize_author` when we implement the trait on a type:

 
```
pub trait Summary {
    fn summarize_author(&self) -> String;

    fn summarize(&self) -> String {
        format!("(Read more from {}...)", self.summarize_author())
    }
}

pub struct Tweet {
    pub username: String,
    pub content: String,
    pub reply: bool,
    pub retweet: bool,
}

impl Summary for Tweet {
    fn summarize_author(&self) -> String {
        format!("@{}", self.username)
    }
}
```
 After we define `summarize_author`, we can call `summarize` on instances of the `Tweet` struct, and the default implementation of `summarize` will call the definition of `summarize_author` that we’ve provided. Because we’ve implemented `summarize_author`, the `Summary` trait has given us the behavior of the `summarize` method without requiring us to write any more code.

 
```
use aggregator::{self, Summary, Tweet};

fn main() {
    let tweet = Tweet {
        username: String::from("horse_ebooks"),
        content: String::from(
            "of course, as you probably already know, people",
        ),
        reply: false,
        retweet: false,
    };

    println!("1 new tweet: {}", tweet.summarize());
}
```
 This code prints `1 new tweet: (Read more from @horse_ebooks...)`.

 Note that it isn’t possible to call the default implementation from an overriding implementation of that same method.

 ### Traits as Parameters

 Now that you know how to define and implement traits, we can explore how to use traits to define functions that accept many different types. We'll use the `Summary` trait we implemented on the `NewsArticle` and `Tweet` types in Listing 10-13 to define a `notify` function that calls the `summarize` method on its `item` parameter, which is of some type that implements the `Summary` trait. To do this, we use the `impl Trait` syntax, like this:

 
```
pub trait Summary {
    fn summarize(&self) -> String;
}

pub struct NewsArticle {
    pub headline: String,
    pub location: String,
    pub author: String,
    pub content: String,
}

impl Summary for NewsArticle {
    fn summarize(&self) -> String {
        format!("{}, by {} ({})", self.headline, self.author, self.location)
    }
}

pub struct Tweet {
    pub username: String,
    pub content: String,
    pub reply: bool,
    pub retweet: bool,
}

impl Summary for Tweet {
    fn summarize(&self) -> String {
        format!("{}: {}", self.username, self.content)
    }
}

pub fn notify(item: &impl Summary) {
    println!("Breaking news! {}", item.summarize());
}
```
 Instead of a concrete type for the `item` parameter, we specify the `impl` keyword and the trait name. This parameter accepts any type that implements the specified trait. In the body of `notify`, we can call any methods on `item` that come from the `Summary` trait, such as `summarize`. We can call `notify` and pass in any instance of `NewsArticle` or `Tweet`. Code that calls the function with any other type, such as a `String` or an `i32`, won’t compile because those types don’t implement `Summary`.

 #### Trait Bound Syntax

 The `impl Trait` syntax works for straightforward cases but is actually syntax sugar for a longer form known as a *trait bound*; it looks like this:

 
```
pub fn notify<T: Summary>(item: &T) {
    println!("Breaking news! {}", item.summarize());
}
```
 This longer form is equivalent to the example in the previous section but is more verbose. We place trait bounds with the declaration of the generic type parameter after a colon and inside angle brackets.

 The `impl Trait` syntax is convenient and makes for more concise code in simple cases, while the fuller trait bound syntax can express more complexity in other cases. For example, we can have two parameters that implement `Summary`. Doing so with the `impl Trait` syntax looks like this:

 
```
pub fn notify(item1: &impl Summary, item2: &impl Summary) {
```
 Using `impl Trait` is appropriate if we want this function to allow `item1` and `item2` to have different types (as long as both types implement `Summary`). If we want to force both parameters to have the same type, however, we must use a trait bound, like this:

 
```
pub fn notify<T: Summary>(item1: &T, item2: &T) {
```
 The generic type `T` specified as the type of the `item1` and `item2` parameters constrains the function such that the concrete type of the value passed as an argument for `item1` and `item2` must be the same.

 #### Specifying Multiple Trait Bounds with the `+` Syntax

 We can also specify more than one trait bound. Say we wanted `notify` to use display formatting as well as `summarize` on `item`: we specify in the `notify` definition that `item` must implement both `Display` and `Summary`. We can do so using the `+` syntax:

 
```
pub fn notify(item: &(impl Summary + Display)) {
```
 The `+` syntax is also valid with trait bounds on generic types:

 
```
pub fn notify<T: Summary + Display>(item: &T) {
```
 With the two trait bounds specified, the body of `notify` can call `summarize` and use `{}` to format `item`.

 #### Clearer Trait Bounds with `where` Clauses

 Using too many trait bounds has its downsides. Each generic has its own trait bounds, so functions with multiple generic type parameters can contain lots of trait bound information between the function’s name and its parameter list, making the function signature hard to read. For this reason, Rust has alternate syntax for specifying trait bounds inside a `where` clause after the function signature. So instead of writing this:

 
```
fn some_function<T: Display + Clone, U: Clone + Debug>(t: &T, u: &U) -> i32 {
```
 we can use a `where` clause, like this:

 
```
fn some_function<T, U>(t: &T, u: &U) -> i32
where
    T: Display + Clone,
    U: Clone + Debug,
{
    unimplemented!()
}
```
 This function’s signature is less cluttered: the function name, parameter list, and return type are close together, similar to a function without lots of trait bounds.

 ### Returning Types that Implement Traits

 We can also use the `impl Trait` syntax in the return position to return a value of some type that implements a trait, as shown here:

 
```
pub trait Summary {
    fn summarize(&self) -> String;
}

pub struct NewsArticle {
    pub headline: String,
    pub location: String,
    pub author: String,
    pub content: String,
}

impl Summary for NewsArticle {
    fn summarize(&self) -> String {
        format!("{}, by {} ({})", self.headline, self.author, self.location)
    }
}

pub struct Tweet {
    pub username: String,
    pub content: String,
    pub reply: bool,
    pub retweet: bool,
}

impl Summary for Tweet {
    fn summarize(&self) -> String {
        format!("{}: {}", self.username, self.content)
    }
}

fn returns_summarizable() -> impl Summary {
    Tweet {
        username: String::from("horse_ebooks"),
        content: String::from(
            "of course, as you probably already know, people",
        ),
        reply: false,
        retweet: false,
    }
}
```
 By using `impl Summary` for the return type, we specify that the `returns_summarizable` function returns some type that implements the `Summary` trait without naming the concrete type. In this case, `returns_summarizable` returns a `Tweet`, but the code calling this function doesn’t need to know that.

 The ability to specify a return type only by the trait it implements is especially useful in the context of closures and iterators, which we cover in Chapter 13. Closures and iterators create types that only the compiler knows or types that are very long to specify. The `impl Trait` syntax lets you concisely specify that a function returns some type that implements the `Iterator` trait without needing to write out a very long type.

 However, you can only use `impl Trait` if you’re returning a single type. For example, this code that returns either a `NewsArticle` or a `Tweet` with the return type specified as `impl Summary` wouldn’t work:

 
```
pub trait Summary {
    fn summarize(&self) -> String;
}

pub struct NewsArticle {
    pub headline: String,
    pub location: String,
    pub author: String,
    pub content: String,
}

impl Summary for NewsArticle {
    fn summarize(&self) -> String {
        format!("{}, by {} ({})", self.headline, self.author, self.location)
    }
}

pub struct Tweet {
    pub username: String,
    pub content: String,
    pub reply: bool,
    pub retweet: bool,
}

impl Summary for Tweet {
    fn summarize(&self) -> String {
        format!("{}: {}", self.username, self.content)
    }
}

fn returns_summarizable(switch: bool) -> impl Summary {
    if switch {
        NewsArticle {
            headline: String::from(
                "Penguins win the Stanley Cup Championship!",
            ),
            location: String::from("Pittsburgh, PA, USA"),
            author: String::from("Iceburgh"),
            content: String::from(
                "The Pittsburgh Penguins once again are the best \
                 hockey team in the NHL.",
            ),
        }
    } else {
        Tweet {
            username: String::from("horse_ebooks"),
            content: String::from(
                "of course, as you probably already know, people",
            ),
            reply: false,
            retweet: false,
        }
    }
}
```
 Returning either a `NewsArticle` or a `Tweet` isn’t allowed due to restrictions around how the `impl Trait` syntax is implemented in the compiler. We’ll cover how to write a function with this behavior in the [“Using Trait Objects That Allow for Values of Different Types”](ch17-02-trait-objects#using-trait-objects-that-allow-for-values-of-different-types) section of Chapter 17.

 ### Using Trait Bounds to Conditionally Implement Methods

 By using a trait bound with an `impl` block that uses generic type parameters, we can implement methods conditionally for types that implement the specified traits. For example, the type `Pair<T>` in Listing 10-15 always implements the `new` function to return a new instance of `Pair<T>` (recall from the [“Defining Methods”](ch05-03-method-syntax#defining-methods) section of Chapter 5 that `Self` is a type alias for the type of the `impl` block, which in this case is `Pair<T>`). But in the next `impl` block, `Pair<T>` only implements the `cmp_display` method if its inner type `T` implements the `PartialOrd` trait that enables comparison *and* the `Display` trait that enables printing.

 Filename: src/lib.rs

 
```
use std::fmt::Display;

struct Pair<T> {
    x: T,
    y: T,
}

impl<T> Pair<T> {
    fn new(x: T, y: T) -> Self {
        Self { x, y }
    }
}

impl<T: Display + PartialOrd> Pair<T> {
    fn cmp_display(&self) {
        if self.x >= self.y {
            println!("The largest member is x = {}", self.x);
        } else {
            println!("The largest member is y = {}", self.y);
        }
    }
}
```
 Listing 10-15: Conditionally implementing methods on a generic type depending on trait bounds

 We can also conditionally implement a trait for any type that implements another trait. Implementations of a trait on any type that satisfies the trait bounds are called *blanket implementations* and are extensively used in the Rust standard library. For example, the standard library implements the `ToString` trait on any type that implements the `Display` trait. The `impl` block in the standard library looks similar to this code:

 
```
impl<T: Display> ToString for T {
    // --snip--
}
```
 Because the standard library has this blanket implementation, we can call the `to_string` method defined by the `ToString` trait on any type that implements the `Display` trait. For example, we can turn integers into their corresponding `String` values like this because integers implement `Display`:

 
```
#![allow(unused)]
fn main() {
let s = 3.to_string();
}
```
 Blanket implementations appear in the documentation for the trait in the “Implementors” section.

 Traits and trait bounds let us write code that uses generic type parameters to reduce duplication but also specify to the compiler that we want the generic type to have particular behavior. The compiler can then use the trait bound information to check that all the concrete types used with our code provide the correct behavior. In dynamically typed languages, we would get an error at runtime if we called a method on a type which didn’t define the method. But Rust moves these errors to compile time so we’re forced to fix the problems before our code is even able to run. Additionally, we don’t have to write code that checks for behavior at runtime because we’ve already checked at compile time. Doing so improves performance without having to give up the flexibility of generics.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch10-02-traits.html>

Refactoring to Improve Modularity and Error Handling
====================================================

 To improve our program, we’ll fix four problems that have to do with the program’s structure and how it’s handling potential errors. First, our `main` function now performs two tasks: it parses arguments and reads files. As our program grows, the number of separate tasks the `main` function handles will increase. As a function gains responsibilities, it becomes more difficult to reason about, harder to test, and harder to change without breaking one of its parts. It’s best to separate functionality so each function is responsible for one task.

 This issue also ties into the second problem: although `query` and `file_path` are configuration variables to our program, variables like `contents` are used to perform the program’s logic. The longer `main` becomes, the more variables we’ll need to bring into scope; the more variables we have in scope, the harder it will be to keep track of the purpose of each. It’s best to group the configuration variables into one structure to make their purpose clear.

 The third problem is that we’ve used `expect` to print an error message when reading the file fails, but the error message just prints `Should have been able to read the file`. Reading a file can fail in a number of ways: for example, the file could be missing, or we might not have permission to open it. Right now, regardless of the situation, we’d print the same error message for everything, which wouldn’t give the user any information!

 Fourth, we use `expect` repeatedly to handle different errors, and if the user runs our program without specifying enough arguments, they’ll get an `index out of bounds` error from Rust that doesn’t clearly explain the problem. It would be best if all the error-handling code were in one place so future maintainers had only one place to consult the code if the error-handling logic needed to change. Having all the error-handling code in one place will also ensure that we’re printing messages that will be meaningful to our end users.

 Let’s address these four problems by refactoring our project.

 ### Separation of Concerns for Binary Projects

 The organizational problem of allocating responsibility for multiple tasks to the `main` function is common to many binary projects. As a result, the Rust community has developed guidelines for splitting the separate concerns of a binary program when `main` starts getting large. This process has the following steps:

 * Split your program into a *main.rs* and a *lib.rs* and move your program’s logic to *lib.rs*.
* As long as your command line parsing logic is small, it can remain in *main.rs*.
* When the command line parsing logic starts getting complicated, extract it from *main.rs* and move it to *lib.rs*.

 The responsibilities that remain in the `main` function after this process should be limited to the following:

 * Calling the command line parsing logic with the argument values
* Setting up any other configuration
* Calling a `run` function in *lib.rs*
* Handling the error if `run` returns an error

 This pattern is about separating concerns: *main.rs* handles running the program, and *lib.rs* handles all the logic of the task at hand. Because you can’t test the `main` function directly, this structure lets you test all of your program’s logic by moving it into functions in *lib.rs*. The code that remains in *main.rs* will be small enough to verify its correctness by reading it. Let’s rework our program by following this process.

 #### Extracting the Argument Parser

 We’ll extract the functionality for parsing arguments into a function that `main` will call to prepare for moving the command line parsing logic to *src/lib.rs*. Listing 12-5 shows the new start of `main` that calls a new function `parse_config`, which we’ll define in *src/main.rs* for the moment.

 Filename: src/main.rs

 
```
use std::env;
use std::fs;

fn main() {
    let args: Vec<String> = env::args().collect();

    let (query, file_path) = parse_config(&args);

    // --snip--

    println!("Searching for {}", query);
    println!("In file {}", file_path);

    let contents = fs::read_to_string(file_path)
        .expect("Should have been able to read the file");

    println!("With text:\n{contents}");
}

fn parse_config(args: &[String]) -> (&str, &str) {
    let query = &args[1];
    let file_path = &args[2];

    (query, file_path)
}
```
 Listing 12-5: Extracting a `parse_config` function from `main`

 We’re still collecting the command line arguments into a vector, but instead of assigning the argument value at index 1 to the variable `query` and the argument value at index 2 to the variable `file_path` within the `main` function, we pass the whole vector to the `parse_config` function. The `parse_config` function then holds the logic that determines which argument goes in which variable and passes the values back to `main`. We still create the `query` and `file_path` variables in `main`, but `main` no longer has the responsibility of determining how the command line arguments and variables correspond.

 This rework may seem like overkill for our small program, but we’re refactoring in small, incremental steps. After making this change, run the program again to verify that the argument parsing still works. It’s good to check your progress often, to help identify the cause of problems when they occur.

 #### Grouping Configuration Values

 We can take another small step to improve the `parse_config` function further. At the moment, we’re returning a tuple, but then we immediately break that tuple into individual parts again. This is a sign that perhaps we don’t have the right abstraction yet.

 Another indicator that shows there’s room for improvement is the `config` part of `parse_config`, which implies that the two values we return are related and are both part of one configuration value. We’re not currently conveying this meaning in the structure of the data other than by grouping the two values into a tuple; we’ll instead put the two values into one struct and give each of the struct fields a meaningful name. Doing so will make it easier for future maintainers of this code to understand how the different values relate to each other and what their purpose is.

 Listing 12-6 shows the improvements to the `parse_config` function.

 Filename: src/main.rs

 
```
use std::env;
use std::fs;

fn main() {
    let args: Vec<String> = env::args().collect();

    let config = parse_config(&args);

    println!("Searching for {}", config.query);
    println!("In file {}", config.file_path);

    let contents = fs::read_to_string(config.file_path)
        .expect("Should have been able to read the file");

    // --snip--

    println!("With text:\n{contents}");
}

struct Config {
    query: String,
    file_path: String,
}

fn parse_config(args: &[String]) -> Config {
    let query = args[1].clone();
    let file_path = args[2].clone();

    Config { query, file_path }
}
```
 Listing 12-6: Refactoring `parse_config` to return an instance of a `Config` struct

 We’ve added a struct named `Config` defined to have fields named `query` and `file_path`. The signature of `parse_config` now indicates that it returns a `Config` value. In the body of `parse_config`, where we used to return string slices that reference `String` values in `args`, we now define `Config` to contain owned `String` values. The `args` variable in `main` is the owner of the argument values and is only letting the `parse_config` function borrow them, which means we’d violate Rust’s borrowing rules if `Config` tried to take ownership of the values in `args`.

 There are a number of ways we could manage the `String` data; the easiest, though somewhat inefficient, route is to call the `clone` method on the values. This will make a full copy of the data for the `Config` instance to own, which takes more time and memory than storing a reference to the string data. However, cloning the data also makes our code very straightforward because we don’t have to manage the lifetimes of the references; in this circumstance, giving up a little performance to gain simplicity is a worthwhile trade-off.

 
>  ### The Trade-Offs of Using `clone`
> 
>  There’s a tendency among many Rustaceans to avoid using `clone` to fix ownership problems because of its runtime cost. In [Chapter 13](ch13-00-functional-features), you’ll learn how to use more efficient methods in this type of situation. But for now, it’s okay to copy a few strings to continue making progress because you’ll make these copies only once and your file path and query string are very small. It’s better to have a working program that’s a bit inefficient than to try to hyperoptimize code on your first pass. As you become more experienced with Rust, it’ll be easier to start with the most efficient solution, but for now, it’s perfectly acceptable to call `clone`.
> 
>  

 We’ve updated `main` so it places the instance of `Config` returned by `parse_config` into a variable named `config`, and we updated the code that previously used the separate `query` and `file_path` variables so it now uses the fields on the `Config` struct instead.

 Now our code more clearly conveys that `query` and `file_path` are related and that their purpose is to configure how the program will work. Any code that uses these values knows to find them in the `config` instance in the fields named for their purpose.

 #### Creating a Constructor for `Config`

 So far, we’ve extracted the logic responsible for parsing the command line arguments from `main` and placed it in the `parse_config` function. Doing so helped us to see that the `query` and `file_path` values were related and that relationship should be conveyed in our code. We then added a `Config` struct to name the related purpose of `query` and `file_path` and to be able to return the values’ names as struct field names from the `parse_config` function.

 So now that the purpose of the `parse_config` function is to create a `Config` instance, we can change `parse_config` from a plain function to a function named `new` that is associated with the `Config` struct. Making this change will make the code more idiomatic. We can create instances of types in the standard library, such as `String`, by calling `String::new`. Similarly, by changing `parse_config` into a `new` function associated with `Config`, we’ll be able to create instances of `Config` by calling `Config::new`. Listing 12-7 shows the changes we need to make.

 Filename: src/main.rs

 
```
use std::env;
use std::fs;

fn main() {
    let args: Vec<String> = env::args().collect();

    let config = Config::new(&args);

    println!("Searching for {}", config.query);
    println!("In file {}", config.file_path);

    let contents = fs::read_to_string(config.file_path)
        .expect("Should have been able to read the file");

    println!("With text:\n{contents}");

    // --snip--
}

// --snip--

struct Config {
    query: String,
    file_path: String,
}

impl Config {
    fn new(args: &[String]) -> Config {
        let query = args[1].clone();
        let file_path = args[2].clone();

        Config { query, file_path }
    }
}
```
 Listing 12-7: Changing `parse_config` into `Config::new`

 We’ve updated `main` where we were calling `parse_config` to instead call `Config::new`. We’ve changed the name of `parse_config` to `new` and moved it within an `impl` block, which associates the `new` function with `Config`. Try compiling this code again to make sure it works.

 ### Fixing the Error Handling

 Now we’ll work on fixing our error handling. Recall that attempting to access the values in the `args` vector at index 1 or index 2 will cause the program to panic if the vector contains fewer than three items. Try running the program without any arguments; it will look like this:

 
```
$ cargo run
   Compiling minigrep v0.1.0 (file:///projects/minigrep)
    Finished dev [unoptimized + debuginfo] target(s) in 0.0s
     Running `target/debug/minigrep`
thread 'main' panicked at 'index out of bounds: the len is 1 but the index is 1', src/main.rs:27:21
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

```
 The line `index out of bounds: the len is 1 but the index is 1` is an error message intended for programmers. It won’t help our end users understand what they should do instead. Let’s fix that now.

 #### Improving the Error Message

 In Listing 12-8, we add a check in the `new` function that will verify that the slice is long enough before accessing index 1 and 2. If the slice isn’t long enough, the program panics and displays a better error message.

 Filename: src/main.rs

 
```
use std::env;
use std::fs;

fn main() {
    let args: Vec<String> = env::args().collect();

    let config = Config::new(&args);

    println!("Searching for {}", config.query);
    println!("In file {}", config.file_path);

    let contents = fs::read_to_string(config.file_path)
        .expect("Should have been able to read the file");

    println!("With text:\n{contents}");
}

struct Config {
    query: String,
    file_path: String,
}

impl Config {
    // --snip--
    fn new(args: &[String]) -> Config {
        if args.len() < 3 {
            panic!("not enough arguments");
        }
        // --snip--

        let query = args[1].clone();
        let file_path = args[2].clone();

        Config { query, file_path }
    }
}
```
 Listing 12-8: Adding a check for the number of arguments

 This code is similar to [the `Guess::new` function we wrote in Listing 9-13](ch09-03-to-panic-or-not-to-panic#creating-custom-types-for-validation), where we called `panic!` when the `value` argument was out of the range of valid values. Instead of checking for a range of values here, we’re checking that the length of `args` is at least 3 and the rest of the function can operate under the assumption that this condition has been met. If `args` has fewer than three items, this condition will be true, and we call the `panic!` macro to end the program immediately.

 With these extra few lines of code in `new`, let’s run the program without any arguments again to see what the error looks like now:

 
```
$ cargo run
   Compiling minigrep v0.1.0 (file:///projects/minigrep)
    Finished dev [unoptimized + debuginfo] target(s) in 0.0s
     Running `target/debug/minigrep`
thread 'main' panicked at 'not enough arguments', src/main.rs:26:13
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

```
 This output is better: we now have a reasonable error message. However, we also have extraneous information we don’t want to give to our users. Perhaps using the technique we used in Listing 9-13 isn’t the best to use here: a call to `panic!` is more appropriate for a programming problem than a usage problem, [as discussed in Chapter 9](ch09-03-to-panic-or-not-to-panic#guidelines-for-error-handling). Instead, we’ll use the other technique you learned about in Chapter 9—[returning a `Result`](ch09-02-recoverable-errors-with-result) that indicates either success or an error.

 #### Returning a `Result` Instead of Calling `panic!`

 We can instead return a `Result` value that will contain a `Config` instance in the successful case and will describe the problem in the error case. We’re also going to change the function name from `new` to `build` because many programmers expect `new` functions to never fail. When `Config::build` is communicating to `main`, we can use the `Result` type to signal there was a problem. Then we can change `main` to convert an `Err` variant into a more practical error for our users without the surrounding text about `thread 'main'` and `RUST_BACKTRACE` that a call to `panic!` causes.

 Listing 12-9 shows the changes we need to make to the return value of the function we’re now calling `Config::build` and the body of the function needed to return a `Result`. Note that this won’t compile until we update `main` as well, which we’ll do in the next listing.

 Filename: src/main.rs

 
```
use std::env;
use std::fs;

fn main() {
    let args: Vec<String> = env::args().collect();

    let config = Config::new(&args);

    println!("Searching for {}", config.query);
    println!("In file {}", config.file_path);

    let contents = fs::read_to_string(config.file_path)
        .expect("Should have been able to read the file");

    println!("With text:\n{contents}");
}

struct Config {
    query: String,
    file_path: String,
}

impl Config {
    fn build(args: &[String]) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("not enough arguments");
        }

        let query = args[1].clone();
        let file_path = args[2].clone();

        Ok(Config { query, file_path })
    }
}
```
 Listing 12-9: Returning a `Result` from `Config::build`

 Our `build` function returns a `Result` with a `Config` instance in the success case and a `&'static str` in the error case. Our error values will always be string literals that have the `'static` lifetime.

 We’ve made two changes in the body of the function: instead of calling `panic!` when the user doesn’t pass enough arguments, we now return an `Err` value, and we’ve wrapped the `Config` return value in an `Ok`. These changes make the function conform to its new type signature.

 Returning an `Err` value from `Config::build` allows the `main` function to handle the `Result` value returned from the `build` function and exit the process more cleanly in the error case.

 #### Calling `Config::build` and Handling Errors

 To handle the error case and print a user-friendly message, we need to update `main` to handle the `Result` being returned by `Config::build`, as shown in Listing 12-10. We’ll also take the responsibility of exiting the command line tool with a nonzero error code away from `panic!` and instead implement it by hand. A nonzero exit status is a convention to signal to the process that called our program that the program exited with an error state.

 Filename: src/main.rs

 
```
use std::env;
use std::fs;
use std::process;

fn main() {
    let args: Vec<String> = env::args().collect();

    let config = Config::build(&args).unwrap_or_else(|err| {
        println!("Problem parsing arguments: {err}");
        process::exit(1);
    });

    // --snip--

    println!("Searching for {}", config.query);
    println!("In file {}", config.file_path);

    let contents = fs::read_to_string(config.file_path)
        .expect("Should have been able to read the file");

    println!("With text:\n{contents}");
}

struct Config {
    query: String,
    file_path: String,
}

impl Config {
    fn build(args: &[String]) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("not enough arguments");
        }

        let query = args[1].clone();
        let file_path = args[2].clone();

        Ok(Config { query, file_path })
    }
}
```
 Listing 12-10: Exiting with an error code if building a `Config` fails

 In this listing, we’ve used a method we haven’t covered in detail yet: `unwrap_or_else`, which is defined on `Result<T, E>` by the standard library. Using `unwrap_or_else` allows us to define some custom, non-`panic!` error handling. If the `Result` is an `Ok` value, this method’s behavior is similar to `unwrap`: it returns the inner value `Ok` is wrapping. However, if the value is an `Err` value, this method calls the code in the *closure*, which is an anonymous function we define and pass as an argument to `unwrap_or_else`. We’ll cover closures in more detail in [Chapter 13](ch13-00-functional-features). For now, you just need to know that `unwrap_or_else` will pass the inner value of the `Err`, which in this case is the static string `"not enough arguments"` that we added in Listing 12-9, to our closure in the argument `err` that appears between the vertical pipes. The code in the closure can then use the `err` value when it runs.

 We’ve added a new `use` line to bring `process` from the standard library into scope. The code in the closure that will be run in the error case is only two lines: we print the `err` value and then call `process::exit`. The `process::exit` function will stop the program immediately and return the number that was passed as the exit status code. This is similar to the `panic!`-based handling we used in Listing 12-8, but we no longer get all the extra output. Let’s try it:

 
```
$ cargo run
   Compiling minigrep v0.1.0 (file:///projects/minigrep)
    Finished dev [unoptimized + debuginfo] target(s) in 0.48s
     Running `target/debug/minigrep`
Problem parsing arguments: not enough arguments

```
 Great! This output is much friendlier for our users.

 ### Extracting Logic from `main`

 Now that we’ve finished refactoring the configuration parsing, let’s turn to the program’s logic. As we stated in [“Separation of Concerns for Binary Projects”](#separation-of-concerns-for-binary-projects), we’ll extract a function named `run` that will hold all the logic currently in the `main` function that isn’t involved with setting up configuration or handling errors. When we’re done, `main` will be concise and easy to verify by inspection, and we’ll be able to write tests for all the other logic.

 Listing 12-11 shows the extracted `run` function. For now, we’re just making the small, incremental improvement of extracting the function. We’re still defining the function in *src/main.rs*.

 Filename: src/main.rs

 
```
use std::env;
use std::fs;
use std::process;

fn main() {
    // --snip--

    let args: Vec<String> = env::args().collect();

    let config = Config::build(&args).unwrap_or_else(|err| {
        println!("Problem parsing arguments: {err}");
        process::exit(1);
    });

    println!("Searching for {}", config.query);
    println!("In file {}", config.file_path);

    run(config);
}

fn run(config: Config) {
    let contents = fs::read_to_string(config.file_path)
        .expect("Should have been able to read the file");

    println!("With text:\n{contents}");
}

// --snip--

struct Config {
    query: String,
    file_path: String,
}

impl Config {
    fn build(args: &[String]) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("not enough arguments");
        }

        let query = args[1].clone();
        let file_path = args[2].clone();

        Ok(Config { query, file_path })
    }
}
```
 Listing 12-11: Extracting a `run` function containing the rest of the program logic

 The `run` function now contains all the remaining logic from `main`, starting from reading the file. The `run` function takes the `Config` instance as an argument.

 #### Returning Errors from the `run` Function

 With the remaining program logic separated into the `run` function, we can improve the error handling, as we did with `Config::build` in Listing 12-9. Instead of allowing the program to panic by calling `expect`, the `run` function will return a `Result<T, E>` when something goes wrong. This will let us further consolidate the logic around handling errors into `main` in a user-friendly way. Listing 12-12 shows the changes we need to make to the signature and body of `run`.

 Filename: src/main.rs

 
```
use std::env;
use std::fs;
use std::process;
use std::error::Error;

// --snip--


fn main() {
    let args: Vec<String> = env::args().collect();

    let config = Config::build(&args).unwrap_or_else(|err| {
        println!("Problem parsing arguments: {err}");
        process::exit(1);
    });

    println!("Searching for {}", config.query);
    println!("In file {}", config.file_path);

    run(config);
}

fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.file_path)?;

    println!("With text:\n{contents}");

    Ok(())
}

struct Config {
    query: String,
    file_path: String,
}

impl Config {
    fn build(args: &[String]) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("not enough arguments");
        }

        let query = args[1].clone();
        let file_path = args[2].clone();

        Ok(Config { query, file_path })
    }
}
```
 Listing 12-12: Changing the `run` function to return `Result`

 We’ve made three significant changes here. First, we changed the return type of the `run` function to `Result<(), Box<dyn Error>>`. This function previously returned the unit type, `()`, and we keep that as the value returned in the `Ok` case.

 For the error type, we used the *trait object* `Box<dyn Error>` (and we’ve brought `std::error::Error` into scope with a `use` statement at the top). We’ll cover trait objects in [Chapter 17](ch17-00-oop). For now, just know that `Box<dyn Error>` means the function will return a type that implements the `Error` trait, but we don’t have to specify what particular type the return value will be. This gives us flexibility to return error values that may be of different types in different error cases. The `dyn` keyword is short for “dynamic.”

 Second, we’ve removed the call to `expect` in favor of the `?` operator, as we talked about in [Chapter 9](ch09-02-recoverable-errors-with-result#a-shortcut-for-propagating-errors-the--operator). Rather than `panic!` on an error, `?` will return the error value from the current function for the caller to handle.

 Third, the `run` function now returns an `Ok` value in the success case. We’ve declared the `run` function’s success type as `()` in the signature, which means we need to wrap the unit type value in the `Ok` value. This `Ok(())` syntax might look a bit strange at first, but using `()` like this is the idiomatic way to indicate that we’re calling `run` for its side effects only; it doesn’t return a value we need.

 When you run this code, it will compile but will display a warning:

 
```
$ cargo run the poem.txt
   Compiling minigrep v0.1.0 (file:///projects/minigrep)
warning: unused `Result` that must be used
  --> src/main.rs:19:5
   |
19 |     run(config);
   |     ^^^^^^^^^^^
   |
   = note: this `Result` may be an `Err` variant, which should be handled
   = note: `#[warn(unused_must_use)]` on by default

warning: `minigrep` (bin "minigrep") generated 1 warning
    Finished dev [unoptimized + debuginfo] target(s) in 0.71s
     Running `target/debug/minigrep the poem.txt`
Searching for the
In file poem.txt
With text:
I'm nobody! Who are you?
Are you nobody, too?
Then there's a pair of us - don't tell!
They'd banish us, you know.

How dreary to be somebody!
How public, like a frog
To tell your name the livelong day
To an admiring bog!


```
 Rust tells us that our code ignored the `Result` value and the `Result` value might indicate that an error occurred. But we’re not checking to see whether or not there was an error, and the compiler reminds us that we probably meant to have some error-handling code here! Let’s rectify that problem now.

 #### Handling Errors Returned from `run` in `main`

 We’ll check for errors and handle them using a technique similar to one we used with `Config::build` in Listing 12-10, but with a slight difference:

 Filename: src/main.rs

 
```
use std::env;
use std::error::Error;
use std::fs;
use std::process;

fn main() {
    // --snip--

    let args: Vec<String> = env::args().collect();

    let config = Config::build(&args).unwrap_or_else(|err| {
        println!("Problem parsing arguments: {err}");
        process::exit(1);
    });

    println!("Searching for {}", config.query);
    println!("In file {}", config.file_path);

    if let Err(e) = run(config) {
        println!("Application error: {e}");
        process::exit(1);
    }
}

fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.file_path)?;

    println!("With text:\n{contents}");

    Ok(())
}

struct Config {
    query: String,
    file_path: String,
}

impl Config {
    fn build(args: &[String]) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("not enough arguments");
        }

        let query = args[1].clone();
        let file_path = args[2].clone();

        Ok(Config { query, file_path })
    }
}
```
 We use `if let` rather than `unwrap_or_else` to check whether `run` returns an `Err` value and call `process::exit(1)` if it does. The `run` function doesn’t return a value that we want to `unwrap` in the same way that `Config::build` returns the `Config` instance. Because `run` returns `()` in the success case, we only care about detecting an error, so we don’t need `unwrap_or_else` to return the unwrapped value, which would only be `()`.

 The bodies of the `if let` and the `unwrap_or_else` functions are the same in both cases: we print the error and exit.

 ### Splitting Code into a Library Crate

 Our `minigrep` project is looking good so far! Now we’ll split the *src/main.rs* file and put some code into the *src/lib.rs* file. That way we can test the code and have a *src/main.rs* file with fewer responsibilities.

 Let’s move all the code that isn’t the `main` function from *src/main.rs* to *src/lib.rs*:

 * The `run` function definition
* The relevant `use` statements
* The definition of `Config`
* The `Config::build` function definition

 The contents of *src/lib.rs* should have the signatures shown in Listing 12-13 (we’ve omitted the bodies of the functions for brevity). Note that this won’t compile until we modify *src/main.rs* in Listing 12-14.

 Filename: src/lib.rs

 
```
use std::error::Error;
use std::fs;

pub struct Config {
    pub query: String,
    pub file_path: String,
}

impl Config {
    pub fn build(args: &[String]) -> Result<Config, &'static str> {
        // --snip--
        if args.len() < 3 {
            return Err("not enough arguments");
        }

        let query = args[1].clone();
        let file_path = args[2].clone();

        Ok(Config { query, file_path })
    }
}

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    // --snip--
    let contents = fs::read_to_string(config.file_path)?;

    println!("With text:\n{contents}");

    Ok(())
}
```
 Listing 12-13: Moving `Config` and `run` into *src/lib.rs*

 We’ve made liberal use of the `pub` keyword: on `Config`, on its fields and its `build` method, and on the `run` function. We now have a library crate that has a public API we can test!

 Now we need to bring the code we moved to *src/lib.rs* into the scope of the binary crate in *src/main.rs*, as shown in Listing 12-14.

 Filename: src/main.rs

 
```
use std::env;
use std::process;

use minigrep::Config;

fn main() {
    // --snip--
    let args: Vec<String> = env::args().collect();

    let config = Config::build(&args).unwrap_or_else(|err| {
        println!("Problem parsing arguments: {err}");
        process::exit(1);
    });

    println!("Searching for {}", config.query);
    println!("In file {}", config.file_path);

    if let Err(e) = minigrep::run(config) {
        // --snip--
        println!("Application error: {e}");
        process::exit(1);
    }
}
```
 Listing 12-14: Using the `minigrep` library crate in *src/main.rs*

 We add a `use minigrep::Config` line to bring the `Config` type from the library crate into the binary crate’s scope, and we prefix the `run` function with our crate name. Now all the functionality should be connected and should work. Run the program with `cargo run` and make sure everything works correctly.

 Whew! That was a lot of work, but we’ve set ourselves up for success in the future. Now it’s much easier to handle errors, and we’ve made the code more modular. Almost all of our work will be done in *src/lib.rs* from here on out.

 Let’s take advantage of this newfound modularity by doing something that would have been difficult with the old code but is easy with the new code: we’ll write some tests!



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch12-03-improving-error-handling-and-modularity.html>

Developing the Library’s Functionality with Test-Driven Development
===================================================================

 Now that we’ve extracted the logic into *src/lib.rs* and left the argument collecting and error handling in *src/main.rs*, it’s much easier to write tests for the core functionality of our code. We can call functions directly with various arguments and check return values without having to call our binary from the command line.

 In this section, we’ll add the searching logic to the `minigrep` program using the test-driven development (TDD) process with the following steps:

 1. Write a test that fails and run it to make sure it fails for the reason you expect.
2. Write or modify just enough code to make the new test pass.
3. Refactor the code you just added or changed and make sure the tests continue to pass.
4. Repeat from step 1!

 Though it’s just one of many ways to write software, TDD can help drive code design. Writing the test before you write the code that makes the test pass helps to maintain high test coverage throughout the process.

 We’ll test drive the implementation of the functionality that will actually do the searching for the query string in the file contents and produce a list of lines that match the query. We’ll add this functionality in a function called `search`.

 ### Writing a Failing Test

 Because we don’t need them anymore, let’s remove the `println!` statements from *src/lib.rs* and *src/main.rs* that we used to check the program’s behavior. Then, in *src/lib.rs*, add a `tests` module with a test function, as we did in [Chapter 11](ch11-01-writing-tests#the-anatomy-of-a-test-function). The test function specifies the behavior we want the `search` function to have: it will take a query and the text to search, and it will return only the lines from the text that contain the query. Listing 12-15 shows this test, which won’t compile yet.

 Filename: src/lib.rs

 
```
use std::error::Error;
use std::fs;

pub struct Config {
    pub query: String,
    pub file_path: String,
}

impl Config {
    pub fn build(args: &[String]) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("not enough arguments");
        }

        let query = args[1].clone();
        let file_path = args[2].clone();

        Ok(Config { query, file_path })
    }
}

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.file_path)?;

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn one_result() {
        let query = "duct";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.";

        assert_eq!(vec!["safe, fast, productive."], search(query, contents));
    }
}
```
 Listing 12-15: Creating a failing test for the `search` function we wish we had

 This test searches for the string `"duct"`. The text we’re searching is three lines, only one of which contains `"duct"` (Note that the backslash after the opening double quote tells Rust not to put a newline character at the beginning of the contents of this string literal). We assert that the value returned from the `search` function contains only the line we expect.

 We aren’t yet able to run this test and watch it fail because the test doesn’t even compile: the `search` function doesn’t exist yet! In accordance with TDD principles, we’ll add just enough code to get the test to compile and run by adding a definition of the `search` function that always returns an empty vector, as shown in Listing 12-16. Then the test should compile and fail because an empty vector doesn’t match a vector containing the line `"safe, fast, productive."`

 Filename: src/lib.rs

 
```
use std::error::Error;
use std::fs;

pub struct Config {
    pub query: String,
    pub file_path: String,
}

impl Config {
    pub fn build(args: &[String]) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("not enough arguments");
        }

        let query = args[1].clone();
        let file_path = args[2].clone();

        Ok(Config { query, file_path })
    }
}

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.file_path)?;

    Ok(())
}

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    vec![]
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn one_result() {
        let query = "duct";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.";

        assert_eq!(vec!["safe, fast, productive."], search(query, contents));
    }
}
```
 Listing 12-16: Defining just enough of the `search` function so our test will compile

 Notice that we need to define an explicit lifetime `'a` in the signature of `search` and use that lifetime with the `contents` argument and the return value. Recall in [Chapter 10](ch10-03-lifetime-syntax) that the lifetime parameters specify which argument lifetime is connected to the lifetime of the return value. In this case, we indicate that the returned vector should contain string slices that reference slices of the argument `contents` (rather than the argument `query`).

 In other words, we tell Rust that the data returned by the `search` function will live as long as the data passed into the `search` function in the `contents` argument. This is important! The data referenced *by* a slice needs to be valid for the reference to be valid; if the compiler assumes we’re making string slices of `query` rather than `contents`, it will do its safety checking incorrectly.

 If we forget the lifetime annotations and try to compile this function, we’ll get this error:

 
```
$ cargo build
   Compiling minigrep v0.1.0 (file:///projects/minigrep)
error[E0106]: missing lifetime specifier
  --> src/lib.rs:28:51
   |
28 | pub fn search(query: &str, contents: &str) -> Vec<&str> {
   |                      ----            ----         ^ expected named lifetime parameter
   |
   = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `query` or `contents`
help: consider introducing a named lifetime parameter
   |
28 | pub fn search<'a>(query: &'a str, contents: &'a str) -> Vec<&'a str> {
   |              ++++         ++                 ++              ++

For more information about this error, try `rustc --explain E0106`.
error: could not compile `minigrep` due to previous error

```
 Rust can’t possibly know which of the two arguments we need, so we need to tell it explicitly. Because `contents` is the argument that contains all of our text and we want to return the parts of that text that match, we know `contents` is the argument that should be connected to the return value using the lifetime syntax.

 Other programming languages don’t require you to connect arguments to return values in the signature, but this practice will get easier over time. You might want to compare this example with the [“Validating References with Lifetimes”](ch10-03-lifetime-syntax#validating-references-with-lifetimes) section in Chapter 10.

 Now let’s run the test:

 
```
$ cargo test
   Compiling minigrep v0.1.0 (file:///projects/minigrep)
    Finished test [unoptimized + debuginfo] target(s) in 0.97s
     Running unittests src/lib.rs (target/debug/deps/minigrep-9cd200e5fac0fc94)

running 1 test
test tests::one_result ... FAILED

failures:

---- tests::one_result stdout ----
thread 'tests::one_result' panicked at 'assertion failed: `(left == right)`
  left: `["safe, fast, productive."]`,
 right: `[]`', src/lib.rs:44:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace


failures:
    tests::one_result

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

error: test failed, to rerun pass `--lib`

```
 Great, the test fails, exactly as we expected. Let’s get the test to pass!

 ### Writing Code to Pass the Test

 Currently, our test is failing because we always return an empty vector. To fix that and implement `search`, our program needs to follow these steps:

 * Iterate through each line of the contents.
* Check whether the line contains our query string.
* If it does, add it to the list of values we’re returning.
* If it doesn’t, do nothing.
* Return the list of results that match.

 Let’s work through each step, starting with iterating through lines.

 #### Iterating Through Lines with the `lines` Method

 Rust has a helpful method to handle line-by-line iteration of strings, conveniently named `lines`, that works as shown in Listing 12-17. Note this won’t compile yet.

 Filename: src/lib.rs

 
```
use std::error::Error;
use std::fs;

pub struct Config {
    pub query: String,
    pub file_path: String,
}

impl Config {
    pub fn build(args: &[String]) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("not enough arguments");
        }

        let query = args[1].clone();
        let file_path = args[2].clone();

        Ok(Config { query, file_path })
    }
}

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.file_path)?;

    Ok(())
}

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    for line in contents.lines() {
        // do something with line
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn one_result() {
        let query = "duct";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.";

        assert_eq!(vec!["safe, fast, productive."], search(query, contents));
    }
}
```
 Listing 12-17: Iterating through each line in `contents` 

 The `lines` method returns an iterator. We’ll talk about iterators in depth in [Chapter 13](ch13-02-iterators), but recall that you saw this way of using an iterator in [Listing 3-5](ch03-05-control-flow#looping-through-a-collection-with-for), where we used a `for` loop with an iterator to run some code on each item in a collection.

 #### Searching Each Line for the Query

 Next, we’ll check whether the current line contains our query string. Fortunately, strings have a helpful method named `contains` that does this for us! Add a call to the `contains` method in the `search` function, as shown in Listing 12-18. Note this still won’t compile yet.

 Filename: src/lib.rs

 
```
use std::error::Error;
use std::fs;

pub struct Config {
    pub query: String,
    pub file_path: String,
}

impl Config {
    pub fn build(args: &[String]) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("not enough arguments");
        }

        let query = args[1].clone();
        let file_path = args[2].clone();

        Ok(Config { query, file_path })
    }
}

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.file_path)?;

    Ok(())
}

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    for line in contents.lines() {
        if line.contains(query) {
            // do something with line
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn one_result() {
        let query = "duct";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.";

        assert_eq!(vec!["safe, fast, productive."], search(query, contents));
    }
}
```
 Listing 12-18: Adding functionality to see whether the line contains the string in `query`

 At the moment, we’re building up functionality. To get it to compile, we need to return a value from the body as we indicated we would in the function signature.

 #### Storing Matching Lines

 To finish this function, we need a way to store the matching lines that we want to return. For that, we can make a mutable vector before the `for` loop and call the `push` method to store a `line` in the vector. After the `for` loop, we return the vector, as shown in Listing 12-19.

 Filename: src/lib.rs

 
```
use std::error::Error;
use std::fs;

pub struct Config {
    pub query: String,
    pub file_path: String,
}

impl Config {
    pub fn build(args: &[String]) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("not enough arguments");
        }

        let query = args[1].clone();
        let file_path = args[2].clone();

        Ok(Config { query, file_path })
    }
}

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.file_path)?;

    Ok(())
}

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    let mut results = Vec::new();

    for line in contents.lines() {
        if line.contains(query) {
            results.push(line);
        }
    }

    results
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn one_result() {
        let query = "duct";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.";

        assert_eq!(vec!["safe, fast, productive."], search(query, contents));
    }
}
```
 Listing 12-19: Storing the lines that match so we can return them

 Now the `search` function should return only the lines that contain `query`, and our test should pass. Let’s run the test:

 
```
$ cargo test
   Compiling minigrep v0.1.0 (file:///projects/minigrep)
    Finished test [unoptimized + debuginfo] target(s) in 1.22s
     Running unittests src/lib.rs (target/debug/deps/minigrep-9cd200e5fac0fc94)

running 1 test
test tests::one_result ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

     Running unittests src/main.rs (target/debug/deps/minigrep-9cd200e5fac0fc94)

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests minigrep

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s


```
 Our test passed, so we know it works!

 At this point, we could consider opportunities for refactoring the implementation of the search function while keeping the tests passing to maintain the same functionality. The code in the search function isn’t too bad, but it doesn’t take advantage of some useful features of iterators. We’ll return to this example in [Chapter 13](ch13-02-iterators), where we’ll explore iterators in detail, and look at how to improve it.

 #### Using the `search` Function in the `run` Function

 Now that the `search` function is working and tested, we need to call `search` from our `run` function. We need to pass the `config.query` value and the `contents` that `run` reads from the file to the `search` function. Then `run` will print each line returned from `search`:

 Filename: src/lib.rs

 
```
use std::error::Error;
use std::fs;

pub struct Config {
    pub query: String,
    pub file_path: String,
}

impl Config {
    pub fn build(args: &[String]) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("not enough arguments");
        }

        let query = args[1].clone();
        let file_path = args[2].clone();

        Ok(Config { query, file_path })
    }
}

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.file_path)?;

    for line in search(&config.query, &contents) {
        println!("{line}");
    }

    Ok(())
}

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    let mut results = Vec::new();

    for line in contents.lines() {
        if line.contains(query) {
            results.push(line);
        }
    }

    results
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn one_result() {
        let query = "duct";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.";

        assert_eq!(vec!["safe, fast, productive."], search(query, contents));
    }
}
```
 We’re still using a `for` loop to return each line from `search` and print it.

 Now the entire program should work! Let’s try it out, first with a word that should return exactly one line from the Emily Dickinson poem, “frog”:

 
```
$ cargo run -- frog poem.txt
   Compiling minigrep v0.1.0 (file:///projects/minigrep)
    Finished dev [unoptimized + debuginfo] target(s) in 0.38s
     Running `target/debug/minigrep frog poem.txt`
How public, like a frog

```
 Cool! Now let’s try a word that will match multiple lines, like “body”:

 
```
$ cargo run -- body poem.txt
   Compiling minigrep v0.1.0 (file:///projects/minigrep)
    Finished dev [unoptimized + debuginfo] target(s) in 0.0s
     Running `target/debug/minigrep body poem.txt`
I'm nobody! Who are you?
Are you nobody, too?
How dreary to be somebody!

```
 And finally, let’s make sure that we don’t get any lines when we search for a word that isn’t anywhere in the poem, such as “monomorphization”:

 
```
$ cargo run -- monomorphization poem.txt
   Compiling minigrep v0.1.0 (file:///projects/minigrep)
    Finished dev [unoptimized + debuginfo] target(s) in 0.0s
     Running `target/debug/minigrep monomorphization poem.txt`

```
 Excellent! We’ve built our own mini version of a classic tool and learned a lot about how to structure applications. We’ve also learned a bit about file input and output, lifetimes, testing, and command line parsing.

 To round out this project, we’ll briefly demonstrate how to work with environment variables and how to print to standard error, both of which are useful when you’re writing command line programs.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch12-04-testing-the-librarys-functionality.html>

Working with Environment Variables
==================================

 We’ll improve `minigrep` by adding an extra feature: an option for case-insensitive searching that the user can turn on via an environment variable. We could make this feature a command line option and require that users enter it each time they want it to apply, but by instead making it an environment variable, we allow our users to set the environment variable once and have all their searches be case insensitive in that terminal session.

 ### Writing a Failing Test for the Case-Insensitive `search` Function

 We first add a new `search_case_insensitive` function that will be called when the environment variable has a value. We’ll continue to follow the TDD process, so the first step is again to write a failing test. We’ll add a new test for the new `search_case_insensitive` function and rename our old test from `one_result` to `case_sensitive` to clarify the differences between the two tests, as shown in Listing 12-20.

 Filename: src/lib.rs

 
```
use std::error::Error;
use std::fs;

pub struct Config {
    pub query: String,
    pub file_path: String,
}

impl Config {
    pub fn build(args: &[String]) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("not enough arguments");
        }

        let query = args[1].clone();
        let file_path = args[2].clone();

        Ok(Config { query, file_path })
    }
}

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.file_path)?;

    for line in search(&config.query, &contents) {
        println!("{line}");
    }

    Ok(())
}

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    let mut results = Vec::new();

    for line in contents.lines() {
        if line.contains(query) {
            results.push(line);
        }
    }

    results
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn case_sensitive() {
        let query = "duct";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";

        assert_eq!(vec!["safe, fast, productive."], search(query, contents));
    }

    #[test]
    fn case_insensitive() {
        let query = "rUsT";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";

        assert_eq!(
            vec!["Rust:", "Trust me."],
            search_case_insensitive(query, contents)
        );
    }
}
```
 Listing 12-20: Adding a new failing test for the case-insensitive function we’re about to add

 Note that we’ve edited the old test’s `contents` too. We’ve added a new line with the text `"Duct tape."` using a capital D that shouldn’t match the query `"duct"` when we’re searching in a case-sensitive manner. Changing the old test in this way helps ensure that we don’t accidentally break the case-sensitive search functionality that we’ve already implemented. This test should pass now and should continue to pass as we work on the case-insensitive search.

 The new test for the case-*insensitive* search uses `"rUsT"` as its query. In the `search_case_insensitive` function we’re about to add, the query `"rUsT"` should match the line containing `"Rust:"` with a capital R and match the line `"Trust me."` even though both have different casing from the query. This is our failing test, and it will fail to compile because we haven’t yet defined the `search_case_insensitive` function. Feel free to add a skeleton implementation that always returns an empty vector, similar to the way we did for the `search` function in Listing 12-16 to see the test compile and fail.

 ### Implementing the `search_case_insensitive` Function

 The `search_case_insensitive` function, shown in Listing 12-21, will be almost the same as the `search` function. The only difference is that we’ll lowercase the `query` and each `line` so whatever the case of the input arguments, they’ll be the same case when we check whether the line contains the query.

 Filename: src/lib.rs

 
```
use std::error::Error;
use std::fs;

pub struct Config {
    pub query: String,
    pub file_path: String,
}

impl Config {
    pub fn build(args: &[String]) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("not enough arguments");
        }

        let query = args[1].clone();
        let file_path = args[2].clone();

        Ok(Config { query, file_path })
    }
}

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.file_path)?;

    for line in search(&config.query, &contents) {
        println!("{line}");
    }

    Ok(())
}

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    let mut results = Vec::new();

    for line in contents.lines() {
        if line.contains(query) {
            results.push(line);
        }
    }

    results
}

pub fn search_case_insensitive<'a>(
    query: &str,
    contents: &'a str,
) -> Vec<&'a str> {
    let query = query.to_lowercase();
    let mut results = Vec::new();

    for line in contents.lines() {
        if line.to_lowercase().contains(&query) {
            results.push(line);
        }
    }

    results
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn case_sensitive() {
        let query = "duct";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";

        assert_eq!(vec!["safe, fast, productive."], search(query, contents));
    }

    #[test]
    fn case_insensitive() {
        let query = "rUsT";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";

        assert_eq!(
            vec!["Rust:", "Trust me."],
            search_case_insensitive(query, contents)
        );
    }
}
```
 Listing 12-21: Defining the `search_case_insensitive` function to lowercase the query and the line before comparing them

 First, we lowercase the `query` string and store it in a shadowed variable with the same name. Calling `to_lowercase` on the query is necessary so no matter whether the user’s query is `"rust"`, `"RUST"`, `"Rust"`, or `"rUsT"`, we’ll treat the query as if it were `"rust"` and be insensitive to the case. While `to_lowercase` will handle basic Unicode, it won’t be 100% accurate. If we were writing a real application, we’d want to do a bit more work here, but this section is about environment variables, not Unicode, so we’ll leave it at that here.

 Note that `query` is now a `String` rather than a string slice, because calling `to_lowercase` creates new data rather than referencing existing data. Say the query is `"rUsT"`, as an example: that string slice doesn’t contain a lowercase `u` or `t` for us to use, so we have to allocate a new `String` containing `"rust"`. When we pass `query` as an argument to the `contains` method now, we need to add an ampersand because the signature of `contains` is defined to take a string slice.

 Next, we add a call to `to_lowercase` on each `line` to lowercase all characters. Now that we’ve converted `line` and `query` to lowercase, we’ll find matches no matter what the case of the query is.

 Let’s see if this implementation passes the tests:

 
```
$ cargo test
   Compiling minigrep v0.1.0 (file:///projects/minigrep)
    Finished test [unoptimized + debuginfo] target(s) in 1.33s
     Running unittests src/lib.rs (target/debug/deps/minigrep-9cd200e5fac0fc94)

running 2 tests
test tests::case_insensitive ... ok
test tests::case_sensitive ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

     Running unittests src/main.rs (target/debug/deps/minigrep-9cd200e5fac0fc94)

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests minigrep

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s


```
 Great! They passed. Now, let’s call the new `search_case_insensitive` function from the `run` function. First, we’ll add a configuration option to the `Config` struct to switch between case-sensitive and case-insensitive search. Adding this field will cause compiler errors because we aren’t initializing this field anywhere yet:

 Filename: src/lib.rs

 
```
use std::error::Error;
use std::fs;

pub struct Config {
    pub query: String,
    pub file_path: String,
    pub ignore_case: bool,
}

impl Config {
    pub fn build(args: &[String]) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("not enough arguments");
        }

        let query = args[1].clone();
        let file_path = args[2].clone();

        Ok(Config { query, file_path })
    }
}

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.file_path)?;

    let results = if config.ignore_case {
        search_case_insensitive(&config.query, &contents)
    } else {
        search(&config.query, &contents)
    };

    for line in results {
        println!("{line}");
    }

    Ok(())
}

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    let mut results = Vec::new();

    for line in contents.lines() {
        if line.contains(query) {
            results.push(line);
        }
    }

    results
}

pub fn search_case_insensitive<'a>(
    query: &str,
    contents: &'a str,
) -> Vec<&'a str> {
    let query = query.to_lowercase();
    let mut results = Vec::new();

    for line in contents.lines() {
        if line.to_lowercase().contains(&query) {
            results.push(line);
        }
    }

    results
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn case_sensitive() {
        let query = "duct";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";

        assert_eq!(vec!["safe, fast, productive."], search(query, contents));
    }

    #[test]
    fn case_insensitive() {
        let query = "rUsT";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";

        assert_eq!(
            vec!["Rust:", "Trust me."],
            search_case_insensitive(query, contents)
        );
    }
}
```
 We added the `ignore_case` field that holds a Boolean. Next, we need the `run` function to check the `ignore_case` field’s value and use that to decide whether to call the `search` function or the `search_case_insensitive` function, as shown in Listing 12-22. This still won’t compile yet.

 Filename: src/lib.rs

 
```
use std::error::Error;
use std::fs;

pub struct Config {
    pub query: String,
    pub file_path: String,
    pub ignore_case: bool,
}

impl Config {
    pub fn build(args: &[String]) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("not enough arguments");
        }

        let query = args[1].clone();
        let file_path = args[2].clone();

        Ok(Config { query, file_path })
    }
}

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.file_path)?;

    let results = if config.ignore_case {
        search_case_insensitive(&config.query, &contents)
    } else {
        search(&config.query, &contents)
    };

    for line in results {
        println!("{line}");
    }

    Ok(())
}

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    let mut results = Vec::new();

    for line in contents.lines() {
        if line.contains(query) {
            results.push(line);
        }
    }

    results
}

pub fn search_case_insensitive<'a>(
    query: &str,
    contents: &'a str,
) -> Vec<&'a str> {
    let query = query.to_lowercase();
    let mut results = Vec::new();

    for line in contents.lines() {
        if line.to_lowercase().contains(&query) {
            results.push(line);
        }
    }

    results
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn case_sensitive() {
        let query = "duct";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";

        assert_eq!(vec!["safe, fast, productive."], search(query, contents));
    }

    #[test]
    fn case_insensitive() {
        let query = "rUsT";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";

        assert_eq!(
            vec!["Rust:", "Trust me."],
            search_case_insensitive(query, contents)
        );
    }
}
```
 Listing 12-22: Calling either `search` or `search_case_insensitive` based on the value in `config.ignore_case`

 Finally, we need to check for the environment variable. The functions for working with environment variables are in the `env` module in the standard library, so we bring that module into scope at the top of *src/lib.rs*. Then we’ll use the `var` function from the `env` module to check to see if any value has been set for an environment variable named `IGNORE_CASE`, as shown in Listing 12-23.

 Filename: src/lib.rs

 
```
use std::env;
// --snip--

use std::error::Error;
use std::fs;

pub struct Config {
    pub query: String,
    pub file_path: String,
    pub ignore_case: bool,
}

impl Config {
    pub fn build(args: &[String]) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("not enough arguments");
        }

        let query = args[1].clone();
        let file_path = args[2].clone();

        let ignore_case = env::var("IGNORE_CASE").is_ok();

        Ok(Config {
            query,
            file_path,
            ignore_case,
        })
    }
}

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.file_path)?;

    let results = if config.ignore_case {
        search_case_insensitive(&config.query, &contents)
    } else {
        search(&config.query, &contents)
    };

    for line in results {
        println!("{line}");
    }

    Ok(())
}

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    let mut results = Vec::new();

    for line in contents.lines() {
        if line.contains(query) {
            results.push(line);
        }
    }

    results
}

pub fn search_case_insensitive<'a>(
    query: &str,
    contents: &'a str,
) -> Vec<&'a str> {
    let query = query.to_lowercase();
    let mut results = Vec::new();

    for line in contents.lines() {
        if line.to_lowercase().contains(&query) {
            results.push(line);
        }
    }

    results
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn case_sensitive() {
        let query = "duct";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";

        assert_eq!(vec!["safe, fast, productive."], search(query, contents));
    }

    #[test]
    fn case_insensitive() {
        let query = "rUsT";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";

        assert_eq!(
            vec!["Rust:", "Trust me."],
            search_case_insensitive(query, contents)
        );
    }
}
```
 Listing 12-23: Checking for any value in an environment variable named `IGNORE_CASE`

 Here, we create a new variable `ignore_case`. To set its value, we call the `env::var` function and pass it the name of the `IGNORE_CASE` environment variable. The `env::var` function returns a `Result` that will be the successful `Ok` variant that contains the value of the environment variable if the environment variable is set to any value. It will return the `Err` variant if the environment variable is not set.

 We’re using the `is_ok` method on the `Result` to check whether the environment variable is set, which means the program should do a case-insensitive search. If the `IGNORE_CASE` environment variable isn’t set to anything, `is_ok` will return false and the program will perform a case-sensitive search. We don’t care about the *value* of the environment variable, just whether it’s set or unset, so we’re checking `is_ok` rather than using `unwrap`, `expect`, or any of the other methods we’ve seen on `Result`.

 We pass the value in the `ignore_case` variable to the `Config` instance so the `run` function can read that value and decide whether to call `search_case_insensitive` or `search`, as we implemented in Listing 12-22.

 Let’s give it a try! First, we’ll run our program without the environment variable set and with the query `to`, which should match any line that contains the word “to” in all lowercase:

 
```
$ cargo run -- to poem.txt
   Compiling minigrep v0.1.0 (file:///projects/minigrep)
    Finished dev [unoptimized + debuginfo] target(s) in 0.0s
     Running `target/debug/minigrep to poem.txt`
Are you nobody, too?
How dreary to be somebody!

```
 Looks like that still works! Now, let’s run the program with `IGNORE_CASE` set to `1` but with the same query `to`.

 
```
$ IGNORE_CASE=1 cargo run -- to poem.txt

```
 If you’re using PowerShell, you will need to set the environment variable and run the program as separate commands:

 
```
PS> $Env:IGNORE_CASE=1; cargo run -- to poem.txt

```
 This will make `IGNORE_CASE` persist for the remainder of your shell session. It can be unset with the `Remove-Item` cmdlet:

 
```
PS> Remove-Item Env:IGNORE_CASE

```
 We should get lines that contain “to” that might have uppercase letters:

 
```
Are you nobody, too?
How dreary to be somebody!
To tell your name the livelong day
To an admiring bog!

```
 Excellent, we also got lines containing “To”! Our `minigrep` program can now do case-insensitive searching controlled by an environment variable. Now you know how to manage options set using either command line arguments or environment variables.

 Some programs allow arguments *and* environment variables for the same configuration. In those cases, the programs decide that one or the other takes precedence. For another exercise on your own, try controlling case sensitivity through either a command line argument or an environment variable. Decide whether the command line argument or the environment variable should take precedence if the program is run with one set to case sensitive and one set to ignore case.

 The `std::env` module contains many more useful features for dealing with environment variables: check out its documentation to see what is available.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch12-05-working-with-environment-variables.html>

Writing Error Messages to Standard Error Instead of Standard Output
===================================================================

 At the moment, we’re writing all of our output to the terminal using the `println!` macro. In most terminals, there are two kinds of output: *standard output* (`stdout`) for general information and *standard error* (`stderr`) for error messages. This distinction enables users to choose to direct the successful output of a program to a file but still print error messages to the screen.

 The `println!` macro is only capable of printing to standard output, so we have to use something else to print to standard error.

 ### Checking Where Errors Are Written

 First, let’s observe how the content printed by `minigrep` is currently being written to standard output, including any error messages we want to write to standard error instead. We’ll do that by redirecting the standard output stream to a file while intentionally causing an error. We won’t redirect the standard error stream, so any content sent to standard error will continue to display on the screen.

 Command line programs are expected to send error messages to the standard error stream so we can still see error messages on the screen even if we redirect the standard output stream to a file. Our program is not currently well-behaved: we’re about to see that it saves the error message output to a file instead!

 To demonstrate this behavior, we’ll run the program with `>` and the file path, *output.txt*, that we want to redirect the standard output stream to. We won’t pass any arguments, which should cause an error:

 
```
$ cargo run > output.txt

```
 The `>` syntax tells the shell to write the contents of standard output to *output.txt* instead of the screen. We didn’t see the error message we were expecting printed to the screen, so that means it must have ended up in the file. This is what *output.txt* contains:

 
```
Problem parsing arguments: not enough arguments

```
 Yup, our error message is being printed to standard output. It’s much more useful for error messages like this to be printed to standard error so only data from a successful run ends up in the file. We’ll change that.

 ### Printing Errors to Standard Error

 We’ll use the code in Listing 12-24 to change how error messages are printed. Because of the refactoring we did earlier in this chapter, all the code that prints error messages is in one function, `main`. The standard library provides the `eprintln!` macro that prints to the standard error stream, so let’s change the two places we were calling `println!` to print errors to use `eprintln!` instead.

 Filename: src/main.rs

 
```
use std::env;
use std::process;

use minigrep::Config;

fn main() {
    let args: Vec<String> = env::args().collect();

    let config = Config::build(&args).unwrap_or_else(|err| {
        eprintln!("Problem parsing arguments: {err}");
        process::exit(1);
    });

    if let Err(e) = minigrep::run(config) {
        eprintln!("Application error: {e}");
        process::exit(1);
    }
}
```
 Listing 12-24: Writing error messages to standard error instead of standard output using `eprintln!`

 Let’s now run the program again in the same way, without any arguments and redirecting standard output with `>`:

 
```
$ cargo run > output.txt
Problem parsing arguments: not enough arguments

```
 Now we see the error onscreen and *output.txt* contains nothing, which is the behavior we expect of command line programs.

 Let’s run the program again with arguments that don’t cause an error but still redirect standard output to a file, like so:

 
```
$ cargo run -- to poem.txt > output.txt

```
 We won’t see any output to the terminal, and *output.txt* will contain our results:

 Filename: output.txt

 
```
Are you nobody, too?
How dreary to be somebody!

```
 This demonstrates that we’re now using standard output for successful output and standard error for error output as appropriate.

 Summary
-------

 This chapter recapped some of the major concepts you’ve learned so far and covered how to perform common I/O operations in Rust. By using command line arguments, files, environment variables, and the `eprintln!` macro for printing errors, you’re now prepared to write command line applications. Combined with the concepts in previous chapters, your code will be well organized, store data effectively in the appropriate data structures, handle errors nicely, and be well tested.

 Next, we’ll explore some Rust features that were influenced by functional languages: closures and iterators.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch12-06-writing-to-stderr-instead-of-stdout.html>

Functional Language Features: Iterators and Closures
====================================================

 Rust’s design has taken inspiration from many existing languages and techniques, and one significant influence is *functional programming*. Programming in a functional style often includes using functions as values by passing them in arguments, returning them from other functions, assigning them to variables for later execution, and so forth.

 In this chapter, we won’t debate the issue of what functional programming is or isn’t but will instead discuss some features of Rust that are similar to features in many languages often referred to as functional.

 More specifically, we’ll cover:

 * *Closures*, a function-like construct you can store in a variable
* *Iterators*, a way of processing a series of elements
* How to use closures and iterators to improve the I/O project in Chapter 12
* The performance of closures and iterators (Spoiler alert: they’re faster than you might think!)

 We’ve already covered some other Rust features, such as pattern matching and enums, that are also influenced by the functional style. Because mastering closures and iterators is an important part of writing idiomatic, fast Rust code, we’ll devote this entire chapter to them.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch13-00-functional-features.html>

Closures: Anonymous Functions that Capture Their Environment
------------------------------------------------------------

 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.

 ### Capturing the Environment with Closures

 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<ShirtColor>` 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 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<ShirtColor>,
}

impl Inventory {
    fn giveaway(&self, user_preference: Option<ShirtColor>) -> 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: 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<ShirtColor>` and call the `unwrap_or_else` method on `user_preference`. The [`unwrap_or_else` method on `Option<T>`](../std/option/enum.option#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<T>`, in this case `ShirtColor`). If the `Option<T>` is the `Some` variant, `unwrap_or_else` returns the value from within the `Some`. If the `Option<T>` 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 bars). 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:

 
```
$ cargo run
   Compiling shirt-company v0.1.0 (file:///projects/shirt-company)
    Finished dev [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.

 ### Closure Type Inference and Annotation

 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 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: 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: 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 struct `String`, found integer
  |             arguments to this function are incorrect
  |
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` due to 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.

 ### Capturing References or Moving Ownership

 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: 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 [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: 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 [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: 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. 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 did and dropped `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 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!

 ### Moving Captured Values Out of Closures and the `Fn` Traits

 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:

 1. `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.
2. `FnMut` applies to closures that don’t move captured values out of their body, but that might mutate the captured values. These closures can be called more than once.
3. `Fn` applies to closures that don’t move captured values out of their body and that 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<T>` that we used in Listing 13-1:

 
```
impl<T> Option<T> {
    pub fn unwrap_or_else<F>(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<String>`, 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` is only going to call `f` at most one time. 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 the most different kinds of closures and is as flexible as it can be.

 
>  Note: Functions can implement all three of the `Fn` traits too. 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<Vec<T>>` value, we could call `unwrap_or_else(Vec::new)` to get a new, empty vector if the value is `None`.
> 
>  

 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 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: Using `sort_by_key` to order rectangles by width

 This code prints:

 
```
$ cargo run
   Compiling rectangles v0.1.0 (file:///projects/rectangles)
    Finished dev [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 out anything 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("by key called");

    list.sort_by_key(|r| {
        sort_operations.push(value);
        r.width
    });
    println!("{:#?}", list);
}
```
 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 and count the number of times `sort_by_key` gets called 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` 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("by key 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

For more information about this error, try `rustc --explain E0507`.
error: could not compile `rectangles` due to 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. To count the number of times `sort_by_key` is called, keeping a counter in the environment and incrementing its value in the closure body is a more straightforward way to calculate that. 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!("{:#?}, sorted in {num_sort_operations} operations", list);
}
```
 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!



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch13-01-closures.html>

Processing a Series of Items with Iterators
===========================================

 The iterator pattern allows you to perform some task on a sequence of items in turn. An iterator is responsible for the logic of iterating over each item and determining when the sequence has finished. When you use iterators, you don’t have to reimplement that logic yourself.

 In Rust, iterators are *lazy*, meaning they have no effect until you call methods that consume the iterator to use it up. For example, the code in Listing 13-10 creates an iterator over the items in the vector `v1` by calling the `iter` method defined on `Vec<T>`. This code by itself doesn’t do anything useful.

 
```
fn main() {
    let v1 = vec![1, 2, 3];

    let v1_iter = v1.iter();
}
```
 Listing 13-10: Creating an iterator

 The iterator is stored in the `v1_iter` variable. Once we’ve created an iterator, we can use it in a variety of ways. In Listing 3-5 in Chapter 3, we iterated over an array using a `for` loop to execute some code on each of its items. Under the hood this implicitly created and then consumed an iterator, but we glossed over how exactly that works until now.

 In the example in Listing 13-11, we separate the creation of the iterator from the use of the iterator in the `for` loop. When the `for` loop is called using the iterator in `v1_iter`, each element in the iterator is used in one iteration of the loop, which prints out each value.

 
```
fn main() {
    let v1 = vec![1, 2, 3];

    let v1_iter = v1.iter();

    for val in v1_iter {
        println!("Got: {}", val);
    }
}
```
 Listing 13-11: Using an iterator in a `for` loop

 In languages that don’t have iterators provided by their standard libraries, you would likely write this same functionality by starting a variable at index 0, using that variable to index into the vector to get a value, and incrementing the variable value in a loop until it reached the total number of items in the vector.

 Iterators handle all that logic for you, cutting down on repetitive code you could potentially mess up. Iterators give you more flexibility to use the same logic with many different kinds of sequences, not just data structures you can index into, like vectors. Let’s examine how iterators do that.

 ### The `Iterator` Trait and the `next` Method

 All iterators implement a trait named `Iterator` that is defined in the standard library. The definition of the trait looks like this:

 
```
#![allow(unused)]
fn main() {
pub trait Iterator {
    type Item;

    fn next(&mut self) -> Option<Self::Item>;

    // methods with default implementations elided
}
}
```
 Notice this definition uses some new syntax: `type Item` and `Self::Item`, which are defining an *associated type* with this trait. We’ll talk about associated types in depth in Chapter 19. For now, all you need to know is that this code says implementing the `Iterator` trait requires that you also define an `Item` type, and this `Item` type is used in the return type of the `next` method. In other words, the `Item` type will be the type returned from the iterator.

 The `Iterator` trait only requires implementors to define one method: the `next` method, which returns one item of the iterator at a time wrapped in `Some` and, when iteration is over, returns `None`.

 We can call the `next` method on iterators directly; Listing 13-12 demonstrates what values are returned from repeated calls to `next` on the iterator created from the vector.

 Filename: src/lib.rs

 
```
#[cfg(test)]
mod tests {
    #[test]
    fn iterator_demonstration() {
        let v1 = vec![1, 2, 3];

        let mut v1_iter = v1.iter();

        assert_eq!(v1_iter.next(), Some(&1));
        assert_eq!(v1_iter.next(), Some(&2));
        assert_eq!(v1_iter.next(), Some(&3));
        assert_eq!(v1_iter.next(), None);
    }
}
```
 Listing 13-12: Calling the `next` method on an iterator

 Note that we needed to make `v1_iter` mutable: calling the `next` method on an iterator changes internal state that the iterator uses to keep track of where it is in the sequence. In other words, this code *consumes*, or uses up, the iterator. Each call to `next` eats up an item from the iterator. We didn’t need to make `v1_iter` mutable when we used a `for` loop because the loop took ownership of `v1_iter` and made it mutable behind the scenes.

 Also note that the values we get from the calls to `next` are immutable references to the values in the vector. The `iter` method produces an iterator over immutable references. If we want to create an iterator that takes ownership of `v1` and returns owned values, we can call `into_iter` instead of `iter`. Similarly, if we want to iterate over mutable references, we can call `iter_mut` instead of `iter`.

 ### Methods that Consume the Iterator

 The `Iterator` trait has a number of different methods with default implementations provided by the standard library; you can find out about these methods by looking in the standard library API documentation for the `Iterator` trait. Some of these methods call the `next` method in their definition, which is why you’re required to implement the `next` method when implementing the `Iterator` trait.

 Methods that call `next` are called *consuming adaptors*, because calling them uses up the iterator. One example is the `sum` method, which takes ownership of the iterator and iterates through the items by repeatedly calling `next`, thus consuming the iterator. As it iterates through, it adds each item to a running total and returns the total when iteration is complete. Listing 13-13 has a test illustrating a use of the `sum` method:

 Filename: src/lib.rs

 
```
#[cfg(test)]
mod tests {
    #[test]
    fn iterator_sum() {
        let v1 = vec![1, 2, 3];

        let v1_iter = v1.iter();

        let total: i32 = v1_iter.sum();

        assert_eq!(total, 6);
    }
}
```
 Listing 13-13: Calling the `sum` method to get the total of all items in the iterator

 We aren’t allowed to use `v1_iter` after the call to `sum` because `sum` takes ownership of the iterator we call it on.

 ### Methods that Produce Other Iterators

 *Iterator adaptors* are methods defined on the `Iterator` trait that don’t consume the iterator. Instead, they produce different iterators by changing some aspect of the original iterator.

 Listing 13-14 shows an example of calling the iterator adaptor method `map`, which takes a closure to call on each item as the items are iterated through. The `map` method returns a new iterator that produces the modified items. The closure here creates a new iterator in which each item from the vector will be incremented by 1:

 Filename: src/main.rs

 
```
fn main() {
    let v1: Vec<i32> = vec![1, 2, 3];

    v1.iter().map(|x| x + 1);
}
```
 Listing 13-14: Calling the iterator adaptor `map` to create a new iterator

 However, this code produces a warning:

 
```
$ cargo run
   Compiling iterators v0.1.0 (file:///projects/iterators)
warning: unused `Map` that must be used
 --> src/main.rs:4:5
  |
4 |     v1.iter().map(|x| x + 1);
  |     ^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: iterators are lazy and do nothing unless consumed
  = note: `#[warn(unused_must_use)]` on by default

warning: `iterators` (bin "iterators") generated 1 warning
    Finished dev [unoptimized + debuginfo] target(s) in 0.47s
     Running `target/debug/iterators`

```
 The code in Listing 13-14 doesn’t do anything; the closure we’ve specified never gets called. The warning reminds us why: iterator adaptors are lazy, and we need to consume the iterator here.

 To fix this warning and consume the iterator, we’ll use the `collect` method, which we used in Chapter 12 with `env::args` in Listing 12-1. This method consumes the iterator and collects the resulting values into a collection data type.

 In Listing 13-15, we collect the results of iterating over the iterator that’s returned from the call to `map` into a vector. This vector will end up containing each item from the original vector incremented by 1.

 Filename: src/main.rs

 
```
fn main() {
    let v1: Vec<i32> = vec![1, 2, 3];

    let v2: Vec<_> = v1.iter().map(|x| x + 1).collect();

    assert_eq!(v2, vec![2, 3, 4]);
}
```
 Listing 13-15: Calling the `map` method to create a new iterator and then calling the `collect` method to consume the new iterator and create a vector

 Because `map` takes a closure, we can specify any operation we want to perform on each item. This is a great example of how closures let you customize some behavior while reusing the iteration behavior that the `Iterator` trait provides.

 You can chain multiple calls to iterator adaptors to perform complex actions in a readable way. But because all iterators are lazy, you have to call one of the consuming adaptor methods to get results from calls to iterator adaptors.

 ### Using Closures that Capture Their Environment

 Many iterator adapters take closures as arguments, and commonly the closures we’ll specify as arguments to iterator adapters will be closures that capture their environment.

 For this example, we’ll use the `filter` method that takes a closure. The closure gets an item from the iterator and returns a `bool`. If the closure returns `true`, the value will be included in the iteration produced by `filter`. If the closure returns `false`, the value won’t be included.

 In Listing 13-16, we use `filter` with a closure that captures the `shoe_size` variable from its environment to iterate over a collection of `Shoe` struct instances. It will return only shoes that are the specified size.

 Filename: src/lib.rs

 
```
#[derive(PartialEq, Debug)]
struct Shoe {
    size: u32,
    style: String,
}

fn shoes_in_size(shoes: Vec<Shoe>, shoe_size: u32) -> Vec<Shoe> {
    shoes.into_iter().filter(|s| s.size == shoe_size).collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn filters_by_size() {
        let shoes = vec![
            Shoe {
                size: 10,
                style: String::from("sneaker"),
            },
            Shoe {
                size: 13,
                style: String::from("sandal"),
            },
            Shoe {
                size: 10,
                style: String::from("boot"),
            },
        ];

        let in_my_size = shoes_in_size(shoes, 10);

        assert_eq!(
            in_my_size,
            vec![
                Shoe {
                    size: 10,
                    style: String::from("sneaker")
                },
                Shoe {
                    size: 10,
                    style: String::from("boot")
                },
            ]
        );
    }
}
```
 Listing 13-16: Using the `filter` method with a closure that captures `shoe_size`

 The `shoes_in_size` function takes ownership of a vector of shoes and a shoe size as parameters. It returns a vector containing only shoes of the specified size.

 In the body of `shoes_in_size`, we call `into_iter` to create an iterator that takes ownership of the vector. Then we call `filter` to adapt that iterator into a new iterator that only contains elements for which the closure returns `true`.

 The closure captures the `shoe_size` parameter from the environment and compares the value with each shoe’s size, keeping only shoes of the size specified. Finally, calling `collect` gathers the values returned by the adapted iterator into a vector that’s returned by the function.

 The test shows that when we call `shoes_in_size`, we get back only shoes that have the same size as the value we specified.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch13-02-iterators.html>

Improving Our I/O Project
=========================

 With this new knowledge about iterators, we can improve the I/O project in Chapter 12 by using iterators to make places in the code clearer and more concise. Let’s look at how iterators can improve our implementation of the `Config::build` function and the `search` function.

 ### Removing a `clone` Using an Iterator

 In Listing 12-6, we added code that took a slice of `String` values and created an instance of the `Config` struct by indexing into the slice and cloning the values, allowing the `Config` struct to own those values. In Listing 13-17, we’ve reproduced the implementation of the `Config::build` function as it was in Listing 12-23:

 Filename: src/lib.rs

 
```
use std::env;
use std::error::Error;
use std::fs;

pub struct Config {
    pub query: String,
    pub file_path: String,
    pub ignore_case: bool,
}

impl Config {
    pub fn build(args: &[String]) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("not enough arguments");
        }

        let query = args[1].clone();
        let file_path = args[2].clone();

        let ignore_case = env::var("IGNORE_CASE").is_ok();

        Ok(Config {
            query,
            file_path,
            ignore_case,
        })
    }
}

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.file_path)?;

    let results = if config.ignore_case {
        search_case_insensitive(&config.query, &contents)
    } else {
        search(&config.query, &contents)
    };

    for line in results {
        println!("{line}");
    }

    Ok(())
}

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    let mut results = Vec::new();

    for line in contents.lines() {
        if line.contains(query) {
            results.push(line);
        }
    }

    results
}

pub fn search_case_insensitive<'a>(
    query: &str,
    contents: &'a str,
) -> Vec<&'a str> {
    let query = query.to_lowercase();
    let mut results = Vec::new();

    for line in contents.lines() {
        if line.to_lowercase().contains(&query) {
            results.push(line);
        }
    }

    results
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn case_sensitive() {
        let query = "duct";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";

        assert_eq!(vec!["safe, fast, productive."], search(query, contents));
    }

    #[test]
    fn case_insensitive() {
        let query = "rUsT";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";

        assert_eq!(
            vec!["Rust:", "Trust me."],
            search_case_insensitive(query, contents)
        );
    }
}
```
 Listing 13-17: Reproduction of the `Config::build` function from Listing 12-23

 At the time, we said not to worry about the inefficient `clone` calls because we would remove them in the future. Well, that time is now!

 We needed `clone` here because we have a slice with `String` elements in the parameter `args`, but the `build` function doesn’t own `args`. To return ownership of a `Config` instance, we had to clone the values from the `query` and `file_path` fields of `Config` so the `Config` instance can own its values.

 With our new knowledge about iterators, we can change the `build` function to take ownership of an iterator as its argument instead of borrowing a slice. We’ll use the iterator functionality instead of the code that checks the length of the slice and indexes into specific locations. This will clarify what the `Config::build` function is doing because the iterator will access the values.

 Once `Config::build` takes ownership of the iterator and stops using indexing operations that borrow, we can move the `String` values from the iterator into `Config` rather than calling `clone` and making a new allocation.

 #### Using the Returned Iterator Directly

 Open your I/O project’s *src/main.rs* file, which should look like this:

 Filename: src/main.rs

 
```
use std::env;
use std::process;

use minigrep::Config;

fn main() {
    let args: Vec<String> = env::args().collect();

    let config = Config::build(&args).unwrap_or_else(|err| {
        eprintln!("Problem parsing arguments: {err}");
        process::exit(1);
    });

    // --snip--

    if let Err(e) = minigrep::run(config) {
        eprintln!("Application error: {e}");
        process::exit(1);
    }
}
```
 We’ll first change the start of the `main` function that we had in Listing 12-24 to the code in Listing 13-18, which this time uses an iterator. This won’t compile until we update `Config::build` as well.

 Filename: src/main.rs

 
```
use std::env;
use std::process;

use minigrep::Config;

fn main() {
    let config = Config::build(env::args()).unwrap_or_else(|err| {
        eprintln!("Problem parsing arguments: {err}");
        process::exit(1);
    });

    // --snip--

    if let Err(e) = minigrep::run(config) {
        eprintln!("Application error: {e}");
        process::exit(1);
    }
}
```
 Listing 13-18: Passing the return value of `env::args` to `Config::build`

 The `env::args` function returns an iterator! Rather than collecting the iterator values into a vector and then passing a slice to `Config::build`, now we’re passing ownership of the iterator returned from `env::args` to `Config::build` directly.

 Next, we need to update the definition of `Config::build`. In your I/O project’s *src/lib.rs* file, let’s change the signature of `Config::build` to look like Listing 13-19. This still won’t compile because we need to update the function body.

 Filename: src/lib.rs

 
```
use std::env;
use std::error::Error;
use std::fs;

pub struct Config {
    pub query: String,
    pub file_path: String,
    pub ignore_case: bool,
}

impl Config {
    pub fn build(
        mut args: impl Iterator<Item = String>,
    ) -> Result<Config, &'static str> {
        // --snip--
        if args.len() < 3 {
            return Err("not enough arguments");
        }

        let query = args[1].clone();
        let file_path = args[2].clone();

        let ignore_case = env::var("IGNORE_CASE").is_ok();

        Ok(Config {
            query,
            file_path,
            ignore_case,
        })
    }
}

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.file_path)?;

    let results = if config.ignore_case {
        search_case_insensitive(&config.query, &contents)
    } else {
        search(&config.query, &contents)
    };

    for line in results {
        println!("{line}");
    }

    Ok(())
}

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    let mut results = Vec::new();

    for line in contents.lines() {
        if line.contains(query) {
            results.push(line);
        }
    }

    results
}

pub fn search_case_insensitive<'a>(
    query: &str,
    contents: &'a str,
) -> Vec<&'a str> {
    let query = query.to_lowercase();
    let mut results = Vec::new();

    for line in contents.lines() {
        if line.to_lowercase().contains(&query) {
            results.push(line);
        }
    }

    results
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn case_sensitive() {
        let query = "duct";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";

        assert_eq!(vec!["safe, fast, productive."], search(query, contents));
    }

    #[test]
    fn case_insensitive() {
        let query = "rUsT";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";

        assert_eq!(
            vec!["Rust:", "Trust me."],
            search_case_insensitive(query, contents)
        );
    }
}
```
 Listing 13-19: Updating the signature of `Config::build` to expect an iterator

 The standard library documentation for the `env::args` function shows that the type of the iterator it returns is `std::env::Args`, and that type implements the `Iterator` trait and returns `String` values.

 We’ve updated the signature of the `Config::build` function so the parameter `args` has a generic type with the trait bounds `impl Iterator<Item = String>` instead of `&[String]`. This usage of the `impl Trait` syntax we discussed in the [“Traits as Parameters”](ch10-02-traits#traits-as-parameters) section of Chapter 10 means that `args` can be any type that implements the `Iterator` type and returns `String` items.

 Because we’re taking ownership of `args` and we’ll be mutating `args` by iterating over it, we can add the `mut` keyword into the specification of the `args` parameter to make it mutable.

 #### Using `Iterator` Trait Methods Instead of Indexing

 Next, we’ll fix the body of `Config::build`. Because `args` implements the `Iterator` trait, we know we can call the `next` method on it! Listing 13-20 updates the code from Listing 12-23 to use the `next` method:

 Filename: src/lib.rs

 
```
use std::env;
use std::error::Error;
use std::fs;

pub struct Config {
    pub query: String,
    pub file_path: String,
    pub ignore_case: bool,
}

impl Config {
    pub fn build(
        mut args: impl Iterator<Item = String>,
    ) -> Result<Config, &'static str> {
        args.next();

        let query = match args.next() {
            Some(arg) => arg,
            None => return Err("Didn't get a query string"),
        };

        let file_path = match args.next() {
            Some(arg) => arg,
            None => return Err("Didn't get a file path"),
        };

        let ignore_case = env::var("IGNORE_CASE").is_ok();

        Ok(Config {
            query,
            file_path,
            ignore_case,
        })
    }
}

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.file_path)?;

    let results = if config.ignore_case {
        search_case_insensitive(&config.query, &contents)
    } else {
        search(&config.query, &contents)
    };

    for line in results {
        println!("{line}");
    }

    Ok(())
}

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    let mut results = Vec::new();

    for line in contents.lines() {
        if line.contains(query) {
            results.push(line);
        }
    }

    results
}

pub fn search_case_insensitive<'a>(
    query: &str,
    contents: &'a str,
) -> Vec<&'a str> {
    let query = query.to_lowercase();
    let mut results = Vec::new();

    for line in contents.lines() {
        if line.to_lowercase().contains(&query) {
            results.push(line);
        }
    }

    results
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn case_sensitive() {
        let query = "duct";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";

        assert_eq!(vec!["safe, fast, productive."], search(query, contents));
    }

    #[test]
    fn case_insensitive() {
        let query = "rUsT";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";

        assert_eq!(
            vec!["Rust:", "Trust me."],
            search_case_insensitive(query, contents)
        );
    }
}
```
 Listing 13-20: Changing the body of `Config::build` to use iterator methods

 Remember that the first value in the return value of `env::args` is the name of the program. We want to ignore that and get to the next value, so first we call `next` and do nothing with the return value. Second, we call `next` to get the value we want to put in the `query` field of `Config`. If `next` returns a `Some`, we use a `match` to extract the value. If it returns `None`, it means not enough arguments were given and we return early with an `Err` value. We do the same thing for the `file_path` value.

 ### Making Code Clearer with Iterator Adaptors

 We can also take advantage of iterators in the `search` function in our I/O project, which is reproduced here in Listing 13-21 as it was in Listing 12-19:

 Filename: src/lib.rs

 
```
use std::error::Error;
use std::fs;

pub struct Config {
    pub query: String,
    pub file_path: String,
}

impl Config {
    pub fn build(args: &[String]) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("not enough arguments");
        }

        let query = args[1].clone();
        let file_path = args[2].clone();

        Ok(Config { query, file_path })
    }
}

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.file_path)?;

    Ok(())
}

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    let mut results = Vec::new();

    for line in contents.lines() {
        if line.contains(query) {
            results.push(line);
        }
    }

    results
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn one_result() {
        let query = "duct";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.";

        assert_eq!(vec!["safe, fast, productive."], search(query, contents));
    }
}
```
 Listing 13-21: The implementation of the `search` function from Listing 12-19

 We can write this code in a more concise way using iterator adaptor methods. Doing so also lets us avoid having a mutable intermediate `results` vector. The functional programming style prefers to minimize the amount of mutable state to make code clearer. Removing the mutable state might enable a future enhancement to make searching happen in parallel, because we wouldn’t have to manage concurrent access to the `results` vector. Listing 13-22 shows this change:

 Filename: src/lib.rs

 
```
use std::env;
use std::error::Error;
use std::fs;

pub struct Config {
    pub query: String,
    pub file_path: String,
    pub ignore_case: bool,
}

impl Config {
    pub fn build(
        mut args: impl Iterator<Item = String>,
    ) -> Result<Config, &'static str> {
        args.next();

        let query = match args.next() {
            Some(arg) => arg,
            None => return Err("Didn't get a query string"),
        };

        let file_path = match args.next() {
            Some(arg) => arg,
            None => return Err("Didn't get a file path"),
        };

        let ignore_case = env::var("IGNORE_CASE").is_ok();

        Ok(Config {
            query,
            file_path,
            ignore_case,
        })
    }
}

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.file_path)?;

    let results = if config.ignore_case {
        search_case_insensitive(&config.query, &contents)
    } else {
        search(&config.query, &contents)
    };

    for line in results {
        println!("{line}");
    }

    Ok(())
}

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    contents
        .lines()
        .filter(|line| line.contains(query))
        .collect()
}

pub fn search_case_insensitive<'a>(
    query: &str,
    contents: &'a str,
) -> Vec<&'a str> {
    let query = query.to_lowercase();
    let mut results = Vec::new();

    for line in contents.lines() {
        if line.to_lowercase().contains(&query) {
            results.push(line);
        }
    }

    results
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn case_sensitive() {
        let query = "duct";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";

        assert_eq!(vec!["safe, fast, productive."], search(query, contents));
    }

    #[test]
    fn case_insensitive() {
        let query = "rUsT";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";

        assert_eq!(
            vec!["Rust:", "Trust me."],
            search_case_insensitive(query, contents)
        );
    }
}
```
 Listing 13-22: Using iterator adaptor methods in the implementation of the `search` function

 Recall that the purpose of the `search` function is to return all lines in `contents` that contain the `query`. Similar to the `filter` example in Listing 13-16, this code uses the `filter` adaptor to keep only the lines that `line.contains(query)` returns `true` for. We then collect the matching lines into another vector with `collect`. Much simpler! Feel free to make the same change to use iterator methods in the `search_case_insensitive` function as well.

 ### Choosing Between Loops or Iterators

 The next logical question is which style you should choose in your own code and why: the original implementation in Listing 13-21 or the version using iterators in Listing 13-22. Most Rust programmers prefer to use the iterator style. It’s a bit tougher to get the hang of at first, but once you get a feel for the various iterator adaptors and what they do, iterators can be easier to understand. Instead of fiddling with the various bits of looping and building new vectors, the code focuses on the high-level objective of the loop. This abstracts away some of the commonplace code so it’s easier to see the concepts that are unique to this code, such as the filtering condition each element in the iterator must pass.

 But are the two implementations truly equivalent? The intuitive assumption might be that the more low-level loop will be faster. Let’s talk about performance.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch13-03-improving-our-io-project.html>

Comparing Performance: Loops vs. Iterators
==========================================

 To determine whether to use loops or iterators, you need to know which implementation is faster: the version of the `search` function with an explicit `for` loop or the version with iterators.

 We ran a benchmark by loading the entire contents of *The Adventures of Sherlock Holmes* by Sir Arthur Conan Doyle into a `String` and looking for the word *the* in the contents. Here are the results of the benchmark on the version of `search` using the `for` loop and the version using iterators:

 
```
test bench_search_for  ... bench:  19,620,300 ns/iter (+/- 915,700)
test bench_search_iter ... bench:  19,234,900 ns/iter (+/- 657,200)

```
 The iterator version was slightly faster! We won’t explain the benchmark code here, because the point is not to prove that the two versions are equivalent but to get a general sense of how these two implementations compare performance-wise.

 For a more comprehensive benchmark, you should check using various texts of various sizes as the `contents`, different words and words of different lengths as the `query`, and all kinds of other variations. The point is this: iterators, although a high-level abstraction, get compiled down to roughly the same code as if you’d written the lower-level code yourself. Iterators are one of Rust’s *zero-cost abstractions*, by which we mean using the abstraction imposes no additional runtime overhead. This is analogous to how Bjarne Stroustrup, the original designer and implementor of C++, defines *zero-overhead* in “Foundations of C++” (2012):

 
>  In general, C++ implementations obey the zero-overhead principle: What you don’t use, you don’t pay for. And further: What you do use, you couldn’t hand code any better.
> 
>  

 As another example, the following code is taken from an audio decoder. The decoding algorithm uses the linear prediction mathematical operation to estimate future values based on a linear function of the previous samples. This code uses an iterator chain to do some math on three variables in scope: a `buffer` slice of data, an array of 12 `coefficients`, and an amount by which to shift data in `qlp_shift`. We’ve declared the variables within this example but not given them any values; although this code doesn’t have much meaning outside of its context, it’s still a concise, real-world example of how Rust translates high-level ideas to low-level code.

 
```
let buffer: &mut [i32];
let coefficients: [i64; 12];
let qlp_shift: i16;

for i in 12..buffer.len() {
    let prediction = coefficients.iter()
                                 .zip(&buffer[i - 12..i])
                                 .map(|(&c, &s)| c * s as i64)
                                 .sum::<i64>() >> qlp_shift;
    let delta = buffer[i];
    buffer[i] = prediction as i32 + delta;
}
```
 To calculate the value of `prediction`, this code iterates through each of the 12 values in `coefficients` and uses the `zip` method to pair the coefficient values with the previous 12 values in `buffer`. Then, for each pair, we multiply the values together, sum all the results, and shift the bits in the sum `qlp_shift` bits to the right.

 Calculations in applications like audio decoders often prioritize performance most highly. Here, we’re creating an iterator, using two adaptors, and then consuming the value. What assembly code would this Rust code compile to? Well, as of this writing, it compiles down to the same assembly you’d write by hand. There’s no loop at all corresponding to the iteration over the values in `coefficients`: Rust knows that there are 12 iterations, so it “unrolls” the loop. *Unrolling* is an optimization that removes the overhead of the loop controlling code and instead generates repetitive code for each iteration of the loop.

 All of the coefficients get stored in registers, which means accessing the values is very fast. There are no bounds checks on the array access at runtime. All these optimizations that Rust is able to apply make the resulting code extremely efficient. Now that you know this, you can use iterators and closures without fear! They make code seem like it’s higher level but don’t impose a runtime performance penalty for doing so.

 Summary
-------

 Closures and iterators are Rust features inspired by functional programming language ideas. They contribute to Rust’s capability to clearly express high-level ideas at low-level performance. The implementations of closures and iterators are such that runtime performance is not affected. This is part of Rust’s goal to strive to provide zero-cost abstractions.

 Now that we’ve improved the expressiveness of our I/O project, let’s look at some more features of `cargo` that will help us share the project with the world.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch13-04-performance.html>

More About Cargo and Crates.io
==============================

 So far we’ve used only the most basic features of Cargo to build, run, and test our code, but it can do a lot more. In this chapter, we’ll discuss some of its other, more advanced features to show you how to do the following:

 * Customize your build through release profiles
* Publish libraries on [crates.io](https://crates.io/)
* Organize large projects with workspaces
* Install binaries from [crates.io](https://crates.io/)
* Extend Cargo using custom commands

 Cargo can do even more than the functionality we cover in this chapter, so for a full explanation of all its features, see [its documentation](https://doc.rust-lang.org/cargo/index.html).



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch14-00-more-about-cargo.html>

Customizing Builds with Release Profiles
========================================

 In Rust, *release profiles* are predefined and customizable profiles with different configurations that allow a programmer to have more control over various options for compiling code. Each profile is configured independently of the others.

 Cargo has two main profiles: the `dev` profile Cargo uses when you run `cargo build` and the `release` profile Cargo uses when you run `cargo build --release`. The `dev` profile is defined with good defaults for development, and the `release` profile has good defaults for release builds.

 These profile names might be familiar from the output of your builds:

 
```
$ cargo build
    Finished dev [unoptimized + debuginfo] target(s) in 0.0s
$ cargo build --release
    Finished release [optimized] target(s) in 0.0s

```
 The `dev` and `release` are these different profiles used by the compiler.

 Cargo has default settings for each of the profiles that apply when you haven't explicitly added any `[profile.*]` sections in the project’s *Cargo.toml* file. By adding `[profile.*]` sections for any profile you want to customize, you override any subset of the default settings. For example, here are the default values for the `opt-level` setting for the `dev` and `release` profiles:

 Filename: Cargo.toml

 
```
[profile.dev]
opt-level = 0

[profile.release]
opt-level = 3

```
 The `opt-level` setting controls the number of optimizations Rust will apply to your code, with a range of 0 to 3. Applying more optimizations extends compiling time, so if you’re in development and compiling your code often, you’ll want fewer optimizations to compile faster even if the resulting code runs slower. The default `opt-level` for `dev` is therefore `0`. When you’re ready to release your code, it’s best to spend more time compiling. You’ll only compile in release mode once, but you’ll run the compiled program many times, so release mode trades longer compile time for code that runs faster. That is why the default `opt-level` for the `release` profile is `3`.

 You can override a default setting by adding a different value for it in *Cargo.toml*. For example, if we want to use optimization level 1 in the development profile, we can add these two lines to our project’s *Cargo.toml* file:

 Filename: Cargo.toml

 
```
[profile.dev]
opt-level = 1

```
 This code overrides the default setting of `0`. Now when we run `cargo build`, Cargo will use the defaults for the `dev` profile plus our customization to `opt-level`. Because we set `opt-level` to `1`, Cargo will apply more optimizations than the default, but not as many as in a release build.

 For the full list of configuration options and defaults for each profile, see [Cargo’s documentation](https://doc.rust-lang.org/cargo/reference/profiles.html).



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch14-01-release-profiles.html>

Publishing a Crate to Crates.io
===============================

 We’ve used packages from [crates.io](https://crates.io/) as dependencies of our project, but you can also share your code with other people by publishing your own packages. The crate registry at [crates.io](https://crates.io/) distributes the source code of your packages, so it primarily hosts code that is open source.

 Rust and Cargo have features that make your published package easier for people to find and use. We’ll talk about some of these features next and then explain how to publish a package.

 ### Making Useful Documentation Comments

 Accurately documenting your packages will help other users know how and when to use them, so it’s worth investing the time to write documentation. In Chapter 3, we discussed how to comment Rust code using two slashes, `//`. Rust also has a particular kind of comment for documentation, known conveniently as a *documentation comment*, that will generate HTML documentation. The HTML displays the contents of documentation comments for public API items intended for programmers interested in knowing how to *use* your crate as opposed to how your crate is *implemented*.

 Documentation comments use three slashes, `///`, instead of two and support Markdown notation for formatting the text. Place documentation comments just before the item they’re documenting. Listing 14-1 shows documentation comments for an `add_one` function in a crate named `my_crate`.

 Filename: src/lib.rs

 
```
/// Adds one to the number given.
///
/// # Examples
///
/// ```
/// let arg = 5;
/// let answer = my_crate::add_one(arg);
///
/// assert_eq!(6, answer);
/// ```
pub fn add_one(x: i32) -> i32 {
    x + 1
}
```
 Listing 14-1: A documentation comment for a function

 Here, we give a description of what the `add_one` function does, start a section with the heading `Examples`, and then provide code that demonstrates how to use the `add_one` function. We can generate the HTML documentation from this documentation comment by running `cargo doc`. This command runs the `rustdoc` tool distributed with Rust and puts the generated HTML documentation in the *target/doc* directory.

 For convenience, running `cargo doc --open` will build the HTML for your current crate’s documentation (as well as the documentation for all of your crate’s dependencies) and open the result in a web browser. Navigate to the `add_one` function and you’ll see how the text in the documentation comments is rendered, as shown in Figure 14-1:

 ![Rendered HTML documentation for the `add_one` function of `my_crate`](https://doc.rust-lang.org/book/img/trpl14-01.png) Figure 14-1: HTML documentation for the `add_one` function

 #### Commonly Used Sections

 We used the `# Examples` Markdown heading in Listing 14-1 to create a section in the HTML with the title “Examples.” Here are some other sections that crate authors commonly use in their documentation:

 * **Panics**: The scenarios in which the function being documented could panic. Callers of the function who don’t want their programs to panic should make sure they don’t call the function in these situations.
* **Errors**: If the function returns a `Result`, describing the kinds of errors that might occur and what conditions might cause those errors to be returned can be helpful to callers so they can write code to handle the different kinds of errors in different ways.
* **Safety**: If the function is `unsafe` to call (we discuss unsafety in Chapter 19), there should be a section explaining why the function is unsafe and covering the invariants that the function expects callers to uphold.

 Most documentation comments don’t need all of these sections, but this is a good checklist to remind you of the aspects of your code users will be interested in knowing about.

 #### Documentation Comments as Tests

 Adding example code blocks in your documentation comments can help demonstrate how to use your library, and doing so has an additional bonus: running `cargo test` will run the code examples in your documentation as tests! Nothing is better than documentation with examples. But nothing is worse than examples that don’t work because the code has changed since the documentation was written. If we run `cargo test` with the documentation for the `add_one` function from Listing 14-1, we will see a section in the test results like this:

 
```
   Doc-tests my_crate

running 1 test
test src/lib.rs - add_one (line 5) ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.27s

```
 Now if we change either the function or the example so the `assert_eq!` in the example panics and run `cargo test` again, we’ll see that the doc tests catch that the example and the code are out of sync with each other!

 #### Commenting Contained Items

 The style of doc comment `//!` adds documentation to the item that contains the comments rather than to the items following the comments. We typically use these doc comments inside the crate root file (*src/lib.rs* by convention) or inside a module to document the crate or the module as a whole.

 For example, to add documentation that describes the purpose of the `my_crate` crate that contains the `add_one` function, we add documentation comments that start with `//!` to the beginning of the *src/lib.rs* file, as shown in Listing 14-2:

 Filename: src/lib.rs

 
```
//! # My Crate
//!
//! `my_crate` is a collection of utilities to make performing certain
//! calculations more convenient.

/// Adds one to the number given.
// --snip--
///
/// # Examples
///
/// ```
/// let arg = 5;
/// let answer = my_crate::add_one(arg);
///
/// assert_eq!(6, answer);
/// ```
pub fn add_one(x: i32) -> i32 {
    x + 1
}
```
 Listing 14-2: Documentation for the `my_crate` crate as a whole

 Notice there isn’t any code after the last line that begins with `//!`. Because we started the comments with `//!` instead of `///`, we’re documenting the item that contains this comment rather than an item that follows this comment. In this case, that item is the *src/lib.rs* file, which is the crate root. These comments describe the entire crate.

 When we run `cargo doc --open`, these comments will display on the front page of the documentation for `my_crate` above the list of public items in the crate, as shown in Figure 14-2:

 ![Rendered HTML documentation with a comment for the crate as a whole] Figure 14-2: Rendered documentation for `my_crate`, including the comment describing the crate as a whole

 Documentation comments within items are useful for describing crates and modules especially. Use them to explain the overall purpose of the container to help your users understand the crate’s organization.

 ### Exporting a Convenient Public API with `pub use`

 The structure of your public API is a major consideration when publishing a crate. People who use your crate are less familiar with the structure than you are and might have difficulty finding the pieces they want to use if your crate has a large module hierarchy.

 In Chapter 7, we covered how to make items public using the `pub` keyword, and bring items into a scope with the `use` keyword. However, the structure that makes sense to you while you’re developing a crate might not be very convenient for your users. You might want to organize your structs in a hierarchy containing multiple levels, but then people who want to use a type you’ve defined deep in the hierarchy might have trouble finding out that type exists. They might also be annoyed at having to enter `use` `my_crate::some_module::another_module::UsefulType;` rather than `use` `my_crate::UsefulType;`.

 The good news is that if the structure *isn’t* convenient for others to use from another library, you don’t have to rearrange your internal organization: instead, you can re-export items to make a public structure that’s different from your private structure by using `pub use`. Re-exporting takes a public item in one location and makes it public in another location, as if it were defined in the other location instead.

 For example, say we made a library named `art` for modeling artistic concepts. Within this library are two modules: a `kinds` module containing two enums named `PrimaryColor` and `SecondaryColor` and a `utils` module containing a function named `mix`, as shown in Listing 14-3:

 Filename: src/lib.rs

 
```
//! # Art
//!
//! A library for modeling artistic concepts.

pub mod kinds {
    /// The primary colors according to the RYB color model.
    pub enum PrimaryColor {
        Red,
        Yellow,
        Blue,
    }

    /// The secondary colors according to the RYB color model.
    pub enum SecondaryColor {
        Orange,
        Green,
        Purple,
    }
}

pub mod utils {
    use crate::kinds::*;

    /// Combines two primary colors in equal amounts to create
    /// a secondary color.
    pub fn mix(c1: PrimaryColor, c2: PrimaryColor) -> SecondaryColor {
        // --snip--
        unimplemented!();
    }
}
```
 Listing 14-3: An `art` library with items organized into `kinds` and `utils` modules

 Figure 14-3 shows what the front page of the documentation for this crate generated by `cargo doc` would look like:

 ![Rendered documentation for the `art` crate that lists the `kinds` and `utils` modules] Figure 14-3: Front page of the documentation for `art` that lists the `kinds` and `utils` modules

 Note that the `PrimaryColor` and `SecondaryColor` types aren’t listed on the front page, nor is the `mix` function. We have to click `kinds` and `utils` to see them.

 Another crate that depends on this library would need `use` statements that bring the items from `art` into scope, specifying the module structure that’s currently defined. Listing 14-4 shows an example of a crate that uses the `PrimaryColor` and `mix` items from the `art` crate:

 Filename: src/main.rs

 
```
use art::kinds::PrimaryColor;
use art::utils::mix;

fn main() {
    let red = PrimaryColor::Red;
    let yellow = PrimaryColor::Yellow;
    mix(red, yellow);
}
```
 Listing 14-4: A crate using the `art` crate’s items with its internal structure exported

 The author of the code in Listing 14-4, which uses the `art` crate, had to figure out that `PrimaryColor` is in the `kinds` module and `mix` is in the `utils` module. The module structure of the `art` crate is more relevant to developers working on the `art` crate than to those using it. The internal structure doesn’t contain any useful information for someone trying to understand how to use the `art` crate, but rather causes confusion because developers who use it have to figure out where to look, and must specify the module names in the `use` statements.

 To remove the internal organization from the public API, we can modify the `art` crate code in Listing 14-3 to add `pub use` statements to re-export the items at the top level, as shown in Listing 14-5:

 Filename: src/lib.rs

 
```
//! # Art
//!
//! A library for modeling artistic concepts.

pub use self::kinds::PrimaryColor;
pub use self::kinds::SecondaryColor;
pub use self::utils::mix;

pub mod kinds {
    // --snip--
    /// The primary colors according to the RYB color model.
    pub enum PrimaryColor {
        Red,
        Yellow,
        Blue,
    }

    /// The secondary colors according to the RYB color model.
    pub enum SecondaryColor {
        Orange,
        Green,
        Purple,
    }
}

pub mod utils {
    // --snip--
    use crate::kinds::*;

    /// Combines two primary colors in equal amounts to create
    /// a secondary color.
    pub fn mix(c1: PrimaryColor, c2: PrimaryColor) -> SecondaryColor {
        SecondaryColor::Orange
    }
}
```
 Listing 14-5: Adding `pub use` statements to re-export items

 The API documentation that `cargo doc` generates for this crate will now list and link re-exports on the front page, as shown in Figure 14-4, making the `PrimaryColor` and `SecondaryColor` types and the `mix` function easier to find.

 ![Rendered documentation for the `art` crate with the re-exports on the front page](https://doc.rust-lang.org/book/img/trpl14-04.png) Figure 14-4: The front page of the documentation for `art` that lists the re-exports

 The `art` crate users can still see and use the internal structure from Listing 14-3 as demonstrated in Listing 14-4, or they can use the more convenient structure in Listing 14-5, as shown in Listing 14-6:

 Filename: src/main.rs

 
```
use art::mix;
use art::PrimaryColor;

fn main() {
    // --snip--
    let red = PrimaryColor::Red;
    let yellow = PrimaryColor::Yellow;
    mix(red, yellow);
}
```
 Listing 14-6: A program using the re-exported items from the `art` crate

 In cases where there are many nested modules, re-exporting the types at the top level with `pub use` can make a significant difference in the experience of people who use the crate. Another common use of `pub use` is to re-export definitions of a dependency in the current crate to make that crate's definitions part of your crate’s public API.

 Creating a useful public API structure is more of an art than a science, and you can iterate to find the API that works best for your users. Choosing `pub use` gives you flexibility in how you structure your crate internally and decouples that internal structure from what you present to your users. Look at some of the code of crates you’ve installed to see if their internal structure differs from their public API.

 ### Setting Up a Crates.io Account

 Before you can publish any crates, you need to create an account on [crates.io](https://crates.io/) and get an API token. To do so, visit the home page at [crates.io](https://crates.io/) and log in via a GitHub account. (The GitHub account is currently a requirement, but the site might support other ways of creating an account in the future.) Once you’re logged in, visit your account settings at <https://crates.io/me/> and retrieve your API key. Then run the `cargo login` command with your API key, like this:

 
```
$ cargo login abcdefghijklmnopqrstuvwxyz012345

```
 This command will inform Cargo of your API token and store it locally in *~/.cargo/credentials*. Note that this token is a *secret*: do not share it with anyone else. If you do share it with anyone for any reason, you should revoke it and generate a new token on [crates.io](https://crates.io/).

 ### Adding Metadata to a New Crate

 Let’s say you have a crate you want to publish. Before publishing, you’ll need to add some metadata in the `[package]` section of the crate’s *Cargo.toml* file.

 Your crate will need a unique name. While you’re working on a crate locally, you can name a crate whatever you’d like. However, crate names on [crates.io](https://crates.io/) are allocated on a first-come, first-served basis. Once a crate name is taken, no one else can publish a crate with that name. Before attempting to publish a crate, search for the name you want to use. If the name has been used, you will need to find another name and edit the `name` field in the *Cargo.toml* file under the `[package]` section to use the new name for publishing, like so:

 Filename: Cargo.toml

 
```
[package]
name = "guessing_game"

```
 Even if you’ve chosen a unique name, when you run `cargo publish` to publish the crate at this point, you’ll get a warning and then an error:

 
```
$ cargo publish
    Updating crates.io index
warning: manifest has no description, license, license-file, documentation, homepage or repository.
See https://doc.rust-lang.org/cargo/reference/manifest.html#package-metadata for more info.
--snip--
error: failed to publish to registry at https://crates.io

Caused by:
  the remote server responded with an error: missing or empty metadata fields: description, license. Please see https://doc.rust-lang.org/cargo/reference/manifest.html for how to upload metadata

```
 This errors because you’re missing some crucial information: a description and license are required so people will know what your crate does and under what terms they can use it. In *Cargo.toml*, add a description that's just a sentence or two, because it will appear with your crate in search results. For the `license` field, you need to give a *license identifier value*. The [Linux Foundation’s Software Package Data Exchange (SPDX)](http://spdx.org/licenses/) lists the identifiers you can use for this value. For example, to specify that you’ve licensed your crate using the MIT License, add the `MIT` identifier:

 Filename: Cargo.toml

 
```
[package]
name = "guessing_game"
license = "MIT"

```
 If you want to use a license that doesn’t appear in the SPDX, you need to place the text of that license in a file, include the file in your project, and then use `license-file` to specify the name of that file instead of using the `license` key.

 Guidance on which license is appropriate for your project is beyond the scope of this book. Many people in the Rust community license their projects in the same way as Rust by using a dual license of `MIT OR Apache-2.0`. This practice demonstrates that you can also specify multiple license identifiers separated by `OR` to have multiple licenses for your project.

 With a unique name, the version, your description, and a license added, the *Cargo.toml* file for a project that is ready to publish might look like this:

 Filename: Cargo.toml

 
```
[package]
name = "guessing_game"
version = "0.1.0"
edition = "2021"
description = "A fun game where you guess what number the computer has chosen."
license = "MIT OR Apache-2.0"

[dependencies]

```
 [Cargo’s documentation](https://doc.rust-lang.org/cargo/index.html) describes other metadata you can specify to ensure others can discover and use your crate more easily.

 ### Publishing to Crates.io

 Now that you’ve created an account, saved your API token, chosen a name for your crate, and specified the required metadata, you’re ready to publish! Publishing a crate uploads a specific version to [crates.io](https://crates.io/) for others to use.

 Be careful, because a publish is *permanent*. The version can never be overwritten, and the code cannot be deleted. One major goal of [crates.io](https://crates.io/) is to act as a permanent archive of code so that builds of all projects that depend on crates from [crates.io](https://crates.io/) will continue to work. Allowing version deletions would make fulfilling that goal impossible. However, there is no limit to the number of crate versions you can publish.

 Run the `cargo publish` command again. It should succeed now:

 
```
$ cargo publish
    Updating crates.io index
   Packaging guessing_game v0.1.0 (file:///projects/guessing_game)
   Verifying guessing_game v0.1.0 (file:///projects/guessing_game)
   Compiling guessing_game v0.1.0
(file:///projects/guessing_game/target/package/guessing_game-0.1.0)
    Finished dev [unoptimized + debuginfo] target(s) in 0.19s
   Uploading guessing_game v0.1.0 (file:///projects/guessing_game)

```
 Congratulations! You’ve now shared your code with the Rust community, and anyone can easily add your crate as a dependency of their project.

 ### Publishing a New Version of an Existing Crate

 When you’ve made changes to your crate and are ready to release a new version, you change the `version` value specified in your *Cargo.toml* file and republish. Use the [Semantic Versioning rules](http://semver.org/) to decide what an appropriate next version number is based on the kinds of changes you’ve made. Then run `cargo publish` to upload the new version.

 ### Deprecating Versions from Crates.io with `cargo yank`

 Although you can’t remove previous versions of a crate, you can prevent any future projects from adding them as a new dependency. This is useful when a crate version is broken for one reason or another. In such situations, Cargo supports *yanking* a crate version.

 Yanking a version prevents new projects from depending on that version while allowing all existing projects that depend on it to continue. Essentially, a yank means that all projects with a *Cargo.lock* will not break, and any future *Cargo.lock* files generated will not use the yanked version.

 To yank a version of a crate, in the directory of the crate that you’ve previously published, run `cargo yank` and specify which version you want to yank. For example, if we've published a crate named `guessing_game` version 1.0.1 and we want to yank it, in the project directory for `guessing_game` we'd run:

 
```
$ cargo yank --vers 1.0.1
    Updating crates.io index
        Yank guessing_game@1.0.1

```
 By adding `--undo` to the command, you can also undo a yank and allow projects to start depending on a version again:

 
```
$ cargo yank --vers 1.0.1 --undo
    Updating crates.io index
      Unyank guessing_game@1.0.1

```
 A yank *does not* delete any code. It cannot, for example, delete accidentally uploaded secrets. If that happens, you must reset those secrets immediately.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html>

Cargo Workspaces
================

 In Chapter 12, we built a package that included a binary crate and a library crate. As your project develops, you might find that the library crate continues to get bigger and you want to split your package further into multiple library crates. Cargo offers a feature called *workspaces* that can help manage multiple related packages that are developed in tandem.

 ### Creating a Workspace

 A *workspace* is a set of packages that share the same *Cargo.lock* and output directory. Let’s make a project using a workspace—we’ll use trivial code so we can concentrate on the structure of the workspace. There are multiple ways to structure a workspace, so we'll just show one common way. We’ll have a workspace containing a binary and two libraries. The binary, which will provide the main functionality, will depend on the two libraries. One library will provide an `add_one` function, and a second library an `add_two` function. These three crates will be part of the same workspace. We’ll start by creating a new directory for the workspace:

 
```
$ mkdir add
$ cd add

```
 Next, in the *add* directory, we create the *Cargo.toml* file that will configure the entire workspace. This file won’t have a `[package]` section. Instead, it will start with a `[workspace]` section that will allow us to add members to the workspace by specifying the path to the package with our binary crate; in this case, that path is *adder*:

 Filename: Cargo.toml

 
```
[workspace]

members = [
    "adder",
]

```
 Next, we’ll create the `adder` binary crate by running `cargo new` within the *add* directory:

 
```
$ cargo new adder
     Created binary (application) `adder` package

```
 At this point, we can build the workspace by running `cargo build`. The files in your *add* directory should look like this:

 
```
├── Cargo.lock
├── Cargo.toml
├── adder
│   ├── Cargo.toml
│   └── src
│       └── main.rs
└── target

```
 The workspace has one *target* directory at the top level that the compiled artifacts will be placed into; the `adder` package doesn’t have its own *target* directory. Even if we were to run `cargo build` from inside the *adder* directory, the compiled artifacts would still end up in *add/target* rather than *add/adder/target*. Cargo structures the *target* directory in a workspace like this because the crates in a workspace are meant to depend on each other. If each crate had its own *target* directory, each crate would have to recompile each of the other crates in the workspace to place the artifacts in its own *target* directory. By sharing one *target* directory, the crates can avoid unnecessary rebuilding.

 ### Creating the Second Package in the Workspace

 Next, let’s create another member package in the workspace and call it `add_one`. Change the top-level *Cargo.toml* to specify the *add\_one* path in the `members` list:

 Filename: Cargo.toml

 
```
[workspace]

members = [
    "adder",
    "add_one",
]

```
 Then generate a new library crate named `add_one`:

 
```
$ cargo new add_one --lib
     Created library `add_one` package

```
 Your *add* directory should now have these directories and files:

 
```
├── Cargo.lock
├── Cargo.toml
├── add_one
│   ├── Cargo.toml
│   └── src
│       └── lib.rs
├── adder
│   ├── Cargo.toml
│   └── src
│       └── main.rs
└── target

```
 In the *add\_one/src/lib.rs* file, let’s add an `add_one` function:

 Filename: add\_one/src/lib.rs

 
```
pub fn add_one(x: i32) -> i32 {
    x + 1
}
```
 Now we can have the `adder` package with our binary depend on the `add_one` package that has our library. First, we’ll need to add a path dependency on `add_one` to *adder/Cargo.toml*.

 Filename: adder/Cargo.toml

 
```
[dependencies]
add_one = { path = "../add_one" }

```
 Cargo doesn’t assume that crates in a workspace will depend on each other, so we need to be explicit about the dependency relationships.

 Next, let’s use the `add_one` function (from the `add_one` crate) in the `adder` crate. Open the *adder/src/main.rs* file and add a `use` line at the top to bring the new `add_one` library crate into scope. Then change the `main` function to call the `add_one` function, as in Listing 14-7.

 Filename: adder/src/main.rs

 
```
use add_one;

fn main() {
    let num = 10;
    println!("Hello, world! {num} plus one is {}!", add_one::add_one(num));
}
```
 Listing 14-7: Using the `add_one` library crate from the `adder` crate

 Let’s build the workspace by running `cargo build` in the top-level *add* directory!

 
```
$ cargo build
   Compiling add_one v0.1.0 (file:///projects/add/add_one)
   Compiling adder v0.1.0 (file:///projects/add/adder)
    Finished dev [unoptimized + debuginfo] target(s) in 0.68s

```
 To run the binary crate from the *add* directory, we can specify which package in the workspace we want to run by using the `-p` argument and the package name with `cargo run`:

 
```
$ cargo run -p adder
    Finished dev [unoptimized + debuginfo] target(s) in 0.0s
     Running `target/debug/adder`
Hello, world! 10 plus one is 11!

```
 This runs the code in *adder/src/main.rs*, which depends on the `add_one` crate.

 #### Depending on an External Package in a Workspace

 Notice that the workspace has only one *Cargo.lock* file at the top level, rather than having a *Cargo.lock* in each crate’s directory. This ensures that all crates are using the same version of all dependencies. If we add the `rand` package to the *adder/Cargo.toml* and *add\_one/Cargo.toml* files, Cargo will resolve both of those to one version of `rand` and record that in the one *Cargo.lock*. Making all crates in the workspace use the same dependencies means the crates will always be compatible with each other. Let’s add the `rand` crate to the `[dependencies]` section in the *add\_one/Cargo.toml* file so we can use the `rand` crate in the `add_one` crate:

 Filename: add\_one/Cargo.toml

 
```
[dependencies]
rand = "0.8.5"

```
 We can now add `use rand;` to the *add\_one/src/lib.rs* file, and building the whole workspace by running `cargo build` in the *add* directory will bring in and compile the `rand` crate. We will get one warning because we aren’t referring to the `rand` we brought into scope:

 
```
$ cargo build
    Updating crates.io index
  Downloaded rand v0.8.5
   --snip--
   Compiling rand v0.8.5
   Compiling add_one v0.1.0 (file:///projects/add/add_one)
warning: unused import: `rand`
 --> add_one/src/lib.rs:1:5
  |
1 | use rand;
  |     ^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

warning: `add_one` (lib) generated 1 warning
   Compiling adder v0.1.0 (file:///projects/add/adder)
    Finished dev [unoptimized + debuginfo] target(s) in 10.18s

```
 The top-level *Cargo.lock* now contains information about the dependency of `add_one` on `rand`. However, even though `rand` is used somewhere in the workspace, we can’t use it in other crates in the workspace unless we add `rand` to their *Cargo.toml* files as well. For example, if we add `use rand;` to the *adder/src/main.rs* file for the `adder` package, we’ll get an error:

 
```
$ cargo build
  --snip--
   Compiling adder v0.1.0 (file:///projects/add/adder)
error[E0432]: unresolved import `rand`
 --> adder/src/main.rs:2:5
  |
2 | use rand;
  |     ^^^^ no external crate `rand`

```
 To fix this, edit the *Cargo.toml* file for the `adder` package and indicate that `rand` is a dependency for it as well. Building the `adder` package will add `rand` to the list of dependencies for `adder` in *Cargo.lock*, but no additional copies of `rand` will be downloaded. Cargo has ensured that every crate in every package in the workspace using the `rand` package will be using the same version, saving us space and ensuring that the crates in the workspace will be compatible with each other.

 #### Adding a Test to a Workspace

 For another enhancement, let’s add a test of the `add_one::add_one` function within the `add_one` crate:

 Filename: add\_one/src/lib.rs

 
```
pub fn add_one(x: i32) -> i32 {
    x + 1
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        assert_eq!(3, add_one(2));
    }
}
```
 Now run `cargo test` in the top-level *add* directory. Running `cargo test` in a workspace structured like this one will run the tests for all the crates in the workspace:

 
```
$ cargo test
   Compiling add_one v0.1.0 (file:///projects/add/add_one)
   Compiling adder v0.1.0 (file:///projects/add/adder)
    Finished test [unoptimized + debuginfo] target(s) in 0.27s
     Running unittests src/lib.rs (target/debug/deps/add_one-f0253159197f7841)

running 1 test
test tests::it_works ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

     Running unittests src/main.rs (target/debug/deps/adder-49979ff40686fa8e)

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests add_one

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

```
 The first section of the output shows that the `it_works` test in the `add_one` crate passed. The next section shows that zero tests were found in the `adder` crate, and then the last section shows zero documentation tests were found in the `add_one` crate.

 We can also run tests for one particular crate in a workspace from the top-level directory by using the `-p` flag and specifying the name of the crate we want to test:

 
```
$ cargo test -p add_one
    Finished test [unoptimized + debuginfo] target(s) in 0.00s
     Running unittests src/lib.rs (target/debug/deps/add_one-b3235fea9a156f74)

running 1 test
test tests::it_works ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests add_one

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

```
 This output shows `cargo test` only ran the tests for the `add_one` crate and didn’t run the `adder` crate tests.

 If you publish the crates in the workspace to [crates.io](https://crates.io/), each crate in the workspace will need to be published separately. Like `cargo test`, we can publish a particular crate in our workspace by using the `-p` flag and specifying the name of the crate we want to publish.

 For additional practice, add an `add_two` crate to this workspace in a similar way as the `add_one` crate!

 As your project grows, consider using a workspace: it’s easier to understand smaller, individual components than one big blob of code. Furthermore, keeping the crates in a workspace can make coordination between crates easier if they are often changed at the same time.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch14-03-cargo-workspaces.html>

Installing Binaries with `cargo install`
----------------------------------------

 The `cargo install` command allows you to install and use binary crates locally. This isn’t intended to replace system packages; it’s meant to be a convenient way for Rust developers to install tools that others have shared on [crates.io](https://crates.io/). Note that you can only install packages that have binary targets. A *binary target* is the runnable program that is created if the crate has a *src/main.rs* file or another file specified as a binary, as opposed to a library target that isn’t runnable on its own but is suitable for including within other programs. Usually, crates have information in the *README* file about whether a crate is a library, has a binary target, or both.

 All binaries installed with `cargo install` are stored in the installation root’s *bin* folder. If you installed Rust using *rustup.rs* and don’t have any custom configurations, this directory will be *$HOME/.cargo/bin*. Ensure that directory is in your `$PATH` to be able to run programs you’ve installed with `cargo install`.

 For example, in Chapter 12 we mentioned that there’s a Rust implementation of the `grep` tool called `ripgrep` for searching files. To install `ripgrep`, we can run the following:

 
```
$ cargo install ripgrep
    Updating crates.io index
  Downloaded ripgrep v13.0.0
  Downloaded 1 crate (243.3 KB) in 0.88s
  Installing ripgrep v13.0.0
--snip--
   Compiling ripgrep v13.0.0
    Finished release [optimized + debuginfo] target(s) in 3m 10s
  Installing ~/.cargo/bin/rg
   Installed package `ripgrep v13.0.0` (executable `rg`)

```
 The second-to-last line of the output shows the location and the name of the installed binary, which in the case of `ripgrep` is `rg`. As long as the installation directory is in your `$PATH`, as mentioned previously, you can then run `rg --help` and start using a faster, rustier tool for searching files!



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch14-04-installing-binaries.html>

Extending Cargo with Custom Commands
====================================

 Cargo is designed so you can extend it with new subcommands without having to modify Cargo. If a binary in your `$PATH` is named `cargo-something`, you can run it as if it was a Cargo subcommand by running `cargo something`. Custom commands like this are also listed when you run `cargo --list`. Being able to use `cargo install` to install extensions and then run them just like the built-in Cargo tools is a super convenient benefit of Cargo’s design!

 Summary
-------

 Sharing code with Cargo and [crates.io](https://crates.io/) is part of what makes the Rust ecosystem useful for many different tasks. Rust’s standard library is small and stable, but crates are easy to share, use, and improve on a timeline different from that of the language. Don’t be shy about sharing code that’s useful to you on [crates.io](https://crates.io/); it’s likely that it will be useful to someone else as well!



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch14-05-extending-cargo.html>

Smart Pointers
==============

 A *pointer* is a general concept for a variable that contains an address in memory. This address refers to, or “points at,” some other data. The most common kind of pointer in Rust is a reference, which you learned about in Chapter 4. References are indicated by the `&` symbol and borrow the value they point to. They don’t have any special capabilities other than referring to data, and have no overhead.

 *Smart pointers*, on the other hand, are data structures that act like a pointer but also have additional metadata and capabilities. The concept of smart pointers isn’t unique to Rust: smart pointers originated in C++ and exist in other languages as well. Rust has a variety of smart pointers defined in the standard library that provide functionality beyond that provided by references. To explore the general concept, we’ll look at a couple of different examples of smart pointers, including a *reference counting* smart pointer type. This pointer enables you to allow data to have multiple owners by keeping track of the number of owners and, when no owners remain, cleaning up the data.

 Rust, with its concept of ownership and borrowing, has an additional difference between references and smart pointers: while references only borrow data, in many cases, smart pointers *own* the data they point to.

 Though we didn’t call them as such at the time, we’ve already encountered a few smart pointers in this book, including `String` and `Vec<T>` in Chapter 8. Both these types count as smart pointers because they own some memory and allow you to manipulate it. They also have metadata and extra capabilities or guarantees. `String`, for example, stores its capacity as metadata and has the extra ability to ensure its data will always be valid UTF-8.

 Smart pointers are usually implemented using structs. Unlike an ordinary struct, smart pointers implement the `Deref` and `Drop` traits. The `Deref` trait allows an instance of the smart pointer struct to behave like a reference so you can write your code to work with either references or smart pointers. The `Drop` trait allows you to customize the code that’s run when an instance of the smart pointer goes out of scope. In this chapter, we’ll discuss both traits and demonstrate why they’re important to smart pointers.

 Given that the smart pointer pattern is a general design pattern used frequently in Rust, this chapter won’t cover every existing smart pointer. Many libraries have their own smart pointers, and you can even write your own. We’ll cover the most common smart pointers in the standard library:

 * `Box<T>` for allocating values on the heap
* `Rc<T>`, a reference counting type that enables multiple ownership
* `Ref<T>` and `RefMut<T>`, accessed through `RefCell<T>`, a type that enforces the borrowing rules at runtime instead of compile time

 In addition, we’ll cover the *interior mutability* pattern where an immutable type exposes an API for mutating an interior value. We’ll also discuss *reference cycles*: how they can leak memory and how to prevent them.

 Let’s dive in!



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch15-00-smart-pointers.html>

Using `Box<T>` to Point to Data on the Heap
===========================================

 The most straightforward smart pointer is a *box*, whose type is written `Box<T>`. Boxes allow you to store data on the heap rather than the stack. What remains on the stack is the pointer to the heap data. Refer to Chapter 4 to review the difference between the stack and the heap.

 Boxes don’t have performance overhead, other than storing their data on the heap instead of on the stack. But they don’t have many extra capabilities either. You’ll use them most often in these situations:

 * When you have a type whose size can’t be known at compile time and you want to use a value of that type in a context that requires an exact size
* When you have a large amount of data and you want to transfer ownership but ensure the data won’t be copied when you do so
* When you want to own a value and you care only that it’s a type that implements a particular trait rather than being of a specific type

 We’ll demonstrate the first situation in the [“Enabling Recursive Types with Boxes”](#enabling-recursive-types-with-boxes) section. In the second case, transferring ownership of a large amount of data can take a long time because the data is copied around on the stack. To improve performance in this situation, we can store the large amount of data on the heap in a box. Then, only the small amount of pointer data is copied around on the stack, while the data it references stays in one place on the heap. The third case is known as a *trait object*, and Chapter 17 devotes an entire section, [“Using Trait Objects That Allow for Values of Different Types,”](ch17-02-trait-objects#using-trait-objects-that-allow-for-values-of-different-types) just to that topic. So what you learn here you’ll apply again in Chapter 17!

 ### Using a `Box<T>` to Store Data on the Heap

 Before we discuss the heap storage use case for `Box<T>`, we’ll cover the syntax and how to interact with values stored within a `Box<T>`.

 Listing 15-1 shows how to use a box to store an `i32` value on the heap:

 Filename: src/main.rs

 
```
fn main() {
    let b = Box::new(5);
    println!("b = {}", b);
}
```
 Listing 15-1: Storing an `i32` value on the heap using a box

 We define the variable `b` to have the value of a `Box` that points to the value `5`, which is allocated on the heap. This program will print `b = 5`; in this case, we can access the data in the box similar to how we would if this data were on the stack. Just like any owned value, when a box goes out of scope, as `b` does at the end of `main`, it will be deallocated. The deallocation happens both for the box (stored on the stack) and the data it points to (stored on the heap).

 Putting a single value on the heap isn’t very useful, so you won’t use boxes by themselves in this way very often. Having values like a single `i32` on the stack, where they’re stored by default, is more appropriate in the majority of situations. Let’s look at a case where boxes allow us to define types that we wouldn’t be allowed to if we didn’t have boxes.

 ### Enabling Recursive Types with Boxes

 A value of *recursive type* can have another value of the same type as part of itself. Recursive types pose an issue because at compile time Rust needs to know how much space a type takes up. However, the nesting of values of recursive types could theoretically continue infinitely, so Rust can’t know how much space the value needs. Because boxes have a known size, we can enable recursive types by inserting a box in the recursive type definition.

 As an example of a recursive type, let’s explore the *cons list*. This is a data type commonly found in functional programming languages. The cons list type we’ll define is straightforward except for the recursion; therefore, the concepts in the example we’ll work with will be useful any time you get into more complex situations involving recursive types.

 #### More Information About the Cons List

 A *cons list* is a data structure that comes from the Lisp programming language and its dialects and is made up of nested pairs, and is the Lisp version of a linked list. Its name comes from the `cons` function (short for “construct function”) in Lisp that constructs a new pair from its two arguments. By calling `cons` on a pair consisting of a value and another pair, we can construct cons lists made up of recursive pairs.

 For example, here’s a pseudocode representation of a cons list containing the list 1, 2, 3 with each pair in parentheses:

 
```
(1, (2, (3, Nil)))

```
 Each item in a cons list contains two elements: the value of the current item and the next item. The last item in the list contains only a value called `Nil` without a next item. A cons list is produced by recursively calling the `cons` function. The canonical name to denote the base case of the recursion is `Nil`. Note that this is not the same as the “null” or “nil” concept in Chapter 6, which is an invalid or absent value.

 The cons list isn’t a commonly used data structure in Rust. Most of the time when you have a list of items in Rust, `Vec<T>` is a better choice to use. Other, more complex recursive data types *are* useful in various situations, but by starting with the cons list in this chapter, we can explore how boxes let us define a recursive data type without much distraction.

 Listing 15-2 contains an enum definition for a cons list. Note that this code won’t compile yet because the `List` type doesn’t have a known size, which we’ll demonstrate.

 Filename: src/main.rs

 
```
enum List {
    Cons(i32, List),
    Nil,
}

fn main() {}
```
 Listing 15-2: The first attempt at defining an enum to represent a cons list data structure of `i32` values

 
>  Note: We’re implementing a cons list that holds only `i32` values for the purposes of this example. We could have implemented it using generics, as we discussed in Chapter 10, to define a cons list type that could store values of any type.
> 
>  

 Using the `List` type to store the list `1, 2, 3` would look like the code in Listing 15-3:

 Filename: src/main.rs

 
```
enum List {
    Cons(i32, List),
    Nil,
}

use crate::List::{Cons, Nil};

fn main() {
    let list = Cons(1, Cons(2, Cons(3, Nil)));
}
```
 Listing 15-3: Using the `List` enum to store the list `1, 2, 3`

 The first `Cons` value holds `1` and another `List` value. This `List` value is another `Cons` value that holds `2` and another `List` value. This `List` value is one more `Cons` value that holds `3` and a `List` value, which is finally `Nil`, the non-recursive variant that signals the end of the list.

 If we try to compile the code in Listing 15-3, we get the error shown in Listing 15-4:

 
```
$ cargo run
   Compiling cons-list v0.1.0 (file:///projects/cons-list)
error[E0072]: recursive type `List` has infinite size
 --> src/main.rs:1:1
  |
1 | enum List {
  | ^^^^^^^^^
2 |     Cons(i32, List),
  |               ---- recursive without indirection
  |
help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to break the cycle
  |
2 |     Cons(i32, Box<List>),
  |               ++++    +

For more information about this error, try `rustc --explain E0072`.
error: could not compile `cons-list` due to previous error

```
 Listing 15-4: The error we get when attempting to define a recursive enum

 The error shows this type “has infinite size.” The reason is that we’ve defined `List` with a variant that is recursive: it holds another value of itself directly. As a result, Rust can’t figure out how much space it needs to store a `List` value. Let’s break down why we get this error. First, we’ll look at how Rust decides how much space it needs to store a value of a non-recursive type.

 #### Computing the Size of a Non-Recursive Type

 Recall the `Message` enum we defined in Listing 6-2 when we discussed enum definitions in Chapter 6:

 
```
enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}

fn main() {}
```
 To determine how much space to allocate for a `Message` value, Rust goes through each of the variants to see which variant needs the most space. Rust sees that `Message::Quit` doesn’t need any space, `Message::Move` needs enough space to store two `i32` values, and so forth. Because only one variant will be used, the most space a `Message` value will need is the space it would take to store the largest of its variants.

 Contrast this with what happens when Rust tries to determine how much space a recursive type like the `List` enum in Listing 15-2 needs. The compiler starts by looking at the `Cons` variant, which holds a value of type `i32` and a value of type `List`. Therefore, `Cons` needs an amount of space equal to the size of an `i32` plus the size of a `List`. To figure out how much memory the `List` type needs, the compiler looks at the variants, starting with the `Cons` variant. The `Cons` variant holds a value of type `i32` and a value of type `List`, and this process continues infinitely, as shown in Figure 15-1.

 ![An infinite Cons list] Figure 15-1: An infinite `List` consisting of infinite `Cons` variants

 #### Using `Box<T>` to Get a Recursive Type with a Known Size

 Because Rust can’t figure out how much space to allocate for recursively defined types, the compiler gives an error with this helpful suggestion:

 
```
help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `List` representable
  |
2 |     Cons(i32, Box<List>),
  |               ++++    +

```
 In this suggestion, “indirection” means that instead of storing a value directly, we should change the data structure to store the value indirectly by storing a pointer to the value instead.

 Because a `Box<T>` is a pointer, Rust always knows how much space a `Box<T>` needs: a pointer’s size doesn’t change based on the amount of data it’s pointing to. This means we can put a `Box<T>` inside the `Cons` variant instead of another `List` value directly. The `Box<T>` will point to the next `List` value that will be on the heap rather than inside the `Cons` variant. Conceptually, we still have a list, created with lists holding other lists, but this implementation is now more like placing the items next to one another rather than inside one another.

 We can change the definition of the `List` enum in Listing 15-2 and the usage of the `List` in Listing 15-3 to the code in Listing 15-5, which will compile:

 Filename: src/main.rs

 
```
enum List {
    Cons(i32, Box<List>),
    Nil,
}

use crate::List::{Cons, Nil};

fn main() {
    let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil))))));
}
```
 Listing 15-5: Definition of `List` that uses `Box<T>` in order to have a known size

 The `Cons` variant needs the size of an `i32` plus the space to store the box’s pointer data. The `Nil` variant stores no values, so it needs less space than the `Cons` variant. We now know that any `List` value will take up the size of an `i32` plus the size of a box’s pointer data. By using a box, we’ve broken the infinite, recursive chain, so the compiler can figure out the size it needs to store a `List` value. Figure 15-2 shows what the `Cons` variant looks like now.

 ![A finite Cons list] Figure 15-2: A `List` that is not infinitely sized because `Cons` holds a `Box`

 Boxes provide only the indirection and heap allocation; they don’t have any other special capabilities, like those we’ll see with the other smart pointer types. They also don’t have the performance overhead that these special capabilities incur, so they can be useful in cases like the cons list where the indirection is the only feature we need. We’ll look at more use cases for boxes in Chapter 17, too.

 The `Box<T>` type is a smart pointer because it implements the `Deref` trait, which allows `Box<T>` values to be treated like references. When a `Box<T>` value goes out of scope, the heap data that the box is pointing to is cleaned up as well because of the `Drop` trait implementation. These two traits will be even more important to the functionality provided by the other smart pointer types we’ll discuss in the rest of this chapter. Let’s explore these two traits in more detail.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch15-01-box.html>

Treating Smart Pointers Like Regular References with the `Deref` Trait
======================================================================

 Implementing the `Deref` trait allows you to customize the behavior of the *dereference operator* `*` (not to be confused with the multiplication or glob operator). By implementing `Deref` in such a way that a smart pointer can be treated like a regular reference, you can write code that operates on references and use that code with smart pointers too.

 Let’s first look at how the dereference operator works with regular references. Then we’ll try to define a custom type that behaves like `Box<T>`, and see why the dereference operator doesn’t work like a reference on our newly defined type. We’ll explore how implementing the `Deref` trait makes it possible for smart pointers to work in ways similar to references. Then we’ll look at Rust’s *deref coercion* feature and how it lets us work with either references or smart pointers.

 
>  Note: there’s one big difference between the `MyBox<T>` type we’re about to build and the real `Box<T>`: our version will not store its data on the heap. We are focusing this example on `Deref`, so where the data is actually stored is less important than the pointer-like behavior.
> 
>  

 ### Following the Pointer to the Value

 A regular reference is a type of pointer, and one way to think of a pointer is as an arrow to a value stored somewhere else. In Listing 15-6, we create a reference to an `i32` value and then use the dereference operator to follow the reference to the value:

 Filename: src/main.rs

 
```
fn main() {
    let x = 5;
    let y = &x;

    assert_eq!(5, x);
    assert_eq!(5, *y);
}
```
 Listing 15-6: Using the dereference operator to follow a reference to an `i32` value

 The variable `x` holds an `i32` value `5`. We set `y` equal to a reference to `x`. We can assert that `x` is equal to `5`. However, if we want to make an assertion about the value in `y`, we have to use `*y` to follow the reference to the value it’s pointing to (hence *dereference*) so the compiler can compare the actual value. Once we dereference `y`, we have access to the integer value `y` is pointing to that we can compare with `5`.

 If we tried to write `assert_eq!(5, y);` instead, we would get this compilation error:

 
```
$ cargo run
   Compiling deref-example v0.1.0 (file:///projects/deref-example)
error[E0277]: can't compare `{integer}` with `&{integer}`
 --> src/main.rs:6:5
  |
6 |     assert_eq!(5, y);
  |     ^^^^^^^^^^^^^^^^ no implementation for `{integer} == &{integer}`
  |
  = help: the trait `PartialEq<&{integer}>` is not implemented for `{integer}`
  = help: the following other types implement trait `PartialEq<Rhs>`:
            f32
            f64
            i128
            i16
            i32
            i64
            i8
            isize
          and 6 others
  = note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info)

For more information about this error, try `rustc --explain E0277`.
error: could not compile `deref-example` due to previous error

```
 Comparing a number and a reference to a number isn’t allowed because they’re different types. We must use the dereference operator to follow the reference to the value it’s pointing to.

 ### Using `Box<T>` Like a Reference

 We can rewrite the code in Listing 15-6 to use a `Box<T>` instead of a reference; the dereference operator used on the `Box<T>` in Listing 15-7 functions in the same way as the dereference operator used on the reference in Listing 15-6:

 Filename: src/main.rs

 
```
fn main() {
    let x = 5;
    let y = Box::new(x);

    assert_eq!(5, x);
    assert_eq!(5, *y);
}
```
 Listing 15-7: Using the dereference operator on a `Box<i32>`

 The main difference between Listing 15-7 and Listing 15-6 is that here we set `y` to be an instance of a `Box<T>` pointing to a copied value of `x` rather than a reference pointing to the value of `x`. In the last assertion, we can use the dereference operator to follow the pointer of the `Box<T>` in the same way that we did when `y` was a reference. Next, we’ll explore what is special about `Box<T>` that enables us to use the dereference operator by defining our own type.

 ### Defining Our Own Smart Pointer

 Let’s build a smart pointer similar to the `Box<T>` type provided by the standard library to experience how smart pointers behave differently from references by default. Then we’ll look at how to add the ability to use the dereference operator.

 The `Box<T>` type is ultimately defined as a tuple struct with one element, so Listing 15-8 defines a `MyBox<T>` type in the same way. We’ll also define a `new` function to match the `new` function defined on `Box<T>`.

 Filename: src/main.rs

 
```
struct MyBox<T>(T);

impl<T> MyBox<T> {
    fn new(x: T) -> MyBox<T> {
        MyBox(x)
    }
}

fn main() {}
```
 Listing 15-8: Defining a `MyBox<T>` type

 We define a struct named `MyBox` and declare a generic parameter `T`, because we want our type to hold values of any type. The `MyBox` type is a tuple struct with one element of type `T`. The `MyBox::new` function takes one parameter of type `T` and returns a `MyBox` instance that holds the value passed in.

 Let’s try adding the `main` function in Listing 15-7 to Listing 15-8 and changing it to use the `MyBox<T>` type we’ve defined instead of `Box<T>`. The code in Listing 15-9 won’t compile because Rust doesn’t know how to dereference `MyBox`.

 Filename: src/main.rs

 
```
struct MyBox<T>(T);

impl<T> MyBox<T> {
    fn new(x: T) -> MyBox<T> {
        MyBox(x)
    }
}

fn main() {
    let x = 5;
    let y = MyBox::new(x);

    assert_eq!(5, x);
    assert_eq!(5, *y);
}
```
 Listing 15-9: Attempting to use `MyBox<T>` in the same way we used references and `Box<T>`

 Here’s the resulting compilation error:

 
```
$ cargo run
   Compiling deref-example v0.1.0 (file:///projects/deref-example)
error[E0614]: type `MyBox<{integer}>` cannot be dereferenced
  --> src/main.rs:14:19
   |
14 |     assert_eq!(5, *y);
   |                   ^^

For more information about this error, try `rustc --explain E0614`.
error: could not compile `deref-example` due to previous error

```
 Our `MyBox<T>` type can’t be dereferenced because we haven’t implemented that ability on our type. To enable dereferencing with the `*` operator, we implement the `Deref` trait.

 ### Treating a Type Like a Reference by Implementing the `Deref` Trait

 As discussed in the [“Implementing a Trait on a Type”](ch10-02-traits#implementing-a-trait-on-a-type) section of Chapter 10, to implement a trait, we need to provide implementations for the trait’s required methods. The `Deref` trait, provided by the standard library, requires us to implement one method named `deref` that borrows `self` and returns a reference to the inner data. Listing 15-10 contains an implementation of `Deref` to add to the definition of `MyBox`:

 Filename: src/main.rs

 
```
use std::ops::Deref;

impl<T> Deref for MyBox<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

struct MyBox<T>(T);

impl<T> MyBox<T> {
    fn new(x: T) -> MyBox<T> {
        MyBox(x)
    }
}

fn main() {
    let x = 5;
    let y = MyBox::new(x);

    assert_eq!(5, x);
    assert_eq!(5, *y);
}
```
 Listing 15-10: Implementing `Deref` on `MyBox<T>`

 The `type Target = T;` syntax defines an associated type for the `Deref` trait to use. Associated types are a slightly different way of declaring a generic parameter, but you don’t need to worry about them for now; we’ll cover them in more detail in Chapter 19.

 We fill in the body of the `deref` method with `&self.0` so `deref` returns a reference to the value we want to access with the `*` operator; recall from the [“Using Tuple Structs without Named Fields to Create Different Types”](ch05-01-defining-structs#using-tuple-structs-without-named-fields-to-create-different-types) section of Chapter 5 that `.0` accesses the first value in a tuple struct. The `main` function in Listing 15-9 that calls `*` on the `MyBox<T>` value now compiles, and the assertions pass!

 Without the `Deref` trait, the compiler can only dereference `&` references. The `deref` method gives the compiler the ability to take a value of any type that implements `Deref` and call the `deref` method to get a `&` reference that it knows how to dereference.

 When we entered `*y` in Listing 15-9, behind the scenes Rust actually ran this code:

 
```
*(y.deref())
```
 Rust substitutes the `*` operator with a call to the `deref` method and then a plain dereference so we don’t have to think about whether or not we need to call the `deref` method. This Rust feature lets us write code that functions identically whether we have a regular reference or a type that implements `Deref`.

 The reason the `deref` method returns a reference to a value, and that the plain dereference outside the parentheses in `*(y.deref())` is still necessary, is to do with the ownership system. If the `deref` method returned the value directly instead of a reference to the value, the value would be moved out of `self`. We don’t want to take ownership of the inner value inside `MyBox<T>` in this case or in most cases where we use the dereference operator.

 Note that the `*` operator is replaced with a call to the `deref` method and then a call to the `*` operator just once, each time we use a `*` in our code. Because the substitution of the `*` operator does not recurse infinitely, we end up with data of type `i32`, which matches the `5` in `assert_eq!` in Listing 15-9.

 ### Implicit Deref Coercions with Functions and Methods

 *Deref coercion* converts a reference to a type that implements the `Deref` trait into a reference to another type. For example, deref coercion can convert `&String` to `&str` because `String` implements the `Deref` trait such that it returns `&str`. Deref coercion is a convenience Rust performs on arguments to functions and methods, and works only on types that implement the `Deref` trait. It happens automatically when we pass a reference to a particular type’s value as an argument to a function or method that doesn’t match the parameter type in the function or method definition. A sequence of calls to the `deref` method converts the type we provided into the type the parameter needs.

 Deref coercion was added to Rust so that programmers writing function and method calls don’t need to add as many explicit references and dereferences with `&` and `*`. The deref coercion feature also lets us write more code that can work for either references or smart pointers.

 To see deref coercion in action, let’s use the `MyBox<T>` type we defined in Listing 15-8 as well as the implementation of `Deref` that we added in Listing 15-10. Listing 15-11 shows the definition of a function that has a string slice parameter:

 Filename: src/main.rs

 
```
fn hello(name: &str) {
    println!("Hello, {name}!");
}

fn main() {}
```
 Listing 15-11: A `hello` function that has the parameter `name` of type `&str`

 We can call the `hello` function with a string slice as an argument, such as `hello("Rust");` for example. Deref coercion makes it possible to call `hello` with a reference to a value of type `MyBox<String>`, as shown in Listing 15-12:

 Filename: src/main.rs

 
```
use std::ops::Deref;

impl<T> Deref for MyBox<T> {
    type Target = T;

    fn deref(&self) -> &T {
        &self.0
    }
}

struct MyBox<T>(T);

impl<T> MyBox<T> {
    fn new(x: T) -> MyBox<T> {
        MyBox(x)
    }
}

fn hello(name: &str) {
    println!("Hello, {name}!");
}

fn main() {
    let m = MyBox::new(String::from("Rust"));
    hello(&m);
}
```
 Listing 15-12: Calling `hello` with a reference to a `MyBox<String>` value, which works because of deref coercion

 Here we’re calling the `hello` function with the argument `&m`, which is a reference to a `MyBox<String>` value. Because we implemented the `Deref` trait on `MyBox<T>` in Listing 15-10, Rust can turn `&MyBox<String>` into `&String` by calling `deref`. The standard library provides an implementation of `Deref` on `String` that returns a string slice, and this is in the API documentation for `Deref`. Rust calls `deref` again to turn the `&String` into `&str`, which matches the `hello` function’s definition.

 If Rust didn’t implement deref coercion, we would have to write the code in Listing 15-13 instead of the code in Listing 15-12 to call `hello` with a value of type `&MyBox<String>`.

 Filename: src/main.rs

 
```
use std::ops::Deref;

impl<T> Deref for MyBox<T> {
    type Target = T;

    fn deref(&self) -> &T {
        &self.0
    }
}

struct MyBox<T>(T);

impl<T> MyBox<T> {
    fn new(x: T) -> MyBox<T> {
        MyBox(x)
    }
}

fn hello(name: &str) {
    println!("Hello, {name}!");
}

fn main() {
    let m = MyBox::new(String::from("Rust"));
    hello(&(*m)[..]);
}
```
 Listing 15-13: The code we would have to write if Rust didn’t have deref coercion

 The `(*m)` dereferences the `MyBox<String>` into a `String`. Then the `&` and `[..]` take a string slice of the `String` that is equal to the whole string to match the signature of `hello`. This code without deref coercions is harder to read, write, and understand with all of these symbols involved. Deref coercion allows Rust to handle these conversions for us automatically.

 When the `Deref` trait is defined for the types involved, Rust will analyze the types and use `Deref::deref` as many times as necessary to get a reference to match the parameter’s type. The number of times that `Deref::deref` needs to be inserted is resolved at compile time, so there is no runtime penalty for taking advantage of deref coercion!

 ### How Deref Coercion Interacts with Mutability

 Similar to how you use the `Deref` trait to override the `*` operator on immutable references, you can use the `DerefMut` trait to override the `*` operator on mutable references.

 Rust does deref coercion when it finds types and trait implementations in three cases:

 * From `&T` to `&U` when `T: Deref<Target=U>`
* From `&mut T` to `&mut U` when `T: DerefMut<Target=U>`
* From `&mut T` to `&U` when `T: Deref<Target=U>`

 The first two cases are the same as each other except that the second implements mutability. The first case states that if you have a `&T`, and `T` implements `Deref` to some type `U`, you can get a `&U` transparently. The second case states that the same deref coercion happens for mutable references.

 The third case is trickier: Rust will also coerce a mutable reference to an immutable one. But the reverse is *not* possible: immutable references will never coerce to mutable references. Because of the borrowing rules, if you have a mutable reference, that mutable reference must be the only reference to that data (otherwise, the program wouldn’t compile). Converting one mutable reference to one immutable reference will never break the borrowing rules. Converting an immutable reference to a mutable reference would require that the initial immutable reference is the only immutable reference to that data, but the borrowing rules don’t guarantee that. Therefore, Rust can’t make the assumption that converting an immutable reference to a mutable reference is possible.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch15-02-deref.html>

Running Code on Cleanup with the `Drop` Trait
=============================================

 The second trait important to the smart pointer pattern is `Drop`, which lets you customize what happens when a value is about to go out of scope. You can provide an implementation for the `Drop` trait on any type, and that code can be used to release resources like files or network connections.

 We’re introducing `Drop` in the context of smart pointers because the functionality of the `Drop` trait is almost always used when implementing a smart pointer. For example, when a `Box<T>` is dropped it will deallocate the space on the heap that the box points to.

 In some languages, for some types, the programmer must call code to free memory or resources every time they finish using an instance of those types. Examples include file handles, sockets, or locks. If they forget, the system might become overloaded and crash. In Rust, you can specify that a particular bit of code be run whenever a value goes out of scope, and the compiler will insert this code automatically. As a result, you don’t need to be careful about placing cleanup code everywhere in a program that an instance of a particular type is finished with—you still won’t leak resources!

 You specify the code to run when a value goes out of scope by implementing the `Drop` trait. The `Drop` trait requires you to implement one method named `drop` that takes a mutable reference to `self`. To see when Rust calls `drop`, let’s implement `drop` with `println!` statements for now.

 Listing 15-14 shows a `CustomSmartPointer` struct whose only custom functionality is that it will print `Dropping CustomSmartPointer!` when the instance goes out of scope, to show when Rust runs the `drop` function.

 Filename: src/main.rs

 
```
struct CustomSmartPointer {
    data: String,
}

impl Drop for CustomSmartPointer {
    fn drop(&mut self) {
        println!("Dropping CustomSmartPointer with data `{}`!", self.data);
    }
}

fn main() {
    let c = CustomSmartPointer {
        data: String::from("my stuff"),
    };
    let d = CustomSmartPointer {
        data: String::from("other stuff"),
    };
    println!("CustomSmartPointers created.");
}
```
 Listing 15-14: A `CustomSmartPointer` struct that implements the `Drop` trait where we would put our cleanup code

 The `Drop` trait is included in the prelude, so we don’t need to bring it into scope. We implement the `Drop` trait on `CustomSmartPointer` and provide an implementation for the `drop` method that calls `println!`. The body of the `drop` function is where you would place any logic that you wanted to run when an instance of your type goes out of scope. We’re printing some text here to demonstrate visually when Rust will call `drop`.

 In `main`, we create two instances of `CustomSmartPointer` and then print `CustomSmartPointers created`. At the end of `main`, our instances of `CustomSmartPointer` will go out of scope, and Rust will call the code we put in the `drop` method, printing our final message. Note that we didn’t need to call the `drop` method explicitly.

 When we run this program, we’ll see the following output:

 
```
$ cargo run
   Compiling drop-example v0.1.0 (file:///projects/drop-example)
    Finished dev [unoptimized + debuginfo] target(s) in 0.60s
     Running `target/debug/drop-example`
CustomSmartPointers created.
Dropping CustomSmartPointer with data `other stuff`!
Dropping CustomSmartPointer with data `my stuff`!

```
 Rust automatically called `drop` for us when our instances went out of scope, calling the code we specified. Variables are dropped in the reverse order of their creation, so `d` was dropped before `c`. This example’s purpose is to give you a visual guide to how the `drop` method works; usually you would specify the cleanup code that your type needs to run rather than a print message.

 ### Dropping a Value Early with `std::mem::drop`

 Unfortunately, it’s not straightforward to disable the automatic `drop` functionality. Disabling `drop` isn’t usually necessary; the whole point of the `Drop` trait is that it’s taken care of automatically. Occasionally, however, you might want to clean up a value early. One example is when using smart pointers that manage locks: you might want to force the `drop` method that releases the lock so that other code in the same scope can acquire the lock. Rust doesn’t let you call the `Drop` trait’s `drop` method manually; instead you have to call the `std::mem::drop` function provided by the standard library if you want to force a value to be dropped before the end of its scope.

 If we try to call the `Drop` trait’s `drop` method manually by modifying the `main` function from Listing 15-14, as shown in Listing 15-15, we’ll get a compiler error:

 Filename: src/main.rs

 
```
struct CustomSmartPointer {
    data: String,
}

impl Drop for CustomSmartPointer {
    fn drop(&mut self) {
        println!("Dropping CustomSmartPointer with data `{}`!", self.data);
    }
}

fn main() {
    let c = CustomSmartPointer {
        data: String::from("some data"),
    };
    println!("CustomSmartPointer created.");
    c.drop();
    println!("CustomSmartPointer dropped before the end of main.");
}
```
 Listing 15-15: Attempting to call the `drop` method from the `Drop` trait manually to clean up early

 When we try to compile this code, we’ll get this error:

 
```
$ cargo run
   Compiling drop-example v0.1.0 (file:///projects/drop-example)
error[E0040]: explicit use of destructor method
  --> src/main.rs:16:7
   |
16 |     c.drop();
   |     --^^^^--
   |     | |
   |     | explicit destructor calls not allowed
   |     help: consider using `drop` function: `drop(c)`

For more information about this error, try `rustc --explain E0040`.
error: could not compile `drop-example` due to previous error

```
 This error message states that we’re not allowed to explicitly call `drop`. The error message uses the term *destructor*, which is the general programming term for a function that cleans up an instance. A *destructor* is analogous to a *constructor*, which creates an instance. The `drop` function in Rust is one particular destructor.

 Rust doesn’t let us call `drop` explicitly because Rust would still automatically call `drop` on the value at the end of `main`. This would cause a *double free* error because Rust would be trying to clean up the same value twice.

 We can’t disable the automatic insertion of `drop` when a value goes out of scope, and we can’t call the `drop` method explicitly. So, if we need to force a value to be cleaned up early, we use the `std::mem::drop` function.

 The `std::mem::drop` function is different from the `drop` method in the `Drop` trait. We call it by passing as an argument the value we want to force drop. The function is in the prelude, so we can modify `main` in Listing 15-15 to call the `drop` function, as shown in Listing 15-16:

 Filename: src/main.rs

 
```
struct CustomSmartPointer {
    data: String,
}

impl Drop for CustomSmartPointer {
    fn drop(&mut self) {
        println!("Dropping CustomSmartPointer with data `{}`!", self.data);
    }
}

fn main() {
    let c = CustomSmartPointer {
        data: String::from("some data"),
    };
    println!("CustomSmartPointer created.");
    drop(c);
    println!("CustomSmartPointer dropped before the end of main.");
}
```
 Listing 15-16: Calling `std::mem::drop` to explicitly drop a value before it goes out of scope

 Running this code will print the following:

 
```
$ cargo run
   Compiling drop-example v0.1.0 (file:///projects/drop-example)
    Finished dev [unoptimized + debuginfo] target(s) in 0.73s
     Running `target/debug/drop-example`
CustomSmartPointer created.
Dropping CustomSmartPointer with data `some data`!
CustomSmartPointer dropped before the end of main.

```
 The text `Dropping CustomSmartPointer with data `some data`!` is printed between the `CustomSmartPointer created.` and `CustomSmartPointer dropped before the end of main.` text, showing that the `drop` method code is called to drop `c` at that point.

 You can use code specified in a `Drop` trait implementation in many ways to make cleanup convenient and safe: for instance, you could use it to create your own memory allocator! With the `Drop` trait and Rust’s ownership system, you don’t have to remember to clean up because Rust does it automatically.

 You also don’t have to worry about problems resulting from accidentally cleaning up values still in use: the ownership system that makes sure references are always valid also ensures that `drop` gets called only once when the value is no longer being used.

 Now that we’ve examined `Box<T>` and some of the characteristics of smart pointers, let’s look at a few other smart pointers defined in the standard library.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch15-03-drop.html>

`Rc<T>`, the Reference Counted Smart Pointer
=============================================

 In the majority of cases, ownership is clear: you know exactly which variable owns a given value. However, there are cases when a single value might have multiple owners. For example, in graph data structures, multiple edges might point to the same node, and that node is conceptually owned by all of the edges that point to it. A node shouldn’t be cleaned up unless it doesn’t have any edges pointing to it and so has no owners.

 You have to enable multiple ownership explicitly by using the Rust type `Rc<T>`, which is an abbreviation for *reference counting*. The `Rc<T>` type keeps track of the number of references to a value to determine whether or not the value is still in use. If there are zero references to a value, the value can be cleaned up without any references becoming invalid.

 Imagine `Rc<T>` as a TV in a family room. When one person enters to watch TV, they turn it on. Others can come into the room and watch the TV. When the last person leaves the room, they turn off the TV because it’s no longer being used. If someone turns off the TV while others are still watching it, there would be uproar from the remaining TV watchers!

 We use the `Rc<T>` type when we want to allocate some data on the heap for multiple parts of our program to read and we can’t determine at compile time which part will finish using the data last. If we knew which part would finish last, we could just make that part the data’s owner, and the normal ownership rules enforced at compile time would take effect.

 Note that `Rc<T>` is only for use in single-threaded scenarios. When we discuss concurrency in Chapter 16, we’ll cover how to do reference counting in multithreaded programs.

 ### Using `Rc<T>` to Share Data

 Let’s return to our cons list example in Listing 15-5. Recall that we defined it using `Box<T>`. This time, we’ll create two lists that both share ownership of a third list. Conceptually, this looks similar to Figure 15-3:

 ![Two lists that share ownership of a third list] Figure 15-3: Two lists, `b` and `c`, sharing ownership of a third list, `a`

 We’ll create list `a` that contains 5 and then 10. Then we’ll make two more lists: `b` that starts with 3 and `c` that starts with 4. Both `b` and `c` lists will then continue on to the first `a` list containing 5 and 10. In other words, both lists will share the first list containing 5 and 10.

 Trying to implement this scenario using our definition of `List` with `Box<T>` won’t work, as shown in Listing 15-17:

 Filename: src/main.rs

 
```
enum List {
    Cons(i32, Box<List>),
    Nil,
}

use crate::List::{Cons, Nil};

fn main() {
    let a = Cons(5, Box::new(Cons(10, Box::new(Nil))));
    let b = Cons(3, Box::new(a));
    let c = Cons(4, Box::new(a));
}
```
 Listing 15-17: Demonstrating we’re not allowed to have two lists using `Box<T>` that try to share ownership of a third list

 When we compile this code, we get this error:

 
```
$ cargo run
   Compiling cons-list v0.1.0 (file:///projects/cons-list)
error[E0382]: use of moved value: `a`
  --> src/main.rs:11:30
   |
9  |     let a = Cons(5, Box::new(Cons(10, Box::new(Nil))));
   |         - move occurs because `a` has type `List`, which does not implement the `Copy` trait
10 |     let b = Cons(3, Box::new(a));
   |                              - value moved here
11 |     let c = Cons(4, Box::new(a));
   |                              ^ value used here after move

For more information about this error, try `rustc --explain E0382`.
error: could not compile `cons-list` due to previous error

```
 The `Cons` variants own the data they hold, so when we create the `b` list, `a` is moved into `b` and `b` owns `a`. Then, when we try to use `a` again when creating `c`, we’re not allowed to because `a` has been moved.

 We could change the definition of `Cons` to hold references instead, but then we would have to specify lifetime parameters. By specifying lifetime parameters, we would be specifying that every element in the list will live at least as long as the entire list. This is the case for the elements and lists in Listing 15-17, but not in every scenario.

 Instead, we’ll change our definition of `List` to use `Rc<T>` in place of `Box<T>`, as shown in Listing 15-18. Each `Cons` variant will now hold a value and an `Rc<T>` pointing to a `List`. When we create `b`, instead of taking ownership of `a`, we’ll clone the `Rc<List>` that `a` is holding, thereby increasing the number of references from one to two and letting `a` and `b` share ownership of the data in that `Rc<List>`. We’ll also clone `a` when creating `c`, increasing the number of references from two to three. Every time we call `Rc::clone`, the reference count to the data within the `Rc<List>` will increase, and the data won’t be cleaned up unless there are zero references to it.

 Filename: src/main.rs

 
```
enum List {
    Cons(i32, Rc<List>),
    Nil,
}

use crate::List::{Cons, Nil};
use std::rc::Rc;

fn main() {
    let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil)))));
    let b = Cons(3, Rc::clone(&a));
    let c = Cons(4, Rc::clone(&a));
}
```
 Listing 15-18: A definition of `List` that uses `Rc<T>`

 We need to add a `use` statement to bring `Rc<T>` into scope because it’s not in the prelude. In `main`, we create the list holding 5 and 10 and store it in a new `Rc<List>` in `a`. Then when we create `b` and `c`, we call the `Rc::clone` function and pass a reference to the `Rc<List>` in `a` as an argument.

 We could have called `a.clone()` rather than `Rc::clone(&a)`, but Rust’s convention is to use `Rc::clone` in this case. The implementation of `Rc::clone` doesn’t make a deep copy of all the data like most types’ implementations of `clone` do. The call to `Rc::clone` only increments the reference count, which doesn’t take much time. Deep copies of data can take a lot of time. By using `Rc::clone` for reference counting, we can visually distinguish between the deep-copy kinds of clones and the kinds of clones that increase the reference count. When looking for performance problems in the code, we only need to consider the deep-copy clones and can disregard calls to `Rc::clone`.

 ### Cloning an `Rc<T>` Increases the Reference Count

 Let’s change our working example in Listing 15-18 so we can see the reference counts changing as we create and drop references to the `Rc<List>` in `a`.

 In Listing 15-19, we’ll change `main` so it has an inner scope around list `c`; then we can see how the reference count changes when `c` goes out of scope.

 Filename: src/main.rs

 
```
enum List {
    Cons(i32, Rc<List>),
    Nil,
}

use crate::List::{Cons, Nil};
use std::rc::Rc;

fn main() {
    let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil)))));
    println!("count after creating a = {}", Rc::strong_count(&a));
    let b = Cons(3, Rc::clone(&a));
    println!("count after creating b = {}", Rc::strong_count(&a));
    {
        let c = Cons(4, Rc::clone(&a));
        println!("count after creating c = {}", Rc::strong_count(&a));
    }
    println!("count after c goes out of scope = {}", Rc::strong_count(&a));
}
```
 Listing 15-19: Printing the reference count

 At each point in the program where the reference count changes, we print the reference count, which we get by calling the `Rc::strong_count` function. This function is named `strong_count` rather than `count` because the `Rc<T>` type also has a `weak_count`; we’ll see what `weak_count` is used for in the [“Preventing Reference Cycles: Turning an `Rc<T>` into a `Weak<T>`”](ch15-06-reference-cycles#preventing-reference-cycles-turning-an-rct-into-a-weakt) section.

 This code prints the following:

 
```
$ cargo run
   Compiling cons-list v0.1.0 (file:///projects/cons-list)
    Finished dev [unoptimized + debuginfo] target(s) in 0.45s
     Running `target/debug/cons-list`
count after creating a = 1
count after creating b = 2
count after creating c = 3
count after c goes out of scope = 2

```
 We can see that the `Rc<List>` in `a` has an initial reference count of 1; then each time we call `clone`, the count goes up by 1. When `c` goes out of scope, the count goes down by 1. We don’t have to call a function to decrease the reference count like we have to call `Rc::clone` to increase the reference count: the implementation of the `Drop` trait decreases the reference count automatically when an `Rc<T>` value goes out of scope.

 What we can’t see in this example is that when `b` and then `a` go out of scope at the end of `main`, the count is then 0, and the `Rc<List>` is cleaned up completely. Using `Rc<T>` allows a single value to have multiple owners, and the count ensures that the value remains valid as long as any of the owners still exist.

 Via immutable references, `Rc<T>` allows you to share data between multiple parts of your program for reading only. If `Rc<T>` allowed you to have multiple mutable references too, you might violate one of the borrowing rules discussed in Chapter 4: multiple mutable borrows to the same place can cause data races and inconsistencies. But being able to mutate data is very useful! In the next section, we’ll discuss the interior mutability pattern and the `RefCell<T>` type that you can use in conjunction with an `Rc<T>` to work with this immutability restriction.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch15-04-rc.html>

`RefCell<T>` and the Interior Mutability Pattern
=================================================

 *Interior mutability* is a design pattern in Rust that allows you to mutate data even when there are immutable references to that data; normally, this action is disallowed by the borrowing rules. To mutate data, the pattern uses `unsafe` code inside a data structure to bend Rust’s usual rules that govern mutation and borrowing. Unsafe code indicates to the compiler that we’re checking the rules manually instead of relying on the compiler to check them for us; we will discuss unsafe code more in Chapter 19.

 We can use types that use the interior mutability pattern only when we can ensure that the borrowing rules will be followed at runtime, even though the compiler can’t guarantee that. The `unsafe` code involved is then wrapped in a safe API, and the outer type is still immutable.

 Let’s explore this concept by looking at the `RefCell<T>` type that follows the interior mutability pattern.

 ### Enforcing Borrowing Rules at Runtime with `RefCell<T>`

 Unlike `Rc<T>`, the `RefCell<T>` type represents single ownership over the data it holds. So, what makes `RefCell<T>` different from a type like `Box<T>`? Recall the borrowing rules you learned in Chapter 4:

 * At any given time, you can have *either* (but not both) one mutable reference or any number of immutable references.
* References must always be valid.

 With references and `Box<T>`, the borrowing rules’ invariants are enforced at compile time. With `RefCell<T>`, these invariants are enforced *at runtime*. With references, if you break these rules, you’ll get a compiler error. With `RefCell<T>`, if you break these rules, your program will panic and exit.

 The advantages of checking the borrowing rules at compile time are that errors will be caught sooner in the development process, and there is no impact on runtime performance because all the analysis is completed beforehand. For those reasons, checking the borrowing rules at compile time is the best choice in the majority of cases, which is why this is Rust’s default.

 The advantage of checking the borrowing rules at runtime instead is that certain memory-safe scenarios are then allowed, where they would’ve been disallowed by the compile-time checks. Static analysis, like the Rust compiler, is inherently conservative. Some properties of code are impossible to detect by analyzing the code: the most famous example is the Halting Problem, which is beyond the scope of this book but is an interesting topic to research.

 Because some analysis is impossible, if the Rust compiler can’t be sure the code complies with the ownership rules, it might reject a correct program; in this way, it’s conservative. If Rust accepted an incorrect program, users wouldn’t be able to trust in the guarantees Rust makes. However, if Rust rejects a correct program, the programmer will be inconvenienced, but nothing catastrophic can occur. The `RefCell<T>` type is useful when you’re sure your code follows the borrowing rules but the compiler is unable to understand and guarantee that.

 Similar to `Rc<T>`, `RefCell<T>` is only for use in single-threaded scenarios and will give you a compile-time error if you try using it in a multithreaded context. We’ll talk about how to get the functionality of `RefCell<T>` in a multithreaded program in Chapter 16.

 Here is a recap of the reasons to choose `Box<T>`, `Rc<T>`, or `RefCell<T>`:

 * `Rc<T>` enables multiple owners of the same data; `Box<T>` and `RefCell<T>` have single owners.
* `Box<T>` allows immutable or mutable borrows checked at compile time; `Rc<T>` allows only immutable borrows checked at compile time; `RefCell<T>` allows immutable or mutable borrows checked at runtime.
* Because `RefCell<T>` allows mutable borrows checked at runtime, you can mutate the value inside the `RefCell<T>` even when the `RefCell<T>` is immutable.

 Mutating the value inside an immutable value is the *interior mutability* pattern. Let’s look at a situation in which interior mutability is useful and examine how it’s possible.

 ### Interior Mutability: A Mutable Borrow to an Immutable Value

 A consequence of the borrowing rules is that when you have an immutable value, you can’t borrow it mutably. For example, this code won’t compile:

 
```
fn main() {
    let x = 5;
    let y = &mut x;
}
```
 If you tried to compile this code, you’d get the following error:

 
```
$ cargo run
   Compiling borrowing v0.1.0 (file:///projects/borrowing)
error[E0596]: cannot borrow `x` as mutable, as it is not declared as mutable
 --> src/main.rs:3:13
  |
2 |     let x = 5;
  |         - help: consider changing this to be mutable: `mut x`
3 |     let y = &mut x;
  |             ^^^^^^ cannot borrow as mutable

For more information about this error, try `rustc --explain E0596`.
error: could not compile `borrowing` due to previous error

```
 However, there are situations in which it would be useful for a value to mutate itself in its methods but appear immutable to other code. Code outside the value’s methods would not be able to mutate the value. Using `RefCell<T>` is one way to get the ability to have interior mutability, but `RefCell<T>` doesn’t get around the borrowing rules completely: the borrow checker in the compiler allows this interior mutability, and the borrowing rules are checked at runtime instead. If you violate the rules, you’ll get a `panic!` instead of a compiler error.

 Let’s work through a practical example where we can use `RefCell<T>` to mutate an immutable value and see why that is useful.

 #### A Use Case for Interior Mutability: Mock Objects

 Sometimes during testing a programmer will use a type in place of another type, in order to observe particular behavior and assert it’s implemented correctly. This placeholder type is called a *test double*. Think of it in the sense of a “stunt double” in filmmaking, where a person steps in and substitutes for an actor to do a particular tricky scene. Test doubles stand in for other types when we’re running tests. *Mock objects* are specific types of test doubles that record what happens during a test so you can assert that the correct actions took place.

 Rust doesn’t have objects in the same sense as other languages have objects, and Rust doesn’t have mock object functionality built into the standard library as some other languages do. However, you can definitely create a struct that will serve the same purposes as a mock object.

 Here’s the scenario we’ll test: we’ll create a library that tracks a value against a maximum value and sends messages based on how close to the maximum value the current value is. This library could be used to keep track of a user’s quota for the number of API calls they’re allowed to make, for example.

 Our library will only provide the functionality of tracking how close to the maximum a value is and what the messages should be at what times. Applications that use our library will be expected to provide the mechanism for sending the messages: the application could put a message in the application, send an email, send a text message, or something else. The library doesn’t need to know that detail. All it needs is something that implements a trait we’ll provide called `Messenger`. Listing 15-20 shows the library code:

 Filename: src/lib.rs

 
```
pub trait Messenger {
    fn send(&self, msg: &str);
}

pub struct LimitTracker<'a, T: Messenger> {
    messenger: &'a T,
    value: usize,
    max: usize,
}

impl<'a, T> LimitTracker<'a, T>
where
    T: Messenger,
{
    pub fn new(messenger: &'a T, max: usize) -> LimitTracker<'a, T> {
        LimitTracker {
            messenger,
            value: 0,
            max,
        }
    }

    pub fn set_value(&mut self, value: usize) {
        self.value = value;

        let percentage_of_max = self.value as f64 / self.max as f64;

        if percentage_of_max >= 1.0 {
            self.messenger.send("Error: You are over your quota!");
        } else if percentage_of_max >= 0.9 {
            self.messenger
                .send("Urgent warning: You've used up over 90% of your quota!");
        } else if percentage_of_max >= 0.75 {
            self.messenger
                .send("Warning: You've used up over 75% of your quota!");
        }
    }
}
```
 Listing 15-20: A library to keep track of how close a value is to a maximum value and warn when the value is at certain levels

 One important part of this code is that the `Messenger` trait has one method called `send` that takes an immutable reference to `self` and the text of the message. This trait is the interface our mock object needs to implement so that the mock can be used in the same way a real object is. The other important part is that we want to test the behavior of the `set_value` method on the `LimitTracker`. We can change what we pass in for the `value` parameter, but `set_value` doesn’t return anything for us to make assertions on. We want to be able to say that if we create a `LimitTracker` with something that implements the `Messenger` trait and a particular value for `max`, when we pass different numbers for `value`, the messenger is told to send the appropriate messages.

 We need a mock object that, instead of sending an email or text message when we call `send`, will only keep track of the messages it’s told to send. We can create a new instance of the mock object, create a `LimitTracker` that uses the mock object, call the `set_value` method on `LimitTracker`, and then check that the mock object has the messages we expect. Listing 15-21 shows an attempt to implement a mock object to do just that, but the borrow checker won’t allow it:

 Filename: src/lib.rs

 
```
pub trait Messenger {
    fn send(&self, msg: &str);
}

pub struct LimitTracker<'a, T: Messenger> {
    messenger: &'a T,
    value: usize,
    max: usize,
}

impl<'a, T> LimitTracker<'a, T>
where
    T: Messenger,
{
    pub fn new(messenger: &'a T, max: usize) -> LimitTracker<'a, T> {
        LimitTracker {
            messenger,
            value: 0,
            max,
        }
    }

    pub fn set_value(&mut self, value: usize) {
        self.value = value;

        let percentage_of_max = self.value as f64 / self.max as f64;

        if percentage_of_max >= 1.0 {
            self.messenger.send("Error: You are over your quota!");
        } else if percentage_of_max >= 0.9 {
            self.messenger
                .send("Urgent warning: You've used up over 90% of your quota!");
        } else if percentage_of_max >= 0.75 {
            self.messenger
                .send("Warning: You've used up over 75% of your quota!");
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    struct MockMessenger {
        sent_messages: Vec<String>,
    }

    impl MockMessenger {
        fn new() -> MockMessenger {
            MockMessenger {
                sent_messages: vec![],
            }
        }
    }

    impl Messenger for MockMessenger {
        fn send(&self, message: &str) {
            self.sent_messages.push(String::from(message));
        }
    }

    #[test]
    fn it_sends_an_over_75_percent_warning_message() {
        let mock_messenger = MockMessenger::new();
        let mut limit_tracker = LimitTracker::new(&mock_messenger, 100);

        limit_tracker.set_value(80);

        assert_eq!(mock_messenger.sent_messages.len(), 1);
    }
}
```
 Listing 15-21: An attempt to implement a `MockMessenger` that isn’t allowed by the borrow checker

 This test code defines a `MockMessenger` struct that has a `sent_messages` field with a `Vec` of `String` values to keep track of the messages it’s told to send. We also define an associated function `new` to make it convenient to create new `MockMessenger` values that start with an empty list of messages. We then implement the `Messenger` trait for `MockMessenger` so we can give a `MockMessenger` to a `LimitTracker`. In the definition of the `send` method, we take the message passed in as a parameter and store it in the `MockMessenger` list of `sent_messages`.

 In the test, we’re testing what happens when the `LimitTracker` is told to set `value` to something that is more than 75 percent of the `max` value. First, we create a new `MockMessenger`, which will start with an empty list of messages. Then we create a new `LimitTracker` and give it a reference to the new `MockMessenger` and a `max` value of 100. We call the `set_value` method on the `LimitTracker` with a value of 80, which is more than 75 percent of 100. Then we assert that the list of messages that the `MockMessenger` is keeping track of should now have one message in it.

 However, there’s one problem with this test, as shown here:

 
```
$ cargo test
   Compiling limit-tracker v0.1.0 (file:///projects/limit-tracker)
error[E0596]: cannot borrow `self.sent_messages` as mutable, as it is behind a `&` reference
  --> src/lib.rs:58:13
   |
2  |     fn send(&self, msg: &str);
   |             ----- help: consider changing that to be a mutable reference: `&mut self`
...
58 |             self.sent_messages.push(String::from(message));
   |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `self` is a `&` reference, so the data it refers to cannot be borrowed as mutable

For more information about this error, try `rustc --explain E0596`.
error: could not compile `limit-tracker` due to previous error
warning: build failed, waiting for other jobs to finish...

```
 We can’t modify the `MockMessenger` to keep track of the messages, because the `send` method takes an immutable reference to `self`. We also can’t take the suggestion from the error text to use `&mut self` instead, because then the signature of `send` wouldn’t match the signature in the `Messenger` trait definition (feel free to try and see what error message you get).

 This is a situation in which interior mutability can help! We’ll store the `sent_messages` within a `RefCell<T>`, and then the `send` method will be able to modify `sent_messages` to store the messages we’ve seen. Listing 15-22 shows what that looks like:

 Filename: src/lib.rs

 
```
pub trait Messenger {
    fn send(&self, msg: &str);
}

pub struct LimitTracker<'a, T: Messenger> {
    messenger: &'a T,
    value: usize,
    max: usize,
}

impl<'a, T> LimitTracker<'a, T>
where
    T: Messenger,
{
    pub fn new(messenger: &'a T, max: usize) -> LimitTracker<'a, T> {
        LimitTracker {
            messenger,
            value: 0,
            max,
        }
    }

    pub fn set_value(&mut self, value: usize) {
        self.value = value;

        let percentage_of_max = self.value as f64 / self.max as f64;

        if percentage_of_max >= 1.0 {
            self.messenger.send("Error: You are over your quota!");
        } else if percentage_of_max >= 0.9 {
            self.messenger
                .send("Urgent warning: You've used up over 90% of your quota!");
        } else if percentage_of_max >= 0.75 {
            self.messenger
                .send("Warning: You've used up over 75% of your quota!");
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::RefCell;

    struct MockMessenger {
        sent_messages: RefCell<Vec<String>>,
    }

    impl MockMessenger {
        fn new() -> MockMessenger {
            MockMessenger {
                sent_messages: RefCell::new(vec![]),
            }
        }
    }

    impl Messenger for MockMessenger {
        fn send(&self, message: &str) {
            self.sent_messages.borrow_mut().push(String::from(message));
        }
    }

    #[test]
    fn it_sends_an_over_75_percent_warning_message() {
        // --snip--
        let mock_messenger = MockMessenger::new();
        let mut limit_tracker = LimitTracker::new(&mock_messenger, 100);

        limit_tracker.set_value(80);

        assert_eq!(mock_messenger.sent_messages.borrow().len(), 1);
    }
}
```
 Listing 15-22: Using `RefCell<T>` to mutate an inner value while the outer value is considered immutable

 The `sent_messages` field is now of type `RefCell<Vec<String>>` instead of `Vec<String>`. In the `new` function, we create a new `RefCell<Vec<String>>` instance around the empty vector.

 For the implementation of the `send` method, the first parameter is still an immutable borrow of `self`, which matches the trait definition. We call `borrow_mut` on the `RefCell<Vec<String>>` in `self.sent_messages` to get a mutable reference to the value inside the `RefCell<Vec<String>>`, which is the vector. Then we can call `push` on the mutable reference to the vector to keep track of the messages sent during the test.

 The last change we have to make is in the assertion: to see how many items are in the inner vector, we call `borrow` on the `RefCell<Vec<String>>` to get an immutable reference to the vector.

 Now that you’ve seen how to use `RefCell<T>`, let’s dig into how it works!

 #### Keeping Track of Borrows at Runtime with `RefCell<T>`

 When creating immutable and mutable references, we use the `&` and `&mut` syntax, respectively. With `RefCell<T>`, we use the `borrow` and `borrow_mut` methods, which are part of the safe API that belongs to `RefCell<T>`. The `borrow` method returns the smart pointer type `Ref<T>`, and `borrow_mut` returns the smart pointer type `RefMut<T>`. Both types implement `Deref`, so we can treat them like regular references.

 The `RefCell<T>` keeps track of how many `Ref<T>` and `RefMut<T>` smart pointers are currently active. Every time we call `borrow`, the `RefCell<T>` increases its count of how many immutable borrows are active. When a `Ref<T>` value goes out of scope, the count of immutable borrows goes down by one. Just like the compile-time borrowing rules, `RefCell<T>` lets us have many immutable borrows or one mutable borrow at any point in time.

 If we try to violate these rules, rather than getting a compiler error as we would with references, the implementation of `RefCell<T>` will panic at runtime. Listing 15-23 shows a modification of the implementation of `send` in Listing 15-22. We’re deliberately trying to create two mutable borrows active for the same scope to illustrate that `RefCell<T>` prevents us from doing this at runtime.

 Filename: src/lib.rs

 
```
pub trait Messenger {
    fn send(&self, msg: &str);
}

pub struct LimitTracker<'a, T: Messenger> {
    messenger: &'a T,
    value: usize,
    max: usize,
}

impl<'a, T> LimitTracker<'a, T>
where
    T: Messenger,
{
    pub fn new(messenger: &'a T, max: usize) -> LimitTracker<'a, T> {
        LimitTracker {
            messenger,
            value: 0,
            max,
        }
    }

    pub fn set_value(&mut self, value: usize) {
        self.value = value;

        let percentage_of_max = self.value as f64 / self.max as f64;

        if percentage_of_max >= 1.0 {
            self.messenger.send("Error: You are over your quota!");
        } else if percentage_of_max >= 0.9 {
            self.messenger
                .send("Urgent warning: You've used up over 90% of your quota!");
        } else if percentage_of_max >= 0.75 {
            self.messenger
                .send("Warning: You've used up over 75% of your quota!");
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::RefCell;

    struct MockMessenger {
        sent_messages: RefCell<Vec<String>>,
    }

    impl MockMessenger {
        fn new() -> MockMessenger {
            MockMessenger {
                sent_messages: RefCell::new(vec![]),
            }
        }
    }

    impl Messenger for MockMessenger {
        fn send(&self, message: &str) {
            let mut one_borrow = self.sent_messages.borrow_mut();
            let mut two_borrow = self.sent_messages.borrow_mut();

            one_borrow.push(String::from(message));
            two_borrow.push(String::from(message));
        }
    }

    #[test]
    fn it_sends_an_over_75_percent_warning_message() {
        let mock_messenger = MockMessenger::new();
        let mut limit_tracker = LimitTracker::new(&mock_messenger, 100);

        limit_tracker.set_value(80);

        assert_eq!(mock_messenger.sent_messages.borrow().len(), 1);
    }
}
```
 Listing 15-23: Creating two mutable references in the same scope to see that `RefCell<T>` will panic

 We create a variable `one_borrow` for the `RefMut<T>` smart pointer returned from `borrow_mut`. Then we create another mutable borrow in the same way in the variable `two_borrow`. This makes two mutable references in the same scope, which isn’t allowed. When we run the tests for our library, the code in Listing 15-23 will compile without any errors, but the test will fail:

 
```
$ cargo test
   Compiling limit-tracker v0.1.0 (file:///projects/limit-tracker)
    Finished test [unoptimized + debuginfo] target(s) in 0.91s
     Running unittests src/lib.rs (target/debug/deps/limit_tracker-e599811fa246dbde)

running 1 test
test tests::it_sends_an_over_75_percent_warning_message ... FAILED

failures:

---- tests::it_sends_an_over_75_percent_warning_message stdout ----
thread 'tests::it_sends_an_over_75_percent_warning_message' panicked at 'already borrowed: BorrowMutError', src/lib.rs:60:53
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace


failures:
    tests::it_sends_an_over_75_percent_warning_message

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

error: test failed, to rerun pass `--lib`

```
 Notice that the code panicked with the message `already borrowed: BorrowMutError`. This is how `RefCell<T>` handles violations of the borrowing rules at runtime.

 Choosing to catch borrowing errors at runtime rather than compile time, as we’ve done here, means you’d potentially be finding mistakes in your code later in the development process: possibly not until your code was deployed to production. Also, your code would incur a small runtime performance penalty as a result of keeping track of the borrows at runtime rather than compile time. However, using `RefCell<T>` makes it possible to write a mock object that can modify itself to keep track of the messages it has seen while you’re using it in a context where only immutable values are allowed. You can use `RefCell<T>` despite its trade-offs to get more functionality than regular references provide.

 ### Having Multiple Owners of Mutable Data by Combining `Rc<T>` and `RefCell<T>`

 A common way to use `RefCell<T>` is in combination with `Rc<T>`. Recall that `Rc<T>` lets you have multiple owners of some data, but it only gives immutable access to that data. If you have an `Rc<T>` that holds a `RefCell<T>`, you can get a value that can have multiple owners *and* that you can mutate!

 For example, recall the cons list example in Listing 15-18 where we used `Rc<T>` to allow multiple lists to share ownership of another list. Because `Rc<T>` holds only immutable values, we can’t change any of the values in the list once we’ve created them. Let’s add in `RefCell<T>` to gain the ability to change the values in the lists. Listing 15-24 shows that by using a `RefCell<T>` in the `Cons` definition, we can modify the value stored in all the lists:

 Filename: src/main.rs

 
```
#[derive(Debug)]
enum List {
    Cons(Rc<RefCell<i32>>, Rc<List>),
    Nil,
}

use crate::List::{Cons, Nil};
use std::cell::RefCell;
use std::rc::Rc;

fn main() {
    let value = Rc::new(RefCell::new(5));

    let a = Rc::new(Cons(Rc::clone(&value), Rc::new(Nil)));

    let b = Cons(Rc::new(RefCell::new(3)), Rc::clone(&a));
    let c = Cons(Rc::new(RefCell::new(4)), Rc::clone(&a));

    *value.borrow_mut() += 10;

    println!("a after = {:?}", a);
    println!("b after = {:?}", b);
    println!("c after = {:?}", c);
}
```
 Listing 15-24: Using `Rc<RefCell<i32>>` to create a `List` that we can mutate

 We create a value that is an instance of `Rc<RefCell<i32>>` and store it in a variable named `value` so we can access it directly later. Then we create a `List` in `a` with a `Cons` variant that holds `value`. We need to clone `value` so both `a` and `value` have ownership of the inner `5` value rather than transferring ownership from `value` to `a` or having `a` borrow from `value`.

 We wrap the list `a` in an `Rc<T>` so when we create lists `b` and `c`, they can both refer to `a`, which is what we did in Listing 15-18.

 After we’ve created the lists in `a`, `b`, and `c`, we want to add 10 to the value in `value`. We do this by calling `borrow_mut` on `value`, which uses the automatic dereferencing feature we discussed in Chapter 5 (see the section [“Where’s the `->` Operator?”](ch05-03-method-syntax#wheres-the---operator)) to dereference the `Rc<T>` to the inner `RefCell<T>` value. The `borrow_mut` method returns a `RefMut<T>` smart pointer, and we use the dereference operator on it and change the inner value.

 When we print `a`, `b`, and `c`, we can see that they all have the modified value of 15 rather than 5:

 
```
$ cargo run
   Compiling cons-list v0.1.0 (file:///projects/cons-list)
    Finished dev [unoptimized + debuginfo] target(s) in 0.63s
     Running `target/debug/cons-list`
a after = Cons(RefCell { value: 15 }, Nil)
b after = Cons(RefCell { value: 3 }, Cons(RefCell { value: 15 }, Nil))
c after = Cons(RefCell { value: 4 }, Cons(RefCell { value: 15 }, Nil))

```
 This technique is pretty neat! By using `RefCell<T>`, we have an outwardly immutable `List` value. But we can use the methods on `RefCell<T>` that provide access to its interior mutability so we can modify our data when we need to. The runtime checks of the borrowing rules protect us from data races, and it’s sometimes worth trading a bit of speed for this flexibility in our data structures. Note that `RefCell<T>` does not work for multithreaded code! `Mutex<T>` is the thread-safe version of `RefCell<T>` and we’ll discuss `Mutex<T>` in Chapter 16.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch15-05-interior-mutability.html>

Reference Cycles Can Leak Memory
================================

 Rust’s memory safety guarantees make it difficult, but not impossible, to accidentally create memory that is never cleaned up (known as a *memory leak*). Preventing memory leaks entirely is not one of Rust’s guarantees, meaning memory leaks are memory safe in Rust. We can see that Rust allows memory leaks by using `Rc<T>` and `RefCell<T>`: it’s possible to create references where items refer to each other in a cycle. This creates memory leaks because the reference count of each item in the cycle will never reach 0, and the values will never be dropped.

 ### Creating a Reference Cycle

 Let’s look at how a reference cycle might happen and how to prevent it, starting with the definition of the `List` enum and a `tail` method in Listing 15-25:

 Filename: src/main.rs

 
```
use crate::List::{Cons, Nil};
use std::cell::RefCell;
use std::rc::Rc;

#[derive(Debug)]
enum List {
    Cons(i32, RefCell<Rc<List>>),
    Nil,
}

impl List {
    fn tail(&self) -> Option<&RefCell<Rc<List>>> {
        match self {
            Cons(_, item) => Some(item),
            Nil => None,
        }
    }
}

fn main() {}
```
 Listing 15-25: A cons list definition that holds a `RefCell<T>` so we can modify what a `Cons` variant is referring to

 We’re using another variation of the `List` definition from Listing 15-5. The second element in the `Cons` variant is now `RefCell<Rc<List>>`, meaning that instead of having the ability to modify the `i32` value as we did in Listing 15-24, we want to modify the `List` value a `Cons` variant is pointing to. We’re also adding a `tail` method to make it convenient for us to access the second item if we have a `Cons` variant.

 In Listing 15-26, we’re adding a `main` function that uses the definitions in Listing 15-25. This code creates a list in `a` and a list in `b` that points to the list in `a`. Then it modifies the list in `a` to point to `b`, creating a reference cycle. There are `println!` statements along the way to show what the reference counts are at various points in this process.

 Filename: src/main.rs

 
```
use crate::List::{Cons, Nil};
use std::cell::RefCell;
use std::rc::Rc;

#[derive(Debug)]
enum List {
    Cons(i32, RefCell<Rc<List>>),
    Nil,
}

impl List {
    fn tail(&self) -> Option<&RefCell<Rc<List>>> {
        match self {
            Cons(_, item) => Some(item),
            Nil => None,
        }
    }
}

fn main() {
    let a = Rc::new(Cons(5, RefCell::new(Rc::new(Nil))));

    println!("a initial rc count = {}", Rc::strong_count(&a));
    println!("a next item = {:?}", a.tail());

    let b = Rc::new(Cons(10, RefCell::new(Rc::clone(&a))));

    println!("a rc count after b creation = {}", Rc::strong_count(&a));
    println!("b initial rc count = {}", Rc::strong_count(&b));
    println!("b next item = {:?}", b.tail());

    if let Some(link) = a.tail() {
        *link.borrow_mut() = Rc::clone(&b);
    }

    println!("b rc count after changing a = {}", Rc::strong_count(&b));
    println!("a rc count after changing a = {}", Rc::strong_count(&a));

    // Uncomment the next line to see that we have a cycle;
    // it will overflow the stack
    // println!("a next item = {:?}", a.tail());
}
```
 Listing 15-26: Creating a reference cycle of two `List` values pointing to each other

 We create an `Rc<List>` instance holding a `List` value in the variable `a` with an initial list of `5, Nil`. We then create an `Rc<List>` instance holding another `List` value in the variable `b` that contains the value 10 and points to the list in `a`.

 We modify `a` so it points to `b` instead of `Nil`, creating a cycle. We do that by using the `tail` method to get a reference to the `RefCell<Rc<List>>` in `a`, which we put in the variable `link`. Then we use the `borrow_mut` method on the `RefCell<Rc<List>>` to change the value inside from an `Rc<List>` that holds a `Nil` value to the `Rc<List>` in `b`.

 When we run this code, keeping the last `println!` commented out for the moment, we’ll get this output:

 
```
$ cargo run
   Compiling cons-list v0.1.0 (file:///projects/cons-list)
    Finished dev [unoptimized + debuginfo] target(s) in 0.53s
     Running `target/debug/cons-list`
a initial rc count = 1
a next item = Some(RefCell { value: Nil })
a rc count after b creation = 2
b initial rc count = 1
b next item = Some(RefCell { value: Cons(5, RefCell { value: Nil }) })
b rc count after changing a = 2
a rc count after changing a = 2

```
 The reference count of the `Rc<List>` instances in both `a` and `b` are 2 after we change the list in `a` to point to `b`. At the end of `main`, Rust drops the variable `b`, which decreases the reference count of the `b` `Rc<List>` instance from 2 to 1. The memory that `Rc<List>` has on the heap won’t be dropped at this point, because its reference count is 1, not 0. Then Rust drops `a`, which decreases the reference count of the `a` `Rc<List>` instance from 2 to 1 as well. This instance’s memory can’t be dropped either, because the other `Rc<List>` instance still refers to it. The memory allocated to the list will remain uncollected forever. To visualize this reference cycle, we’ve created a diagram in Figure 15-4.

 ![Reference cycle of lists] Figure 15-4: A reference cycle of lists `a` and `b` pointing to each other

 If you uncomment the last `println!` and run the program, Rust will try to print this cycle with `a` pointing to `b` pointing to `a` and so forth until it overflows the stack.

 Compared to a real-world program, the consequences of creating a reference cycle in this example aren’t very dire: right after we create the reference cycle, the program ends. However, if a more complex program allocated lots of memory in a cycle and held onto it for a long time, the program would use more memory than it needed and might overwhelm the system, causing it to run out of available memory.

 Creating reference cycles is not easily done, but it’s not impossible either. If you have `RefCell<T>` values that contain `Rc<T>` values or similar nested combinations of types with interior mutability and reference counting, you must ensure that you don’t create cycles; you can’t rely on Rust to catch them. Creating a reference cycle would be a logic bug in your program that you should use automated tests, code reviews, and other software development practices to minimize.

 Another solution for avoiding reference cycles is reorganizing your data structures so that some references express ownership and some references don’t. As a result, you can have cycles made up of some ownership relationships and some non-ownership relationships, and only the ownership relationships affect whether or not a value can be dropped. In Listing 15-25, we always want `Cons` variants to own their list, so reorganizing the data structure isn’t possible. Let’s look at an example using graphs made up of parent nodes and child nodes to see when non-ownership relationships are an appropriate way to prevent reference cycles.

 ### Preventing Reference Cycles: Turning an `Rc<T>` into a `Weak<T>`

 So far, we’ve demonstrated that calling `Rc::clone` increases the `strong_count` of an `Rc<T>` instance, and an `Rc<T>` instance is only cleaned up if its `strong_count` is 0. You can also create a *weak reference* to the value within an `Rc<T>` instance by calling `Rc::downgrade` and passing a reference to the `Rc<T>`. Strong references are how you can share ownership of an `Rc<T>` instance. Weak references don’t express an ownership relationship, and their count doesn’t affect when an `Rc<T>` instance is cleaned up. They won’t cause a reference cycle because any cycle involving some weak references will be broken once the strong reference count of values involved is 0.

 When you call `Rc::downgrade`, you get a smart pointer of type `Weak<T>`. Instead of increasing the `strong_count` in the `Rc<T>` instance by 1, calling `Rc::downgrade` increases the `weak_count` by 1. The `Rc<T>` type uses `weak_count` to keep track of how many `Weak<T>` references exist, similar to `strong_count`. The difference is the `weak_count` doesn’t need to be 0 for the `Rc<T>` instance to be cleaned up.

 Because the value that `Weak<T>` references might have been dropped, to do anything with the value that a `Weak<T>` is pointing to, you must make sure the value still exists. Do this by calling the `upgrade` method on a `Weak<T>` instance, which will return an `Option<Rc<T>>`. You’ll get a result of `Some` if the `Rc<T>` value has not been dropped yet and a result of `None` if the `Rc<T>` value has been dropped. Because `upgrade` returns an `Option<Rc<T>>`, Rust will ensure that the `Some` case and the `None` case are handled, and there won’t be an invalid pointer.

 As an example, rather than using a list whose items know only about the next item, we’ll create a tree whose items know about their children items *and* their parent items.

 #### Creating a Tree Data Structure: a `Node` with Child Nodes

 To start, we’ll build a tree with nodes that know about their child nodes. We’ll create a struct named `Node` that holds its own `i32` value as well as references to its children `Node` values:

 Filename: src/main.rs

 
```
use std::cell::RefCell;
use std::rc::Rc;

#[derive(Debug)]
struct Node {
    value: i32,
    children: RefCell<Vec<Rc<Node>>>,
}

fn main() {
    let leaf = Rc::new(Node {
        value: 3,
        children: RefCell::new(vec![]),
    });

    let branch = Rc::new(Node {
        value: 5,
        children: RefCell::new(vec![Rc::clone(&leaf)]),
    });
}
```
 We want a `Node` to own its children, and we want to share that ownership with variables so we can access each `Node` in the tree directly. To do this, we define the `Vec<T>` items to be values of type `Rc<Node>`. We also want to modify which nodes are children of another node, so we have a `RefCell<T>` in `children` around the `Vec<Rc<Node>>`.

 Next, we’ll use our struct definition and create one `Node` instance named `leaf` with the value 3 and no children, and another instance named `branch` with the value 5 and `leaf` as one of its children, as shown in Listing 15-27:

 Filename: src/main.rs

 
```
use std::cell::RefCell;
use std::rc::Rc;

#[derive(Debug)]
struct Node {
    value: i32,
    children: RefCell<Vec<Rc<Node>>>,
}

fn main() {
    let leaf = Rc::new(Node {
        value: 3,
        children: RefCell::new(vec![]),
    });

    let branch = Rc::new(Node {
        value: 5,
        children: RefCell::new(vec![Rc::clone(&leaf)]),
    });
}
```
 Listing 15-27: Creating a `leaf` node with no children and a `branch` node with `leaf` as one of its children

 We clone the `Rc<Node>` in `leaf` and store that in `branch`, meaning the `Node` in `leaf` now has two owners: `leaf` and `branch`. We can get from `branch` to `leaf` through `branch.children`, but there’s no way to get from `leaf` to `branch`. The reason is that `leaf` has no reference to `branch` and doesn’t know they’re related. We want `leaf` to know that `branch` is its parent. We’ll do that next.

 #### Adding a Reference from a Child to Its Parent

 To make the child node aware of its parent, we need to add a `parent` field to our `Node` struct definition. The trouble is in deciding what the type of `parent` should be. We know it can’t contain an `Rc<T>`, because that would create a reference cycle with `leaf.parent` pointing to `branch` and `branch.children` pointing to `leaf`, which would cause their `strong_count` values to never be 0.

 Thinking about the relationships another way, a parent node should own its children: if a parent node is dropped, its child nodes should be dropped as well. However, a child should not own its parent: if we drop a child node, the parent should still exist. This is a case for weak references!

 So instead of `Rc<T>`, we’ll make the type of `parent` use `Weak<T>`, specifically a `RefCell<Weak<Node>>`. Now our `Node` struct definition looks like this:

 Filename: src/main.rs

 
```
use std::cell::RefCell;
use std::rc::{Rc, Weak};

#[derive(Debug)]
struct Node {
    value: i32,
    parent: RefCell<Weak<Node>>,
    children: RefCell<Vec<Rc<Node>>>,
}

fn main() {
    let leaf = Rc::new(Node {
        value: 3,
        parent: RefCell::new(Weak::new()),
        children: RefCell::new(vec![]),
    });

    println!("leaf parent = {:?}", leaf.parent.borrow().upgrade());

    let branch = Rc::new(Node {
        value: 5,
        parent: RefCell::new(Weak::new()),
        children: RefCell::new(vec![Rc::clone(&leaf)]),
    });

    *leaf.parent.borrow_mut() = Rc::downgrade(&branch);

    println!("leaf parent = {:?}", leaf.parent.borrow().upgrade());
}
```
 A node will be able to refer to its parent node but doesn’t own its parent. In Listing 15-28, we update `main` to use this new definition so the `leaf` node will have a way to refer to its parent, `branch`:

 Filename: src/main.rs

 
```
use std::cell::RefCell;
use std::rc::{Rc, Weak};

#[derive(Debug)]
struct Node {
    value: i32,
    parent: RefCell<Weak<Node>>,
    children: RefCell<Vec<Rc<Node>>>,
}

fn main() {
    let leaf = Rc::new(Node {
        value: 3,
        parent: RefCell::new(Weak::new()),
        children: RefCell::new(vec![]),
    });

    println!("leaf parent = {:?}", leaf.parent.borrow().upgrade());

    let branch = Rc::new(Node {
        value: 5,
        parent: RefCell::new(Weak::new()),
        children: RefCell::new(vec![Rc::clone(&leaf)]),
    });

    *leaf.parent.borrow_mut() = Rc::downgrade(&branch);

    println!("leaf parent = {:?}", leaf.parent.borrow().upgrade());
}
```
 Listing 15-28: A `leaf` node with a weak reference to its parent node `branch`

 Creating the `leaf` node looks similar to Listing 15-27 with the exception of the `parent` field: `leaf` starts out without a parent, so we create a new, empty `Weak<Node>` reference instance.

 At this point, when we try to get a reference to the parent of `leaf` by using the `upgrade` method, we get a `None` value. We see this in the output from the first `println!` statement:

 
```
leaf parent = None

```
 When we create the `branch` node, it will also have a new `Weak<Node>` reference in the `parent` field, because `branch` doesn’t have a parent node. We still have `leaf` as one of the children of `branch`. Once we have the `Node` instance in `branch`, we can modify `leaf` to give it a `Weak<Node>` reference to its parent. We use the `borrow_mut` method on the `RefCell<Weak<Node>>` in the `parent` field of `leaf`, and then we use the `Rc::downgrade` function to create a `Weak<Node>` reference to `branch` from the `Rc<Node>` in `branch.`

 When we print the parent of `leaf` again, this time we’ll get a `Some` variant holding `branch`: now `leaf` can access its parent! When we print `leaf`, we also avoid the cycle that eventually ended in a stack overflow like we had in Listing 15-26; the `Weak<Node>` references are printed as `(Weak)`:

 
```
leaf parent = Some(Node { value: 5, parent: RefCell { value: (Weak) },
children: RefCell { value: [Node { value: 3, parent: RefCell { value: (Weak) },
children: RefCell { value: [] } }] } })

```
 The lack of infinite output indicates that this code didn’t create a reference cycle. We can also tell this by looking at the values we get from calling `Rc::strong_count` and `Rc::weak_count`.

 #### Visualizing Changes to `strong_count` and `weak_count`

 Let’s look at how the `strong_count` and `weak_count` values of the `Rc<Node>` instances change by creating a new inner scope and moving the creation of `branch` into that scope. By doing so, we can see what happens when `branch` is created and then dropped when it goes out of scope. The modifications are shown in Listing 15-29:

 Filename: src/main.rs

 
```
use std::cell::RefCell;
use std::rc::{Rc, Weak};

#[derive(Debug)]
struct Node {
    value: i32,
    parent: RefCell<Weak<Node>>,
    children: RefCell<Vec<Rc<Node>>>,
}

fn main() {
    let leaf = Rc::new(Node {
        value: 3,
        parent: RefCell::new(Weak::new()),
        children: RefCell::new(vec![]),
    });

    println!(
        "leaf strong = {}, weak = {}",
        Rc::strong_count(&leaf),
        Rc::weak_count(&leaf),
    );

    {
        let branch = Rc::new(Node {
            value: 5,
            parent: RefCell::new(Weak::new()),
            children: RefCell::new(vec![Rc::clone(&leaf)]),
        });

        *leaf.parent.borrow_mut() = Rc::downgrade(&branch);

        println!(
            "branch strong = {}, weak = {}",
            Rc::strong_count(&branch),
            Rc::weak_count(&branch),
        );

        println!(
            "leaf strong = {}, weak = {}",
            Rc::strong_count(&leaf),
            Rc::weak_count(&leaf),
        );
    }

    println!("leaf parent = {:?}", leaf.parent.borrow().upgrade());
    println!(
        "leaf strong = {}, weak = {}",
        Rc::strong_count(&leaf),
        Rc::weak_count(&leaf),
    );
}
```
 Listing 15-29: Creating `branch` in an inner scope and examining strong and weak reference counts

 After `leaf` is created, its `Rc<Node>` has a strong count of 1 and a weak count of 0. In the inner scope, we create `branch` and associate it with `leaf`, at which point when we print the counts, the `Rc<Node>` in `branch` will have a strong count of 1 and a weak count of 1 (for `leaf.parent` pointing to `branch` with a `Weak<Node>`). When we print the counts in `leaf`, we’ll see it will have a strong count of 2, because `branch` now has a clone of the `Rc<Node>` of `leaf` stored in `branch.children`, but will still have a weak count of 0.

 When the inner scope ends, `branch` goes out of scope and the strong count of the `Rc<Node>` decreases to 0, so its `Node` is dropped. The weak count of 1 from `leaf.parent` has no bearing on whether or not `Node` is dropped, so we don’t get any memory leaks!

 If we try to access the parent of `leaf` after the end of the scope, we’ll get `None` again. At the end of the program, the `Rc<Node>` in `leaf` has a strong count of 1 and a weak count of 0, because the variable `leaf` is now the only reference to the `Rc<Node>` again.

 All of the logic that manages the counts and value dropping is built into `Rc<T>` and `Weak<T>` and their implementations of the `Drop` trait. By specifying that the relationship from a child to its parent should be a `Weak<T>` reference in the definition of `Node`, you’re able to have parent nodes point to child nodes and vice versa without creating a reference cycle and memory leaks.

 Summary
-------

 This chapter covered how to use smart pointers to make different guarantees and trade-offs from those Rust makes by default with regular references. The `Box<T>` type has a known size and points to data allocated on the heap. The `Rc<T>` type keeps track of the number of references to data on the heap so that data can have multiple owners. The `RefCell<T>` type with its interior mutability gives us a type that we can use when we need an immutable type but need to change an inner value of that type; it also enforces the borrowing rules at runtime instead of at compile time.

 Also discussed were the `Deref` and `Drop` traits, which enable a lot of the functionality of smart pointers. We explored reference cycles that can cause memory leaks and how to prevent them using `Weak<T>`.

 If this chapter has piqued your interest and you want to implement your own smart pointers, check out [“The Rustonomicon”](https://doc.rust-lang.org/nomicon/index.html) for more useful information.

 Next, we’ll talk about concurrency in Rust. You’ll even learn about a few new smart pointers.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch15-06-reference-cycles.html>

Fearless Concurrency
====================

 Handling concurrent programming safely and efficiently is another of Rust’s major goals. *Concurrent programming*, where different parts of a program execute independently, and *parallel programming*, where different parts of a program execute at the same time, are becoming increasingly important as more computers take advantage of their multiple processors. Historically, programming in these contexts has been difficult and error prone: Rust hopes to change that.

 Initially, the Rust team thought that ensuring memory safety and preventing concurrency problems were two separate challenges to be solved with different methods. Over time, the team discovered that the ownership and type systems are a powerful set of tools to help manage memory safety *and* concurrency problems! By leveraging ownership and type checking, many concurrency errors are compile-time errors in Rust rather than runtime errors. Therefore, rather than making you spend lots of time trying to reproduce the exact circumstances under which a runtime concurrency bug occurs, incorrect code will refuse to compile and present an error explaining the problem. As a result, you can fix your code while you’re working on it rather than potentially after it has been shipped to production. We’ve nicknamed this aspect of Rust *fearless* *concurrency*. Fearless concurrency allows you to write code that is free of subtle bugs and is easy to refactor without introducing new bugs.

 
>  Note: For simplicity’s sake, we’ll refer to many of the problems as *concurrent* rather than being more precise by saying *concurrent and/or parallel*. If this book were about concurrency and/or parallelism, we’d be more specific. For this chapter, please mentally substitute *concurrent and/or parallel* whenever we use *concurrent*.
> 
>  

 Many languages are dogmatic about the solutions they offer for handling concurrent problems. For example, Erlang has elegant functionality for message-passing concurrency but has only obscure ways to share state between threads. Supporting only a subset of possible solutions is a reasonable strategy for higher-level languages, because a higher-level language promises benefits from giving up some control to gain abstractions. However, lower-level languages are expected to provide the solution with the best performance in any given situation and have fewer abstractions over the hardware. Therefore, Rust offers a variety of tools for modeling problems in whatever way is appropriate for your situation and requirements.

 Here are the topics we’ll cover in this chapter:

 * How to create threads to run multiple pieces of code at the same time
* *Message-passing* concurrency, where channels send messages between threads
* *Shared-state* concurrency, where multiple threads have access to some piece of data
* The `Sync` and `Send` traits, which extend Rust’s concurrency guarantees to user-defined types as well as types provided by the standard library



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch16-00-concurrency.html>

Using Threads to Run Code Simultaneously
========================================

 In most current operating systems, an executed program’s code is run in a *process*, and the operating system will manage multiple processes at once. Within a program, you can also have independent parts that run simultaneously. The features that run these independent parts are called *threads*. For example, a web server could have multiple threads so that it could respond to more than one request at the same time.

 Splitting the computation in your program into multiple threads to run multiple tasks at the same time can improve performance, but it also adds complexity. Because threads can run simultaneously, there’s no inherent guarantee about the order in which parts of your code on different threads will run. This can lead to problems, such as:

 * Race conditions, where threads are accessing data or resources in an inconsistent order
* Deadlocks, where two threads are waiting for each other, preventing both threads from continuing
* Bugs that happen only in certain situations and are hard to reproduce and fix reliably

 Rust attempts to mitigate the negative effects of using threads, but programming in a multithreaded context still takes careful thought and requires a code structure that is different from that in programs running in a single thread.

 Programming languages implement threads in a few different ways, and many operating systems provide an API the language can call for creating new threads. The Rust standard library uses a *1:1* model of thread implementation, whereby a program uses one operating system thread per one language thread. There are crates that implement other models of threading that make different tradeoffs to the 1:1 model.

 ### Creating a New Thread with `spawn`

 To create a new thread, we call the `thread::spawn` function and pass it a closure (we talked about closures in Chapter 13) containing the code we want to run in the new thread. The example in Listing 16-1 prints some text from a main thread and other text from a new thread:

 Filename: src/main.rs

 
```
use std::thread;
use std::time::Duration;

fn main() {
    thread::spawn(|| {
        for i in 1..10 {
            println!("hi number {} from the spawned thread!", i);
            thread::sleep(Duration::from_millis(1));
        }
    });

    for i in 1..5 {
        println!("hi number {} from the main thread!", i);
        thread::sleep(Duration::from_millis(1));
    }
}
```
 Listing 16-1: Creating a new thread to print one thing while the main thread prints something else

 Note that when the main thread of a Rust program completes, all spawned threads are shut down, whether or not they have finished running. The output from this program might be a little different every time, but it will look similar to the following:

 
```
hi number 1 from the main thread!
hi number 1 from the spawned thread!
hi number 2 from the main thread!
hi number 2 from the spawned thread!
hi number 3 from the main thread!
hi number 3 from the spawned thread!
hi number 4 from the main thread!
hi number 4 from the spawned thread!
hi number 5 from the spawned thread!

```
 The calls to `thread::sleep` force a thread to stop its execution for a short duration, allowing a different thread to run. The threads will probably take turns, but that isn’t guaranteed: it depends on how your operating system schedules the threads. In this run, the main thread printed first, even though the print statement from the spawned thread appears first in the code. And even though we told the spawned thread to print until `i` is 9, it only got to 5 before the main thread shut down.

 If you run this code and only see output from the main thread, or don’t see any overlap, try increasing the numbers in the ranges to create more opportunities for the operating system to switch between the threads.

 ### Waiting for All Threads to Finish Using `join` Handles

 The code in Listing 16-1 not only stops the spawned thread prematurely most of the time due to the main thread ending, but because there is no guarantee on the order in which threads run, we also can’t guarantee that the spawned thread will get to run at all!

 We can fix the problem of the spawned thread not running or ending prematurely by saving the return value of `thread::spawn` in a variable. The return type of `thread::spawn` is `JoinHandle`. A `JoinHandle` is an owned value that, when we call the `join` method on it, will wait for its thread to finish. Listing 16-2 shows how to use the `JoinHandle` of the thread we created in Listing 16-1 and call `join` to make sure the spawned thread finishes before `main` exits:

 Filename: src/main.rs

 
```
use std::thread;
use std::time::Duration;

fn main() {
    let handle = thread::spawn(|| {
        for i in 1..10 {
            println!("hi number {} from the spawned thread!", i);
            thread::sleep(Duration::from_millis(1));
        }
    });

    for i in 1..5 {
        println!("hi number {} from the main thread!", i);
        thread::sleep(Duration::from_millis(1));
    }

    handle.join().unwrap();
}
```
 Listing 16-2: Saving a `JoinHandle` from `thread::spawn` to guarantee the thread is run to completion

 Calling `join` on the handle blocks the thread currently running until the thread represented by the handle terminates. *Blocking* a thread means that thread is prevented from performing work or exiting. Because we’ve put the call to `join` after the main thread’s `for` loop, running Listing 16-2 should produce output similar to this:

 
```
hi number 1 from the main thread!
hi number 2 from the main thread!
hi number 1 from the spawned thread!
hi number 3 from the main thread!
hi number 2 from the spawned thread!
hi number 4 from the main thread!
hi number 3 from the spawned thread!
hi number 4 from the spawned thread!
hi number 5 from the spawned thread!
hi number 6 from the spawned thread!
hi number 7 from the spawned thread!
hi number 8 from the spawned thread!
hi number 9 from the spawned thread!

```
 The two threads continue alternating, but the main thread waits because of the call to `handle.join()` and does not end until the spawned thread is finished.

 But let’s see what happens when we instead move `handle.join()` before the `for` loop in `main`, like this:

 Filename: src/main.rs

 
```
use std::thread;
use std::time::Duration;

fn main() {
    let handle = thread::spawn(|| {
        for i in 1..10 {
            println!("hi number {} from the spawned thread!", i);
            thread::sleep(Duration::from_millis(1));
        }
    });

    handle.join().unwrap();

    for i in 1..5 {
        println!("hi number {} from the main thread!", i);
        thread::sleep(Duration::from_millis(1));
    }
}
```
 The main thread will wait for the spawned thread to finish and then run its `for` loop, so the output won’t be interleaved anymore, as shown here:

 
```
hi number 1 from the spawned thread!
hi number 2 from the spawned thread!
hi number 3 from the spawned thread!
hi number 4 from the spawned thread!
hi number 5 from the spawned thread!
hi number 6 from the spawned thread!
hi number 7 from the spawned thread!
hi number 8 from the spawned thread!
hi number 9 from the spawned thread!
hi number 1 from the main thread!
hi number 2 from the main thread!
hi number 3 from the main thread!
hi number 4 from the main thread!

```
 Small details, such as where `join` is called, can affect whether or not your threads run at the same time.

 ### Using `move` Closures with Threads

 We'll often use the `move` keyword with closures passed to `thread::spawn` because the closure will then take ownership of the values it uses from the environment, thus transferring ownership of those values from one thread to another. In the [“Capturing References or Moving Ownership”](ch13-01-closures#capturing-references-or-moving-ownership) section of Chapter 13, we discussed `move` in the context of closures. Now, we’ll concentrate more on the interaction between `move` and `thread::spawn`.

 Notice in Listing 16-1 that the closure we pass to `thread::spawn` takes no arguments: we’re not using any data from the main thread in the spawned thread’s code. To use data from the main thread in the spawned thread, the spawned thread’s closure must capture the values it needs. Listing 16-3 shows an attempt to create a vector in the main thread and use it in the spawned thread. However, this won’t yet work, as you’ll see in a moment.

 Filename: src/main.rs

 
```
use std::thread;

fn main() {
    let v = vec![1, 2, 3];

    let handle = thread::spawn(|| {
        println!("Here's a vector: {:?}", v);
    });

    handle.join().unwrap();
}
```
 Listing 16-3: Attempting to use a vector created by the main thread in another thread

 The closure uses `v`, so it will capture `v` and make it part of the closure’s environment. Because `thread::spawn` runs this closure in a new thread, we should be able to access `v` inside that new thread. But when we compile this example, we get the following error:

 
```
$ cargo run
   Compiling threads v0.1.0 (file:///projects/threads)
error[E0373]: closure may outlive the current function, but it borrows `v`, which is owned by the current function
 --> src/main.rs:6:32
  |
6 |     let handle = thread::spawn(|| {
  |                                ^^ may outlive borrowed value `v`
7 |         println!("Here's a vector: {:?}", v);
  |                                           - `v` is borrowed here
  |
note: function requires argument type to outlive `'static`
 --> src/main.rs:6:18
  |
6 |       let handle = thread::spawn(|| {
  |  __________________^
7 | |         println!("Here's a vector: {:?}", v);
8 | |     });
  | |______^
help: to force the closure to take ownership of `v` (and any other referenced variables), use the `move` keyword
  |
6 |     let handle = thread::spawn(move || {
  |                                ++++

For more information about this error, try `rustc --explain E0373`.
error: could not compile `threads` due to previous error

```
 Rust *infers* how to capture `v`, and because `println!` only needs a reference to `v`, the closure tries to borrow `v`. However, there’s a problem: Rust can’t tell how long the spawned thread will run, so it doesn’t know if the reference to `v` will always be valid.

 Listing 16-4 provides a scenario that’s more likely to have a reference to `v` that won’t be valid:

 Filename: src/main.rs

 
```
use std::thread;

fn main() {
    let v = vec![1, 2, 3];

    let handle = thread::spawn(|| {
        println!("Here's a vector: {:?}", v);
    });

    drop(v); // oh no!

    handle.join().unwrap();
}
```
 Listing 16-4: A thread with a closure that attempts to capture a reference to `v` from a main thread that drops `v`

 If Rust allowed us to run this code, there’s a possibility the spawned thread would be immediately put in the background without running at all. The spawned thread has a reference to `v` inside, but the main thread immediately drops `v`, using the `drop` function we discussed in Chapter 15. Then, when the spawned thread starts to execute, `v` is no longer valid, so a reference to it is also invalid. Oh no!

 To fix the compiler error in Listing 16-3, we can use the error message’s advice:

 
```
help: to force the closure to take ownership of `v` (and any other referenced variables), use the `move` keyword
  |
6 |     let handle = thread::spawn(move || {
  |                                ++++

```
 By adding the `move` keyword before the closure, we force the closure to take ownership of the values it’s using rather than allowing Rust to infer that it should borrow the values. The modification to Listing 16-3 shown in Listing 16-5 will compile and run as we intend:

 Filename: src/main.rs

 
```
use std::thread;

fn main() {
    let v = vec![1, 2, 3];

    let handle = thread::spawn(move || {
        println!("Here's a vector: {:?}", v);
    });

    handle.join().unwrap();
}
```
 Listing 16-5: Using the `move` keyword to force a closure to take ownership of the values it uses

 We might be tempted to try the same thing to fix the code in Listing 16-4 where the main thread called `drop` by using a `move` closure. However, this fix will not work because what Listing 16-4 is trying to do is disallowed for a different reason. If we added `move` to the closure, we would move `v` into the closure’s environment, and we could no longer call `drop` on it in the main thread. We would get this compiler error instead:

 
```
$ cargo run
   Compiling threads v0.1.0 (file:///projects/threads)
error[E0382]: use of moved value: `v`
  --> src/main.rs:10:10
   |
4  |     let v = vec![1, 2, 3];
   |         - move occurs because `v` has type `Vec<i32>`, which does not implement the `Copy` trait
5  |
6  |     let handle = thread::spawn(move || {
   |                                ------- value moved into closure here
7  |         println!("Here's a vector: {:?}", v);
   |                                           - variable moved due to use in closure
...
10 |     drop(v); // oh no!
   |          ^ value used here after move

For more information about this error, try `rustc --explain E0382`.
error: could not compile `threads` due to previous error

```
 Rust’s ownership rules have saved us again! We got an error from the code in Listing 16-3 because Rust was being conservative and only borrowing `v` for the thread, which meant the main thread could theoretically invalidate the spawned thread’s reference. By telling Rust to move ownership of `v` to the spawned thread, we’re guaranteeing Rust that the main thread won’t use `v` anymore. If we change Listing 16-4 in the same way, we’re then violating the ownership rules when we try to use `v` in the main thread. The `move` keyword overrides Rust’s conservative default of borrowing; it doesn’t let us violate the ownership rules.

 With a basic understanding of threads and the thread API, let’s look at what we can *do* with threads.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch16-01-threads.html>

Using Message Passing to Transfer Data Between Threads
======================================================

 One increasingly popular approach to ensuring safe concurrency is *message passing*, where threads or actors communicate by sending each other messages containing data. Here’s the idea in a slogan from [the Go language documentation](https://golang.org/doc/effective_go.html#concurrency): “Do not communicate by sharing memory; instead, share memory by communicating.”

 To accomplish message-sending concurrency, Rust's standard library provides an implementation of *channels*. A channel is a general programming concept by which data is sent from one thread to another.

 You can imagine a channel in programming as being like a directional channel of water, such as a stream or a river. If you put something like a rubber duck into a river, it will travel downstream to the end of the waterway.

 A channel has two halves: a transmitter and a receiver. The transmitter half is the upstream location where you put rubber ducks into the river, and the receiver half is where the rubber duck ends up downstream. One part of your code calls methods on the transmitter with the data you want to send, and another part checks the receiving end for arriving messages. A channel is said to be *closed* if either the transmitter or receiver half is dropped.

 Here, we’ll work up to a program that has one thread to generate values and send them down a channel, and another thread that will receive the values and print them out. We’ll be sending simple values between threads using a channel to illustrate the feature. Once you’re familiar with the technique, you could use channels for any threads that need to communicate between each other, such as a chat system or a system where many threads perform parts of a calculation and send the parts to one thread that aggregates the results.

 First, in Listing 16-6, we’ll create a channel but not do anything with it. Note that this won’t compile yet because Rust can’t tell what type of values we want to send over the channel.

 Filename: src/main.rs

 
```
use std::sync::mpsc;

fn main() {
    let (tx, rx) = mpsc::channel();
}
```
 Listing 16-6: Creating a channel and assigning the two halves to `tx` and `rx`

 We create a new channel using the `mpsc::channel` function; `mpsc` stands for *multiple producer, single consumer*. In short, the way Rust’s standard library implements channels means a channel can have multiple *sending* ends that produce values but only one *receiving* end that consumes those values. Imagine multiple streams flowing together into one big river: everything sent down any of the streams will end up in one river at the end. We’ll start with a single producer for now, but we’ll add multiple producers when we get this example working.

 The `mpsc::channel` function returns a tuple, the first element of which is the sending end--the transmitter--and the second element is the receiving end--the receiver. The abbreviations `tx` and `rx` are traditionally used in many fields for *transmitter* and *receiver* respectively, so we name our variables as such to indicate each end. We’re using a `let` statement with a pattern that destructures the tuples; we’ll discuss the use of patterns in `let` statements and destructuring in Chapter 18. For now, know that using a `let` statement this way is a convenient approach to extract the pieces of the tuple returned by `mpsc::channel`.

 Let’s move the transmitting end into a spawned thread and have it send one string so the spawned thread is communicating with the main thread, as shown in Listing 16-7. This is like putting a rubber duck in the river upstream or sending a chat message from one thread to another.

 Filename: src/main.rs

 
```
use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let val = String::from("hi");
        tx.send(val).unwrap();
    });
}
```
 Listing 16-7: Moving `tx` to a spawned thread and sending “hi”

 Again, we’re using `thread::spawn` to create a new thread and then using `move` to move `tx` into the closure so the spawned thread owns `tx`. The spawned thread needs to own the transmitter to be able to send messages through the channel. The transmitter has a `send` method that takes the value we want to send. The `send` method returns a `Result<T, E>` type, so if the receiver has already been dropped and there’s nowhere to send a value, the send operation will return an error. In this example, we’re calling `unwrap` to panic in case of an error. But in a real application, we would handle it properly: return to Chapter 9 to review strategies for proper error handling.

 In Listing 16-8, we’ll get the value from the receiver in the main thread. This is like retrieving the rubber duck from the water at the end of the river or receiving a chat message.

 Filename: src/main.rs

 
```
use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let val = String::from("hi");
        tx.send(val).unwrap();
    });

    let received = rx.recv().unwrap();
    println!("Got: {}", received);
}
```
 Listing 16-8: Receiving the value “hi” in the main thread and printing it

 The receiver has two useful methods: `recv` and `try_recv`. We’re using `recv`, short for *receive*, which will block the main thread’s execution and wait until a value is sent down the channel. Once a value is sent, `recv` will return it in a `Result<T, E>`. When the transmitter closes, `recv` will return an error to signal that no more values will be coming.

 The `try_recv` method doesn’t block, but will instead return a `Result<T, E>` immediately: an `Ok` value holding a message if one is available and an `Err` value if there aren’t any messages this time. Using `try_recv` is useful if this thread has other work to do while waiting for messages: we could write a loop that calls `try_recv` every so often, handles a message if one is available, and otherwise does other work for a little while until checking again.

 We’ve used `recv` in this example for simplicity; we don’t have any other work for the main thread to do other than wait for messages, so blocking the main thread is appropriate.

 When we run the code in Listing 16-8, we’ll see the value printed from the main thread:

 
```
Got: hi

```
 Perfect!

 ### Channels and Ownership Transference

 The ownership rules play a vital role in message sending because they help you write safe, concurrent code. Preventing errors in concurrent programming is the advantage of thinking about ownership throughout your Rust programs. Let’s do an experiment to show how channels and ownership work together to prevent problems: we’ll try to use a `val` value in the spawned thread *after* we’ve sent it down the channel. Try compiling the code in Listing 16-9 to see why this code isn’t allowed:

 Filename: src/main.rs

 
```
use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let val = String::from("hi");
        tx.send(val).unwrap();
        println!("val is {}", val);
    });

    let received = rx.recv().unwrap();
    println!("Got: {}", received);
}
```
 Listing 16-9: Attempting to use `val` after we’ve sent it down the channel

 Here, we try to print `val` after we’ve sent it down the channel via `tx.send`. Allowing this would be a bad idea: once the value has been sent to another thread, that thread could modify or drop it before we try to use the value again. Potentially, the other thread’s modifications could cause errors or unexpected results due to inconsistent or nonexistent data. However, Rust gives us an error if we try to compile the code in Listing 16-9:

 
```
$ cargo run
   Compiling message-passing v0.1.0 (file:///projects/message-passing)
error[E0382]: borrow of moved value: `val`
  --> src/main.rs:10:31
   |
8  |         let val = String::from("hi");
   |             --- move occurs because `val` has type `String`, which does not implement the `Copy` trait
9  |         tx.send(val).unwrap();
   |                 --- value moved here
10 |         println!("val is {}", val);
   |                               ^^^ value borrowed here after move
   |
   = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)

For more information about this error, try `rustc --explain E0382`.
error: could not compile `message-passing` due to previous error

```
 Our concurrency mistake has caused a compile time error. The `send` function takes ownership of its parameter, and when the value is moved, the receiver takes ownership of it. This stops us from accidentally using the value again after sending it; the ownership system checks that everything is okay.

 ### Sending Multiple Values and Seeing the Receiver Waiting

 The code in Listing 16-8 compiled and ran, but it didn’t clearly show us that two separate threads were talking to each other over the channel. In Listing 16-10 we’ve made some modifications that will prove the code in Listing 16-8 is running concurrently: the spawned thread will now send multiple messages and pause for a second between each message.

 Filename: src/main.rs

 
```
use std::sync::mpsc;
use std::thread;
use std::time::Duration;

fn main() {
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let vals = vec![
            String::from("hi"),
            String::from("from"),
            String::from("the"),
            String::from("thread"),
        ];

        for val in vals {
            tx.send(val).unwrap();
            thread::sleep(Duration::from_secs(1));
        }
    });

    for received in rx {
        println!("Got: {}", received);
    }
}
```
 Listing 16-10: Sending multiple messages and pausing between each

 This time, the spawned thread has a vector of strings that we want to send to the main thread. We iterate over them, sending each individually, and pause between each by calling the `thread::sleep` function with a `Duration` value of 1 second.

 In the main thread, we’re not calling the `recv` function explicitly anymore: instead, we’re treating `rx` as an iterator. For each value received, we’re printing it. When the channel is closed, iteration will end.

 When running the code in Listing 16-10, you should see the following output with a 1-second pause in between each line:

 
```
Got: hi
Got: from
Got: the
Got: thread

```
 Because we don’t have any code that pauses or delays in the `for` loop in the main thread, we can tell that the main thread is waiting to receive values from the spawned thread.

 ### Creating Multiple Producers by Cloning the Transmitter

 Earlier we mentioned that `mpsc` was an acronym for *multiple producer, single consumer*. Let’s put `mpsc` to use and expand the code in Listing 16-10 to create multiple threads that all send values to the same receiver. We can do so by cloning the transmitter, as shown in Listing 16-11:

 Filename: src/main.rs

 
```
use std::sync::mpsc;
use std::thread;
use std::time::Duration;

fn main() {
    // --snip--

    let (tx, rx) = mpsc::channel();

    let tx1 = tx.clone();
    thread::spawn(move || {
        let vals = vec![
            String::from("hi"),
            String::from("from"),
            String::from("the"),
            String::from("thread"),
        ];

        for val in vals {
            tx1.send(val).unwrap();
            thread::sleep(Duration::from_secs(1));
        }
    });

    thread::spawn(move || {
        let vals = vec![
            String::from("more"),
            String::from("messages"),
            String::from("for"),
            String::from("you"),
        ];

        for val in vals {
            tx.send(val).unwrap();
            thread::sleep(Duration::from_secs(1));
        }
    });

    for received in rx {
        println!("Got: {}", received);
    }

    // --snip--
}
```
 Listing 16-11: Sending multiple messages from multiple producers

 This time, before we create the first spawned thread, we call `clone` on the transmitter. This will give us a new transmitter we can pass to the first spawned thread. We pass the original transmitter to a second spawned thread. This gives us two threads, each sending different messages to the one receiver.

 When you run the code, your output should look something like this:

 
```
Got: hi
Got: more
Got: from
Got: messages
Got: for
Got: the
Got: thread
Got: you

```
 You might see the values in another order, depending on your system. This is what makes concurrency interesting as well as difficult. If you experiment with `thread::sleep`, giving it various values in the different threads, each run will be more nondeterministic and create different output each time.

 Now that we’ve looked at how channels work, let’s look at a different method of concurrency.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch16-02-message-passing.html>

Shared-State Concurrency
========================

 Message passing is a fine way of handling concurrency, but it’s not the only one. Another method would be for multiple threads to access the same shared data. Consider this part of the slogan from the Go language documentation again: “do not communicate by sharing memory.”

 What would communicating by sharing memory look like? In addition, why would message-passing enthusiasts caution not to use memory sharing?

 In a way, channels in any programming language are similar to single ownership, because once you transfer a value down a channel, you should no longer use that value. Shared memory concurrency is like multiple ownership: multiple threads can access the same memory location at the same time. As you saw in Chapter 15, where smart pointers made multiple ownership possible, multiple ownership can add complexity because these different owners need managing. Rust’s type system and ownership rules greatly assist in getting this management correct. For an example, let’s look at mutexes, one of the more common concurrency primitives for shared memory.

 ### Using Mutexes to Allow Access to Data from One Thread at a Time

 *Mutex* is an abbreviation for *mutual exclusion*, as in, a mutex allows only one thread to access some data at any given time. To access the data in a mutex, a thread must first signal that it wants access by asking to acquire the mutex’s *lock*. The lock is a data structure that is part of the mutex that keeps track of who currently has exclusive access to the data. Therefore, the mutex is described as *guarding* the data it holds via the locking system.

 Mutexes have a reputation for being difficult to use because you have to remember two rules:

 * You must attempt to acquire the lock before using the data.
* When you’re done with the data that the mutex guards, you must unlock the data so other threads can acquire the lock.

 For a real-world metaphor for a mutex, imagine a panel discussion at a conference with only one microphone. Before a panelist can speak, they have to ask or signal that they want to use the microphone. When they get the microphone, they can talk for as long as they want to and then hand the microphone to the next panelist who requests to speak. If a panelist forgets to hand the microphone off when they’re finished with it, no one else is able to speak. If management of the shared microphone goes wrong, the panel won’t work as planned!

 Management of mutexes can be incredibly tricky to get right, which is why so many people are enthusiastic about channels. However, thanks to Rust’s type system and ownership rules, you can’t get locking and unlocking wrong.

 #### The API of `Mutex<T>`

 As an example of how to use a mutex, let’s start by using a mutex in a single-threaded context, as shown in Listing 16-12:

 Filename: src/main.rs

 
```
use std::sync::Mutex;

fn main() {
    let m = Mutex::new(5);

    {
        let mut num = m.lock().unwrap();
        *num = 6;
    }

    println!("m = {:?}", m);
}
```
 Listing 16-12: Exploring the API of `Mutex<T>` in a single-threaded context for simplicity

 As with many types, we create a `Mutex<T>` using the associated function `new`. To access the data inside the mutex, we use the `lock` method to acquire the lock. This call will block the current thread so it can’t do any work until it’s our turn to have the lock.

 The call to `lock` would fail if another thread holding the lock panicked. In that case, no one would ever be able to get the lock, so we’ve chosen to `unwrap` and have this thread panic if we’re in that situation.

 After we’ve acquired the lock, we can treat the return value, named `num` in this case, as a mutable reference to the data inside. The type system ensures that we acquire a lock before using the value in `m`. The type of `m` is `Mutex<i32>`, not `i32`, so we *must* call `lock` to be able to use the `i32` value. We can’t forget; the type system won’t let us access the inner `i32` otherwise.

 As you might suspect, `Mutex<T>` is a smart pointer. More accurately, the call to `lock` *returns* a smart pointer called `MutexGuard`, wrapped in a `LockResult` that we handled with the call to `unwrap`. The `MutexGuard` smart pointer implements `Deref` to point at our inner data; the smart pointer also has a `Drop` implementation that releases the lock automatically when a `MutexGuard` goes out of scope, which happens at the end of the inner scope. As a result, we don’t risk forgetting to release the lock and blocking the mutex from being used by other threads, because the lock release happens automatically.

 After dropping the lock, we can print the mutex value and see that we were able to change the inner `i32` to 6.

 #### Sharing a `Mutex<T>` Between Multiple Threads

 Now, let’s try to share a value between multiple threads using `Mutex<T>`. We’ll spin up 10 threads and have them each increment a counter value by 1, so the counter goes from 0 to 10. The next example in Listing 16-13 will have a compiler error, and we’ll use that error to learn more about using `Mutex<T>` and how Rust helps us use it correctly.

 Filename: src/main.rs

 
```
use std::sync::Mutex;
use std::thread;

fn main() {
    let counter = Mutex::new(0);
    let mut handles = vec![];

    for _ in 0..10 {
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();

            *num += 1;
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("Result: {}", *counter.lock().unwrap());
}
```
 Listing 16-13: Ten threads each increment a counter guarded by a `Mutex<T>`

 We create a `counter` variable to hold an `i32` inside a `Mutex<T>`, as we did in Listing 16-12. Next, we create 10 threads by iterating over a range of numbers. We use `thread::spawn` and give all the threads the same closure: one that moves the counter into the thread, acquires a lock on the `Mutex<T>` by calling the `lock` method, and then adds 1 to the value in the mutex. When a thread finishes running its closure, `num` will go out of scope and release the lock so another thread can acquire it.

 In the main thread, we collect all the join handles. Then, as we did in Listing 16-2, we call `join` on each handle to make sure all the threads finish. At that point, the main thread will acquire the lock and print the result of this program.

 We hinted that this example wouldn’t compile. Now let’s find out why!

 
```
$ cargo run
   Compiling shared-state v0.1.0 (file:///projects/shared-state)
error[E0382]: use of moved value: `counter`
  --> src/main.rs:9:36
   |
5  |     let counter = Mutex::new(0);
   |         ------- move occurs because `counter` has type `Mutex<i32>`, which does not implement the `Copy` trait
...
9  |         let handle = thread::spawn(move || {
   |                                    ^^^^^^^ value moved into closure here, in previous iteration of loop
10 |             let mut num = counter.lock().unwrap();
   |                           ------- use occurs due to use in closure

For more information about this error, try `rustc --explain E0382`.
error: could not compile `shared-state` due to previous error

```
 The error message states that the `counter` value was moved in the previous iteration of the loop. Rust is telling us that we can’t move the ownership of lock `counter` into multiple threads. Let’s fix the compiler error with a multiple-ownership method we discussed in Chapter 15.

 #### Multiple Ownership with Multiple Threads

 In Chapter 15, we gave a value multiple owners by using the smart pointer `Rc<T>` to create a reference counted value. Let’s do the same here and see what happens. We’ll wrap the `Mutex<T>` in `Rc<T>` in Listing 16-14 and clone the `Rc<T>` before moving ownership to the thread.

 Filename: src/main.rs

 
```
use std::rc::Rc;
use std::sync::Mutex;
use std::thread;

fn main() {
    let counter = Rc::new(Mutex::new(0));
    let mut handles = vec![];

    for _ in 0..10 {
        let counter = Rc::clone(&counter);
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();

            *num += 1;
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("Result: {}", *counter.lock().unwrap());
}
```
 Listing 16-14: Attempting to use `Rc<T>` to allow multiple threads to own the `Mutex<T>`

 Once again, we compile and get... different errors! The compiler is teaching us a lot.

 
```
$ cargo run
   Compiling shared-state v0.1.0 (file:///projects/shared-state)
error[E0277]: `Rc<Mutex<i32>>` cannot be sent between threads safely
  --> src/main.rs:11:36
   |
11 |           let handle = thread::spawn(move || {
   |                        ------------- ^------
   |                        |             |
   |  ______________________|_____________within this `[closure@src/main.rs:11:36: 11:43]`
   | |                      |
   | |                      required by a bound introduced by this call
12 | |             let mut num = counter.lock().unwrap();
13 | |
14 | |             *num += 1;
15 | |         });
   | |_________^ `Rc<Mutex<i32>>` cannot be sent between threads safely
   |
   = help: within `[closure@src/main.rs:11:36: 11:43]`, the trait `Send` is not implemented for `Rc<Mutex<i32>>`
note: required because it's used within this closure
  --> src/main.rs:11:36
   |
11 |         let handle = thread::spawn(move || {
   |                                    ^^^^^^^
note: required by a bound in `spawn`
  --> /rustc/d5a82bbd26e1ad8b7401f6a718a9c57c96905483/library/std/src/thread/mod.rs:704:8
   |
   = note: required by this bound in `spawn`

For more information about this error, try `rustc --explain E0277`.
error: could not compile `shared-state` due to previous error

```
 Wow, that error message is very wordy! Here’s the important part to focus on: ``Rc<Mutex<i32>>` cannot be sent between threads safely`. The compiler is also telling us the reason why: `the trait `Send` is not implemented for `Rc<Mutex<i32>>`` . We’ll talk about `Send` in the next section: it’s one of the traits that ensures the types we use with threads are meant for use in concurrent situations.

 Unfortunately, `Rc<T>` is not safe to share across threads. When `Rc<T>` manages the reference count, it adds to the count for each call to `clone` and subtracts from the count when each clone is dropped. But it doesn’t use any concurrency primitives to make sure that changes to the count can’t be interrupted by another thread. This could lead to wrong counts—subtle bugs that could in turn lead to memory leaks or a value being dropped before we’re done with it. What we need is a type exactly like `Rc<T>` but one that makes changes to the reference count in a thread-safe way.

 #### Atomic Reference Counting with `Arc<T>`

 Fortunately, `Arc<T>` *is* a type like `Rc<T>` that is safe to use in concurrent situations. The *a* stands for *atomic*, meaning it’s an *atomically reference counted* type. Atomics are an additional kind of concurrency primitive that we won’t cover in detail here: see the standard library documentation for [`std::sync::atomic`](../std/sync/atomic/index) for more details. At this point, you just need to know that atomics work like primitive types but are safe to share across threads.

 You might then wonder why all primitive types aren’t atomic and why standard library types aren’t implemented to use `Arc<T>` by default. The reason is that thread safety comes with a performance penalty that you only want to pay when you really need to. If you’re just performing operations on values within a single thread, your code can run faster if it doesn’t have to enforce the guarantees atomics provide.

 Let’s return to our example: `Arc<T>` and `Rc<T>` have the same API, so we fix our program by changing the `use` line, the call to `new`, and the call to `clone`. The code in Listing 16-15 will finally compile and run:

 Filename: src/main.rs

 
```
use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];

    for _ in 0..10 {
        let counter = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();

            *num += 1;
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("Result: {}", *counter.lock().unwrap());
}
```
 Listing 16-15: Using an `Arc<T>` to wrap the `Mutex<T>` to be able to share ownership across multiple threads

 This code will print the following:

 
```
Result: 10

```
 We did it! We counted from 0 to 10, which may not seem very impressive, but it did teach us a lot about `Mutex<T>` and thread safety. You could also use this program’s structure to do more complicated operations than just incrementing a counter. Using this strategy, you can divide a calculation into independent parts, split those parts across threads, and then use a `Mutex<T>` to have each thread update the final result with its part.

 Note that if you are doing simple numerical operations, there are types simpler than `Mutex<T>` types provided by the [`std::sync::atomic` module of the standard library](../std/sync/atomic/index). These types provide safe, concurrent, atomic access to primitive types. We chose to use `Mutex<T>` with a primitive type for this example so we could concentrate on how `Mutex<T>` works.

 ### Similarities Between `RefCell<T>`/`Rc<T>` and `Mutex<T>`/`Arc<T>`

 You might have noticed that `counter` is immutable but we could get a mutable reference to the value inside it; this means `Mutex<T>` provides interior mutability, as the `Cell` family does. In the same way we used `RefCell<T>` in Chapter 15 to allow us to mutate contents inside an `Rc<T>`, we use `Mutex<T>` to mutate contents inside an `Arc<T>`.

 Another detail to note is that Rust can’t protect you from all kinds of logic errors when you use `Mutex<T>`. Recall in Chapter 15 that using `Rc<T>` came with the risk of creating reference cycles, where two `Rc<T>` values refer to each other, causing memory leaks. Similarly, `Mutex<T>` comes with the risk of creating *deadlocks*. These occur when an operation needs to lock two resources and two threads have each acquired one of the locks, causing them to wait for each other forever. If you’re interested in deadlocks, try creating a Rust program that has a deadlock; then research deadlock mitigation strategies for mutexes in any language and have a go at implementing them in Rust. The standard library API documentation for `Mutex<T>` and `MutexGuard` offers useful information.

 We’ll round out this chapter by talking about the `Send` and `Sync` traits and how we can use them with custom types.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch16-03-shared-state.html>

Extensible Concurrency with the `Sync` and `Send` Traits
========================================================

 Interestingly, the Rust language has *very* few concurrency features. Almost every concurrency feature we’ve talked about so far in this chapter has been part of the standard library, not the language. Your options for handling concurrency are not limited to the language or the standard library; you can write your own concurrency features or use those written by others.

 However, two concurrency concepts are embedded in the language: the `std::marker` traits `Sync` and `Send`.

 ### Allowing Transference of Ownership Between Threads with `Send`

 The `Send` marker trait indicates that ownership of values of the type implementing `Send` can be transferred between threads. Almost every Rust type is `Send`, but there are some exceptions, including `Rc<T>`: this cannot be `Send` because if you cloned an `Rc<T>` value and tried to transfer ownership of the clone to another thread, both threads might update the reference count at the same time. For this reason, `Rc<T>` is implemented for use in single-threaded situations where you don’t want to pay the thread-safe performance penalty.

 Therefore, Rust’s type system and trait bounds ensure that you can never accidentally send an `Rc<T>` value across threads unsafely. When we tried to do this in Listing 16-14, we got the error `the trait Send is not implemented for Rc<Mutex<i32>>`. When we switched to `Arc<T>`, which is `Send`, the code compiled.

 Any type composed entirely of `Send` types is automatically marked as `Send` as well. Almost all primitive types are `Send`, aside from raw pointers, which we’ll discuss in Chapter 19.

 ### Allowing Access from Multiple Threads with `Sync`

 The `Sync` marker trait indicates that it is safe for the type implementing `Sync` to be referenced from multiple threads. In other words, any type `T` is `Sync` if `&T` (an immutable reference to `T`) is `Send`, meaning the reference can be sent safely to another thread. Similar to `Send`, primitive types are `Sync`, and types composed entirely of types that are `Sync` are also `Sync`.

 The smart pointer `Rc<T>` is also not `Sync` for the same reasons that it’s not `Send`. The `RefCell<T>` type (which we talked about in Chapter 15) and the family of related `Cell<T>` types are not `Sync`. The implementation of borrow checking that `RefCell<T>` does at runtime is not thread-safe. The smart pointer `Mutex<T>` is `Sync` and can be used to share access with multiple threads as you saw in the [“Sharing a `Mutex<T>` Between Multiple Threads”](ch16-03-shared-state#sharing-a-mutext-between-multiple-threads) section.

 ### Implementing `Send` and `Sync` Manually Is Unsafe

 Because types that are made up of `Send` and `Sync` traits are automatically also `Send` and `Sync`, we don’t have to implement those traits manually. As marker traits, they don’t even have any methods to implement. They’re just useful for enforcing invariants related to concurrency.

 Manually implementing these traits involves implementing unsafe Rust code. We’ll talk about using unsafe Rust code in Chapter 19; for now, the important information is that building new concurrent types not made up of `Send` and `Sync` parts requires careful thought to uphold the safety guarantees. [“The Rustonomicon”](https://doc.rust-lang.org/nomicon/index.html) has more information about these guarantees and how to uphold them.

 Summary
-------

 This isn’t the last you’ll see of concurrency in this book: the project in Chapter 20 will use the concepts in this chapter in a more realistic situation than the smaller examples discussed here.

 As mentioned earlier, because very little of how Rust handles concurrency is part of the language, many concurrency solutions are implemented as crates. These evolve more quickly than the standard library, so be sure to search online for the current, state-of-the-art crates to use in multithreaded situations.

 The Rust standard library provides channels for message passing and smart pointer types, such as `Mutex<T>` and `Arc<T>`, that are safe to use in concurrent contexts. The type system and the borrow checker ensure that the code using these solutions won’t end up with data races or invalid references. Once you get your code to compile, you can rest assured that it will happily run on multiple threads without the kinds of hard-to-track-down bugs common in other languages. Concurrent programming is no longer a concept to be afraid of: go forth and make your programs concurrent, fearlessly!

 Next, we’ll talk about idiomatic ways to model problems and structure solutions as your Rust programs get bigger. In addition, we’ll discuss how Rust’s idioms relate to those you might be familiar with from object-oriented programming.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch16-04-extensible-concurrency-sync-and-send.html>

Object-Oriented Programming Features of Rust
============================================

 Object-oriented programming (OOP) is a way of modeling programs. Objects as a programmatic concept were introduced in the programming language Simula in the 1960s. Those objects influenced Alan Kay’s programming architecture in which objects pass messages to each other. To describe this architecture, he coined the term *object-oriented programming* in 1967. Many competing definitions describe what OOP is, and by some of these definitions Rust is object-oriented, but by others it is not. In this chapter, we’ll explore certain characteristics that are commonly considered object-oriented and how those characteristics translate to idiomatic Rust. We’ll then show you how to implement an object-oriented design pattern in Rust and discuss the trade-offs of doing so versus implementing a solution using some of Rust’s strengths instead.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch17-00-oop.html>

Characteristics of Object-Oriented Languages
============================================

 There is no consensus in the programming community about what features a language must have to be considered object-oriented. Rust is influenced by many programming paradigms, including OOP; for example, we explored the features that came from functional programming in Chapter 13. Arguably, OOP languages share certain common characteristics, namely objects, encapsulation, and inheritance. Let’s look at what each of those characteristics means and whether Rust supports it.

 ### Objects Contain Data and Behavior

 The book *Design Patterns: Elements of Reusable Object-Oriented Software* by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (Addison-Wesley Professional, 1994), colloquially referred to as *The Gang of Four* book, is a catalog of object-oriented design patterns. It defines OOP this way:

 
>  Object-oriented programs are made up of objects. An *object* packages both data and the procedures that operate on that data. The procedures are typically called *methods* or *operations*.
> 
>  

 Using this definition, Rust is object-oriented: structs and enums have data, and `impl` blocks provide methods on structs and enums. Even though structs and enums with methods aren’t *called* objects, they provide the same functionality, according to the Gang of Four’s definition of objects.

 ### Encapsulation that Hides Implementation Details

 Another aspect commonly associated with OOP is the idea of *encapsulation*, which means that the implementation details of an object aren’t accessible to code using that object. Therefore, the only way to interact with an object is through its public API; code using the object shouldn’t be able to reach into the object’s internals and change data or behavior directly. This enables the programmer to change and refactor an object’s internals without needing to change the code that uses the object.

 We discussed how to control encapsulation in Chapter 7: we can use the `pub` keyword to decide which modules, types, functions, and methods in our code should be public, and by default everything else is private. For example, we can define a struct `AveragedCollection` that has a field containing a vector of `i32` values. The struct can also have a field that contains the average of the values in the vector, meaning the average doesn’t have to be computed on demand whenever anyone needs it. In other words, `AveragedCollection` will cache the calculated average for us. Listing 17-1 has the definition of the `AveragedCollection` struct:

 Filename: src/lib.rs

 
```
pub struct AveragedCollection {
    list: Vec<i32>,
    average: f64,
}
```
 Listing 17-1: An `AveragedCollection` struct that maintains a list of integers and the average of the items in the collection

 The struct is marked `pub` so that other code can use it, but the fields within the struct remain private. This is important in this case because we want to ensure that whenever a value is added or removed from the list, the average is also updated. We do this by implementing `add`, `remove`, and `average` methods on the struct, as shown in Listing 17-2:

 Filename: src/lib.rs

 
```
pub struct AveragedCollection {
    list: Vec<i32>,
    average: f64,
}

impl AveragedCollection {
    pub fn add(&mut self, value: i32) {
        self.list.push(value);
        self.update_average();
    }

    pub fn remove(&mut self) -> Option<i32> {
        let result = self.list.pop();
        match result {
            Some(value) => {
                self.update_average();
                Some(value)
            }
            None => None,
        }
    }

    pub fn average(&self) -> f64 {
        self.average
    }

    fn update_average(&mut self) {
        let total: i32 = self.list.iter().sum();
        self.average = total as f64 / self.list.len() as f64;
    }
}
```
 Listing 17-2: Implementations of the public methods `add`, `remove`, and `average` on `AveragedCollection`

 The public methods `add`, `remove`, and `average` are the only ways to access or modify data in an instance of `AveragedCollection`. When an item is added to `list` using the `add` method or removed using the `remove` method, the implementations of each call the private `update_average` method that handles updating the `average` field as well.

 We leave the `list` and `average` fields private so there is no way for external code to add or remove items to or from the `list` field directly; otherwise, the `average` field might become out of sync when the `list` changes. The `average` method returns the value in the `average` field, allowing external code to read the `average` but not modify it.

 Because we’ve encapsulated the implementation details of the struct `AveragedCollection`, we can easily change aspects, such as the data structure, in the future. For instance, we could use a `HashSet<i32>` instead of a `Vec<i32>` for the `list` field. As long as the signatures of the `add`, `remove`, and `average` public methods stay the same, code using `AveragedCollection` wouldn’t need to change. If we made `list` public instead, this wouldn’t necessarily be the case: `HashSet<i32>` and `Vec<i32>` have different methods for adding and removing items, so the external code would likely have to change if it were modifying `list` directly.

 If encapsulation is a required aspect for a language to be considered object-oriented, then Rust meets that requirement. The option to use `pub` or not for different parts of code enables encapsulation of implementation details.

 ### Inheritance as a Type System and as Code Sharing

 *Inheritance* is a mechanism whereby an object can inherit elements from another object’s definition, thus gaining the parent object’s data and behavior without you having to define them again.

 If a language must have inheritance to be an object-oriented language, then Rust is not one. There is no way to define a struct that inherits the parent struct’s fields and method implementations without using a macro.

 However, if you’re used to having inheritance in your programming toolbox, you can use other solutions in Rust, depending on your reason for reaching for inheritance in the first place.

 You would choose inheritance for two main reasons. One is for reuse of code: you can implement particular behavior for one type, and inheritance enables you to reuse that implementation for a different type. You can do this in a limited way in Rust code using default trait method implementations, which you saw in Listing 10-14 when we added a default implementation of the `summarize` method on the `Summary` trait. Any type implementing the `Summary` trait would have the `summarize` method available on it without any further code. This is similar to a parent class having an implementation of a method and an inheriting child class also having the implementation of the method. We can also override the default implementation of the `summarize` method when we implement the `Summary` trait, which is similar to a child class overriding the implementation of a method inherited from a parent class.

 The other reason to use inheritance relates to the type system: to enable a child type to be used in the same places as the parent type. This is also called *polymorphism*, which means that you can substitute multiple objects for each other at runtime if they share certain characteristics.

 
>  ### Polymorphism
> 
>  To many people, polymorphism is synonymous with inheritance. But it’s actually a more general concept that refers to code that can work with data of multiple types. For inheritance, those types are generally subclasses.
> 
>  Rust instead uses generics to abstract over different possible types and trait bounds to impose constraints on what those types must provide. This is sometimes called *bounded parametric polymorphism*.
> 
>  

 Inheritance has recently fallen out of favor as a programming design solution in many programming languages because it’s often at risk of sharing more code than necessary. Subclasses shouldn’t always share all characteristics of their parent class but will do so with inheritance. This can make a program’s design less flexible. It also introduces the possibility of calling methods on subclasses that don’t make sense or that cause errors because the methods don’t apply to the subclass. In addition, some languages will only allow single inheritance (meaning a subclass can only inherit from one class), further restricting the flexibility of a program’s design.

 For these reasons, Rust takes the different approach of using trait objects instead of inheritance. Let’s look at how trait objects enable polymorphism in Rust.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch17-01-what-is-oo.html>

All the Places Patterns Can Be Used
===================================

 Patterns pop up in a number of places in Rust, and you’ve been using them a lot without realizing it! This section discusses all the places where patterns are valid.

 ### 
`match` Arms

 As discussed in Chapter 6, we use patterns in the arms of `match` expressions. Formally, `match` expressions are defined as the keyword `match`, a value to match on, and one or more match arms that consist of a pattern and an expression to run if the value matches that arm’s pattern, like this:

 
```
match VALUE {
    PATTERN => EXPRESSION,
    PATTERN => EXPRESSION,
    PATTERN => EXPRESSION,
}

```
 For example, here's the `match` expression from Listing 6-5 that matches on an `Option<i32>` value in the variable `x`:

 
```
match x {
    None => None,
    Some(i) => Some(i + 1),
}
```
 The patterns in this `match` expression are the `None` and `Some(i)` on the left of each arrow.

 One requirement for `match` expressions is that they need to be *exhaustive* in the sense that all possibilities for the value in the `match` expression must be accounted for. One way to ensure you’ve covered every possibility is to have a catchall pattern for the last arm: for example, a variable name matching any value can never fail and thus covers every remaining case.

 The particular pattern `_` will match anything, but it never binds to a variable, so it’s often used in the last match arm. The `_` pattern can be useful when you want to ignore any value not specified, for example. We’ll cover the `_` pattern in more detail in the [“Ignoring Values in a Pattern”](ch18-03-pattern-syntax#ignoring-values-in-a-pattern) section later in this chapter.

 ### Conditional `if let` Expressions

 In Chapter 6 we discussed how to use `if let` expressions mainly as a shorter way to write the equivalent of a `match` that only matches one case. Optionally, `if let` can have a corresponding `else` containing code to run if the pattern in the `if let` doesn’t match.

 Listing 18-1 shows that it’s also possible to mix and match `if let`, `else if`, and `else if let` expressions. Doing so gives us more flexibility than a `match` expression in which we can express only one value to compare with the patterns. Also, Rust doesn't require that the conditions in a series of `if let`, `else if`, `else if let` arms relate to each other.

 The code in Listing 18-1 determines what color to make your background based on a series of checks for several conditions. For this example, we’ve created variables with hardcoded values that a real program might receive from user input.

 Filename: src/main.rs

 
```
fn main() {
    let favorite_color: Option<&str> = None;
    let is_tuesday = false;
    let age: Result<u8, _> = "34".parse();

    if let Some(color) = favorite_color {
        println!("Using your favorite color, {color}, as the background");
    } else if is_tuesday {
        println!("Tuesday is green day!");
    } else if let Ok(age) = age {
        if age > 30 {
            println!("Using purple as the background color");
        } else {
            println!("Using orange as the background color");
        }
    } else {
        println!("Using blue as the background color");
    }
}
```
 Listing 18-1: Mixing `if let`, `else if`, `else if let`, and `else`

 If the user specifies a favorite color, that color is used as the background. If no favorite color is specified and today is Tuesday, the background color is green. Otherwise, if the user specifies their age as a string and we can parse it as a number successfully, the color is either purple or orange depending on the value of the number. If none of these conditions apply, the background color is blue.

 This conditional structure lets us support complex requirements. With the hardcoded values we have here, this example will print `Using purple as the background color`.

 You can see that `if let` can also introduce shadowed variables in the same way that `match` arms can: the line `if let Ok(age) = age` introduces a new shadowed `age` variable that contains the value inside the `Ok` variant. This means we need to place the `if age > 30` condition within that block: we can’t combine these two conditions into `if let Ok(age) = age && age > 30`. The shadowed `age` we want to compare to 30 isn’t valid until the new scope starts with the curly bracket.

 The downside of using `if let` expressions is that the compiler doesn’t check for exhaustiveness, whereas with `match` expressions it does. If we omitted the last `else` block and therefore missed handling some cases, the compiler would not alert us to the possible logic bug.

 ### 
`while let` Conditional Loops

 Similar in construction to `if let`, the `while let` conditional loop allows a `while` loop to run for as long as a pattern continues to match. In Listing 18-2 we code a `while let` loop that uses a vector as a stack and prints the values in the vector in the opposite order in which they were pushed.

 
```
fn main() {
    let mut stack = Vec::new();

    stack.push(1);
    stack.push(2);
    stack.push(3);

    while let Some(top) = stack.pop() {
        println!("{}", top);
    }
}
```
 Listing 18-2: Using a `while let` loop to print values for as long as `stack.pop()` returns `Some`

 This example prints 3, 2, and then 1. The `pop` method takes the last element out of the vector and returns `Some(value)`. If the vector is empty, `pop` returns `None`. The `while` loop continues running the code in its block as long as `pop` returns `Some`. When `pop` returns `None`, the loop stops. We can use `while let` to pop every element off our stack.

 ### 
`for` Loops

 In a `for` loop, the value that directly follows the keyword `for` is a pattern. For example, in `for x in y` the `x` is the pattern. Listing 18-3 demonstrates how to use a pattern in a `for` loop to destructure, or break apart, a tuple as part of the `for` loop.

 
```
fn main() {
    let v = vec!['a', 'b', 'c'];

    for (index, value) in v.iter().enumerate() {
        println!("{} is at index {}", value, index);
    }
}
```
 Listing 18-3: Using a pattern in a `for` loop to destructure a tuple

 The code in Listing 18-3 will print the following:

 
```
$ cargo run
   Compiling patterns v0.1.0 (file:///projects/patterns)
    Finished dev [unoptimized + debuginfo] target(s) in 0.52s
     Running `target/debug/patterns`
a is at index 0
b is at index 1
c is at index 2

```
 We adapt an iterator using the `enumerate` method so it produces a value and the index for that value, placed into a tuple. The first value produced is the tuple `(0, 'a')`. When this value is matched to the pattern `(index, value)`, `index` will be `0` and `value` will be `'a'`, printing the first line of the output.

 ### 
`let` Statements

 Prior to this chapter, we had only explicitly discussed using patterns with `match` and `if let`, but in fact, we’ve used patterns in other places as well, including in `let` statements. For example, consider this straightforward variable assignment with `let`:

 
```
#![allow(unused)]
fn main() {
let x = 5;
}
```
 Every time you've used a `let` statement like this you've been using patterns, although you might not have realized it! More formally, a `let` statement looks like this:

 
```
let PATTERN = EXPRESSION;

```
 In statements like `let x = 5;` with a variable name in the `PATTERN` slot, the variable name is just a particularly simple form of a pattern. Rust compares the expression against the pattern and assigns any names it finds. So in the `let x = 5;` example, `x` is a pattern that means “bind what matches here to the variable `x`.” Because the name `x` is the whole pattern, this pattern effectively means “bind everything to the variable `x`, whatever the value is.”

 To see the pattern matching aspect of `let` more clearly, consider Listing 18-4, which uses a pattern with `let` to destructure a tuple.

 
```
fn main() {
    let (x, y, z) = (1, 2, 3);
}
```
 Listing 18-4: Using a pattern to destructure a tuple and create three variables at once

 Here, we match a tuple against a pattern. Rust compares the value `(1, 2, 3)` to the pattern `(x, y, z)` and sees that the value matches the pattern, so Rust binds `1` to `x`, `2` to `y`, and `3` to `z`. You can think of this tuple pattern as nesting three individual variable patterns inside it.

 If the number of elements in the pattern doesn’t match the number of elements in the tuple, the overall type won’t match and we’ll get a compiler error. For example, Listing 18-5 shows an attempt to destructure a tuple with three elements into two variables, which won’t work.

 
```
fn main() {
    let (x, y) = (1, 2, 3);
}
```
 Listing 18-5: Incorrectly constructing a pattern whose variables don’t match the number of elements in the tuple

 Attempting to compile this code results in this type error:

 
```
$ cargo run
   Compiling patterns v0.1.0 (file:///projects/patterns)
error[E0308]: mismatched types
 --> src/main.rs:2:9
  |
2 |     let (x, y) = (1, 2, 3);
  |         ^^^^^^   --------- this expression has type `({integer}, {integer}, {integer})`
  |         |
  |         expected a tuple with 3 elements, found one with 2 elements
  |
  = note: expected tuple `({integer}, {integer}, {integer})`
             found tuple `(_, _)`

For more information about this error, try `rustc --explain E0308`.
error: could not compile `patterns` due to previous error

```
 To fix the error, we could ignore one or more of the values in the tuple using `_` or `..`, as you’ll see in the [“Ignoring Values in a Pattern”](ch18-03-pattern-syntax#ignoring-values-in-a-pattern) section. If the problem is that we have too many variables in the pattern, the solution is to make the types match by removing variables so the number of variables equals the number of elements in the tuple.

 ### Function Parameters

 Function parameters can also be patterns. The code in Listing 18-6, which declares a function named `foo` that takes one parameter named `x` of type `i32`, should by now look familiar.

 
```
fn foo(x: i32) {
    // code goes here
}

fn main() {}
```
 Listing 18-6: A function signature uses patterns in the parameters

 The `x` part is a pattern! As we did with `let`, we could match a tuple in a function’s arguments to the pattern. Listing 18-7 splits the values in a tuple as we pass it to a function.

 Filename: src/main.rs

 
```
fn print_coordinates(&(x, y): &(i32, i32)) {
    println!("Current location: ({}, {})", x, y);
}

fn main() {
    let point = (3, 5);
    print_coordinates(&point);
}
```
 Listing 18-7: A function with parameters that destructure a tuple

 This code prints `Current location: (3, 5)`. The values `&(3, 5)` match the pattern `&(x, y)`, so `x` is the value `3` and `y` is the value `5`.

 We can also use patterns in closure parameter lists in the same way as in function parameter lists, because closures are similar to functions, as discussed in Chapter 13.

 At this point, you’ve seen several ways of using patterns, but patterns don’t work the same in every place we can use them. In some places, the patterns must be irrefutable; in other circumstances, they can be refutable. We’ll discuss these two concepts next.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch18-01-all-the-places-for-patterns.html>

Refutability: Whether a Pattern Might Fail to Match
===================================================

 Patterns come in two forms: refutable and irrefutable. Patterns that will match for any possible value passed are *irrefutable*. An example would be `x` in the statement `let x = 5;` because `x` matches anything and therefore cannot fail to match. Patterns that can fail to match for some possible value are *refutable*. An example would be `Some(x)` in the expression `if let Some(x) = a_value` because if the value in the `a_value` variable is `None` rather than `Some`, the `Some(x)` pattern will not match.

 Function parameters, `let` statements, and `for` loops can only accept irrefutable patterns, because the program cannot do anything meaningful when values don’t match. The `if let` and `while let` expressions accept refutable and irrefutable patterns, but the compiler warns against irrefutable patterns because by definition they’re intended to handle possible failure: the functionality of a conditional is in its ability to perform differently depending on success or failure.

 In general, you shouldn’t have to worry about the distinction between refutable and irrefutable patterns; however, you do need to be familiar with the concept of refutability so you can respond when you see it in an error message. In those cases, you’ll need to change either the pattern or the construct you’re using the pattern with, depending on the intended behavior of the code.

 Let’s look at an example of what happens when we try to use a refutable pattern where Rust requires an irrefutable pattern and vice versa. Listing 18-8 shows a `let` statement, but for the pattern we’ve specified `Some(x)`, a refutable pattern. As you might expect, this code will not compile.

 
```
fn main() {
    let some_option_value: Option<i32> = None;
    let Some(x) = some_option_value;
}
```
 Listing 18-8: Attempting to use a refutable pattern with `let`

 If `some_option_value` was a `None` value, it would fail to match the pattern `Some(x)`, meaning the pattern is refutable. However, the `let` statement can only accept an irrefutable pattern because there is nothing valid the code can do with a `None` value. At compile time, Rust will complain that we’ve tried to use a refutable pattern where an irrefutable pattern is required:

 
```
$ cargo run
   Compiling patterns v0.1.0 (file:///projects/patterns)
error[E0005]: refutable pattern in local binding: `None` not covered
 --> src/main.rs:3:9
  |
3 |     let Some(x) = some_option_value;
  |         ^^^^^^^ pattern `None` not covered
  |
  = note: `let` bindings require an "irrefutable pattern", like a `struct` or an `enum` with only one variant
  = note: for more information, visit https://doc.rust-lang.org/book/ch18-02-refutability.html
note: `Option<i32>` defined here
 --> /rustc/d5a82bbd26e1ad8b7401f6a718a9c57c96905483/library/core/src/option.rs:518:1
  |
  = note: 
/rustc/d5a82bbd26e1ad8b7401f6a718a9c57c96905483/library/core/src/option.rs:522:5: not covered
  = note: the matched value is of type `Option<i32>`
help: you might want to use `if let` to ignore the variant that isn't matched
  |
3 |     let x = if let Some(x) = some_option_value { x } else { todo!() };
  |     ++++++++++                                 ++++++++++++++++++++++
help: alternatively, you might want to use let else to handle the variant that isn't matched
  |
3 |     let Some(x) = some_option_value else { todo!() };
  |                                     ++++++++++++++++

For more information about this error, try `rustc --explain E0005`.
error: could not compile `patterns` due to previous error

```
 Because we didn’t cover (and couldn’t cover!) every valid value with the pattern `Some(x)`, Rust rightfully produces a compiler error.

 If we have a refutable pattern where an irrefutable pattern is needed, we can fix it by changing the code that uses the pattern: instead of using `let`, we can use `if let`. Then if the pattern doesn’t match, the code will just skip the code in the curly brackets, giving it a way to continue validly. Listing 18-9 shows how to fix the code in Listing 18-8.

 
```
fn main() {
    let some_option_value: Option<i32> = None;
    if let Some(x) = some_option_value {
        println!("{}", x);
    }
}
```
 Listing 18-9: Using `if let` and a block with refutable patterns instead of `let`

 We’ve given the code an out! This code is perfectly valid, although it means we cannot use an irrefutable pattern without receiving an error. If we give `if let` a pattern that will always match, such as `x`, as shown in Listing 18-10, the compiler will give a warning.

 
```
fn main() {
    if let x = 5 {
        println!("{}", x);
    };
}
```
 Listing 18-10: Attempting to use an irrefutable pattern with `if let`

 Rust complains that it doesn’t make sense to use `if let` with an irrefutable pattern:

 
```
$ cargo run
   Compiling patterns v0.1.0 (file:///projects/patterns)
warning: irrefutable `if let` pattern
 --> src/main.rs:2:8
  |
2 |     if let x = 5 {
  |        ^^^^^^^^^
  |
  = note: this pattern will always match, so the `if let` is useless
  = help: consider replacing the `if let` with a `let`
  = note: `#[warn(irrefutable_let_patterns)]` on by default

warning: `patterns` (bin "patterns") generated 1 warning
    Finished dev [unoptimized + debuginfo] target(s) in 0.39s
     Running `target/debug/patterns`
5

```
 For this reason, match arms must use refutable patterns, except for the last arm, which should match any remaining values with an irrefutable pattern. Rust allows us to use an irrefutable pattern in a `match` with only one arm, but this syntax isn’t particularly useful and could be replaced with a simpler `let` statement.

 Now that you know where to use patterns and the difference between refutable and irrefutable patterns, let’s cover all the syntax we can use to create patterns.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch18-02-refutability.html>

Advanced Features
=================

 By now, you’ve learned the most commonly used parts of the Rust programming language. Before we do one more project in Chapter 20, we’ll look at a few aspects of the language you might run into every once in a while, but may not use every day. You can use this chapter as a reference for when you encounter any unknowns. The features covered here are useful in very specific situations. Although you might not reach for them often, we want to make sure you have a grasp of all the features Rust has to offer.

 In this chapter, we’ll cover:

 * Unsafe Rust: how to opt out of some of Rust’s guarantees and take responsibility for manually upholding those guarantees
* Advanced traits: associated types, default type parameters, fully qualified syntax, supertraits, and the newtype pattern in relation to traits
* Advanced types: more about the newtype pattern, type aliases, the never type, and dynamically sized types
* Advanced functions and closures: function pointers and returning closures
* Macros: ways to define code that defines more code at compile time

 It’s a panoply of Rust features with something for everyone! Let’s dive in!



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch19-00-advanced-features.html>

Using Trait Objects That Allow for Values of Different Types
============================================================

 In Chapter 8, we mentioned that one limitation of vectors is that they can store elements of only one type. We created a workaround in Listing 8-9 where we defined a `SpreadsheetCell` enum that had variants to hold integers, floats, and text. This meant we could store different types of data in each cell and still have a vector that represented a row of cells. This is a perfectly good solution when our interchangeable items are a fixed set of types that we know when our code is compiled.

 However, sometimes we want our library user to be able to extend the set of types that are valid in a particular situation. To show how we might achieve this, we’ll create an example graphical user interface (GUI) tool that iterates through a list of items, calling a `draw` method on each one to draw it to the screen—a common technique for GUI tools. We’ll create a library crate called `gui` that contains the structure of a GUI library. This crate might include some types for people to use, such as `Button` or `TextField`. In addition, `gui` users will want to create their own types that can be drawn: for instance, one programmer might add an `Image` and another might add a `SelectBox`.

 We won’t implement a fully fledged GUI library for this example but will show how the pieces would fit together. At the time of writing the library, we can’t know and define all the types other programmers might want to create. But we do know that `gui` needs to keep track of many values of different types, and it needs to call a `draw` method on each of these differently typed values. It doesn’t need to know exactly what will happen when we call the `draw` method, just that the value will have that method available for us to call.

 To do this in a language with inheritance, we might define a class named `Component` that has a method named `draw` on it. The other classes, such as `Button`, `Image`, and `SelectBox`, would inherit from `Component` and thus inherit the `draw` method. They could each override the `draw` method to define their custom behavior, but the framework could treat all of the types as if they were `Component` instances and call `draw` on them. But because Rust doesn’t have inheritance, we need another way to structure the `gui` library to allow users to extend it with new types.

 ### Defining a Trait for Common Behavior

 To implement the behavior we want `gui` to have, we’ll define a trait named `Draw` that will have one method named `draw`. Then we can define a vector that takes a *trait object*. A trait object points to both an instance of a type implementing our specified trait and a table used to look up trait methods on that type at runtime. We create a trait object by specifying some sort of pointer, such as a `&` reference or a `Box<T>` smart pointer, then the `dyn` keyword, and then specifying the relevant trait. (We’ll talk about the reason trait objects must use a pointer in Chapter 19 in the section [“Dynamically Sized Types and the `Sized` Trait.”](ch19-04-advanced-types#dynamically-sized-types-and-the-sized-trait)) We can use trait objects in place of a generic or concrete type. Wherever we use a trait object, Rust’s type system will ensure at compile time that any value used in that context will implement the trait object’s trait. Consequently, we don’t need to know all the possible types at compile time.

 We’ve mentioned that, in Rust, we refrain from calling structs and enums “objects” to distinguish them from other languages’ objects. In a struct or enum, the data in the struct fields and the behavior in `impl` blocks are separated, whereas in other languages, the data and behavior combined into one concept is often labeled an object. However, trait objects *are* more like objects in other languages in the sense that they combine data and behavior. But trait objects differ from traditional objects in that we can’t add data to a trait object. Trait objects aren’t as generally useful as objects in other languages: their specific purpose is to allow abstraction across common behavior.

 Listing 17-3 shows how to define a trait named `Draw` with one method named `draw`:

 Filename: src/lib.rs

 
```
pub trait Draw {
    fn draw(&self);
}
```
 Listing 17-3: Definition of the `Draw` trait

 This syntax should look familiar from our discussions on how to define traits in Chapter 10. Next comes some new syntax: Listing 17-4 defines a struct named `Screen` that holds a vector named `components`. This vector is of type `Box<dyn Draw>`, which is a trait object; it’s a stand-in for any type inside a `Box` that implements the `Draw` trait.

 Filename: src/lib.rs

 
```
pub trait Draw {
    fn draw(&self);
}

pub struct Screen {
    pub components: Vec<Box<dyn Draw>>,
}
```
 Listing 17-4: Definition of the `Screen` struct with a `components` field holding a vector of trait objects that implement the `Draw` trait

 On the `Screen` struct, we’ll define a method named `run` that will call the `draw` method on each of its `components`, as shown in Listing 17-5:

 Filename: src/lib.rs

 
```
pub trait Draw {
    fn draw(&self);
}

pub struct Screen {
    pub components: Vec<Box<dyn Draw>>,
}

impl Screen {
    pub fn run(&self) {
        for component in self.components.iter() {
            component.draw();
        }
    }
}
```
 Listing 17-5: A `run` method on `Screen` that calls the `draw` method on each component

 This works differently from defining a struct that uses a generic type parameter with trait bounds. A generic type parameter can only be substituted with one concrete type at a time, whereas trait objects allow for multiple concrete types to fill in for the trait object at runtime. For example, we could have defined the `Screen` struct using a generic type and a trait bound as in Listing 17-6:

 Filename: src/lib.rs

 
```
pub trait Draw {
    fn draw(&self);
}

pub struct Screen<T: Draw> {
    pub components: Vec<T>,
}

impl<T> Screen<T>
where
    T: Draw,
{
    pub fn run(&self) {
        for component in self.components.iter() {
            component.draw();
        }
    }
}
```
 Listing 17-6: An alternate implementation of the `Screen` struct and its `run` method using generics and trait bounds

 This restricts us to a `Screen` instance that has a list of components all of type `Button` or all of type `TextField`. If you’ll only ever have homogeneous collections, using generics and trait bounds is preferable because the definitions will be monomorphized at compile time to use the concrete types.

 On the other hand, with the method using trait objects, one `Screen` instance can hold a `Vec<T>` that contains a `Box<Button>` as well as a `Box<TextField>`. Let’s look at how this works, and then we’ll talk about the runtime performance implications.

 ### Implementing the Trait

 Now we’ll add some types that implement the `Draw` trait. We’ll provide the `Button` type. Again, actually implementing a GUI library is beyond the scope of this book, so the `draw` method won’t have any useful implementation in its body. To imagine what the implementation might look like, a `Button` struct might have fields for `width`, `height`, and `label`, as shown in Listing 17-7:

 Filename: src/lib.rs

 
```
pub trait Draw {
    fn draw(&self);
}

pub struct Screen {
    pub components: Vec<Box<dyn Draw>>,
}

impl Screen {
    pub fn run(&self) {
        for component in self.components.iter() {
            component.draw();
        }
    }
}

pub struct Button {
    pub width: u32,
    pub height: u32,
    pub label: String,
}

impl Draw for Button {
    fn draw(&self) {
        // code to actually draw a button
    }
}
```
 Listing 17-7: A `Button` struct that implements the `Draw` trait

 The `width`, `height`, and `label` fields on `Button` will differ from the fields on other components; for example, a `TextField` type might have those same fields plus a `placeholder` field. Each of the types we want to draw on the screen will implement the `Draw` trait but will use different code in the `draw` method to define how to draw that particular type, as `Button` has here (without the actual GUI code, as mentioned). The `Button` type, for instance, might have an additional `impl` block containing methods related to what happens when a user clicks the button. These kinds of methods won’t apply to types like `TextField`.

 If someone using our library decides to implement a `SelectBox` struct that has `width`, `height`, and `options` fields, they implement the `Draw` trait on the `SelectBox` type as well, as shown in Listing 17-8:

 Filename: src/main.rs

 
```
use gui::Draw;

struct SelectBox {
    width: u32,
    height: u32,
    options: Vec<String>,
}

impl Draw for SelectBox {
    fn draw(&self) {
        // code to actually draw a select box
    }
}

fn main() {}
```
 Listing 17-8: Another crate using `gui` and implementing the `Draw` trait on a `SelectBox` struct

 Our library’s user can now write their `main` function to create a `Screen` instance. To the `Screen` instance, they can add a `SelectBox` and a `Button` by putting each in a `Box<T>` to become a trait object. They can then call the `run` method on the `Screen` instance, which will call `draw` on each of the components. Listing 17-9 shows this implementation:

 Filename: src/main.rs

 
```
use gui::Draw;

struct SelectBox {
    width: u32,
    height: u32,
    options: Vec<String>,
}

impl Draw for SelectBox {
    fn draw(&self) {
        // code to actually draw a select box
    }
}

use gui::{Button, Screen};

fn main() {
    let screen = Screen {
        components: vec![
            Box::new(SelectBox {
                width: 75,
                height: 10,
                options: vec![
                    String::from("Yes"),
                    String::from("Maybe"),
                    String::from("No"),
                ],
            }),
            Box::new(Button {
                width: 50,
                height: 10,
                label: String::from("OK"),
            }),
        ],
    };

    screen.run();
}
```
 Listing 17-9: Using trait objects to store values of different types that implement the same trait

 When we wrote the library, we didn’t know that someone might add the `SelectBox` type, but our `Screen` implementation was able to operate on the new type and draw it because `SelectBox` implements the `Draw` trait, which means it implements the `draw` method.

 This concept—of being concerned only with the messages a value responds to rather than the value’s concrete type—is similar to the concept of *duck typing* in dynamically typed languages: if it walks like a duck and quacks like a duck, then it must be a duck! In the implementation of `run` on `Screen` in Listing 17-5, `run` doesn’t need to know what the concrete type of each component is. It doesn’t check whether a component is an instance of a `Button` or a `SelectBox`, it just calls the `draw` method on the component. By specifying `Box<dyn Draw>` as the type of the values in the `components` vector, we’ve defined `Screen` to need values that we can call the `draw` method on.

 The advantage of using trait objects and Rust’s type system to write code similar to code using duck typing is that we never have to check whether a value implements a particular method at runtime or worry about getting errors if a value doesn’t implement a method but we call it anyway. Rust won’t compile our code if the values don’t implement the traits that the trait objects need.

 For example, Listing 17-10 shows what happens if we try to create a `Screen` with a `String` as a component:

 Filename: src/main.rs

 
```
use gui::Screen;

fn main() {
    let screen = Screen {
        components: vec![Box::new(String::from("Hi"))],
    };

    screen.run();
}
```
 Listing 17-10: Attempting to use a type that doesn’t implement the trait object’s trait

 We’ll get this error because `String` doesn’t implement the `Draw` trait:

 
```
$ cargo run
   Compiling gui v0.1.0 (file:///projects/gui)
error[E0277]: the trait bound `String: Draw` is not satisfied
 --> src/main.rs:5:26
  |
5 |         components: vec![Box::new(String::from("Hi"))],
  |                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Draw` is not implemented for `String`
  |
  = help: the trait `Draw` is implemented for `Button`
  = note: required for the cast from `String` to the object type `dyn Draw`

For more information about this error, try `rustc --explain E0277`.
error: could not compile `gui` due to previous error

```
 This error lets us know that either we’re passing something to `Screen` we didn’t mean to pass and so should pass a different type or we should implement `Draw` on `String` so that `Screen` is able to call `draw` on it.

 ### Trait Objects Perform Dynamic Dispatch

 Recall in the [“Performance of Code Using Generics”](ch10-01-syntax#performance-of-code-using-generics) section in Chapter 10 our discussion on the monomorphization process performed by the compiler when we use trait bounds on generics: the compiler generates nongeneric implementations of functions and methods for each concrete type that we use in place of a generic type parameter. The code that results from monomorphization is doing *static dispatch*, which is when the compiler knows what method you’re calling at compile time. This is opposed to *dynamic dispatch*, which is when the compiler can’t tell at compile time which method you’re calling. In dynamic dispatch cases, the compiler emits code that at runtime will figure out which method to call.

 When we use trait objects, Rust must use dynamic dispatch. The compiler doesn’t know all the types that might be used with the code that’s using trait objects, so it doesn’t know which method implemented on which type to call. Instead, at runtime, Rust uses the pointers inside the trait object to know which method to call. This lookup incurs a runtime cost that doesn’t occur with static dispatch. Dynamic dispatch also prevents the compiler from choosing to inline a method’s code, which in turn prevents some optimizations. However, we did get extra flexibility in the code that we wrote in Listing 17-5 and were able to support in Listing 17-9, so it’s a trade-off to consider.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch17-02-trait-objects.html>

Implementing an Object-Oriented Design Pattern
==============================================

 The *state pattern* is an object-oriented design pattern. The crux of the pattern is that we define a set of states a value can have internally. The states are represented by a set of *state objects*, and the value’s behavior changes based on its state. We’re going to work through an example of a blog post struct that has a field to hold its state, which will be a state object from the set "draft", "review", or "published".

 The state objects share functionality: in Rust, of course, we use structs and traits rather than objects and inheritance. Each state object is responsible for its own behavior and for governing when it should change into another state. The value that holds a state object knows nothing about the different behavior of the states or when to transition between states.

 The advantage of using the state pattern is that, when the business requirements of the program change, we won’t need to change the code of the value holding the state or the code that uses the value. We’ll only need to update the code inside one of the state objects to change its rules or perhaps add more state objects.

 First, we’re going to implement the state pattern in a more traditional object-oriented way, then we’ll use an approach that’s a bit more natural in Rust. Let’s dig in to incrementally implementing a blog post workflow using the state pattern.

 The final functionality will look like this:

 1. A blog post starts as an empty draft.
2. When the draft is done, a review of the post is requested.
3. When the post is approved, it gets published.
4. Only published blog posts return content to print, so unapproved posts can’t accidentally be published.

 Any other changes attempted on a post should have no effect. For example, if we try to approve a draft blog post before we’ve requested a review, the post should remain an unpublished draft.

 Listing 17-11 shows this workflow in code form: this is an example usage of the API we’ll implement in a library crate named `blog`. This won’t compile yet because we haven’t implemented the `blog` crate.

 Filename: src/main.rs

 
```
use blog::Post;

fn main() {
    let mut post = Post::new();

    post.add_text("I ate a salad for lunch today");
    assert_eq!("", post.content());

    post.request_review();
    assert_eq!("", post.content());

    post.approve();
    assert_eq!("I ate a salad for lunch today", post.content());
}
```
 Listing 17-11: Code that demonstrates the desired behavior we want our `blog` crate to have

 We want to allow the user to create a new draft blog post with `Post::new`. We want to allow text to be added to the blog post. If we try to get the post’s content immediately, before approval, we shouldn’t get any text because the post is still a draft. We’ve added `assert_eq!` in the code for demonstration purposes. An excellent unit test for this would be to assert that a draft blog post returns an empty string from the `content` method, but we’re not going to write tests for this example.

 Next, we want to enable a request for a review of the post, and we want `content` to return an empty string while waiting for the review. When the post receives approval, it should get published, meaning the text of the post will be returned when `content` is called.

 Notice that the only type we’re interacting with from the crate is the `Post` type. This type will use the state pattern and will hold a value that will be one of three state objects representing the various states a post can be in—draft, waiting for review, or published. Changing from one state to another will be managed internally within the `Post` type. The states change in response to the methods called by our library’s users on the `Post` instance, but they don’t have to manage the state changes directly. Also, users can’t make a mistake with the states, like publishing a post before it’s reviewed.

 ### Defining `Post` and Creating a New Instance in the Draft State

 Let’s get started on the implementation of the library! We know we need a public `Post` struct that holds some content, so we’ll start with the definition of the struct and an associated public `new` function to create an instance of `Post`, as shown in Listing 17-12. We’ll also make a private `State` trait that will define the behavior that all state objects for a `Post` must have.

 Then `Post` will hold a trait object of `Box<dyn State>` inside an `Option<T>` in a private field named `state` to hold the state object. You’ll see why the `Option<T>` is necessary in a bit.

 Filename: src/lib.rs

 
```
pub struct Post {
    state: Option<Box<dyn State>>,
    content: String,
}

impl Post {
    pub fn new() -> Post {
        Post {
            state: Some(Box::new(Draft {})),
            content: String::new(),
        }
    }
}

trait State {}

struct Draft {}

impl State for Draft {}
```
 Listing 17-12: Definition of a `Post` struct and a `new` function that creates a new `Post` instance, a `State` trait, and a `Draft` struct

 The `State` trait defines the behavior shared by different post states. The state objects are `Draft`, `PendingReview`, and `Published`, and they will all implement the `State` trait. For now, the trait doesn’t have any methods, and we’ll start by defining just the `Draft` state because that is the state we want a post to start in.

 When we create a new `Post`, we set its `state` field to a `Some` value that holds a `Box`. This `Box` points to a new instance of the `Draft` struct. This ensures whenever we create a new instance of `Post`, it will start out as a draft. Because the `state` field of `Post` is private, there is no way to create a `Post` in any other state! In the `Post::new` function, we set the `content` field to a new, empty `String`.

 ### Storing the Text of the Post Content

 We saw in Listing 17-11 that we want to be able to call a method named `add_text` and pass it a `&str` that is then added as the text content of the blog post. We implement this as a method, rather than exposing the `content` field as `pub`, so that later we can implement a method that will control how the `content` field’s data is read. The `add_text` method is pretty straightforward, so let’s add the implementation in Listing 17-13 to the `impl Post` block:

 Filename: src/lib.rs

 
```
pub struct Post {
    state: Option<Box<dyn State>>,
    content: String,
}

impl Post {
    // --snip--
    pub fn new() -> Post {
        Post {
            state: Some(Box::new(Draft {})),
            content: String::new(),
        }
    }

    pub fn add_text(&mut self, text: &str) {
        self.content.push_str(text);
    }
}

trait State {}

struct Draft {}

impl State for Draft {}
```
 Listing 17-13: Implementing the `add_text` method to add text to a post’s `content`

 The `add_text` method takes a mutable reference to `self`, because we’re changing the `Post` instance that we’re calling `add_text` on. We then call `push_str` on the `String` in `content` and pass the `text` argument to add to the saved `content`. This behavior doesn’t depend on the state the post is in, so it’s not part of the state pattern. The `add_text` method doesn’t interact with the `state` field at all, but it is part of the behavior we want to support.

 ### Ensuring the Content of a Draft Post Is Empty

 Even after we’ve called `add_text` and added some content to our post, we still want the `content` method to return an empty string slice because the post is still in the draft state, as shown on line 7 of Listing 17-11. For now, let’s implement the `content` method with the simplest thing that will fulfill this requirement: always returning an empty string slice. We’ll change this later once we implement the ability to change a post’s state so it can be published. So far, posts can only be in the draft state, so the post content should always be empty. Listing 17-14 shows this placeholder implementation:

 Filename: src/lib.rs

 
```
pub struct Post {
    state: Option<Box<dyn State>>,
    content: String,
}

impl Post {
    // --snip--
    pub fn new() -> Post {
        Post {
            state: Some(Box::new(Draft {})),
            content: String::new(),
        }
    }

    pub fn add_text(&mut self, text: &str) {
        self.content.push_str(text);
    }

    pub fn content(&self) -> &str {
        ""
    }
}

trait State {}

struct Draft {}

impl State for Draft {}
```
 Listing 17-14: Adding a placeholder implementation for the `content` method on `Post` that always returns an empty string slice

 With this added `content` method, everything in Listing 17-11 up to line 7 works as intended.

 ### Requesting a Review of the Post Changes Its State

 Next, we need to add functionality to request a review of a post, which should change its state from `Draft` to `PendingReview`. Listing 17-15 shows this code:

 Filename: src/lib.rs

 
```
pub struct Post {
    state: Option<Box<dyn State>>,
    content: String,
}

impl Post {
    // --snip--
    pub fn new() -> Post {
        Post {
            state: Some(Box::new(Draft {})),
            content: String::new(),
        }
    }

    pub fn add_text(&mut self, text: &str) {
        self.content.push_str(text);
    }

    pub fn content(&self) -> &str {
        ""
    }

    pub fn request_review(&mut self) {
        if let Some(s) = self.state.take() {
            self.state = Some(s.request_review())
        }
    }
}

trait State {
    fn request_review(self: Box<Self>) -> Box<dyn State>;
}

struct Draft {}

impl State for Draft {
    fn request_review(self: Box<Self>) -> Box<dyn State> {
        Box::new(PendingReview {})
    }
}

struct PendingReview {}

impl State for PendingReview {
    fn request_review(self: Box<Self>) -> Box<dyn State> {
        self
    }
}
```
 Listing 17-15: Implementing `request_review` methods on `Post` and the `State` trait

 We give `Post` a public method named `request_review` that will take a mutable reference to `self`. Then we call an internal `request_review` method on the current state of `Post`, and this second `request_review` method consumes the current state and returns a new state.

 We add the `request_review` method to the `State` trait; all types that implement the trait will now need to implement the `request_review` method. Note that rather than having `self`, `&self`, or `&mut self` as the first parameter of the method, we have `self: Box<Self>`. This syntax means the method is only valid when called on a `Box` holding the type. This syntax takes ownership of `Box<Self>`, invalidating the old state so the state value of the `Post` can transform into a new state.

 To consume the old state, the `request_review` method needs to take ownership of the state value. This is where the `Option` in the `state` field of `Post` comes in: we call the `take` method to take the `Some` value out of the `state` field and leave a `None` in its place, because Rust doesn’t let us have unpopulated fields in structs. This lets us move the `state` value out of `Post` rather than borrowing it. Then we’ll set the post’s `state` value to the result of this operation.

 We need to set `state` to `None` temporarily rather than setting it directly with code like `self.state = self.state.request_review();` to get ownership of the `state` value. This ensures `Post` can’t use the old `state` value after we’ve transformed it into a new state.

 The `request_review` method on `Draft` returns a new, boxed instance of a new `PendingReview` struct, which represents the state when a post is waiting for a review. The `PendingReview` struct also implements the `request_review` method but doesn’t do any transformations. Rather, it returns itself, because when we request a review on a post already in the `PendingReview` state, it should stay in the `PendingReview` state.

 Now we can start seeing the advantages of the state pattern: the `request_review` method on `Post` is the same no matter its `state` value. Each state is responsible for its own rules.

 We’ll leave the `content` method on `Post` as is, returning an empty string slice. We can now have a `Post` in the `PendingReview` state as well as in the `Draft` state, but we want the same behavior in the `PendingReview` state. Listing 17-11 now works up to line 10!

 ### Adding `approve` to Change the Behavior of `content`

 The `approve` method will be similar to the `request_review` method: it will set `state` to the value that the current state says it should have when that state is approved, as shown in Listing 17-16:

 Filename: src/lib.rs

 
```
pub struct Post {
    state: Option<Box<dyn State>>,
    content: String,
}

impl Post {
    // --snip--
    pub fn new() -> Post {
        Post {
            state: Some(Box::new(Draft {})),
            content: String::new(),
        }
    }

    pub fn add_text(&mut self, text: &str) {
        self.content.push_str(text);
    }

    pub fn content(&self) -> &str {
        ""
    }

    pub fn request_review(&mut self) {
        if let Some(s) = self.state.take() {
            self.state = Some(s.request_review())
        }
    }

    pub fn approve(&mut self) {
        if let Some(s) = self.state.take() {
            self.state = Some(s.approve())
        }
    }
}

trait State {
    fn request_review(self: Box<Self>) -> Box<dyn State>;
    fn approve(self: Box<Self>) -> Box<dyn State>;
}

struct Draft {}

impl State for Draft {
    // --snip--
    fn request_review(self: Box<Self>) -> Box<dyn State> {
        Box::new(PendingReview {})
    }

    fn approve(self: Box<Self>) -> Box<dyn State> {
        self
    }
}

struct PendingReview {}

impl State for PendingReview {
    // --snip--
    fn request_review(self: Box<Self>) -> Box<dyn State> {
        self
    }

    fn approve(self: Box<Self>) -> Box<dyn State> {
        Box::new(Published {})
    }
}

struct Published {}

impl State for Published {
    fn request_review(self: Box<Self>) -> Box<dyn State> {
        self
    }

    fn approve(self: Box<Self>) -> Box<dyn State> {
        self
    }
}
```
 Listing 17-16: Implementing the `approve` method on `Post` and the `State` trait

 We add the `approve` method to the `State` trait and add a new struct that implements `State`, the `Published` state.

 Similar to the way `request_review` on `PendingReview` works, if we call the `approve` method on a `Draft`, it will have no effect because `approve` will return `self`. When we call `approve` on `PendingReview`, it returns a new, boxed instance of the `Published` struct. The `Published` struct implements the `State` trait, and for both the `request_review` method and the `approve` method, it returns itself, because the post should stay in the `Published` state in those cases.

 Now we need to update the `content` method on `Post`. We want the value returned from `content` to depend on the current state of the `Post`, so we’re going to have the `Post` delegate to a `content` method defined on its `state`, as shown in Listing 17-17:

 Filename: src/lib.rs

 
```
pub struct Post {
    state: Option<Box<dyn State>>,
    content: String,
}

impl Post {
    // --snip--
    pub fn new() -> Post {
        Post {
            state: Some(Box::new(Draft {})),
            content: String::new(),
        }
    }

    pub fn add_text(&mut self, text: &str) {
        self.content.push_str(text);
    }

    pub fn content(&self) -> &str {
        self.state.as_ref().unwrap().content(self)
    }
    // --snip--

    pub fn request_review(&mut self) {
        if let Some(s) = self.state.take() {
            self.state = Some(s.request_review())
        }
    }

    pub fn approve(&mut self) {
        if let Some(s) = self.state.take() {
            self.state = Some(s.approve())
        }
    }
}

trait State {
    fn request_review(self: Box<Self>) -> Box<dyn State>;
    fn approve(self: Box<Self>) -> Box<dyn State>;
}

struct Draft {}

impl State for Draft {
    fn request_review(self: Box<Self>) -> Box<dyn State> {
        Box::new(PendingReview {})
    }

    fn approve(self: Box<Self>) -> Box<dyn State> {
        self
    }
}

struct PendingReview {}

impl State for PendingReview {
    fn request_review(self: Box<Self>) -> Box<dyn State> {
        self
    }

    fn approve(self: Box<Self>) -> Box<dyn State> {
        Box::new(Published {})
    }
}

struct Published {}

impl State for Published {
    fn request_review(self: Box<Self>) -> Box<dyn State> {
        self
    }

    fn approve(self: Box<Self>) -> Box<dyn State> {
        self
    }
}
```
 Listing 17-17: Updating the `content` method on `Post` to delegate to a `content` method on `State`

 Because the goal is to keep all these rules inside the structs that implement `State`, we call a `content` method on the value in `state` and pass the post instance (that is, `self`) as an argument. Then we return the value that’s returned from using the `content` method on the `state` value.

 We call the `as_ref` method on the `Option` because we want a reference to the value inside the `Option` rather than ownership of the value. Because `state` is an `Option<Box<dyn State>>`, when we call `as_ref`, an `Option<&Box<dyn State>>` is returned. If we didn’t call `as_ref`, we would get an error because we can’t move `state` out of the borrowed `&self` of the function parameter.

 We then call the `unwrap` method, which we know will never panic, because we know the methods on `Post` ensure that `state` will always contain a `Some` value when those methods are done. This is one of the cases we talked about in the [“Cases In Which You Have More Information Than the Compiler”](ch09-03-to-panic-or-not-to-panic#cases-in-which-you-have-more-information-than-the-compiler) section of Chapter 9 when we know that a `None` value is never possible, even though the compiler isn’t able to understand that.

 At this point, when we call `content` on the `&Box<dyn State>`, deref coercion will take effect on the `&` and the `Box` so the `content` method will ultimately be called on the type that implements the `State` trait. That means we need to add `content` to the `State` trait definition, and that is where we’ll put the logic for what content to return depending on which state we have, as shown in Listing 17-18:

 Filename: src/lib.rs

 
```
pub struct Post {
    state: Option<Box<dyn State>>,
    content: String,
}

impl Post {
    pub fn new() -> Post {
        Post {
            state: Some(Box::new(Draft {})),
            content: String::new(),
        }
    }

    pub fn add_text(&mut self, text: &str) {
        self.content.push_str(text);
    }

    pub fn content(&self) -> &str {
        self.state.as_ref().unwrap().content(self)
    }

    pub fn request_review(&mut self) {
        if let Some(s) = self.state.take() {
            self.state = Some(s.request_review())
        }
    }

    pub fn approve(&mut self) {
        if let Some(s) = self.state.take() {
            self.state = Some(s.approve())
        }
    }
}

trait State {
    // --snip--
    fn request_review(self: Box<Self>) -> Box<dyn State>;
    fn approve(self: Box<Self>) -> Box<dyn State>;

    fn content<'a>(&self, post: &'a Post) -> &'a str {
        ""
    }
}

// --snip--

struct Draft {}

impl State for Draft {
    fn request_review(self: Box<Self>) -> Box<dyn State> {
        Box::new(PendingReview {})
    }

    fn approve(self: Box<Self>) -> Box<dyn State> {
        self
    }
}

struct PendingReview {}

impl State for PendingReview {
    fn request_review(self: Box<Self>) -> Box<dyn State> {
        self
    }

    fn approve(self: Box<Self>) -> Box<dyn State> {
        Box::new(Published {})
    }
}

struct Published {}

impl State for Published {
    // --snip--
    fn request_review(self: Box<Self>) -> Box<dyn State> {
        self
    }

    fn approve(self: Box<Self>) -> Box<dyn State> {
        self
    }

    fn content<'a>(&self, post: &'a Post) -> &'a str {
        &post.content
    }
}
```
 Listing 17-18: Adding the `content` method to the `State` trait

 We add a default implementation for the `content` method that returns an empty string slice. That means we don’t need to implement `content` on the `Draft` and `PendingReview` structs. The `Published` struct will override the `content` method and return the value in `post.content`.

 Note that we need lifetime annotations on this method, as we discussed in Chapter 10. We’re taking a reference to a `post` as an argument and returning a reference to part of that `post`, so the lifetime of the returned reference is related to the lifetime of the `post` argument.

 And we’re done—all of Listing 17-11 now works! We’ve implemented the state pattern with the rules of the blog post workflow. The logic related to the rules lives in the state objects rather than being scattered throughout `Post`.

 
>  #### Why Not An Enum?
> 
>  You may have been wondering why we didn’t use an `enum` with the different possible post states as variants. That’s certainly a possible solution, try it and compare the end results to see which you prefer! One disadvantage of using an enum is every place that checks the value of the enum will need a `match` expression or similar to handle every possible variant. This could get more repetitive than this trait object solution.
> 
>  

 ### Trade-offs of the State Pattern

 We’ve shown that Rust is capable of implementing the object-oriented state pattern to encapsulate the different kinds of behavior a post should have in each state. The methods on `Post` know nothing about the various behaviors. The way we organized the code, we have to look in only one place to know the different ways a published post can behave: the implementation of the `State` trait on the `Published` struct.

 If we were to create an alternative implementation that didn’t use the state pattern, we might instead use `match` expressions in the methods on `Post` or even in the `main` code that checks the state of the post and changes behavior in those places. That would mean we would have to look in several places to understand all the implications of a post being in the published state! This would only increase the more states we added: each of those `match` expressions would need another arm.

 With the state pattern, the `Post` methods and the places we use `Post` don’t need `match` expressions, and to add a new state, we would only need to add a new struct and implement the trait methods on that one struct.

 The implementation using the state pattern is easy to extend to add more functionality. To see the simplicity of maintaining code that uses the state pattern, try a few of these suggestions:

 * Add a `reject` method that changes the post’s state from `PendingReview` back to `Draft`.
* Require two calls to `approve` before the state can be changed to `Published`.
* Allow users to add text content only when a post is in the `Draft` state. Hint: have the state object responsible for what might change about the content but not responsible for modifying the `Post`.

 One downside of the state pattern is that, because the states implement the transitions between states, some of the states are coupled to each other. If we add another state between `PendingReview` and `Published`, such as `Scheduled`, we would have to change the code in `PendingReview` to transition to `Scheduled` instead. It would be less work if `PendingReview` didn’t need to change with the addition of a new state, but that would mean switching to another design pattern.

 Another downside is that we’ve duplicated some logic. To eliminate some of the duplication, we might try to make default implementations for the `request_review` and `approve` methods on the `State` trait that return `self`; however, this would violate object safety, because the trait doesn’t know what the concrete `self` will be exactly. We want to be able to use `State` as a trait object, so we need its methods to be object safe.

 Other duplication includes the similar implementations of the `request_review` and `approve` methods on `Post`. Both methods delegate to the implementation of the same method on the value in the `state` field of `Option` and set the new value of the `state` field to the result. If we had a lot of methods on `Post` that followed this pattern, we might consider defining a macro to eliminate the repetition (see the [“Macros”](ch19-06-macros#macros) section in Chapter 19).

 By implementing the state pattern exactly as it’s defined for object-oriented languages, we’re not taking as full advantage of Rust’s strengths as we could. Let’s look at some changes we can make to the `blog` crate that can make invalid states and transitions into compile time errors.

 #### Encoding States and Behavior as Types

 We’ll show you how to rethink the state pattern to get a different set of trade-offs. Rather than encapsulating the states and transitions completely so outside code has no knowledge of them, we’ll encode the states into different types. Consequently, Rust’s type checking system will prevent attempts to use draft posts where only published posts are allowed by issuing a compiler error.

 Let’s consider the first part of `main` in Listing 17-11:

 Filename: src/main.rs

 
```
use blog::Post;

fn main() {
    let mut post = Post::new();

    post.add_text("I ate a salad for lunch today");
    assert_eq!("", post.content());

    post.request_review();
    assert_eq!("", post.content());

    post.approve();
    assert_eq!("I ate a salad for lunch today", post.content());
}
```
 We still enable the creation of new posts in the draft state using `Post::new` and the ability to add text to the post’s content. But instead of having a `content` method on a draft post that returns an empty string, we’ll make it so draft posts don’t have the `content` method at all. That way, if we try to get a draft post’s content, we’ll get a compiler error telling us the method doesn’t exist. As a result, it will be impossible for us to accidentally display draft post content in production, because that code won’t even compile. Listing 17-19 shows the definition of a `Post` struct and a `DraftPost` struct, as well as methods on each:

 Filename: src/lib.rs

 
```
pub struct Post {
    content: String,
}

pub struct DraftPost {
    content: String,
}

impl Post {
    pub fn new() -> DraftPost {
        DraftPost {
            content: String::new(),
        }
    }

    pub fn content(&self) -> &str {
        &self.content
    }
}

impl DraftPost {
    pub fn add_text(&mut self, text: &str) {
        self.content.push_str(text);
    }
}
```
 Listing 17-19: A `Post` with a `content` method and a `DraftPost` without a `content` method

 Both the `Post` and `DraftPost` structs have a private `content` field that stores the blog post text. The structs no longer have the `state` field because we’re moving the encoding of the state to the types of the structs. The `Post` struct will represent a published post, and it has a `content` method that returns the `content`.

 We still have a `Post::new` function, but instead of returning an instance of `Post`, it returns an instance of `DraftPost`. Because `content` is private and there aren’t any functions that return `Post`, it’s not possible to create an instance of `Post` right now.

 The `DraftPost` struct has an `add_text` method, so we can add text to `content` as before, but note that `DraftPost` does not have a `content` method defined! So now the program ensures all posts start as draft posts, and draft posts don’t have their content available for display. Any attempt to get around these constraints will result in a compiler error.

 #### Implementing Transitions as Transformations into Different Types

 So how do we get a published post? We want to enforce the rule that a draft post has to be reviewed and approved before it can be published. A post in the pending review state should still not display any content. Let’s implement these constraints by adding another struct, `PendingReviewPost`, defining the `request_review` method on `DraftPost` to return a `PendingReviewPost`, and defining an `approve` method on `PendingReviewPost` to return a `Post`, as shown in Listing 17-20:

 Filename: src/lib.rs

 
```
pub struct Post {
    content: String,
}

pub struct DraftPost {
    content: String,
}

impl Post {
    pub fn new() -> DraftPost {
        DraftPost {
            content: String::new(),
        }
    }

    pub fn content(&self) -> &str {
        &self.content
    }
}

impl DraftPost {
    // --snip--
    pub fn add_text(&mut self, text: &str) {
        self.content.push_str(text);
    }

    pub fn request_review(self) -> PendingReviewPost {
        PendingReviewPost {
            content: self.content,
        }
    }
}

pub struct PendingReviewPost {
    content: String,
}

impl PendingReviewPost {
    pub fn approve(self) -> Post {
        Post {
            content: self.content,
        }
    }
}
```
 Listing 17-20: A `PendingReviewPost` that gets created by calling `request_review` on `DraftPost` and an `approve` method that turns a `PendingReviewPost` into a published `Post`

 The `request_review` and `approve` methods take ownership of `self`, thus consuming the `DraftPost` and `PendingReviewPost` instances and transforming them into a `PendingReviewPost` and a published `Post`, respectively. This way, we won’t have any lingering `DraftPost` instances after we’ve called `request_review` on them, and so forth. The `PendingReviewPost` struct doesn’t have a `content` method defined on it, so attempting to read its content results in a compiler error, as with `DraftPost`. Because the only way to get a published `Post` instance that does have a `content` method defined is to call the `approve` method on a `PendingReviewPost`, and the only way to get a `PendingReviewPost` is to call the `request_review` method on a `DraftPost`, we’ve now encoded the blog post workflow into the type system.

 But we also have to make some small changes to `main`. The `request_review` and `approve` methods return new instances rather than modifying the struct they’re called on, so we need to add more `let post =` shadowing assignments to save the returned instances. We also can’t have the assertions about the draft and pending review posts’ contents be empty strings, nor do we need them: we can’t compile code that tries to use the content of posts in those states any longer. The updated code in `main` is shown in Listing 17-21:

 Filename: src/main.rs

 
```
use blog::Post;

fn main() {
    let mut post = Post::new();

    post.add_text("I ate a salad for lunch today");

    let post = post.request_review();

    let post = post.approve();

    assert_eq!("I ate a salad for lunch today", post.content());
}
```
 Listing 17-21: Modifications to `main` to use the new implementation of the blog post workflow

 The changes we needed to make to `main` to reassign `post` mean that this implementation doesn’t quite follow the object-oriented state pattern anymore: the transformations between the states are no longer encapsulated entirely within the `Post` implementation. However, our gain is that invalid states are now impossible because of the type system and the type checking that happens at compile time! This ensures that certain bugs, such as display of the content of an unpublished post, will be discovered before they make it to production.

 Try the tasks suggested at the start of this section on the `blog` crate as it is after Listing 17-21 to see what you think about the design of this version of the code. Note that some of the tasks might be completed already in this design.

 We’ve seen that even though Rust is capable of implementing object-oriented design patterns, other patterns, such as encoding state into the type system, are also available in Rust. These patterns have different trade-offs. Although you might be very familiar with object-oriented patterns, rethinking the problem to take advantage of Rust’s features can provide benefits, such as preventing some bugs at compile time. Object-oriented patterns won’t always be the best solution in Rust due to certain features, like ownership, that object-oriented languages don’t have.

 Summary
-------

 No matter whether or not you think Rust is an object-oriented language after reading this chapter, you now know that you can use trait objects to get some object-oriented features in Rust. Dynamic dispatch can give your code some flexibility in exchange for a bit of runtime performance. You can use this flexibility to implement object-oriented patterns that can help your code’s maintainability. Rust also has other features, like ownership, that object-oriented languages don’t have. An object-oriented pattern won’t always be the best way to take advantage of Rust’s strengths, but is an available option.

 Next, we’ll look at patterns, which are another of Rust’s features that enable lots of flexibility. We’ve looked at them briefly throughout the book but haven’t seen their full capability yet. Let’s go!



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch17-03-oo-design-patterns.html>

Patterns and Matching
=====================

 *Patterns* are a special syntax in Rust for matching against the structure of types, both complex and simple. Using patterns in conjunction with `match` expressions and other constructs gives you more control over a program’s control flow. A pattern consists of some combination of the following:

 * Literals
* Destructured arrays, enums, structs, or tuples
* Variables
* Wildcards
* Placeholders

 Some example patterns include `x`, `(a, 3)`, and `Some(Color::Red)`. In the contexts in which patterns are valid, these components describe the shape of data. Our program then matches values against the patterns to determine whether it has the correct shape of data to continue running a particular piece of code.

 To use a pattern, we compare it to some value. If the pattern matches the value, we use the value parts in our code. Recall the `match` expressions in Chapter 6 that used patterns, such as the coin-sorting machine example. If the value fits the shape of the pattern, we can use the named pieces. If it doesn’t, the code associated with the pattern won’t run.

 This chapter is a reference on all things related to patterns. We’ll cover the valid places to use patterns, the difference between refutable and irrefutable patterns, and the different kinds of pattern syntax that you might see. By the end of the chapter, you’ll know how to use patterns to express many concepts in a clear way.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch18-00-patterns.html>

Pattern Syntax
==============

 In this section, we gather all the syntax valid in patterns and discuss why and when you might want to use each one.

 ### Matching Literals

 As you saw in Chapter 6, you can match patterns against literals directly. The following code gives some examples:

 
```
fn main() {
    let x = 1;

    match x {
        1 => println!("one"),
        2 => println!("two"),
        3 => println!("three"),
        _ => println!("anything"),
    }
}
```
 This code prints `one` because the value in `x` is 1. This syntax is useful when you want your code to take an action if it gets a particular concrete value.

 ### Matching Named Variables

 Named variables are irrefutable patterns that match any value, and we’ve used them many times in the book. However, there is a complication when you use named variables in `match` expressions. Because `match` starts a new scope, variables declared as part of a pattern inside the `match` expression will shadow those with the same name outside the `match` construct, as is the case with all variables. In Listing 18-11, we declare a variable named `x` with the value `Some(5)` and a variable `y` with the value `10`. We then create a `match` expression on the value `x`. Look at the patterns in the match arms and `println!` at the end, and try to figure out what the code will print before running this code or reading further.

 Filename: src/main.rs

 
```
fn main() {
    let x = Some(5);
    let y = 10;

    match x {
        Some(50) => println!("Got 50"),
        Some(y) => println!("Matched, y = {y}"),
        _ => println!("Default case, x = {:?}", x),
    }

    println!("at the end: x = {:?}, y = {y}", x);
}
```
 Listing 18-11: A `match` expression with an arm that introduces a shadowed variable `y`

 Let’s walk through what happens when the `match` expression runs. The pattern in the first match arm doesn’t match the defined value of `x`, so the code continues.

 The pattern in the second match arm introduces a new variable named `y` that will match any value inside a `Some` value. Because we’re in a new scope inside the `match` expression, this is a new `y` variable, not the `y` we declared at the beginning with the value 10. This new `y` binding will match any value inside a `Some`, which is what we have in `x`. Therefore, this new `y` binds to the inner value of the `Some` in `x`. That value is `5`, so the expression for that arm executes and prints `Matched, y = 5`.

 If `x` had been a `None` value instead of `Some(5)`, the patterns in the first two arms wouldn’t have matched, so the value would have matched to the underscore. We didn’t introduce the `x` variable in the pattern of the underscore arm, so the `x` in the expression is still the outer `x` that hasn’t been shadowed. In this hypothetical case, the `match` would print `Default case, x = None`.

 When the `match` expression is done, its scope ends, and so does the scope of the inner `y`. The last `println!` produces `at the end: x = Some(5), y = 10`.

 To create a `match` expression that compares the values of the outer `x` and `y`, rather than introducing a shadowed variable, we would need to use a match guard conditional instead. We’ll talk about match guards later in the [“Extra Conditionals with Match Guards”](#extra-conditionals-with-match-guards) section.

 ### Multiple Patterns

 In `match` expressions, you can match multiple patterns using the `|` syntax, which is the pattern *or* operator. For example, in the following code we match the value of `x` against the match arms, the first of which has an *or* option, meaning if the value of `x` matches either of the values in that arm, that arm’s code will run:

 
```
fn main() {
    let x = 1;

    match x {
        1 | 2 => println!("one or two"),
        3 => println!("three"),
        _ => println!("anything"),
    }
}
```
 This code prints `one or two`.

 ### Matching Ranges of Values with `..=`

 The `..=` syntax allows us to match to an inclusive range of values. In the following code, when a pattern matches any of the values within the given range, that arm will execute:

 
```
fn main() {
    let x = 5;

    match x {
        1..=5 => println!("one through five"),
        _ => println!("something else"),
    }
}
```
 If `x` is 1, 2, 3, 4, or 5, the first arm will match. This syntax is more convenient for multiple match values than using the `|` operator to express the same idea; if we were to use `|` we would have to specify `1 | 2 | 3 | 4 | 5`. Specifying a range is much shorter, especially if we want to match, say, any number between 1 and 1,000!

 The compiler checks that the range isn’t empty at compile time, and because the only types for which Rust can tell if a range is empty or not are `char` and numeric values, ranges are only allowed with numeric or `char` values.

 Here is an example using ranges of `char` values:

 
```
fn main() {
    let x = 'c';

    match x {
        'a'..='j' => println!("early ASCII letter"),
        'k'..='z' => println!("late ASCII letter"),
        _ => println!("something else"),
    }
}
```
 Rust can tell that `'c'` is within the first pattern’s range and prints `early ASCII letter`.

 ### Destructuring to Break Apart Values

 We can also use patterns to destructure structs, enums, and tuples to use different parts of these values. Let’s walk through each value.

 #### Destructuring Structs

 Listing 18-12 shows a `Point` struct with two fields, `x` and `y`, that we can break apart using a pattern with a `let` statement.

 Filename: src/main.rs

 
```
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let p = Point { x: 0, y: 7 };

    let Point { x: a, y: b } = p;
    assert_eq!(0, a);
    assert_eq!(7, b);
}
```
 Listing 18-12: Destructuring a struct’s fields into separate variables

 This code creates the variables `a` and `b` that match the values of the `x` and `y` fields of the `p` struct. This example shows that the names of the variables in the pattern don’t have to match the field names of the struct. However, it’s common to match the variable names to the field names to make it easier to remember which variables came from which fields. Because of this common usage, and because writing `let Point { x: x, y: y } = p;` contains a lot of duplication, Rust has a shorthand for patterns that match struct fields: you only need to list the name of the struct field, and the variables created from the pattern will have the same names. Listing 18-13 behaves in the same way as the code in Listing 18-12, but the variables created in the `let` pattern are `x` and `y` instead of `a` and `b`.

 Filename: src/main.rs

 
```
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let p = Point { x: 0, y: 7 };

    let Point { x, y } = p;
    assert_eq!(0, x);
    assert_eq!(7, y);
}
```
 Listing 18-13: Destructuring struct fields using struct field shorthand

 This code creates the variables `x` and `y` that match the `x` and `y` fields of the `p` variable. The outcome is that the variables `x` and `y` contain the values from the `p` struct.

 We can also destructure with literal values as part of the struct pattern rather than creating variables for all the fields. Doing so allows us to test some of the fields for particular values while creating variables to destructure the other fields.

 In Listing 18-14, we have a `match` expression that separates `Point` values into three cases: points that lie directly on the `x` axis (which is true when `y = 0`), on the `y` axis (`x = 0`), or neither.

 Filename: src/main.rs

 
```
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let p = Point { x: 0, y: 7 };

    match p {
        Point { x, y: 0 } => println!("On the x axis at {x}"),
        Point { x: 0, y } => println!("On the y axis at {y}"),
        Point { x, y } => {
            println!("On neither axis: ({x}, {y})");
        }
    }
}
```
 Listing 18-14: Destructuring and matching literal values in one pattern

 The first arm will match any point that lies on the `x` axis by specifying that the `y` field matches if its value matches the literal `0`. The pattern still creates an `x` variable that we can use in the code for this arm.

 Similarly, the second arm matches any point on the `y` axis by specifying that the `x` field matches if its value is `0` and creates a variable `y` for the value of the `y` field. The third arm doesn’t specify any literals, so it matches any other `Point` and creates variables for both the `x` and `y` fields.

 In this example, the value `p` matches the second arm by virtue of `x` containing a 0, so this code will print `On the y axis at 7`.

 Remember that a `match` expression stops checking arms once it has found the first matching pattern, so even though `Point { x: 0, y: 0}` is on the `x` axis and the `y` axis, this code would only print `On the x axis at 0`.

 #### Destructuring Enums

 We've destructured enums in this book (for example, Listing 6-5 in Chapter 6), but haven’t yet explicitly discussed that the pattern to destructure an enum corresponds to the way the data stored within the enum is defined. As an example, in Listing 18-15 we use the `Message` enum from Listing 6-2 and write a `match` with patterns that will destructure each inner value.

 Filename: src/main.rs

 
```
enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}

fn main() {
    let msg = Message::ChangeColor(0, 160, 255);

    match msg {
        Message::Quit => {
            println!("The Quit variant has no data to destructure.");
        }
        Message::Move { x, y } => {
            println!("Move in the x direction {x} and in the y direction {y}");
        }
        Message::Write(text) => {
            println!("Text message: {text}");
        }
        Message::ChangeColor(r, g, b) => {
            println!("Change the color to red {r}, green {g}, and blue {b}",)
        }
    }
}
```
 Listing 18-15: Destructuring enum variants that hold different kinds of values

 This code will print `Change the color to red 0, green 160, and blue 255`. Try changing the value of `msg` to see the code from the other arms run.

 For enum variants without any data, like `Message::Quit`, we can’t destructure the value any further. We can only match on the literal `Message::Quit` value, and no variables are in that pattern.

 For struct-like enum variants, such as `Message::Move`, we can use a pattern similar to the pattern we specify to match structs. After the variant name, we place curly brackets and then list the fields with variables so we break apart the pieces to use in the code for this arm. Here we use the shorthand form as we did in Listing 18-13.

 For tuple-like enum variants, like `Message::Write` that holds a tuple with one element and `Message::ChangeColor` that holds a tuple with three elements, the pattern is similar to the pattern we specify to match tuples. The number of variables in the pattern must match the number of elements in the variant we’re matching.

 #### Destructuring Nested Structs and Enums

 So far, our examples have all been matching structs or enums one level deep, but matching can work on nested items too! For example, we can refactor the code in Listing 18-15 to support RGB and HSV colors in the `ChangeColor` message, as shown in Listing 18-16.

 
```
enum Color {
    Rgb(i32, i32, i32),
    Hsv(i32, i32, i32),
}

enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(Color),
}

fn main() {
    let msg = Message::ChangeColor(Color::Hsv(0, 160, 255));

    match msg {
        Message::ChangeColor(Color::Rgb(r, g, b)) => {
            println!("Change color to red {r}, green {g}, and blue {b}");
        }
        Message::ChangeColor(Color::Hsv(h, s, v)) => {
            println!("Change color to hue {h}, saturation {s}, value {v}")
        }
        _ => (),
    }
}
```
 Listing 18-16: Matching on nested enums

 The pattern of the first arm in the `match` expression matches a `Message::ChangeColor` enum variant that contains a `Color::Rgb` variant; then the pattern binds to the three inner `i32` values. The pattern of the second arm also matches a `Message::ChangeColor` enum variant, but the inner enum matches `Color::Hsv` instead. We can specify these complex conditions in one `match` expression, even though two enums are involved.

 #### Destructuring Structs and Tuples

 We can mix, match, and nest destructuring patterns in even more complex ways. The following example shows a complicated destructure where we nest structs and tuples inside a tuple and destructure all the primitive values out:

 
```
fn main() {
    struct Point {
        x: i32,
        y: i32,
    }

    let ((feet, inches), Point { x, y }) = ((3, 10), Point { x: 3, y: -10 });
}
```
 This code lets us break complex types into their component parts so we can use the values we’re interested in separately.

 Destructuring with patterns is a convenient way to use pieces of values, such as the value from each field in a struct, separately from each other.

 ### Ignoring Values in a Pattern

 You’ve seen that it’s sometimes useful to ignore values in a pattern, such as in the last arm of a `match`, to get a catchall that doesn’t actually do anything but does account for all remaining possible values. There are a few ways to ignore entire values or parts of values in a pattern: using the `_` pattern (which you’ve seen), using the `_` pattern within another pattern, using a name that starts with an underscore, or using `..` to ignore remaining parts of a value. Let’s explore how and why to use each of these patterns.

 #### Ignoring an Entire Value with `_`

 We’ve used the underscore as a wildcard pattern that will match any value but not bind to the value. This is especially useful as the last arm in a `match` expression, but we can also use it in any pattern, including function parameters, as shown in Listing 18-17.

 Filename: src/main.rs

 
```
fn foo(_: i32, y: i32) {
    println!("This code only uses the y parameter: {}", y);
}

fn main() {
    foo(3, 4);
}
```
 Listing 18-17: Using `_` in a function signature

 This code will completely ignore the value `3` passed as the first argument, and will print `This code only uses the y parameter: 4`.

 In most cases when you no longer need a particular function parameter, you would change the signature so it doesn’t include the unused parameter. Ignoring a function parameter can be especially useful in cases when, for example, you're implementing a trait when you need a certain type signature but the function body in your implementation doesn’t need one of the parameters. You then avoid getting a compiler warning about unused function parameters, as you would if you used a name instead.

 #### Ignoring Parts of a Value with a Nested `_`

 We can also use `_` inside another pattern to ignore just part of a value, for example, when we want to test for only part of a value but have no use for the other parts in the corresponding code we want to run. Listing 18-18 shows code responsible for managing a setting’s value. The business requirements are that the user should not be allowed to overwrite an existing customization of a setting but can unset the setting and give it a value if it is currently unset.

 
```
fn main() {
    let mut setting_value = Some(5);
    let new_setting_value = Some(10);

    match (setting_value, new_setting_value) {
        (Some(_), Some(_)) => {
            println!("Can't overwrite an existing customized value");
        }
        _ => {
            setting_value = new_setting_value;
        }
    }

    println!("setting is {:?}", setting_value);
}
```
 Listing 18-18: Using an underscore within patterns that match `Some` variants when we don’t need to use the value inside the `Some`

 This code will print `Can't overwrite an existing customized value` and then `setting is Some(5)`. In the first match arm, we don’t need to match on or use the values inside either `Some` variant, but we do need to test for the case when `setting_value` and `new_setting_value` are the `Some` variant. In that case, we print the reason for not changing `setting_value`, and it doesn’t get changed.

 In all other cases (if either `setting_value` or `new_setting_value` are `None`) expressed by the `_` pattern in the second arm, we want to allow `new_setting_value` to become `setting_value`.

 We can also use underscores in multiple places within one pattern to ignore particular values. Listing 18-19 shows an example of ignoring the second and fourth values in a tuple of five items.

 
```
fn main() {
    let numbers = (2, 4, 8, 16, 32);

    match numbers {
        (first, _, third, _, fifth) => {
            println!("Some numbers: {first}, {third}, {fifth}")
        }
    }
}
```
 Listing 18-19: Ignoring multiple parts of a tuple

 This code will print `Some numbers: 2, 8, 32`, and the values 4 and 16 will be ignored.

 #### Ignoring an Unused Variable by Starting Its Name with `_`

 If you create a variable but don’t use it anywhere, Rust will usually issue a warning because an unused variable could be a bug. However, sometimes it’s useful to be able to create a variable you won’t use yet, such as when you’re prototyping or just starting a project. In this situation, you can tell Rust not to warn you about the unused variable by starting the name of the variable with an underscore. In Listing 18-20, we create two unused variables, but when we compile this code, we should only get a warning about one of them.

 Filename: src/main.rs

 
```
fn main() {
    let _x = 5;
    let y = 10;
}
```
 Listing 18-20: Starting a variable name with an underscore to avoid getting unused variable warnings

 Here we get a warning about not using the variable `y`, but we don’t get a warning about not using `_x`.

 Note that there is a subtle difference between using only `_` and using a name that starts with an underscore. The syntax `_x` still binds the value to the variable, whereas `_` doesn’t bind at all. To show a case where this distinction matters, Listing 18-21 will provide us with an error.

 
```
fn main() {
    let s = Some(String::from("Hello!"));

    if let Some(_s) = s {
        println!("found a string");
    }

    println!("{:?}", s);
}
```
 Listing 18-21: An unused variable starting with an underscore still binds the value, which might take ownership of the value

 We’ll receive an error because the `s` value will still be moved into `_s`, which prevents us from using `s` again. However, using the underscore by itself doesn’t ever bind to the value. Listing 18-22 will compile without any errors because `s` doesn’t get moved into `_`.

 
```
fn main() {
    let s = Some(String::from("Hello!"));

    if let Some(_) = s {
        println!("found a string");
    }

    println!("{:?}", s);
}
```
 Listing 18-22: Using an underscore does not bind the value

 This code works just fine because we never bind `s` to anything; it isn’t moved.

 #### Ignoring Remaining Parts of a Value with `..`

 With values that have many parts, we can use the `..` syntax to use specific parts and ignore the rest, avoiding the need to list underscores for each ignored value. The `..` pattern ignores any parts of a value that we haven’t explicitly matched in the rest of the pattern. In Listing 18-23, we have a `Point` struct that holds a coordinate in three-dimensional space. In the `match` expression, we want to operate only on the `x` coordinate and ignore the values in the `y` and `z` fields.

 
```
fn main() {
    struct Point {
        x: i32,
        y: i32,
        z: i32,
    }

    let origin = Point { x: 0, y: 0, z: 0 };

    match origin {
        Point { x, .. } => println!("x is {}", x),
    }
}
```
 Listing 18-23: Ignoring all fields of a `Point` except for `x` by using `..`

 We list the `x` value and then just include the `..` pattern. This is quicker than having to list `y: _` and `z: _`, particularly when we’re working with structs that have lots of fields in situations where only one or two fields are relevant.

 The syntax `..` will expand to as many values as it needs to be. Listing 18-24 shows how to use `..` with a tuple.

 Filename: src/main.rs

 
```
fn main() {
    let numbers = (2, 4, 8, 16, 32);

    match numbers {
        (first, .., last) => {
            println!("Some numbers: {first}, {last}");
        }
    }
}
```
 Listing 18-24: Matching only the first and last values in a tuple and ignoring all other values

 In this code, the first and last value are matched with `first` and `last`. The `..` will match and ignore everything in the middle.

 However, using `..` must be unambiguous. If it is unclear which values are intended for matching and which should be ignored, Rust will give us an error. Listing 18-25 shows an example of using `..` ambiguously, so it will not compile.

 Filename: src/main.rs

 
```
fn main() {
    let numbers = (2, 4, 8, 16, 32);

    match numbers {
        (.., second, ..) => {
            println!("Some numbers: {}", second)
        },
    }
}
```
 Listing 18-25: An attempt to use `..` in an ambiguous way

 When we compile this example, we get this error:

 
```
$ cargo run
   Compiling patterns v0.1.0 (file:///projects/patterns)
error: `..` can only be used once per tuple pattern
 --> src/main.rs:5:22
  |
5 |         (.., second, ..) => {
  |          --          ^^ can only be used once per tuple pattern
  |          |
  |          previously used here

error: could not compile `patterns` due to previous error

```
 It’s impossible for Rust to determine how many values in the tuple to ignore before matching a value with `second` and then how many further values to ignore thereafter. This code could mean that we want to ignore `2`, bind `second` to `4`, and then ignore `8`, `16`, and `32`; or that we want to ignore `2` and `4`, bind `second` to `8`, and then ignore `16` and `32`; and so forth. The variable name `second` doesn’t mean anything special to Rust, so we get a compiler error because using `..` in two places like this is ambiguous.

 ### Extra Conditionals with Match Guards

 A *match guard* is an additional `if` condition, specified after the pattern in a `match` arm, that must also match for that arm to be chosen. Match guards are useful for expressing more complex ideas than a pattern alone allows.

 The condition can use variables created in the pattern. Listing 18-26 shows a `match` where the first arm has the pattern `Some(x)` and also has a match guard of `if x % 2 == 0` (which will be true if the number is even).

 
```
fn main() {
    let num = Some(4);

    match num {
        Some(x) if x % 2 == 0 => println!("The number {} is even", x),
        Some(x) => println!("The number {} is odd", x),
        None => (),
    }
}
```
 Listing 18-26: Adding a match guard to a pattern

 This example will print `The number 4 is even`. When `num` is compared to the pattern in the first arm, it matches, because `Some(4)` matches `Some(x)`. Then the match guard checks whether the remainder of dividing `x` by 2 is equal to 0, and because it is, the first arm is selected.

 If `num` had been `Some(5)` instead, the match guard in the first arm would have been false because the remainder of 5 divided by 2 is 1, which is not equal to 0. Rust would then go to the second arm, which would match because the second arm doesn’t have a match guard and therefore matches any `Some` variant.

 There is no way to express the `if x % 2 == 0` condition within a pattern, so the match guard gives us the ability to express this logic. The downside of this additional expressiveness is that the compiler doesn't try to check for exhaustiveness when match guard expressions are involved.

 In Listing 18-11, we mentioned that we could use match guards to solve our pattern-shadowing problem. Recall that we created a new variable inside the pattern in the `match` expression instead of using the variable outside the `match`. That new variable meant we couldn’t test against the value of the outer variable. Listing 18-27 shows how we can use a match guard to fix this problem.

 Filename: src/main.rs

 
```
fn main() {
    let x = Some(5);
    let y = 10;

    match x {
        Some(50) => println!("Got 50"),
        Some(n) if n == y => println!("Matched, n = {n}"),
        _ => println!("Default case, x = {:?}", x),
    }

    println!("at the end: x = {:?}, y = {y}", x);
}
```
 Listing 18-27: Using a match guard to test for equality with an outer variable

 This code will now print `Default case, x = Some(5)`. The pattern in the second match arm doesn’t introduce a new variable `y` that would shadow the outer `y`, meaning we can use the outer `y` in the match guard. Instead of specifying the pattern as `Some(y)`, which would have shadowed the outer `y`, we specify `Some(n)`. This creates a new variable `n` that doesn’t shadow anything because there is no `n` variable outside the `match`.

 The match guard `if n == y` is not a pattern and therefore doesn’t introduce new variables. This `y` *is* the outer `y` rather than a new shadowed `y`, and we can look for a value that has the same value as the outer `y` by comparing `n` to `y`.

 You can also use the *or* operator `|` in a match guard to specify multiple patterns; the match guard condition will apply to all the patterns. Listing 18-28 shows the precedence when combining a pattern that uses `|` with a match guard. The important part of this example is that the `if y` match guard applies to `4`, `5`, *and* `6`, even though it might look like `if y` only applies to `6`.

 
```
fn main() {
    let x = 4;
    let y = false;

    match x {
        4 | 5 | 6 if y => println!("yes"),
        _ => println!("no"),
    }
}
```
 Listing 18-28: Combining multiple patterns with a match guard

 The match condition states that the arm only matches if the value of `x` is equal to `4`, `5`, or `6` *and* if `y` is `true`. When this code runs, the pattern of the first arm matches because `x` is `4`, but the match guard `if y` is false, so the first arm is not chosen. The code moves on to the second arm, which does match, and this program prints `no`. The reason is that the `if` condition applies to the whole pattern `4 | 5 | 6`, not only to the last value `6`. In other words, the precedence of a match guard in relation to a pattern behaves like this:

 
```
(4 | 5 | 6) if y => ...

```
 rather than this:

 
```
4 | 5 | (6 if y) => ...

```
 After running the code, the precedence behavior is evident: if the match guard were applied only to the final value in the list of values specified using the `|` operator, the arm would have matched and the program would have printed `yes`.

 ### 
`@` Bindings

 The *at* operator `@` lets us create a variable that holds a value at the same time as we’re testing that value for a pattern match. In Listing 18-29, we want to test that a `Message::Hello` `id` field is within the range `3..=7`. We also want to bind the value to the variable `id_variable` so we can use it in the code associated with the arm. We could name this variable `id`, the same as the field, but for this example we’ll use a different name.

 
```
fn main() {
    enum Message {
        Hello { id: i32 },
    }

    let msg = Message::Hello { id: 5 };

    match msg {
        Message::Hello {
            id: id_variable @ 3..=7,
        } => println!("Found an id in range: {}", id_variable),
        Message::Hello { id: 10..=12 } => {
            println!("Found an id in another range")
        }
        Message::Hello { id } => println!("Found some other id: {}", id),
    }
}
```
 Listing 18-29: Using `@` to bind to a value in a pattern while also testing it

 This example will print `Found an id in range: 5`. By specifying `id_variable @` before the range `3..=7`, we’re capturing whatever value matched the range while also testing that the value matched the range pattern.

 In the second arm, where we only have a range specified in the pattern, the code associated with the arm doesn’t have a variable that contains the actual value of the `id` field. The `id` field’s value could have been 10, 11, or 12, but the code that goes with that pattern doesn’t know which it is. The pattern code isn’t able to use the value from the `id` field, because we haven’t saved the `id` value in a variable.

 In the last arm, where we’ve specified a variable without a range, we do have the value available to use in the arm’s code in a variable named `id`. The reason is that we’ve used the struct field shorthand syntax. But we haven’t applied any test to the value in the `id` field in this arm, as we did with the first two arms: any value would match this pattern.

 Using `@` lets us test a value and save it in a variable within one pattern.

 Summary
-------

 Rust’s patterns are very useful in distinguishing between different kinds of data. When used in `match` expressions, Rust ensures your patterns cover every possible value, or your program won’t compile. Patterns in `let` statements and function parameters make those constructs more useful, enabling the destructuring of values into smaller parts at the same time as assigning to variables. We can create simple or complex patterns to suit our needs.

 Next, for the penultimate chapter of the book, we’ll look at some advanced aspects of a variety of Rust’s features.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch18-03-pattern-syntax.html>

Unsafe Rust
===========

 All the code we’ve discussed so far has had Rust’s memory safety guarantees enforced at compile time. However, Rust has a second language hidden inside it that doesn’t enforce these memory safety guarantees: it’s called *unsafe Rust* and works just like regular Rust, but gives us extra superpowers.

 Unsafe Rust exists because, by nature, static analysis is conservative. When the compiler tries to determine whether or not code upholds the guarantees, it’s better for it to reject some valid programs than to accept some invalid programs. Although the code *might* be okay, if the Rust compiler doesn’t have enough information to be confident, it will reject the code. In these cases, you can use unsafe code to tell the compiler, “Trust me, I know what I’m doing.” Be warned, however, that you use unsafe Rust at your own risk: if you use unsafe code incorrectly, problems can occur due to memory unsafety, such as null pointer dereferencing.

 Another reason Rust has an unsafe alter ego is that the underlying computer hardware is inherently unsafe. If Rust didn’t let you do unsafe operations, you couldn’t do certain tasks. Rust needs to allow you to do low-level systems programming, such as directly interacting with the operating system or even writing your own operating system. Working with low-level systems programming is one of the goals of the language. Let’s explore what we can do with unsafe Rust and how to do it.

 ### Unsafe Superpowers

 To switch to unsafe Rust, use the `unsafe` keyword and then start a new block that holds the unsafe code. You can take five actions in unsafe Rust that you can’t in safe Rust, which we call *unsafe superpowers*. Those superpowers include the ability to:

 * Dereference a raw pointer
* Call an unsafe function or method
* Access or modify a mutable static variable
* Implement an unsafe trait
* Access fields of `union`s

 It’s important to understand that `unsafe` doesn’t turn off the borrow checker or disable any other of Rust’s safety checks: if you use a reference in unsafe code, it will still be checked. The `unsafe` keyword only gives you access to these five features that are then not checked by the compiler for memory safety. You’ll still get some degree of safety inside of an unsafe block.

 In addition, `unsafe` does not mean the code inside the block is necessarily dangerous or that it will definitely have memory safety problems: the intent is that as the programmer, you’ll ensure the code inside an `unsafe` block will access memory in a valid way.

 People are fallible, and mistakes will happen, but by requiring these five unsafe operations to be inside blocks annotated with `unsafe` you’ll know that any errors related to memory safety must be within an `unsafe` block. Keep `unsafe` blocks small; you’ll be thankful later when you investigate memory bugs.

 To isolate unsafe code as much as possible, it’s best to enclose unsafe code within a safe abstraction and provide a safe API, which we’ll discuss later in the chapter when we examine unsafe functions and methods. Parts of the standard library are implemented as safe abstractions over unsafe code that has been audited. Wrapping unsafe code in a safe abstraction prevents uses of `unsafe` from leaking out into all the places that you or your users might want to use the functionality implemented with `unsafe` code, because using a safe abstraction is safe.

 Let’s look at each of the five unsafe superpowers in turn. We’ll also look at some abstractions that provide a safe interface to unsafe code.

 ### Dereferencing a Raw Pointer

 In Chapter 4, in the [“Dangling References”](ch04-02-references-and-borrowing#dangling-references) section, we mentioned that the compiler ensures references are always valid. Unsafe Rust has two new types called *raw pointers* that are similar to references. As with references, raw pointers can be immutable or mutable and are written as `*const T` and `*mut T`, respectively. The asterisk isn’t the dereference operator; it’s part of the type name. In the context of raw pointers, *immutable* means that the pointer can’t be directly assigned to after being dereferenced.

 Different from references and smart pointers, raw pointers:

 * Are allowed to ignore the borrowing rules by having both immutable and mutable pointers or multiple mutable pointers to the same location
* Aren’t guaranteed to point to valid memory
* Are allowed to be null
* Don’t implement any automatic cleanup

 By opting out of having Rust enforce these guarantees, you can give up guaranteed safety in exchange for greater performance or the ability to interface with another language or hardware where Rust’s guarantees don’t apply.

 Listing 19-1 shows how to create an immutable and a mutable raw pointer from references.

 
```
fn main() {
    let mut num = 5;

    let r1 = &num as *const i32;
    let r2 = &mut num as *mut i32;
}
```
 Listing 19-1: Creating raw pointers from references

 Notice that we don’t include the `unsafe` keyword in this code. We can create raw pointers in safe code; we just can’t dereference raw pointers outside an unsafe block, as you’ll see in a bit.

 We’ve created raw pointers by using `as` to cast an immutable and a mutable reference into their corresponding raw pointer types. Because we created them directly from references guaranteed to be valid, we know these particular raw pointers are valid, but we can’t make that assumption about just any raw pointer.

 To demonstrate this, next we’ll create a raw pointer whose validity we can’t be so certain of. Listing 19-2 shows how to create a raw pointer to an arbitrary location in memory. Trying to use arbitrary memory is undefined: there might be data at that address or there might not, the compiler might optimize the code so there is no memory access, or the program might error with a segmentation fault. Usually, there is no good reason to write code like this, but it is possible.

 
```
fn main() {
    let address = 0x012345usize;
    let r = address as *const i32;
}
```
 Listing 19-2: Creating a raw pointer to an arbitrary memory address

 Recall that we can create raw pointers in safe code, but we can’t *dereference* raw pointers and read the data being pointed to. In Listing 19-3, we use the dereference operator `*` on a raw pointer that requires an `unsafe` block.

 
```
fn main() {
    let mut num = 5;

    let r1 = &num as *const i32;
    let r2 = &mut num as *mut i32;

    unsafe {
        println!("r1 is: {}", *r1);
        println!("r2 is: {}", *r2);
    }
}
```
 Listing 19-3: Dereferencing raw pointers within an `unsafe` block

 Creating a pointer does no harm; it’s only when we try to access the value that it points at that we might end up dealing with an invalid value.

 Note also that in Listing 19-1 and 19-3, we created `*const i32` and `*mut i32` raw pointers that both pointed to the same memory location, where `num` is stored. If we instead tried to create an immutable and a mutable reference to `num`, the code would not have compiled because Rust’s ownership rules don’t allow a mutable reference at the same time as any immutable references. With raw pointers, we can create a mutable pointer and an immutable pointer to the same location and change data through the mutable pointer, potentially creating a data race. Be careful!

 With all of these dangers, why would you ever use raw pointers? One major use case is when interfacing with C code, as you’ll see in the next section, [“Calling an Unsafe Function or Method.”](#calling-an-unsafe-function-or-method) Another case is when building up safe abstractions that the borrow checker doesn’t understand. We’ll introduce unsafe functions and then look at an example of a safe abstraction that uses unsafe code.

 ### Calling an Unsafe Function or Method

 The second type of operation you can perform in an unsafe block is calling unsafe functions. Unsafe functions and methods look exactly like regular functions and methods, but they have an extra `unsafe` before the rest of the definition. The `unsafe` keyword in this context indicates the function has requirements we need to uphold when we call this function, because Rust can’t guarantee we’ve met these requirements. By calling an unsafe function within an `unsafe` block, we’re saying that we’ve read this function’s documentation and take responsibility for upholding the function’s contracts.

 Here is an unsafe function named `dangerous` that doesn’t do anything in its body:

 
```
fn main() {
    unsafe fn dangerous() {}

    unsafe {
        dangerous();
    }
}
```
 We must call the `dangerous` function within a separate `unsafe` block. If we try to call `dangerous` without the `unsafe` block, we’ll get an error:

 
```
$ cargo run
   Compiling unsafe-example v0.1.0 (file:///projects/unsafe-example)
error[E0133]: call to unsafe function is unsafe and requires unsafe function or block
 --> src/main.rs:4:5
  |
4 |     dangerous();
  |     ^^^^^^^^^^^ call to unsafe function
  |
  = note: consult the function's documentation for information on how to avoid undefined behavior

For more information about this error, try `rustc --explain E0133`.
error: could not compile `unsafe-example` due to previous error

```
 With the `unsafe` block, we’re asserting to Rust that we’ve read the function’s documentation, we understand how to use it properly, and we’ve verified that we’re fulfilling the contract of the function.

 Bodies of unsafe functions are effectively `unsafe` blocks, so to perform other unsafe operations within an unsafe function, we don’t need to add another `unsafe` block.

 #### Creating a Safe Abstraction over Unsafe Code

 Just because a function contains unsafe code doesn’t mean we need to mark the entire function as unsafe. In fact, wrapping unsafe code in a safe function is a common abstraction. As an example, let’s study the `split_at_mut` function from the standard library, which requires some unsafe code. We’ll explore how we might implement it. This safe method is defined on mutable slices: it takes one slice and makes it two by splitting the slice at the index given as an argument. Listing 19-4 shows how to use `split_at_mut`.

 
```
fn main() {
    let mut v = vec![1, 2, 3, 4, 5, 6];

    let r = &mut v[..];

    let (a, b) = r.split_at_mut(3);

    assert_eq!(a, &mut [1, 2, 3]);
    assert_eq!(b, &mut [4, 5, 6]);
}
```
 Listing 19-4: Using the safe `split_at_mut` function

 We can’t implement this function using only safe Rust. An attempt might look something like Listing 19-5, which won’t compile. For simplicity, we’ll implement `split_at_mut` as a function rather than a method and only for slices of `i32` values rather than for a generic type `T`.

 
```
fn split_at_mut(values: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
    let len = values.len();

    assert!(mid <= len);

    (&mut values[..mid], &mut values[mid..])
}

fn main() {
    let mut vector = vec![1, 2, 3, 4, 5, 6];
    let (left, right) = split_at_mut(&mut vector, 3);
}
```
 Listing 19-5: An attempted implementation of `split_at_mut` using only safe Rust

 This function first gets the total length of the slice. Then it asserts that the index given as a parameter is within the slice by checking whether it’s less than or equal to the length. The assertion means that if we pass an index that is greater than the length to split the slice at, the function will panic before it attempts to use that index.

 Then we return two mutable slices in a tuple: one from the start of the original slice to the `mid` index and another from `mid` to the end of the slice.

 When we try to compile the code in Listing 19-5, we’ll get an error.

 
```
$ cargo run
   Compiling unsafe-example v0.1.0 (file:///projects/unsafe-example)
error[E0499]: cannot borrow `*values` as mutable more than once at a time
 --> src/main.rs:6:31
  |
1 | fn split_at_mut(values: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
  |                         - let's call the lifetime of this reference `'1`
...
6 |     (&mut values[..mid], &mut values[mid..])
  |     --------------------------^^^^^^--------
  |     |     |                   |
  |     |     |                   second mutable borrow occurs here
  |     |     first mutable borrow occurs here
  |     returning this value requires that `*values` is borrowed for `'1`

For more information about this error, try `rustc --explain E0499`.
error: could not compile `unsafe-example` due to previous error

```
 Rust’s borrow checker can’t understand that we’re borrowing different parts of the slice; it only knows that we’re borrowing from the same slice twice. Borrowing different parts of a slice is fundamentally okay because the two slices aren’t overlapping, but Rust isn’t smart enough to know this. When we know code is okay, but Rust doesn’t, it’s time to reach for unsafe code.

 Listing 19-6 shows how to use an `unsafe` block, a raw pointer, and some calls to unsafe functions to make the implementation of `split_at_mut` work.

 
```
use std::slice;

fn split_at_mut(values: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
    let len = values.len();
    let ptr = values.as_mut_ptr();

    assert!(mid <= len);

    unsafe {
        (
            slice::from_raw_parts_mut(ptr, mid),
            slice::from_raw_parts_mut(ptr.add(mid), len - mid),
        )
    }
}

fn main() {
    let mut vector = vec![1, 2, 3, 4, 5, 6];
    let (left, right) = split_at_mut(&mut vector, 3);
}
```
 Listing 19-6: Using unsafe code in the implementation of the `split_at_mut` function

 Recall from [“The Slice Type”](ch04-03-slices#the-slice-type) section in Chapter 4 that slices are a pointer to some data and the length of the slice. We use the `len` method to get the length of a slice and the `as_mut_ptr` method to access the raw pointer of a slice. In this case, because we have a mutable slice to `i32` values, `as_mut_ptr` returns a raw pointer with the type `*mut i32`, which we’ve stored in the variable `ptr`.

 We keep the assertion that the `mid` index is within the slice. Then we get to the unsafe code: the `slice::from_raw_parts_mut` function takes a raw pointer and a length, and it creates a slice. We use this function to create a slice that starts from `ptr` and is `mid` items long. Then we call the `add` method on `ptr` with `mid` as an argument to get a raw pointer that starts at `mid`, and we create a slice using that pointer and the remaining number of items after `mid` as the length.

 The function `slice::from_raw_parts_mut` is unsafe because it takes a raw pointer and must trust that this pointer is valid. The `add` method on raw pointers is also unsafe, because it must trust that the offset location is also a valid pointer. Therefore, we had to put an `unsafe` block around our calls to `slice::from_raw_parts_mut` and `add` so we could call them. By looking at the code and by adding the assertion that `mid` must be less than or equal to `len`, we can tell that all the raw pointers used within the `unsafe` block will be valid pointers to data within the slice. This is an acceptable and appropriate use of `unsafe`.

 Note that we don’t need to mark the resulting `split_at_mut` function as `unsafe`, and we can call this function from safe Rust. We’ve created a safe abstraction to the unsafe code with an implementation of the function that uses `unsafe` code in a safe way, because it creates only valid pointers from the data this function has access to.

 In contrast, the use of `slice::from_raw_parts_mut` in Listing 19-7 would likely crash when the slice is used. This code takes an arbitrary memory location and creates a slice 10,000 items long.

 
```
fn main() {
    use std::slice;

    let address = 0x01234usize;
    let r = address as *mut i32;

    let values: &[i32] = unsafe { slice::from_raw_parts_mut(r, 10000) };
}
```
 Listing 19-7: Creating a slice from an arbitrary memory location

 We don’t own the memory at this arbitrary location, and there is no guarantee that the slice this code creates contains valid `i32` values. Attempting to use `values` as though it’s a valid slice results in undefined behavior.

 #### Using `extern` Functions to Call External Code

 Sometimes, your Rust code might need to interact with code written in another language. For this, Rust has the keyword `extern` that facilitates the creation and use of a *Foreign Function Interface (FFI)*. An FFI is a way for a programming language to define functions and enable a different (foreign) programming language to call those functions.

 Listing 19-8 demonstrates how to set up an integration with the `abs` function from the C standard library. Functions declared within `extern` blocks are always unsafe to call from Rust code. The reason is that other languages don’t enforce Rust’s rules and guarantees, and Rust can’t check them, so responsibility falls on the programmer to ensure safety.

 Filename: src/main.rs

 
```
extern "C" {
    fn abs(input: i32) -> i32;
}

fn main() {
    unsafe {
        println!("Absolute value of -3 according to C: {}", abs(-3));
    }
}
```
 Listing 19-8: Declaring and calling an `extern` function defined in another language

 Within the `extern "C"` block, we list the names and signatures of external functions from another language we want to call. The `"C"` part defines which *application binary interface (ABI)* the external function uses: the ABI defines how to call the function at the assembly level. The `"C"` ABI is the most common and follows the C programming language’s ABI.

 
>  #### Calling Rust Functions from Other Languages
> 
>  We can also use `extern` to create an interface that allows other languages to call Rust functions. Instead of creating a whole `extern` block, we add the `extern` keyword and specify the ABI to use just before the `fn` keyword for the relevant function. We also need to add a `#[no_mangle]` annotation to tell the Rust compiler not to mangle the name of this function. *Mangling* is when a compiler changes the name we’ve given a function to a different name that contains more information for other parts of the compilation process to consume but is less human readable. Every programming language compiler mangles names slightly differently, so for a Rust function to be nameable by other languages, we must disable the Rust compiler’s name mangling.
> 
>  In the following example, we make the `call_from_c` function accessible from C code, after it’s compiled to a shared library and linked from C:
> 
>  
> ```
> #![allow(unused)]
> fn main() {
> #[no_mangle]
> pub extern "C" fn call_from_c() {
>     println!("Just called a Rust function from C!");
> }
> }
> ```
>  This usage of `extern` does not require `unsafe`.
> 
>  

 ### Accessing or Modifying a Mutable Static Variable

 In this book, we’ve not yet talked about *global variables*, which Rust does support but can be problematic with Rust’s ownership rules. If two threads are accessing the same mutable global variable, it can cause a data race.

 In Rust, global variables are called *static* variables. Listing 19-9 shows an example declaration and use of a static variable with a string slice as a value.

 Filename: src/main.rs

 
```
static HELLO_WORLD: &str = "Hello, world!";

fn main() {
    println!("name is: {}", HELLO_WORLD);
}
```
 Listing 19-9: Defining and using an immutable static variable

 Static variables are similar to constants, which we discussed in the [“Differences Between Variables and Constants”](ch03-01-variables-and-mutability#constants) section in Chapter 3. The names of static variables are in `SCREAMING_SNAKE_CASE` by convention. Static variables can only store references with the `'static` lifetime, which means the Rust compiler can figure out the lifetime and we aren’t required to annotate it explicitly. Accessing an immutable static variable is safe.

 A subtle difference between constants and immutable static variables is that values in a static variable have a fixed address in memory. Using the value will always access the same data. Constants, on the other hand, are allowed to duplicate their data whenever they’re used. Another difference is that static variables can be mutable. Accessing and modifying mutable static variables is *unsafe*. Listing 19-10 shows how to declare, access, and modify a mutable static variable named `COUNTER`.

 Filename: src/main.rs

 
```
static mut COUNTER: u32 = 0;

fn add_to_count(inc: u32) {
    unsafe {
        COUNTER += inc;
    }
}

fn main() {
    add_to_count(3);

    unsafe {
        println!("COUNTER: {}", COUNTER);
    }
}
```
 Listing 19-10: Reading from or writing to a mutable static variable is unsafe

 As with regular variables, we specify mutability using the `mut` keyword. Any code that reads or writes from `COUNTER` must be within an `unsafe` block. This code compiles and prints `COUNTER: 3` as we would expect because it’s single threaded. Having multiple threads access `COUNTER` would likely result in data races.

 With mutable data that is globally accessible, it’s difficult to ensure there are no data races, which is why Rust considers mutable static variables to be unsafe. Where possible, it’s preferable to use the concurrency techniques and thread-safe smart pointers we discussed in Chapter 16 so the compiler checks that data accessed from different threads is done safely.

 ### Implementing an Unsafe Trait

 We can use `unsafe` to implement an unsafe trait. A trait is unsafe when at least one of its methods has some invariant that the compiler can’t verify. We declare that a trait is `unsafe` by adding the `unsafe` keyword before `trait` and marking the implementation of the trait as `unsafe` too, as shown in Listing 19-11.

 
```
unsafe trait Foo {
    // methods go here
}

unsafe impl Foo for i32 {
    // method implementations go here
}

fn main() {}
```
 Listing 19-11: Defining and implementing an unsafe trait

 By using `unsafe impl`, we’re promising that we’ll uphold the invariants that the compiler can’t verify.

 As an example, recall the `Sync` and `Send` marker traits we discussed in the [“Extensible Concurrency with the `Sync` and `Send` Traits”](ch16-04-extensible-concurrency-sync-and-send#extensible-concurrency-with-the-sync-and-send-traits) section in Chapter 16: the compiler implements these traits automatically if our types are composed entirely of `Send` and `Sync` types. If we implement a type that contains a type that is not `Send` or `Sync`, such as raw pointers, and we want to mark that type as `Send` or `Sync`, we must use `unsafe`. Rust can’t verify that our type upholds the guarantees that it can be safely sent across threads or accessed from multiple threads; therefore, we need to do those checks manually and indicate as such with `unsafe`.

 ### Accessing Fields of a Union

 The final action that works only with `unsafe` is accessing fields of a *union*. A `union` is similar to a `struct`, but only one declared field is used in a particular instance at one time. Unions are primarily used to interface with unions in C code. Accessing union fields is unsafe because Rust can’t guarantee the type of the data currently being stored in the union instance. You can learn more about unions in [the Rust Reference](../reference/items/unions).

 ### When to Use Unsafe Code

 Using `unsafe` to take one of the five actions (superpowers) just discussed isn’t wrong or even frowned upon. But it is trickier to get `unsafe` code correct because the compiler can’t help uphold memory safety. When you have a reason to use `unsafe` code, you can do so, and having the explicit `unsafe` annotation makes it easier to track down the source of problems when they occur.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch19-01-unsafe-rust.html>

Advanced Traits
===============

 We first covered traits in the [“Traits: Defining Shared Behavior”](ch10-02-traits#traits-defining-shared-behavior) section of Chapter 10, but we didn’t discuss the more advanced details. Now that you know more about Rust, we can get into the nitty-gritty.

 ### Specifying Placeholder Types in Trait Definitions with Associated Types

 *Associated types* connect a type placeholder with a trait such that the trait method definitions can use these placeholder types in their signatures. The implementor of a trait will specify the concrete type to be used instead of the placeholder type for the particular implementation. That way, we can define a trait that uses some types without needing to know exactly what those types are until the trait is implemented.

 We’ve described most of the advanced features in this chapter as being rarely needed. Associated types are somewhere in the middle: they’re used more rarely than features explained in the rest of the book but more commonly than many of the other features discussed in this chapter.

 One example of a trait with an associated type is the `Iterator` trait that the standard library provides. The associated type is named `Item` and stands in for the type of the values the type implementing the `Iterator` trait is iterating over. The definition of the `Iterator` trait is as shown in Listing 19-12.

 
```
pub trait Iterator {
    type Item;

    fn next(&mut self) -> Option<Self::Item>;
}
```
 Listing 19-12: The definition of the `Iterator` trait that has an associated type `Item`

 The type `Item` is a placeholder, and the `next` method’s definition shows that it will return values of type `Option<Self::Item>`. Implementors of the `Iterator` trait will specify the concrete type for `Item`, and the `next` method will return an `Option` containing a value of that concrete type.

 Associated types might seem like a similar concept to generics, in that the latter allow us to define a function without specifying what types it can handle. To examine the difference between the two concepts, we’ll look at an implementation of the `Iterator` trait on a type named `Counter` that specifies the `Item` type is `u32`:

 Filename: src/lib.rs

 
```
struct Counter {
    count: u32,
}

impl Counter {
    fn new() -> Counter {
        Counter { count: 0 }
    }
}

impl Iterator for Counter {
    type Item = u32;

    fn next(&mut self) -> Option<Self::Item> {
        // --snip--
        if self.count < 5 {
            self.count += 1;
            Some(self.count)
        } else {
            None
        }
    }
}
```
 This syntax seems comparable to that of generics. So why not just define the `Iterator` trait with generics, as shown in Listing 19-13?

 
```
pub trait Iterator<T> {
    fn next(&mut self) -> Option<T>;
}
```
 Listing 19-13: A hypothetical definition of the `Iterator` trait using generics

 The difference is that when using generics, as in Listing 19-13, we must annotate the types in each implementation; because we can also implement `Iterator<String> for Counter` or any other type, we could have multiple implementations of `Iterator` for `Counter`. In other words, when a trait has a generic parameter, it can be implemented for a type multiple times, changing the concrete types of the generic type parameters each time. When we use the `next` method on `Counter`, we would have to provide type annotations to indicate which implementation of `Iterator` we want to use.

 With associated types, we don’t need to annotate types because we can’t implement a trait on a type multiple times. In Listing 19-12 with the definition that uses associated types, we can only choose what the type of `Item` will be once, because there can only be one `impl Iterator for Counter`. We don’t have to specify that we want an iterator of `u32` values everywhere that we call `next` on `Counter`.

 Associated types also become part of the trait’s contract: implementors of the trait must provide a type to stand in for the associated type placeholder. Associated types often have a name that describes how the type will be used, and documenting the associated type in the API documentation is good practice.

 ### Default Generic Type Parameters and Operator Overloading

 When we use generic type parameters, we can specify a default concrete type for the generic type. This eliminates the need for implementors of the trait to specify a concrete type if the default type works. You specify a default type when declaring a generic type with the `<PlaceholderType=ConcreteType>` syntax.

 A great example of a situation where this technique is useful is with *operator overloading*, in which you customize the behavior of an operator (such as `+`) in particular situations.

 Rust doesn’t allow you to create your own operators or overload arbitrary operators. But you can overload the operations and corresponding traits listed in `std::ops` by implementing the traits associated with the operator. For example, in Listing 19-14 we overload the `+` operator to add two `Point` instances together. We do this by implementing the `Add` trait on a `Point` struct:

 Filename: src/main.rs

 
```
use std::ops::Add;

#[derive(Debug, Copy, Clone, PartialEq)]
struct Point {
    x: i32,
    y: i32,
}

impl Add for Point {
    type Output = Point;

    fn add(self, other: Point) -> Point {
        Point {
            x: self.x + other.x,
            y: self.y + other.y,
        }
    }
}

fn main() {
    assert_eq!(
        Point { x: 1, y: 0 } + Point { x: 2, y: 3 },
        Point { x: 3, y: 3 }
    );
}
```
 Listing 19-14: Implementing the `Add` trait to overload the `+` operator for `Point` instances

 The `add` method adds the `x` values of two `Point` instances and the `y` values of two `Point` instances to create a new `Point`. The `Add` trait has an associated type named `Output` that determines the type returned from the `add` method.

 The default generic type in this code is within the `Add` trait. Here is its definition:

 
```
#![allow(unused)]
fn main() {
trait Add<Rhs=Self> {
    type Output;

    fn add(self, rhs: Rhs) -> Self::Output;
}
}
```
 This code should look generally familiar: a trait with one method and an associated type. The new part is `Rhs=Self`: this syntax is called *default type parameters*. The `Rhs` generic type parameter (short for “right hand side”) defines the type of the `rhs` parameter in the `add` method. If we don’t specify a concrete type for `Rhs` when we implement the `Add` trait, the type of `Rhs` will default to `Self`, which will be the type we’re implementing `Add` on.

 When we implemented `Add` for `Point`, we used the default for `Rhs` because we wanted to add two `Point` instances. Let’s look at an example of implementing the `Add` trait where we want to customize the `Rhs` type rather than using the default.

 We have two structs, `Millimeters` and `Meters`, holding values in different units. This thin wrapping of an existing type in another struct is known as the *newtype pattern*, which we describe in more detail in the [“Using the Newtype Pattern to Implement External Traits on External Types”](ch19-03-advanced-traits#using-the-newtype-pattern-to-implement-external-traits-on-external-types) section. We want to add values in millimeters to values in meters and have the implementation of `Add` do the conversion correctly. We can implement `Add` for `Millimeters` with `Meters` as the `Rhs`, as shown in Listing 19-15.

 Filename: src/lib.rs

 
```
use std::ops::Add;

struct Millimeters(u32);
struct Meters(u32);

impl Add<Meters> for Millimeters {
    type Output = Millimeters;

    fn add(self, other: Meters) -> Millimeters {
        Millimeters(self.0 + (other.0 * 1000))
    }
}
```
 Listing 19-15: Implementing the `Add` trait on `Millimeters` to add `Millimeters` to `Meters`

 To add `Millimeters` and `Meters`, we specify `impl Add<Meters>` to set the value of the `Rhs` type parameter instead of using the default of `Self`.

 You’ll use default type parameters in two main ways:

 * To extend a type without breaking existing code
* To allow customization in specific cases most users won’t need

 The standard library’s `Add` trait is an example of the second purpose: usually, you’ll add two like types, but the `Add` trait provides the ability to customize beyond that. Using a default type parameter in the `Add` trait definition means you don’t have to specify the extra parameter most of the time. In other words, a bit of implementation boilerplate isn’t needed, making it easier to use the trait.

 The first purpose is similar to the second but in reverse: if you want to add a type parameter to an existing trait, you can give it a default to allow extension of the functionality of the trait without breaking the existing implementation code.

 ### Fully Qualified Syntax for Disambiguation: Calling Methods with the Same Name

 Nothing in Rust prevents a trait from having a method with the same name as another trait’s method, nor does Rust prevent you from implementing both traits on one type. It’s also possible to implement a method directly on the type with the same name as methods from traits.

 When calling methods with the same name, you’ll need to tell Rust which one you want to use. Consider the code in Listing 19-16 where we’ve defined two traits, `Pilot` and `Wizard`, that both have a method called `fly`. We then implement both traits on a type `Human` that already has a method named `fly` implemented on it. Each `fly` method does something different.

 Filename: src/main.rs

 
```
trait Pilot {
    fn fly(&self);
}

trait Wizard {
    fn fly(&self);
}

struct Human;

impl Pilot for Human {
    fn fly(&self) {
        println!("This is your captain speaking.");
    }
}

impl Wizard for Human {
    fn fly(&self) {
        println!("Up!");
    }
}

impl Human {
    fn fly(&self) {
        println!("*waving arms furiously*");
    }
}

fn main() {}
```
 Listing 19-16: Two traits are defined to have a `fly` method and are implemented on the `Human` type, and a `fly` method is implemented on `Human` directly

 When we call `fly` on an instance of `Human`, the compiler defaults to calling the method that is directly implemented on the type, as shown in Listing 19-17.

 Filename: src/main.rs

 
```
trait Pilot {
    fn fly(&self);
}

trait Wizard {
    fn fly(&self);
}

struct Human;

impl Pilot for Human {
    fn fly(&self) {
        println!("This is your captain speaking.");
    }
}

impl Wizard for Human {
    fn fly(&self) {
        println!("Up!");
    }
}

impl Human {
    fn fly(&self) {
        println!("*waving arms furiously*");
    }
}

fn main() {
    let person = Human;
    person.fly();
}
```
 Listing 19-17: Calling `fly` on an instance of `Human`

 Running this code will print `*waving arms furiously*`, showing that Rust called the `fly` method implemented on `Human` directly.

 To call the `fly` methods from either the `Pilot` trait or the `Wizard` trait, we need to use more explicit syntax to specify which `fly` method we mean. Listing 19-18 demonstrates this syntax.

 Filename: src/main.rs

 
```
trait Pilot {
    fn fly(&self);
}

trait Wizard {
    fn fly(&self);
}

struct Human;

impl Pilot for Human {
    fn fly(&self) {
        println!("This is your captain speaking.");
    }
}

impl Wizard for Human {
    fn fly(&self) {
        println!("Up!");
    }
}

impl Human {
    fn fly(&self) {
        println!("*waving arms furiously*");
    }
}

fn main() {
    let person = Human;
    Pilot::fly(&person);
    Wizard::fly(&person);
    person.fly();
}
```
 Listing 19-18: Specifying which trait’s `fly` method we want to call

 Specifying the trait name before the method name clarifies to Rust which implementation of `fly` we want to call. We could also write `Human::fly(&person)`, which is equivalent to the `person.fly()` that we used in Listing 19-18, but this is a bit longer to write if we don’t need to disambiguate.

 Running this code prints the following:

 
```
$ cargo run
   Compiling traits-example v0.1.0 (file:///projects/traits-example)
    Finished dev [unoptimized + debuginfo] target(s) in 0.46s
     Running `target/debug/traits-example`
This is your captain speaking.
Up!
*waving arms furiously*

```
 Because the `fly` method takes a `self` parameter, if we had two *types* that both implement one *trait*, Rust could figure out which implementation of a trait to use based on the type of `self`.

 However, associated functions that are not methods don’t have a `self` parameter. When there are multiple types or traits that define non-method functions with the same function name, Rust doesn't always know which type you mean unless you use *fully qualified syntax*. For example, in Listing 19-19 we create a trait for an animal shelter that wants to name all baby dogs *Spot*. We make an `Animal` trait with an associated non-method function `baby_name`. The `Animal` trait is implemented for the struct `Dog`, on which we also provide an associated non-method function `baby_name` directly.

 Filename: src/main.rs

 
```
trait Animal {
    fn baby_name() -> String;
}

struct Dog;

impl Dog {
    fn baby_name() -> String {
        String::from("Spot")
    }
}

impl Animal for Dog {
    fn baby_name() -> String {
        String::from("puppy")
    }
}

fn main() {
    println!("A baby dog is called a {}", Dog::baby_name());
}
```
 Listing 19-19: A trait with an associated function and a type with an associated function of the same name that also implements the trait

 We implement the code for naming all puppies Spot in the `baby_name` associated function that is defined on `Dog`. The `Dog` type also implements the trait `Animal`, which describes characteristics that all animals have. Baby dogs are called puppies, and that is expressed in the implementation of the `Animal` trait on `Dog` in the `baby_name` function associated with the `Animal` trait.

 In `main`, we call the `Dog::baby_name` function, which calls the associated function defined on `Dog` directly. This code prints the following:

 
```
$ cargo run
   Compiling traits-example v0.1.0 (file:///projects/traits-example)
    Finished dev [unoptimized + debuginfo] target(s) in 0.54s
     Running `target/debug/traits-example`
A baby dog is called a Spot

```
 This output isn’t what we wanted. We want to call the `baby_name` function that is part of the `Animal` trait that we implemented on `Dog` so the code prints `A baby dog is called a puppy`. The technique of specifying the trait name that we used in Listing 19-18 doesn’t help here; if we change `main` to the code in Listing 19-20, we’ll get a compilation error.

 Filename: src/main.rs

 
```
trait Animal {
    fn baby_name() -> String;
}

struct Dog;

impl Dog {
    fn baby_name() -> String {
        String::from("Spot")
    }
}

impl Animal for Dog {
    fn baby_name() -> String {
        String::from("puppy")
    }
}

fn main() {
    println!("A baby dog is called a {}", Animal::baby_name());
}
```
 Listing 19-20: Attempting to call the `baby_name` function from the `Animal` trait, but Rust doesn’t know which implementation to use

 Because `Animal::baby_name` doesn’t have a `self` parameter, and there could be other types that implement the `Animal` trait, Rust can’t figure out which implementation of `Animal::baby_name` we want. We’ll get this compiler error:

 
```
$ cargo run
   Compiling traits-example v0.1.0 (file:///projects/traits-example)
error[E0790]: cannot call associated function on trait without specifying the corresponding `impl` type
  --> src/main.rs:20:43
   |
2  |     fn baby_name() -> String;
   |     ------------------------- `Animal::baby_name` defined here
...
20 |     println!("A baby dog is called a {}", Animal::baby_name());
   |                                           ^^^^^^^^^^^^^^^^^ cannot call associated function of trait
   |
help: use the fully-qualified path to the only available implementation
   |
20 |     println!("A baby dog is called a {}", <Dog as Animal>::baby_name());
   |                                           +++++++       +

For more information about this error, try `rustc --explain E0790`.
error: could not compile `traits-example` due to previous error

```
 To disambiguate and tell Rust that we want to use the implementation of `Animal` for `Dog` as opposed to the implementation of `Animal` for some other type, we need to use fully qualified syntax. Listing 19-21 demonstrates how to use fully qualified syntax.

 Filename: src/main.rs

 
```
trait Animal {
    fn baby_name() -> String;
}

struct Dog;

impl Dog {
    fn baby_name() -> String {
        String::from("Spot")
    }
}

impl Animal for Dog {
    fn baby_name() -> String {
        String::from("puppy")
    }
}

fn main() {
    println!("A baby dog is called a {}", <Dog as Animal>::baby_name());
}
```
 Listing 19-21: Using fully qualified syntax to specify that we want to call the `baby_name` function from the `Animal` trait as implemented on `Dog`

 We’re providing Rust with a type annotation within the angle brackets, which indicates we want to call the `baby_name` method from the `Animal` trait as implemented on `Dog` by saying that we want to treat the `Dog` type as an `Animal` for this function call. This code will now print what we want:

 
```
$ cargo run
   Compiling traits-example v0.1.0 (file:///projects/traits-example)
    Finished dev [unoptimized + debuginfo] target(s) in 0.48s
     Running `target/debug/traits-example`
A baby dog is called a puppy

```
 In general, fully qualified syntax is defined as follows:

 
```
<Type as Trait>::function(receiver_if_method, next_arg, ...);
```
 For associated functions that aren’t methods, there would not be a `receiver`: there would only be the list of other arguments. You could use fully qualified syntax everywhere that you call functions or methods. However, you’re allowed to omit any part of this syntax that Rust can figure out from other information in the program. You only need to use this more verbose syntax in cases where there are multiple implementations that use the same name and Rust needs help to identify which implementation you want to call.

 ### Using Supertraits to Require One Trait’s Functionality Within Another Trait

 Sometimes, you might write a trait definition that depends on another trait: for a type to implement the first trait, you want to require that type to also implement the second trait. You would do this so that your trait definition can make use of the associated items of the second trait. The trait your trait definition is relying on is called a *supertrait* of your trait.

 For example, let’s say we want to make an `OutlinePrint` trait with an `outline_print` method that will print a given value formatted so that it's framed in asterisks. That is, given a `Point` struct that implements the standard library trait `Display` to result in `(x, y)`, when we call `outline_print` on a `Point` instance that has `1` for `x` and `3` for `y`, it should print the following:

 
```
**********
*        *
* (1, 3) *
*        *
**********

```
 In the implementation of the `outline_print` method, we want to use the `Display` trait’s functionality. Therefore, we need to specify that the `OutlinePrint` trait will work only for types that also implement `Display` and provide the functionality that `OutlinePrint` needs. We can do that in the trait definition by specifying `OutlinePrint: Display`. This technique is similar to adding a trait bound to the trait. Listing 19-22 shows an implementation of the `OutlinePrint` trait.

 Filename: src/main.rs

 
```
use std::fmt;

trait OutlinePrint: fmt::Display {
    fn outline_print(&self) {
        let output = self.to_string();
        let len = output.len();
        println!("{}", "*".repeat(len + 4));
        println!("*{}*", " ".repeat(len + 2));
        println!("* {} *", output);
        println!("*{}*", " ".repeat(len + 2));
        println!("{}", "*".repeat(len + 4));
    }
}

fn main() {}
```
 Listing 19-22: Implementing the `OutlinePrint` trait that requires the functionality from `Display`

 Because we’ve specified that `OutlinePrint` requires the `Display` trait, we can use the `to_string` function that is automatically implemented for any type that implements `Display`. If we tried to use `to_string` without adding a colon and specifying the `Display` trait after the trait name, we’d get an error saying that no method named `to_string` was found for the type `&Self` in the current scope.

 Let’s see what happens when we try to implement `OutlinePrint` on a type that doesn’t implement `Display`, such as the `Point` struct:

 Filename: src/main.rs

 
```
use std::fmt;

trait OutlinePrint: fmt::Display {
    fn outline_print(&self) {
        let output = self.to_string();
        let len = output.len();
        println!("{}", "*".repeat(len + 4));
        println!("*{}*", " ".repeat(len + 2));
        println!("* {} *", output);
        println!("*{}*", " ".repeat(len + 2));
        println!("{}", "*".repeat(len + 4));
    }
}

struct Point {
    x: i32,
    y: i32,
}

impl OutlinePrint for Point {}

fn main() {
    let p = Point { x: 1, y: 3 };
    p.outline_print();
}
```
 We get an error saying that `Display` is required but not implemented:

 
```
$ cargo run
   Compiling traits-example v0.1.0 (file:///projects/traits-example)
error[E0277]: `Point` doesn't implement `std::fmt::Display`
  --> src/main.rs:20:6
   |
20 | impl OutlinePrint for Point {}
   |      ^^^^^^^^^^^^ `Point` cannot be formatted with the default formatter
   |
   = help: the trait `std::fmt::Display` is not implemented for `Point`
   = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
note: required by a bound in `OutlinePrint`
  --> src/main.rs:3:21
   |
3  | trait OutlinePrint: fmt::Display {
   |                     ^^^^^^^^^^^^ required by this bound in `OutlinePrint`

For more information about this error, try `rustc --explain E0277`.
error: could not compile `traits-example` due to previous error

```
 To fix this, we implement `Display` on `Point` and satisfy the constraint that `OutlinePrint` requires, like so:

 Filename: src/main.rs

 
```
trait OutlinePrint: fmt::Display {
    fn outline_print(&self) {
        let output = self.to_string();
        let len = output.len();
        println!("{}", "*".repeat(len + 4));
        println!("*{}*", " ".repeat(len + 2));
        println!("* {} *", output);
        println!("*{}*", " ".repeat(len + 2));
        println!("{}", "*".repeat(len + 4));
    }
}

struct Point {
    x: i32,
    y: i32,
}

impl OutlinePrint for Point {}

use std::fmt;

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

fn main() {
    let p = Point { x: 1, y: 3 };
    p.outline_print();
}
```
 Then implementing the `OutlinePrint` trait on `Point` will compile successfully, and we can call `outline_print` on a `Point` instance to display it within an outline of asterisks.

 ### Using the Newtype Pattern to Implement External Traits on External Types

 In Chapter 10 in the [“Implementing a Trait on a Type”](ch10-02-traits#implementing-a-trait-on-a-type) section, we mentioned the orphan rule that states we’re only allowed to implement a trait on a type if either the trait or the type are local to our crate. It’s possible to get around this restriction using the *newtype pattern*, which involves creating a new type in a tuple struct. (We covered tuple structs in the [“Using Tuple Structs without Named Fields to Create Different Types”](ch05-01-defining-structs#using-tuple-structs-without-named-fields-to-create-different-types) section of Chapter 5.) The tuple struct will have one field and be a thin wrapper around the type we want to implement a trait for. Then the wrapper type is local to our crate, and we can implement the trait on the wrapper. *Newtype* is a term that originates from the Haskell programming language. There is no runtime performance penalty for using this pattern, and the wrapper type is elided at compile time.

 As an example, let’s say we want to implement `Display` on `Vec<T>`, which the orphan rule prevents us from doing directly because the `Display` trait and the `Vec<T>` type are defined outside our crate. We can make a `Wrapper` struct that holds an instance of `Vec<T>`; then we can implement `Display` on `Wrapper` and use the `Vec<T>` value, as shown in Listing 19-23.

 Filename: src/main.rs

 
```
use std::fmt;

struct Wrapper(Vec<String>);

impl fmt::Display for Wrapper {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "[{}]", self.0.join(", "))
    }
}

fn main() {
    let w = Wrapper(vec![String::from("hello"), String::from("world")]);
    println!("w = {}", w);
}
```
 Listing 19-23: Creating a `Wrapper` type around `Vec<String>` to implement `Display`

 The implementation of `Display` uses `self.0` to access the inner `Vec<T>`, because `Wrapper` is a tuple struct and `Vec<T>` is the item at index 0 in the tuple. Then we can use the functionality of the `Display` type on `Wrapper`.

 The downside of using this technique is that `Wrapper` is a new type, so it doesn’t have the methods of the value it’s holding. We would have to implement all the methods of `Vec<T>` directly on `Wrapper` such that the methods delegate to `self.0`, which would allow us to treat `Wrapper` exactly like a `Vec<T>`. If we wanted the new type to have every method the inner type has, implementing the `Deref` trait (discussed in Chapter 15 in the [“Treating Smart Pointers Like Regular References with the `Deref` Trait”](ch15-02-deref#treating-smart-pointers-like-regular-references-with-the-deref-trait) section) on the `Wrapper` to return the inner type would be a solution. If we don’t want the `Wrapper` type to have all the methods of the inner type—for example, to restrict the `Wrapper` type’s behavior—we would have to implement just the methods we do want manually.

 This newtype pattern is also useful even when traits are not involved. Let’s switch focus and look at some advanced ways to interact with Rust’s type system.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch19-03-advanced-traits.html>

Advanced Types
==============

 The Rust type system has some features that we’ve so far mentioned but haven’t yet discussed. We’ll start by discussing newtypes in general as we examine why newtypes are useful as types. Then we’ll move on to type aliases, a feature similar to newtypes but with slightly different semantics. We’ll also discuss the `!` type and dynamically sized types.

 ### Using the Newtype Pattern for Type Safety and Abstraction

 
>  Note: This section assumes you’ve read the earlier section [“Using the Newtype Pattern to Implement External Traits on External Types.”](ch19-03-advanced-traits#using-the-newtype-pattern-to-implement-external-traits-on-external-types)
> 
>  

 The newtype pattern is also useful for tasks beyond those we’ve discussed so far, including statically enforcing that values are never confused and indicating the units of a value. You saw an example of using newtypes to indicate units in Listing 19-15: recall that the `Millimeters` and `Meters` structs wrapped `u32` values in a newtype. If we wrote a function with a parameter of type `Millimeters`, we couldn’t compile a program that accidentally tried to call that function with a value of type `Meters` or a plain `u32`.

 We can also use the newtype pattern to abstract away some implementation details of a type: the new type can expose a public API that is different from the API of the private inner type.

 Newtypes can also hide internal implementation. For example, we could provide a `People` type to wrap a `HashMap<i32, String>` that stores a person’s ID associated with their name. Code using `People` would only interact with the public API we provide, such as a method to add a name string to the `People` collection; that code wouldn’t need to know that we assign an `i32` ID to names internally. The newtype pattern is a lightweight way to achieve encapsulation to hide implementation details, which we discussed in the [“Encapsulation that Hides Implementation Details”](ch17-01-what-is-oo#encapsulation-that-hides-implementation-details) section of Chapter 17.

 ### Creating Type Synonyms with Type Aliases

 Rust provides the ability to declare a *type alias* to give an existing type another name. For this we use the `type` keyword. For example, we can create the alias `Kilometers` to `i32` like so:

 
```
fn main() {
    type Kilometers = i32;

    let x: i32 = 5;
    let y: Kilometers = 5;

    println!("x + y = {}", x + y);
}
```
 Now, the alias `Kilometers` is a *synonym* for `i32`; unlike the `Millimeters` and `Meters` types we created in Listing 19-15, `Kilometers` is not a separate, new type. Values that have the type `Kilometers` will be treated the same as values of type `i32`:

 
```
fn main() {
    type Kilometers = i32;

    let x: i32 = 5;
    let y: Kilometers = 5;

    println!("x + y = {}", x + y);
}
```
 Because `Kilometers` and `i32` are the same type, we can add values of both types and we can pass `Kilometers` values to functions that take `i32` parameters. However, using this method, we don’t get the type checking benefits that we get from the newtype pattern discussed earlier. In other words, if we mix up `Kilometers` and `i32` values somewhere, the compiler will not give us an error.

 The main use case for type synonyms is to reduce repetition. For example, we might have a lengthy type like this:

 
```
Box<dyn Fn() + Send + 'static>
```
 Writing this lengthy type in function signatures and as type annotations all over the code can be tiresome and error prone. Imagine having a project full of code like that in Listing 19-24.

 
```
fn main() {
    let f: Box<dyn Fn() + Send + 'static> = Box::new(|| println!("hi"));

    fn takes_long_type(f: Box<dyn Fn() + Send + 'static>) {
        // --snip--
    }

    fn returns_long_type() -> Box<dyn Fn() + Send + 'static> {
        // --snip--
        Box::new(|| ())
    }
}
```
 Listing 19-24: Using a long type in many places

 A type alias makes this code more manageable by reducing the repetition. In Listing 19-25, we’ve introduced an alias named `Thunk` for the verbose type and can replace all uses of the type with the shorter alias `Thunk`.

 
```
fn main() {
    type Thunk = Box<dyn Fn() + Send + 'static>;

    let f: Thunk = Box::new(|| println!("hi"));

    fn takes_long_type(f: Thunk) {
        // --snip--
    }

    fn returns_long_type() -> Thunk {
        // --snip--
        Box::new(|| ())
    }
}
```
 Listing 19-25: Introducing a type alias `Thunk` to reduce repetition

 This code is much easier to read and write! Choosing a meaningful name for a type alias can help communicate your intent as well (*thunk* is a word for code to be evaluated at a later time, so it’s an appropriate name for a closure that gets stored).

 Type aliases are also commonly used with the `Result<T, E>` type for reducing repetition. Consider the `std::io` module in the standard library. I/O operations often return a `Result<T, E>` to handle situations when operations fail to work. This library has a `std::io::Error` struct that represents all possible I/O errors. Many of the functions in `std::io` will be returning `Result<T, E>` where the `E` is `std::io::Error`, such as these functions in the `Write` trait:

 
```
use std::fmt;
use std::io::Error;

pub trait Write {
    fn write(&mut self, buf: &[u8]) -> Result<usize, Error>;
    fn flush(&mut self) -> Result<(), Error>;

    fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>;
    fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<(), Error>;
}
```
 The `Result<..., Error>` is repeated a lot. As such, `std::io` has this type alias declaration:

 
```
use std::fmt;

type Result<T> = std::result::Result<T, std::io::Error>;

pub trait Write {
    fn write(&mut self, buf: &[u8]) -> Result<usize>;
    fn flush(&mut self) -> Result<()>;

    fn write_all(&mut self, buf: &[u8]) -> Result<()>;
    fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()>;
}
```
 Because this declaration is in the `std::io` module, we can use the fully qualified alias `std::io::Result<T>`; that is, a `Result<T, E>` with the `E` filled in as `std::io::Error`. The `Write` trait function signatures end up looking like this:

 
```
use std::fmt;

type Result<T> = std::result::Result<T, std::io::Error>;

pub trait Write {
    fn write(&mut self, buf: &[u8]) -> Result<usize>;
    fn flush(&mut self) -> Result<()>;

    fn write_all(&mut self, buf: &[u8]) -> Result<()>;
    fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()>;
}
```
 The type alias helps in two ways: it makes code easier to write *and* it gives us a consistent interface across all of `std::io`. Because it’s an alias, it’s just another `Result<T, E>`, which means we can use any methods that work on `Result<T, E>` with it, as well as special syntax like the `?` operator.

 ### The Never Type that Never Returns

 Rust has a special type named `!` that’s known in type theory lingo as the *empty type* because it has no values. We prefer to call it the *never type* because it stands in the place of the return type when a function will never return. Here is an example:

 
```
fn bar() -> ! {
    // --snip--
    panic!();
}
```
 This code is read as “the function `bar` returns never.” Functions that return never are called *diverging functions*. We can’t create values of the type `!` so `bar` can never possibly return.

 But what use is a type you can never create values for? Recall the code from Listing 2-5, part of the number guessing game; we’ve reproduced a bit of it here in Listing 19-26.

 
```
use rand::Rng;
use std::cmp::Ordering;
use std::io;

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 19-26: A `match` with an arm that ends in `continue`

 At the time, we skipped over some details in this code. In Chapter 6 in [“The `match` Control Flow Operator”](ch06-02-match#the-match-control-flow-operator) section, we discussed that `match` arms must all return the same type. So, for example, the following code doesn’t work:

 
```
fn main() {
    let guess = "3";
    let guess = match guess.trim().parse() {
        Ok(_) => 5,
        Err(_) => "hello",
    };
}
```
 The type of `guess` in this code would have to be an integer *and* a string, and Rust requires that `guess` have only one type. So what does `continue` return? How were we allowed to return a `u32` from one arm and have another arm that ends with `continue` in Listing 19-26?

 As you might have guessed, `continue` has a `!` value. That is, when Rust computes the type of `guess`, it looks at both match arms, the former with a value of `u32` and the latter with a `!` value. Because `!` can never have a value, Rust decides that the type of `guess` is `u32`.

 The formal way of describing this behavior is that expressions of type `!` can be coerced into any other type. We’re allowed to end this `match` arm with `continue` because `continue` doesn’t return a value; instead, it moves control back to the top of the loop, so in the `Err` case, we never assign a value to `guess`.

 The never type is useful with the `panic!` macro as well. Recall the `unwrap` function that we call on `Option<T>` values to produce a value or panic with this definition:

 
```
enum Option<T> {
    Some(T),
    None,
}

use crate::Option::*;

impl<T> Option<T> {
    pub fn unwrap(self) -> T {
        match self {
            Some(val) => val,
            None => panic!("called `Option::unwrap()` on a `None` value"),
        }
    }
}
```
 In this code, the same thing happens as in the `match` in Listing 19-26: Rust sees that `val` has the type `T` and `panic!` has the type `!`, so the result of the overall `match` expression is `T`. This code works because `panic!` doesn’t produce a value; it ends the program. In the `None` case, we won’t be returning a value from `unwrap`, so this code is valid.

 One final expression that has the type `!` is a `loop`:

 
```
fn main() {
    print!("forever ");

    loop {
        print!("and ever ");
    }
}
```
 Here, the loop never ends, so `!` is the value of the expression. However, this wouldn’t be true if we included a `break`, because the loop would terminate when it got to the `break`.

 ### Dynamically Sized Types and the `Sized` Trait

 Rust needs to know certain details about its types, such as how much space to allocate for a value of a particular type. This leaves one corner of its type system a little confusing at first: the concept of *dynamically sized types*. Sometimes referred to as *DSTs* or *unsized types*, these types let us write code using values whose size we can know only at runtime.

 Let’s dig into the details of a dynamically sized type called `str`, which we’ve been using throughout the book. That’s right, not `&str`, but `str` on its own, is a DST. We can’t know how long the string is until runtime, meaning we can’t create a variable of type `str`, nor can we take an argument of type `str`. Consider the following code, which does not work:

 
```
fn main() {
    let s1: str = "Hello there!";
    let s2: str = "How's it going?";
}
```
 Rust needs to know how much memory to allocate for any value of a particular type, and all values of a type must use the same amount of memory. If Rust allowed us to write this code, these two `str` values would need to take up the same amount of space. But they have different lengths: `s1` needs 12 bytes of storage and `s2` needs 15. This is why it’s not possible to create a variable holding a dynamically sized type.

 So what do we do? In this case, you already know the answer: we make the types of `s1` and `s2` a `&str` rather than a `str`. Recall from the [“String Slices”](ch04-03-slices#string-slices) section of Chapter 4 that the slice data structure just stores the starting position and the length of the slice. So although a `&T` is a single value that stores the memory address of where the `T` is located, a `&str` is *two* values: the address of the `str` and its length. As such, we can know the size of a `&str` value at compile time: it’s twice the length of a `usize`. That is, we always know the size of a `&str`, no matter how long the string it refers to is. In general, this is the way in which dynamically sized types are used in Rust: they have an extra bit of metadata that stores the size of the dynamic information. The golden rule of dynamically sized types is that we must always put values of dynamically sized types behind a pointer of some kind.

 We can combine `str` with all kinds of pointers: for example, `Box<str>` or `Rc<str>`. In fact, you’ve seen this before but with a different dynamically sized type: traits. Every trait is a dynamically sized type we can refer to by using the name of the trait. In Chapter 17 in the [“Using Trait Objects That Allow for Values of Different Types”](ch17-02-trait-objects#using-trait-objects-that-allow-for-values-of-different-types) section, we mentioned that to use traits as trait objects, we must put them behind a pointer, such as `&dyn Trait` or `Box<dyn Trait>` (`Rc<dyn Trait>` would work too).

 To work with DSTs, Rust provides the `Sized` trait to determine whether or not a type’s size is known at compile time. This trait is automatically implemented for everything whose size is known at compile time. In addition, Rust implicitly adds a bound on `Sized` to every generic function. That is, a generic function definition like this:

 
```
fn generic<T>(t: T) {
    // --snip--
}
```
 is actually treated as though we had written this:

 
```
fn generic<T: Sized>(t: T) {
    // --snip--
}
```
 By default, generic functions will work only on types that have a known size at compile time. However, you can use the following special syntax to relax this restriction:

 
```
fn generic<T: ?Sized>(t: &T) {
    // --snip--
}
```
 A trait bound on `?Sized` means “`T` may or may not be `Sized`” and this notation overrides the default that generic types must have a known size at compile time. The `?Trait` syntax with this meaning is only available for `Sized`, not any other traits.

 Also note that we switched the type of the `t` parameter from `T` to `&T`. Because the type might not be `Sized`, we need to use it behind some kind of pointer. In this case, we’ve chosen a reference.

 Next, we’ll talk about functions and closures!



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch19-04-advanced-types.html>

Macros
======

 We’ve used macros like `println!` throughout this book, but we haven’t fully explored what a macro is and how it works. The term *macro* refers to a family of features in Rust: *declarative* macros with `macro_rules!` and three kinds of *procedural* macros:

 * Custom `#[derive]` macros that specify code added with the `derive` attribute used on structs and enums
* Attribute-like macros that define custom attributes usable on any item
* Function-like macros that look like function calls but operate on the tokens specified as their argument

 We’ll talk about each of these in turn, but first, let’s look at why we even need macros when we already have functions.

 ### The Difference Between Macros and Functions

 Fundamentally, macros are a way of writing code that writes other code, which is known as *metaprogramming*. In Appendix C, we discuss the `derive` attribute, which generates an implementation of various traits for you. We’ve also used the `println!` and `vec!` macros throughout the book. All of these macros *expand* to produce more code than the code you’ve written manually.

 Metaprogramming is useful for reducing the amount of code you have to write and maintain, which is also one of the roles of functions. However, macros have some additional powers that functions don’t.

 A function signature must declare the number and type of parameters the function has. Macros, on the other hand, can take a variable number of parameters: we can call `println!("hello")` with one argument or `println!("hello {}", name)` with two arguments. Also, macros are expanded before the compiler interprets the meaning of the code, so a macro can, for example, implement a trait on a given type. A function can’t, because it gets called at runtime and a trait needs to be implemented at compile time.

 The downside to implementing a macro instead of a function is that macro definitions are more complex than function definitions because you’re writing Rust code that writes Rust code. Due to this indirection, macro definitions are generally more difficult to read, understand, and maintain than function definitions.

 Another important difference between macros and functions is that you must define macros or bring them into scope *before* you call them in a file, as opposed to functions you can define anywhere and call anywhere.

 ### Declarative Macros with `macro_rules!` for General Metaprogramming

 The most widely used form of macros in Rust is the *declarative macro*. These are also sometimes referred to as “macros by example,” “`macro_rules!` macros,” or just plain “macros.” At their core, declarative macros allow you to write something similar to a Rust `match` expression. As discussed in Chapter 6, `match` expressions are control structures that take an expression, compare the resulting value of the expression to patterns, and then run the code associated with the matching pattern. Macros also compare a value to patterns that are associated with particular code: in this situation, the value is the literal Rust source code passed to the macro; the patterns are compared with the structure of that source code; and the code associated with each pattern, when matched, replaces the code passed to the macro. This all happens during compilation.

 To define a macro, you use the `macro_rules!` construct. Let’s explore how to use `macro_rules!` by looking at how the `vec!` macro is defined. Chapter 8 covered how we can use the `vec!` macro to create a new vector with particular values. For example, the following macro creates a new vector containing three integers:

 
```
#![allow(unused)]
fn main() {
let v: Vec<u32> = vec![1, 2, 3];
}
```
 We could also use the `vec!` macro to make a vector of two integers or a vector of five string slices. We wouldn’t be able to use a function to do the same because we wouldn’t know the number or type of values up front.

 Listing 19-28 shows a slightly simplified definition of the `vec!` macro.

 Filename: src/lib.rs

 
```
#[macro_export]
macro_rules! vec {
    ( $( $x:expr ),* ) => {
        {
            let mut temp_vec = Vec::new();
            $(
                temp_vec.push($x);
            )*
            temp_vec
        }
    };
}
```
 Listing 19-28: A simplified version of the `vec!` macro definition

 
>  Note: The actual definition of the `vec!` macro in the standard library includes code to preallocate the correct amount of memory up front. That code is an optimization that we don’t include here to make the example simpler.
> 
>  

 The `#[macro_export]` annotation indicates that this macro should be made available whenever the crate in which the macro is defined is brought into scope. Without this annotation, the macro can’t be brought into scope.

 We then start the macro definition with `macro_rules!` and the name of the macro we’re defining *without* the exclamation mark. The name, in this case `vec`, is followed by curly brackets denoting the body of the macro definition.

 The structure in the `vec!` body is similar to the structure of a `match` expression. Here we have one arm with the pattern `( $( $x:expr ),* )`, followed by `=>` and the block of code associated with this pattern. If the pattern matches, the associated block of code will be emitted. Given that this is the only pattern in this macro, there is only one valid way to match; any other pattern will result in an error. More complex macros will have more than one arm.

 Valid pattern syntax in macro definitions is different than the pattern syntax covered in Chapter 18 because macro patterns are matched against Rust code structure rather than values. Let’s walk through what the pattern pieces in Listing 19-28 mean; for the full macro pattern syntax, see the [Rust Reference](../reference/macros-by-example).

 First, we use a set of parentheses to encompass the whole pattern. We use a dollar sign (`$`) to declare a variable in the macro system that will contain the Rust code matching the pattern. The dollar sign makes it clear this is a macro variable as opposed to a regular Rust variable. Next comes a set of parentheses that captures values that match the pattern within the parentheses for use in the replacement code. Within `$()` is `$x:expr`, which matches any Rust expression and gives the expression the name `$x`.

 The comma following `$()` indicates that a literal comma separator character could optionally appear after the code that matches the code in `$()`. The `*` specifies that the pattern matches zero or more of whatever precedes the `*`.

 When we call this macro with `vec![1, 2, 3];`, the `$x` pattern matches three times with the three expressions `1`, `2`, and `3`.

 Now let’s look at the pattern in the body of the code associated with this arm: `temp_vec.push()` within `$()*` is generated for each part that matches `$()` in the pattern zero or more times depending on how many times the pattern matches. The `$x` is replaced with each expression matched. When we call this macro with `vec![1, 2, 3];`, the code generated that replaces this macro call will be the following:

 
```
{
    let mut temp_vec = Vec::new();
    temp_vec.push(1);
    temp_vec.push(2);
    temp_vec.push(3);
    temp_vec
}
```
 We’ve defined a macro that can take any number of arguments of any type and can generate code to create a vector containing the specified elements.

 To learn more about how to write macros, consult the online documentation or other resources, such as [“The Little Book of Rust Macros”](https://veykril.github.io/tlborm/) started by Daniel Keep and continued by Lukas Wirth.

 ### Procedural Macros for Generating Code from Attributes

 The second form of macros is the *procedural macro*, which acts more like a function (and is a type of procedure). Procedural macros accept some code as an input, operate on that code, and produce some code as an output rather than matching against patterns and replacing the code with other code as declarative macros do. The three kinds of procedural macros are custom derive, attribute-like, and function-like, and all work in a similar fashion.

 When creating procedural macros, the definitions must reside in their own crate with a special crate type. This is for complex technical reasons that we hope to eliminate in the future. In Listing 19-29, we show how to define a procedural macro, where `some_attribute` is a placeholder for using a specific macro variety.

 Filename: src/lib.rs

 
```
use proc_macro;

#[some_attribute]
pub fn some_name(input: TokenStream) -> TokenStream {
}
```
 Listing 19-29: An example of defining a procedural macro

 The function that defines a procedural macro takes a `TokenStream` as an input and produces a `TokenStream` as an output. The `TokenStream` type is defined by the `proc_macro` crate that is included with Rust and represents a sequence of tokens. This is the core of the macro: the source code that the macro is operating on makes up the input `TokenStream`, and the code the macro produces is the output `TokenStream`. The function also has an attribute attached to it that specifies which kind of procedural macro we’re creating. We can have multiple kinds of procedural macros in the same crate.

 Let’s look at the different kinds of procedural macros. We’ll start with a custom derive macro and then explain the small dissimilarities that make the other forms different.

 ### How to Write a Custom `derive` Macro

 Let’s create a crate named `hello_macro` that defines a trait named `HelloMacro` with one associated function named `hello_macro`. Rather than making our users implement the `HelloMacro` trait for each of their types, we’ll provide a procedural macro so users can annotate their type with `#[derive(HelloMacro)]` to get a default implementation of the `hello_macro` function. The default implementation will print `Hello, Macro! My name is TypeName!` where `TypeName` is the name of the type on which this trait has been defined. In other words, we’ll write a crate that enables another programmer to write code like Listing 19-30 using our crate.

 Filename: src/main.rs

 
```
use hello_macro::HelloMacro;
use hello_macro_derive::HelloMacro;

#[derive(HelloMacro)]
struct Pancakes;

fn main() {
    Pancakes::hello_macro();
}
```
 Listing 19-30: The code a user of our crate will be able to write when using our procedural macro

 This code will print `Hello, Macro! My name is Pancakes!` when we’re done. The first step is to make a new library crate, like this:

 
```
$ cargo new hello_macro --lib

```
 Next, we’ll define the `HelloMacro` trait and its associated function:

 Filename: src/lib.rs

 
```
pub trait HelloMacro {
    fn hello_macro();
}
```
 We have a trait and its function. At this point, our crate user could implement the trait to achieve the desired functionality, like so:

 
```
use hello_macro::HelloMacro;

struct Pancakes;

impl HelloMacro for Pancakes {
    fn hello_macro() {
        println!("Hello, Macro! My name is Pancakes!");
    }
}

fn main() {
    Pancakes::hello_macro();
}
```
 However, they would need to write the implementation block for each type they wanted to use with `hello_macro`; we want to spare them from having to do this work.

 Additionally, we can’t yet provide the `hello_macro` function with default implementation that will print the name of the type the trait is implemented on: Rust doesn’t have reflection capabilities, so it can’t look up the type’s name at runtime. We need a macro to generate code at compile time.

 The next step is to define the procedural macro. At the time of this writing, procedural macros need to be in their own crate. Eventually, this restriction might be lifted. The convention for structuring crates and macro crates is as follows: for a crate named `foo`, a custom derive procedural macro crate is called `foo_derive`. Let’s start a new crate called `hello_macro_derive` inside our `hello_macro` project:

 
```
$ cargo new hello_macro_derive --lib

```
 Our two crates are tightly related, so we create the procedural macro crate within the directory of our `hello_macro` crate. If we change the trait definition in `hello_macro`, we’ll have to change the implementation of the procedural macro in `hello_macro_derive` as well. The two crates will need to be published separately, and programmers using these crates will need to add both as dependencies and bring them both into scope. We could instead have the `hello_macro` crate use `hello_macro_derive` as a dependency and re-export the procedural macro code. However, the way we’ve structured the project makes it possible for programmers to use `hello_macro` even if they don’t want the `derive` functionality.

 We need to declare the `hello_macro_derive` crate as a procedural macro crate. We’ll also need functionality from the `syn` and `quote` crates, as you’ll see in a moment, so we need to add them as dependencies. Add the following to the *Cargo.toml* file for `hello_macro_derive`:

 Filename: hello\_macro\_derive/Cargo.toml

 
```
[lib]
proc-macro = true

[dependencies]
syn = "1.0"
quote = "1.0"

```
 To start defining the procedural macro, place the code in Listing 19-31 into your *src/lib.rs* file for the `hello_macro_derive` crate. Note that this code won’t compile until we add a definition for the `impl_hello_macro` function.

 Filename: hello\_macro\_derive/src/lib.rs

 
```
use proc_macro::TokenStream;
use quote::quote;
use syn;

#[proc_macro_derive(HelloMacro)]
pub fn hello_macro_derive(input: TokenStream) -> TokenStream {
    // Construct a representation of Rust code as a syntax tree
    // that we can manipulate
    let ast = syn::parse(input).unwrap();

    // Build the trait implementation
    impl_hello_macro(&ast)
}
```
 Listing 19-31: Code that most procedural macro crates will require in order to process Rust code

 Notice that we’ve split the code into the `hello_macro_derive` function, which is responsible for parsing the `TokenStream`, and the `impl_hello_macro` function, which is responsible for transforming the syntax tree: this makes writing a procedural macro more convenient. The code in the outer function (`hello_macro_derive` in this case) will be the same for almost every procedural macro crate you see or create. The code you specify in the body of the inner function (`impl_hello_macro` in this case) will be different depending on your procedural macro’s purpose.

 We’ve introduced three new crates: `proc_macro`, [`syn`](https://crates.io/crates/syn), and [`quote`](https://crates.io/crates/quote). The `proc_macro` crate comes with Rust, so we didn’t need to add that to the dependencies in *Cargo.toml*. The `proc_macro` crate is the compiler’s API that allows us to read and manipulate Rust code from our code.

 The `syn` crate parses Rust code from a string into a data structure that we can perform operations on. The `quote` crate turns `syn` data structures back into Rust code. These crates make it much simpler to parse any sort of Rust code we might want to handle: writing a full parser for Rust code is no simple task.

 The `hello_macro_derive` function will be called when a user of our library specifies `#[derive(HelloMacro)]` on a type. This is possible because we’ve annotated the `hello_macro_derive` function here with `proc_macro_derive` and specified the name `HelloMacro`, which matches our trait name; this is the convention most procedural macros follow.

 The `hello_macro_derive` function first converts the `input` from a `TokenStream` to a data structure that we can then interpret and perform operations on. This is where `syn` comes into play. The `parse` function in `syn` takes a `TokenStream` and returns a `DeriveInput` struct representing the parsed Rust code. Listing 19-32 shows the relevant parts of the `DeriveInput` struct we get from parsing the `struct Pancakes;` string:

 
```
DeriveInput {
    // --snip--

    ident: Ident {
        ident: "Pancakes",
        span: #0 bytes(95..103)
    },
    data: Struct(
        DataStruct {
            struct_token: Struct,
            fields: Unit,
            semi_token: Some(
                Semi
            )
        }
    )
}
```
 Listing 19-32: The `DeriveInput` instance we get when parsing the code that has the macro’s attribute in Listing 19-30

 The fields of this struct show that the Rust code we’ve parsed is a unit struct with the `ident` (identifier, meaning the name) of `Pancakes`. There are more fields on this struct for describing all sorts of Rust code; check the [`syn` documentation for `DeriveInput`](https://docs.rs/syn/1.0/syn/struct.DeriveInput.html) for more information.

 Soon we’ll define the `impl_hello_macro` function, which is where we’ll build the new Rust code we want to include. But before we do, note that the output for our derive macro is also a `TokenStream`. The returned `TokenStream` is added to the code that our crate users write, so when they compile their crate, they’ll get the extra functionality that we provide in the modified `TokenStream`.

 You might have noticed that we’re calling `unwrap` to cause the `hello_macro_derive` function to panic if the call to the `syn::parse` function fails here. It’s necessary for our procedural macro to panic on errors because `proc_macro_derive` functions must return `TokenStream` rather than `Result` to conform to the procedural macro API. We’ve simplified this example by using `unwrap`; in production code, you should provide more specific error messages about what went wrong by using `panic!` or `expect`.

 Now that we have the code to turn the annotated Rust code from a `TokenStream` into a `DeriveInput` instance, let’s generate the code that implements the `HelloMacro` trait on the annotated type, as shown in Listing 19-33.

 Filename: hello\_macro\_derive/src/lib.rs

 
```
use proc_macro::TokenStream;
use quote::quote;
use syn;

#[proc_macro_derive(HelloMacro)]
pub fn hello_macro_derive(input: TokenStream) -> TokenStream {
    // Construct a representation of Rust code as a syntax tree
    // that we can manipulate
    let ast = syn::parse(input).unwrap();

    // Build the trait implementation
    impl_hello_macro(&ast)
}

fn impl_hello_macro(ast: &syn::DeriveInput) -> TokenStream {
    let name = &ast.ident;
    let gen = quote! {
        impl HelloMacro for #name {
            fn hello_macro() {
                println!("Hello, Macro! My name is {}!", stringify!(#name));
            }
        }
    };
    gen.into()
}
```
 Listing 19-33: Implementing the `HelloMacro` trait using the parsed Rust code

 We get an `Ident` struct instance containing the name (identifier) of the annotated type using `ast.ident`. The struct in Listing 19-32 shows that when we run the `impl_hello_macro` function on the code in Listing 19-30, the `ident` we get will have the `ident` field with a value of `"Pancakes"`. Thus, the `name` variable in Listing 19-33 will contain an `Ident` struct instance that, when printed, will be the string `"Pancakes"`, the name of the struct in Listing 19-30.

 The `quote!` macro lets us define the Rust code that we want to return. The compiler expects something different to the direct result of the `quote!` macro’s execution, so we need to convert it to a `TokenStream`. We do this by calling the `into` method, which consumes this intermediate representation and returns a value of the required `TokenStream` type.

 The `quote!` macro also provides some very cool templating mechanics: we can enter `#name`, and `quote!` will replace it with the value in the variable `name`. You can even do some repetition similar to the way regular macros work. Check out [the `quote` crate’s docs](https://docs.rs/quote) for a thorough introduction.

 We want our procedural macro to generate an implementation of our `HelloMacro` trait for the type the user annotated, which we can get by using `#name`. The trait implementation has the one function `hello_macro`, whose body contains the functionality we want to provide: printing `Hello, Macro! My name is` and then the name of the annotated type.

 The `stringify!` macro used here is built into Rust. It takes a Rust expression, such as `1 + 2`, and at compile time turns the expression into a string literal, such as `"1 + 2"`. This is different than `format!` or `println!`, macros which evaluate the expression and then turn the result into a `String`. There is a possibility that the `#name` input might be an expression to print literally, so we use `stringify!`. Using `stringify!` also saves an allocation by converting `#name` to a string literal at compile time.

 At this point, `cargo build` should complete successfully in both `hello_macro` and `hello_macro_derive`. Let’s hook up these crates to the code in Listing 19-30 to see the procedural macro in action! Create a new binary project in your *projects* directory using `cargo new pancakes`. We need to add `hello_macro` and `hello_macro_derive` as dependencies in the `pancakes` crate’s *Cargo.toml*. If you’re publishing your versions of `hello_macro` and `hello_macro_derive` to [crates.io](https://crates.io/), they would be regular dependencies; if not, you can specify them as `path` dependencies as follows:

 
```
hello_macro = { path = "../hello_macro" }
hello_macro_derive = { path = "../hello_macro/hello_macro_derive" }

```
 Put the code in Listing 19-30 into *src/main.rs*, and run `cargo run`: it should print `Hello, Macro! My name is Pancakes!` The implementation of the `HelloMacro` trait from the procedural macro was included without the `pancakes` crate needing to implement it; the `#[derive(HelloMacro)]` added the trait implementation.

 Next, let’s explore how the other kinds of procedural macros differ from custom derive macros.

 ### Attribute-like macros

 Attribute-like macros are similar to custom derive macros, but instead of generating code for the `derive` attribute, they allow you to create new attributes. They’re also more flexible: `derive` only works for structs and enums; attributes can be applied to other items as well, such as functions. Here’s an example of using an attribute-like macro: say you have an attribute named `route` that annotates functions when using a web application framework:

 
```
#[route(GET, "/")]
fn index() {
```
 This `#[route]` attribute would be defined by the framework as a procedural macro. The signature of the macro definition function would look like this:

 
```
#[proc_macro_attribute]
pub fn route(attr: TokenStream, item: TokenStream) -> TokenStream {
```
 Here, we have two parameters of type `TokenStream`. The first is for the contents of the attribute: the `GET, "/"` part. The second is the body of the item the attribute is attached to: in this case, `fn index() {}` and the rest of the function’s body.

 Other than that, attribute-like macros work the same way as custom derive macros: you create a crate with the `proc-macro` crate type and implement a function that generates the code you want!

 ### Function-like macros

 Function-like macros define macros that look like function calls. Similarly to `macro_rules!` macros, they’re more flexible than functions; for example, they can take an unknown number of arguments. However, `macro_rules!` macros can be defined only using the match-like syntax we discussed in the section [“Declarative Macros with `macro_rules!` for General Metaprogramming”](#declarative-macros-with-macro_rules-for-general-metaprogramming) earlier. Function-like macros take a `TokenStream` parameter and their definition manipulates that `TokenStream` using Rust code as the other two types of procedural macros do. An example of a function-like macro is an `sql!` macro that might be called like so:

 
```
let sql = sql!(SELECT * FROM posts WHERE id=1);
```
 This macro would parse the SQL statement inside it and check that it’s syntactically correct, which is much more complex processing than a `macro_rules!` macro can do. The `sql!` macro would be defined like this:

 
```
#[proc_macro]
pub fn sql(input: TokenStream) -> TokenStream {
```
 This definition is similar to the custom derive macro’s signature: we receive the tokens that are inside the parentheses and return the code we wanted to generate.

 Summary
-------

 Whew! Now you have some Rust features in your toolbox that you likely won’t use often, but you’ll know they’re available in very particular circumstances. We’ve introduced several complex topics so that when you encounter them in error message suggestions or in other peoples’ code, you’ll be able to recognize these concepts and syntax. Use this chapter as a reference to guide you to solutions.

 Next, we’ll put everything we’ve discussed throughout the book into practice and do one more project!



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch19-06-macros.html>

Final Project: Building a Multithreaded Web Server
==================================================

 It’s been a long journey, but we’ve reached the end of the book. In this chapter, we’ll build one more project together to demonstrate some of the concepts we covered in the final chapters, as well as recap some earlier lessons.

 For our final project, we’ll make a web server that says “hello” and looks like Figure 20-1 in a web browser.

 ![hello from rust]

 Figure 20-1: Our final shared project

 Here is our plan for building the web server:

 1. Learn a bit about TCP and HTTP.
2. Listen for TCP connections on a socket.
3. Parse a small number of HTTP requests.
4. Create a proper HTTP response.
5. Improve the throughput of our server with a thread pool.

 Before we get started, we should mention one detail: the method we’ll use won’t be the best way to build a web server with Rust. Community members have published a number of production-ready crates available on [crates.io](https://crates.io/) that provide more complete web server and thread pool implementations than we’ll build. However, our intention in this chapter is to help you learn, not to take the easy route. Because Rust is a systems programming language, we can choose the level of abstraction we want to work with and can go to a lower level than is possible or practical in other languages. We’ll therefore write the basic HTTP server and thread pool manually so you can learn the general ideas and techniques behind the crates you might use in the future.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch20-00-final-project-a-web-server.html>

Building a Single-Threaded Web Server
=====================================

 We’ll start by getting a single-threaded web server working. Before we begin, let’s look at a quick overview of the protocols involved in building web servers. The details of these protocols are beyond the scope of this book, but a brief overview will give you the information you need.

 The two main protocols involved in web servers are *Hypertext Transfer Protocol* *(HTTP)* and *Transmission Control Protocol* *(TCP)*. Both protocols are *request-response* protocols, meaning a *client* initiates requests and a *server* listens to the requests and provides a response to the client. The contents of those requests and responses are defined by the protocols.

 TCP is the lower-level protocol that describes the details of how information gets from one server to another but doesn’t specify what that information is. HTTP builds on top of TCP by defining the contents of the requests and responses. It’s technically possible to use HTTP with other protocols, but in the vast majority of cases, HTTP sends its data over TCP. We’ll work with the raw bytes of TCP and HTTP requests and responses.

 ### Listening to the TCP Connection

 Our web server needs to listen to a TCP connection, so that’s the first part we’ll work on. The standard library offers a `std::net` module that lets us do this. Let’s make a new project in the usual fashion:

 
```
$ cargo new hello
     Created binary (application) `hello` project
$ cd hello

```
 Now enter the code in Listing 20-1 in *src/main.rs* to start. This code will listen at the local address `127.0.0.1:7878` for incoming TCP streams. When it gets an incoming stream, it will print `Connection established!`.

 Filename: src/main.rs

 
```
use std::net::TcpListener;

fn main() {
    let listener = TcpListener::bind("127.0.0.1:7878").unwrap();

    for stream in listener.incoming() {
        let stream = stream.unwrap();

        println!("Connection established!");
    }
}
```
 Listing 20-1: Listening for incoming streams and printing a message when we receive a stream

 Using `TcpListener`, we can listen for TCP connections at the address `127.0.0.1:7878`. In the address, the section before the colon is an IP address representing your computer (this is the same on every computer and doesn’t represent the authors’ computer specifically), and `7878` is the port. We’ve chosen this port for two reasons: HTTP isn’t normally accepted on this port so our server is unlikely to conflict with any other web server you might have running on your machine, and 7878 is *rust* typed on a telephone.

 The `bind` function in this scenario works like the `new` function in that it will return a new `TcpListener` instance. The function is called `bind` because, in networking, connecting to a port to listen to is known as “binding to a port.”

 The `bind` function returns a `Result<T, E>`, which indicates that it’s possible for binding to fail. For example, connecting to port 80 requires administrator privileges (nonadministrators can listen only on ports higher than 1023), so if we tried to connect to port 80 without being an administrator, binding wouldn’t work. Binding also wouldn’t work, for example, if we ran two instances of our program and so had two programs listening to the same port. Because we’re writing a basic server just for learning purposes, we won’t worry about handling these kinds of errors; instead, we use `unwrap` to stop the program if errors happen.

 The `incoming` method on `TcpListener` returns an iterator that gives us a sequence of streams (more specifically, streams of type `TcpStream`). A single *stream* represents an open connection between the client and the server. A *connection* is the name for the full request and response process in which a client connects to the server, the server generates a response, and the server closes the connection. As such, we will read from the `TcpStream` to see what the client sent and then write our response to the stream to send data back to the client. Overall, this `for` loop will process each connection in turn and produce a series of streams for us to handle.

 For now, our handling of the stream consists of calling `unwrap` to terminate our program if the stream has any errors; if there aren’t any errors, the program prints a message. We’ll add more functionality for the success case in the next listing. The reason we might receive errors from the `incoming` method when a client connects to the server is that we’re not actually iterating over connections. Instead, we’re iterating over *connection attempts*. The connection might not be successful for a number of reasons, many of them operating system specific. For example, many operating systems have a limit to the number of simultaneous open connections they can support; new connection attempts beyond that number will produce an error until some of the open connections are closed.

 Let’s try running this code! Invoke `cargo run` in the terminal and then load *127.0.0.1:7878* in a web browser. The browser should show an error message like “Connection reset,” because the server isn’t currently sending back any data. But when you look at your terminal, you should see several messages that were printed when the browser connected to the server!

 
```
     Running `target/debug/hello`
Connection established!
Connection established!
Connection established!

```
 Sometimes, you’ll see multiple messages printed for one browser request; the reason might be that the browser is making a request for the page as well as a request for other resources, like the *favicon.ico* icon that appears in the browser tab.

 It could also be that the browser is trying to connect to the server multiple times because the server isn’t responding with any data. When `stream` goes out of scope and is dropped at the end of the loop, the connection is closed as part of the `drop` implementation. Browsers sometimes deal with closed connections by retrying, because the problem might be temporary. The important factor is that we’ve successfully gotten a handle to a TCP connection!

 Remember to stop the program by pressing ctrl-c when you’re done running a particular version of the code. Then restart the program by invoking the `cargo run` command after you’ve made each set of code changes to make sure you’re running the newest code.

 ### Reading the Request

 Let’s implement the functionality to read the request from the browser! To separate the concerns of first getting a connection and then taking some action with the connection, we’ll start a new function for processing connections. In this new `handle_connection` function, we’ll read data from the TCP stream and print it so we can see the data being sent from the browser. Change the code to look like Listing 20-2.

 Filename: src/main.rs

 
```
use std::{
    io::{prelude::*, BufReader},
    net::{TcpListener, TcpStream},
};

fn main() {
    let listener = TcpListener::bind("127.0.0.1:7878").unwrap();

    for stream in listener.incoming() {
        let stream = stream.unwrap();

        handle_connection(stream);
    }
}

fn handle_connection(mut stream: TcpStream) {
    let buf_reader = BufReader::new(&mut stream);
    let http_request: Vec<_> = buf_reader
        .lines()
        .map(|result| result.unwrap())
        .take_while(|line| !line.is_empty())
        .collect();

    println!("Request: {:#?}", http_request);
}
```
 Listing 20-2: Reading from the `TcpStream` and printing the data

 We bring `std::io::prelude` and `std::io::BufReader` into scope to get access to traits and types that let us read from and write to the stream. In the `for` loop in the `main` function, instead of printing a message that says we made a connection, we now call the new `handle_connection` function and pass the `stream` to it.

 In the `handle_connection` function, we create a new `BufReader` instance that wraps a mutable reference to the `stream`. `BufReader` adds buffering by managing calls to the `std::io::Read` trait methods for us.

 We create a variable named `http_request` to collect the lines of the request the browser sends to our server. We indicate that we want to collect these lines in a vector by adding the `Vec<_>` type annotation.

 `BufReader` implements the `std::io::BufRead` trait, which provides the `lines` method. The `lines` method returns an iterator of `Result<String, std::io::Error>` by splitting the stream of data whenever it sees a newline byte. To get each `String`, we map and `unwrap` each `Result`. The `Result` might be an error if the data isn’t valid UTF-8 or if there was a problem reading from the stream. Again, a production program should handle these errors more gracefully, but we’re choosing to stop the program in the error case for simplicity.

 The browser signals the end of an HTTP request by sending two newline characters in a row, so to get one request from the stream, we take lines until we get a line that is the empty string. Once we’ve collected the lines into the vector, we’re printing them out using pretty debug formatting so we can take a look at the instructions the web browser is sending to our server.

 Let’s try this code! Start the program and make a request in a web browser again. Note that we’ll still get an error page in the browser, but our program’s output in the terminal will now look similar to this:

 
```
$ cargo run
   Compiling hello v0.1.0 (file:///projects/hello)
    Finished dev [unoptimized + debuginfo] target(s) in 0.42s
     Running `target/debug/hello`
Request: [
    "GET / HTTP/1.1",
    "Host: 127.0.0.1:7878",
    "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:99.0) Gecko/20100101 Firefox/99.0",
    "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
    "Accept-Language: en-US,en;q=0.5",
    "Accept-Encoding: gzip, deflate, br",
    "DNT: 1",
    "Connection: keep-alive",
    "Upgrade-Insecure-Requests: 1",
    "Sec-Fetch-Dest: document",
    "Sec-Fetch-Mode: navigate",
    "Sec-Fetch-Site: none",
    "Sec-Fetch-User: ?1",
    "Cache-Control: max-age=0",
]

```
 Depending on your browser, you might get slightly different output. Now that we’re printing the request data, we can see why we get multiple connections from one browser request by looking at the path after `GET` in the first line of the request. If the repeated connections are all requesting */*, we know the browser is trying to fetch */* repeatedly because it’s not getting a response from our program.

 Let’s break down this request data to understand what the browser is asking of our program.

 ### A Closer Look at an HTTP Request

 HTTP is a text-based protocol, and a request takes this format:

 
```
Method Request-URI HTTP-Version CRLF
headers CRLF
message-body

```
 The first line is the *request line* that holds information about what the client is requesting. The first part of the request line indicates the *method* being used, such as `GET` or `POST`, which describes how the client is making this request. Our client used a `GET` request, which means it is asking for information.

 The next part of the request line is */*, which indicates the *Uniform Resource Identifier* *(URI)* the client is requesting: a URI is almost, but not quite, the same as a *Uniform Resource Locator* *(URL)*. The difference between URIs and URLs isn’t important for our purposes in this chapter, but the HTTP spec uses the term URI, so we can just mentally substitute URL for URI here.

 The last part is the HTTP version the client uses, and then the request line ends in a *CRLF sequence*. (CRLF stands for *carriage return* and *line feed*, which are terms from the typewriter days!) The CRLF sequence can also be written as `\r\n`, where `\r` is a carriage return and `\n` is a line feed. The CRLF sequence separates the request line from the rest of the request data. Note that when the CRLF is printed, we see a new line start rather than `\r\n`.

 Looking at the request line data we received from running our program so far, we see that `GET` is the method, */* is the request URI, and `HTTP/1.1` is the version.

 After the request line, the remaining lines starting from `Host:` onward are headers. `GET` requests have no body.

 Try making a request from a different browser or asking for a different address, such as *127.0.0.1:7878/test*, to see how the request data changes.

 Now that we know what the browser is asking for, let’s send back some data!

 ### Writing a Response

 We’re going to implement sending data in response to a client request. Responses have the following format:

 
```
HTTP-Version Status-Code Reason-Phrase CRLF
headers CRLF
message-body

```
 The first line is a *status line* that contains the HTTP version used in the response, a numeric status code that summarizes the result of the request, and a reason phrase that provides a text description of the status code. After the CRLF sequence are any headers, another CRLF sequence, and the body of the response.

 Here is an example response that uses HTTP version 1.1, has a status code of 200, an OK reason phrase, no headers, and no body:

 
```
HTTP/1.1 200 OK\r\n\r\n

```
 The status code 200 is the standard success response. The text is a tiny successful HTTP response. Let’s write this to the stream as our response to a successful request! From the `handle_connection` function, remove the `println!` that was printing the request data and replace it with the code in Listing 20-3.

 Filename: src/main.rs

 
```
use std::{
    io::{prelude::*, BufReader},
    net::{TcpListener, TcpStream},
};

fn main() {
    let listener = TcpListener::bind("127.0.0.1:7878").unwrap();

    for stream in listener.incoming() {
        let stream = stream.unwrap();

        handle_connection(stream);
    }
}

fn handle_connection(mut stream: TcpStream) {
    let buf_reader = BufReader::new(&mut stream);
    let http_request: Vec<_> = buf_reader
        .lines()
        .map(|result| result.unwrap())
        .take_while(|line| !line.is_empty())
        .collect();

    let response = "HTTP/1.1 200 OK\r\n\r\n";

    stream.write_all(response.as_bytes()).unwrap();
}
```
 Listing 20-3: Writing a tiny successful HTTP response to the stream

 The first new line defines the `response` variable that holds the success message’s data. Then we call `as_bytes` on our `response` to convert the string data to bytes. The `write_all` method on `stream` takes a `&[u8]` and sends those bytes directly down the connection. Because the `write_all` operation could fail, we use `unwrap` on any error result as before. Again, in a real application you would add error handling here.

 With these changes, let’s run our code and make a request. We’re no longer printing any data to the terminal, so we won’t see any output other than the output from Cargo. When you load *127.0.0.1:7878* in a web browser, you should get a blank page instead of an error. You’ve just hand-coded receiving an HTTP request and sending a response!

 ### Returning Real HTML

 Let’s implement the functionality for returning more than a blank page. Create the new file *hello.html* in the root of your project directory, not in the *src* directory. You can input any HTML you want; Listing 20-4 shows one possibility.

 Filename: hello.html

 
```
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Hello!</title>
  </head>
  <body>
    <h1>Hello!</h1>
    <p>Hi from Rust</p>
  </body>
</html>

```
 Listing 20-4: A sample HTML file to return in a response

 This is a minimal HTML5 document with a heading and some text. To return this from the server when a request is received, we’ll modify `handle_connection` as shown in Listing 20-5 to read the HTML file, add it to the response as a body, and send it.

 Filename: src/main.rs

 
```
use std::{
    fs,
    io::{prelude::*, BufReader},
    net::{TcpListener, TcpStream},
};
// --snip--

fn main() {
    let listener = TcpListener::bind("127.0.0.1:7878").unwrap();

    for stream in listener.incoming() {
        let stream = stream.unwrap();

        handle_connection(stream);
    }
}

fn handle_connection(mut stream: TcpStream) {
    let buf_reader = BufReader::new(&mut stream);
    let http_request: Vec<_> = buf_reader
        .lines()
        .map(|result| result.unwrap())
        .take_while(|line| !line.is_empty())
        .collect();

    let status_line = "HTTP/1.1 200 OK";
    let contents = fs::read_to_string("hello.html").unwrap();
    let length = contents.len();

    let response =
        format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");

    stream.write_all(response.as_bytes()).unwrap();
}
```
 Listing 20-5: Sending the contents of *hello.html* as the body of the response

 We’ve added `fs` to the `use` statement to bring the standard library’s filesystem module into scope. The code for reading the contents of a file to a string should look familiar; we used it in Chapter 12 when we read the contents of a file for our I/O project in Listing 12-4.

 Next, we use `format!` to add the file’s contents as the body of the success response. To ensure a valid HTTP response, we add the `Content-Length` header which is set to the size of our response body, in this case the size of `hello.html`.

 Run this code with `cargo run` and load *127.0.0.1:7878* in your browser; you should see your HTML rendered!

 Currently, we’re ignoring the request data in `http_request` and just sending back the contents of the HTML file unconditionally. That means if you try requesting *127.0.0.1:7878/something-else* in your browser, you’ll still get back this same HTML response. At the moment, our server is very limited and does not do what most web servers do. We want to customize our responses depending on the request and only send back the HTML file for a well-formed request to */*.

 ### Validating the Request and Selectively Responding

 Right now, our web server will return the HTML in the file no matter what the client requested. Let’s add functionality to check that the browser is requesting */* before returning the HTML file and return an error if the browser requests anything else. For this we need to modify `handle_connection`, as shown in Listing 20-6. This new code checks the content of the request received against what we know a request for */* looks like and adds `if` and `else` blocks to treat requests differently.

 Filename: src/main.rs

 
```
use std::{
    fs,
    io::{prelude::*, BufReader},
    net::{TcpListener, TcpStream},
};

fn main() {
    let listener = TcpListener::bind("127.0.0.1:7878").unwrap();

    for stream in listener.incoming() {
        let stream = stream.unwrap();

        handle_connection(stream);
    }
}
// --snip--

fn handle_connection(mut stream: TcpStream) {
    let buf_reader = BufReader::new(&mut stream);
    let request_line = buf_reader.lines().next().unwrap().unwrap();

    if request_line == "GET / HTTP/1.1" {
        let status_line = "HTTP/1.1 200 OK";
        let contents = fs::read_to_string("hello.html").unwrap();
        let length = contents.len();

        let response = format!(
            "{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}"
        );

        stream.write_all(response.as_bytes()).unwrap();
    } else {
        // some other request
    }
}
```
 Listing 20-6: Handling requests to */* differently from other requests

 We’re only going to be looking at the first line of the HTTP request, so rather than reading the entire request into a vector, we’re calling `next` to get the first item from the iterator. The first `unwrap` takes care of the `Option` and stops the program if the iterator has no items. The second `unwrap` handles the `Result` and has the same effect as the `unwrap` that was in the `map` added in Listing 20-2.

 Next, we check the `request_line` to see if it equals the request line of a GET request to the */* path. If it does, the `if` block returns the contents of our HTML file.

 If the `request_line` does *not* equal the GET request to the */* path, it means we’ve received some other request. We’ll add code to the `else` block in a moment to respond to all other requests.

 Run this code now and request *127.0.0.1:7878*; you should get the HTML in *hello.html*. If you make any other request, such as *127.0.0.1:7878/something-else*, you’ll get a connection error like those you saw when running the code in Listing 20-1 and Listing 20-2.

 Now let’s add the code in Listing 20-7 to the `else` block to return a response with the status code 404, which signals that the content for the request was not found. We’ll also return some HTML for a page to render in the browser indicating the response to the end user.

 Filename: src/main.rs

 
```
use std::{
    fs,
    io::{prelude::*, BufReader},
    net::{TcpListener, TcpStream},
};

fn main() {
    let listener = TcpListener::bind("127.0.0.1:7878").unwrap();

    for stream in listener.incoming() {
        let stream = stream.unwrap();

        handle_connection(stream);
    }
}

fn handle_connection(mut stream: TcpStream) {
    let buf_reader = BufReader::new(&mut stream);
    let request_line = buf_reader.lines().next().unwrap().unwrap();

    if request_line == "GET / HTTP/1.1" {
        let status_line = "HTTP/1.1 200 OK";
        let contents = fs::read_to_string("hello.html").unwrap();
        let length = contents.len();

        let response = format!(
            "{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}"
        );

        stream.write_all(response.as_bytes()).unwrap();
    // --snip--
    } else {
        let status_line = "HTTP/1.1 404 NOT FOUND";
        let contents = fs::read_to_string("404.html").unwrap();
        let length = contents.len();

        let response = format!(
            "{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}"
        );

        stream.write_all(response.as_bytes()).unwrap();
    }
}
```
 Listing 20-7: Responding with status code 404 and an error page if anything other than */* was requested

 Here, our response has a status line with status code 404 and the reason phrase `NOT FOUND`. The body of the response will be the HTML in the file *404.html*. You’ll need to create a *404.html* file next to *hello.html* for the error page; again feel free to use any HTML you want or use the example HTML in Listing 20-8.

 Filename: 404.html

 
```
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Hello!</title>
  </head>
  <body>
    <h1>Oops!</h1>
    <p>Sorry, I don't know what you're asking for.</p>
  </body>
</html>

```
 Listing 20-8: Sample content for the page to send back with any 404 response

 With these changes, run your server again. Requesting *127.0.0.1:7878* should return the contents of *hello.html*, and any other request, like *127.0.0.1:7878/foo*, should return the error HTML from *404.html*.

 ### A Touch of Refactoring

 At the moment the `if` and `else` blocks have a lot of repetition: they’re both reading files and writing the contents of the files to the stream. The only differences are the status line and the filename. Let’s make the code more concise by pulling out those differences into separate `if` and `else` lines that will assign the values of the status line and the filename to variables; we can then use those variables unconditionally in the code to read the file and write the response. Listing 20-9 shows the resulting code after replacing the large `if` and `else` blocks.

 Filename: src/main.rs

 
```
use std::{
    fs,
    io::{prelude::*, BufReader},
    net::{TcpListener, TcpStream},
};

fn main() {
    let listener = TcpListener::bind("127.0.0.1:7878").unwrap();

    for stream in listener.incoming() {
        let stream = stream.unwrap();

        handle_connection(stream);
    }
}
// --snip--

fn handle_connection(mut stream: TcpStream) {
    // --snip--
    let buf_reader = BufReader::new(&mut stream);
    let request_line = buf_reader.lines().next().unwrap().unwrap();

    let (status_line, filename) = if request_line == "GET / HTTP/1.1" {
        ("HTTP/1.1 200 OK", "hello.html")
    } else {
        ("HTTP/1.1 404 NOT FOUND", "404.html")
    };

    let contents = fs::read_to_string(filename).unwrap();
    let length = contents.len();

    let response =
        format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");

    stream.write_all(response.as_bytes()).unwrap();
}
```
 Listing 20-9: Refactoring the `if` and `else` blocks to contain only the code that differs between the two cases

 Now the `if` and `else` blocks only return the appropriate values for the status line and filename in a tuple; we then use destructuring to assign these two values to `status_line` and `filename` using a pattern in the `let` statement, as discussed in Chapter 18.

 The previously duplicated code is now outside the `if` and `else` blocks and uses the `status_line` and `filename` variables. This makes it easier to see the difference between the two cases, and it means we have only one place to update the code if we want to change how the file reading and response writing work. The behavior of the code in Listing 20-9 will be the same as that in Listing 20-8.

 Awesome! We now have a simple web server in approximately 40 lines of Rust code that responds to one request with a page of content and responds to all other requests with a 404 response.

 Currently, our server runs in a single thread, meaning it can only serve one request at a time. Let’s examine how that can be a problem by simulating some slow requests. Then we’ll fix it so our server can handle multiple requests at once.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch20-01-single-threaded.html>

Advanced Functions and Closures
===============================

 This section explores some advanced features related to functions and closures, including function pointers and returning closures.

 ### Function Pointers

 We’ve talked about how to pass closures to functions; you can also pass regular functions to functions! This technique is useful when you want to pass a function you’ve already defined rather than defining a new closure. Functions coerce to the type `fn` (with a lowercase f), not to be confused with the `Fn` closure trait. The `fn` type is called a *function pointer*. Passing functions with function pointers will allow you to use functions as arguments to other functions.

 The syntax for specifying that a parameter is a function pointer is similar to that of closures, as shown in Listing 19-27, where we’ve defined a function `add_one` that adds one to its parameter. The function `do_twice` takes two parameters: a function pointer to any function that takes an `i32` parameter and returns an `i32`, and one `i32 value`. The `do_twice` function calls the function `f` twice, passing it the `arg` value, then adds the two function call results together. The `main` function calls `do_twice` with the arguments `add_one` and `5`.

 Filename: src/main.rs

 
```
fn add_one(x: i32) -> i32 {
    x + 1
}

fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 {
    f(arg) + f(arg)
}

fn main() {
    let answer = do_twice(add_one, 5);

    println!("The answer is: {}", answer);
}
```
 Listing 19-27: Using the `fn` type to accept a function pointer as an argument

 This code prints `The answer is: 12`. We specify that the parameter `f` in `do_twice` is an `fn` that takes one parameter of type `i32` and returns an `i32`. We can then call `f` in the body of `do_twice`. In `main`, we can pass the function name `add_one` as the first argument to `do_twice`.

 Unlike closures, `fn` is a type rather than a trait, so we specify `fn` as the parameter type directly rather than declaring a generic type parameter with one of the `Fn` traits as a trait bound.

 Function pointers implement all three of the closure traits (`Fn`, `FnMut`, and `FnOnce`), meaning you can always pass a function pointer as an argument for a function that expects a closure. It’s best to write functions using a generic type and one of the closure traits so your functions can accept either functions or closures.

 That said, one example of where you would want to only accept `fn` and not closures is when interfacing with external code that doesn’t have closures: C functions can accept functions as arguments, but C doesn’t have closures.

 As an example of where you could use either a closure defined inline or a named function, let’s look at a use of the `map` method provided by the `Iterator` trait in the standard library. To use the `map` function to turn a vector of numbers into a vector of strings, we could use a closure, like this:

 
```
fn main() {
    let list_of_numbers = vec![1, 2, 3];
    let list_of_strings: Vec<String> =
        list_of_numbers.iter().map(|i| i.to_string()).collect();
}
```
 Or we could name a function as the argument to `map` instead of the closure, like this:

 
```
fn main() {
    let list_of_numbers = vec![1, 2, 3];
    let list_of_strings: Vec<String> =
        list_of_numbers.iter().map(ToString::to_string).collect();
}
```
 Note that we must use the fully qualified syntax that we talked about earlier in the [“Advanced Traits”](ch19-03-advanced-traits#advanced-traits) section because there are multiple functions available named `to_string`. Here, we’re using the `to_string` function defined in the `ToString` trait, which the standard library has implemented for any type that implements `Display`.

 Recall from the [“Enum values”](ch06-01-defining-an-enum#enum-values) section of Chapter 6 that the name of each enum variant that we define also becomes an initializer function. We can use these initializer functions as function pointers that implement the closure traits, which means we can specify the initializer functions as arguments for methods that take closures, like so:

 
```
fn main() {
    enum Status {
        Value(u32),
        Stop,
    }

    let list_of_statuses: Vec<Status> = (0u32..20).map(Status::Value).collect();
}
```
 Here we create `Status::Value` instances using each `u32` value in the range that `map` is called on by using the initializer function of `Status::Value`. Some people prefer this style, and some people prefer to use closures. They compile to the same code, so use whichever style is clearer to you.

 ### Returning Closures

 Closures are represented by traits, which means you can’t return closures directly. In most cases where you might want to return a trait, you can instead use the concrete type that implements the trait as the return value of the function. However, you can’t do that with closures because they don’t have a concrete type that is returnable; you’re not allowed to use the function pointer `fn` as a return type, for example.

 The following code tries to return a closure directly, but it won’t compile:

 
```
fn returns_closure() -> dyn Fn(i32) -> i32 {
    |x| x + 1
}
```
 The compiler error is as follows:

 
```
$ cargo build
   Compiling functions-example v0.1.0 (file:///projects/functions-example)
error[E0746]: return type cannot have an unboxed trait object
 --> src/lib.rs:1:25
  |
1 | fn returns_closure() -> dyn Fn(i32) -> i32 {
  |                         ^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
  |
  = note: for information on `impl Trait`, see <https://doc.rust-lang.org/book/ch10-02-traits.html#returning-types-that-implement-traits>
help: use `impl Fn(i32) -> i32` as the return type, as all return paths are of type `[closure@src/lib.rs:2:5: 2:8]`, which implements `Fn(i32) -> i32`
  |
1 | fn returns_closure() -> impl Fn(i32) -> i32 {
  |                         ~~~~~~~~~~~~~~~~~~~

For more information about this error, try `rustc --explain E0746`.
error: could not compile `functions-example` due to previous error

```
 The error references the `Sized` trait again! Rust doesn’t know how much space it will need to store the closure. We saw a solution to this problem earlier. We can use a trait object:

 
```
fn returns_closure() -> Box<dyn Fn(i32) -> i32> {
    Box::new(|x| x + 1)
}
```
 This code will compile just fine. For more about trait objects, refer to the section [“Using Trait Objects That Allow for Values of Different Types”](ch17-02-trait-objects#using-trait-objects-that-allow-for-values-of-different-types) in Chapter 17.

 Next, let’s look at macros!



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch19-05-advanced-functions-and-closures.html>

Turning Our Single-Threaded Server into a Multithreaded Server
==============================================================

 Right now, the server will process each request in turn, meaning it won’t process a second connection until the first is finished processing. If the server received more and more requests, this serial execution would be less and less optimal. If the server receives a request that takes a long time to process, subsequent requests will have to wait until the long request is finished, even if the new requests can be processed quickly. We’ll need to fix this, but first, we’ll look at the problem in action.

 ### Simulating a Slow Request in the Current Server Implementation

 We’ll look at how a slow-processing request can affect other requests made to our current server implementation. Listing 20-10 implements handling a request to */sleep* with a simulated slow response that will cause the server to sleep for 5 seconds before responding.

 Filename: src/main.rs

 
```
use std::{
    fs,
    io::{prelude::*, BufReader},
    net::{TcpListener, TcpStream},
    thread,
    time::Duration,
};
// --snip--

fn main() {
    let listener = TcpListener::bind("127.0.0.1:7878").unwrap();

    for stream in listener.incoming() {
        let stream = stream.unwrap();

        handle_connection(stream);
    }
}

fn handle_connection(mut stream: TcpStream) {
    // --snip--

    let buf_reader = BufReader::new(&mut stream);
    let request_line = buf_reader.lines().next().unwrap().unwrap();

    let (status_line, filename) = match &request_line[..] {
        "GET / HTTP/1.1" => ("HTTP/1.1 200 OK", "hello.html"),
        "GET /sleep HTTP/1.1" => {
            thread::sleep(Duration::from_secs(5));
            ("HTTP/1.1 200 OK", "hello.html")
        }
        _ => ("HTTP/1.1 404 NOT FOUND", "404.html"),
    };

    // --snip--

    let contents = fs::read_to_string(filename).unwrap();
    let length = contents.len();

    let response =
        format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");

    stream.write_all(response.as_bytes()).unwrap();
}
```
 Listing 20-10: Simulating a slow request by sleeping for 5 seconds

 We switched from `if` to `match` now that we have three cases. We need to explicitly match on a slice of `request_line` to pattern match against the string literal values; `match` doesn’t do automatic referencing and dereferencing like the equality method does.

 The first arm is the same as the `if` block from Listing 20-9. The second arm matches a request to */sleep*. When that request is received, the server will sleep for 5 seconds before rendering the successful HTML page. The third arm is the same as the `else` block from Listing 20-9.

 You can see how primitive our server is: real libraries would handle the recognition of multiple requests in a much less verbose way!

 Start the server using `cargo run`. Then open two browser windows: one for *http://127.0.0.1:7878/* and the other for *http://127.0.0.1:7878/sleep*. If you enter the */* URI a few times, as before, you’ll see it respond quickly. But if you enter */sleep* and then load */*, you’ll see that */* waits until `sleep` has slept for its full 5 seconds before loading.

 There are multiple techniques we could use to avoid requests backing up behind a slow request; the one we’ll implement is a thread pool.

 ### Improving Throughput with a Thread Pool

 A *thread pool* is a group of spawned threads that are waiting and ready to handle a task. When the program receives a new task, it assigns one of the threads in the pool to the task, and that thread will process the task. The remaining threads in the pool are available to handle any other tasks that come in while the first thread is processing. When the first thread is done processing its task, it’s returned to the pool of idle threads, ready to handle a new task. A thread pool allows you to process connections concurrently, increasing the throughput of your server.

 We’ll limit the number of threads in the pool to a small number to protect us from Denial of Service (DoS) attacks; if we had our program create a new thread for each request as it came in, someone making 10 million requests to our server could create havoc by using up all our server’s resources and grinding the processing of requests to a halt.

 Rather than spawning unlimited threads, then, we’ll have a fixed number of threads waiting in the pool. Requests that come in are sent to the pool for processing. The pool will maintain a queue of incoming requests. Each of the threads in the pool will pop off a request from this queue, handle the request, and then ask the queue for another request. With this design, we can process up to `N` requests concurrently, where `N` is the number of threads. If each thread is responding to a long-running request, subsequent requests can still back up in the queue, but we’ve increased the number of long-running requests we can handle before reaching that point.

 This technique is just one of many ways to improve the throughput of a web server. Other options you might explore are the *fork/join model*, the *single-threaded async I/O model*, or the *multi-threaded async I/O model*. If you’re interested in this topic, you can read more about other solutions and try to implement them; with a low-level language like Rust, all of these options are possible.

 Before we begin implementing a thread pool, let’s talk about what using the pool should look like. When you’re trying to design code, writing the client interface first can help guide your design. Write the API of the code so it’s structured in the way you want to call it; then implement the functionality within that structure rather than implementing the functionality and then designing the public API.

 Similar to how we used test-driven development in the project in Chapter 12, we’ll use compiler-driven development here. We’ll write the code that calls the functions we want, and then we’ll look at errors from the compiler to determine what we should change next to get the code to work. Before we do that, however, we’ll explore the technique we’re not going to use as a starting point.

 #### Spawning a Thread for Each Request

 First, let’s explore how our code might look if it did create a new thread for every connection. As mentioned earlier, this isn’t our final plan due to the problems with potentially spawning an unlimited number of threads, but it is a starting point to get a working multithreaded server first. Then we’ll add the thread pool as an improvement, and contrasting the two solutions will be easier. Listing 20-11 shows the changes to make to `main` to spawn a new thread to handle each stream within the `for` loop.

 Filename: src/main.rs

 
```
use std::{
    fs,
    io::{prelude::*, BufReader},
    net::{TcpListener, TcpStream},
    thread,
    time::Duration,
};

fn main() {
    let listener = TcpListener::bind("127.0.0.1:7878").unwrap();

    for stream in listener.incoming() {
        let stream = stream.unwrap();

        thread::spawn(|| {
            handle_connection(stream);
        });
    }
}

fn handle_connection(mut stream: TcpStream) {
    let buf_reader = BufReader::new(&mut stream);
    let request_line = buf_reader.lines().next().unwrap().unwrap();

    let (status_line, filename) = match &request_line[..] {
        "GET / HTTP/1.1" => ("HTTP/1.1 200 OK", "hello.html"),
        "GET /sleep HTTP/1.1" => {
            thread::sleep(Duration::from_secs(5));
            ("HTTP/1.1 200 OK", "hello.html")
        }
        _ => ("HTTP/1.1 404 NOT FOUND", "404.html"),
    };

    let contents = fs::read_to_string(filename).unwrap();
    let length = contents.len();

    let response =
        format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");

    stream.write_all(response.as_bytes()).unwrap();
}
```
 Listing 20-11: Spawning a new thread for each stream

 As you learned in Chapter 16, `thread::spawn` will create a new thread and then run the code in the closure in the new thread. If you run this code and load */sleep* in your browser, then */* in two more browser tabs, you’ll indeed see that the requests to */* don’t have to wait for */sleep* to finish. However, as we mentioned, this will eventually overwhelm the system because you’d be making new threads without any limit.

 #### Creating a Finite Number of Threads

 We want our thread pool to work in a similar, familiar way so switching from threads to a thread pool doesn’t require large changes to the code that uses our API. Listing 20-12 shows the hypothetical interface for a `ThreadPool` struct we want to use instead of `thread::spawn`.

 Filename: src/main.rs

 
```
use std::{
    fs,
    io::{prelude::*, BufReader},
    net::{TcpListener, TcpStream},
    thread,
    time::Duration,
};

fn main() {
    let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
    let pool = ThreadPool::new(4);

    for stream in listener.incoming() {
        let stream = stream.unwrap();

        pool.execute(|| {
            handle_connection(stream);
        });
    }
}

fn handle_connection(mut stream: TcpStream) {
    let buf_reader = BufReader::new(&mut stream);
    let request_line = buf_reader.lines().next().unwrap().unwrap();

    let (status_line, filename) = match &request_line[..] {
        "GET / HTTP/1.1" => ("HTTP/1.1 200 OK", "hello.html"),
        "GET /sleep HTTP/1.1" => {
            thread::sleep(Duration::from_secs(5));
            ("HTTP/1.1 200 OK", "hello.html")
        }
        _ => ("HTTP/1.1 404 NOT FOUND", "404.html"),
    };

    let contents = fs::read_to_string(filename).unwrap();
    let length = contents.len();

    let response =
        format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");

    stream.write_all(response.as_bytes()).unwrap();
}
```
 Listing 20-12: Our ideal `ThreadPool` interface

 We use `ThreadPool::new` to create a new thread pool with a configurable number of threads, in this case four. Then, in the `for` loop, `pool.execute` has a similar interface as `thread::spawn` in that it takes a closure the pool should run for each stream. We need to implement `pool.execute` so it takes the closure and gives it to a thread in the pool to run. This code won’t yet compile, but we’ll try so the compiler can guide us in how to fix it.

 #### Building `ThreadPool` Using Compiler Driven Development

 Make the changes in Listing 20-12 to *src/main.rs*, and then let’s use the compiler errors from `cargo check` to drive our development. Here is the first error we get:

 
```
$ cargo check
    Checking hello v0.1.0 (file:///projects/hello)
error[E0433]: failed to resolve: use of undeclared type `ThreadPool`
  --> src/main.rs:11:16
   |
11 |     let pool = ThreadPool::new(4);
   |                ^^^^^^^^^^ use of undeclared type `ThreadPool`

For more information about this error, try `rustc --explain E0433`.
error: could not compile `hello` due to previous error

```
 Great! This error tells us we need a `ThreadPool` type or module, so we’ll build one now. Our `ThreadPool` implementation will be independent of the kind of work our web server is doing. So, let’s switch the `hello` crate from a binary crate to a library crate to hold our `ThreadPool` implementation. After we change to a library crate, we could also use the separate thread pool library for any work we want to do using a thread pool, not just for serving web requests.

 Create a *src/lib.rs* that contains the following, which is the simplest definition of a `ThreadPool` struct that we can have for now:

 Filename: src/lib.rs

 
```
pub struct ThreadPool;
```
 Then edit *main.rs* file to bring `ThreadPool` into scope from the library crate by adding the following code to the top of *src/main.rs*:

 Filename: src/main.rs

 
```
use hello::ThreadPool;
use std::{
    fs,
    io::{prelude::*, BufReader},
    net::{TcpListener, TcpStream},
    thread,
    time::Duration,
};

fn main() {
    let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
    let pool = ThreadPool::new(4);

    for stream in listener.incoming() {
        let stream = stream.unwrap();

        pool.execute(|| {
            handle_connection(stream);
        });
    }
}

fn handle_connection(mut stream: TcpStream) {
    let buf_reader = BufReader::new(&mut stream);
    let request_line = buf_reader.lines().next().unwrap().unwrap();

    let (status_line, filename) = match &request_line[..] {
        "GET / HTTP/1.1" => ("HTTP/1.1 200 OK", "hello.html"),
        "GET /sleep HTTP/1.1" => {
            thread::sleep(Duration::from_secs(5));
            ("HTTP/1.1 200 OK", "hello.html")
        }
        _ => ("HTTP/1.1 404 NOT FOUND", "404.html"),
    };

    let contents = fs::read_to_string(filename).unwrap();
    let length = contents.len();

    let response =
        format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");

    stream.write_all(response.as_bytes()).unwrap();
}
```
 This code still won’t work, but let’s check it again to get the next error that we need to address:

 
```
$ cargo check
    Checking hello v0.1.0 (file:///projects/hello)
error[E0599]: no function or associated item named `new` found for struct `ThreadPool` in the current scope
  --> src/main.rs:12:28
   |
12 |     let pool = ThreadPool::new(4);
   |                            ^^^ function or associated item not found in `ThreadPool`

For more information about this error, try `rustc --explain E0599`.
error: could not compile `hello` due to previous error

```
 This error indicates that next we need to create an associated function named `new` for `ThreadPool`. We also know that `new` needs to have one parameter that can accept `4` as an argument and should return a `ThreadPool` instance. Let’s implement the simplest `new` function that will have those characteristics:

 Filename: src/lib.rs

 
```
pub struct ThreadPool;

impl ThreadPool {
    pub fn new(size: usize) -> ThreadPool {
        ThreadPool
    }
}
```
 We chose `usize` as the type of the `size` parameter, because we know that a negative number of threads doesn’t make any sense. We also know we’ll use this 4 as the number of elements in a collection of threads, which is what the `usize` type is for, as discussed in the [“Integer Types”](ch03-02-data-types#integer-types) section of Chapter 3.

 Let’s check the code again:

 
```
$ cargo check
    Checking hello v0.1.0 (file:///projects/hello)
error[E0599]: no method named `execute` found for struct `ThreadPool` in the current scope
  --> src/main.rs:17:14
   |
17 |         pool.execute(|| {
   |              ^^^^^^^ method not found in `ThreadPool`

For more information about this error, try `rustc --explain E0599`.
error: could not compile `hello` due to previous error

```
 Now the error occurs because we don’t have an `execute` method on `ThreadPool`. Recall from the [“Creating a Finite Number of Threads”](#creating-a-finite-number-of-threads) section that we decided our thread pool should have an interface similar to `thread::spawn`. In addition, we’ll implement the `execute` function so it takes the closure it’s given and gives it to an idle thread in the pool to run.

 We’ll define the `execute` method on `ThreadPool` to take a closure as a parameter. Recall from the [“Moving Captured Values Out of the Closure and the `Fn` Traits”](ch13-01-closures#moving-captured-values-out-of-the-closure-and-the-fn-traits) section in Chapter 13 that we can take closures as parameters with three different traits: `Fn`, `FnMut`, and `FnOnce`. We need to decide which kind of closure to use here. We know we’ll end up doing something similar to the standard library `thread::spawn` implementation, so we can look at what bounds the signature of `thread::spawn` has on its parameter. The documentation shows us the following:

 
```
pub fn spawn<F, T>(f: F) -> JoinHandle<T>
    where
        F: FnOnce() -> T,
        F: Send + 'static,
        T: Send + 'static,
```
 The `F` type parameter is the one we’re concerned with here; the `T` type parameter is related to the return value, and we’re not concerned with that. We can see that `spawn` uses `FnOnce` as the trait bound on `F`. This is probably what we want as well, because we’ll eventually pass the argument we get in `execute` to `spawn`. We can be further confident that `FnOnce` is the trait we want to use because the thread for running a request will only execute that request’s closure one time, which matches the `Once` in `FnOnce`.

 The `F` type parameter also has the trait bound `Send` and the lifetime bound `'static`, which are useful in our situation: we need `Send` to transfer the closure from one thread to another and `'static` because we don’t know how long the thread will take to execute. Let’s create an `execute` method on `ThreadPool` that will take a generic parameter of type `F` with these bounds:

 Filename: src/lib.rs

 
```
pub struct ThreadPool;

impl ThreadPool {
    // --snip--
    pub fn new(size: usize) -> ThreadPool {
        ThreadPool
    }

    pub fn execute<F>(&self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
    }
}
```
 We still use the `()` after `FnOnce` because this `FnOnce` represents a closure that takes no parameters and returns the unit type `()`. Just like function definitions, the return type can be omitted from the signature, but even if we have no parameters, we still need the parentheses.

 Again, this is the simplest implementation of the `execute` method: it does nothing, but we’re trying only to make our code compile. Let’s check it again:

 
```
$ cargo check
    Checking hello v0.1.0 (file:///projects/hello)
    Finished dev [unoptimized + debuginfo] target(s) in 0.24s

```
 It compiles! But note that if you try `cargo run` and make a request in the browser, you’ll see the errors in the browser that we saw at the beginning of the chapter. Our library isn’t actually calling the closure passed to `execute` yet!

 
>  Note: A saying you might hear about languages with strict compilers, such as Haskell and Rust, is “if the code compiles, it works.” But this saying is not universally true. Our project compiles, but it does absolutely nothing! If we were building a real, complete project, this would be a good time to start writing unit tests to check that the code compiles *and* has the behavior we want.
> 
>  

 #### Validating the Number of Threads in `new`

 We aren’t doing anything with the parameters to `new` and `execute`. Let’s implement the bodies of these functions with the behavior we want. To start, let’s think about `new`. Earlier we chose an unsigned type for the `size` parameter, because a pool with a negative number of threads makes no sense. However, a pool with zero threads also makes no sense, yet zero is a perfectly valid `usize`. We’ll add code to check that `size` is greater than zero before we return a `ThreadPool` instance and have the program panic if it receives a zero by using the `assert!` macro, as shown in Listing 20-13.

 Filename: src/lib.rs

 
```
pub struct ThreadPool;

impl ThreadPool {
    /// Create a new ThreadPool.
    ///
    /// The size is the number of threads in the pool.
    ///
    /// # Panics
    ///
    /// The `new` function will panic if the size is zero.
    pub fn new(size: usize) -> ThreadPool {
        assert!(size > 0);

        ThreadPool
    }

    // --snip--
    pub fn execute<F>(&self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
    }
}
```
 Listing 20-13: Implementing `ThreadPool::new` to panic if `size` is zero

 We’ve also added some documentation for our `ThreadPool` with doc comments. Note that we followed good documentation practices by adding a section that calls out the situations in which our function can panic, as discussed in Chapter 14. Try running `cargo doc --open` and clicking the `ThreadPool` struct to see what the generated docs for `new` look like!

 Instead of adding the `assert!` macro as we’ve done here, we could change `new` into `build` and return a `Result` like we did with `Config::build` in the I/O project in Listing 12-9. But we’ve decided in this case that trying to create a thread pool without any threads should be an unrecoverable error. If you’re feeling ambitious, try to write a function named `build` with the following signature to compare with the `new` function:

 
```
pub fn build(size: usize) -> Result<ThreadPool, PoolCreationError> {
```
 #### Creating Space to Store the Threads

 Now that we have a way to know we have a valid number of threads to store in the pool, we can create those threads and store them in the `ThreadPool` struct before returning the struct. But how do we “store” a thread? Let’s take another look at the `thread::spawn` signature:

 
```
pub fn spawn<F, T>(f: F) -> JoinHandle<T>
    where
        F: FnOnce() -> T,
        F: Send + 'static,
        T: Send + 'static,
```
 The `spawn` function returns a `JoinHandle<T>`, where `T` is the type that the closure returns. Let’s try using `JoinHandle` too and see what happens. In our case, the closures we’re passing to the thread pool will handle the connection and not return anything, so `T` will be the unit type `()`.

 The code in Listing 20-14 will compile but doesn’t create any threads yet. We’ve changed the definition of `ThreadPool` to hold a vector of `thread::JoinHandle<()>` instances, initialized the vector with a capacity of `size`, set up a `for` loop that will run some code to create the threads, and returned a `ThreadPool` instance containing them.

 Filename: src/lib.rs

 
```
use std::thread;

pub struct ThreadPool {
    threads: Vec<thread::JoinHandle<()>>,
}

impl ThreadPool {
    // --snip--
    /// Create a new ThreadPool.
    ///
    /// The size is the number of threads in the pool.
    ///
    /// # Panics
    ///
    /// The `new` function will panic if the size is zero.
    pub fn new(size: usize) -> ThreadPool {
        assert!(size > 0);

        let mut threads = Vec::with_capacity(size);

        for _ in 0..size {
            // create some threads and store them in the vector
        }

        ThreadPool { threads }
    }
    // --snip--

    pub fn execute<F>(&self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
    }
}
```
 Listing 20-14: Creating a vector for `ThreadPool` to hold the threads

 We’ve brought `std::thread` into scope in the library crate, because we’re using `thread::JoinHandle` as the type of the items in the vector in `ThreadPool`.

 Once a valid size is received, our `ThreadPool` creates a new vector that can hold `size` items. The `with_capacity` function performs the same task as `Vec::new` but with an important difference: it preallocates space in the vector. Because we know we need to store `size` elements in the vector, doing this allocation up front is slightly more efficient than using `Vec::new`, which resizes itself as elements are inserted.

 When you run `cargo check` again, it should succeed.

 #### A `Worker` Struct Responsible for Sending Code from the `ThreadPool` to a Thread

 We left a comment in the `for` loop in Listing 20-14 regarding the creation of threads. Here, we’ll look at how we actually create threads. The standard library provides `thread::spawn` as a way to create threads, and `thread::spawn` expects to get some code the thread should run as soon as the thread is created. However, in our case, we want to create the threads and have them *wait* for code that we’ll send later. The standard library’s implementation of threads doesn’t include any way to do that; we have to implement it manually.

 We’ll implement this behavior by introducing a new data structure between the `ThreadPool` and the threads that will manage this new behavior. We’ll call this data structure *Worker*, which is a common term in pooling implementations. The Worker picks up code that needs to be run and runs the code in the Worker’s thread. Think of people working in the kitchen at a restaurant: the workers wait until orders come in from customers, and then they’re responsible for taking those orders and fulfilling them.

 Instead of storing a vector of `JoinHandle<()>` instances in the thread pool, we’ll store instances of the `Worker` struct. Each `Worker` will store a single `JoinHandle<()>` instance. Then we’ll implement a method on `Worker` that will take a closure of code to run and send it to the already running thread for execution. We’ll also give each worker an `id` so we can distinguish between the different workers in the pool when logging or debugging.

 Here is the new process that will happen when we create a `ThreadPool`. We’ll implement the code that sends the closure to the thread after we have `Worker` set up in this way:

 1. Define a `Worker` struct that holds an `id` and a `JoinHandle<()>`.
2. Change `ThreadPool` to hold a vector of `Worker` instances.
3. Define a `Worker::new` function that takes an `id` number and returns a `Worker` instance that holds the `id` and a thread spawned with an empty closure.
4. In `ThreadPool::new`, use the `for` loop counter to generate an `id`, create a new `Worker` with that `id`, and store the worker in the vector.

 If you’re up for a challenge, try implementing these changes on your own before looking at the code in Listing 20-15.

 Ready? Here is Listing 20-15 with one way to make the preceding modifications.

 Filename: src/lib.rs

 
```
use std::thread;

pub struct ThreadPool {
    workers: Vec<Worker>,
}

impl ThreadPool {
    // --snip--
    /// Create a new ThreadPool.
    ///
    /// The size is the number of threads in the pool.
    ///
    /// # Panics
    ///
    /// The `new` function will panic if the size is zero.
    pub fn new(size: usize) -> ThreadPool {
        assert!(size > 0);

        let mut workers = Vec::with_capacity(size);

        for id in 0..size {
            workers.push(Worker::new(id));
        }

        ThreadPool { workers }
    }
    // --snip--

    pub fn execute<F>(&self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
    }
}

struct Worker {
    id: usize,
    thread: thread::JoinHandle<()>,
}

impl Worker {
    fn new(id: usize) -> Worker {
        let thread = thread::spawn(|| {});

        Worker { id, thread }
    }
}
```
 Listing 20-15: Modifying `ThreadPool` to hold `Worker` instances instead of holding threads directly

 We’ve changed the name of the field on `ThreadPool` from `threads` to `workers` because it’s now holding `Worker` instances instead of `JoinHandle<()>` instances. We use the counter in the `for` loop as an argument to `Worker::new`, and we store each new `Worker` in the vector named `workers`.

 External code (like our server in *src/main.rs*) doesn’t need to know the implementation details regarding using a `Worker` struct within `ThreadPool`, so we make the `Worker` struct and its `new` function private. The `Worker::new` function uses the `id` we give it and stores a `JoinHandle<()>` instance that is created by spawning a new thread using an empty closure.

 
>  Note: If the operating system can’t create a thread because there aren’t enough system resources, `thread::spawn` will panic. That will cause our whole server to panic, even though the creation of some threads might succeed. For simplicity’s sake, this behavior is fine, but in a production thread pool implementation, you’d likely want to use [`std::thread::Builder`](../std/thread/struct.builder) and its [`spawn`](../std/thread/struct.builder#method.spawn) method that returns `Result` instead.
> 
>  

 This code will compile and will store the number of `Worker` instances we specified as an argument to `ThreadPool::new`. But we’re *still* not processing the closure that we get in `execute`. Let’s look at how to do that next.

 #### Sending Requests to Threads via Channels

 The next problem we’ll tackle is that the closures given to `thread::spawn` do absolutely nothing. Currently, we get the closure we want to execute in the `execute` method. But we need to give `thread::spawn` a closure to run when we create each `Worker` during the creation of the `ThreadPool`.

 We want the `Worker` structs that we just created to fetch the code to run from a queue held in the `ThreadPool` and send that code to its thread to run.

 The channels we learned about in Chapter 16—a simple way to communicate between two threads—would be perfect for this use case. We’ll use a channel to function as the queue of jobs, and `execute` will send a job from the `ThreadPool` to the `Worker` instances, which will send the job to its thread. Here is the plan:

 1. The `ThreadPool` will create a channel and hold on to the sender.
2. Each `Worker` will hold on to the receiver.
3. We’ll create a new `Job` struct that will hold the closures we want to send down the channel.
4. The `execute` method will send the job it wants to execute through the sender.
5. In its thread, the `Worker` will loop over its receiver and execute the closures of any jobs it receives.

 Let’s start by creating a channel in `ThreadPool::new` and holding the sender in the `ThreadPool` instance, as shown in Listing 20-16. The `Job` struct doesn’t hold anything for now but will be the type of item we’re sending down the channel.

 Filename: src/lib.rs

 
```
use std::{sync::mpsc, thread};

pub struct ThreadPool {
    workers: Vec<Worker>,
    sender: mpsc::Sender<Job>,
}

struct Job;

impl ThreadPool {
    // --snip--
    /// Create a new ThreadPool.
    ///
    /// The size is the number of threads in the pool.
    ///
    /// # Panics
    ///
    /// The `new` function will panic if the size is zero.
    pub fn new(size: usize) -> ThreadPool {
        assert!(size > 0);

        let (sender, receiver) = mpsc::channel();

        let mut workers = Vec::with_capacity(size);

        for id in 0..size {
            workers.push(Worker::new(id));
        }

        ThreadPool { workers, sender }
    }
    // --snip--

    pub fn execute<F>(&self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
    }
}

struct Worker {
    id: usize,
    thread: thread::JoinHandle<()>,
}

impl Worker {
    fn new(id: usize) -> Worker {
        let thread = thread::spawn(|| {});

        Worker { id, thread }
    }
}
```
 Listing 20-16: Modifying `ThreadPool` to store the sender of a channel that transmits `Job` instances

 In `ThreadPool::new`, we create our new channel and have the pool hold the sender. This will successfully compile.

 Let’s try passing a receiver of the channel into each worker as the thread pool creates the channel. We know we want to use the receiver in the thread that the workers spawn, so we’ll reference the `receiver` parameter in the closure. The code in Listing 20-17 won’t quite compile yet.

 Filename: src/lib.rs

 
```
use std::{sync::mpsc, thread};

pub struct ThreadPool {
    workers: Vec<Worker>,
    sender: mpsc::Sender<Job>,
}

struct Job;

impl ThreadPool {
    // --snip--
    /// Create a new ThreadPool.
    ///
    /// The size is the number of threads in the pool.
    ///
    /// # Panics
    ///
    /// The `new` function will panic if the size is zero.
    pub fn new(size: usize) -> ThreadPool {
        assert!(size > 0);

        let (sender, receiver) = mpsc::channel();

        let mut workers = Vec::with_capacity(size);

        for id in 0..size {
            workers.push(Worker::new(id, receiver));
        }

        ThreadPool { workers, sender }
    }
    // --snip--

    pub fn execute<F>(&self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
    }
}

// --snip--


struct Worker {
    id: usize,
    thread: thread::JoinHandle<()>,
}

impl Worker {
    fn new(id: usize, receiver: mpsc::Receiver<Job>) -> Worker {
        let thread = thread::spawn(|| {
            receiver;
        });

        Worker { id, thread }
    }
}
```
 Listing 20-17: Passing the receiver to the workers

 We’ve made some small and straightforward changes: we pass the receiver into `Worker::new`, and then we use it inside the closure.

 When we try to check this code, we get this error:

 
```
$ cargo check
    Checking hello v0.1.0 (file:///projects/hello)
error[E0382]: use of moved value: `receiver`
  --> src/lib.rs:26:42
   |
21 |         let (sender, receiver) = mpsc::channel();
   |                      -------- move occurs because `receiver` has type `std::sync::mpsc::Receiver<Job>`, which does not implement the `Copy` trait
...
26 |             workers.push(Worker::new(id, receiver));
   |                                          ^^^^^^^^ value moved here, in previous iteration of loop

For more information about this error, try `rustc --explain E0382`.
error: could not compile `hello` due to previous error

```
 The code is trying to pass `receiver` to multiple `Worker` instances. This won’t work, as you’ll recall from Chapter 16: the channel implementation that Rust provides is multiple *producer*, single *consumer*. This means we can’t just clone the consuming end of the channel to fix this code. We also don’t want to send a message multiple times to multiple consumers; we want one list of messages with multiple workers such that each message gets processed once.

 Additionally, taking a job off the channel queue involves mutating the `receiver`, so the threads need a safe way to share and modify `receiver`; otherwise, we might get race conditions (as covered in Chapter 16).

 Recall the thread-safe smart pointers discussed in Chapter 16: to share ownership across multiple threads and allow the threads to mutate the value, we need to use `Arc<Mutex<T>>`. The `Arc` type will let multiple workers own the receiver, and `Mutex` will ensure that only one worker gets a job from the receiver at a time. Listing 20-18 shows the changes we need to make.

 Filename: src/lib.rs

 
```
use std::{
    sync::{mpsc, Arc, Mutex},
    thread,
};
// --snip--

pub struct ThreadPool {
    workers: Vec<Worker>,
    sender: mpsc::Sender<Job>,
}

struct Job;

impl ThreadPool {
    // --snip--
    /// Create a new ThreadPool.
    ///
    /// The size is the number of threads in the pool.
    ///
    /// # Panics
    ///
    /// The `new` function will panic if the size is zero.
    pub fn new(size: usize) -> ThreadPool {
        assert!(size > 0);

        let (sender, receiver) = mpsc::channel();

        let receiver = Arc::new(Mutex::new(receiver));

        let mut workers = Vec::with_capacity(size);

        for id in 0..size {
            workers.push(Worker::new(id, Arc::clone(&receiver)));
        }

        ThreadPool { workers, sender }
    }

    // --snip--

    pub fn execute<F>(&self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
    }
}

// --snip--

struct Worker {
    id: usize,
    thread: thread::JoinHandle<()>,
}

impl Worker {
    fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
        // --snip--
        let thread = thread::spawn(|| {
            receiver;
        });

        Worker { id, thread }
    }
}
```
 Listing 20-18: Sharing the receiver among the workers using `Arc` and `Mutex`

 In `ThreadPool::new`, we put the receiver in an `Arc` and a `Mutex`. For each new worker, we clone the `Arc` to bump the reference count so the workers can share ownership of the receiver.

 With these changes, the code compiles! We’re getting there!

 #### Implementing the `execute` Method

 Let’s finally implement the `execute` method on `ThreadPool`. We’ll also change `Job` from a struct to a type alias for a trait object that holds the type of closure that `execute` receives. As discussed in the [“Creating Type Synonyms with Type Aliases”](ch19-04-advanced-types#creating-type-synonyms-with-type-aliases) section of Chapter 19, type aliases allow us to make long types shorter for ease of use. Look at Listing 20-19.

 Filename: src/lib.rs

 
```
use std::{
    sync::{mpsc, Arc, Mutex},
    thread,
};

pub struct ThreadPool {
    workers: Vec<Worker>,
    sender: mpsc::Sender<Job>,
}

// --snip--

type Job = Box<dyn FnOnce() + Send + 'static>;

impl ThreadPool {
    // --snip--
    /// Create a new ThreadPool.
    ///
    /// The size is the number of threads in the pool.
    ///
    /// # Panics
    ///
    /// The `new` function will panic if the size is zero.
    pub fn new(size: usize) -> ThreadPool {
        assert!(size > 0);

        let (sender, receiver) = mpsc::channel();

        let receiver = Arc::new(Mutex::new(receiver));

        let mut workers = Vec::with_capacity(size);

        for id in 0..size {
            workers.push(Worker::new(id, Arc::clone(&receiver)));
        }

        ThreadPool { workers, sender }
    }

    pub fn execute<F>(&self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
        let job = Box::new(f);

        self.sender.send(job).unwrap();
    }
}

// --snip--

struct Worker {
    id: usize,
    thread: thread::JoinHandle<()>,
}

impl Worker {
    fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
        let thread = thread::spawn(|| {
            receiver;
        });

        Worker { id, thread }
    }
}
```
 Listing 20-19: Creating a `Job` type alias for a `Box` that holds each closure and then sending the job down the channel

 After creating a new `Job` instance using the closure we get in `execute`, we send that job down the sending end of the channel. We’re calling `unwrap` on `send` for the case that sending fails. This might happen if, for example, we stop all our threads from executing, meaning the receiving end has stopped receiving new messages. At the moment, we can’t stop our threads from executing: our threads continue executing as long as the pool exists. The reason we use `unwrap` is that we know the failure case won’t happen, but the compiler doesn’t know that.

 But we’re not quite done yet! In the worker, our closure being passed to `thread::spawn` still only *references* the receiving end of the channel. Instead, we need the closure to loop forever, asking the receiving end of the channel for a job and running the job when it gets one. Let’s make the change shown in Listing 20-20 to `Worker::new`.

 Filename: src/lib.rs

 
```
use std::{
    sync::{mpsc, Arc, Mutex},
    thread,
};

pub struct ThreadPool {
    workers: Vec<Worker>,
    sender: mpsc::Sender<Job>,
}

type Job = Box<dyn FnOnce() + Send + 'static>;

impl ThreadPool {
    /// Create a new ThreadPool.
    ///
    /// The size is the number of threads in the pool.
    ///
    /// # Panics
    ///
    /// The `new` function will panic if the size is zero.
    pub fn new(size: usize) -> ThreadPool {
        assert!(size > 0);

        let (sender, receiver) = mpsc::channel();

        let receiver = Arc::new(Mutex::new(receiver));

        let mut workers = Vec::with_capacity(size);

        for id in 0..size {
            workers.push(Worker::new(id, Arc::clone(&receiver)));
        }

        ThreadPool { workers, sender }
    }

    pub fn execute<F>(&self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
        let job = Box::new(f);

        self.sender.send(job).unwrap();
    }
}

struct Worker {
    id: usize,
    thread: thread::JoinHandle<()>,
}

// --snip--

impl Worker {
    fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
        let thread = thread::spawn(move || loop {
            let job = receiver.lock().unwrap().recv().unwrap();

            println!("Worker {id} got a job; executing.");

            job();
        });

        Worker { id, thread }
    }
}
```
 Listing 20-20: Receiving and executing the jobs in the worker’s thread

 Here, we first call `lock` on the `receiver` to acquire the mutex, and then we call `unwrap` to panic on any errors. Acquiring a lock might fail if the mutex is in a *poisoned* state, which can happen if some other thread panicked while holding the lock rather than releasing the lock. In this situation, calling `unwrap` to have this thread panic is the correct action to take. Feel free to change this `unwrap` to an `expect` with an error message that is meaningful to you.

 If we get the lock on the mutex, we call `recv` to receive a `Job` from the channel. A final `unwrap` moves past any errors here as well, which might occur if the thread holding the sender has shut down, similar to how the `send` method returns `Err` if the receiver shuts down.

 The call to `recv` blocks, so if there is no job yet, the current thread will wait until a job becomes available. The `Mutex<T>` ensures that only one `Worker` thread at a time is trying to request a job.

 Our thread pool is now in a working state! Give it a `cargo run` and make some requests:

 
```
$ cargo run
   Compiling hello v0.1.0 (file:///projects/hello)
warning: field is never read: `workers`
 --> src/lib.rs:7:5
  |
7 |     workers: Vec<Worker>,
  |     ^^^^^^^^^^^^^^^^^^^^
  |
  = note: `#[warn(dead_code)]` on by default

warning: field is never read: `id`
  --> src/lib.rs:48:5
   |
48 |     id: usize,
   |     ^^^^^^^^^

warning: field is never read: `thread`
  --> src/lib.rs:49:5
   |
49 |     thread: thread::JoinHandle<()>,
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

warning: `hello` (lib) generated 3 warnings
    Finished dev [unoptimized + debuginfo] target(s) in 1.40s
     Running `target/debug/hello`
Worker 0 got a job; executing.
Worker 2 got a job; executing.
Worker 1 got a job; executing.
Worker 3 got a job; executing.
Worker 0 got a job; executing.
Worker 2 got a job; executing.
Worker 1 got a job; executing.
Worker 3 got a job; executing.
Worker 0 got a job; executing.
Worker 2 got a job; executing.

```
 Success! We now have a thread pool that executes connections asynchronously. There are never more than four threads created, so our system won’t get overloaded if the server receives a lot of requests. If we make a request to */sleep*, the server will be able to serve other requests by having another thread run them.

 
>  Note: if you open */sleep* in multiple browser windows simultaneously, they might load one at a time in 5 second intervals. Some web browsers execute multiple instances of the same request sequentially for caching reasons. This limitation is not caused by our web server.
> 
>  

 After learning about the `while let` loop in Chapter 18, you might be wondering why we didn’t write the worker thread code as shown in Listing 20-21.

 Filename: src/lib.rs

 
```
use std::{
    sync::{mpsc, Arc, Mutex},
    thread,
};

pub struct ThreadPool {
    workers: Vec<Worker>,
    sender: mpsc::Sender<Job>,
}

type Job = Box<dyn FnOnce() + Send + 'static>;

impl ThreadPool {
    /// Create a new ThreadPool.
    ///
    /// The size is the number of threads in the pool.
    ///
    /// # Panics
    ///
    /// The `new` function will panic if the size is zero.
    pub fn new(size: usize) -> ThreadPool {
        assert!(size > 0);

        let (sender, receiver) = mpsc::channel();

        let receiver = Arc::new(Mutex::new(receiver));

        let mut workers = Vec::with_capacity(size);

        for id in 0..size {
            workers.push(Worker::new(id, Arc::clone(&receiver)));
        }

        ThreadPool { workers, sender }
    }

    pub fn execute<F>(&self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
        let job = Box::new(f);

        self.sender.send(job).unwrap();
    }
}

struct Worker {
    id: usize,
    thread: thread::JoinHandle<()>,
}
// --snip--

impl Worker {
    fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
        let thread = thread::spawn(move || {
            while let Ok(job) = receiver.lock().unwrap().recv() {
                println!("Worker {id} got a job; executing.");

                job();
            }
        });

        Worker { id, thread }
    }
}
```
 Listing 20-21: An alternative implementation of `Worker::new` using `while let`

 This code compiles and runs but doesn’t result in the desired threading behavior: a slow request will still cause other requests to wait to be processed. The reason is somewhat subtle: the `Mutex` struct has no public `unlock` method because the ownership of the lock is based on the lifetime of the `MutexGuard<T>` within the `LockResult<MutexGuard<T>>` that the `lock` method returns. At compile time, the borrow checker can then enforce the rule that a resource guarded by a `Mutex` cannot be accessed unless we hold the lock. However, this implementation can also result in the lock being held longer than intended if we aren’t mindful of the lifetime of the `MutexGuard<T>`.

 The code in Listing 20-20 that uses `let job = receiver.lock().unwrap().recv().unwrap();` works because with `let`, any temporary values used in the expression on the right hand side of the equals sign are immediately dropped when the `let` statement ends. However, `while let` (and `if let` and `match`) does not drop temporary values until the end of the associated block. In Listing 20-21, the lock remains held for the duration of the call to `job()`, meaning other workers cannot receive jobs.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch20-02-multithreaded.html>

Graceful Shutdown and Cleanup
=============================

 The code in Listing 20-20 is responding to requests asynchronously through the use of a thread pool, as we intended. We get some warnings about the `workers`, `id`, and `thread` fields that we’re not using in a direct way that reminds us we’re not cleaning up anything. When we use the less elegant ctrl-c method to halt the main thread, all other threads are stopped immediately as well, even if they’re in the middle of serving a request.

 Next, then, we’ll implement the `Drop` trait to call `join` on each of the threads in the pool so they can finish the requests they’re working on before closing. Then we’ll implement a way to tell the threads they should stop accepting new requests and shut down. To see this code in action, we’ll modify our server to accept only two requests before gracefully shutting down its thread pool.

 ### Implementing the `Drop` Trait on `ThreadPool`

 Let’s start with implementing `Drop` on our thread pool. When the pool is dropped, our threads should all join to make sure they finish their work. Listing 20-22 shows a first attempt at a `Drop` implementation; this code won’t quite work yet.

 Filename: src/lib.rs

 
```
use std::{
    sync::{mpsc, Arc, Mutex},
    thread,
};

pub struct ThreadPool {
    workers: Vec<Worker>,
    sender: mpsc::Sender<Job>,
}

type Job = Box<dyn FnOnce() + Send + 'static>;

impl ThreadPool {
    /// Create a new ThreadPool.
    ///
    /// The size is the number of threads in the pool.
    ///
    /// # Panics
    ///
    /// The `new` function will panic if the size is zero.
    pub fn new(size: usize) -> ThreadPool {
        assert!(size > 0);

        let (sender, receiver) = mpsc::channel();

        let receiver = Arc::new(Mutex::new(receiver));

        let mut workers = Vec::with_capacity(size);

        for id in 0..size {
            workers.push(Worker::new(id, Arc::clone(&receiver)));
        }

        ThreadPool { workers, sender }
    }

    pub fn execute<F>(&self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
        let job = Box::new(f);

        self.sender.send(job).unwrap();
    }
}

impl Drop for ThreadPool {
    fn drop(&mut self) {
        for worker in &mut self.workers {
            println!("Shutting down worker {}", worker.id);

            worker.thread.join().unwrap();
        }
    }
}

struct Worker {
    id: usize,
    thread: thread::JoinHandle<()>,
}

impl Worker {
    fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
        let thread = thread::spawn(move || loop {
            let job = receiver.lock().unwrap().recv().unwrap();

            println!("Worker {id} got a job; executing.");

            job();
        });

        Worker { id, thread }
    }
}
```
 Listing 20-22: Joining each thread when the thread pool goes out of scope

 First, we loop through each of the thread pool `workers`. We use `&mut` for this because `self` is a mutable reference, and we also need to be able to mutate `worker`. For each worker, we print a message saying that this particular worker is shutting down, and then we call `join` on that worker’s thread. If the call to `join` fails, we use `unwrap` to make Rust panic and go into an ungraceful shutdown.

 Here is the error we get when we compile this code:

 
```
$ cargo check
    Checking hello v0.1.0 (file:///projects/hello)
error[E0507]: cannot move out of `worker.thread` which is behind a mutable reference
  --> src/lib.rs:52:13
   |
52 |             worker.thread.join().unwrap();
   |             ^^^^^^^^^^^^^ ------ `worker.thread` moved due to this method call
   |             |
   |             move occurs because `worker.thread` has type `JoinHandle<()>`, which does not implement the `Copy` trait
   |
note: this function takes ownership of the receiver `self`, which moves `worker.thread`
  --> /rustc/d5a82bbd26e1ad8b7401f6a718a9c57c96905483/library/std/src/thread/mod.rs:1581:17

For more information about this error, try `rustc --explain E0507`.
error: could not compile `hello` due to previous error

```
 The error tells us we can’t call `join` because we only have a mutable borrow of each `worker` and `join` takes ownership of its argument. To solve this issue, we need to move the thread out of the `Worker` instance that owns `thread` so `join` can consume the thread. We did this in Listing 17-15: if `Worker` holds an `Option<thread::JoinHandle<()>>` instead, we can call the `take` method on the `Option` to move the value out of the `Some` variant and leave a `None` variant in its place. In other words, a `Worker` that is running will have a `Some` variant in `thread`, and when we want to clean up a `Worker`, we’ll replace `Some` with `None` so the `Worker` doesn’t have a thread to run.

 So we know we want to update the definition of `Worker` like this:

 Filename: src/lib.rs

 
```
use std::{
    sync::{mpsc, Arc, Mutex},
    thread,
};

pub struct ThreadPool {
    workers: Vec<Worker>,
    sender: mpsc::Sender<Job>,
}

type Job = Box<dyn FnOnce() + Send + 'static>;

impl ThreadPool {
    /// Create a new ThreadPool.
    ///
    /// The size is the number of threads in the pool.
    ///
    /// # Panics
    ///
    /// The `new` function will panic if the size is zero.
    pub fn new(size: usize) -> ThreadPool {
        assert!(size > 0);

        let (sender, receiver) = mpsc::channel();

        let receiver = Arc::new(Mutex::new(receiver));

        let mut workers = Vec::with_capacity(size);

        for id in 0..size {
            workers.push(Worker::new(id, Arc::clone(&receiver)));
        }

        ThreadPool { workers, sender }
    }

    pub fn execute<F>(&self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
        let job = Box::new(f);

        self.sender.send(job).unwrap();
    }
}

impl Drop for ThreadPool {
    fn drop(&mut self) {
        for worker in &mut self.workers {
            println!("Shutting down worker {}", worker.id);

            worker.thread.join().unwrap();
        }
    }
}

struct Worker {
    id: usize,
    thread: Option<thread::JoinHandle<()>>,
}

impl Worker {
    fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
        let thread = thread::spawn(move || loop {
            let job = receiver.lock().unwrap().recv().unwrap();

            println!("Worker {id} got a job; executing.");

            job();
        });

        Worker { id, thread }
    }
}
```
 Now let’s lean on the compiler to find the other places that need to change. Checking this code, we get two errors:

 
```
$ cargo check
    Checking hello v0.1.0 (file:///projects/hello)
error[E0599]: no method named `join` found for enum `Option` in the current scope
  --> src/lib.rs:52:27
   |
52 |             worker.thread.join().unwrap();
   |                           ^^^^ method not found in `Option<JoinHandle<()>>`
   |
note: the method `join` exists on the type `JoinHandle<()>`
  --> /rustc/d5a82bbd26e1ad8b7401f6a718a9c57c96905483/library/std/src/thread/mod.rs:1581:5
help: consider using `Option::expect` to unwrap the `JoinHandle<()>` value, panicking if the value is an `Option::None`
   |
52 |             worker.thread.expect("REASON").join().unwrap();
   |                          +++++++++++++++++

error[E0308]: mismatched types
  --> src/lib.rs:72:22
   |
72 |         Worker { id, thread }
   |                      ^^^^^^ expected enum `Option`, found struct `JoinHandle`
   |
   = note: expected enum `Option<JoinHandle<()>>`
            found struct `JoinHandle<_>`
help: try wrapping the expression in `Some`
   |
72 |         Worker { id, thread: Some(thread) }
   |                      +++++++++++++      +

Some errors have detailed explanations: E0308, E0599.
For more information about an error, try `rustc --explain E0308`.
error: could not compile `hello` due to 2 previous errors

```
 Let’s address the second error, which points to the code at the end of `Worker::new`; we need to wrap the `thread` value in `Some` when we create a new `Worker`. Make the following changes to fix this error:

 Filename: src/lib.rs

 
```
use std::{
    sync::{mpsc, Arc, Mutex},
    thread,
};

pub struct ThreadPool {
    workers: Vec<Worker>,
    sender: mpsc::Sender<Job>,
}

type Job = Box<dyn FnOnce() + Send + 'static>;

impl ThreadPool {
    /// Create a new ThreadPool.
    ///
    /// The size is the number of threads in the pool.
    ///
    /// # Panics
    ///
    /// The `new` function will panic if the size is zero.
    pub fn new(size: usize) -> ThreadPool {
        assert!(size > 0);

        let (sender, receiver) = mpsc::channel();

        let receiver = Arc::new(Mutex::new(receiver));

        let mut workers = Vec::with_capacity(size);

        for id in 0..size {
            workers.push(Worker::new(id, Arc::clone(&receiver)));
        }

        ThreadPool { workers, sender }
    }

    pub fn execute<F>(&self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
        let job = Box::new(f);

        self.sender.send(job).unwrap();
    }
}

impl Drop for ThreadPool {
    fn drop(&mut self) {
        for worker in &mut self.workers {
            println!("Shutting down worker {}", worker.id);

            worker.thread.join().unwrap();
        }
    }
}

struct Worker {
    id: usize,
    thread: Option<thread::JoinHandle<()>>,
}

impl Worker {
    fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
        // --snip--

        let thread = thread::spawn(move || loop {
            let job = receiver.lock().unwrap().recv().unwrap();

            println!("Worker {id} got a job; executing.");

            job();
        });

        Worker {
            id,
            thread: Some(thread),
        }
    }
}
```
 The first error is in our `Drop` implementation. We mentioned earlier that we intended to call `take` on the `Option` value to move `thread` out of `worker`. The following changes will do so:

 Filename: src/lib.rs

 
```
use std::{
    sync::{mpsc, Arc, Mutex},
    thread,
};

pub struct ThreadPool {
    workers: Vec<Worker>,
    sender: mpsc::Sender<Job>,
}

type Job = Box<dyn FnOnce() + Send + 'static>;

impl ThreadPool {
    /// Create a new ThreadPool.
    ///
    /// The size is the number of threads in the pool.
    ///
    /// # Panics
    ///
    /// The `new` function will panic if the size is zero.
    pub fn new(size: usize) -> ThreadPool {
        assert!(size > 0);

        let (sender, receiver) = mpsc::channel();

        let receiver = Arc::new(Mutex::new(receiver));

        let mut workers = Vec::with_capacity(size);

        for id in 0..size {
            workers.push(Worker::new(id, Arc::clone(&receiver)));
        }

        ThreadPool { workers, sender }
    }

    pub fn execute<F>(&self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
        let job = Box::new(f);

        self.sender.send(job).unwrap();
    }
}

impl Drop for ThreadPool {
    fn drop(&mut self) {
        for worker in &mut self.workers {
            println!("Shutting down worker {}", worker.id);

            if let Some(thread) = worker.thread.take() {
                thread.join().unwrap();
            }
        }
    }
}

struct Worker {
    id: usize,
    thread: Option<thread::JoinHandle<()>>,
}

impl Worker {
    fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
        let thread = thread::spawn(move || loop {
            let job = receiver.lock().unwrap().recv().unwrap();

            println!("Worker {id} got a job; executing.");

            job();
        });

        Worker {
            id,
            thread: Some(thread),
        }
    }
}
```
 As discussed in Chapter 17, the `take` method on `Option` takes the `Some` variant out and leaves `None` in its place. We’re using `if let` to destructure the `Some` and get the thread; then we call `join` on the thread. If a worker’s thread is already `None`, we know that worker has already had its thread cleaned up, so nothing happens in that case.

 ### Signaling to the Threads to Stop Listening for Jobs

 With all the changes we’ve made, our code compiles without any warnings. However, the bad news is this code doesn’t function the way we want it to yet. The key is the logic in the closures run by the threads of the `Worker` instances: at the moment, we call `join`, but that won’t shut down the threads because they `loop` forever looking for jobs. If we try to drop our `ThreadPool` with our current implementation of `drop`, the main thread will block forever waiting for the first thread to finish.

 To fix this problem, we’ll need a change in the `ThreadPool` `drop` implementation and then a change in the `Worker` loop.

 First, we’ll change the `ThreadPool` `drop` implementation to explicitly drop the `sender` before waiting for the threads to finish. Listing 20-23 shows the changes to `ThreadPool` to explicitly drop `sender`. We use the same `Option` and `take` technique as we did with the thread to be able to move `sender` out of `ThreadPool`:

 Filename: src/lib.rs

 
```
use std::{
    sync::{mpsc, Arc, Mutex},
    thread,
};

pub struct ThreadPool {
    workers: Vec<Worker>,
    sender: Option<mpsc::Sender<Job>>,
}
// --snip--

type Job = Box<dyn FnOnce() + Send + 'static>;

impl ThreadPool {
    /// Create a new ThreadPool.
    ///
    /// The size is the number of threads in the pool.
    ///
    /// # Panics
    ///
    /// The `new` function will panic if the size is zero.
    pub fn new(size: usize) -> ThreadPool {
        // --snip--

        assert!(size > 0);

        let (sender, receiver) = mpsc::channel();

        let receiver = Arc::new(Mutex::new(receiver));

        let mut workers = Vec::with_capacity(size);

        for id in 0..size {
            workers.push(Worker::new(id, Arc::clone(&receiver)));
        }

        ThreadPool {
            workers,
            sender: Some(sender),
        }
    }

    pub fn execute<F>(&self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
        let job = Box::new(f);

        self.sender.as_ref().unwrap().send(job).unwrap();
    }
}

impl Drop for ThreadPool {
    fn drop(&mut self) {
        drop(self.sender.take());

        for worker in &mut self.workers {
            println!("Shutting down worker {}", worker.id);

            if let Some(thread) = worker.thread.take() {
                thread.join().unwrap();
            }
        }
    }
}

struct Worker {
    id: usize,
    thread: Option<thread::JoinHandle<()>>,
}

impl Worker {
    fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
        let thread = thread::spawn(move || loop {
            let job = receiver.lock().unwrap().recv().unwrap();

            println!("Worker {id} got a job; executing.");

            job();
        });

        Worker {
            id,
            thread: Some(thread),
        }
    }
}
```
 Listing 20-23: Explicitly drop `sender` before joining the worker threads

 Dropping `sender` closes the channel, which indicates no more messages will be sent. When that happens, all the calls to `recv` that the workers do in the infinite loop will return an error. In Listing 20-24, we change the `Worker` loop to gracefully exit the loop in that case, which means the threads will finish when the `ThreadPool` `drop` implementation calls `join` on them.

 Filename: src/lib.rs

 
```
use std::{
    sync::{mpsc, Arc, Mutex},
    thread,
};

pub struct ThreadPool {
    workers: Vec<Worker>,
    sender: Option<mpsc::Sender<Job>>,
}

type Job = Box<dyn FnOnce() + Send + 'static>;

impl ThreadPool {
    /// Create a new ThreadPool.
    ///
    /// The size is the number of threads in the pool.
    ///
    /// # Panics
    ///
    /// The `new` function will panic if the size is zero.
    pub fn new(size: usize) -> ThreadPool {
        assert!(size > 0);

        let (sender, receiver) = mpsc::channel();

        let receiver = Arc::new(Mutex::new(receiver));

        let mut workers = Vec::with_capacity(size);

        for id in 0..size {
            workers.push(Worker::new(id, Arc::clone(&receiver)));
        }

        ThreadPool {
            workers,
            sender: Some(sender),
        }
    }

    pub fn execute<F>(&self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
        let job = Box::new(f);

        self.sender.as_ref().unwrap().send(job).unwrap();
    }
}

impl Drop for ThreadPool {
    fn drop(&mut self) {
        drop(self.sender.take());

        for worker in &mut self.workers {
            println!("Shutting down worker {}", worker.id);

            if let Some(thread) = worker.thread.take() {
                thread.join().unwrap();
            }
        }
    }
}

struct Worker {
    id: usize,
    thread: Option<thread::JoinHandle<()>>,
}

impl Worker {
    fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
        let thread = thread::spawn(move || loop {
            let message = receiver.lock().unwrap().recv();

            match message {
                Ok(job) => {
                    println!("Worker {id} got a job; executing.");

                    job();
                }
                Err(_) => {
                    println!("Worker {id} disconnected; shutting down.");
                    break;
                }
            }
        });

        Worker {
            id,
            thread: Some(thread),
        }
    }
}
```
 Listing 20-24: Explicitly break out of the loop when `recv` returns an error

 To see this code in action, let’s modify `main` to accept only two requests before gracefully shutting down the server, as shown in Listing 20-25.

 Filename: src/main.rs

 
```
use hello::ThreadPool;
use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
use std::thread;
use std::time::Duration;

fn main() {
    let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
    let pool = ThreadPool::new(4);

    for stream in listener.incoming().take(2) {
        let stream = stream.unwrap();

        pool.execute(|| {
            handle_connection(stream);
        });
    }

    println!("Shutting down.");
}

fn handle_connection(mut stream: TcpStream) {
    let mut buffer = [0; 1024];
    stream.read(&mut buffer).unwrap();

    let get = b"GET / HTTP/1.1\r\n";
    let sleep = b"GET /sleep HTTP/1.1\r\n";

    let (status_line, filename) = if buffer.starts_with(get) {
        ("HTTP/1.1 200 OK", "hello.html")
    } else if buffer.starts_with(sleep) {
        thread::sleep(Duration::from_secs(5));
        ("HTTP/1.1 200 OK", "hello.html")
    } else {
        ("HTTP/1.1 404 NOT FOUND", "404.html")
    };

    let contents = fs::read_to_string(filename).unwrap();

    let response = format!(
        "{}\r\nContent-Length: {}\r\n\r\n{}",
        status_line,
        contents.len(),
        contents
    );

    stream.write_all(response.as_bytes()).unwrap();
    stream.flush().unwrap();
}
```
 Listing 20-25: Shut down the server after serving two requests by exiting the loop

 You wouldn’t want a real-world web server to shut down after serving only two requests. This code just demonstrates that the graceful shutdown and cleanup is in working order.

 The `take` method is defined in the `Iterator` trait and limits the iteration to the first two items at most. The `ThreadPool` will go out of scope at the end of `main`, and the `drop` implementation will run.

 Start the server with `cargo run`, and make three requests. The third request should error, and in your terminal you should see output similar to this:

 
```
$ cargo run
   Compiling hello v0.1.0 (file:///projects/hello)
    Finished dev [unoptimized + debuginfo] target(s) in 1.0s
     Running `target/debug/hello`
Worker 0 got a job; executing.
Shutting down.
Shutting down worker 0
Worker 3 got a job; executing.
Worker 1 disconnected; shutting down.
Worker 2 disconnected; shutting down.
Worker 3 disconnected; shutting down.
Worker 0 disconnected; shutting down.
Shutting down worker 1
Shutting down worker 2
Shutting down worker 3

```
 You might see a different ordering of workers and messages printed. We can see how this code works from the messages: workers 0 and 3 got the first two requests. The server stopped accepting connections after the second connection, and the `Drop` implementation on `ThreadPool` starts executing before worker 3 even starts its job. Dropping the `sender` disconnects all the workers and tells them to shut down. The workers each print a message when they disconnect, and then the thread pool calls `join` to wait for each worker thread to finish.

 Notice one interesting aspect of this particular execution: the `ThreadPool` dropped the `sender`, and before any worker received an error, we tried to join worker 0. Worker 0 had not yet gotten an error from `recv`, so the main thread blocked waiting for worker 0 to finish. In the meantime, worker 3 received a job and then all threads received an error. When worker 0 finished, the main thread waited for the rest of the workers to finish. At that point, they had all exited their loops and stopped.

 Congrats! We’ve now completed our project; we have a basic web server that uses a thread pool to respond asynchronously. We’re able to perform a graceful shutdown of the server, which cleans up all the threads in the pool.

 Here’s the full code for reference:

 Filename: src/main.rs

 
```
use hello::ThreadPool;
use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
use std::thread;
use std::time::Duration;

fn main() {
    let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
    let pool = ThreadPool::new(4);

    for stream in listener.incoming().take(2) {
        let stream = stream.unwrap();

        pool.execute(|| {
            handle_connection(stream);
        });
    }

    println!("Shutting down.");
}

fn handle_connection(mut stream: TcpStream) {
    let mut buffer = [0; 1024];
    stream.read(&mut buffer).unwrap();

    let get = b"GET / HTTP/1.1\r\n";
    let sleep = b"GET /sleep HTTP/1.1\r\n";

    let (status_line, filename) = if buffer.starts_with(get) {
        ("HTTP/1.1 200 OK", "hello.html")
    } else if buffer.starts_with(sleep) {
        thread::sleep(Duration::from_secs(5));
        ("HTTP/1.1 200 OK", "hello.html")
    } else {
        ("HTTP/1.1 404 NOT FOUND", "404.html")
    };

    let contents = fs::read_to_string(filename).unwrap();

    let response = format!(
        "{}\r\nContent-Length: {}\r\n\r\n{}",
        status_line,
        contents.len(),
        contents
    );

    stream.write_all(response.as_bytes()).unwrap();
    stream.flush().unwrap();
}
```
 Filename: src/lib.rs

 
```
use std::{
    sync::{mpsc, Arc, Mutex},
    thread,
};

pub struct ThreadPool {
    workers: Vec<Worker>,
    sender: Option<mpsc::Sender<Job>>,
}

type Job = Box<dyn FnOnce() + Send + 'static>;

impl ThreadPool {
    /// Create a new ThreadPool.
    ///
    /// The size is the number of threads in the pool.
    ///
    /// # Panics
    ///
    /// The `new` function will panic if the size is zero.
    pub fn new(size: usize) -> ThreadPool {
        assert!(size > 0);

        let (sender, receiver) = mpsc::channel();

        let receiver = Arc::new(Mutex::new(receiver));

        let mut workers = Vec::with_capacity(size);

        for id in 0..size {
            workers.push(Worker::new(id, Arc::clone(&receiver)));
        }

        ThreadPool {
            workers,
            sender: Some(sender),
        }
    }

    pub fn execute<F>(&self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
        let job = Box::new(f);

        self.sender.as_ref().unwrap().send(job).unwrap();
    }
}

impl Drop for ThreadPool {
    fn drop(&mut self) {
        drop(self.sender.take());

        for worker in &mut self.workers {
            println!("Shutting down worker {}", worker.id);

            if let Some(thread) = worker.thread.take() {
                thread.join().unwrap();
            }
        }
    }
}

struct Worker {
    id: usize,
    thread: Option<thread::JoinHandle<()>>,
}

impl Worker {
    fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
        let thread = thread::spawn(move || loop {
            let message = receiver.lock().unwrap().recv();

            match message {
                Ok(job) => {
                    println!("Worker {id} got a job; executing.");

                    job();
                }
                Err(_) => {
                    println!("Worker {id} disconnected; shutting down.");
                    break;
                }
            }
        });

        Worker {
            id,
            thread: Some(thread),
        }
    }
}
```
 We could do more here! If you want to continue enhancing this project, here are some ideas:

 * Add more documentation to `ThreadPool` and its public methods.
* Add tests of the library’s functionality.
* Change calls to `unwrap` to more robust error handling.
* Use `ThreadPool` to perform some task other than serving web requests.
* Find a thread pool crate on [crates.io](https://crates.io/) and implement a similar web server using the crate instead. Then compare its API and robustness to the thread pool we implemented.

 Summary
-------

 Well done! You’ve made it to the end of the book! We want to thank you for joining us on this tour of Rust. You’re now ready to implement your own Rust projects and help with other peoples’ projects. Keep in mind that there is a welcoming community of other Rustaceans who would love to help you with any challenges you encounter on your Rust journey.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/ch20-03-graceful-shutdown-and-cleanup.html>

Appendix
========

 The following sections contain reference material you may find useful in your Rust journey.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/appendix-00.html>

Appendix A: Keywords
====================

 The following list contains keywords that are reserved for current or future use by the Rust language. As such, they cannot be used as identifiers (except as raw identifiers as we’ll discuss in the “[Raw Identifiers](#raw-identifiers)” section). Identifiers are names of functions, variables, parameters, struct fields, modules, crates, constants, macros, static values, attributes, types, traits, or lifetimes.

 ### Keywords Currently in Use

 The following is a list of keywords currently in use, with their functionality described.

 * `as` - perform primitive casting, disambiguate the specific trait containing an item, or rename items in `use` statements
* `async` - return a `Future` instead of blocking the current thread
* `await` - suspend execution until the result of a `Future` is ready
* `break` - exit a loop immediately
* `const` - define constant items or constant raw pointers
* `continue` - continue to the next loop iteration
* `crate` - in a module path, refers to the crate root
* `dyn` - dynamic dispatch to a trait object
* `else` - fallback for `if` and `if let` control flow constructs
* `enum` - define an enumeration
* `extern` - link an external function or variable
* `false` - Boolean false literal
* `fn` - define a function or the function pointer type
* `for` - loop over items from an iterator, implement a trait, or specify a higher-ranked lifetime
* `if` - branch based on the result of a conditional expression
* `impl` - implement inherent or trait functionality
* `in` - part of `for` loop syntax
* `let` - bind a variable
* `loop` - loop unconditionally
* `match` - match a value to patterns
* `mod` - define a module
* `move` - make a closure take ownership of all its captures
* `mut` - denote mutability in references, raw pointers, or pattern bindings
* `pub` - denote public visibility in struct fields, `impl` blocks, or modules
* `ref` - bind by reference
* `return` - return from function
* `Self` - a type alias for the type we are defining or implementing
* `self` - method subject or current module
* `static` - global variable or lifetime lasting the entire program execution
* `struct` - define a structure
* `super` - parent module of the current module
* `trait` - define a trait
* `true` - Boolean true literal
* `type` - define a type alias or associated type
* `union` - define a [union](../reference/items/unions); is only a keyword when used in a union declaration
* `unsafe` - denote unsafe code, functions, traits, or implementations
* `use` - bring symbols into scope
* `where` - denote clauses that constrain a type
* `while` - loop conditionally based on the result of an expression

 ### Keywords Reserved for Future Use

 The following keywords do not yet have any functionality but are reserved by Rust for potential future use.

 * `abstract`
* `become`
* `box`
* `do`
* `final`
* `macro`
* `override`
* `priv`
* `try`
* `typeof`
* `unsized`
* `virtual`
* `yield`

 ### Raw Identifiers

 *Raw identifiers* are the syntax that lets you use keywords where they wouldn’t normally be allowed. You use a raw identifier by prefixing a keyword with `r#`.

 For example, `match` is a keyword. If you try to compile the following function that uses `match` as its name:

 Filename: src/main.rs

 
```
fn match(needle: &str, haystack: &str) -> bool {
    haystack.contains(needle)
}
```
 you’ll get this error:

 
```
error: expected identifier, found keyword `match`
 --> src/main.rs:4:4
  |
4 | fn match(needle: &str, haystack: &str) -> bool {
  |    ^^^^^ expected identifier, found keyword

```
 The error shows that you can’t use the keyword `match` as the function identifier. To use `match` as a function name, you need to use the raw identifier syntax, like this:

 Filename: src/main.rs

 
```
fn r#match(needle: &str, haystack: &str) -> bool {
    haystack.contains(needle)
}

fn main() {
    assert!(r#match("foo", "foobar"));
}
```
 This code will compile without any errors. Note the `r#` prefix on the function name in its definition as well as where the function is called in `main`.

 Raw identifiers allow you to use any word you choose as an identifier, even if that word happens to be a reserved keyword. This gives us more freedom to choose identifier names, as well as lets us integrate with programs written in a language where these words aren’t keywords. In addition, raw identifiers allow you to use libraries written in a different Rust edition than your crate uses. For example, `try` isn’t a keyword in the 2015 edition but is in the 2018 edition. If you depend on a library that’s written using the 2015 edition and has a `try` function, you’ll need to use the raw identifier syntax, `r#try` in this case, to call that function from your 2018 edition code. See [Appendix E](appendix-05-editions) for more information on editions.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/appendix-01-keywords.html>

Appendix B: Operators and Symbols
=================================

 This appendix contains a glossary of Rust’s syntax, including operators and other symbols that appear by themselves or in the context of paths, generics, trait bounds, macros, attributes, comments, tuples, and brackets.

 ### Operators

 Table B-1 contains the operators in Rust, an example of how the operator would appear in context, a short explanation, and whether that operator is overloadable. If an operator is overloadable, the relevant trait to use to overload that operator is listed.

 Table B-1: Operators

 


| Operator | Example | Explanation | Overloadable? |
| --- | --- | --- | --- |
| `!` | `ident!(...)`, `ident!{...}`, `ident![...]` | Macro expansion |  |
| `!` | `!expr` | Bitwise or logical complement | `Not` |
| `!=` | `expr != expr` | Nonequality comparison | `PartialEq` |
| `%` | `expr % expr` | Arithmetic remainder | `Rem` |
| `%=` | `var %= expr` | Arithmetic remainder and assignment | `RemAssign` |
| `&` | `&expr`, `&mut expr` | Borrow |  |
| `&` | `&type`, `&mut type`, `&'a type`, `&'a mut type` | Borrowed pointer type |  |
| `&` | `expr & expr` | Bitwise AND | `BitAnd` |
| `&=` | `var &= expr` | Bitwise AND and assignment | `BitAndAssign` |
| `&&` | `expr && expr` | Short-circuiting logical AND |  |
| `*` | `expr * expr` | Arithmetic multiplication | `Mul` |
| `*=` | `var *= expr` | Arithmetic multiplication and assignment | `MulAssign` |
| `*` | `*expr` | Dereference | `Deref` |
| `*` | `*const type`, `*mut type` | Raw pointer |  |
| `+` | `trait + trait`, `'a + trait` | Compound type constraint |  |
| `+` | `expr + expr` | Arithmetic addition | `Add` |
| `+=` | `var += expr` | Arithmetic addition and assignment | `AddAssign` |
| `,` | `expr, expr` | Argument and element separator |  |
| `-` | `- expr` | Arithmetic negation | `Neg` |
| `-` | `expr - expr` | Arithmetic subtraction | `Sub` |
| `-=` | `var -= expr` | Arithmetic subtraction and assignment | `SubAssign` |
| `->` | `fn(...) -> type`, `|...| -> type` | Function and closure return type |  |
| `.` | `expr.ident` | Member access |  |
| `..` | `..`, `expr..`, `..expr`, `expr..expr` | Right-exclusive range literal | `PartialOrd` |
| `..=` | `..=expr`, `expr..=expr` | Right-inclusive range literal | `PartialOrd` |
| `..` | `..expr` | Struct literal update syntax |  |
| `..` | `variant(x, ..)`, `struct_type { x, .. }` | “And the rest” pattern binding |  |
| `...` | `expr...expr` | (Deprecated, use `..=` instead) In a pattern: inclusive range pattern |  |
| `/` | `expr / expr` | Arithmetic division | `Div` |
| `/=` | `var /= expr` | Arithmetic division and assignment | `DivAssign` |
| `:` | `pat: type`, `ident: type` | Constraints |  |
| `:` | `ident: expr` | Struct field initializer |  |
| `:` | `'a: loop {...}` | Loop label |  |
| `;` | `expr;` | Statement and item terminator |  |
| `;` | `[...; len]` | Part of fixed-size array syntax |  |
| `<<` | `expr << expr` | Left-shift | `Shl` |
| `<<=` | `var <<= expr` | Left-shift and assignment | `ShlAssign` |
| `<` | `expr < expr` | Less than comparison | `PartialOrd` |
| `<=` | `expr <= expr` | Less than or equal to comparison | `PartialOrd` |
| `=` | `var = expr`, `ident = type` | Assignment/equivalence |  |
| `==` | `expr == expr` | Equality comparison | `PartialEq` |
| `=>` | `pat => expr` | Part of match arm syntax |  |
| `>` | `expr > expr` | Greater than comparison | `PartialOrd` |
| `>=` | `expr >= expr` | Greater than or equal to comparison | `PartialOrd` |
| `>>` | `expr >> expr` | Right-shift | `Shr` |
| `>>=` | `var >>= expr` | Right-shift and assignment | `ShrAssign` |
| `@` | `ident @ pat` | Pattern binding |  |
| `^` | `expr ^ expr` | Bitwise exclusive OR | `BitXor` |
| `^=` | `var ^= expr` | Bitwise exclusive OR and assignment | `BitXorAssign` |
| `|` | `pat | pat` | Pattern alternatives |  |
| `|` | `expr | expr` | Bitwise OR | `BitOr` |
| `|=` | `var |= expr` | Bitwise OR and assignment | `BitOrAssign` |
| `||` | `expr || expr` | Short-circuiting logical OR |  |
| `?` | `expr?` | Error propagation |  |

  ### Non-operator Symbols

 The following list contains all symbols that don’t function as operators; that is, they don’t behave like a function or method call.

 Table B-2 shows symbols that appear on their own and are valid in a variety of locations.

 Table B-2: Stand-Alone Syntax

 


| Symbol | Explanation |
| --- | --- |
| `'ident` | Named lifetime or loop label |
| `...u8`, `...i32`, `...f64`, `...usize`, etc. | Numeric literal of specific type |
| `"..."` | String literal |
| `r"..."`, `r#"..."#`, `r##"..."##`, etc. | Raw string literal, escape characters not processed |
| `b"..."` | Byte string literal; constructs an array of bytes instead of a string |
| `br"..."`, `br#"..."#`, `br##"..."##`, etc. | Raw byte string literal, combination of raw and byte string literal |
| `'...'` | Character literal |
| `b'...'` | ASCII byte literal |
| `|...| expr` | Closure |
| `!` | Always empty bottom type for diverging functions |
| `_` | “Ignored” pattern binding; also used to make integer literals readable |

  Table B-3 shows symbols that appear in the context of a path through the module hierarchy to an item.

 Table B-3: Path-Related Syntax

 


| Symbol | Explanation |
| --- | --- |
| `ident::ident` | Namespace path |
| `::path` | Path relative to the crate root (i.e., an explicitly absolute path) |
| `self::path` | Path relative to the current module (i.e., an explicitly relative path). |
| `super::path` | Path relative to the parent of the current module |
| `type::ident`, `<type as trait>::ident` | Associated constants, functions, and types |
| `<type>::...` | Associated item for a type that cannot be directly named (e.g., `<&T>::...`, `<[T]>::...`, etc.) |
| `trait::method(...)` | Disambiguating a method call by naming the trait that defines it |
| `type::method(...)` | Disambiguating a method call by naming the type for which it’s defined |
| `<type as trait>::method(...)` | Disambiguating a method call by naming the trait and type |

  Table B-4 shows symbols that appear in the context of using generic type parameters.

 Table B-4: Generics

 


| Symbol | Explanation |
| --- | --- |
| `path<...>` | Specifies parameters to generic type in a type (e.g., `Vec<u8>`) |
| `path::<...>`, `method::<...>` | Specifies parameters to generic type, function, or method in an expression; often referred to as turbofish (e.g., `"42".parse::<i32>()`) |
| `fn ident<...> ...` | Define generic function |
| `struct ident<...> ...` | Define generic structure |
| `enum ident<...> ...` | Define generic enumeration |
| `impl<...> ...` | Define generic implementation |
| `for<...> type` | Higher-ranked lifetime bounds |
| `type<ident=type>` | A generic type where one or more associated types have specific assignments (e.g., `Iterator<Item=T>`) |

  Table B-5 shows symbols that appear in the context of constraining generic type parameters with trait bounds.

 Table B-5: Trait Bound Constraints

 


| Symbol | Explanation |
| --- | --- |
| `T: U` | Generic parameter `T` constrained to types that implement `U` |
| `T: 'a` | Generic type `T` must outlive lifetime `'a` (meaning the type cannot transitively contain any references with lifetimes shorter than `'a`) |
| `T: 'static` | Generic type `T` contains no borrowed references other than `'static` ones |
| `'b: 'a` | Generic lifetime `'b` must outlive lifetime `'a` |
| `T: ?Sized` | Allow generic type parameter to be a dynamically sized type |
| `'a + trait`, `trait + trait` | Compound type constraint |

  Table B-6 shows symbols that appear in the context of calling or defining macros and specifying attributes on an item.

 Table B-6: Macros and Attributes

 


| Symbol | Explanation |
| --- | --- |
| `#[meta]` | Outer attribute |
| `#![meta]` | Inner attribute |
| `$ident` | Macro substitution |
| `$ident:kind` | Macro capture |
| `$(…)…` | Macro repetition |
| `ident!(...)`, `ident!{...}`, `ident![...]` | Macro invocation |

  Table B-7 shows symbols that create comments.

 Table B-7: Comments

 


| Symbol | Explanation |
| --- | --- |
| `//` | Line comment |
| `//!` | Inner line doc comment |
| `///` | Outer line doc comment |
| `/*...*/` | Block comment |
| `/*!...*/` | Inner block doc comment |
| `/**...*/` | Outer block doc comment |

  Table B-8 shows symbols that appear in the context of using tuples.

 Table B-8: Tuples

 


| Symbol | Explanation |
| --- | --- |
| `()` | Empty tuple (aka unit), both literal and type |
| `(expr)` | Parenthesized expression |
| `(expr,)` | Single-element tuple expression |
| `(type,)` | Single-element tuple type |
| `(expr, ...)` | Tuple expression |
| `(type, ...)` | Tuple type |
| `expr(expr, ...)` | Function call expression; also used to initialize tuple `struct`s and tuple `enum` variants |
| `expr.0`, `expr.1`, etc. | Tuple indexing |

  Table B-9 shows the contexts in which curly braces are used.

 Table B-9: Curly Brackets

 


| Context | Explanation |
| --- | --- |
| `{...}` | Block expression |
| `Type {...}` | `struct` literal |

  Table B-10 shows the contexts in which square brackets are used.

 Table B-10: Square Brackets

 


| Context | Explanation |
| --- | --- |
| `[...]` | Array literal |
| `[expr; len]` | Array literal containing `len` copies of `expr` |
| `[type; len]` | Array type containing `len` instances of `type` |
| `expr[expr]` | Collection indexing. Overloadable (`Index`, `IndexMut`) |
| `expr[..]`, `expr[a..]`, `expr[..b]`, `expr[a..b]` | Collection indexing pretending to be collection slicing, using `Range`, `RangeFrom`, `RangeTo`, or `RangeFull` as the “index” |

 

 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/appendix-02-operators.html>

Appendix C: Derivable Traits
============================

 In various places in the book, we’ve discussed the `derive` attribute, which you can apply to a struct or enum definition. The `derive` attribute generates code that will implement a trait with its own default implementation on the type you’ve annotated with the `derive` syntax.

 In this appendix, we provide a reference of all the traits in the standard library that you can use with `derive`. Each section covers:

 * What operators and methods deriving this trait will enable
* What the implementation of the trait provided by `derive` does
* What implementing the trait signifies about the type
* The conditions in which you’re allowed or not allowed to implement the trait
* Examples of operations that require the trait

 If you want different behavior from that provided by the `derive` attribute, consult the [standard library documentation](../std/index) for each trait for details of how to manually implement them.

 These traits listed here are the only ones defined by the standard library that can be implemented on your types using `derive`. Other traits defined in the standard library don’t have sensible default behavior, so it’s up to you to implement them in the way that makes sense for what you’re trying to accomplish.

 An example of a trait that can’t be derived is `Display`, which handles formatting for end users. You should always consider the appropriate way to display a type to an end user. What parts of the type should an end user be allowed to see? What parts would they find relevant? What format of the data would be most relevant to them? The Rust compiler doesn’t have this insight, so it can’t provide appropriate default behavior for you.

 The list of derivable traits provided in this appendix is not comprehensive: libraries can implement `derive` for their own traits, making the list of traits you can use `derive` with truly open-ended. Implementing `derive` involves using a procedural macro, which is covered in the [“Macros”](ch19-06-macros#macros) section of Chapter 19.

 ### 
`Debug` for Programmer Output

 The `Debug` trait enables debug formatting in format strings, which you indicate by adding `:?` within `{}` placeholders.

 The `Debug` trait allows you to print instances of a type for debugging purposes, so you and other programmers using your type can inspect an instance at a particular point in a program’s execution.

 The `Debug` trait is required, for example, in use of the `assert_eq!` macro. This macro prints the values of instances given as arguments if the equality assertion fails so programmers can see why the two instances weren’t equal.

 ### 
`PartialEq` and `Eq` for Equality Comparisons

 The `PartialEq` trait allows you to compare instances of a type to check for equality and enables use of the `==` and `!=` operators.

 Deriving `PartialEq` implements the `eq` method. When `PartialEq` is derived on structs, two instances are equal only if *all* fields are equal, and the instances are not equal if any fields are not equal. When derived on enums, each variant is equal to itself and not equal to the other variants.

 The `PartialEq` trait is required, for example, with the use of the `assert_eq!` macro, which needs to be able to compare two instances of a type for equality.

 The `Eq` trait has no methods. Its purpose is to signal that for every value of the annotated type, the value is equal to itself. The `Eq` trait can only be applied to types that also implement `PartialEq`, although not all types that implement `PartialEq` can implement `Eq`. One example of this is floating point number types: the implementation of floating point numbers states that two instances of the not-a-number (`NaN`) value are not equal to each other.

 An example of when `Eq` is required is for keys in a `HashMap<K, V>` so the `HashMap<K, V>` can tell whether two keys are the same.

 ### 
`PartialOrd` and `Ord` for Ordering Comparisons

 The `PartialOrd` trait allows you to compare instances of a type for sorting purposes. A type that implements `PartialOrd` can be used with the `<`, `>`, `<=`, and `>=` operators. You can only apply the `PartialOrd` trait to types that also implement `PartialEq`.

 Deriving `PartialOrd` implements the `partial_cmp` method, which returns an `Option<Ordering>` that will be `None` when the values given don’t produce an ordering. An example of a value that doesn’t produce an ordering, even though most values of that type can be compared, is the not-a-number (`NaN`) floating point value. Calling `partial_cmp` with any floating point number and the `NaN` floating point value will return `None`.

 When derived on structs, `PartialOrd` compares two instances by comparing the value in each field in the order in which the fields appear in the struct definition. When derived on enums, variants of the enum declared earlier in the enum definition are considered less than the variants listed later.

 The `PartialOrd` trait is required, for example, for the `gen_range` method from the `rand` crate that generates a random value in the range specified by a range expression.

 The `Ord` trait allows you to know that for any two values of the annotated type, a valid ordering will exist. The `Ord` trait implements the `cmp` method, which returns an `Ordering` rather than an `Option<Ordering>` because a valid ordering will always be possible. You can only apply the `Ord` trait to types that also implement `PartialOrd` and `Eq` (and `Eq` requires `PartialEq`). When derived on structs and enums, `cmp` behaves the same way as the derived implementation for `partial_cmp` does with `PartialOrd`.

 An example of when `Ord` is required is when storing values in a `BTreeSet<T>`, a data structure that stores data based on the sort order of the values.

 ### 
`Clone` and `Copy` for Duplicating Values

 The `Clone` trait allows you to explicitly create a deep copy of a value, and the duplication process might involve running arbitrary code and copying heap data. See the [“Ways Variables and Data Interact: Clone”](ch04-01-what-is-ownership#ways-variables-and-data-interact-clone) section in Chapter 4 for more information on `Clone`.

 Deriving `Clone` implements the `clone` method, which when implemented for the whole type, calls `clone` on each of the parts of the type. This means all the fields or values in the type must also implement `Clone` to derive `Clone`.

 An example of when `Clone` is required is when calling the `to_vec` method on a slice. The slice doesn’t own the type instances it contains, but the vector returned from `to_vec` will need to own its instances, so `to_vec` calls `clone` on each item. Thus, the type stored in the slice must implement `Clone`.

 The `Copy` trait allows you to duplicate a value by only copying bits stored on the stack; no arbitrary code is necessary. See the [“Stack-Only Data: Copy”](ch04-01-what-is-ownership#stack-only-data-copy) section in Chapter 4 for more information on `Copy`.

 The `Copy` trait doesn’t define any methods to prevent programmers from overloading those methods and violating the assumption that no arbitrary code is being run. That way, all programmers can assume that copying a value will be very fast.

 You can derive `Copy` on any type whose parts all implement `Copy`. A type that implements `Copy` must also implement `Clone`, because a type that implements `Copy` has a trivial implementation of `Clone` that performs the same task as `Copy`.

 The `Copy` trait is rarely required; types that implement `Copy` have optimizations available, meaning you don’t have to call `clone`, which makes the code more concise.

 Everything possible with `Copy` you can also accomplish with `Clone`, but the code might be slower or have to use `clone` in places.

 ### 
`Hash` for Mapping a Value to a Value of Fixed Size

 The `Hash` trait allows you to take an instance of a type of arbitrary size and map that instance to a value of fixed size using a hash function. Deriving `Hash` implements the `hash` method. The derived implementation of the `hash` method combines the result of calling `hash` on each of the parts of the type, meaning all fields or values must also implement `Hash` to derive `Hash`.

 An example of when `Hash` is required is in storing keys in a `HashMap<K, V>` to store data efficiently.

 ### 
`Default` for Default Values

 The `Default` trait allows you to create a default value for a type. Deriving `Default` implements the `default` function. The derived implementation of the `default` function calls the `default` function on each part of the type, meaning all fields or values in the type must also implement `Default` to derive `Default`.

 The `Default::default` function is commonly used in combination with the struct update syntax discussed in the [“Creating Instances From Other Instances With Struct Update Syntax”](ch05-01-defining-structs#creating-instances-from-other-instances-with-struct-update-syntax) section in Chapter 5. You can customize a few fields of a struct and then set and use a default value for the rest of the fields by using `..Default::default()`.

 The `Default` trait is required when you use the method `unwrap_or_default` on `Option<T>` instances, for example. If the `Option<T>` is `None`, the method `unwrap_or_default` will return the result of `Default::default` for the type `T` stored in the `Option<T>`.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/appendix-03-derivable-traits.html>

Appendix D - Useful Development Tools
=====================================

 In this appendix, we talk about some useful development tools that the Rust project provides. We’ll look at automatic formatting, quick ways to apply warning fixes, a linter, and integrating with IDEs.

 ### Automatic Formatting with `rustfmt`

 The `rustfmt` tool reformats your code according to the community code style. Many collaborative projects use `rustfmt` to prevent arguments about which style to use when writing Rust: everyone formats their code using the tool.

 To install `rustfmt`, enter the following:

 
```
$ rustup component add rustfmt

```
 This command gives you `rustfmt` and `cargo-fmt`, similar to how Rust gives you both `rustc` and `cargo`. To format any Cargo project, enter the following:

 
```
$ cargo fmt

```
 Running this command reformats all the Rust code in the current crate. This should only change the code style, not the code semantics. For more information on `rustfmt`, see [its documentation](https://github.com/rust-lang/rustfmt).

 ### Fix Your Code with `rustfix`

 The rustfix tool is included with Rust installations and can automatically fix compiler warnings that have a clear way to correct the problem that’s likely what you want. It’s likely you’ve seen compiler warnings before. For example, consider this code:

 Filename: src/main.rs

 
```
fn do_something() {}

fn main() {
    for i in 0..100 {
        do_something();
    }
}
```
 Here, we’re calling the `do_something` function 100 times, but we never use the variable `i` in the body of the `for` loop. Rust warns us about that:

 
```
$ cargo build
   Compiling myprogram v0.1.0 (file:///projects/myprogram)
warning: unused variable: `i`
 --> src/main.rs:4:9
  |
4 |     for i in 0..100 {
  |         ^ help: consider using `_i` instead
  |
  = note: #[warn(unused_variables)] on by default

    Finished dev [unoptimized + debuginfo] target(s) in 0.50s

```
 The warning suggests that we use `_i` as a name instead: the underscore indicates that we intend for this variable to be unused. We can automatically apply that suggestion using the `rustfix` tool by running the command `cargo fix`:

 
```
$ cargo fix
    Checking myprogram v0.1.0 (file:///projects/myprogram)
      Fixing src/main.rs (1 fix)
    Finished dev [unoptimized + debuginfo] target(s) in 0.59s

```
 When we look at *src/main.rs* again, we’ll see that `cargo fix` has changed the code:

 Filename: src/main.rs

 
```
fn do_something() {}

fn main() {
    for _i in 0..100 {
        do_something();
    }
}
```
 The `for` loop variable is now named `_i`, and the warning no longer appears.

 You can also use the `cargo fix` command to transition your code between different Rust editions. Editions are covered in Appendix E.

 ### More Lints with Clippy

 The Clippy tool is a collection of lints to analyze your code so you can catch common mistakes and improve your Rust code.

 To install Clippy, enter the following:

 
```
$ rustup component add clippy

```
 To run Clippy’s lints on any Cargo project, enter the following:

 
```
$ cargo clippy

```
 For example, say you write a program that uses an approximation of a mathematical constant, such as pi, as this program does:

 Filename: src/main.rs

 
```
fn main() {
    let x = 3.1415;
    let r = 8.0;
    println!("the area of the circle is {}", x * r * r);
}
```
 Running `cargo clippy` on this project results in this error:

 
```
error: approximate value of `f{32, 64}::consts::PI` found
 --> src/main.rs:2:13
  |
2 |     let x = 3.1415;
  |             ^^^^^^
  |
  = note: `#[deny(clippy::approx_constant)]` on by default
  = help: consider using the constant directly
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#approx_constant

```
 This error lets you know that Rust already has a more precise `PI` constant defined, and that your program would be more correct if you used the constant instead. You would then change your code to use the `PI` constant. The following code doesn’t result in any errors or warnings from Clippy:

 Filename: src/main.rs

 
```
fn main() {
    let x = std::f64::consts::PI;
    let r = 8.0;
    println!("the area of the circle is {}", x * r * r);
}
```
 For more information on Clippy, see [its documentation](https://github.com/rust-lang/rust-clippy).

 ### IDE Integration Using `rust-analyzer`

 To help IDE integration, the Rust community recommends using [`rust-analyzer`](https://rust-analyzer.github.io). This tool is a set of compiler-centric utilities that speaks the [Language Server Protocol](http://langserver.org/), which is a specification for IDEs and programming languages to communicate with each other. Different clients can use `rust-analyzer`, such as [the Rust analyzer plug-in for Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer).

 Visit the `rust-analyzer` project’s [home page](https://rust-analyzer.github.io) for installation instructions, then install the language server support in your particular IDE. Your IDE will gain abilities such as autocompletion, jump to definition, and inline errors.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/appendix-04-useful-development-tools.html>

Appendix E - Editions
=====================

 In Chapter 1, you saw that `cargo new` adds a bit of metadata to your *Cargo.toml* file about an edition. This appendix talks about what that means!

 The Rust language and compiler have a six-week release cycle, meaning users get a constant stream of new features. Other programming languages release larger changes less often; Rust releases smaller updates more frequently. After a while, all of these tiny changes add up. But from release to release, it can be difficult to look back and say, “Wow, between Rust 1.10 and Rust 1.31, Rust has changed a lot!”

 Every two or three years, the Rust team produces a new Rust *edition*. Each edition brings together the features that have landed into a clear package with fully updated documentation and tooling. New editions ship as part of the usual six-week release process.

 Editions serve different purposes for different people:

 * For active Rust users, a new edition brings together incremental changes into an easy-to-understand package.
* For non-users, a new edition signals that some major advancements have landed, which might make Rust worth another look.
* For those developing Rust, a new edition provides a rallying point for the project as a whole.

 At the time of this writing, three Rust editions are available: Rust 2015, Rust 2018, and Rust 2021. This book is written using Rust 2021 edition idioms.

 The `edition` key in *Cargo.toml* indicates which edition the compiler should use for your code. If the key doesn’t exist, Rust uses `2015` as the edition value for backward compatibility reasons.

 Each project can opt in to an edition other than the default 2015 edition. Editions can contain incompatible changes, such as including a new keyword that conflicts with identifiers in code. However, unless you opt in to those changes, your code will continue to compile even as you upgrade the Rust compiler version you use.

 All Rust compiler versions support any edition that existed prior to that compiler’s release, and they can link crates of any supported editions together. Edition changes only affect the way the compiler initially parses code. Therefore, if you’re using Rust 2015 and one of your dependencies uses Rust 2018, your project will compile and be able to use that dependency. The opposite situation, where your project uses Rust 2018 and a dependency uses Rust 2015, works as well.

 To be clear: most features will be available on all editions. Developers using any Rust edition will continue to see improvements as new stable releases are made. However, in some cases, mainly when new keywords are added, some new features might only be available in later editions. You will need to switch editions if you want to take advantage of such features.

 For more details, the [*Edition Guide*](https://doc.rust-lang.org/stable/edition-guide/index.html) is a complete book about editions that enumerates the differences between editions and explains how to automatically upgrade your code to a new edition via `cargo fix`.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/appendix-05-editions.html>

Appendix F: Translations of the Book
====================================

 For resources in languages other than English. Most are still in progress; see [the Translations label](https://github.com/rust-lang/book/issues?q=is%3Aopen+is%3Aissue+label%3ATranslations) to help or let us know about a new translation!

 * [Português](https://github.com/rust-br/rust-book-pt-br) (BR)
* [Português](https://github.com/nunojesus/rust-book-pt-pt) (PT)
* [简体中文](https://github.com/KaiserY/trpl-zh-cn)
* [正體中文](https://github.com/rust-tw/book-tw)
* [Українська](https://github.com/pavloslav/rust-book-uk-ua)
* [Español](https://github.com/thecodix/book), [alternate](https://github.com/ManRR/rust-book-es)
* [Italiano](https://github.com/EmanueleGurini/book_it)
* [Русский](https://github.com/rust-lang-ru/book)
* [한국어](https://github.com/rinthel/rust-lang-book-ko)
* [日本語](https://github.com/rust-lang-ja/book-ja)
* [Français](https://github.com/Jimskapt/rust-book-fr)
* [Polski](https://github.com/paytchoo/book-pl)
* [Cebuano](https://github.com/agentzero1/book)
* [Tagalog](https://github.com/josephace135/book)
* [Esperanto](https://github.com/psychoslave/Rust-libro)
* [ελληνική](https://github.com/TChatzigiannakis/rust-book-greek)
* [Svenska](https://github.com/sebras/book)
* [Farsi](https://github.com/pomokhtari/rust-book-fa)
* [Deutsch](https://github.com/rust-lang-de/rustbook-de)
* [हिंदी](https://github.com/venkatarun95/rust-book-hindi)
* [ไทย](https://github.com/rust-lang-th/book-th)
* [Danske](https://github.com/DanKHansen/book-dk)



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/appendix-06-translation.html>

Appendix G - How Rust is Made and “Nightly Rust”
================================================

 This appendix is about how Rust is made and how that affects you as a Rust developer.

 ### Stability Without Stagnation

 As a language, Rust cares a *lot* about the stability of your code. We want Rust to be a rock-solid foundation you can build on, and if things were constantly changing, that would be impossible. At the same time, if we can’t experiment with new features, we may not find out important flaws until after their release, when we can no longer change things.

 Our solution to this problem is what we call “stability without stagnation”, and our guiding principle is this: you should never have to fear upgrading to a new version of stable Rust. Each upgrade should be painless, but should also bring you new features, fewer bugs, and faster compile times.

 ### Choo, Choo! Release Channels and Riding the Trains

 Rust development operates on a *train schedule*. That is, all development is done on the `master` branch of the Rust repository. Releases follow a software release train model, which has been used by Cisco IOS and other software projects. There are three *release channels* for Rust:

 * Nightly
* Beta
* Stable

 Most Rust developers primarily use the stable channel, but those who want to try out experimental new features may use nightly or beta.

 Here’s an example of how the development and release process works: let’s assume that the Rust team is working on the release of Rust 1.5. That release happened in December of 2015, but it will provide us with realistic version numbers. A new feature is added to Rust: a new commit lands on the `master` branch. Each night, a new nightly version of Rust is produced. Every day is a release day, and these releases are created by our release infrastructure automatically. So as time passes, our releases look like this, once a night:

 
```
nightly: * - - * - - *

```
 Every six weeks, it’s time to prepare a new release! The `beta` branch of the Rust repository branches off from the `master` branch used by nightly. Now, there are two releases:

 
```
nightly: * - - * - - *
                     |
beta:                *

```
 Most Rust users do not use beta releases actively, but test against beta in their CI system to help Rust discover possible regressions. In the meantime, there’s still a nightly release every night:

 
```
nightly: * - - * - - * - - * - - *
                     |
beta:                *

```
 Let’s say a regression is found. Good thing we had some time to test the beta release before the regression snuck into a stable release! The fix is applied to `master`, so that nightly is fixed, and then the fix is backported to the `beta` branch, and a new release of beta is produced:

 
```
nightly: * - - * - - * - - * - - * - - *
                     |
beta:                * - - - - - - - - *

```
 Six weeks after the first beta was created, it’s time for a stable release! The `stable` branch is produced from the `beta` branch:

 
```
nightly: * - - * - - * - - * - - * - - * - * - *
                     |
beta:                * - - - - - - - - *
                                       |
stable:                                *

```
 Hooray! Rust 1.5 is done! However, we’ve forgotten one thing: because the six weeks have gone by, we also need a new beta of the *next* version of Rust, 1.6. So after `stable` branches off of `beta`, the next version of `beta` branches off of `nightly` again:

 
```
nightly: * - - * - - * - - * - - * - - * - * - *
                     |                         |
beta:                * - - - - - - - - *       *
                                       |
stable:                                *

```
 This is called the “train model” because every six weeks, a release “leaves the station”, but still has to take a journey through the beta channel before it arrives as a stable release.

 Rust releases every six weeks, like clockwork. If you know the date of one Rust release, you can know the date of the next one: it’s six weeks later. A nice aspect of having releases scheduled every six weeks is that the next train is coming soon. If a feature happens to miss a particular release, there’s no need to worry: another one is happening in a short time! This helps reduce pressure to sneak possibly unpolished features in close to the release deadline.

 Thanks to this process, you can always check out the next build of Rust and verify for yourself that it’s easy to upgrade to: if a beta release doesn’t work as expected, you can report it to the team and get it fixed before the next stable release happens! Breakage in a beta release is relatively rare, but `rustc` is still a piece of software, and bugs do exist.

 ### Unstable Features

 There’s one more catch with this release model: unstable features. Rust uses a technique called “feature flags” to determine what features are enabled in a given release. If a new feature is under active development, it lands on `master`, and therefore, in nightly, but behind a *feature flag*. If you, as a user, wish to try out the work-in-progress feature, you can, but you must be using a nightly release of Rust and annotate your source code with the appropriate flag to opt in.

 If you’re using a beta or stable release of Rust, you can’t use any feature flags. This is the key that allows us to get practical use with new features before we declare them stable forever. Those who wish to opt into the bleeding edge can do so, and those who want a rock-solid experience can stick with stable and know that their code won’t break. Stability without stagnation.

 This book only contains information about stable features, as in-progress features are still changing, and surely they’ll be different between when this book was written and when they get enabled in stable builds. You can find documentation for nightly-only features online.

 ### Rustup and the Role of Rust Nightly

 Rustup makes it easy to change between different release channels of Rust, on a global or per-project basis. By default, you’ll have stable Rust installed. To install nightly, for example:

 
```
$ rustup toolchain install nightly

```
 You can see all of the *toolchains* (releases of Rust and associated components) you have installed with `rustup` as well. Here’s an example on one of your authors’ Windows computer:

 
```
> rustup toolchain list
stable-x86_64-pc-windows-msvc (default)
beta-x86_64-pc-windows-msvc
nightly-x86_64-pc-windows-msvc

```
 As you can see, the stable toolchain is the default. Most Rust users use stable most of the time. You might want to use stable most of the time, but use nightly on a specific project, because you care about a cutting-edge feature. To do so, you can use `rustup override` in that project’s directory to set the nightly toolchain as the one `rustup` should use when you’re in that directory:

 
```
$ cd ~/projects/needs-nightly
$ rustup override set nightly

```
 Now, every time you call `rustc` or `cargo` inside of *~/projects/needs-nightly*, `rustup` will make sure that you are using nightly Rust, rather than your default of stable Rust. This comes in handy when you have a lot of Rust projects!

 ### The RFC Process and Teams

 So how do you learn about these new features? Rust’s development model follows a *Request For Comments (RFC) process*. If you’d like an improvement in Rust, you can write up a proposal, called an RFC.

 Anyone can write RFCs to improve Rust, and the proposals are reviewed and discussed by the Rust team, which is comprised of many topic subteams. There’s a full list of the teams [on Rust’s website](https://www.rust-lang.org/governance), which includes teams for each area of the project: language design, compiler implementation, infrastructure, documentation, and more. The appropriate team reads the proposal and the comments, writes some comments of their own, and eventually, there’s consensus to accept or reject the feature.

 If the feature is accepted, an issue is opened on the Rust repository, and someone can implement it. The person who implements it very well may not be the person who proposed the feature in the first place! When the implementation is ready, it lands on the `master` branch behind a feature gate, as we discussed in the [“Unstable Features”](#unstable-features) section.

 After some time, once Rust developers who use nightly releases have been able to try out the new feature, team members will discuss the feature, how it’s worked out on nightly, and decide if it should make it into stable Rust or not. If the decision is to move forward, the feature gate is removed, and the feature is now considered stable! It rides the trains into a new stable release of Rust.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/book/appendix-07-nightly-rust.html>

Introduction
============

 This book is the primary reference for the Rust programming language. It provides three kinds of material:

 * Chapters that informally describe each language construct and their use.
* Chapters that informally describe the memory model, concurrency model, runtime services, linkage model, and debugging facilities.
* Appendix chapters providing rationale and references to languages that influenced the design.

  Warning: This book is incomplete. Documenting everything takes a while. See the [GitHub issues](https://github.com/rust-lang/reference/issues) for what is not documented in this book.

  Rust releases
-------------

 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](../std/index), 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/](index). 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/index.html).

 What *The Reference* is not
---------------------------

 This book does not serve as an introduction to the language. Background familiarity with the language is assumed. A separate [book](../index) is available to help acquire such background familiarity.

 This book also does not serve as a reference to the [standard library](../std/index) 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/rustc/index.html). Cargo has a [book](https://doc.rust-lang.org/cargo/index.html) that contains a [reference](https://doc.rust-lang.org/cargo/reference/index.html). There are a few pages such as <linkage> 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/unstable-book/index.html).

 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.

 Finally, this book is not normative. It may include details that are specific to `rustc` itself, and should not be taken as a specification for the Rust language. We intend to produce such a book someday, and until then, the reference is the closest thing we have to one.

 How to use this book
--------------------

 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](expressions#temporaries) is defined in the [expressions chapter](expressions), 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.

 ### Conventions

 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.
* Differences in the language by which edition the crate is compiled under are in a blockquote that start with the words "Edition Differences:" in **bold**.

 
>  **Edition Differences**: In the 2015 edition, this syntax is valid that is disallowed as of the 2018 edition.
> 
>
* Notes that contain useful information about the state of the book or point out useful, but mostly out of scope, information are in blockquotes that start with the word "Note:" in **bold**.

 
>  **Note**: This is an example note.
> 
>
* 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 `<code>` 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 structure is in blockquotes with either "Lexer" or "Syntax" in **bold superscript** as the first line.

 
>  **Syntax**  
>  *ExampleGrammar*:  
>  `~` [*Expression*](expressions)  
>  | `box` [*Expression*](expressions)
> 
>  

 See [Notation](notation) for more detail.

 Contributing
------------

 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. We also want the reference to be as normative as possible, so if you see anything that is wrong or is non-normative but not specifically called out, please also [file an issue](https://github.com/rust-lang/reference/issues).



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/introduction.html>

Crate std
=========


The Rust Standard Library
-------------------------

 The Rust Standard Library is the foundation of portable Rust software, a set of minimal and battle-tested shared abstractions for the [broader Rust ecosystem](https://crates.io). It offers core types, like [`Vec<T>`](vec/struct.vec "struct std::vec::Vec") and [`Option<T>`](option/enum.option "enum std::option::Option"), library-defined [operations on language primitives](#primitives), [standard macros](#macros), [I/O](io/index "mod std::io") and [multithreading](thread/index "mod std::thread"), among [many other things](#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`](../book/ch07-02-defining-modules-to-control-scope-and-privacy) statements through the path `std`, as in [`use std::env`](env/index).

 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 bar](#) at the top of the page.

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

 * [`std::*` modules](#modules)
* [Primitive types](#primitives)
* [Standard macros](#macros)
* [The Rust Prelude](prelude/index "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 `[-]` button near the top of the page to collapse it into a more skimmable view.

 While you are looking at that `[-]` button also notice the `source` link. Rust’s API documentation comes with the source code and you are encouraged to read it. The standard library source is generally high quality and a peek behind the curtains is often enlightening.

 What is in the standard library documentation?
----------------------------------------------

 First of all, The Rust Standard Library is divided into a number of focused modules, [all listed further down this page](#modules). These modules are the bedrock upon which all of Rust is forged, and they have mighty names like [`std::slice`](slice/index "mod std::slice") and [`std::cmp`](cmp/index "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](../book/ch03-02-data-types) 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](#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 `i32`](primitive.i32 "primitive i32") that lists all the methods that can be called on 32-bit integers (very useful), and there is a [page for the module `std::i32`](i32/index "mod std::i32") that documents the constant values [`MIN`](i32/constant.min "constant std::i32::MIN") and [`MAX`](i32/constant.max "constant std::i32::MAX") (rarely useful).

 Note the documentation for the primitives [`str`](primitive.str "primitive str") and [`[T]`](primitive.slice "primitive slice") (also called ‘slice’). Many method calls on [`String`](string/struct.string "struct std::string::String") and [`Vec<T>`](vec/struct.vec "struct std::vec::Vec") are actually calls to methods on [`str`](primitive.str "primitive str") and [`[T]`](primitive.slice "primitive slice") respectively, via [deref coercions](../book/ch15-02-deref#implicit-deref-coercions-with-functions-and-methods).

 Third, the standard library defines [The Rust Prelude](prelude/index "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](#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.

 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). 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 [Discord](https://discord.gg/rust-lang) #docs.

 A Tour of The Rust Standard Library
-----------------------------------

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

 ### Containers and collections

 The [`option`](option/index "mod std::option") and [`result`](result/index "mod std::result") modules define optional and error-handling types, [`Option<T>`](option/enum.option "enum std::option::Option") and [`Result<T, E>`](result/enum.result "enum std::result::Result"). The [`iter`](iter/index "mod std::iter") module defines Rust’s iterator trait, [`Iterator`](iter/trait.iterator "trait std::iter::Iterator"), which works with the [`for`](../book/ch03-05-control-flow#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<T>`](vec/struct.vec "struct std::vec::Vec") - A heap-allocated *vector* that is resizable at runtime.
* [`[T; N]`](primitive.array "primitive array") - An inline *array* with a fixed size at compile time.
* [`[T]`](primitive.slice "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]>`](boxed/index "mod std::boxed") - *owned slice*

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

 For converting to strings use the [`format!`](macro.format "macro std::format") macro, and for converting from strings use the [`FromStr`](str/trait.fromstr "trait std::str::FromStr") trait.

 Data may be shared by placing it in a reference-counted box or the [`Rc`](rc/struct.rc "struct std::rc::Rc") type, and if further contained in a [`Cell`](cell/struct.cell "struct std::cell::Cell") or [`RefCell`](cell/struct.refcell "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`](sync/struct.arc "struct std::sync::Arc"), with a [`Mutex`](sync/struct.mutex "struct std::sync::Mutex") to get the same effect.

 The [`collections`](collections/index "mod std::collections") module defines maps, sets, linked lists and other typical collection types, including the common [`HashMap<K, V>`](collections/hash_map/struct.hashmap "struct std::collections::hash_map::HashMap").

 ### 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](fs/struct.file "struct std::fs::File"), [TCP](net/struct.tcpstream "struct std::net::TcpStream"), and [UDP](net/struct.udpsocket "struct std::net::UdpSocket"), are defined in the [`io`](io/index "mod std::io"), [`fs`](fs/index "mod std::fs"), and [`net`](net/index "mod std::net") modules.

 The [`thread`](thread/index "mod std::thread") module contains Rust’s threading abstractions. [`sync`](sync/index "mod std::sync") contains further primitive shared memory types, including [`atomic`](sync/atomic/index "mod std::sync::atomic") and [`mpsc`](sync/mpsc/index "mod std::sync::mpsc"), which contains the channel types for message passing.

 Primitive Types
---------------


* [never](primitive.never "primitive std::never")Experimental

The `!` type, also called “never”.
* [array](primitive.array "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](primitive.bool "primitive std::bool")
The boolean type.
* [char](primitive.char "primitive std::char")
A character type.
* [f32](primitive.f32 "primitive std::f32")
A 32-bit floating point type (specifically, the “binary32” type defined in IEEE 754-2008).
* [f64](primitive.f64 "primitive std::f64")
A 64-bit floating point type (specifically, the “binary64” type defined in IEEE 754-2008).
* [fn](primitive.fn "primitive std::fn")
Function pointers, like `fn(usize) -> bool`.
* [i8](primitive.i8 "primitive std::i8")
The 8-bit signed integer type.
* [i16](primitive.i16 "primitive std::i16")
The 16-bit signed integer type.
* [i32](primitive.i32 "primitive std::i32")
The 32-bit signed integer type.
* [i64](primitive.i64 "primitive std::i64")
The 64-bit signed integer type.
* [i128](primitive.i128 "primitive std::i128")
The 128-bit signed integer type.
* [isize](primitive.isize "primitive std::isize")
The pointer-sized signed integer type.
* [pointer](primitive.pointer "primitive std::pointer")
Raw, unsafe pointers, `*const T`, and `*mut T`.
* [reference](primitive.reference "primitive std::reference")
References, `&T` and `&mut T`.
* [slice](primitive.slice "primitive std::slice")
A dynamically-sized view into a contiguous sequence, `[T]`. Contiguous here means that elements are laid out so that every element is the same distance from its neighbors.
* [str](primitive.str "primitive std::str")
String slices.
* [tuple](primitive.tuple "primitive std::tuple")
A finite heterogeneous sequence, `(T, U, ..)`.
* [u8](primitive.u8 "primitive std::u8")
The 8-bit unsigned integer type.
* [u16](primitive.u16 "primitive std::u16")
The 16-bit unsigned integer type.
* [u32](primitive.u32 "primitive std::u32")
The 32-bit unsigned integer type.
* [u64](primitive.u64 "primitive std::u64")
The 64-bit unsigned integer type.
* [u128](primitive.u128 "primitive std::u128")
The 128-bit unsigned integer type.
* [unit](primitive.unit "primitive std::unit")
The `()` type, also called “unit”.
* [usize](primitive.usize "primitive std::usize")
The pointer-sized unsigned integer type.


Modules
-------


* [assert\_matches](assert_matches/index "mod std::assert_matches")Experimental

Unstable module containing the unstable `assert_matches` macro.
* [async\_iter](async_iter/index "mod std::async_iter")Experimental

Composable asynchronous iteration.
* [intrinsics](intrinsics/index "mod std::intrinsics")Experimental

Compiler intrinsics.
* [simd](simd/index "mod std::simd")Experimental

Portable SIMD module.
* [alloc](alloc/index "mod std::alloc")
Memory allocation APIs.
* [any](any/index "mod std::any")
Utilities for dynamic typing or type reflection.
* [arch](arch/index "mod std::arch")
SIMD and vendor intrinsics module.
* [array](array/index "mod std::array")
Utilities for the array primitive type.
* [ascii](ascii/index "mod std::ascii")
Operations on ASCII strings and characters.
* [backtrace](backtrace/index "mod std::backtrace")
Support for capturing a stack backtrace of an OS thread
* [borrow](borrow/index "mod std::borrow")
A module for working with borrowed data.
* [boxed](boxed/index "mod std::boxed")
The `Box<T>` type for heap allocation.
* [cell](cell/index "mod std::cell")
Shareable mutable containers.
* [char](char/index "mod std::char")
Utilities for the `char` primitive type.
* [clone](clone/index "mod std::clone")
The `Clone` trait for types that cannot be ‘implicitly copied’.
* [cmp](cmp/index "mod std::cmp")
Utilities for comparing and ordering values.
* [collections](collections/index "mod std::collections")
Collection types.
* [convert](convert/index "mod std::convert")
Traits for conversions between types.
* [default](default/index "mod std::default")
The `Default` trait for types with a default value.
* [env](env/index "mod std::env")
Inspection and manipulation of the process’s environment.
* [error](error/index "mod std::error")
Interfaces for working with Errors.
* [f32](f32/index "mod std::f32")
Constants for the `f32` single-precision floating point type.
* [f64](f64/index "mod std::f64")
Constants for the `f64` double-precision floating point type.
* [ffi](ffi/index "mod std::ffi")
Utilities related to FFI bindings.
* [fmt](fmt/index "mod std::fmt")
Utilities for formatting and printing `String`s.
* [fs](fs/index "mod std::fs")
Filesystem manipulation operations.
* [future](future/index "mod std::future")
Asynchronous basic functionality.
* [hash](hash/index "mod std::hash")
Generic hashing support.
* [hint](hint/index "mod std::hint")
Hints to compiler that affects how code should be emitted or optimized. Hints may be compile time or runtime.
* [i8](i8/index "mod std::i8")Deprecation planned

Redundant constants module for the [`i8` primitive type](primitive.i8 "primitive i8").
* [i16](i16/index "mod std::i16")Deprecation planned

Redundant constants module for the [`i16` primitive type](primitive.i16 "primitive i16").
* [i32](i32/index "mod std::i32")Deprecation planned

Redundant constants module for the [`i32` primitive type](primitive.i32 "primitive i32").
* [i64](i64/index "mod std::i64")Deprecation planned

Redundant constants module for the [`i64` primitive type](primitive.i64 "primitive i64").
* [i128](i128/index "mod std::i128")Deprecation planned

Redundant constants module for the [`i128` primitive type](primitive.i128 "primitive i128").
* [io](io/index "mod std::io")
Traits, helpers, and type definitions for core I/O functionality.
* [isize](isize/index "mod std::isize")Deprecation planned

Redundant constants module for the [`isize` primitive type](primitive.isize "primitive isize").
* [iter](iter/index "mod std::iter")
Composable external iteration.
* [marker](marker/index "mod std::marker")
Primitive traits and types representing basic properties of types.
* [mem](mem/index "mod std::mem")
Basic functions for dealing with memory.
* [net](net/index "mod std::net")
Networking primitives for TCP/UDP communication.
* [num](num/index "mod std::num")
Additional functionality for numerics.
* [ops](ops/index "mod std::ops")
Overloadable operators.
* [option](option/index "mod std::option")
Optional values.
* [os](os/index "mod std::os")
OS-specific functionality.
* [panic](panic/index "mod std::panic")
Panic support in the standard library.
* [path](path/index "mod std::path")
Cross-platform path manipulation.
* [pin](pin/index "mod std::pin")
Types that pin data to its location in memory.
* [prelude](prelude/index "mod std::prelude")
The Rust Prelude
* [primitive](primitive/index "mod std::primitive")
This module reexports the primitive types to allow usage that is not possibly shadowed by other declared types.
* [process](process/index "mod std::process")
A module for working with processes.
* [ptr](ptr/index "mod std::ptr")
Manually manage memory through raw pointers.
* [rc](rc/index "mod std::rc")
Single-threaded reference-counting pointers. ‘Rc’ stands for ‘Reference Counted’.
* [result](result/index "mod std::result")
Error handling with the `Result` type.
* [slice](slice/index "mod std::slice")
Utilities for the slice primitive type.
* [str](str/index "mod std::str")
Utilities for the `str` primitive type.
* [string](string/index "mod std::string")
A UTF-8–encoded, growable string.
* [sync](sync/index "mod std::sync")
Useful synchronization primitives.
* [task](task/index "mod std::task")
Types and Traits for working with asynchronous tasks.
* [thread](thread/index "mod std::thread")
Native threads.
* [time](time/index "mod std::time")
Temporal quantification.
* [u8](u8/index "mod std::u8")Deprecation planned

Redundant constants module for the [`u8` primitive type](primitive.u8 "primitive u8").
* [u16](u16/index "mod std::u16")Deprecation planned

Redundant constants module for the [`u16` primitive type](primitive.u16 "primitive u16").
* [u32](u32/index "mod std::u32")Deprecation planned

Redundant constants module for the [`u32` primitive type](primitive.u32 "primitive u32").
* [u64](u64/index "mod std::u64")Deprecation planned

Redundant constants module for the [`u64` primitive type](primitive.u64 "primitive u64").
* [u128](u128/index "mod std::u128")Deprecation planned

Redundant constants module for the [`u128` primitive type](primitive.u128 "primitive u128").
* [usize](usize/index "mod std::usize")Deprecation planned

Redundant constants module for the [`usize` primitive type](primitive.usize "primitive usize").
* [vec](vec/index "mod std::vec")
A contiguous growable array type with heap-allocated contents, written `Vec<T>`.


Macros
------


* [concat\_bytes](macro.concat_bytes "macro std::concat_bytes")Experimental

Concatenates literals into a byte slice.
* [concat\_idents](macro.concat_idents "macro std::concat_idents")Experimental

Concatenates identifiers into one identifier.
* [const\_format\_args](macro.const_format_args "macro std::const_format_args")Experimental

Same as [`format_args`](macro.format_args "macro std::format_args"), but can be used in some const contexts.
* [format\_args\_nl](macro.format_args_nl "macro std::format_args_nl")Experimental

Same as [`format_args`](macro.format_args "macro std::format_args"), but adds a newline in the end.
* [log\_syntax](macro.log_syntax "macro std::log_syntax")Experimental

Prints passed tokens into the standard output.
* [trace\_macros](macro.trace_macros "macro std::trace_macros")Experimental

Enables or disables tracing functionality used for debugging other macros.
* [assert](macro.assert "macro std::assert")
Asserts that a boolean expression is `true` at runtime.
* [assert\_eq](macro.assert_eq "macro std::assert_eq")
Asserts that two expressions are equal to each other (using [`PartialEq`](cmp/trait.partialeq "trait std::cmp::PartialEq")).
* [assert\_ne](macro.assert_ne "macro std::assert_ne")
Asserts that two expressions are not equal to each other (using [`PartialEq`](cmp/trait.partialeq "trait std::cmp::PartialEq")).
* [cfg](macro.cfg "macro std::cfg")
Evaluates boolean combinations of configuration flags at compile-time.
* [column](macro.column "macro std::column")
Expands to the column number at which it was invoked.
* [compile\_error](macro.compile_error "macro std::compile_error")
Causes compilation to fail with the given error message when encountered.
* [concat](macro.concat "macro std::concat")
Concatenates literals into a static string slice.
* [dbg](macro.dbg "macro std::dbg")
Prints and returns the value of a given expression for quick and dirty debugging.
* [debug\_assert](macro.debug_assert "macro std::debug_assert")
Asserts that a boolean expression is `true` at runtime.
* [debug\_assert\_eq](macro.debug_assert_eq "macro std::debug_assert_eq")
Asserts that two expressions are equal to each other.
* [debug\_assert\_ne](macro.debug_assert_ne "macro std::debug_assert_ne")
Asserts that two expressions are not equal to each other.
* [env](macro.env "macro std::env")
Inspects an environment variable at compile time.
* [eprint](macro.eprint "macro std::eprint")
Prints to the standard error.
* [eprintln](macro.eprintln "macro std::eprintln")
Prints to the standard error, with a newline.
* [file](macro.file "macro std::file")
Expands to the file name in which it was invoked.
* [format](macro.format "macro std::format")
Creates a `String` using interpolation of runtime expressions.
* [format\_args](macro.format_args "macro std::format_args")
Constructs parameters for the other string-formatting macros.
* [include](macro.include "macro std::include")
Parses a file as an expression or an item according to the context.
* [include\_bytes](macro.include_bytes "macro std::include_bytes")
Includes a file as a reference to a byte array.
* [include\_str](macro.include_str "macro std::include_str")
Includes a UTF-8 encoded file as a string.
* [is\_x86\_feature\_detected](macro.is_x86_feature_detected "macro std::is_x86_feature_detected")x86 or x86-64

A macro to test at *runtime* whether a CPU feature is available on x86/x86-64 platforms.
* [line](macro.line "macro std::line")
Expands to the line number on which it was invoked.
* [matches](macro.matches "macro std::matches")
Returns whether the given expression matches any of the given patterns.
* [module\_path](macro.module_path "macro std::module_path")
Expands to a string that represents the current module path.
* [option\_env](macro.option_env "macro std::option_env")
Optionally inspects an environment variable at compile time.
* [panic](macro.panic "macro std::panic")
Panics the current thread.
* [print](macro.print "macro std::print")
Prints to the standard output.
* [println](macro.println "macro std::println")
Prints to the standard output, with a newline.
* [stringify](macro.stringify "macro std::stringify")
Stringifies its arguments.
* [thread\_local](macro.thread_local "macro std::thread_local")
Declare a new thread local storage key of type [`std::thread::LocalKey`](thread/struct.localkey "struct std::thread::LocalKey").
* [todo](macro.todo "macro std::todo")
Indicates unfinished code.
* [try](macro.try "macro std::try")Deprecated

Unwraps a result or propagates its error.
* [unimplemented](macro.unimplemented "macro std::unimplemented")
Indicates unimplemented code by panicking with a message of “not implemented”.
* [unreachable](macro.unreachable "macro std::unreachable")
Indicates unreachable code.
* [vec](macro.vec "macro std::vec")
Creates a [`Vec`](vec/struct.vec "struct std::vec::Vec") containing the arguments.
* [write](macro.write "macro std::write")
Writes formatted data into a buffer.
* [writeln](macro.writeln "macro std::writeln")
Write formatted data into a buffer, with a newline appended.


Keywords
--------


* [SelfTy](keyword.selfty "keyword std::SelfTy")
The implementing type within a [`trait`](keyword.trait) or [`impl`](keyword.impl) block, or the current type within a type definition.
* [as](keyword.as "keyword std::as")
Cast between types, or rename an import.
* [async](keyword.async "keyword std::async")
Return a [`Future`](future/trait.future "trait std::future::Future") instead of blocking the current thread.
* [await](keyword.await "keyword std::await")
Suspend execution until the result of a [`Future`](future/trait.future "trait std::future::Future") is ready.
* [break](keyword.break "keyword std::break")
Exit early from a loop.
* [const](keyword.const "keyword std::const")
Compile-time constants, compile-time evaluable functions, and raw pointers.
* [continue](keyword.continue "keyword std::continue")
Skip to the next iteration of a loop.
* [crate](keyword.crate "keyword std::crate")
A Rust binary or library.
* [dyn](keyword.dyn "keyword std::dyn")

`dyn` is a prefix of a [trait object](../book/ch17-02-trait-objects)’s type.
* [else](keyword.else "keyword std::else")
What expression to evaluate when an [`if`](keyword.if) condition evaluates to [`false`](keyword.false).
* [enum](keyword.enum "keyword std::enum")
A type that can be any one of several variants.
* [extern](keyword.extern "keyword std::extern")
Link to or import external code.
* [false](keyword.false "keyword std::false")
A value of type [`bool`](primitive.bool "primitive bool") representing logical **false**.
* [fn](keyword.fn "keyword std::fn")
A function or function pointer.
* [for](keyword.for "keyword std::for")
Iteration with [`in`](keyword.in), trait implementation with [`impl`](keyword.impl), or [higher-ranked trait bounds](../reference/trait-bounds#higher-ranked-trait-bounds) (`for<'a>`).
* [if](keyword.if "keyword std::if")
Evaluate a block if a condition holds.
* [impl](keyword.impl "keyword std::impl")
Implement some functionality for a type.
* [in](keyword.in "keyword std::in")
Iterate over a series of values with [`for`](keyword.for).
* [let](keyword.let "keyword std::let")
Bind a value to a variable.
* [loop](keyword.loop "keyword std::loop")
Loop indefinitely.
* [match](keyword.match "keyword std::match")
Control flow based on pattern matching.
* [mod](keyword.mod "keyword std::mod")
Organize code into [modules](../reference/items/modules).
* [move](keyword.move "keyword std::move")
Capture a [closure](../book/ch13-01-closures)’s environment by value.
* [mut](keyword.mut "keyword std::mut")
A mutable variable, reference, or pointer.
* [pub](keyword.pub "keyword std::pub")
Make an item visible to others.
* [ref](keyword.ref "keyword std::ref")
Bind by reference during pattern matching.
* [return](keyword.return "keyword std::return")
Return a value from a function.
* [self](keyword.self "keyword std::self")
The receiver of a method, or the current module.
* [static](keyword.static "keyword std::static")
A static item is a value which is valid for the entire duration of your program (a `'static` lifetime).
* [struct](keyword.struct "keyword std::struct")
A type that is composed of other types.
* [super](keyword.super "keyword std::super")
The parent of the current [module](../reference/items/modules).
* [trait](keyword.trait "keyword std::trait")
A common interface for a group of types.
* [true](keyword.true "keyword std::true")
A value of type [`bool`](primitive.bool "primitive bool") representing logical **true**.
* [type](keyword.type "keyword std::type")
Define an alias for an existing type.
* [union](keyword.union "keyword std::union")
The [Rust equivalent of a C-style union](../reference/items/unions).
* [unsafe](keyword.unsafe "keyword std::unsafe")
Code or interfaces whose [memory safety](../book/ch19-01-unsafe-rust) cannot be verified by the type system.
* [use](keyword.use "keyword std::use")
Import or rename items from other crates or modules.
* [where](keyword.where "keyword std::where")
Add constraints that must be upheld to use an item.
* [while](keyword.while "keyword std::while")
Loop while a condition is upheld.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/index.html>

If you are not automatically redirected to the error code index, please [here](https://doc.rust-lang.org/error_codes/error-index.html).
=======================================================================================================================================



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/error-index.html>

Macro std::println
==================



```
macro_rules! println {
    () => { ... };
    ($($arg:tt)*) => { ... };
}
```

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!`](macro.format "macro std::format"), but writes to the standard output instead. See [`std::fmt`](fmt/index "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()`](io/struct.stdout "struct std::io::Stdout"):

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

let mut lock = stdout().lock();
writeln!(lock, "hello world").unwrap();
```
 Use `println!` only for the primary output of your program. Use [`eprintln!`](macro.eprintln "macro std::eprintln") instead to print error and progress messages.

 Panics
------

 Panics if writing to [`io::stdout`](io/fn.stdout "fn std::io::stdout") fails.

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

 Examples
--------

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


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/macro.println.html>

Macro std::dbg
==============



```
macro_rules! dbg {
    () => { ... };
    ($val:expr $(,)?) => { ... };
    ($($val:expr),+ $(,)?) => { ... };
}
```

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] a * 2 = 4
assert_eq!(b, 5);
```
 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.

 Stability
---------

 The exact output printed by this macro should not be relied upon and is subject to future changes.

 Panics
------

 Panics if writing to `io::stderr` fails.

 Further examples
----------------

 With a method call:

 
```
fn foo(n: usize) {
    if let Some(_) = dbg!(n.checked_sub(4)) {
        // ...
    }
}

foo(3)
```
 This prints to [stderr](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)):

 
```
[src/main.rs:4] 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));
```
 This prints to [stderr](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)):

 
```
[src/main.rs:3] n <= 1 = false
[src/main.rs:3] n <= 1 = false
[src/main.rs:3] n <= 1 = false
[src/main.rs:3] n <= 1 = true
[src/main.rs:4] 1 = 1
[src/main.rs:5] n * factorial(n - 1) = 2
[src/main.rs:5] n * factorial(n - 1) = 6
[src/main.rs:5] n * factorial(n - 1) = 24
[src/main.rs:11] factorial(4) = 24

```
 The `dbg!(..)` macro moves the input:

 ⓘ
```
/// 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!
```

 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));
```
 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
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/macro.dbg.html>

Attributes
==========

 
>  **Syntax**  
>  *InnerAttribute* :  
>  `#` `!` `[` *Attr* `]`
> 
>  *OuterAttribute* :  
>  `#` `[` *Attr* `]`
> 
>  *Attr* :  
>  [*SimplePath*](paths#simple-paths) *AttrInput*?
> 
>  *AttrInput* :  
>  [*DelimTokenTree*](macros)  
>  | `=` [*Expression*](expressions)
> 
>  

 An *attribute* is a general, free-form metadatum that is interpreted according to name, convention, language, and compiler version. Attributes are modeled on Attributes in [ECMA-335](https://www.ecma-international.org/publications/standards/Ecma-335.htm), with the syntax coming from [ECMA-334](https://www.ecma-international.org/publications/standards/Ecma-334.htm) (C#).

 *Inner attributes*, written with a bang (`!`) after the hash (`#`), apply to the item that the attribute is declared within. *Outer attributes*, written without the bang after the hash, apply to the thing that follows the attribute.

 The attribute consists of a path to the attribute, followed by an optional delimited token tree whose interpretation is defined by the attribute. Attributes other than macro attributes also allow the input to be an equals sign (`=`) followed by an expression. See the [meta item syntax](#meta-item-attribute-syntax) below for more details.

 Attributes can be classified into the following kinds:

 * [Built-in attributes](#built-in-attributes-index)
* [Macro attributes](procedural-macros#attribute-macros)
* [Derive macro helper attributes](procedural-macros#derive-macro-helper-attributes)
* [Tool attributes](#tool-attributes)

 Attributes may be applied to many things in the language:

 * All [item declarations](items) accept outer attributes while [external blocks](items/external-blocks), [functions](items/functions), [implementations](items/implementations), and [modules](items/modules) accept inner attributes.
* Most <statements> accept outer attributes (see [Expression Attributes](expressions#expression-attributes) for limitations on expression statements).
* [Block expressions](expressions/block-expr) accept outer and inner attributes, but only when they are the outer expression of an [expression statement](statements#expression-statements) or the final expression of another block expression.
* [Enum](items/enumerations) variants and [struct](items/structs) and [union](items/unions) fields accept outer attributes.
* [Match expression arms](expressions/match-expr) accept outer attributes.
* [Generic lifetime or type parameter](items/generics) accept outer attributes.
* Expressions accept outer attributes in limited situations, see [Expression Attributes](expressions#expression-attributes) for details.
* [Function](items/functions), [closure](expressions/closure-expr) and [function pointer](types/function-pointer) parameters accept outer attributes. This includes attributes on variadic parameters denoted with `...` in function pointers and [external blocks](items/external-blocks#variadic-functions).

 Some examples of attributes:

 
```
#![allow(unused)]
fn main() {
// General metadata applied to the enclosing module or crate.
#![crate_type = "lib"]

// A function marked as a unit test
#[test]
fn test_foo() {
    /* ... */
}

// A conditionally-compiled module
#[cfg(target_os = "linux")]
mod bar {
    /* ... */
}

// A lint attribute used to suppress a warning/error
#[allow(non_camel_case_types)]
type int8_t = i8;

// Inner attribute applies to the entire function.
fn some_unused_variables() {
  #![allow(unused_variables)]

  let x = ();
  let y = ();
  let z = ();
}
}
```
 Meta Item Attribute Syntax
--------------------------

 A "meta item" is the syntax used for the *Attr* rule by most [built-in attributes](#built-in-attributes-index). It has the following grammar:

 
>  **Syntax**  
>  *MetaItem* :  
>  [*SimplePath*](paths#simple-paths)  
>  | [*SimplePath*](paths#simple-paths) `=` [*Expression*](expressions)  
>  | [*SimplePath*](paths#simple-paths) `(` *MetaSeq*? `)`
> 
>  *MetaSeq* :  
>  *MetaItemInner* ( `,` MetaItemInner )\* `,`?
> 
>  *MetaItemInner* :  
>  *MetaItem*  
>  | [*Expression*](expressions)
> 
>  

 Expressions in meta items must macro-expand to literal expressions, which must not include integer or float type suffixes. Expressions which are not literal expressions will be syntactically accepted (and can be passed to proc-macros), but will be rejected after parsing.

 Note that if the attribute appears within another macro, it will be expanded after that outer macro. For example, the following code will expand the `Serialize` proc-macro first, which must preserve the `include_str!` call in order for it to be expanded:

 
```
#[derive(Serialize)]
struct Foo {
    #[doc = include_str!("x.md")]
    x: u32
}
```
 Additionally, macros in attributes will be expanded only after all other attributes applied to the item:

 
```
#[macro_attr1] // expanded first
#[doc = mac!()] // `mac!` is expanded fourth.
#[macro_attr2] // expanded second
#[derive(MacroDerive1, MacroDerive2)] // expanded third
fn foo() {}
```
 Various built-in attributes use different subsets of the meta item syntax to specify their inputs. The following grammar rules show some commonly used forms:

 
>  **Syntax**  
>  *MetaWord*:  
>  [IDENTIFIER](identifiers)
> 
>  *MetaNameValueStr*:  
>  [IDENTIFIER](identifiers) `=` ([STRING\_LITERAL](tokens#string-literals) | [RAW\_STRING\_LITERAL](tokens#raw-string-literals))
> 
>  *MetaListPaths*:  
>  [IDENTIFIER](identifiers) `(` ( [*SimplePath*](paths#simple-paths) (`,` [*SimplePath*](paths#simple-paths))\* `,`? )? `)`
> 
>  *MetaListIdents*:  
>  [IDENTIFIER](identifiers) `(` ( [IDENTIFIER](identifiers) (`,` [IDENTIFIER](identifiers))\* `,`? )? `)`
> 
>  *MetaListNameValueStr*:  
>  [IDENTIFIER](identifiers) `(` ( *MetaNameValueStr* (`,` *MetaNameValueStr*)\* `,`? )? `)`
> 
>  

 Some examples of meta items are:

 


| Style | Example |
| --- | --- |
| *MetaWord* | `no_std` |
| *MetaNameValueStr* | `doc = "example"` |
| *MetaListPaths* | `allow(unused, clippy::inline_always)` |
| *MetaListIdents* | `macro_use(foo, bar)` |
| *MetaListNameValueStr* | `link(name = "CoreFoundation", kind = "framework")` |

  Active and inert attributes
---------------------------

 An attribute is either active or inert. During attribute processing, *active attributes* remove themselves from the thing they are on while *inert attributes* stay on.

 The [`cfg`](conditional-compilation#the-cfg-attribute) and [`cfg_attr`](conditional-compilation#the-cfg_attr-attribute) attributes are active. The [`test`](attributes/testing#the-test-attribute) attribute is inert when compiling for tests and active otherwise. [Attribute macros](procedural-macros#attribute-macros) are active. All other attributes are inert.

 Tool attributes
---------------

 The compiler may allow attributes for external tools where each tool resides in its own namespace in the [tool prelude](names/preludes#tool-prelude). The first segment of the attribute path is the name of the tool, with one or more additional segments whose interpretation is up to the tool.

 When a tool is not in use, the tool's attributes are accepted without a warning. When the tool is in use, the tool is responsible for processing and interpretation of its attributes.

 Tool attributes are not available if the [`no_implicit_prelude`](names/preludes#the-no_implicit_prelude-attribute) attribute is used.

 
```
#![allow(unused)]
fn main() {
// Tells the rustfmt tool to not format the following element.
#[rustfmt::skip]
struct S {
}

// Controls the "cyclomatic complexity" threshold for the clippy tool.
#[clippy::cyclomatic_complexity = "100"]
pub fn f() {}
}
```
 
>  Note: `rustc` currently recognizes the tools "clippy" and "rustfmt".
> 
>  

 Built-in attributes index
-------------------------

 The following is an index of all built-in attributes.

 * Conditional compilation
	+ [`cfg`](conditional-compilation#the-cfg-attribute) — Controls conditional compilation.
	+ [`cfg_attr`](conditional-compilation#the-cfg_attr-attribute) — Conditionally includes attributes.
* Testing
	+ [`test`](attributes/testing#the-test-attribute) — Marks a function as a test.
	+ [`ignore`](attributes/testing#the-ignore-attribute) — Disables a test function.
	+ [`should_panic`](attributes/testing#the-should_panic-attribute) — Indicates a test should generate a panic.
* Derive
	+ [`derive`](attributes/derive) — Automatic trait implementations.
	+ [`automatically_derived`](attributes/derive#the-automatically_derived-attribute) — Marker for implementations created by `derive`.
* Macros
	+ [`macro_export`](macros-by-example#path-based-scope) — Exports a `macro_rules` macro for cross-crate usage.
	+ [`macro_use`](macros-by-example#the-macro_use-attribute) — Expands macro visibility, or imports macros from other crates.
	+ [`proc_macro`](procedural-macros#function-like-procedural-macros) — Defines a function-like macro.
	+ [`proc_macro_derive`](procedural-macros#derive-macros) — Defines a derive macro.
	+ [`proc_macro_attribute`](procedural-macros#attribute-macros) — Defines an attribute macro.
* Diagnostics
	+ [`allow`](attributes/diagnostics#lint-check-attributes), [`warn`](attributes/diagnostics#lint-check-attributes), [`deny`](attributes/diagnostics#lint-check-attributes), [`forbid`](attributes/diagnostics#lint-check-attributes) — Alters the default lint level.
	+ [`deprecated`](attributes/diagnostics#the-deprecated-attribute) — Generates deprecation notices.
	+ [`must_use`](attributes/diagnostics#the-must_use-attribute) — Generates a lint for unused values.
* ABI, linking, symbols, and FFI
	+ [`link`](items/external-blocks#the-link-attribute) — Specifies a native library to link with an `extern` block.
	+ [`link_name`](items/external-blocks#the-link_name-attribute) — Specifies the name of the symbol for functions or statics in an `extern` block.
	+ [`link_ordinal`](items/external-blocks#the-link_ordinal-attribute) — Specifies the ordinal of the symbol for functions or statics in an `extern` block.
	+ [`no_link`](items/extern-crates#the-no_link-attribute) — Prevents linking an extern crate.
	+ [`repr`](type-layout#representations) — Controls type layout.
	+ [`crate_type`](linkage) — Specifies the type of crate (library, executable, etc.).
	+ [`no_main`](crates-and-source-files#the-no_main-attribute) — Disables emitting the `main` symbol.
	+ [`export_name`](abi#the-export_name-attribute) — Specifies the exported symbol name for a function or static.
	+ [`link_section`](abi#the-link_section-attribute) — Specifies the section of an object file to use for a function or static.
	+ [`no_mangle`](abi#the-no_mangle-attribute) — Disables symbol name encoding.
	+ [`used`](abi#the-used-attribute) — Forces the compiler to keep a static item in the output object file.
	+ [`crate_name`](crates-and-source-files#the-crate_name-attribute) — Specifies the crate name.
* Code generation
	+ [`inline`](attributes/codegen#the-inline-attribute) — Hint to inline code.
	+ [`cold`](attributes/codegen#the-cold-attribute) — Hint that a function is unlikely to be called.
	+ [`no_builtins`](attributes/codegen#the-no_builtins-attribute) — Disables use of certain built-in functions.
	+ [`target_feature`](attributes/codegen#the-target_feature-attribute) — Configure platform-specific code generation.
	+ [`track_caller`](attributes/codegen#the-track_caller-attribute) - Pass the parent call location to `std::panic::Location::caller()`.
	+ [`instruction_set`](attributes/codegen#the-instruction_set-attribute) - Specify the instruction set used to generate a functions code
* Documentation
	+ `doc` — Specifies documentation. See [The Rustdoc Book](https://doc.rust-lang.org/rustdoc/the-doc-attribute.html) for more information. [Doc comments](comments#doc-comments) are transformed into `doc` attributes.
* Preludes
	+ [`no_std`](names/preludes#the-no_std-attribute) — Removes std from the prelude.
	+ [`no_implicit_prelude`](names/preludes#the-no_implicit_prelude-attribute) — Disables prelude lookups within a module.
* Modules
	+ [`path`](items/modules#the-path-attribute) — Specifies the filename for a module.
* Limits
	+ [`recursion_limit`](attributes/limits#the-recursion_limit-attribute) — Sets the maximum recursion limit for certain compile-time operations.
	+ [`type_length_limit`](attributes/limits#the-type_length_limit-attribute) — Sets the maximum size of a polymorphic type.
* Runtime
	+ [`panic_handler`](runtime#the-panic_handler-attribute) — Sets the function to handle panics.
	+ [`global_allocator`](runtime#the-global_allocator-attribute) — Sets the global memory allocator.
	+ [`windows_subsystem`](runtime#the-windows_subsystem-attribute) — Specifies the windows subsystem to link with.
* Features
	+ `feature` — Used to enable unstable or experimental compiler features. See [The Unstable Book](https://doc.rust-lang.org/unstable-book/index.html) for features implemented in `rustc`.
* Type System
	+ [`non_exhaustive`](attributes/type_system#the-non_exhaustive-attribute) — Indicate that a type will have more fields/variants added in future.
* Debugger
	+ [`debugger_visualizer`](attributes/debugger#the-debugger_visualizer-attribute) — Embeds a file that specifies debugger output for a type.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/attributes.html>

Module std::prelude
===================


The Rust Prelude
----------------

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

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

 Other preludes
--------------

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

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

 Prelude contents
----------------

 The first version of the prelude is used in Rust 2015 and Rust 2018, and lives in [`std::prelude::v1`](v1/index "mod std::prelude::v1"). [`std::prelude::rust_2015`](rust_2015/index "mod std::prelude::rust_2015") and [`std::prelude::rust_2018`](rust_2018/index "mod std::prelude::rust_2018") re-export this prelude. It re-exports the following:

 * `[std::marker](../marker/index "mod std::marker")::{[Copy](../marker/trait.copy "trait std::marker::Copy"), [Send](../marker/trait.send "trait std::marker::Send"), [Sized](../marker/trait.sized "trait std::marker::Sized"), [Sync](../marker/trait.sync "trait std::marker::Sync"), [Unpin](../marker/trait.unpin "trait std::marker::Unpin")}`, marker traits that indicate fundamental properties of types.
* `[std::ops](../ops/index "mod std::ops")::{[Drop](../ops/trait.drop "trait std::ops::Drop"), [Fn](../ops/trait.fn "trait std::ops::Fn"), [FnMut](../ops/trait.fnmut "trait std::ops::FnMut"), [FnOnce](../ops/trait.fnonce "trait std::ops::FnOnce")}`, various operations for both destructors and overloading `()`.
* `[std::mem](../mem/index "mod std::mem")::[drop](../mem/fn.drop "fn std::mem::drop")`, a convenience function for explicitly dropping a value.
* `[std::boxed](../boxed/index "mod std::boxed")::[Box](../boxed/struct.box "struct std::boxed::Box")`, a way to allocate values on the heap.
* `[std::borrow](../borrow/index "mod std::borrow")::[ToOwned](../borrow/trait.toowned "trait std::borrow::ToOwned")`, the conversion trait that defines [`to_owned`](../borrow/trait.toowned#tymethod.to_owned "method std::borrow::ToOwned::to_owned"), the generic method for creating an owned type from a borrowed type.
* `[std::clone](../clone/index "mod std::clone")::[Clone](../clone/trait.clone "trait std::clone::Clone")`, the ubiquitous trait that defines [`clone`](../clone/trait.clone#tymethod.clone "method std::clone::Clone::clone"), the method for producing a copy of a value.
* `[std::cmp](../cmp/index "mod std::cmp")::{[PartialEq](../cmp/trait.partialeq "trait std::cmp::PartialEq"), [PartialOrd](../cmp/trait.partialord "trait std::cmp::PartialOrd"), [Eq](../cmp/trait.eq "trait std::cmp::Eq"), [Ord](../cmp/trait.ord "trait std::cmp::Ord")}`, the comparison traits, which implement the comparison operators and are often seen in trait bounds.
* `[std::convert](../convert/index "mod std::convert")::{[AsRef](../convert/trait.asref "trait std::convert::AsRef"), [AsMut](../convert/trait.asmut "trait std::convert::AsMut"), [Into](../convert/trait.into "trait std::convert::Into"), [From](../convert/trait.from "trait std::convert::From")}`, generic conversions, used by savvy API authors to create overloaded methods.
* `[std::default](../default/index "mod std::default")::[Default](../default/trait.default "trait std::default::Default")`, types that have default values.
* `[std::iter](../iter/index "mod std::iter")::{[Iterator](../iter/trait.iterator "trait std::iter::Iterator"), [Extend](../iter/trait.extend "trait std::iter::Extend"), [IntoIterator](../iter/trait.intoiterator "trait std::iter::IntoIterator"), [DoubleEndedIterator](../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator"), [ExactSizeIterator](../iter/trait.exactsizeiterator "trait std::iter::ExactSizeIterator")}`, iterators of various kinds.
* `[std::option](../option/index "mod std::option")::[Option](../option/enum.option "enum std::option::Option")::{[self](../option/enum.option "enum std::option::Option"), [Some](../option/enum.option#variant.Some "variant std::option::Option::Some"), [None](../option/enum.option#variant.None "variant std::option::Option::None")}`, a type which expresses the presence or absence of a value. This type is so commonly used, its variants are also exported.
* `[std::result](../result/index "mod std::result")::[Result](../result/enum.result "enum std::result::Result")::{[self](../result/enum.result "enum std::result::Result"), [Ok](../result/enum.result#variant.Ok "variant std::result::Result::Ok"), [Err](../result/enum.result#variant.Err "variant std::result::Result::Err")}`, a type for functions that may succeed or fail. Like [`Option`](../option/enum.option "enum std::option::Option"), its variants are exported as well.
* `[std::string](../string/index "mod std::string")::{[String](../string/struct.string "struct std::string::String"), [ToString](../string/trait.tostring "trait std::string::ToString")}`, heap-allocated strings.
* `[std::vec](../vec/index "mod std::vec")::[Vec](../vec/struct.vec "struct std::vec::Vec")`, a growable, heap-allocated vector.

 The prelude used in Rust 2021, [`std::prelude::rust_2021`](rust_2021/index "mod std::prelude::rust_2021"), includes all of the above, and in addition re-exports:

 * `[std::convert](../convert/index "mod std::convert")::{[TryFrom](../convert/trait.tryfrom "trait std::convert::TryFrom"), [TryInto](../convert/trait.tryinto "trait std::convert::TryInto")}`,
* `[std::iter](../iter/index "mod std::iter")::[FromIterator](../iter/trait.fromiterator "trait std::iter::FromIterator")`.

 Modules
-------


* [rust\_2024](rust_2024/index "mod std::prelude::rust_2024")Experimental

The 2024 version of the prelude of The Rust Standard Library.
* [rust\_2015](rust_2015/index "mod std::prelude::rust_2015")
The 2015 version of the prelude of The Rust Standard Library.
* [rust\_2018](rust_2018/index "mod std::prelude::rust_2018")
The 2018 version of the prelude of The Rust Standard Library.
* [rust\_2021](rust_2021/index "mod std::prelude::rust_2021")
The 2021 version of the prelude of The Rust Standard Library.
* [v1](v1/index "mod std::prelude::v1")
The first version of the prelude of The Rust Standard Library.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/prelude/index.html>

Struct std::io::Stdin
=====================



```
pub struct Stdin { /* private fields */ }
```

A handle to the standard input stream of a process.

 Each handle is a shared reference to a global buffer of input data to this process. A handle can be `lock`’d to gain full access to [`BufRead`](trait.bufread "trait std::io::BufRead") methods (e.g., `.lines()`). Reads to this handle are otherwise locked with respect to other reads.

 This handle implements the `Read` trait, but beware that concurrent reads of `Stdin` must be executed with care.

 Created by the [`io::stdin`](fn.stdin "fn std::io::stdin") method.

 #### Note: Windows Portability Considerations

 When operating in a console, the Windows implementation of this stream does not support non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return an error.

 In a process with a detached console, such as one using `#![windows_subsystem = "windows"]`, or in a child process spawned from such a process, the contained handle will be null. In such cases, the standard library’s `Read` and `Write` will do nothing and silently succeed. All other I/O operations, via the standard library or via raw Windows API calls, will fail.

 Examples
--------

 
```
use std::io;

fn main() -> io::Result<()> {
    let mut buffer = String::new();
    let stdin = io::stdin(); // We get `Stdin` here.
    stdin.read_line(&mut buffer)?;
    Ok(())
}
```
 Implementations
---------------



[source](https://doc.rust-lang.org/src/std/io/stdio.rs.html#331-411)
```
impl Stdin
```

[source](https://doc.rust-lang.org/src/std/io/stdio.rs.html#354-358)
```
pub fn lock(&self) -> StdinLock<'static> ⓘ
```

Locks this handle to the standard input stream, returning a readable guard.

 The lock is released when the returned lock goes out of scope. The returned guard also implements the [`Read`](trait.read "trait std::io::Read") and [`BufRead`](trait.bufread "trait std::io::BufRead") traits for accessing the underlying data.

 ##### Examples

 
```
use std::io::{self, BufRead};

fn main() -> io::Result<()> {
    let mut buffer = String::new();
    let stdin = io::stdin();
    let mut handle = stdin.lock();

    handle.read_line(&mut buffer)?;
    Ok(())
}
```
 
[source](https://doc.rust-lang.org/src/std/io/stdio.rs.html#387-389)
```
pub fn read_line(&self, buf: &mut String) -> Result<usize>
```

Locks this handle and reads a line of input, appending it to the specified buffer.

 For detailed semantics of this method, see the documentation on [`BufRead::read_line`](trait.bufread#method.read_line "method std::io::BufRead::read_line").

 ##### Examples

 
```
use std::io;

let mut input = String::new();
match io::stdin().read_line(&mut input) {
    Ok(n) => {
        println!("{n} bytes read");
        println!("{input}");
    }
    Err(error) => println!("error: {error}"),
}
```
 You can run the example one of two ways:

 * Pipe some text to it, e.g., `printf foo | path/to/executable`
* Give it text interactively by running the executable directly, in which case it will wait for the Enter key to be pressed before continuing

 
[source](https://doc.rust-lang.org/src/std/io/stdio.rs.html#408-410)1.62.0
```
pub fn lines(self) -> Lines<StdinLock<'static>> ⓘ
```

Consumes this handle and returns an iterator over input lines.

 For detailed semantics of this method, see the documentation on [`BufRead::lines`](trait.bufread#method.lines "method std::io::BufRead::lines").

 ##### Examples

 
```
use std::io;

let lines = io::stdin().lines();
for line in lines {
    println!("got a line: {}", line.unwrap());
}
```
 


Trait Implementations
---------------------



[source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#419-424)1.63.0
```
impl AsFd for Stdin
```

[source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#421-423)
```
fn as_fd(&self) -> BorrowedFd<'_>
```
Borrows the file descriptor. [Read more](../os/fd/trait.asfd#tymethod.as_fd)


[source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#520-525)1.63.0
```
impl AsHandle for StdinAvailable on Windows only.
```

[source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#522-524)
```
fn as_handle(&self) -> BorrowedHandle<'_>
```
Borrows the handle. [Read more](../os/windows/io/trait.ashandle#tymethod.as_handle)


[source](https://doc.rust-lang.org/src/std/os/fd/raw.rs.html#187-192)1.21.0
```
impl AsRawFd for Stdin
```

[source](https://doc.rust-lang.org/src/std/os/fd/raw.rs.html#189-191)
```
fn as_raw_fd(&self) -> RawFd
```
Extracts the raw file descriptor. [Read more](../os/fd/trait.asrawfd#tymethod.as_raw_fd)


[source](https://doc.rust-lang.org/src/std/os/windows/io/raw.rs.html#104-108)1.21.0
```
impl AsRawHandle for StdinAvailable on Windows only.
```

[source](https://doc.rust-lang.org/src/std/os/windows/io/raw.rs.html#105-107)
```
fn as_raw_handle(&self) -> RawHandle
```
Extracts the raw handle. [Read more](../os/windows/io/trait.asrawhandle#tymethod.as_raw_handle)


[source](https://doc.rust-lang.org/src/std/io/stdio.rs.html#414-418)1.16.0
```
impl Debug for Stdin
```

[source](https://doc.rust-lang.org/src/std/io/stdio.rs.html#415-417)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result
```
Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt)


[source](https://doc.rust-lang.org/src/std/io/stdio.rs.html#1085)1.70.0
```
impl IsTerminal for Stdin
```

[source](https://doc.rust-lang.org/src/std/io/stdio.rs.html#1085)
```
fn is_terminal(&self) -> bool
```
Returns `true` if the descriptor/handle refers to a terminal/tty. [Read more](trait.isterminal#tymethod.is_terminal)


[source](https://doc.rust-lang.org/src/std/io/stdio.rs.html#421-444)
```
impl Read for Stdin
```

[source](https://doc.rust-lang.org/src/std/io/stdio.rs.html#422-424)
```
fn read(&mut self, buf: &mut [u8]) -> Result<usize>
```
Pull some bytes from this source into the specified buffer, returning how many bytes were read. [Read more](trait.read#tymethod.read)

[source](https://doc.rust-lang.org/src/std/io/stdio.rs.html#425-427)
```
fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<()>
```

🔬This is a nightly-only experimental API. (`read_buf` [#78485](https://github.com/rust-lang/rust/issues/78485))
Pull some bytes from this source into the specified buffer. [Read more](trait.read#method.read_buf)

[source](https://doc.rust-lang.org/src/std/io/stdio.rs.html#428-430)
```
fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
```
Like `read`, except that it reads into a slice of buffers. [Read more](trait.read#method.read_vectored)

[source](https://doc.rust-lang.org/src/std/io/stdio.rs.html#432-434)
```
fn is_read_vectored(&self) -> bool
```

🔬This is a nightly-only experimental API. (`can_vector` [#69941](https://github.com/rust-lang/rust/issues/69941))
Determines if this `Read`er has an efficient `read_vectored` implementation. [Read more](trait.read#method.is_read_vectored)

[source](https://doc.rust-lang.org/src/std/io/stdio.rs.html#435-437)
```
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize>
```
Read all bytes until EOF in this source, placing them into `buf`. [Read more](trait.read#method.read_to_end)

[source](https://doc.rust-lang.org/src/std/io/stdio.rs.html#438-440)
```
fn read_to_string(&mut self, buf: &mut String) -> Result<usize>
```
Read all bytes until EOF in this source, appending them to `buf`. [Read more](trait.read#method.read_to_string)

[source](https://doc.rust-lang.org/src/std/io/stdio.rs.html#441-443)
```
fn read_exact(&mut self, buf: &mut [u8]) -> Result<()>
```
Read the exact number of bytes required to fill `buf`. [Read more](trait.read#method.read_exact)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#858-873)
```
fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<()>
```

🔬This is a nightly-only experimental API. (`read_buf` [#78485](https://github.com/rust-lang/rust/issues/78485))
Read the exact number of bytes required to fill `cursor`. [Read more](trait.read#method.read_buf_exact)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#910-915)
```
fn by_ref(&mut self) -> &mut Self
where
    Self: Sized,
```
Creates a “by reference” adaptor for this instance of `Read`. [Read more](trait.read#method.by_ref)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#953-958)
```
fn bytes(self) -> Bytes<Self> ⓘ
where
    Self: Sized,
```
Transforms this `Read` instance to an [`Iterator`](../iter/trait.iterator "trait std::iter::Iterator") over its bytes. [Read more](trait.read#method.bytes)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#991-996)
```
fn chain<R: Read>(self, next: R) -> Chain<Self, R> ⓘ
where
    Self: Sized,
```
Creates an adapter which will chain this stream with another. [Read more](trait.read#method.chain)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1030-1035)
```
fn take(self, limit: u64) -> Take<Self> ⓘ
where
    Self: Sized,
```
Creates an adapter which will read at most `limit` bytes from it. [Read more](trait.read#method.take)



Auto Trait Implementations
--------------------------




```
impl RefUnwindSafe for Stdin
```

```
impl Send for Stdin
```

```
impl Sync for Stdin
```

```
impl Unpin for Stdin
```

```
impl UnwindSafe for Stdin
```


Blanket Implementations
-----------------------



[source](https://doc.rust-lang.org/src/core/any.rs.html#200)
```
impl<T> Any for T
where
    T: 'static + ?Sized,
```

[source](https://doc.rust-lang.org/src/core/any.rs.html#201)
```
fn type_id(&self) -> TypeId
```
Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#208)
```
impl<T> Borrow<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#210)
```
fn borrow(&self) -> &T
```
Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#216)
```
impl<T> BorrowMut<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#217)
```
fn borrow_mut(&mut self) -> &mut T
```
Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#723)
```
impl<T> From<T> for T
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#726)
```
fn from(t: T) -> T
```

Returns the argument unchanged.

 

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#707)
```
impl<T, U> Into<U> for T
where
    U: From<T>,
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#716)
```
fn into(self) -> U
```

Calls `U::from(self)`.

 That is, this conversion is whatever the implementation of `[From](../convert/trait.from "trait std::convert::From")<T> for U` chooses to do.

 

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#763)
```
impl<T, U> TryFrom<U> for T
where
    U: Into<T>,
```


```
type Error = Infallible
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#770)
```
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#748)
```
impl<T, U> TryInto<U> for T
where
    U: TryFrom<T>,
```


```
type Error = <U as TryFrom<T>>::Error
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#755)
```
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
```
Performs the conversion.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/io/struct.Stdin.html>

Struct std::string::String
==========================



```
pub struct String { /* private fields */ }
```

A UTF-8–encoded, growable string.

 The `String` type is the most common string type that has ownership over the contents of the string. It has a close relationship with its borrowed counterpart, the primitive [`str`](../primitive.str "str").

 Examples
--------

 You can create a `String` from [a literal string](../primitive.str "&str") with [`String::from`](../convert/trait.from#tymethod.from "associated function std::convert::From::from"):

 
```
let hello = String::from("Hello, world!");
```
 You can append a [`char`](../primitive.char "primitive char") to a `String` with the [`push`](struct.string#method.push "method std::string::String::push") method, and append a [`&str`](../primitive.str "&str") with the [`push_str`](struct.string#method.push_str "method std::string::String::push_str") method:

 
```
let mut hello = String::from("Hello, ");

hello.push('w');
hello.push_str("orld!");
```
 If you have a vector of UTF-8 bytes, you can create a `String` from it with the [`from_utf8`](struct.string#method.from_utf8 "associated function std::string::String::from_utf8") method:

 
```
// some bytes, in a vector
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);
```
 UTF-8
-----

 `String`s are always valid UTF-8. If you need a non-UTF-8 string, consider [`OsString`](../ffi/struct.osstring "ffi::OsString"). It is similar, but without the UTF-8 constraint. Because UTF-8 is a variable width encoding, `String`s are typically smaller than an array of the same `chars`:

 
```
use std::mem;

// `s` is ASCII which represents each `char` as one byte
let s = "hello";
assert_eq!(s.len(), 5);

// A `char` array with the same contents would be longer because
// every `char` is four bytes
let s = ['h', 'e', 'l', 'l', 'o'];
let size: usize = s.into_iter().map(|c| mem::size_of_val(&c)).sum();
assert_eq!(size, 20);

// However, for non-ASCII strings, the difference will be smaller
// and sometimes they are the same
let s = "💖💖💖💖💖";
assert_eq!(s.len(), 20);

let s = ['💖', '💖', '💖', '💖', '💖'];
let size: usize = s.into_iter().map(|c| mem::size_of_val(&c)).sum();
assert_eq!(size, 20);
```
 This raises interesting questions as to how `s[i]` should work. What should `i` be here? Several options include byte indices and `char` indices but, because of UTF-8 encoding, only byte indices would provide constant time indexing. Getting the `i`th `char`, for example, is available using [`chars`](../primitive.str#method.chars "method str::chars"):

 
```
let s = "hello";
let third_character = s.chars().nth(2);
assert_eq!(third_character, Some('l'));

let s = "💖💖💖💖💖";
let third_character = s.chars().nth(2);
assert_eq!(third_character, Some('💖'));
```
 Next, what should `s[i]` return? Because indexing returns a reference to underlying data it could be `&u8`, `&[u8]`, or something else similar. Since we’re only providing one index, `&u8` makes the most sense but that might not be what the user expects and can be explicitly achieved with [`as_bytes()`](../primitive.str#method.as_bytes "method str::as_bytes"):

 
```
// The first byte is 104 - the byte value of `'h'`
let s = "hello";
assert_eq!(s.as_bytes()[0], 104);
// or
assert_eq!(s.as_bytes()[0], b'h');

// The first byte is 240 which isn't obviously useful
let s = "💖💖💖💖💖";
assert_eq!(s.as_bytes()[0], 240);
```
 Due to these ambiguities/restrictions, indexing with a `usize` is simply forbidden:

 ⓘ
```
let s = "hello";

// The following will not compile!
println!("The first letter of s is {}", s[0]);
```

 It is more clear, however, how `&s[i..j]` should work (that is, indexing with a range). It should accept byte indices (to be constant-time) and return a `&str` which is UTF-8 encoded. This is also called “string slicing”. Note this will panic if the byte indices provided are not character boundaries - see [`is_char_boundary`](../primitive.str#method.is_char_boundary "method str::is_char_boundary") for more details. See the implementations for [`SliceIndex<str>`](../slice/trait.sliceindex "trait std::slice::SliceIndex") for more details on string slicing. For a non-panicking version of string slicing, see [`get`](../primitive.str#method.get "method str::get").

 The [`bytes`](../primitive.str#method.bytes "method str::bytes") and [`chars`](../primitive.str#method.chars "method str::chars") methods return iterators over the bytes and codepoints of the string, respectively. To iterate over codepoints along with byte indices, use [`char_indices`](../primitive.str#method.char_indices "method str::char_indices").

 Deref
-----

 `String` implements `[Deref](../ops/trait.deref "ops::Deref")<Target = [str](../primitive.str "str")>`, and so inherits all of [`str`](../primitive.str "str")’s methods. In addition, this means that you can pass a `String` to a function which takes a [`&str`](../primitive.str "&str") by using an ampersand (`&`):

 
```
fn takes_str(s: &str) { }

let s = String::from("Hello");

takes_str(&s);
```
 This will create a [`&str`](../primitive.str "&str") from the `String` and pass it in. This conversion is very inexpensive, and so generally, functions will accept [`&str`](../primitive.str "&str")s as arguments unless they need a `String` for some specific reason.

 In certain cases Rust doesn’t have enough information to make this conversion, known as [`Deref`](../ops/trait.deref "ops::Deref") coercion. In the following example a string slice [`&'a str`](../primitive.str "&str") implements the trait `TraitExample`, and the function `example_func` takes anything that implements the trait. In this case Rust would need to make two implicit conversions, which Rust doesn’t have the means to do. For that reason, the following example will not compile.

 ⓘ
```
trait TraitExample {}

impl<'a> TraitExample for &'a str {}

fn example_func<A: TraitExample>(example_arg: A) {}

let example_string = String::from("example_string");
example_func(&example_string);
```

 There are two options that would work instead. The first would be to change the line `example_func(&example_string);` to `example_func(example_string.as_str());`, using the method [`as_str()`](struct.string#method.as_str "method std::string::String::as_str") to explicitly extract the string slice containing the string. The second way changes `example_func(&example_string);` to `example_func(&*example_string);`. In this case we are dereferencing a `String` to a [`str`](../primitive.str "str"), then referencing the [`str`](../primitive.str "str") back to [`&str`](../primitive.str "&str"). The second way is more idiomatic, however both work to do the conversion explicitly rather than relying on the implicit conversion.

 Representation
--------------

 A `String` is made up of three components: a pointer to some bytes, a length, and a capacity. The pointer points to an internal buffer `String` uses to store its data. The length is the number of bytes currently stored in the buffer, and the capacity is the size of the buffer in bytes. As such, the length will always be less than or equal to the capacity.

 This buffer is always stored on the heap.

 You can look at these with the [`as_ptr`](../primitive.str#method.as_ptr "method str::as_ptr"), [`len`](struct.string#method.len "method std::string::String::len"), and [`capacity`](struct.string#method.capacity "method std::string::String::capacity") methods:

 
```
use std::mem;

let story = String::from("Once upon a time...");

// Prevent automatically dropping the String's data
let mut story = mem::ManuallyDrop::new(story);

let ptr = story.as_mut_ptr();
let len = story.len();
let capacity = story.capacity();

// story has nineteen bytes
assert_eq!(19, len);

// We can re-build a String out of ptr, len, and capacity. This is all
// unsafe because we are responsible for making sure the components are
// valid:
let s = unsafe { String::from_raw_parts(ptr, len, capacity) } ;

assert_eq!(String::from("Once upon a time..."), s);
```
 If a `String` has enough capacity, adding elements to it will not re-allocate. For example, consider this program:

 
```
let mut s = String::new();

println!("{}", s.capacity());

for _ in 0..5 {
    s.push_str("hello");
    println!("{}", s.capacity());
}
```
 This will output the following:

 
```
0
8
16
16
32
32

```
 At first, we have no memory allocated at all, but as we append to the string, it increases its capacity appropriately. If we instead use the [`with_capacity`](struct.string#method.with_capacity "associated function std::string::String::with_capacity") method to allocate the correct capacity initially:

 
```
let mut s = String::with_capacity(25);

println!("{}", s.capacity());

for _ in 0..5 {
    s.push_str("hello");
    println!("{}", s.capacity());
}
```
 We end up with a different output:

 
```
25
25
25
25
25
25

```
 Here, there’s no need to allocate more memory inside the loop.

 Implementations
---------------



[source](https://doc.rust-lang.org/src/alloc/string.rs.html#430)
```
impl String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#453)const: 1.39.0
```
pub const fn new() -> String
```

Creates a new empty `String`.

 Given that the `String` is empty, this will not allocate any initial buffer. While that means that this initial operation is very inexpensive, it may cause excessive allocation later when you add data. If you have an idea of how much data the `String` will hold, consider the [`with_capacity`](struct.string#method.with_capacity "associated function std::string::String::with_capacity") method to prevent excessive re-allocation.

 ##### Examples

 Basic usage:

 
```
let s = String::new();
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#498)
```
pub fn with_capacity(capacity: usize) -> String
```

Creates a new empty `String` with at least the specified capacity.

 `String`s have an internal buffer to hold their data. The capacity is the length of that buffer, and can be queried with the [`capacity`](struct.string#method.capacity "method std::string::String::capacity") method. This method creates an empty `String`, but one with an initial buffer that can hold at least `capacity` bytes. This is useful when you may be appending a bunch of data to the `String`, reducing the number of reallocations it needs to do.

 If the given capacity is `0`, no allocation will occur, and this method is identical to the [`new`](struct.string#method.new "associated function std::string::String::new") method.

 ##### Examples

 Basic usage:

 
```
let mut s = String::with_capacity(10);

// The String contains no chars, even though it has capacity for more
assert_eq!(s.len(), 0);

// These are all done without reallocating...
let cap = s.capacity();
for _ in 0..10 {
    s.push('a');
}

assert_eq!(s.capacity(), cap);

// ...but this may make the string reallocate
s.push('a');
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#570)
```
pub fn from_utf8(vec: Vec<u8, Global>) -> Result<String, FromUtf8Error>
```

Converts a vector of bytes to a `String`.

 A string ([`String`](struct.string "struct std::string::String")) is made of bytes ([`u8`](../primitive.u8 "primitive u8")), and a vector of bytes ([`Vec<u8>`](../vec/struct.vec "Vec")) is made of bytes, so this function converts between the two. Not all byte slices are valid `String`s, however: `String` requires that it is valid UTF-8. `from_utf8()` checks to ensure that the bytes are valid UTF-8, and then does the conversion.

 If you are sure that the byte slice is valid UTF-8, and you don’t want to incur the overhead of the validity check, there is an unsafe version of this function, [`from_utf8_unchecked`](struct.string#method.from_utf8_unchecked "associated function std::string::String::from_utf8_unchecked"), which has the same behavior but skips the check.

 This method will take care to not copy the vector, for efficiency’s sake.

 If you need a [`&str`](../primitive.str "&str") instead of a `String`, consider [`str::from_utf8`](../str/fn.from_utf8 "fn std::str::from_utf8").

 The inverse of this method is [`into_bytes`](struct.string#method.into_bytes "method std::string::String::into_bytes").

 ##### Errors

 Returns [`Err`](../result/enum.result#variant.Err "variant std::result::Result::Err") if the slice is not UTF-8 with a description as to why the provided bytes are not UTF-8. The vector you moved in is also included.

 ##### Examples

 Basic usage:

 
```
// some bytes, in a vector
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);
```
 Incorrect bytes:

 
```
// some invalid bytes, in a vector
let sparkle_heart = vec![0, 159, 146, 150];

assert!(String::from_utf8(sparkle_heart).is_err());
```
 See the docs for [`FromUtf8Error`](struct.fromutf8error "struct std::string::FromUtf8Error") for more details on what you can do with this error.

 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#629)
```
pub fn from_utf8_lossy(v: &[u8]) -> Cow<'_, str>
```

Converts a slice of bytes to a string, including invalid characters.

 Strings are made of bytes ([`u8`](../primitive.u8 "primitive u8")), and a slice of bytes ([`&[u8]`](../primitive.slice "primitive slice")) is made of bytes, so this function converts between the two. Not all byte slices are valid strings, however: strings are required to be valid UTF-8. During this conversion, `from_utf8_lossy()` will replace any invalid UTF-8 sequences with [`U+FFFD REPLACEMENT CHARACTER`](../char/constant.replacement_character "constant std::char::REPLACEMENT_CHARACTER"), which looks like this: �

 If you are sure that the byte slice is valid UTF-8, and you don’t want to incur the overhead of the conversion, there is an unsafe version of this function, [`from_utf8_unchecked`](struct.string#method.from_utf8_unchecked "associated function std::string::String::from_utf8_unchecked"), which has the same behavior but skips the checks.

 This function returns a [`Cow<'a, str>`](../borrow/enum.cow "borrow::Cow"). If our byte slice is invalid UTF-8, then we need to insert the replacement characters, which will change the size of the string, and hence, require a `String`. But if it’s already valid UTF-8, we don’t need a new allocation. This return type allows us to handle both cases.

 ##### Examples

 Basic usage:

 
```
// some bytes, in a vector
let sparkle_heart = vec![240, 159, 146, 150];

let sparkle_heart = String::from_utf8_lossy(&sparkle_heart);

assert_eq!("💖", sparkle_heart);
```
 Incorrect bytes:

 
```
// some invalid bytes
let input = b"Hello \xF0\x90\x80World";
let output = String::from_utf8_lossy(input);

assert_eq!("Hello �World", output);
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#680)
```
pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error>
```

Decode a UTF-16–encoded vector `v` into a `String`, returning [`Err`](../result/enum.result#variant.Err "variant std::result::Result::Err") if `v` contains any invalid data.

 ##### Examples

 Basic usage:

 
```
// 𝄞music
let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
          0x0073, 0x0069, 0x0063];
assert_eq!(String::from("𝄞music"),
           String::from_utf16(v).unwrap());

// 𝄞mu<invalid>ic
let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
          0xD800, 0x0069, 0x0063];
assert!(String::from_utf16(v).is_err());
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#722)
```
pub fn from_utf16_lossy(v: &[u16]) -> String
```

Decode a UTF-16–encoded slice `v` into a `String`, replacing invalid data with [the replacement character (`U+FFFD`)](../char/constant.replacement_character "constant std::char::REPLACEMENT_CHARACTER").

 Unlike [`from_utf8_lossy`](struct.string#method.from_utf8_lossy "associated function std::string::String::from_utf8_lossy") which returns a [`Cow<'a, str>`](../borrow/enum.cow "borrow::Cow"), `from_utf16_lossy` returns a `String` since the UTF-16 to UTF-8 conversion requires a memory allocation.

 ##### Examples

 Basic usage:

 
```
// 𝄞mus<invalid>ic<invalid>
let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
          0x0073, 0xDD1E, 0x0069, 0x0063,
          0xD834];

assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
           String::from_utf16_lossy(v));
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#756)
```
pub fn into_raw_parts(self) -> (*mut u8, usize, usize)
```

🔬This is a nightly-only experimental API. (`vec_into_raw_parts` [#65816](https://github.com/rust-lang/rust/issues/65816))

Decomposes a `String` into its raw components.

 Returns the raw pointer to the underlying data, the length of the string (in bytes), and the allocated capacity of the data (in bytes). These are the same arguments in the same order as the arguments to [`from_raw_parts`](struct.string#method.from_raw_parts "associated function std::string::String::from_raw_parts").

 After calling this function, the caller is responsible for the memory previously managed by the `String`. The only way to do this is to convert the raw pointer, length, and capacity back into a `String` with the [`from_raw_parts`](struct.string#method.from_raw_parts "associated function std::string::String::from_raw_parts") function, allowing the destructor to perform the cleanup.

 ##### Examples

 
```
#![feature(vec_into_raw_parts)]
let s = String::from("hello");

let (ptr, len, cap) = s.into_raw_parts();

let rebuilt = unsafe { String::from_raw_parts(ptr, len, cap) };
assert_eq!(rebuilt, "hello");
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#810)
```
pub unsafe fn from_raw_parts(
    buf: *mut u8,
    length: usize,
    capacity: usize
) -> String
```

Creates a new `String` from a length, capacity, and pointer.

 ##### Safety

 This is highly unsafe, due to the number of invariants that aren’t checked:

 * The memory at `buf` needs to have been previously allocated by the same allocator the standard library uses, with a required alignment of exactly 1.
* `length` needs to be less than or equal to `capacity`.
* `capacity` needs to be the correct value.
* The first `length` bytes at `buf` need to be valid UTF-8.

 Violating these may cause problems like corrupting the allocator’s internal data structures. For example, it is normally **not** safe to build a `String` from a pointer to a C `char` array containing UTF-8 *unless* you are certain that array was originally allocated by the Rust standard library’s allocator.

 The ownership of `buf` is effectively transferred to the `String` which may then deallocate, reallocate or change the contents of memory pointed to by the pointer at will. Ensure that nothing else uses the pointer after calling this function.

 ##### Examples

 Basic usage:

 
```
use std::mem;

unsafe {
    let s = String::from("hello");

    // Prevent automatically dropping the String's data
    let mut s = mem::ManuallyDrop::new(s);

    let ptr = s.as_mut_ptr();
    let len = s.len();
    let capacity = s.capacity();

    let s = String::from_raw_parts(ptr, len, capacity);

    assert_eq!(String::from("hello"), s);
}
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#845)
```
pub unsafe fn from_utf8_unchecked(bytes: Vec<u8, Global>) -> String
```

Converts a vector of bytes to a `String` without checking that the string contains valid UTF-8.

 See the safe version, [`from_utf8`](struct.string#method.from_utf8 "associated function std::string::String::from_utf8"), for more details.

 ##### Safety

 This function is unsafe because it does not check that the bytes passed to it are valid UTF-8. If this constraint is violated, it may cause memory unsafety issues with future users of the `String`, as the rest of the standard library assumes that `String`s are valid UTF-8.

 ##### Examples

 Basic usage:

 
```
// some bytes, in a vector
let sparkle_heart = vec![240, 159, 146, 150];

let sparkle_heart = unsafe {
    String::from_utf8_unchecked(sparkle_heart)
};

assert_eq!("💖", sparkle_heart);
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#866)
```
pub fn into_bytes(self) -> Vec<u8, Global> ⓘ
```

Converts a `String` into a byte vector.

 This consumes the `String`, so we do not need to copy its contents.

 ##### Examples

 Basic usage:

 
```
let s = String::from("hello");
let bytes = s.into_bytes();

assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#884)1.7.0
```
pub fn as_str(&self) -> &str
```

Extracts a string slice containing the entire `String`.

 ##### Examples

 Basic usage:

 
```
let s = String::from("foo");

assert_eq!("foo", s.as_str());
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#905)1.7.0
```
pub fn as_mut_str(&mut self) -> &mut str
```

Converts a `String` into a mutable string slice.

 ##### Examples

 Basic usage:

 
```
let mut s = String::from("foobar");
let s_mut_str = s.as_mut_str();

s_mut_str.make_ascii_uppercase();

assert_eq!("FOOBAR", s_mut_str);
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#925)
```
pub fn push_str(&mut self, string: &str)
```

Appends a given string slice onto the end of this `String`.

 ##### Examples

 Basic usage:

 
```
let mut s = String::from("foo");

s.push_str("bar");

assert_eq!("foobar", s);
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#953-955)
```
pub fn extend_from_within<R>(&mut self, src: R)
where
    R: RangeBounds<usize>,
```

🔬This is a nightly-only experimental API. (`string_extend_from_within` [#103806](https://github.com/rust-lang/rust/issues/103806))

Copies elements from `src` range to the end of the string.

 ##### Panics

 Panics if the starting point or end point do not lie on a [`char`](../primitive.char "primitive char") boundary, or if they’re out of bounds.

 ##### Examples

 
```
#![feature(string_extend_from_within)]
let mut string = String::from("abcde");

string.extend_from_within(2..);
assert_eq!(string, "abcdecde");

string.extend_from_within(..2);
assert_eq!(string, "abcdecdeab");

string.extend_from_within(4..8);
assert_eq!(string, "abcdecdeabecde");
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#979)
```
pub fn capacity(&self) -> usize
```

Returns this `String`’s capacity, in bytes.

 ##### Examples

 Basic usage:

 
```
let s = String::with_capacity(10);

assert!(s.capacity() >= 10);
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#1026)
```
pub fn reserve(&mut self, additional: usize)
```

Reserves capacity for at least `additional` bytes 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.

 ##### Panics

 Panics if the new capacity overflows [`usize`](../primitive.usize "primitive usize").

 ##### Examples

 Basic usage:

 
```
let mut s = String::new();

s.reserve(10);

assert!(s.capacity() >= 10);
```
 This might not actually increase the capacity:

 
```
let mut s = String::with_capacity(10);
s.push('a');
s.push('b');

// s now has a length of 2 and a capacity of at least 10
let capacity = s.capacity();
assert_eq!(2, s.len());
assert!(capacity >= 10);

// Since we already have at least an extra 8 capacity, calling this...
s.reserve(8);

// ... doesn't actually increase.
assert_eq!(capacity, s.capacity());
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#1076)
```
pub fn reserve_exact(&mut self, additional: usize)
```

Reserves the minimum capacity for at least `additional` bytes more than the current length. Unlike [`reserve`](struct.string#method.reserve "method std::string::String::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.

 ##### Panics

 Panics if the new capacity overflows [`usize`](../primitive.usize "primitive usize").

 ##### Examples

 Basic usage:

 
```
let mut s = String::new();

s.reserve_exact(10);

assert!(s.capacity() >= 10);
```
 This might not actually increase the capacity:

 
```
let mut s = String::with_capacity(10);
s.push('a');
s.push('b');

// s now has a length of 2 and a capacity of at least 10
let capacity = s.capacity();
assert_eq!(2, s.len());
assert!(capacity >= 10);

// Since we already have at least an extra 8 capacity, calling this...
s.reserve_exact(8);

// ... doesn't actually increase.
assert_eq!(capacity, s.capacity());
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#1111)1.57.0
```
pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>
```

Tries to reserve capacity for at least `additional` bytes 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.

 ##### Errors

 If the capacity overflows, or the allocator reports a failure, then an error is returned.

 ##### Examples

 
```
use std::collections::TryReserveError;

fn process_data(data: &str) -> Result<String, TryReserveError> {
    let mut output = String::new();

    // Pre-reserve the memory, exiting if we can't
    output.try_reserve(data.len())?;

    // Now we know this can't OOM in the middle of our complex work
    output.push_str(data);

    Ok(output)
}
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#1152)1.57.0
```
pub fn try_reserve_exact(
    &mut self,
    additional: usize
) -> Result<(), TryReserveError>
```

Tries to reserve the minimum capacity for at least `additional` bytes more than the current length. Unlike [`try_reserve`](struct.string#method.try_reserve "method std::string::String::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`](struct.string#method.try_reserve "method std::string::String::try_reserve") if future insertions are expected.

 ##### Errors

 If the capacity overflows, or the allocator reports a failure, then an error is returned.

 ##### Examples

 
```
use std::collections::TryReserveError;

fn process_data(data: &str) -> Result<String, TryReserveError> {
    let mut output = String::new();

    // Pre-reserve the memory, exiting if we can't
    output.try_reserve_exact(data.len())?;

    // Now we know this can't OOM in the middle of our complex work
    output.push_str(data);

    Ok(output)
}
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#1174)
```
pub fn shrink_to_fit(&mut self)
```

Shrinks the capacity of this `String` to match its length.

 ##### Examples

 Basic usage:

 
```
let mut s = String::from("foo");

s.reserve(100);
assert!(s.capacity() >= 100);

s.shrink_to_fit();
assert_eq!(3, s.capacity());
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#1201)1.56.0
```
pub fn shrink_to(&mut self, min_capacity: usize)
```

Shrinks the capacity of this `String` 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.

 ##### Examples

 
```
let mut s = String::from("foo");

s.reserve(100);
assert!(s.capacity() >= 100);

s.shrink_to(10);
assert!(s.capacity() >= 10);
s.shrink_to(0);
assert!(s.capacity() >= 3);
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#1223)
```
pub fn push(&mut self, ch: char)
```

Appends the given [`char`](../primitive.char "primitive char") to the end of this `String`.

 ##### Examples

 Basic usage:

 
```
let mut s = String::from("abc");

s.push('1');
s.push('2');
s.push('3');

assert_eq!("abc123", s);
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#1248)
```
pub fn as_bytes(&self) -> &[u8] ⓘ
```

Returns a byte slice of this `String`’s contents.

 The inverse of this method is [`from_utf8`](struct.string#method.from_utf8 "associated function std::string::String::from_utf8").

 ##### Examples

 Basic usage:

 
```
let s = String::from("hello");

assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#1277)
```
pub fn truncate(&mut self, new_len: usize)
```

Shortens this `String` to the specified length.

 If `new_len` is greater than the string’s current length, this has no effect.

 Note that this method has no effect on the allocated capacity of the string

 ##### Panics

 Panics if `new_len` does not lie on a [`char`](../primitive.char "primitive char") boundary.

 ##### Examples

 Basic usage:

 
```
let mut s = String::from("hello");

s.truncate(2);

assert_eq!("he", s);
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#1303)
```
pub fn pop(&mut self) -> Option<char>
```

Removes the last character from the string buffer and returns it.

 Returns [`None`](../option/enum.option#variant.None "variant std::option::Option::None") if this `String` is empty.

 ##### Examples

 Basic usage:

 
```
let mut s = String::from("foo");

assert_eq!(s.pop(), Some('o'));
assert_eq!(s.pop(), Some('o'));
assert_eq!(s.pop(), Some('f'));

assert_eq!(s.pop(), None);
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#1335)
```
pub fn remove(&mut self, idx: usize) -> char
```

Removes a [`char`](../primitive.char "primitive char") from this `String` at a byte position and returns it.

 This is an *O*(*n*) operation, as it requires copying every element in the buffer.

 ##### Panics

 Panics if `idx` is larger than or equal to the `String`’s length, or if it does not lie on a [`char`](../primitive.char "primitive char") boundary.

 ##### Examples

 Basic usage:

 
```
let mut s = String::from("foo");

assert_eq!(s.remove(0), 'f');
assert_eq!(s.remove(1), 'o');
assert_eq!(s.remove(0), 'o');
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#1372-1374)
```
pub fn remove_matches<P, 'a>(&'a mut self, pat: P)
where
    P: for<'x> Pattern<'x>,
```

🔬This is a nightly-only experimental API. (`string_remove_matches` [#72826](https://github.com/rust-lang/rust/issues/72826))

Remove all matches of pattern `pat` in the `String`.

 ##### Examples

 
```
#![feature(string_remove_matches)]
let mut s = String::from("Trees are not green, the sky is not blue.");
s.remove_matches("not ");
assert_eq!("Trees are green, the sky is blue.", s);
```
 Matches will be detected and removed iteratively, so in cases where patterns overlap, only the first pattern will be removed:

 
```
#![feature(string_remove_matches)]
let mut s = String::from("banana");
s.remove_matches("ana");
assert_eq!("bna", s);
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#1452-1454)1.26.0
```
pub fn retain<F>(&mut self, f: F)
where
    F: FnMut(char) -> bool,
```

Retains only the characters specified by the predicate.

 In other words, remove all characters `c` such that `f(c)` returns `false`. This method operates in place, visiting each character exactly once in the original order, and preserves the order of the retained characters.

 ##### Examples

 
```
let mut s = String::from("f_o_ob_ar");

s.retain(|c| c != '_');

assert_eq!(s, "foobar");
```
 Because the elements are visited exactly once in the original order, external state may be used to decide which elements to keep.

 
```
let mut s = String::from("abcde");
let keep = [false, true, true, false, true];
let mut iter = keep.iter();
s.retain(|_| *iter.next().unwrap());
assert_eq!(s, "bce");
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#1531)
```
pub fn insert(&mut self, idx: usize, ch: char)
```

Inserts a character into this `String` at a byte position.

 This is an *O*(*n*) operation as it requires copying every element in the buffer.

 ##### Panics

 Panics if `idx` is larger than the `String`’s length, or if it does not lie on a [`char`](../primitive.char "primitive char") boundary.

 ##### Examples

 Basic usage:

 
```
let mut s = String::with_capacity(3);

s.insert(0, 'f');
s.insert(1, 'o');
s.insert(2, 'o');

assert_eq!("foo", s);
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#1578)1.16.0
```
pub fn insert_str(&mut self, idx: usize, string: &str)
```

Inserts a string slice into this `String` at a byte position.

 This is an *O*(*n*) operation as it requires copying every element in the buffer.

 ##### Panics

 Panics if `idx` is larger than the `String`’s length, or if it does not lie on a [`char`](../primitive.char "primitive char") boundary.

 ##### Examples

 Basic usage:

 
```
let mut s = String::from("bar");

s.insert_str(0, "foo");

assert_eq!("foobar", s);
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#1613)
```
pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8, Global> ⓘ
```

Returns a mutable reference to the contents of this `String`.

 ##### Safety

 This function is unsafe because the returned `&mut Vec` allows writing bytes which are not valid UTF-8. If this constraint is violated, using the original `String` after dropping the `&mut Vec` may violate memory safety, as the rest of the standard library assumes that `String`s are valid UTF-8.

 ##### Examples

 Basic usage:

 
```
let mut s = String::from("hello");

unsafe {
    let vec = s.as_mut_vec();
    assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);

    vec.reverse();
}
assert_eq!(s, "olleh");
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#1636)
```
pub fn len(&self) -> usize
```

Returns the length of this `String`, in bytes, not [`char`](../primitive.char "primitive char")s or graphemes. In other words, it might not be what a human considers the length of the string.

 ##### Examples

 Basic usage:

 
```
let a = String::from("foo");
assert_eq!(a.len(), 3);

let fancy_f = String::from("ƒoo");
assert_eq!(fancy_f.len(), 4);
assert_eq!(fancy_f.chars().count(), 3);
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#1656)
```
pub fn is_empty(&self) -> bool
```

Returns `true` if this `String` has a length of zero, and `false` otherwise.

 ##### Examples

 Basic usage:

 
```
let mut v = String::new();
assert!(v.is_empty());

v.push('a');
assert!(!v.is_empty());
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#1687)1.16.0
```
pub fn split_off(&mut self, at: usize) -> String
```

Splits the string into two at the given byte index.

 Returns a newly allocated `String`. `self` contains bytes `[0, at)`, and the returned `String` contains bytes `[at, len)`. `at` must be on the boundary of a UTF-8 code point.

 Note that the capacity of `self` does not change.

 ##### Panics

 Panics if `at` is not on a `UTF-8` code point boundary, or if it is beyond the last code point of the string.

 ##### Examples

 
```
let mut hello = String::from("Hello, World!");
let world = hello.split_off(7);
assert_eq!(hello, "Hello, ");
assert_eq!(world, "World!");
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#1713)
```
pub fn clear(&mut self)
```

Truncates this `String`, removing all contents.

 While this means the `String` will have a length of zero, it does not touch its capacity.

 ##### Examples

 Basic usage:

 
```
let mut s = String::from("foo");

s.clear();

assert!(s.is_empty());
assert_eq!(0, s.len());
assert_eq!(3, s.capacity());
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#1753-1755)1.6.0
```
pub fn drain<R>(&mut self, range: R) -> Drain<'_> ⓘ
where
    R: RangeBounds<usize>,
```

Removes the specified range from the string in bulk, returning all removed characters as an iterator.

 The returned iterator keeps a mutable borrow on the string to optimize its implementation.

 ##### Panics

 Panics if the starting point or end point do not lie on a [`char`](../primitive.char "primitive char") boundary, or if they’re out of bounds.

 ##### Leaking

 If the returned iterator goes out of scope without being dropped (due to [`core::mem::forget`](../mem/fn.forget "fn std::mem::forget"), for example), the string may still contain a copy of any drained characters, or may have lost characters arbitrarily, including characters outside the range.

 ##### Examples

 Basic usage:

 
```
let mut s = String::from("α is alpha, β is beta");
let beta_offset = s.find('β').unwrap_or(s.len());

// Remove the range up until the β from the string
let t: String = s.drain(..beta_offset).collect();
assert_eq!(t, "α is alpha, ");
assert_eq!(s, "β is beta");

// A full range clears the string, like `clear()` does
s.drain(..);
assert_eq!(s, "");
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#1799-1801)1.27.0
```
pub fn replace_range<R>(&mut self, range: R, replace_with: &str)
where
    R: RangeBounds<usize>,
```

Removes the specified range in the string, and replaces it with the given string. The given string doesn’t need to be the same length as the range.

 ##### Panics

 Panics if the starting point or end point do not lie on a [`char`](../primitive.char "primitive char") boundary, or if they’re out of bounds.

 ##### Examples

 Basic usage:

 
```
let mut s = String::from("α is alpha, β is beta");
let beta_offset = s.find('β').unwrap_or(s.len());

// Replace the range up until the β from the string
s.replace_range(..beta_offset, "Α is capital alpha; ");
assert_eq!(s, "Α is capital alpha; β is beta");
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#1848)1.4.0
```
pub fn into_boxed_str(self) -> Box<str, Global>
```

Converts this `String` into a `[Box](../boxed/struct.box "struct std::boxed::Box")<[str](../primitive.str "str")>`.

 This will drop any excess capacity.

 ##### Examples

 Basic usage:

 
```
let s = String::from("hello");

let b = s.into_boxed_str();
```
 
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#1877)
```
pub fn leak<'a>(self) -> &'a mut str
```

🔬This is a nightly-only experimental API. (`string_leak` [#102929](https://github.com/rust-lang/rust/issues/102929))

Consumes and leaks the `String`, returning a mutable reference to the contents, `&'a mut str`.

 This is mainly useful for data that lives for the remainder of the program’s life. Dropping the returned reference will cause a memory leak.

 It does not reallocate or shrink the `String`, so the leaked allocation may include unused capacity that is not part of the returned slice.

 ##### Examples

 Simple usage:

 
```
#![feature(string_leak)]

let x = String::from("bucket");
let static_ref: &'static mut str = x.leak();
assert_eq!(static_ref, "bucket");
```
 


Methods from [Deref](../ops/trait.deref "trait std::ops::Deref")<Target = [str](../primitive.str)>
--------------------------------------------------------------------------------------------------


[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#160)
```
pub fn len(&self) -> usize
```

Returns the length of `self`.

 This length is in bytes, not [`char`](../primitive.char "primitive char")s or graphemes. In other words, it might not be what a human considers the length of the string.

 ##### Examples

 Basic usage:

 
```
let len = "foo".len();
assert_eq!(3, len);

assert_eq!("ƒoo".len(), 4); // fancy f!
assert_eq!("ƒoo".chars().count(), 3);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#181)
```
pub fn is_empty(&self) -> bool
```

Returns `true` if `self` has a length of zero bytes.

 ##### Examples

 Basic usage:

 
```
let s = "";
assert!(s.is_empty());

let s = "not empty";
assert!(!s.is_empty());
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#211)1.9.0
```
pub fn is_char_boundary(&self, index: usize) -> bool
```

Checks that `index`-th byte is the first byte in a UTF-8 code point sequence or the end of the string.

 The start and end of the string (when `index == self.len()`) are considered to be boundaries.

 Returns `false` if `index` is greater than `self.len()`.

 ##### Examples

 
```
let s = "Löwe 老虎 Léopard";
assert!(s.is_char_boundary(0));
// start of `老`
assert!(s.is_char_boundary(6));
assert!(s.is_char_boundary(s.len()));

// second byte of `ö`
assert!(!s.is_char_boundary(2));

// third byte of `老`
assert!(!s.is_char_boundary(8));
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#258)
```
pub fn floor_char_boundary(&self, index: usize) -> usize
```

🔬This is a nightly-only experimental API. (`round_char_boundary` [#93743](https://github.com/rust-lang/rust/issues/93743))

Finds the closest `x` not exceeding `index` where `is_char_boundary(x)` is `true`.

 This method can help you truncate a string so that it’s still valid UTF-8, but doesn’t exceed a given number of bytes. Note that this is done purely at the character level and can still visually split graphemes, even though the underlying characters aren’t split. For example, the emoji 🧑‍🔬 (scientist) could be split so that the string only includes 🧑 (person) instead.

 ##### Examples

 
```
#![feature(round_char_boundary)]
let s = "❤️🧡💛💚💙💜";
assert_eq!(s.len(), 26);
assert!(!s.is_char_boundary(13));

let closest = s.floor_char_boundary(13);
assert_eq!(closest, 10);
assert_eq!(&s[..closest], "❤️🧡");
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#297)
```
pub fn ceil_char_boundary(&self, index: usize) -> usize
```

🔬This is a nightly-only experimental API. (`round_char_boundary` [#93743](https://github.com/rust-lang/rust/issues/93743))

Finds the closest `x` not below `index` where `is_char_boundary(x)` is `true`.

 This method is the natural complement to [`floor_char_boundary`](../primitive.str#method.floor_char_boundary "method str::floor_char_boundary"). See that method for more details.

 ##### Panics

 Panics if `index > self.len()`.

 ##### Examples

 
```
#![feature(round_char_boundary)]
let s = "❤️🧡💛💚💙💜";
assert_eq!(s.len(), 26);
assert!(!s.is_char_boundary(13));

let closest = s.ceil_char_boundary(13);
assert_eq!(closest, 14);
assert_eq!(&s[..closest], "❤️🧡💛");
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#325)
```
pub fn as_bytes(&self) -> &[u8] ⓘ
```

Converts a string slice to a byte slice. To convert the byte slice back into a string slice, use the [`from_utf8`](../str/fn.from_utf8 "fn std::str::from_utf8") function.

 ##### Examples

 Basic usage:

 
```
let bytes = "bors".as_bytes();
assert_eq!(b"bors", bytes);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#369)1.20.0
```
pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] ⓘ
```

Converts a mutable string slice to a mutable byte slice.

 ##### Safety

 The caller must ensure that the content of the slice is valid UTF-8 before the borrow ends and the underlying `str` is used.

 Use of a `str` whose contents are not valid UTF-8 is undefined behavior.

 ##### Examples

 Basic usage:

 
```
let mut s = String::from("Hello");
let bytes = unsafe { s.as_bytes_mut() };

assert_eq!(b"Hello", bytes);
```
 Mutability:

 
```
let mut s = String::from("🗻∈🌏");

unsafe {
    let bytes = s.as_bytes_mut();

    bytes[0] = 0xF0;
    bytes[1] = 0x9F;
    bytes[2] = 0x8D;
    bytes[3] = 0x94;
}

assert_eq!("🍔∈🌏", s);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#400)
```
pub fn as_ptr(&self) -> *const u8
```

Converts a string slice to a raw pointer.

 As string slices are a slice of bytes, the raw pointer points to a [`u8`](../primitive.u8 "primitive u8"). This pointer will be pointing to the first byte of the string slice.

 The caller must ensure that the returned pointer is never written to. If you need to mutate the contents of the string slice, use [`as_mut_ptr`](../primitive.str#method.as_mut_ptr "method str::as_mut_ptr").

 ##### Examples

 Basic usage:

 
```
let s = "Hello";
let ptr = s.as_ptr();
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#415)1.36.0
```
pub fn as_mut_ptr(&mut self) -> *mut u8
```

Converts a mutable string slice to a raw pointer.

 As string slices are a slice of bytes, the raw pointer points to a [`u8`](../primitive.u8 "primitive u8"). This pointer will be pointing to the first byte of the string slice.

 It is your responsibility to make sure that the string slice only gets modified in a way that it remains valid UTF-8.

 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#440)1.20.0
```
pub fn get<I>(&self, i: I) -> Option<&<I as SliceIndex<str>>::Output>
where
    I: SliceIndex<str>,
```

Returns a subslice of `str`.

 This is the non-panicking alternative to indexing the `str`. Returns [`None`](../option/enum.option#variant.None "variant std::option::Option::None") whenever equivalent indexing operation would panic.

 ##### Examples

 
```
let v = String::from("🗻∈🌏");

assert_eq!(Some("🗻"), v.get(0..4));

// indices not on UTF-8 sequence boundaries
assert!(v.get(1..).is_none());
assert!(v.get(..8).is_none());

// out of bounds
assert!(v.get(..42).is_none());
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#472)1.20.0
```
pub fn get_mut<I>(
    &mut self,
    i: I
) -> Option<&mut <I as SliceIndex<str>>::Output>
where
    I: SliceIndex<str>,
```

Returns a mutable subslice of `str`.

 This is the non-panicking alternative to indexing the `str`. Returns [`None`](../option/enum.option#variant.None "variant std::option::Option::None") whenever equivalent indexing operation would panic.

 ##### Examples

 
```
let mut v = String::from("hello");
// correct length
assert!(v.get_mut(0..5).is_some());
// out of bounds
assert!(v.get_mut(..42).is_none());
assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));

assert_eq!("hello", v);
{
    let s = v.get_mut(0..2);
    let s = s.map(|s| {
        s.make_ascii_uppercase();
        &*s
    });
    assert_eq!(Some("HE"), s);
}
assert_eq!("HEllo", v);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#504)1.20.0
```
pub unsafe fn get_unchecked<I>(&self, i: I) -> &<I as SliceIndex<str>>::Output
where
    I: SliceIndex<str>,
```

Returns an unchecked subslice of `str`.

 This is the unchecked alternative to indexing the `str`.

 ##### Safety

 Callers of this function are responsible that these preconditions are satisfied:

 * The starting index must not exceed the ending index;
* Indexes must be within bounds of the original slice;
* Indexes must lie on UTF-8 sequence boundaries.

 Failing that, the returned string slice may reference invalid memory or violate the invariants communicated by the `str` type.

 ##### Examples

 
```
let v = "🗻∈🌏";
unsafe {
    assert_eq!("🗻", v.get_unchecked(0..4));
    assert_eq!("∈", v.get_unchecked(4..7));
    assert_eq!("🌏", v.get_unchecked(7..11));
}
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#539)1.20.0
```
pub unsafe fn get_unchecked_mut<I>(
    &mut self,
    i: I
) -> &mut <I as SliceIndex<str>>::Output
where
    I: SliceIndex<str>,
```

Returns a mutable, unchecked subslice of `str`.

 This is the unchecked alternative to indexing the `str`.

 ##### Safety

 Callers of this function are responsible that these preconditions are satisfied:

 * The starting index must not exceed the ending index;
* Indexes must be within bounds of the original slice;
* Indexes must lie on UTF-8 sequence boundaries.

 Failing that, the returned string slice may reference invalid memory or violate the invariants communicated by the `str` type.

 ##### Examples

 
```
let mut v = String::from("🗻∈🌏");
unsafe {
    assert_eq!("🗻", v.get_unchecked_mut(0..4));
    assert_eq!("∈", v.get_unchecked_mut(4..7));
    assert_eq!("🌏", v.get_unchecked_mut(7..11));
}
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#592)
```
pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str
```

👎Deprecated since 1.29.0: use `get_unchecked(begin..end)` instead

Creates a string slice from another string slice, bypassing safety checks.

 This is generally not recommended, use with caution! For a safe alternative see [`str`](../primitive.str "primitive str") and [`Index`](../ops/trait.index "trait std::ops::Index").

 This new slice goes from `begin` to `end`, including `begin` but excluding `end`.

 To get a mutable string slice instead, see the [`slice_mut_unchecked`](../primitive.str#method.slice_mut_unchecked "method str::slice_mut_unchecked") method.

 ##### Safety

 Callers of this function are responsible that three preconditions are satisfied:

 * `begin` must not exceed `end`.
* `begin` and `end` must be byte positions within the string slice.
* `begin` and `end` must lie on UTF-8 sequence boundaries.

 ##### Examples

 Basic usage:

 
```
let s = "Löwe 老虎 Léopard";

unsafe {
    assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
}

let s = "Hello, world!";

unsafe {
    assert_eq!("world", s.slice_unchecked(7, 12));
}
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#625)1.5.0
```
pub unsafe fn slice_mut_unchecked(
    &mut self,
    begin: usize,
    end: usize
) -> &mut str
```

👎Deprecated since 1.29.0: use `get_unchecked_mut(begin..end)` instead

Creates a string slice from another string slice, bypassing safety checks. This is generally not recommended, use with caution! For a safe alternative see [`str`](../primitive.str "primitive str") and [`IndexMut`](../ops/trait.indexmut "trait std::ops::IndexMut").

 This new slice goes from `begin` to `end`, including `begin` but excluding `end`.

 To get an immutable string slice instead, see the [`slice_unchecked`](../primitive.str#method.slice_unchecked "method str::slice_unchecked") method.

 ##### Safety

 Callers of this function are responsible that three preconditions are satisfied:

 * `begin` must not exceed `end`.
* `begin` and `end` must be byte positions within the string slice.
* `begin` and `end` must lie on UTF-8 sequence boundaries.

 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#665)1.4.0
```
pub fn split_at(&self, mid: usize) -> (&str, &str)
```

Divide one string slice into two at an index.

 The argument, `mid`, should be a byte offset from the start of the string. It must also be on the boundary of a UTF-8 code point.

 The two slices returned go from the start of the string slice to `mid`, and from `mid` to the end of the string slice.

 To get mutable string slices instead, see the [`split_at_mut`](../primitive.str#method.split_at_mut "method str::split_at_mut") method.

 ##### Panics

 Panics if `mid` is not on a UTF-8 code point boundary, or if it is past the end of the last code point of the string slice.

 ##### Examples

 Basic usage:

 
```
let s = "Per Martin-Löf";

let (first, last) = s.split_at(3);

assert_eq!("Per", first);
assert_eq!(" Martin-Löf", last);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#709)1.4.0
```
pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str)
```

Divide one mutable string slice into two at an index.

 The argument, `mid`, should be a byte offset from the start of the string. It must also be on the boundary of a UTF-8 code point.

 The two slices returned go from the start of the string slice to `mid`, and from `mid` to the end of the string slice.

 To get immutable string slices instead, see the [`split_at`](../primitive.str#method.split_at "method str::split_at") method.

 ##### Panics

 Panics if `mid` is not on a UTF-8 code point boundary, or if it is past the end of the last code point of the string slice.

 ##### Examples

 Basic usage:

 
```
let mut s = "Per Martin-Löf".to_string();
{
    let (first, last) = s.split_at_mut(3);
    first.make_ascii_uppercase();
    assert_eq!("PER", first);
    assert_eq!(" Martin-Löf", last);
}
assert_eq!("PER Martin-Löf", s);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#775)
```
pub fn chars(&self) -> Chars<'_> ⓘ
```

Returns an iterator over the [`char`](../primitive.char "primitive char")s of a string slice.

 As a string slice consists of valid UTF-8, we can iterate through a string slice by [`char`](../primitive.char "primitive char"). This method returns such an iterator.

 It’s important to remember that [`char`](../primitive.char "primitive char") represents a Unicode Scalar Value, and might not match your idea of what a ‘character’ is. Iteration over grapheme clusters may be what you actually want. This functionality is not provided by Rust’s standard library, check crates.io instead.

 ##### Examples

 Basic usage:

 
```
let word = "goodbye";

let count = word.chars().count();
assert_eq!(7, count);

let mut chars = word.chars();

assert_eq!(Some('g'), chars.next());
assert_eq!(Some('o'), chars.next());
assert_eq!(Some('o'), chars.next());
assert_eq!(Some('d'), chars.next());
assert_eq!(Some('b'), chars.next());
assert_eq!(Some('y'), chars.next());
assert_eq!(Some('e'), chars.next());

assert_eq!(None, chars.next());
```
 Remember, [`char`](../primitive.char "primitive char")s might not match your intuition about characters:

 
```
let y = "y̆";

let mut chars = y.chars();

assert_eq!(Some('y'), chars.next()); // not 'y̆'
assert_eq!(Some('\u{0306}'), chars.next());

assert_eq!(None, chars.next());
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#832)
```
pub fn char_indices(&self) -> CharIndices<'_> ⓘ
```

Returns an iterator over the [`char`](../primitive.char "primitive char")s of a string slice, and their positions.

 As a string slice consists of valid UTF-8, we can iterate through a string slice by [`char`](../primitive.char "primitive char"). This method returns an iterator of both these [`char`](../primitive.char "primitive char")s, as well as their byte positions.

 The iterator yields tuples. The position is first, the [`char`](../primitive.char "primitive char") is second.

 ##### Examples

 Basic usage:

 
```
let word = "goodbye";

let count = word.char_indices().count();
assert_eq!(7, count);

let mut char_indices = word.char_indices();

assert_eq!(Some((0, 'g')), char_indices.next());
assert_eq!(Some((1, 'o')), char_indices.next());
assert_eq!(Some((2, 'o')), char_indices.next());
assert_eq!(Some((3, 'd')), char_indices.next());
assert_eq!(Some((4, 'b')), char_indices.next());
assert_eq!(Some((5, 'y')), char_indices.next());
assert_eq!(Some((6, 'e')), char_indices.next());

assert_eq!(None, char_indices.next());
```
 Remember, [`char`](../primitive.char "primitive char")s might not match your intuition about characters:

 
```
let yes = "y̆es";

let mut char_indices = yes.char_indices();

assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
assert_eq!(Some((1, '\u{0306}')), char_indices.next());

// note the 3 here - the last character took up two bytes
assert_eq!(Some((3, 'e')), char_indices.next());
assert_eq!(Some((4, 's')), char_indices.next());

assert_eq!(None, char_indices.next());
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#857)
```
pub fn bytes(&self) -> Bytes<'_> ⓘ
```

An iterator over the bytes of a string slice.

 As a string slice consists of a sequence of bytes, we can iterate through a string slice by byte. This method returns such an iterator.

 ##### Examples

 Basic usage:

 
```
let mut bytes = "bors".bytes();

assert_eq!(Some(b'b'), bytes.next());
assert_eq!(Some(b'o'), bytes.next());
assert_eq!(Some(b'r'), bytes.next());
assert_eq!(Some(b's'), bytes.next());

assert_eq!(None, bytes.next());
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#909)1.1.0
```
pub fn split_whitespace(&self) -> SplitWhitespace<'_> ⓘ
```

Splits a string slice by whitespace.

 The iterator returned will return string slices that are sub-slices of the original string slice, separated by any amount of whitespace.

 ‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property `White_Space`. If you only want to split on ASCII whitespace instead, use [`split_ascii_whitespace`](../primitive.str#method.split_ascii_whitespace "method str::split_ascii_whitespace").

 ##### Examples

 Basic usage:

 
```
let mut iter = "A few words".split_whitespace();

assert_eq!(Some("A"), iter.next());
assert_eq!(Some("few"), iter.next());
assert_eq!(Some("words"), iter.next());

assert_eq!(None, iter.next());
```
 All kinds of whitespace are considered:

 
```
let mut iter = " Mary   had\ta\u{2009}little  \n\t lamb".split_whitespace();
assert_eq!(Some("Mary"), iter.next());
assert_eq!(Some("had"), iter.next());
assert_eq!(Some("a"), iter.next());
assert_eq!(Some("little"), iter.next());
assert_eq!(Some("lamb"), iter.next());

assert_eq!(None, iter.next());
```
 If the string is empty or all whitespace, the iterator yields no string slices:

 
```
assert_eq!("".split_whitespace().next(), None);
assert_eq!("   ".split_whitespace().next(), None);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#958)1.34.0
```
pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_> ⓘ
```

Splits a string slice by ASCII whitespace.

 The iterator returned will return string slices that are sub-slices of the original string slice, separated by any amount of ASCII whitespace.

 To split by Unicode `Whitespace` instead, use [`split_whitespace`](../primitive.str#method.split_whitespace "method str::split_whitespace").

 ##### Examples

 Basic usage:

 
```
let mut iter = "A few words".split_ascii_whitespace();

assert_eq!(Some("A"), iter.next());
assert_eq!(Some("few"), iter.next());
assert_eq!(Some("words"), iter.next());

assert_eq!(None, iter.next());
```
 All kinds of ASCII whitespace are considered:

 
```
let mut iter = " Mary   had\ta little  \n\t lamb".split_ascii_whitespace();
assert_eq!(Some("Mary"), iter.next());
assert_eq!(Some("had"), iter.next());
assert_eq!(Some("a"), iter.next());
assert_eq!(Some("little"), iter.next());
assert_eq!(Some("lamb"), iter.next());

assert_eq!(None, iter.next());
```
 If the string is empty or all ASCII whitespace, the iterator yields no string slices:

 
```
assert_eq!("".split_ascii_whitespace().next(), None);
assert_eq!("   ".split_ascii_whitespace().next(), None);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1006)
```
pub fn lines(&self) -> Lines<'_> ⓘ
```

An iterator over the lines of a string, as string slices.

 Lines are split at line endings that are either newlines (`\n`) or sequences of a carriage return followed by a line feed (`\r\n`).

 Line terminators are not included in the lines returned by the iterator.

 The final line ending is optional. A string that ends with a final line ending will return the same lines as an otherwise identical string without a final line ending.

 ##### Examples

 Basic usage:

 
```
let text = "foo\r\nbar\n\nbaz\n";
let mut lines = text.lines();

assert_eq!(Some("foo"), lines.next());
assert_eq!(Some("bar"), lines.next());
assert_eq!(Some(""), lines.next());
assert_eq!(Some("baz"), lines.next());

assert_eq!(None, lines.next());
```
 The final line ending isn’t required:

 
```
let text = "foo\nbar\n\r\nbaz";
let mut lines = text.lines();

assert_eq!(Some("foo"), lines.next());
assert_eq!(Some("bar"), lines.next());
assert_eq!(Some(""), lines.next());
assert_eq!(Some("baz"), lines.next());

assert_eq!(None, lines.next());
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1015)
```
pub fn lines_any(&self) -> LinesAny<'_> ⓘ
```

👎Deprecated since 1.4.0: use lines() instead now

An iterator over the lines of a string.

 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1036)1.8.0
```
pub fn encode_utf16(&self) -> EncodeUtf16<'_> ⓘ
```

Returns an iterator of `u16` over the string encoded as UTF-16.

 ##### Examples

 Basic usage:

 
```
let text = "Zażółć gęślą jaźń";

let utf8_len = text.len();
let utf16_len = text.encode_utf16().count();

assert!(utf16_len <= utf8_len);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1063)
```
pub fn contains<'a, P>(&'a self, pat: P) -> bool
where
    P: Pattern<'a>,
```

Returns `true` if the given pattern matches a sub-slice of this string slice.

 Returns `false` if it does not.

 The [pattern](../str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](../primitive.char "primitive char"), a slice of [`char`](../primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Examples

 Basic usage:

 
```
let bananas = "bananas";

assert!(bananas.contains("nana"));
assert!(!bananas.contains("apples"));
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1089)
```
pub fn starts_with<'a, P>(&'a self, pat: P) -> bool
where
    P: Pattern<'a>,
```

Returns `true` if the given pattern matches a prefix of this string slice.

 Returns `false` if it does not.

 The [pattern](../str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](../primitive.char "primitive char"), a slice of [`char`](../primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Examples

 Basic usage:

 
```
let bananas = "bananas";

assert!(bananas.starts_with("bana"));
assert!(!bananas.starts_with("nana"));
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1115-1117)
```
pub fn ends_with<'a, P>(&'a self, pat: P) -> bool
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
```

Returns `true` if the given pattern matches a suffix of this string slice.

 Returns `false` if it does not.

 The [pattern](../str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](../primitive.char "primitive char"), a slice of [`char`](../primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Examples

 Basic usage:

 
```
let bananas = "bananas";

assert!(bananas.ends_with("anas"));
assert!(!bananas.ends_with("nana"));
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1166)
```
pub fn find<'a, P>(&'a self, pat: P) -> Option<usize>
where
    P: Pattern<'a>,
```

Returns the byte index of the first character of this string slice that matches the pattern.

 Returns [`None`](../option/enum.option#variant.None "variant std::option::Option::None") if the pattern doesn’t match.

 The [pattern](../str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](../primitive.char "primitive char"), a slice of [`char`](../primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Examples

 Simple patterns:

 
```
let s = "Löwe 老虎 Léopard Gepardi";

assert_eq!(s.find('L'), Some(0));
assert_eq!(s.find('é'), Some(14));
assert_eq!(s.find("pard"), Some(17));
```
 More complex patterns using point-free style and closures:

 
```
let s = "Löwe 老虎 Léopard";

assert_eq!(s.find(char::is_whitespace), Some(5));
assert_eq!(s.find(char::is_lowercase), Some(1));
assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
```
 Not finding the pattern:

 
```
let s = "Löwe 老虎 Léopard";
let x: &[_] = &['1', '2'];

assert_eq!(s.find(x), None);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1212-1214)
```
pub fn rfind<'a, P>(&'a self, pat: P) -> Option<usize>
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
```

Returns the byte index for the first character of the last match of the pattern in this string slice.

 Returns [`None`](../option/enum.option#variant.None "variant std::option::Option::None") if the pattern doesn’t match.

 The [pattern](../str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](../primitive.char "primitive char"), a slice of [`char`](../primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Examples

 Simple patterns:

 
```
let s = "Löwe 老虎 Léopard Gepardi";

assert_eq!(s.rfind('L'), Some(13));
assert_eq!(s.rfind('é'), Some(14));
assert_eq!(s.rfind("pard"), Some(24));
```
 More complex patterns with closures:

 
```
let s = "Löwe 老虎 Léopard";

assert_eq!(s.rfind(char::is_whitespace), Some(12));
assert_eq!(s.rfind(char::is_lowercase), Some(20));
```
 Not finding the pattern:

 
```
let s = "Löwe 老虎 Léopard";
let x: &[_] = &['1', '2'];

assert_eq!(s.rfind(x), None);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1334)
```
pub fn split<'a, P>(&'a self, pat: P) -> Split<'a, P> ⓘ
where
    P: Pattern<'a>,
```

An iterator over substrings of this string slice, separated by characters matched by a pattern.

 The [pattern](../str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](../primitive.char "primitive char"), a slice of [`char`](../primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Iterator behavior

 The returned iterator will be a [`DoubleEndedIterator`](../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator") if the pattern allows a reverse search and forward/reverse search yields the same elements. This is true for, e.g., [`char`](../primitive.char "primitive char"), but not for `&str`.

 If the pattern allows a reverse search but its results might differ from a forward search, the [`rsplit`](../primitive.str#method.rsplit "method str::rsplit") method can be used.

 ##### Examples

 Simple patterns:

 
```
let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);

let v: Vec<&str> = "".split('X').collect();
assert_eq!(v, [""]);

let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
assert_eq!(v, ["lion", "", "tiger", "leopard"]);

let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
assert_eq!(v, ["lion", "tiger", "leopard"]);

let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
assert_eq!(v, ["abc", "def", "ghi"]);

let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
assert_eq!(v, ["lion", "tiger", "leopard"]);
```
 If the pattern is a slice of chars, split on each occurrence of any of the characters:

 
```
let v: Vec<&str> = "2020-11-03 23:59".split(&['-', ' ', ':', '@'][..]).collect();
assert_eq!(v, ["2020", "11", "03", "23", "59"]);
```
 A more complex pattern, using a closure:

 
```
let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
assert_eq!(v, ["abc", "def", "ghi"]);
```
 If a string contains multiple contiguous separators, you will end up with empty strings in the output:

 
```
let x = "||||a||b|c".to_string();
let d: Vec<_> = x.split('|').collect();

assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
```
 Contiguous separators are separated by the empty string.

 
```
let x = "(///)".to_string();
let d: Vec<_> = x.split('/').collect();

assert_eq!(d, &["(", "", "", ")"]);
```
 Separators at the start or end of a string are neighbored by empty strings.

 
```
let d: Vec<_> = "010".split("0").collect();
assert_eq!(d, &["", "1", ""]);
```
 When the empty string is used as a separator, it separates every character in the string, along with the beginning and end of the string.

 
```
let f: Vec<_> = "rust".split("").collect();
assert_eq!(f, &["", "r", "u", "s", "t", ""]);
```
 Contiguous separators can lead to possibly surprising behavior when whitespace is used as the separator. This code is correct:

 
```
let x = "    a  b c".to_string();
let d: Vec<_> = x.split(' ').collect();

assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
```
 It does *not* give you:

 ⓘ
```
assert_eq!(d, &["a", "b", "c"]);
```

 Use [`split_whitespace`](../primitive.str#method.split_whitespace "method str::split_whitespace") for this behavior.

 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1374)1.51.0
```
pub fn split_inclusive<'a, P>(&'a self, pat: P) -> SplitInclusive<'a, P> ⓘ
where
    P: Pattern<'a>,
```

An iterator over substrings of this string slice, separated by characters matched by a pattern. Differs from the iterator produced by `split` in that `split_inclusive` leaves the matched part as the terminator of the substring.

 The [pattern](../str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](../primitive.char "primitive char"), a slice of [`char`](../primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Examples

 
```
let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb."
    .split_inclusive('\n').collect();
assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb."]);
```
 If the last element of the string is matched, that element will be considered the terminator of the preceding substring. That substring will be the last item returned by the iterator.

 
```
let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb.\n"
    .split_inclusive('\n').collect();
assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb.\n"]);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1429-1431)
```
pub fn rsplit<'a, P>(&'a self, pat: P) -> RSplit<'a, P> ⓘ
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
```

An iterator over substrings of the given string slice, separated by characters matched by a pattern and yielded in reverse order.

 The [pattern](../str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](../primitive.char "primitive char"), a slice of [`char`](../primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Iterator behavior

 The returned iterator requires that the pattern supports a reverse search, and it will be a [`DoubleEndedIterator`](../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator") if a forward/reverse search yields the same elements.

 For iterating from the front, the [`split`](../primitive.str#method.split "method str::split") method can be used.

 ##### Examples

 Simple patterns:

 
```
let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);

let v: Vec<&str> = "".rsplit('X').collect();
assert_eq!(v, [""]);

let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
assert_eq!(v, ["leopard", "tiger", "", "lion"]);

let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
assert_eq!(v, ["leopard", "tiger", "lion"]);
```
 A more complex pattern, using a closure:

 
```
let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
assert_eq!(v, ["ghi", "def", "abc"]);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1480)
```
pub fn split_terminator<'a, P>(&'a self, pat: P) -> SplitTerminator<'a, P> ⓘ
where
    P: Pattern<'a>,
```

An iterator over substrings of the given string slice, separated by characters matched by a pattern.

 The [pattern](../str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](../primitive.char "primitive char"), a slice of [`char`](../primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 Equivalent to [`split`](../primitive.str#method.split "method str::split"), except that the trailing substring is skipped if empty.

 This method can be used for string data that is *terminated*, rather than *separated* by a pattern.

 ##### Iterator behavior

 The returned iterator will be a [`DoubleEndedIterator`](../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator") if the pattern allows a reverse search and forward/reverse search yields the same elements. This is true for, e.g., [`char`](../primitive.char "primitive char"), but not for `&str`.

 If the pattern allows a reverse search but its results might differ from a forward search, the [`rsplit_terminator`](../primitive.str#method.rsplit_terminator "method str::rsplit_terminator") method can be used.

 ##### Examples

 Basic usage:

 
```
let v: Vec<&str> = "A.B.".split_terminator('.').collect();
assert_eq!(v, ["A", "B"]);

let v: Vec<&str> = "A..B..".split_terminator(".").collect();
assert_eq!(v, ["A", "", "B", ""]);

let v: Vec<&str> = "A.B:C.D".split_terminator(&['.', ':'][..]).collect();
assert_eq!(v, ["A", "B", "C", "D"]);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1526-1528)
```
pub fn rsplit_terminator<'a, P>(&'a self, pat: P) -> RSplitTerminator<'a, P> ⓘ
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
```

An iterator over substrings of `self`, separated by characters matched by a pattern and yielded in reverse order.

 The [pattern](../str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](../primitive.char "primitive char"), a slice of [`char`](../primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 Equivalent to [`split`](../primitive.str#method.split "method str::split"), except that the trailing substring is skipped if empty.

 This method can be used for string data that is *terminated*, rather than *separated* by a pattern.

 ##### Iterator behavior

 The returned iterator requires that the pattern supports a reverse search, and it will be double ended if a forward/reverse search yields the same elements.

 For iterating from the front, the [`split_terminator`](../primitive.str#method.split_terminator "method str::split_terminator") method can be used.

 ##### Examples

 
```
let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
assert_eq!(v, ["B", "A"]);

let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
assert_eq!(v, ["", "B", "", "A"]);

let v: Vec<&str> = "A.B:C.D".rsplit_terminator(&['.', ':'][..]).collect();
assert_eq!(v, ["D", "C", "B", "A"]);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1581)
```
pub fn splitn<'a, P>(&'a self, n: usize, pat: P) -> SplitN<'a, P> ⓘ
where
    P: Pattern<'a>,
```

An iterator over substrings of the given string slice, separated by a pattern, restricted to returning at most `n` items.

 If `n` substrings are returned, the last substring (the `n`th substring) will contain the remainder of the string.

 The [pattern](../str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](../primitive.char "primitive char"), a slice of [`char`](../primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Iterator behavior

 The returned iterator will not be double ended, because it is not efficient to support.

 If the pattern allows a reverse search, the [`rsplitn`](../primitive.str#method.rsplitn "method str::rsplitn") method can be used.

 ##### Examples

 Simple patterns:

 
```
let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
assert_eq!(v, ["Mary", "had", "a little lambda"]);

let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
assert_eq!(v, ["lion", "", "tigerXleopard"]);

let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
assert_eq!(v, ["abcXdef"]);

let v: Vec<&str> = "".splitn(1, 'X').collect();
assert_eq!(v, [""]);
```
 A more complex pattern, using a closure:

 
```
let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
assert_eq!(v, ["abc", "defXghi"]);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1630-1632)
```
pub fn rsplitn<'a, P>(&'a self, n: usize, pat: P) -> RSplitN<'a, P> ⓘ
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
```

An iterator over substrings of this string slice, separated by a pattern, starting from the end of the string, restricted to returning at most `n` items.

 If `n` substrings are returned, the last substring (the `n`th substring) will contain the remainder of the string.

 The [pattern](../str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](../primitive.char "primitive char"), a slice of [`char`](../primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Iterator behavior

 The returned iterator will not be double ended, because it is not efficient to support.

 For splitting from the front, the [`splitn`](../primitive.str#method.splitn "method str::splitn") method can be used.

 ##### Examples

 Simple patterns:

 
```
let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
assert_eq!(v, ["lamb", "little", "Mary had a"]);

let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
assert_eq!(v, ["leopard", "tiger", "lionX"]);

let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
assert_eq!(v, ["leopard", "lion::tiger"]);
```
 A more complex pattern, using a closure:

 
```
let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
assert_eq!(v, ["ghi", "abc1def"]);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1650)1.52.0
```
pub fn split_once<'a, P>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)>
where
    P: Pattern<'a>,
```

Splits the string on the first occurrence of the specified delimiter and returns prefix before delimiter and suffix after delimiter.

 ##### Examples

 
```
assert_eq!("cfg".split_once('='), None);
assert_eq!("cfg=".split_once('='), Some(("cfg", "")));
assert_eq!("cfg=foo".split_once('='), Some(("cfg", "foo")));
assert_eq!("cfg=foo=bar".split_once('='), Some(("cfg", "foo=bar")));
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1668-1670)1.52.0
```
pub fn rsplit_once<'a, P>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)>
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
```

Splits the string on the last occurrence of the specified delimiter and returns prefix before delimiter and suffix after delimiter.

 ##### Examples

 
```
assert_eq!("cfg".rsplit_once('='), None);
assert_eq!("cfg=foo".rsplit_once('='), Some(("cfg", "foo")));
assert_eq!("cfg=foo=bar".rsplit_once('='), Some(("cfg=foo", "bar")));
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1710)1.2.0
```
pub fn matches<'a, P>(&'a self, pat: P) -> Matches<'a, P> ⓘ
where
    P: Pattern<'a>,
```

An iterator over the disjoint matches of a pattern within the given string slice.

 The [pattern](../str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](../primitive.char "primitive char"), a slice of [`char`](../primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Iterator behavior

 The returned iterator will be a [`DoubleEndedIterator`](../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator") if the pattern allows a reverse search and forward/reverse search yields the same elements. This is true for, e.g., [`char`](../primitive.char "primitive char"), but not for `&str`.

 If the pattern allows a reverse search but its results might differ from a forward search, the [`rmatches`](../primitive.str#method.matches "method str::matches") method can be used.

 ##### Examples

 Basic usage:

 
```
let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
assert_eq!(v, ["abc", "abc", "abc"]);

let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
assert_eq!(v, ["1", "2", "3"]);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1746-1748)1.2.0
```
pub fn rmatches<'a, P>(&'a self, pat: P) -> RMatches<'a, P> ⓘ
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
```

An iterator over the disjoint matches of a pattern within this string slice, yielded in reverse order.

 The [pattern](../str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](../primitive.char "primitive char"), a slice of [`char`](../primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Iterator behavior

 The returned iterator requires that the pattern supports a reverse search, and it will be a [`DoubleEndedIterator`](../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator") if a forward/reverse search yields the same elements.

 For iterating from the front, the [`matches`](../primitive.str#method.matches "method str::matches") method can be used.

 ##### Examples

 Basic usage:

 
```
let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
assert_eq!(v, ["abc", "abc", "abc"]);

let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
assert_eq!(v, ["3", "2", "1"]);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1792)1.5.0
```
pub fn match_indices<'a, P>(&'a self, pat: P) -> MatchIndices<'a, P> ⓘ
where
    P: Pattern<'a>,
```

An iterator over the disjoint matches of a pattern within this string slice as well as the index that the match starts at.

 For matches of `pat` within `self` that overlap, only the indices corresponding to the first match are returned.

 The [pattern](../str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](../primitive.char "primitive char"), a slice of [`char`](../primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Iterator behavior

 The returned iterator will be a [`DoubleEndedIterator`](../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator") if the pattern allows a reverse search and forward/reverse search yields the same elements. This is true for, e.g., [`char`](../primitive.char "primitive char"), but not for `&str`.

 If the pattern allows a reverse search but its results might differ from a forward search, the [`rmatch_indices`](../primitive.str#method.rmatch_indices "method str::rmatch_indices") method can be used.

 ##### Examples

 Basic usage:

 
```
let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);

let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
assert_eq!(v, [(1, "abc"), (4, "abc")]);

let v: Vec<_> = "ababa".match_indices("aba").collect();
assert_eq!(v, [(0, "aba")]); // only the first `aba`
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1834-1836)1.5.0
```
pub fn rmatch_indices<'a, P>(&'a self, pat: P) -> RMatchIndices<'a, P> ⓘ
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
```

An iterator over the disjoint matches of a pattern within `self`, yielded in reverse order along with the index of the match.

 For matches of `pat` within `self` that overlap, only the indices corresponding to the last match are returned.

 The [pattern](../str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](../primitive.char "primitive char"), a slice of [`char`](../primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Iterator behavior

 The returned iterator requires that the pattern supports a reverse search, and it will be a [`DoubleEndedIterator`](../iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator") if a forward/reverse search yields the same elements.

 For iterating from the front, the [`match_indices`](../primitive.str#method.match_indices "method str::match_indices") method can be used.

 ##### Examples

 Basic usage:

 
```
let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);

let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
assert_eq!(v, [(4, "abc"), (1, "abc")]);

let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
assert_eq!(v, [(2, "aba")]); // only the last `aba`
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1860)
```
pub fn trim(&self) -> &str
```

Returns a string slice with leading and trailing whitespace removed.

 ‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property `White_Space`, which includes newlines.

 ##### Examples

 Basic usage:

 
```
let s = "\n Hello\tworld\t\n";

assert_eq!("Hello\tworld", s.trim());
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1899)1.30.0
```
pub fn trim_start(&self) -> &str
```

Returns a string slice with leading whitespace removed.

 ‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property `White_Space`, which includes newlines.

 ##### Text directionality

 A string is a sequence of bytes. `start` in this context means the first position of that byte string; for a left-to-right language like English or Russian, this will be left side, and for right-to-left languages like Arabic or Hebrew, this will be the right side.

 ##### Examples

 Basic usage:

 
```
let s = "\n Hello\tworld\t\n";
assert_eq!("Hello\tworld\t\n", s.trim_start());
```
 Directionality:

 
```
let s = "  English  ";
assert!(Some('E') == s.trim_start().chars().next());

let s = "  עברית  ";
assert!(Some('ע') == s.trim_start().chars().next());
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1938)1.30.0
```
pub fn trim_end(&self) -> &str
```

Returns a string slice with trailing whitespace removed.

 ‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property `White_Space`, which includes newlines.

 ##### Text directionality

 A string is a sequence of bytes. `end` in this context means the last position of that byte string; for a left-to-right language like English or Russian, this will be right side, and for right-to-left languages like Arabic or Hebrew, this will be the left side.

 ##### Examples

 Basic usage:

 
```
let s = "\n Hello\tworld\t\n";
assert_eq!("\n Hello\tworld", s.trim_end());
```
 Directionality:

 
```
let s = "  English  ";
assert!(Some('h') == s.trim_end().chars().rev().next());

let s = "  עברית  ";
assert!(Some('ת') == s.trim_end().chars().rev().next());
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1978)
```
pub fn trim_left(&self) -> &str
```

👎Deprecated since 1.33.0: superseded by `trim_start`

Returns a string slice with leading whitespace removed.

 ‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property `White_Space`.

 ##### Text directionality

 A string is a sequence of bytes. ‘Left’ in this context means the first position of that byte string; for a language like Arabic or Hebrew which are ‘right to left’ rather than ‘left to right’, this will be the *right* side, not the left.

 ##### Examples

 Basic usage:

 
```
let s = " Hello\tworld\t";

assert_eq!("Hello\tworld\t", s.trim_left());
```
 Directionality:

 
```
let s = "  English";
assert!(Some('E') == s.trim_left().chars().next());

let s = "  עברית";
assert!(Some('ע') == s.trim_left().chars().next());
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2018)
```
pub fn trim_right(&self) -> &str
```

👎Deprecated since 1.33.0: superseded by `trim_end`

Returns a string slice with trailing whitespace removed.

 ‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property `White_Space`.

 ##### Text directionality

 A string is a sequence of bytes. ‘Right’ in this context means the last position of that byte string; for a language like Arabic or Hebrew which are ‘right to left’ rather than ‘left to right’, this will be the *left* side, not the right.

 ##### Examples

 Basic usage:

 
```
let s = " Hello\tworld\t";

assert_eq!(" Hello\tworld", s.trim_right());
```
 Directionality:

 
```
let s = "English  ";
assert!(Some('h') == s.trim_right().chars().rev().next());

let s = "עברית  ";
assert!(Some('ת') == s.trim_right().chars().rev().next());
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2051-2053)
```
pub fn trim_matches<'a, P>(&'a self, pat: P) -> &'a str
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: DoubleEndedSearcher<'a>,
```

Returns a string slice with all prefixes and suffixes that match a pattern repeatedly removed.

 The [pattern](../str/pattern/index "mod std::str::pattern") can be a [`char`](../primitive.char "primitive char"), a slice of [`char`](../primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Examples

 Simple patterns:

 
```
assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");

let x: &[_] = &['1', '2'];
assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
```
 A more complex pattern, using a closure:

 
```
assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2100)1.30.0
```
pub fn trim_start_matches<'a, P>(&'a self, pat: P) -> &'a str
where
    P: Pattern<'a>,
```

Returns a string slice with all prefixes that match a pattern repeatedly removed.

 The [pattern](../str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](../primitive.char "primitive char"), a slice of [`char`](../primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Text directionality

 A string is a sequence of bytes. `start` in this context means the first position of that byte string; for a left-to-right language like English or Russian, this will be left side, and for right-to-left languages like Arabic or Hebrew, this will be the right side.

 ##### Examples

 Basic usage:

 
```
assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11");
assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123");

let x: &[_] = &['1', '2'];
assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12");
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2133)1.45.0
```
pub fn strip_prefix<'a, P>(&'a self, prefix: P) -> Option<&'a str>
where
    P: Pattern<'a>,
```

Returns a string slice with the prefix removed.

 If the string starts with the pattern `prefix`, returns substring after the prefix, wrapped in `Some`. Unlike `trim_start_matches`, this method removes the prefix exactly once.

 If the string does not start with `prefix`, returns `None`.

 The [pattern](../str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](../primitive.char "primitive char"), a slice of [`char`](../primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Examples

 
```
assert_eq!("foo:bar".strip_prefix("foo:"), Some("bar"));
assert_eq!("foo:bar".strip_prefix("bar"), None);
assert_eq!("foofoo".strip_prefix("foo"), Some("foo"));
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2160-2163)1.45.0
```
pub fn strip_suffix<'a, P>(&'a self, suffix: P) -> Option<&'a str>
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
```

Returns a string slice with the suffix removed.

 If the string ends with the pattern `suffix`, returns the substring before the suffix, wrapped in `Some`. Unlike `trim_end_matches`, this method removes the suffix exactly once.

 If the string does not end with `suffix`, returns `None`.

 The [pattern](../str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](../primitive.char "primitive char"), a slice of [`char`](../primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Examples

 
```
assert_eq!("bar:foo".strip_suffix(":foo"), Some("bar"));
assert_eq!("bar:foo".strip_suffix("bar"), None);
assert_eq!("foofoo".strip_suffix("foo"), Some("foo"));
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2204-2206)1.30.0
```
pub fn trim_end_matches<'a, P>(&'a self, pat: P) -> &'a str
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
```

Returns a string slice with all suffixes that match a pattern repeatedly removed.

 The [pattern](../str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](../primitive.char "primitive char"), a slice of [`char`](../primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Text directionality

 A string is a sequence of bytes. `end` in this context means the last position of that byte string; for a left-to-right language like English or Russian, this will be right side, and for right-to-left languages like Arabic or Hebrew, this will be the left side.

 ##### Examples

 Simple patterns:

 
```
assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar");
assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");

let x: &[_] = &['1', '2'];
assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar");
```
 A more complex pattern, using a closure:

 
```
assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo");
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2250)
```
pub fn trim_left_matches<'a, P>(&'a self, pat: P) -> &'a str
where
    P: Pattern<'a>,
```

👎Deprecated since 1.33.0: superseded by `trim_start_matches`

Returns a string slice with all prefixes that match a pattern repeatedly removed.

 The [pattern](../str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](../primitive.char "primitive char"), a slice of [`char`](../primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Text directionality

 A string is a sequence of bytes. ‘Left’ in this context means the first position of that byte string; for a language like Arabic or Hebrew which are ‘right to left’ rather than ‘left to right’, this will be the *right* side, not the left.

 ##### Examples

 Basic usage:

 
```
assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");

let x: &[_] = &['1', '2'];
assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2293-2295)
```
pub fn trim_right_matches<'a, P>(&'a self, pat: P) -> &'a str
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
```

👎Deprecated since 1.33.0: superseded by `trim_end_matches`

Returns a string slice with all suffixes that match a pattern repeatedly removed.

 The [pattern](../str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](../primitive.char "primitive char"), a slice of [`char`](../primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Text directionality

 A string is a sequence of bytes. ‘Right’ in this context means the last position of that byte string; for a language like Arabic or Hebrew which are ‘right to left’ rather than ‘left to right’, this will be the *left* side, not the right.

 ##### Examples

 Simple patterns:

 
```
assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");

let x: &[_] = &['1', '2'];
assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
```
 A more complex pattern, using a closure:

 
```
assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2345)
```
pub fn parse<F>(&self) -> Result<F, <F as FromStr>::Err>
where
    F: FromStr,
```

Parses this string slice into another type.

 Because `parse` is so general, it can cause problems with type inference. As such, `parse` is one of the few times you’ll see the syntax affectionately known as the ‘turbofish’: `::<>`. This helps the inference algorithm understand specifically which type you’re trying to parse into.

 `parse` can parse into any type that implements the [`FromStr`](../str/trait.fromstr "trait std::str::FromStr") trait.

 ##### Errors

 Will return [`Err`](../str/trait.fromstr#associatedtype.Err "associated type std::str::FromStr::Err") if it’s not possible to parse this string slice into the desired type.

 ##### Examples

 Basic usage

 
```
let four: u32 = "4".parse().unwrap();

assert_eq!(4, four);
```
 Using the ‘turbofish’ instead of annotating `four`:

 
```
let four = "4".parse::<u32>();

assert_eq!(Ok(4), four);
```
 Failing to parse:

 
```
let nope = "j".parse::<u32>();

assert!(nope.is_err());
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2364)1.23.0
```
pub fn is_ascii(&self) -> bool
```

Checks if all characters in this string are within the ASCII range.

 ##### Examples

 
```
let ascii = "hello!\n";
let non_ascii = "Grüße, Jürgen ❤";

assert!(ascii.is_ascii());
assert!(!non_ascii.is_ascii());
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2376)
```
pub fn as_ascii(&self) -> Option<&[AsciiChar]>
```

🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998))

If this string slice [`is_ascii`](../primitive.str#method.is_ascii "method str::is_ascii"), returns it as a slice of [ASCII characters](../ascii/enum.char "enum std::ascii::Char"), otherwise returns `None`.

 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2396)1.23.0
```
pub fn eq_ignore_ascii_case(&self, other: &str) -> bool
```

Checks that two strings are an ASCII case-insensitive match.

 Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`, but without allocating and copying temporaries.

 ##### Examples

 
```
assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2421)1.23.0
```
pub fn make_ascii_uppercase(&mut self)
```

Converts this string to its ASCII upper case equivalent in-place.

 ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, but non-ASCII letters are unchanged.

 To return a new uppercased value without modifying the existing one, use [`to_ascii_uppercase()`](#method.to_ascii_uppercase).

 ##### Examples

 
```
let mut s = String::from("Grüße, Jürgen ❤");

s.make_ascii_uppercase();

assert_eq!("GRüßE, JüRGEN ❤", s);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2448)1.23.0
```
pub fn make_ascii_lowercase(&mut self)
```

Converts this string to its ASCII lower case equivalent in-place.

 ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’, but non-ASCII letters are unchanged.

 To return a new lowercased value without modifying the existing one, use [`to_ascii_lowercase()`](#method.to_ascii_lowercase).

 ##### Examples

 
```
let mut s = String::from("GRÜßE, JÜRGEN ❤");

s.make_ascii_lowercase();

assert_eq!("grÜße, jÜrgen ❤", s);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2491)1.34.0
```
pub fn escape_debug(&self) -> EscapeDebug<'_> ⓘ
```

Return an iterator that escapes each char in `self` with [`char::escape_debug`](../primitive.char#method.escape_debug "method char::escape_debug").

 Note: only extended grapheme codepoints that begin the string will be escaped.

 ##### Examples

 As an iterator:

 
```
for c in "❤\n!".escape_debug() {
    print!("{c}");
}
println!();
```
 Using `println!` directly:

 
```
println!("{}", "❤\n!".escape_debug());
```
 Both are equivalent to:

 
```
println!("❤\\n!");
```
 Using `to_string`:

 
```
assert_eq!("❤\n!".escape_debug().to_string(), "❤\\n!");
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2537)1.34.0
```
pub fn escape_default(&self) -> EscapeDefault<'_> ⓘ
```

Return an iterator that escapes each char in `self` with [`char::escape_default`](../primitive.char#method.escape_default "method char::escape_default").

 ##### Examples

 As an iterator:

 
```
for c in "❤\n!".escape_default() {
    print!("{c}");
}
println!();
```
 Using `println!` directly:

 
```
println!("{}", "❤\n!".escape_default());
```
 Both are equivalent to:

 
```
println!("\\u{{2764}}\\n!");
```
 Using `to_string`:

 
```
assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!");
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2575)1.34.0
```
pub fn escape_unicode(&self) -> EscapeUnicode<'_> ⓘ
```

Return an iterator that escapes each char in `self` with [`char::escape_unicode`](../primitive.char#method.escape_unicode "method char::escape_unicode").

 ##### Examples

 As an iterator:

 
```
for c in "❤\n!".escape_unicode() {
    print!("{c}");
}
println!();
```
 Using `println!` directly:

 
```
println!("{}", "❤\n!".escape_unicode());
```
 Both are equivalent to:

 
```
println!("\\u{{2764}}\\u{{a}}\\u{{21}}");
```
 Using `to_string`:

 
```
assert_eq!("❤\n!".escape_unicode().to_string(), "\\u{2764}\\u{a}\\u{21}");
```
 
[source](https://doc.rust-lang.org/src/alloc/str.rs.html#271)
```
pub fn replace<'a, P>(&'a self, from: P, to: &str) -> String
where
    P: Pattern<'a>,
```

Replaces all matches of a pattern with another string.

 `replace` creates a new [`String`](struct.string "struct std::string::String"), and copies the data from this string slice into it. While doing so, it attempts to find matches of a pattern. If it finds any, it replaces them with the replacement string slice.

 ##### Examples

 Basic usage:

 
```
let s = "this is old";

assert_eq!("this is new", s.replace("old", "new"));
assert_eq!("than an old", s.replace("is", "an"));
```
 When the pattern doesn’t match, it returns this string slice as [`String`](struct.string "struct std::string::String"):

 
```
let s = "this is old";
assert_eq!(s, s.replace("cookie monster", "little lamb"));
```
 
[source](https://doc.rust-lang.org/src/alloc/str.rs.html#311)1.16.0
```
pub fn replacen<'a, P>(&'a self, pat: P, to: &str, count: usize) -> String
where
    P: Pattern<'a>,
```

Replaces first N matches of a pattern with another string.

 `replacen` creates a new [`String`](struct.string "struct std::string::String"), and copies the data from this string slice into it. While doing so, it attempts to find matches of a pattern. If it finds any, it replaces them with the replacement string slice at most `count` times.

 ##### Examples

 Basic usage:

 
```
let s = "foo foo 123 foo";
assert_eq!("new new 123 foo", s.replacen("foo", "new", 2));
assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3));
assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric, "new", 1));
```
 When the pattern doesn’t match, it returns this string slice as [`String`](struct.string "struct std::string::String"):

 
```
let s = "this is old";
assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));
```
 
[source](https://doc.rust-lang.org/src/alloc/str.rs.html#368)1.2.0
```
pub fn to_lowercase(&self) -> String
```

Returns the lowercase equivalent of this string slice, as a new [`String`](struct.string "struct std::string::String").

 ‘Lowercase’ is defined according to the terms of the Unicode Derived Core Property `Lowercase`.

 Since some characters can expand into multiple characters when changing the case, this function returns a [`String`](struct.string "struct std::string::String") instead of modifying the parameter in-place.

 ##### Examples

 Basic usage:

 
```
let s = "HELLO";

assert_eq!("hello", s.to_lowercase());
```
 A tricky example, with sigma:

 
```
let sigma = "Σ";

assert_eq!("σ", sigma.to_lowercase());

// but at the end of a word, it's ς, not σ:
let odysseus = "ὈΔΥΣΣΕΎΣ";

assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());
```
 Languages without case are not changed:

 
```
let new_year = "农历新年";

assert_eq!(new_year, new_year.to_lowercase());
```
 
[source](https://doc.rust-lang.org/src/alloc/str.rs.html#459)1.2.0
```
pub fn to_uppercase(&self) -> String
```

Returns the uppercase equivalent of this string slice, as a new [`String`](struct.string "struct std::string::String").

 ‘Uppercase’ is defined according to the terms of the Unicode Derived Core Property `Uppercase`.

 Since some characters can expand into multiple characters when changing the case, this function returns a [`String`](struct.string "struct std::string::String") instead of modifying the parameter in-place.

 ##### Examples

 Basic usage:

 
```
let s = "hello";

assert_eq!("HELLO", s.to_uppercase());
```
 Scripts without case are not changed:

 
```
let new_year = "农历新年";

assert_eq!(new_year, new_year.to_uppercase());
```
 One character can become multiple:

 
```
let s = "tschüß";

assert_eq!("TSCHÜSS", s.to_uppercase());
```
 
[source](https://doc.rust-lang.org/src/alloc/str.rs.html#531)1.16.0
```
pub fn repeat(&self, n: usize) -> String
```

Creates a new [`String`](struct.string "struct std::string::String") by repeating a string `n` times.

 ##### Panics

 This function will panic if the capacity would overflow.

 ##### Examples

 Basic usage:

 
```
assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
```
 A panic upon overflow:

 ⓘ
```
// this will panic at runtime
let huge = "0123456789abcdef".repeat(usize::MAX);
```

 
[source](https://doc.rust-lang.org/src/alloc/str.rs.html#561)1.23.0
```
pub fn to_ascii_uppercase(&self) -> String
```

Returns a copy of this string where each character is mapped to its ASCII upper case equivalent.

 ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, but non-ASCII letters are unchanged.

 To uppercase the value in-place, use [`make_ascii_uppercase`](../primitive.str#method.make_ascii_uppercase "method str::make_ascii_uppercase").

 To uppercase ASCII characters in addition to non-ASCII characters, use [`to_uppercase`](#method.to_uppercase).

 ##### Examples

 
```
let s = "Grüße, Jürgen ❤";

assert_eq!("GRüßE, JüRGEN ❤", s.to_ascii_uppercase());
```
 
[source](https://doc.rust-lang.org/src/alloc/str.rs.html#593)1.23.0
```
pub fn to_ascii_lowercase(&self) -> String
```

Returns a copy of this string where each character is mapped to its ASCII lower case equivalent.

 ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’, but non-ASCII letters are unchanged.

 To lowercase the value in-place, use [`make_ascii_lowercase`](../primitive.str#method.make_ascii_lowercase "method str::make_ascii_lowercase").

 To lowercase ASCII characters in addition to non-ASCII characters, use [`to_lowercase`](#method.to_lowercase).

 ##### Examples

 
```
let s = "Grüße, Jürgen ❤";

assert_eq!("grüße, jürgen ❤", s.to_ascii_lowercase());
```
 
Trait Implementations
---------------------



[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2321)
```
impl Add<&str> for String
```

Implements the `+` operator for concatenating two strings.

 This consumes the `String` on the left-hand side and re-uses its buffer (growing it if necessary). This is done to avoid allocating a new `String` and copying the entire contents on every operation, which would lead to *O*(*n*^2) running time when building an *n*-byte string by repeated concatenation.

 The string on the right-hand side is only borrowed; its contents are copied into the returned `String`.

 #### Examples

 Concatenating two `String`s takes the first by value and borrows the second:

 
```
let a = String::from("hello");
let b = String::from(" world");
let c = a + &b;
// `a` is moved and can no longer be used here.
```
 If you want to keep using the first `String`, you can clone it and append to the clone instead:

 
```
let a = String::from("hello");
let b = String::from(" world");
let c = a.clone() + &b;
// `a` is still valid here.
```
 Concatenating `&str` slices can be done by converting the first to a `String`:

 
```
let a = "hello";
let b = " world";
let c = a.to_string() + b;
```
 


```
type Output = String
```
The resulting type after applying the `+` operator.
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2325)
```
fn add(self, other: &str) -> String
```
Performs the `+` operation. [Read more](../ops/trait.add#tymethod.add)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2336)1.12.0
```
impl AddAssign<&str> for String
```

Implements the `+=` operator for appending to a `String`.

 This has the same behavior as the [`push_str`](struct.string#method.push_str "method std::string::String::push_str") method.

 

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2338)
```
fn add_assign(&mut self, other: &str)
```
Performs the `+=` operation. [Read more](../ops/trait.addassign#tymethod.add_assign)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2644)1.43.0
```
impl AsMut<str> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2646)
```
fn as_mut(&mut self) -> &mut str
```
Converts this type into a mutable reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2652)
```
impl AsRef<[u8]> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2654)
```
fn as_ref(&self) -> &[u8] ⓘ
```
Converts this type into a shared reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1326-1331)
```
impl AsRef<OsStr> for String
```

[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1328-1330)
```
fn as_ref(&self) -> &OsStr
```
Converts this type into a shared reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/std/path.rs.html#3157-3162)
```
impl AsRef<Path> for String
```

[source](https://doc.rust-lang.org/src/std/path.rs.html#3159-3161)
```
fn as_ref(&self) -> &Path
```
Converts this type into a shared reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2636)
```
impl AsRef<str> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2638)
```
fn as_ref(&self) -> &str
```
Converts this type into a shared reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/alloc/str.rs.html#188)
```
impl Borrow<str> for String
```

[source](https://doc.rust-lang.org/src/alloc/str.rs.html#190)
```
fn borrow(&self) -> &str
```
Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/alloc/str.rs.html#196)1.36.0
```
impl BorrowMut<str> for String
```

[source](https://doc.rust-lang.org/src/alloc/str.rs.html#198)
```
fn borrow_mut(&mut self) -> &mut str
```
Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#1990)
```
impl Clone for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#1991)
```
fn clone(&self) -> String
```
Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone)

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#1995)
```
fn clone_from(&mut self, source: &String)
```
Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2267)
```
impl Debug for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2269)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2250)
```
impl Default for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2253)
```
fn default() -> String
```

Creates an empty `String`.

 

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2442)
```
impl Deref for String
```


```
type Target = str
```
The resulting type after dereferencing.
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2446)
```
fn deref(&self) -> &str
```
Dereferences the value.

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2452)1.3.0
```
impl DerefMut for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2454)
```
fn deref_mut(&mut self) -> &mut str
```
Mutably dereferences the value.

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2259)
```
impl Display for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2261)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter. [Read more](../fmt/trait.display#tymethod.fmt)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2102)1.2.0
```
impl<'a> Extend<&'a char> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2103)
```
fn extend<I>(&mut self, iter: I)
where
    I: IntoIterator<Item = &'a char>,
```
Extends a collection with the contents of an iterator. [Read more](../iter/trait.extend#tymethod.extend)

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2108)
```
fn extend_one(&mut self, _: &'a 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/src/alloc/string.rs.html#2113)
```
fn extend_reserve(&mut self, additional: usize)
```

🔬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](../iter/trait.extend#method.extend_reserve)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2120)
```
impl<'a> Extend<&'a str> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2121)
```
fn extend<I>(&mut self, iter: I)
where
    I: IntoIterator<Item = &'a str>,
```
Extends a collection with the contents of an iterator. [Read more](../iter/trait.extend#tymethod.extend)

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2126)
```
fn extend_one(&mut self, s: &'a str)
```

🔬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/src/core/iter/traits/collect.rs.html#389)
```
fn extend_reserve(&mut self, additional: usize)
```

🔬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](../iter/trait.extend#method.extend_reserve)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2133)1.45.0
```
impl Extend<Box<str, Global>> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2134)
```
fn extend<I>(&mut self, iter: I)
where
    I: IntoIterator<Item = Box<str, Global>>,
```
Extends a collection with the contents of an iterator. [Read more](../iter/trait.extend#tymethod.extend)

[source](https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#381)
```
fn extend_one(&mut self, item: A)
```

🔬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/src/core/iter/traits/collect.rs.html#389)
```
fn extend_reserve(&mut self, additional: usize)
```

🔬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](../iter/trait.extend#method.extend_reserve)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2154)1.19.0
```
impl<'a> Extend<Cow<'a, str>> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2155)
```
fn extend<I>(&mut self, iter: I)
where
    I: IntoIterator<Item = Cow<'a, str>>,
```
Extends a collection with the contents of an iterator. [Read more](../iter/trait.extend#tymethod.extend)

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2160)
```
fn extend_one(&mut self, s: Cow<'a, str>)
```

🔬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/src/core/iter/traits/collect.rs.html#389)
```
fn extend_reserve(&mut self, additional: usize)
```

🔬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](../iter/trait.extend#method.extend_reserve)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2141)1.4.0
```
impl Extend<String> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2142)
```
fn extend<I>(&mut self, iter: I)
where
    I: IntoIterator<Item = String>,
```
Extends a collection with the contents of an iterator. [Read more](../iter/trait.extend#tymethod.extend)

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2147)
```
fn extend_one(&mut self, s: String)
```

🔬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/src/core/iter/traits/collect.rs.html#389)
```
fn extend_reserve(&mut self, additional: usize)
```

🔬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](../iter/trait.extend#method.extend_reserve)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2081)
```
impl Extend<char> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2082)
```
fn extend<I>(&mut self, iter: I)
where
    I: IntoIterator<Item = char>,
```
Extends a collection with the contents of an iterator. [Read more](../iter/trait.extend#tymethod.extend)

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2090)
```
fn extend_one(&mut self, c: 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/src/alloc/string.rs.html#2095)
```
fn extend_reserve(&mut self, additional: usize)
```

🔬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](../iter/trait.extend#method.extend_reserve)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2809)1.28.0
```
impl<'a> From<&'a String> for Cow<'a, str>
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2824)
```
fn from(s: &'a String) -> Cow<'a, str>
```

Converts a [`String`](struct.string "struct std::string::String") reference into a [`Borrowed`](../borrow/enum.cow#variant.Borrowed "borrow::Cow::Borrowed") variant. No heap allocation is performed, and the string is not copied.

 ##### Example

 
```
let s = "eggplant".to_string();
assert_eq!(Cow::from(&s), Cow::Borrowed("eggplant"));
```
 

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2685)1.35.0
```
impl From<&String> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2690)
```
fn from(s: &String) -> String
```

Converts a `&String` into a [`String`](struct.string "struct std::string::String").

 This clones `s` and returns the clone.

 

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2673)1.44.0
```
impl From<&mut str> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2678)
```
fn from(s: &mut str) -> String
```

Converts a `&mut str` into a [`String`](struct.string "struct std::string::String").

 The result is allocated on the heap.

 

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2661)
```
impl From<&str> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2666)
```
fn from(s: &str) -> String
```

Converts a `&str` into a [`String`](struct.string "struct std::string::String").

 The result is allocated on the heap.

 

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2698)1.18.0
```
impl From<Box<str, Global>> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2713)
```
fn from(s: Box<str, Global>) -> String
```

Converts the given boxed `str` slice to a [`String`](struct.string "struct std::string::String"). It is notable that the `str` slice is owned.

 ##### Examples

 Basic usage:

 
```
let s1: String = String::from("hello world");
let s2: Box<str> = s1.into_boxed_str();
let s3: String = String::from(s2);

assert_eq!("hello world", s3)
```
 

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2741)1.14.0
```
impl<'a> From<Cow<'a, str>> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2758)
```
fn from(s: Cow<'a, str>) -> String
```

Converts a clone-on-write string to an owned instance of [`String`](struct.string "struct std::string::String").

 This extracts the owned string, clones the string if it is not already owned.

 ##### Example

 
```
// If the string is not owned...
let cow: Cow<'_, str> = Cow::Borrowed("eggplant");
// It will allocate on the heap and copy the string.
let owned: String = String::from(cow);
assert_eq!(&owned[..], "eggplant");
```
 

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2710)1.21.0
```
impl From<String> for Arc<str>
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2722)
```
fn from(v: String) -> Arc<str>
```

Allocate a reference-counted `str` and copy `v` into it.

 ##### Example

 
```
let unique: String = "eggplant".to_owned();
let shared: Arc<str> = Arc::from(unique);
assert_eq!("eggplant", &shared[..]);
```
 

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2301)1.6.0
```
impl From<String> for Box<dyn Error + 'static, Global>
```

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2314)
```
fn from(str_err: String) -> Box<dyn Error + 'static, Global>
```

Converts a [`String`](struct.string "struct std::string::String") into a box of dyn [`Error`](../error/trait.error "trait std::error::Error").

 ##### Examples

 
```
use std::error::Error;
use std::mem;

let a_string_error = "a string error".to_string();
let a_boxed_error = Box::<dyn Error>::from(a_string_error);
assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
```
 

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2257)
```
impl From<String> for Box<dyn Error + Sync + Send + 'static, Global>
```

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2272)
```
fn from(err: String) -> Box<dyn Error + Sync + Send + 'static, Global>
```

Converts a [`String`](struct.string "struct std::string::String") into a box of dyn [`Error`](../error/trait.error "trait std::error::Error") + [`Send`](../marker/trait.send "trait std::marker::Send") + [`Sync`](../marker/trait.sync "trait std::marker::Sync").

 ##### Examples

 
```
use std::error::Error;
use std::mem;

let a_string_error = "a string error".to_string();
let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
assert!(
    mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
```
 

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2720)1.20.0
```
impl From<String> for Box<str, Global>
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2734)
```
fn from(s: String) -> Box<str, Global>
```

Converts the given [`String`](struct.string "struct std::string::String") to a boxed `str` slice that is owned.

 ##### Examples

 Basic usage:

 
```
let s1: String = String::from("hello world");
let s2: Box<str> = Box::from(s1);
let s3: String = String::from(s2);

assert_eq!("hello world", s3)
```
 

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2786)
```
impl<'a> From<String> for Cow<'a, str>
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2802)
```
fn from(s: String) -> Cow<'a, str>
```

Converts a [`String`](struct.string "struct std::string::String") into an [`Owned`](../borrow/enum.cow#variant.Owned "borrow::Cow::Owned") variant. No heap allocation is performed, and the string is not copied.

 ##### Example

 
```
let s = "eggplant".to_string();
let s2 = "eggplant".to_string();
assert_eq!(Cow::from(s), Cow::<'static, str>::Owned(s2));
```
 

[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#471-479)
```
impl From<String> for OsString
```

[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#476-478)
```
fn from(s: String) -> OsString
```

Converts a [`String`](struct.string "struct std::string::String") into an [`OsString`](../ffi/struct.osstring "struct std::ffi::OsString").

 This conversion does not allocate or copy memory.

 

[source](https://doc.rust-lang.org/src/std/path.rs.html#1731-1739)
```
impl From<String> for PathBuf
```

[source](https://doc.rust-lang.org/src/std/path.rs.html#1736-1738)
```
fn from(s: String) -> PathBuf
```

Converts a [`String`](struct.string "struct std::string::String") into a [`PathBuf`](../path/struct.pathbuf "struct std::path::PathBuf")

 This conversion does not allocate or copy memory.

 

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1968)1.21.0
```
impl From<String> for Rc<str>
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1980)
```
fn from(v: String) -> Rc<str>
```

Allocate a reference-counted string slice and copy `v` into it.

 ##### Example

 
```
let original: String = "statue".to_owned();
let shared: Rc<str> = Rc::from(original);
assert_eq!("statue", &shared[..]);
```
 

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2854)1.14.0
```
impl From<String> for Vec<u8, Global>
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2869)
```
fn from(string: String) -> Vec<u8, Global> ⓘ
```

Converts the given [`String`](struct.string "struct std::string::String") to a vector [`Vec`](../vec/struct.vec "struct std::vec::Vec") that holds values of type [`u8`](../primitive.u8 "primitive u8").

 ##### Examples

 Basic usage:

 
```
let s1 = String::from("hello world");
let v1 = Vec::from(s1);

for b in v1 {
    println!("{b}");
}
```
 

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2999)1.46.0
```
impl From<char> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#3009)
```
fn from(c: char) -> String
```

Allocates an owned [`String`](struct.string "struct std::string::String") from a single character.

 ##### Example

 
```
let c: char = 'a';
let s: String = String::from(c);
assert_eq!("a", &s[..]);
```
 

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2012)1.17.0
```
impl<'a> FromIterator<&'a char> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2013)
```
fn from_iter<I>(iter: I) -> String
where
    I: IntoIterator<Item = &'a char>,
```
Creates a value from an iterator. [Read more](../iter/trait.fromiterator#tymethod.from_iter)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2022)
```
impl<'a> FromIterator<&'a str> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2023)
```
fn from_iter<I>(iter: I) -> String
where
    I: IntoIterator<Item = &'a str>,
```
Creates a value from an iterator. [Read more](../iter/trait.fromiterator#tymethod.from_iter)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2051)1.45.0
```
impl FromIterator<Box<str, Global>> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2052)
```
fn from_iter<I>(iter: I) -> String
where
    I: IntoIterator<Item = Box<str, Global>>,
```
Creates a value from an iterator. [Read more](../iter/trait.fromiterator#tymethod.from_iter)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2061)1.19.0
```
impl<'a> FromIterator<Cow<'a, str>> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2062)
```
fn from_iter<I>(iter: I) -> String
where
    I: IntoIterator<Item = Cow<'a, str>>,
```
Creates a value from an iterator. [Read more](../iter/trait.fromiterator#tymethod.from_iter)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2847)1.12.0
```
impl<'a> FromIterator<String> for Cow<'a, str>
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2848)
```
fn from_iter<I>(it: I) -> Cow<'a, str>
where
    I: IntoIterator<Item = String>,
```
Creates a value from an iterator. [Read more](../iter/trait.fromiterator#tymethod.from_iter)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2032)1.4.0
```
impl FromIterator<String> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2033)
```
fn from_iter<I>(iter: I) -> String
where
    I: IntoIterator<Item = String>,
```
Creates a value from an iterator. [Read more](../iter/trait.fromiterator#tymethod.from_iter)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2002)
```
impl FromIterator<char> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2003)
```
fn from_iter<I>(iter: I) -> String
where
    I: IntoIterator<Item = char>,
```
Creates a value from an iterator. [Read more](../iter/trait.fromiterator#tymethod.from_iter)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2469)
```
impl FromStr for String
```


```
type Err = Infallible
```
The associated error which can be returned from parsing.
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2472)
```
fn from_str(s: &str) -> Result<String, <String as FromStr>::Err>
```
Parses a string `s` to return a value of this type. [Read more](../str/trait.fromstr#tymethod.from_str)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2275)
```
impl Hash for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2277)
```
fn hash<H>(&self, hasher: &mut H)
where
    H: Hasher,
```
Feeds this value into the given [`Hasher`](../hash/trait.hasher "trait std::hash::Hasher"). [Read more](../hash/trait.hash#tymethod.hash)

[source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#237-239)1.3.0
```
fn hash_slice<H>(data: &[Self], state: &mut H)
where
    H: Hasher,
    Self: Sized,
```
Feeds a slice of this type into the given [`Hasher`](../hash/trait.hasher "trait std::hash::Hasher"). [Read more](../hash/trait.hash#method.hash_slice)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2344)
```
impl Index<Range<usize>> for String
```


```
type Output = str
```
The returned type after indexing.
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2348)
```
fn index(&self, index: Range<usize>) -> &str
```
Performs the indexing (`container[index]`) operation. [Read more](../ops/trait.index#tymethod.index)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2362)
```
impl Index<RangeFrom<usize>> for String
```


```
type Output = str
```
The returned type after indexing.
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2366)
```
fn index(&self, index: RangeFrom<usize>) -> &str
```
Performs the indexing (`container[index]`) operation. [Read more](../ops/trait.index#tymethod.index)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2371)
```
impl Index<RangeFull> for String
```


```
type Output = str
```
The returned type after indexing.
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2375)
```
fn index(&self, _index: RangeFull) -> &str
```
Performs the indexing (`container[index]`) operation. [Read more](../ops/trait.index#tymethod.index)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2380)1.26.0
```
impl Index<RangeInclusive<usize>> for String
```


```
type Output = str
```
The returned type after indexing.
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2384)
```
fn index(&self, index: RangeInclusive<usize>) -> &str
```
Performs the indexing (`container[index]`) operation. [Read more](../ops/trait.index#tymethod.index)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2353)
```
impl Index<RangeTo<usize>> for String
```


```
type Output = str
```
The returned type after indexing.
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2357)
```
fn index(&self, index: RangeTo<usize>) -> &str
```
Performs the indexing (`container[index]`) operation. [Read more](../ops/trait.index#tymethod.index)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2389)1.26.0
```
impl Index<RangeToInclusive<usize>> for String
```


```
type Output = str
```
The returned type after indexing.
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2393)
```
fn index(&self, index: RangeToInclusive<usize>) -> &str
```
Performs the indexing (`container[index]`) operation. [Read more](../ops/trait.index#tymethod.index)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2399)1.3.0
```
impl IndexMut<Range<usize>> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2401)
```
fn index_mut(&mut self, index: Range<usize>) -> &mut str
```
Performs the mutable indexing (`container[index]`) operation. [Read more](../ops/trait.indexmut#tymethod.index_mut)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2413)1.3.0
```
impl IndexMut<RangeFrom<usize>> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2415)
```
fn index_mut(&mut self, index: RangeFrom<usize>) -> &mut str
```
Performs the mutable indexing (`container[index]`) operation. [Read more](../ops/trait.indexmut#tymethod.index_mut)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2420)1.3.0
```
impl IndexMut<RangeFull> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2422)
```
fn index_mut(&mut self, _index: RangeFull) -> &mut str
```
Performs the mutable indexing (`container[index]`) operation. [Read more](../ops/trait.indexmut#tymethod.index_mut)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2427)1.26.0
```
impl IndexMut<RangeInclusive<usize>> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2429)
```
fn index_mut(&mut self, index: RangeInclusive<usize>) -> &mut str
```
Performs the mutable indexing (`container[index]`) operation. [Read more](../ops/trait.indexmut#tymethod.index_mut)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2406)1.3.0
```
impl IndexMut<RangeTo<usize>> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2408)
```
fn index_mut(&mut self, index: RangeTo<usize>) -> &mut str
```
Performs the mutable indexing (`container[index]`) operation. [Read more](../ops/trait.indexmut#tymethod.index_mut)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2434)1.26.0
```
impl IndexMut<RangeToInclusive<usize>> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2436)
```
fn index_mut(&mut self, index: RangeToInclusive<usize>) -> &mut str
```
Performs the mutable indexing (`container[index]`) operation. [Read more](../ops/trait.indexmut#tymethod.index_mut)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#362)
```
impl Ord for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#362)
```
fn cmp(&self, other: &String) -> Ordering
```
This method returns an [`Ordering`](../cmp/enum.ordering "enum std::cmp::Ordering") between `self` and `other`. [Read more](../cmp/trait.ord#tymethod.cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#790-792)1.21.0
```
fn max(self, other: Self) -> Self
where
    Self: Sized,
```
Compares and returns the maximum of two values. [Read more](../cmp/trait.ord#method.max)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#810-812)1.21.0
```
fn min(self, other: Self) -> Self
where
    Self: Sized,
```
Compares and returns the minimum of two values. [Read more](../cmp/trait.ord#method.min)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#835-838)1.50.0
```
fn clamp(self, min: Self, max: Self) -> Self
where
    Self: Sized + PartialOrd<Self>,
```
Restrict a value to a certain interval. [Read more](../cmp/trait.ord#method.clamp)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2241)
```
impl<'a, 'b> PartialEq<&'a str> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2241)
```
fn eq(&self, other: &&'a str) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2241)
```
fn ne(&self, other: &&'a str) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2247)
```
impl<'a, 'b> PartialEq<Cow<'a, str>> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2247)
```
fn eq(&self, other: &Cow<'a, str>) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2247)
```
fn ne(&self, other: &Cow<'a, str>) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2241)
```
impl<'a, 'b> PartialEq<String> for &'a str
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2241)
```
fn eq(&self, other: &String) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2241)
```
fn ne(&self, other: &String) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2247)
```
impl<'a, 'b> PartialEq<String> for Cow<'a, str>
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2247)
```
fn eq(&self, other: &String) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2247)
```
fn ne(&self, other: &String) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#362)
```
impl PartialEq<String> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#362)
```
fn eq(&self, other: &String) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#226)
```
fn ne(&self, other: &Rhs) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2240)
```
impl<'a, 'b> PartialEq<String> for str
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2240)
```
fn eq(&self, other: &String) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2240)
```
fn ne(&self, other: &String) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2240)
```
impl<'a, 'b> PartialEq<str> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2240)
```
fn eq(&self, other: &str) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2240)
```
fn ne(&self, other: &str) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#362)
```
impl PartialOrd<String> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#362)
```
fn partial_cmp(&self, other: &String) -> Option<Ordering>
```
This method returns an ordering between `self` and `other` values if one exists. [Read more](../cmp/trait.partialord#tymethod.partial_cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1067)
```
fn lt(&self, other: &Rhs) -> bool
```
This method tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](../cmp/trait.partialord#method.lt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1084)
```
fn le(&self, other: &Rhs) -> bool
```
This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](../cmp/trait.partialord#method.le)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1100)
```
fn gt(&self, other: &Rhs) -> bool
```
This method tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](../cmp/trait.partialord#method.gt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1117)
```
fn ge(&self, other: &Rhs) -> bool
```
This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](../cmp/trait.partialord#method.ge)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2177)
```
impl<'a, 'b> Pattern<'a> for &'b String
```

A convenience impl that delegates to the impl for `&str`.

 #### Examples

 
```
assert_eq!(String::from("Hello world").find("world"), Some(6));
```
 


```
type Searcher = <&'b str as Pattern<'a>>::Searcher
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Associated searcher for this pattern
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2180)
```
fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Constructs the associated searcher from `self` and the `haystack` to search in.
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2185)
```
fn is_contained_in(self, haystack: &'a str) -> bool
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Checks whether the pattern matches anywhere in the haystack
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2190)
```
fn is_prefix_of(self, haystack: &'a str) -> bool
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Checks whether the pattern matches at the front of the haystack
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2195)
```
fn strip_prefix_of(self, haystack: &'a str) -> Option<&'a str>
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Removes the pattern from the front of haystack, if it matches.
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2200)
```
fn is_suffix_of(self, haystack: &'a str) -> bool
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Checks whether the pattern matches at the back of the haystack
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2205)
```
fn strip_suffix_of(self, haystack: &'a str) -> Option<&'a str>
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Removes the pattern from the back of haystack, if it matches.

[source](https://doc.rust-lang.org/src/std/net/socket_addr.rs.html#310-315)1.16.0
```
impl ToSocketAddrs for String
```


```
type Iter = IntoIter<SocketAddr, Global>
```
Returned iterator over socket addresses which this type may correspond to.
[source](https://doc.rust-lang.org/src/std/net/socket_addr.rs.html#312-314)
```
fn to_socket_addrs(&self) -> Result<IntoIter<SocketAddr>>
```
Converts this object to an iterator of resolved [`SocketAddr`](../net/enum.socketaddr "enum std::net::SocketAddr")s. [Read more](../net/trait.tosocketaddrs#tymethod.to_socket_addrs)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2619)1.17.0
```
impl ToString for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2621)
```
fn to_string(&self) -> String
```
Converts the given value to a `String`. [Read more](trait.tostring#tymethod.to_string)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2876)
```
impl Write for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2878)
```
fn write_str(&mut self, s: &str) -> Result<(), Error>
```
Writes a string slice into this writer, returning whether the write succeeded. [Read more](../fmt/trait.write#tymethod.write_str)

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2884)
```
fn write_char(&mut self, c: char) -> Result<(), Error>
```
Writes a [`char`](../primitive.char "primitive char") into this writer, returning whether the write succeeded. [Read more](../fmt/trait.write#method.write_char)

[source](https://doc.rust-lang.org/src/core/fmt/mod.rs.html#191)
```
fn write_fmt(&mut self, args: Arguments<'_>) -> Result<(), Error>
```
Glue for usage of the [`write!`](../macro.write "macro std::write") macro with implementors of this trait. [Read more](../fmt/trait.write#method.write_fmt)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#362)
```
impl Eq for String
```
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#362)
```
impl StructuralEq for String
```
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#362)
```
impl StructuralPartialEq for String
```


Auto Trait Implementations
--------------------------




```
impl RefUnwindSafe for String
```

```
impl Send for String
```

```
impl Sync for String
```

```
impl Unpin for String
```

```
impl UnwindSafe for String
```


Blanket Implementations
-----------------------



[source](https://doc.rust-lang.org/src/core/any.rs.html#200)
```
impl<T> Any for T
where
    T: 'static + ?Sized,
```

[source](https://doc.rust-lang.org/src/core/any.rs.html#201)
```
fn type_id(&self) -> TypeId
```
Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#208)
```
impl<T> Borrow<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#210)
```
fn borrow(&self) -> &T
```
Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#216)
```
impl<T> BorrowMut<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#217)
```
fn borrow_mut(&mut self) -> &mut T
```
Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#723)
```
impl<T> From<T> for T
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#726)
```
fn from(t: T) -> T
```

Returns the argument unchanged.

 

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#707)
```
impl<T, U> Into<U> for T
where
    U: From<T>,
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#716)
```
fn into(self) -> U
```

Calls `U::from(self)`.

 That is, this conversion is whatever the implementation of `[From](../convert/trait.from "trait std::convert::From")<T> for U` chooses to do.

 

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#82)
```
impl<T> ToOwned for T
where
    T: Clone,
```


```
type Owned = T
```
The resulting type after obtaining ownership.
[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#87)
```
fn to_owned(&self) -> T
```
Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned)

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#91)
```
fn clone_into(&self, target: &mut T)
```
Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2513)
```
impl<T> ToString for T
where
    T: Display + ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2519)
```
default fn to_string(&self) -> String
```
Converts the given value to a `String`. [Read more](trait.tostring#tymethod.to_string)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#763)
```
impl<T, U> TryFrom<U> for T
where
    U: Into<T>,
```


```
type Error = Infallible
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#770)
```
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#748)
```
impl<T, U> TryInto<U> for T
where
    U: TryFrom<T>,
```


```
type Error = <U as TryFrom<T>>::Error
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#755)
```
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
```
Performs the conversion.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/string/struct.String.html>

Enum std::result::Result
========================



```
pub enum Result<T, E> {
    Ok(T),
    Err(E),
}
```

`Result` is a type that represents either success ([`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok")) or failure ([`Err`](enum.result#variant.Err "variant std::result::Result::Err")).

 See the [module documentation](index "mod std::result") for details.

 Variants
--------




```
Ok(T)
```

Contains the success value

 

```
Err(E)
```

Contains the error value

 

Implementations
---------------



[source](https://doc.rust-lang.org/src/core/result.rs.html#518)
```
impl<T, E> Result<T, E>
```

[source](https://doc.rust-lang.org/src/core/result.rs.html#538)const: 1.48.0
```
pub const fn is_ok(&self) -> bool
```

Returns `true` if the result is [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok").

 ##### Examples

 
```
let x: Result<i32, &str> = Ok(-3);
assert_eq!(x.is_ok(), true);

let x: Result<i32, &str> = Err("Some error message");
assert_eq!(x.is_ok(), false);
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#559)1.70.0
```
pub fn is_ok_and(self, f: impl FnOnce(T) -> bool) -> bool
```

Returns `true` if the result is [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok") and the value inside of it matches a predicate.

 ##### Examples

 
```
let x: Result<u32, &str> = Ok(2);
assert_eq!(x.is_ok_and(|x| x > 1), true);

let x: Result<u32, &str> = Ok(0);
assert_eq!(x.is_ok_and(|x| x > 1), false);

let x: Result<u32, &str> = Err("hey");
assert_eq!(x.is_ok_and(|x| x > 1), false);
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#581)const: 1.48.0
```
pub const fn is_err(&self) -> bool
```

Returns `true` if the result is [`Err`](enum.result#variant.Err "variant std::result::Result::Err").

 ##### Examples

 
```
let x: Result<i32, &str> = Ok(-3);
assert_eq!(x.is_err(), false);

let x: Result<i32, &str> = Err("Some error message");
assert_eq!(x.is_err(), true);
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#604)1.70.0
```
pub fn is_err_and(self, f: impl FnOnce(E) -> bool) -> bool
```

Returns `true` if the result is [`Err`](enum.result#variant.Err "variant std::result::Result::Err") and the value inside of it matches a predicate.

 ##### Examples

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

let x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, "!"));
assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);

let x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, "!"));
assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);

let x: Result<u32, Error> = Ok(123);
assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#631)
```
pub fn ok(self) -> Option<T>
```

Converts from `Result<T, E>` to [`Option<T>`](../option/enum.option "enum std::option::Option").

 Converts `self` into an [`Option<T>`](../option/enum.option "enum std::option::Option"), consuming `self`, and discarding the error, if any.

 ##### Examples

 
```
let x: Result<u32, &str> = Ok(2);
assert_eq!(x.ok(), Some(2));

let x: Result<u32, &str> = Err("Nothing here");
assert_eq!(x.ok(), None);
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#654)
```
pub fn err(self) -> Option<E>
```

Converts from `Result<T, E>` to [`Option<E>`](../option/enum.option "enum std::option::Option").

 Converts `self` into an [`Option<E>`](../option/enum.option "enum std::option::Option"), consuming `self`, and discarding the success value, if any.

 ##### Examples

 
```
let x: Result<u32, &str> = Ok(2);
assert_eq!(x.err(), None);

let x: Result<u32, &str> = Err("Nothing here");
assert_eq!(x.err(), Some("Nothing here"));
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#682)const: 1.48.0
```
pub const fn as_ref(&self) -> Result<&T, &E>
```

Converts from `&Result<T, E>` to `Result<&T, &E>`.

 Produces a new `Result`, containing a reference into the original, leaving the original in place.

 ##### Examples

 
```
let x: Result<u32, &str> = Ok(2);
assert_eq!(x.as_ref(), Ok(&2));

let x: Result<u32, &str> = Err("Error");
assert_eq!(x.as_ref(), Err(&"Error"));
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#712)const: [unstable](https://github.com/rust-lang/rust/issues/82814 "Tracking issue for const_result")
```
pub fn as_mut(&mut self) -> Result<&mut T, &mut E>
```

Converts from `&mut Result<T, E>` to `Result<&mut T, &mut E>`.

 ##### Examples

 
```
fn mutate(r: &mut Result<i32, i32>) {
    match r.as_mut() {
        Ok(v) => *v = 42,
        Err(e) => *e = 0,
    }
}

let mut x: Result<i32, i32> = Ok(2);
mutate(&mut x);
assert_eq!(x.unwrap(), 42);

let mut x: Result<i32, i32> = Err(13);
mutate(&mut x);
assert_eq!(x.unwrap_err(), 0);
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#744)
```
pub fn map<U, F>(self, op: F) -> Result<U, E>
where
    F: FnOnce(T) -> U,
```

Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a contained [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok") value, leaving an [`Err`](enum.result#variant.Err "variant std::result::Result::Err") value untouched.

 This function can be used to compose the results of two functions.

 ##### Examples

 Print the numbers on each line of a string multiplied by two.

 
```
let line = "1\n2\n3\n4\n";

for num in line.lines() {
    match num.parse::<i32>().map(|i| i * 2) {
        Ok(n) => println!("{n}"),
        Err(..) => {}
    }
}
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#771)1.41.0
```
pub fn map_or<U, F>(self, default: U, f: F) -> U
where
    F: FnOnce(T) -> U,
```

Returns the provided default (if [`Err`](enum.result#variant.Err "variant std::result::Result::Err")), or applies a function to the contained value (if [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok")),

 Arguments passed to `map_or` are eagerly evaluated; if you are passing the result of a function call, it is recommended to use [`map_or_else`](enum.result#method.map_or_else "method std::result::Result::map_or_else"), which is lazily evaluated.

 ##### Examples

 
```
let x: Result<_, &str> = Ok("foo");
assert_eq!(x.map_or(42, |v| v.len()), 3);

let x: Result<&str, _> = Err("bar");
assert_eq!(x.map_or(42, |v| v.len()), 42);
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#798)1.41.0
```
pub fn map_or_else<U, D, F>(self, default: D, f: F) -> U
where
    D: FnOnce(E) -> U,
    F: FnOnce(T) -> U,
```

Maps a `Result<T, E>` to `U` by applying fallback function `default` to a contained [`Err`](enum.result#variant.Err "variant std::result::Result::Err") value, or function `f` to a contained [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok") value.

 This function can be used to unpack a successful result while handling an error.

 ##### Examples

 
```
let k = 21;

let x : Result<_, &str> = Ok("foo");
assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);

let x : Result<&str, _> = Err("bar");
assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#825)
```
pub fn map_err<F, O>(self, op: O) -> Result<T, F>
where
    O: FnOnce(E) -> F,
```

Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a contained [`Err`](enum.result#variant.Err "variant std::result::Result::Err") value, leaving an [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok") value untouched.

 This function can be used to pass through a successful result while handling an error.

 ##### Examples

 
```
fn stringify(x: u32) -> String { format!("error code: {x}") }

let x: Result<u32, u32> = Ok(2);
assert_eq!(x.map_err(stringify), Ok(2));

let x: Result<u32, u32> = Err(13);
assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#847)
```
pub fn inspect<F>(self, f: F) -> Result<T, E>
where
    F: FnOnce(&T),
```

🔬This is a nightly-only experimental API. (`result_option_inspect` [#91345](https://github.com/rust-lang/rust/issues/91345))

Calls the provided closure with a reference to the contained value (if [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok")).

 ##### Examples

 
```
#![feature(result_option_inspect)]

let x: u8 = "4"
    .parse::<u8>()
    .inspect(|x| println!("original: {x}"))
    .map(|x| x.pow(3))
    .expect("failed to parse number");
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#871)
```
pub fn inspect_err<F>(self, f: F) -> Result<T, E>
where
    F: FnOnce(&E),
```

🔬This is a nightly-only experimental API. (`result_option_inspect` [#91345](https://github.com/rust-lang/rust/issues/91345))

Calls the provided closure with a reference to the contained error (if [`Err`](enum.result#variant.Err "variant std::result::Result::Err")).

 ##### Examples

 
```
#![feature(result_option_inspect)]

use std::{fs, io};

fn read() -> io::Result<String> {
    fs::read_to_string("address.txt")
        .inspect_err(|e| eprintln!("failed to read file: {e}"))
}
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#897-899)1.47.0
```
pub fn as_deref(&self) -> Result<&<T as Deref>::Target, &E>
where
    T: Deref,
```

Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&<T as Deref>::Target, &E>`.

 Coerces the [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok") variant of the original [`Result`](enum.result "enum std::result::Result") via [`Deref`](../ops/trait.deref "trait std::ops::Deref") and returns the new [`Result`](enum.result "enum std::result::Result").

 ##### Examples

 
```
let x: Result<String, u32> = Ok("hello".to_string());
let y: Result<&str, &u32> = Ok("hello");
assert_eq!(x.as_deref(), y);

let x: Result<String, u32> = Err(42);
let y: Result<&str, &u32> = Err(&42);
assert_eq!(x.as_deref(), y);
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#924-926)1.47.0
```
pub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>
where
    T: DerefMut,
```

Converts from `Result<T, E>` (or `&mut Result<T, E>`) to `Result<&mut <T as DerefMut>::Target, &mut E>`.

 Coerces the [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok") variant of the original [`Result`](enum.result "enum std::result::Result") via [`DerefMut`](../ops/trait.derefmut "trait std::ops::DerefMut") and returns the new [`Result`](enum.result "enum std::result::Result").

 ##### Examples

 
```
let mut s = "HELLO".to_string();
let mut x: Result<String, u32> = Ok("hello".to_string());
let y: Result<&mut str, &mut u32> = Ok(&mut s);
assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);

let mut i = 42;
let mut x: Result<String, u32> = Err(42);
let y: Result<&mut str, &mut u32> = Err(&mut i);
assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#950)
```
pub fn iter(&self) -> Iter<'_, T> ⓘ
```

Returns an iterator over the possibly contained value.

 The iterator yields one value if the result is [`Result::Ok`](enum.result#variant.Ok "variant std::result::Result::Ok"), otherwise none.

 ##### Examples

 
```
let x: Result<u32, &str> = Ok(7);
assert_eq!(x.iter().next(), Some(&7));

let x: Result<u32, &str> = Err("nothing!");
assert_eq!(x.iter().next(), None);
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#973)
```
pub fn iter_mut(&mut self) -> IterMut<'_, T> ⓘ
```

Returns a mutable iterator over the possibly contained value.

 The iterator yields one value if the result is [`Result::Ok`](enum.result#variant.Ok "variant std::result::Result::Ok"), otherwise none.

 ##### Examples

 
```
let mut x: Result<u32, &str> = Ok(7);
match x.iter_mut().next() {
    Some(v) => *v = 40,
    None => {},
}
assert_eq!(x, Ok(40));

let mut x: Result<u32, &str> = Err("nothing!");
assert_eq!(x.iter_mut().next(), None);
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#1027-1029)1.4.0
```
pub fn expect(self, msg: &str) -> T
where
    E: Debug,
```

Returns the contained [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok") value, consuming the `self` value.

 Because this function may panic, its use is generally discouraged. Instead, prefer to use pattern matching and handle the [`Err`](enum.result#variant.Err "variant std::result::Result::Err") case explicitly, or call [`unwrap_or`](enum.result#method.unwrap_or "method std::result::Result::unwrap_or"), [`unwrap_or_else`](enum.result#method.unwrap_or_else "method std::result::Result::unwrap_or_else"), or [`unwrap_or_default`](enum.result#method.unwrap_or_default "method std::result::Result::unwrap_or_default").

 ##### Panics

 Panics if the value is an [`Err`](enum.result#variant.Err "variant std::result::Result::Err"), with a panic message including the passed message, and the content of the [`Err`](enum.result#variant.Err "variant std::result::Result::Err").

 ##### Examples

 ⓘ
```
let x: Result<u32, &str> = Err("emergency failure");
x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
```

 ##### Recommended Message Style

 We recommend that `expect` messages are used to describe the reason you *expect* the `Result` should be `Ok`.

 ⓘ
```
let path = std::env::var("IMPORTANT_PATH")
    .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`");
```

 **Hint**: If you’re having trouble remembering how to phrase expect 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”.

 For more detail on expect message styles and the reasoning behind our recommendation please refer to the section on [“Common Message Styles”](../error/index#common-message-styles) in the [`std::error`](../error/index) module docs.

 
[source](https://doc.rust-lang.org/src/core/result.rs.html#1070-1072)
```
pub fn unwrap(self) -> T
where
    E: Debug,
```

Returns the contained [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok") value, consuming the `self` value.

 Because this function may panic, its use is generally discouraged. Instead, prefer to use pattern matching and handle the [`Err`](enum.result#variant.Err "variant std::result::Result::Err") case explicitly, or call [`unwrap_or`](enum.result#method.unwrap_or "method std::result::Result::unwrap_or"), [`unwrap_or_else`](enum.result#method.unwrap_or_else "method std::result::Result::unwrap_or_else"), or [`unwrap_or_default`](enum.result#method.unwrap_or_default "method std::result::Result::unwrap_or_default").

 ##### Panics

 Panics if the value is an [`Err`](enum.result#variant.Err "variant std::result::Result::Err"), with a panic message provided by the [`Err`](enum.result#variant.Err "variant std::result::Result::Err")’s value.

 ##### Examples

 Basic usage:

 
```
let x: Result<u32, &str> = Ok(2);
assert_eq!(x.unwrap(), 2);
```
 ⓘ
```
let x: Result<u32, &str> = Err("emergency failure");
x.unwrap(); // panics with `emergency failure`
```

 
[source](https://doc.rust-lang.org/src/core/result.rs.html#1107-1109)1.16.0
```
pub fn unwrap_or_default(self) -> T
where
    T: Default,
```

Returns the contained [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok") value or a default

 Consumes the `self` argument then, if [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok"), returns the contained value, otherwise if [`Err`](enum.result#variant.Err "variant std::result::Result::Err"), returns the default value for that type.

 ##### Examples

 Converts a string to an integer, turning poorly-formed strings into 0 (the default value for integers). [`parse`](../primitive.str#method.parse "method str::parse") converts a string to any other type that implements [`FromStr`](../str/trait.fromstr "trait std::str::FromStr"), returning an [`Err`](enum.result#variant.Err "variant std::result::Result::Err") on error.

 
```
let good_year_from_input = "1909";
let bad_year_from_input = "190blarg";
let good_year = good_year_from_input.parse().unwrap_or_default();
let bad_year = bad_year_from_input.parse().unwrap_or_default();

assert_eq!(1909, good_year);
assert_eq!(0, bad_year);
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#1134-1136)1.17.0
```
pub fn expect_err(self, msg: &str) -> E
where
    T: Debug,
```

Returns the contained [`Err`](enum.result#variant.Err "variant std::result::Result::Err") value, consuming the `self` value.

 ##### Panics

 Panics if the value is an [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok"), with a panic message including the passed message, and the content of the [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok").

 ##### Examples

 ⓘ
```
let x: Result<u32, &str> = Ok(10);
x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
```

 
[source](https://doc.rust-lang.org/src/core/result.rs.html#1165-1167)
```
pub fn unwrap_err(self) -> E
where
    T: Debug,
```

Returns the contained [`Err`](enum.result#variant.Err "variant std::result::Result::Err") value, consuming the `self` value.

 ##### Panics

 Panics if the value is an [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok"), with a custom panic message provided by the [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok")’s value.

 ##### Examples

 ⓘ
```
let x: Result<u32, &str> = Ok(2);
x.unwrap_err(); // panics with `2`
```

 
```
let x: Result<u32, &str> = Err("emergency failure");
assert_eq!(x.unwrap_err(), "emergency failure");
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#1200-1202)
```
pub fn into_ok(self) -> T
where
    E: Into<!>,
```

🔬This is a nightly-only experimental API. (`unwrap_infallible` [#61695](https://github.com/rust-lang/rust/issues/61695))

Returns the contained [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok") value, but never panics.

 Unlike [`unwrap`](enum.result#method.unwrap "method std::result::Result::unwrap"), this method is known to never panic on the result types it is implemented for. Therefore, it can be used instead of `unwrap` as a maintainability safeguard that will fail to compile if the error type of the `Result` is later changed to an error that can actually occur.

 ##### Examples

 
```

fn only_good_news() -> Result<String, !> {
    Ok("this is fine".into())
}

let s: String = only_good_news().into_ok();
println!("{s}");
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#1235-1237)
```
pub fn into_err(self) -> E
where
    T: Into<!>,
```

🔬This is a nightly-only experimental API. (`unwrap_infallible` [#61695](https://github.com/rust-lang/rust/issues/61695))

Returns the contained [`Err`](enum.result#variant.Err "variant std::result::Result::Err") value, but never panics.

 Unlike [`unwrap_err`](enum.result#method.unwrap_err "method std::result::Result::unwrap_err"), this method is known to never panic on the result types it is implemented for. Therefore, it can be used instead of `unwrap_err` as a maintainability safeguard that will fail to compile if the ok type of the `Result` is later changed to a type that can actually occur.

 ##### Examples

 
```

fn only_bad_news() -> Result<!, String> {
    Err("Oops, it failed".into())
}

let error: String = only_bad_news().into_err();
println!("{error}");
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#1278)
```
pub fn and<U>(self, res: Result<U, E>) -> Result<U, E>
```

Returns `res` if the result is [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok"), otherwise returns the [`Err`](enum.result#variant.Err "variant std::result::Result::Err") value of `self`.

 Arguments passed to `and` are eagerly evaluated; if you are passing the result of a function call, it is recommended to use [`and_then`](enum.result#method.and_then "method std::result::Result::and_then"), which is lazily evaluated.

 ##### Examples

 
```
let x: Result<u32, &str> = Ok(2);
let y: Result<&str, &str> = Err("late error");
assert_eq!(x.and(y), Err("late error"));

let x: Result<u32, &str> = Err("early error");
let y: Result<&str, &str> = Ok("foo");
assert_eq!(x.and(y), Err("early error"));

let x: Result<u32, &str> = Err("not a 2");
let y: Result<&str, &str> = Err("late error");
assert_eq!(x.and(y), Err("not a 2"));

let x: Result<u32, &str> = Ok(2);
let y: Result<&str, &str> = Ok("different result type");
assert_eq!(x.and(y), Ok("different result type"));
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#1317)
```
pub fn and_then<U, F>(self, op: F) -> Result<U, E>
where
    F: FnOnce(T) -> Result<U, E>,
```

Calls `op` if the result is [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok"), otherwise returns the [`Err`](enum.result#variant.Err "variant std::result::Result::Err") value of `self`.

 This function can be used for control flow based on `Result` values.

 ##### Examples

 
```
fn sq_then_to_string(x: u32) -> Result<String, &'static str> {
    x.checked_mul(x).map(|sq| sq.to_string()).ok_or("overflowed")
}

assert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));
assert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err("overflowed"));
assert_eq!(Err("not a number").and_then(sq_then_to_string), Err("not a number"));
```
 Often used to chain fallible operations that may return [`Err`](enum.result#variant.Err "variant std::result::Result::Err").

 
```
use std::{io::ErrorKind, path::Path};

// Note: on Windows "/" maps to "C:\"
let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified());
assert!(root_modified_time.is_ok());

let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified());
assert!(should_fail.is_err());
assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#1353)
```
pub fn or<F>(self, res: Result<T, F>) -> Result<T, F>
```

Returns `res` if the result is [`Err`](enum.result#variant.Err "variant std::result::Result::Err"), otherwise returns the [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok") value of `self`.

 Arguments passed to `or` are eagerly evaluated; if you are passing the result of a function call, it is recommended to use [`or_else`](enum.result#method.or_else "method std::result::Result::or_else"), which is lazily evaluated.

 ##### Examples

 
```
let x: Result<u32, &str> = Ok(2);
let y: Result<u32, &str> = Err("late error");
assert_eq!(x.or(y), Ok(2));

let x: Result<u32, &str> = Err("early error");
let y: Result<u32, &str> = Ok(2);
assert_eq!(x.or(y), Ok(2));

let x: Result<u32, &str> = Err("not a 2");
let y: Result<u32, &str> = Err("late error");
assert_eq!(x.or(y), Err("late error"));

let x: Result<u32, &str> = Ok(2);
let y: Result<u32, &str> = Ok(100);
assert_eq!(x.or(y), Ok(2));
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#1378)
```
pub fn or_else<F, O>(self, op: O) -> Result<T, F>
where
    O: FnOnce(E) -> Result<T, F>,
```

Calls `op` if the result is [`Err`](enum.result#variant.Err "variant std::result::Result::Err"), otherwise returns the [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok") value of `self`.

 This function can be used for control flow based on result values.

 ##### Examples

 
```
fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
fn err(x: u32) -> Result<u32, u32> { Err(x) }

assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#1405)
```
pub fn unwrap_or(self, default: T) -> T
```

Returns the contained [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok") value or a provided default.

 Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing the result of a function call, it is recommended to use [`unwrap_or_else`](enum.result#method.unwrap_or_else "method std::result::Result::unwrap_or_else"), which is lazily evaluated.

 ##### Examples

 
```
let default = 2;
let x: Result<u32, &str> = Ok(9);
assert_eq!(x.unwrap_or(default), 9);

let x: Result<u32, &str> = Err("error");
assert_eq!(x.unwrap_or(default), default);
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#1425)
```
pub fn unwrap_or_else<F>(self, op: F) -> T
where
    F: FnOnce(E) -> T,
```

Returns the contained [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok") value or computes it from a closure.

 ##### Examples

 
```
fn count(x: &str) -> usize { x.len() }

assert_eq!(Ok(2).unwrap_or_else(count), 2);
assert_eq!(Err("foo").unwrap_or_else(count), 3);
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#1455)1.58.0
```
pub unsafe fn unwrap_unchecked(self) -> T
```

Returns the contained [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok") value, consuming the `self` value, without checking that the value is not an [`Err`](enum.result#variant.Err "variant std::result::Result::Err").

 ##### Safety

 Calling this method on an [`Err`](enum.result#variant.Err "variant std::result::Result::Err") is *[undefined behavior](../../reference/behavior-considered-undefined)*.

 ##### Examples

 
```
let x: Result<u32, &str> = Ok(2);
assert_eq!(unsafe { x.unwrap_unchecked() }, 2);
```
 
```
let x: Result<u32, &str> = Err("emergency failure");
unsafe { x.unwrap_unchecked(); } // Undefined behavior!
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#1487)1.58.0
```
pub unsafe fn unwrap_err_unchecked(self) -> E
```

Returns the contained [`Err`](enum.result#variant.Err "variant std::result::Result::Err") value, consuming the `self` value, without checking that the value is not an [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok").

 ##### Safety

 Calling this method on an [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok") is *[undefined behavior](../../reference/behavior-considered-undefined)*.

 ##### Examples

 
```
let x: Result<u32, &str> = Ok(2);
unsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
```
 
```
let x: Result<u32, &str> = Err("emergency failure");
assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure");
```
 

[source](https://doc.rust-lang.org/src/core/result.rs.html#1497)
```
impl<T, E> Result<&T, E>
```

[source](https://doc.rust-lang.org/src/core/result.rs.html#1512-1514)1.59.0
```
pub fn copied(self) -> Result<T, E>
where
    T: Copy,
```

Maps a `Result<&T, E>` to a `Result<T, E>` by copying the contents of the `Ok` part.

 ##### Examples

 
```
let val = 12;
let x: Result<&i32, i32> = Ok(&val);
assert_eq!(x, Ok(&12));
let copied = x.copied();
assert_eq!(copied, Ok(12));
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#1533-1535)1.59.0
```
pub fn cloned(self) -> Result<T, E>
where
    T: Clone,
```

Maps a `Result<&T, E>` to a `Result<T, E>` by cloning the contents of the `Ok` part.

 ##### Examples

 
```
let val = 12;
let x: Result<&i32, i32> = Ok(&val);
assert_eq!(x, Ok(&12));
let cloned = x.cloned();
assert_eq!(cloned, Ok(12));
```
 

[source](https://doc.rust-lang.org/src/core/result.rs.html#1541)
```
impl<T, E> Result<&mut T, E>
```

[source](https://doc.rust-lang.org/src/core/result.rs.html#1556-1558)1.59.0
```
pub fn copied(self) -> Result<T, E>
where
    T: Copy,
```

Maps a `Result<&mut T, E>` to a `Result<T, E>` by copying the contents of the `Ok` part.

 ##### Examples

 
```
let mut val = 12;
let x: Result<&mut i32, i32> = Ok(&mut val);
assert_eq!(x, Ok(&mut 12));
let copied = x.copied();
assert_eq!(copied, Ok(12));
```
 
[source](https://doc.rust-lang.org/src/core/result.rs.html#1577-1579)1.59.0
```
pub fn cloned(self) -> Result<T, E>
where
    T: Clone,
```

Maps a `Result<&mut T, E>` to a `Result<T, E>` by cloning the contents of the `Ok` part.

 ##### Examples

 
```
let mut val = 12;
let x: Result<&mut i32, i32> = Ok(&mut val);
assert_eq!(x, Ok(&mut 12));
let cloned = x.cloned();
assert_eq!(cloned, Ok(12));
```
 

[source](https://doc.rust-lang.org/src/core/result.rs.html#1585)
```
impl<T, E> Result<Option<T>, E>
```

[source](https://doc.rust-lang.org/src/core/result.rs.html#1604)1.33.0 (const: [unstable](https://github.com/rust-lang/rust/issues/82814 "Tracking issue for const_result"))
```
pub fn transpose(self) -> Option<Result<T, E>>
```

Transposes a `Result` of an `Option` into an `Option` of a `Result`.

 `Ok(None)` will be mapped to `None`. `Ok(Some(_))` and `Err(_)` will be mapped to `Some(Ok(_))` and `Some(Err(_))`.

 ##### Examples

 
```
#[derive(Debug, Eq, PartialEq)]
struct SomeErr;

let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
assert_eq!(x.transpose(), y);
```
 

[source](https://doc.rust-lang.org/src/core/result.rs.html#1613)
```
impl<T, E> Result<Result<T, E>, E>
```

[source](https://doc.rust-lang.org/src/core/result.rs.html#1640)
```
pub fn flatten(self) -> Result<T, E>
```

🔬This is a nightly-only experimental API. (`result_flattening` [#70142](https://github.com/rust-lang/rust/issues/70142))

Converts from `Result<Result<T, E>, E>` to `Result<T, E>`

 ##### Examples

 
```
#![feature(result_flattening)]
let x: Result<Result<&'static str, u32>, u32> = Ok(Ok("hello"));
assert_eq!(Ok("hello"), x.flatten());

let x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));
assert_eq!(Err(6), x.flatten());

let x: Result<Result<&'static str, u32>, u32> = Err(6);
assert_eq!(Err(6), x.flatten());
```
 Flattening only removes one level of nesting at a time:

 
```
#![feature(result_flattening)]
let x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok("hello")));
assert_eq!(Ok(Ok("hello")), x.flatten());
assert_eq!(Ok("hello"), x.flatten().flatten());
```
 


Trait Implementations
---------------------



[source](https://doc.rust-lang.org/src/core/result.rs.html#1671)
```
impl<T, E> Clone for Result<T, E>
where
    T: Clone,
    E: Clone,
```

[source](https://doc.rust-lang.org/src/core/result.rs.html#1677)
```
fn clone(&self) -> Result<T, E>
```
Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone)

[source](https://doc.rust-lang.org/src/core/result.rs.html#1685)
```
fn clone_from(&mut self, source: &Result<T, E>)
```
Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from)


[source](https://doc.rust-lang.org/src/core/result.rs.html#498)
```
impl<T, E> Debug for Result<T, E>
where
    T: Debug,
    E: Debug,
```

[source](https://doc.rust-lang.org/src/core/result.rs.html#498)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt)


[source](https://doc.rust-lang.org/src/core/result.rs.html#1887)
```
impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>
where
    V: FromIterator<A>,
```

[source](https://doc.rust-lang.org/src/core/result.rs.html#1931)
```
fn from_iter<I>(iter: I) -> Result<V, E>
where
    I: IntoIterator<Item = Result<A, E>>,
```

Takes each element in the `Iterator`: if it is an `Err`, no further elements are taken, and the `Err` is returned. Should no `Err` occur, a container with the values of each `Result` is returned.

 Here is an example which increments every integer in a vector, checking for overflow:

 
```
let v = vec![1, 2];
let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
    x.checked_add(1).ok_or("Overflow!")
).collect();
assert_eq!(res, Ok(vec![2, 3]));
```
 Here is another example that tries to subtract one from another list of integers, this time checking for underflow:

 
```
let v = vec![1, 2, 0];
let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
    x.checked_sub(1).ok_or("Underflow!")
).collect();
assert_eq!(res, Err("Underflow!"));
```
 Here is a variation on the previous example, showing that no further elements are taken from `iter` after the first `Err`.

 
```
let v = vec![3, 2, 1, 10];
let mut shared = 0;
let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {
    shared += x;
    x.checked_sub(2).ok_or("Underflow!")
}).collect();
assert_eq!(res, Err("Underflow!"));
assert_eq!(shared, 6);
```
 Since the third element caused an underflow, no further elements were taken, so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.

 

[source](https://doc.rust-lang.org/src/core/task/poll.rs.html#283-284)
```
impl<T, E, F> FromResidual<Result<Infallible, E>> for Poll<Option<Result<T, F>>>
where
    F: From<E>,
```

[source](https://doc.rust-lang.org/src/core/task/poll.rs.html#287)
```
fn from_residual(x: Result<Infallible, E>) -> Poll<Option<Result<T, F>>>
```

🔬This is a nightly-only experimental API. (`try_trait_v2` [#84277](https://github.com/rust-lang/rust/issues/84277))
Constructs the type from a compatible `Residual` type. [Read more](../ops/trait.fromresidual#tymethod.from_residual)


[source](https://doc.rust-lang.org/src/core/task/poll.rs.html#252)
```
impl<T, E, F> FromResidual<Result<Infallible, E>> for Poll<Result<T, F>>
where
    F: From<E>,
```

[source](https://doc.rust-lang.org/src/core/task/poll.rs.html#254)
```
fn from_residual(x: Result<Infallible, E>) -> Poll<Result<T, F>>
```

🔬This is a nightly-only experimental API. (`try_trait_v2` [#84277](https://github.com/rust-lang/rust/issues/84277))
Constructs the type from a compatible `Residual` type. [Read more](../ops/trait.fromresidual#tymethod.from_residual)


[source](https://doc.rust-lang.org/src/core/result.rs.html#1956)
```
impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>
where
    F: From<E>,
```

[source](https://doc.rust-lang.org/src/core/result.rs.html#1959)
```
fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
```

🔬This is a nightly-only experimental API. (`try_trait_v2` [#84277](https://github.com/rust-lang/rust/issues/84277))
Constructs the type from a compatible `Residual` type. [Read more](../ops/trait.fromresidual#tymethod.from_residual)


[source](https://doc.rust-lang.org/src/core/result.rs.html#1967)
```
impl<T, E, F> FromResidual<Yeet<E>> for Result<T, F>
where
    F: From<E>,
```

[source](https://doc.rust-lang.org/src/core/result.rs.html#1969)
```
fn from_residual(_: Yeet<E>) -> Result<T, F>
```

🔬This is a nightly-only experimental API. (`try_trait_v2` [#84277](https://github.com/rust-lang/rust/issues/84277))
Constructs the type from a compatible `Residual` type. [Read more](../ops/trait.fromresidual#tymethod.from_residual)


[source](https://doc.rust-lang.org/src/core/result.rs.html#498)
```
impl<T, E> Hash for Result<T, E>
where
    T: Hash,
    E: Hash,
```

[source](https://doc.rust-lang.org/src/core/result.rs.html#498)
```
fn hash<__H>(&self, state: &mut __H)
where
    __H: Hasher,
```
Feeds this value into the given [`Hasher`](../hash/trait.hasher "trait std::hash::Hasher"). [Read more](../hash/trait.hash#tymethod.hash)

[source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#237-239)1.3.0
```
fn hash_slice<H>(data: &[Self], state: &mut H)
where
    H: Hasher,
    Self: Sized,
```
Feeds a slice of this type into the given [`Hasher`](../hash/trait.hasher "trait std::hash::Hasher"). [Read more](../hash/trait.hash#method.hash_slice)


[source](https://doc.rust-lang.org/src/core/result.rs.html#1721)1.4.0
```
impl<'a, T, E> IntoIterator for &'a Result<T, E>
```


```
type Item = &'a T
```
The type of the elements being iterated over.

```
type IntoIter = Iter<'a, T>
```
Which kind of iterator are we turning this into?
[source](https://doc.rust-lang.org/src/core/result.rs.html#1725)
```
fn into_iter(self) -> Iter<'a, T> ⓘ
```
Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter)


[source](https://doc.rust-lang.org/src/core/result.rs.html#1731)1.4.0
```
impl<'a, T, E> IntoIterator for &'a mut Result<T, E>
```


```
type Item = &'a mut T
```
The type of the elements being iterated over.

```
type IntoIter = IterMut<'a, T>
```
Which kind of iterator are we turning this into?
[source](https://doc.rust-lang.org/src/core/result.rs.html#1735)
```
fn into_iter(self) -> IterMut<'a, T> ⓘ
```
Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter)


[source](https://doc.rust-lang.org/src/core/result.rs.html#1695)
```
impl<T, E> IntoIterator for Result<T, E>
```

[source](https://doc.rust-lang.org/src/core/result.rs.html#1715)
```
fn into_iter(self) -> IntoIter<T> ⓘ
```

Returns a consuming iterator over the possibly contained value.

 The iterator yields one value if the result is [`Result::Ok`](enum.result#variant.Ok "variant std::result::Result::Ok"), otherwise none.

 ##### Examples

 
```
let x: Result<u32, &str> = Ok(5);
let v: Vec<u32> = x.into_iter().collect();
assert_eq!(v, [5]);

let x: Result<u32, &str> = Err("nothing!");
let v: Vec<u32> = x.into_iter().collect();
assert_eq!(v, []);
```
 

```
type Item = T
```
The type of the elements being iterated over.

```
type IntoIter = IntoIter<T>
```
Which kind of iterator are we turning this into?

[source](https://doc.rust-lang.org/src/core/result.rs.html#498)
```
impl<T, E> Ord for Result<T, E>
where
    T: Ord,
    E: Ord,
```

[source](https://doc.rust-lang.org/src/core/result.rs.html#498)
```
fn cmp(&self, other: &Result<T, E>) -> Ordering
```
This method returns an [`Ordering`](../cmp/enum.ordering "enum std::cmp::Ordering") between `self` and `other`. [Read more](../cmp/trait.ord#tymethod.cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#790-792)1.21.0
```
fn max(self, other: Self) -> Self
where
    Self: Sized,
```
Compares and returns the maximum of two values. [Read more](../cmp/trait.ord#method.max)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#810-812)1.21.0
```
fn min(self, other: Self) -> Self
where
    Self: Sized,
```
Compares and returns the minimum of two values. [Read more](../cmp/trait.ord#method.min)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#835-838)1.50.0
```
fn clamp(self, min: Self, max: Self) -> Self
where
    Self: Sized + PartialOrd<Self>,
```
Restrict a value to a certain interval. [Read more](../cmp/trait.ord#method.clamp)


[source](https://doc.rust-lang.org/src/core/result.rs.html#498)
```
impl<T, E> PartialEq<Result<T, E>> for Result<T, E>
where
    T: PartialEq<T>,
    E: PartialEq<E>,
```

[source](https://doc.rust-lang.org/src/core/result.rs.html#498)
```
fn eq(&self, other: &Result<T, E>) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#226)
```
fn ne(&self, other: &Rhs) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/result.rs.html#498)
```
impl<T, E> PartialOrd<Result<T, E>> for Result<T, E>
where
    T: PartialOrd<T>,
    E: PartialOrd<E>,
```

[source](https://doc.rust-lang.org/src/core/result.rs.html#498)
```
fn partial_cmp(&self, other: &Result<T, E>) -> Option<Ordering>
```
This method returns an ordering between `self` and `other` values if one exists. [Read more](../cmp/trait.partialord#tymethod.partial_cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1067)
```
fn lt(&self, other: &Rhs) -> bool
```
This method tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](../cmp/trait.partialord#method.lt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1084)
```
fn le(&self, other: &Rhs) -> bool
```
This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](../cmp/trait.partialord#method.le)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1100)
```
fn gt(&self, other: &Rhs) -> bool
```
This method tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](../cmp/trait.partialord#method.gt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1117)
```
fn ge(&self, other: &Rhs) -> bool
```
This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](../cmp/trait.partialord#method.ge)


[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#184)1.16.0
```
impl<T, U, E> Product<Result<U, E>> for Result<T, E>
where
    T: Product<U>,
```

[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#205-207)
```
fn product<I>(iter: I) -> Result<T, E>
where
    I: Iterator<Item = Result<U, E>>,
```

Takes each element in the [`Iterator`](../iter/trait.iterator "trait std::iter::Iterator"): if it is an [`Err`](enum.result#variant.Err "variant std::result::Result::Err"), no further elements are taken, and the [`Err`](enum.result#variant.Err "variant std::result::Result::Err") is returned. Should no [`Err`](enum.result#variant.Err "variant std::result::Result::Err") occur, the product of all elements is returned.

 ##### Examples

 This multiplies each number in a vector of strings, if a string could not be parsed the operation returns `Err`:

 
```
let nums = vec!["5", "10", "1", "2"];
let total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();
assert_eq!(total, Ok(100));
let nums = vec!["5", "10", "one", "2"];
let total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();
assert!(total.is_err());
```
 

[source](https://doc.rust-lang.org/src/core/result.rs.html#1975)
```
impl<T, E> Residual<T> for Result<Infallible, E>
```


```
type TryType = Result<T, E>
```

🔬This is a nightly-only experimental API. (`try_trait_v2_residual` [#91285](https://github.com/rust-lang/rust/issues/91285))
The “return” type of this meta-function.

[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#153)1.16.0
```
impl<T, U, E> Sum<Result<U, E>> for Result<T, E>
where
    T: Sum<U>,
```

[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#175-177)
```
fn sum<I>(iter: I) -> Result<T, E>
where
    I: Iterator<Item = Result<U, E>>,
```

Takes each element in the [`Iterator`](../iter/trait.iterator "trait std::iter::Iterator"): if it is an [`Err`](enum.result#variant.Err "variant std::result::Result::Err"), no further elements are taken, and the [`Err`](enum.result#variant.Err "variant std::result::Result::Err") is returned. Should no [`Err`](enum.result#variant.Err "variant std::result::Result::Err") occur, the sum of all elements is returned.

 ##### Examples

 This sums up every integer in a vector, rejecting the sum if a negative element is encountered:

 
```
let f = |&x: &i32| if x < 0 { Err("Negative element found") } else { Ok(x) };
let v = vec![1, 2];
let res: Result<i32, _> = v.iter().map(f).sum();
assert_eq!(res, Ok(3));
let v = vec![1, -2];
let res: Result<i32, _> = v.iter().map(f).sum();
assert_eq!(res, Err("Negative element found"));
```
 

[source](https://doc.rust-lang.org/src/std/process.rs.html#2272-2282)1.61.0
```
impl<T: Termination, E: Debug> Termination for Result<T, E>
```

[source](https://doc.rust-lang.org/src/std/process.rs.html#2273-2281)
```
fn report(self) -> ExitCode
```
Is called to get the representation of the value as status code. This status code is returned to the operating system.

[source](https://doc.rust-lang.org/src/core/result.rs.html#1937)
```
impl<T, E> Try for Result<T, E>
```


```
type Output = T
```

🔬This is a nightly-only experimental API. (`try_trait_v2` [#84277](https://github.com/rust-lang/rust/issues/84277))
The type of the value produced by `?` when *not* short-circuiting.

```
type Residual = Result<Infallible, E>
```

🔬This is a nightly-only experimental API. (`try_trait_v2` [#84277](https://github.com/rust-lang/rust/issues/84277))
The type of the value passed to [`FromResidual::from_residual`](../ops/trait.fromresidual#tymethod.from_residual "associated function std::ops::FromResidual::from_residual") as part of `?` when short-circuiting. [Read more](../ops/trait.try#associatedtype.Residual)

[source](https://doc.rust-lang.org/src/core/result.rs.html#1942)
```
fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
```

🔬This is a nightly-only experimental API. (`try_trait_v2` [#84277](https://github.com/rust-lang/rust/issues/84277))
Constructs the type from its `Output` type. [Read more](../ops/trait.try#tymethod.from_output)

[source](https://doc.rust-lang.org/src/core/result.rs.html#1947)
```
fn branch(
    self
) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
```

🔬This is a nightly-only experimental API. (`try_trait_v2` [#84277](https://github.com/rust-lang/rust/issues/84277))
Used in `?` to decide whether the operator should produce a value (because this returned [`ControlFlow::Continue`](../ops/enum.controlflow#variant.Continue "variant std::ops::ControlFlow::Continue")) or propagate a value back to the caller (because this returned [`ControlFlow::Break`](../ops/enum.controlflow#variant.Break "variant std::ops::ControlFlow::Break")). [Read more](../ops/trait.try#tymethod.branch)


[source](https://doc.rust-lang.org/src/core/result.rs.html#498)
```
impl<T, E> Copy for Result<T, E>
where
    T: Copy,
    E: Copy,
```
[source](https://doc.rust-lang.org/src/core/result.rs.html#498)
```
impl<T, E> Eq for Result<T, E>
where
    T: Eq,
    E: Eq,
```
[source](https://doc.rust-lang.org/src/core/result.rs.html#498)
```
impl<T, E> StructuralEq for Result<T, E>
```
[source](https://doc.rust-lang.org/src/core/result.rs.html#498)
```
impl<T, E> StructuralPartialEq for Result<T, E>
```


Auto Trait Implementations
--------------------------




```
impl<T, E> RefUnwindSafe for Result<T, E>
where
    E: RefUnwindSafe,
    T: RefUnwindSafe,
```

```
impl<T, E> Send for Result<T, E>
where
    E: Send,
    T: Send,
```

```
impl<T, E> Sync for Result<T, E>
where
    E: Sync,
    T: Sync,
```

```
impl<T, E> Unpin for Result<T, E>
where
    E: Unpin,
    T: Unpin,
```

```
impl<T, E> UnwindSafe for Result<T, E>
where
    E: UnwindSafe,
    T: UnwindSafe,
```


Blanket Implementations
-----------------------



[source](https://doc.rust-lang.org/src/core/any.rs.html#200)
```
impl<T> Any for T
where
    T: 'static + ?Sized,
```

[source](https://doc.rust-lang.org/src/core/any.rs.html#201)
```
fn type_id(&self) -> TypeId
```
Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#208)
```
impl<T> Borrow<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#210)
```
fn borrow(&self) -> &T
```
Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#216)
```
impl<T> BorrowMut<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#217)
```
fn borrow_mut(&mut self) -> &mut T
```
Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#723)
```
impl<T> From<T> for T
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#726)
```
fn from(t: T) -> T
```

Returns the argument unchanged.

 

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#707)
```
impl<T, U> Into<U> for T
where
    U: From<T>,
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#716)
```
fn into(self) -> U
```

Calls `U::from(self)`.

 That is, this conversion is whatever the implementation of `[From](../convert/trait.from "trait std::convert::From")<T> for U` chooses to do.

 

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#82)
```
impl<T> ToOwned for T
where
    T: Clone,
```


```
type Owned = T
```
The resulting type after obtaining ownership.
[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#87)
```
fn to_owned(&self) -> T
```
Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned)

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#91)
```
fn clone_into(&self, target: &mut T)
```
Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#763)
```
impl<T, U> TryFrom<U> for T
where
    U: Into<T>,
```


```
type Error = Infallible
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#770)
```
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#748)
```
impl<T, U> TryInto<U> for T
where
    U: TryFrom<T>,
```


```
type Error = <U as TryFrom<T>>::Error
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#755)
```
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
```
Performs the conversion.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/result/enum.Result.html>

Constant evaluation
===================

 Constant evaluation is the process of computing the result of <expressions> during compilation. Only a subset of all expressions can be evaluated at compile-time.

 Constant expressions
--------------------

 Certain forms of expressions, called constant expressions, can be evaluated at compile time. In [const contexts](#const-context), these are the only allowed expressions, and are always evaluated at compile time. In other places, such as [let statements](statements#let-statements), constant expressions *may* be, but are not guaranteed to be, evaluated at compile time. Behaviors such as out of bounds [array indexing](expressions/array-expr#array-and-slice-indexing-expressions) or [overflow](expressions/operator-expr#overflow) are compiler errors if the value must be evaluated at compile time (i.e. in const contexts). Otherwise, these behaviors are warnings, but will likely panic at run-time.

 The following expressions are constant expressions, so long as any operands are also constant expressions and do not cause any [`Drop::drop`](destructors) calls to be run.

 * [Literals](expressions/literal-expr).
* [Const parameters](items/generics).
* [Paths](expressions/path-expr) to [functions](items/functions) and [constants](items/constant-items). Recursively defining constants is not allowed.
* Paths to [statics](items/static-items). These are only allowed within the initializer of a static.
* [Tuple expressions](expressions/tuple-expr).
* [Array expressions](expressions/array-expr).
* [Struct](expressions/struct-expr) expressions.
* [Block expressions](expressions/block-expr), including `unsafe` blocks.
	+ [let statements](statements#let-statements) and thus irrefutable <patterns>, including mutable bindings
	+ [assignment expressions](expressions/operator-expr#assignment-expressions)
	+ [compound assignment expressions](expressions/operator-expr#compound-assignment-expressions)
	+ [expression statements](statements#expression-statements)
* [Field](expressions/field-expr) expressions.
* Index expressions, [array indexing](expressions/array-expr#array-and-slice-indexing-expressions) or [slice](types/slice) with a `usize`.
* [Range expressions](expressions/range-expr).
* [Closure expressions](expressions/closure-expr) which don't capture variables from the environment.
* Built-in [negation](expressions/operator-expr#negation-operators), [arithmetic](expressions/operator-expr#arithmetic-and-logical-binary-operators), [logical](expressions/operator-expr#arithmetic-and-logical-binary-operators), [comparison](expressions/operator-expr#comparison-operators) or [lazy boolean](expressions/operator-expr#lazy-boolean-operators) operators used on integer and floating point types, `bool`, and `char`.
* Shared [borrow](expressions/operator-expr#borrow-operators)s, except if applied to a type with [interior mutability](interior-mutability).
* The [dereference operator](expressions/operator-expr#the-dereference-operator) except for raw pointers.
* [Grouped](expressions/grouped-expr) expressions.
* [Cast](expressions/operator-expr#type-cast-expressions) expressions, except
	+ pointer to address casts and
	+ function pointer to address casts.
* Calls of [const functions](items/functions#const-functions) and const methods.
* [loop](expressions/loop-expr#infinite-loops), [while](expressions/loop-expr#predicate-loops) and [`while let`](expressions/loop-expr#predicate-pattern-loops) expressions.
* [if](expressions/if-expr#if-expressions), [`if let`](expressions/if-expr#if-let-expressions) and [match](expressions/match-expr) expressions.

 Const context
-------------

 A *const context* is one of the following:

 * [Array type length expressions](types/array)
* [Array repeat length expressions](expressions/array-expr)
* The initializer of
	+ [constants](items/constant-items)
	+ [statics](items/static-items)
	+ [enum discriminants](items/enumerations#discriminants)
* A [const generic argument](items/generics#const-generics)

 Const Functions
---------------

 A *const fn* is a function that one is permitted to call from a const context. Declaring a function `const` has no effect on any existing uses, it only restricts the types that arguments and the return type may use, as well as prevent various expressions from being used within it. You can freely do anything with a const function that you can do with a regular function.

 When called from a const context, the function is interpreted by the compiler at compile time. The interpretation happens in the environment of the compilation target and not the host. So `usize` is `32` bits if you are compiling against a `32` bit system, irrelevant of whether you are building on a `64` bit or a `32` bit system.

 Const functions have various restrictions to make sure that they can be evaluated at compile-time. It is, for example, not possible to write a random number generator as a const function. Calling a const function at compile-time will always yield the same result as calling it at runtime, even when called multiple times. There's one exception to this rule: if you are doing complex floating point operations in extreme situations, then you might get (very slightly) different results. It is advisable to not make array lengths and enum discriminants depend on floating point computations.

 Notable features that are allowed in const contexts but not in const functions include:

 * floating point operations
	+ floating point values are treated just like generic parameters without trait bounds beyond `Copy`. So you cannot do anything with them but copy/move them around.

 Conversely, the following are possible in a const function, but not in a const context:

 * Use of generic type and lifetime parameters.
	+ Const contexts do allow limited use of [const generic parameters](items/generics#const-generics).



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/const_eval.html>

Trait std::ops::Drop
====================



```
pub trait Drop {
    // Required method
    fn drop(&mut self);
}
```

Custom code within the destructor.

 When a value is no longer needed, Rust will run a “destructor” on that value. The most common way that a value is no longer needed is when it goes out of scope. Destructors may still run in other circumstances, but we’re going to focus on scope for the examples here. To learn about some of those other cases, please see [the reference](../../reference/destructors) section on destructors.

 This destructor consists of two components:

 * A call to `Drop::drop` for that value, if this special `Drop` trait is implemented for its type.
* The automatically generated “drop glue” which recursively calls the destructors of all the fields of this value.

 As Rust automatically calls the destructors of all contained fields, you don’t have to implement `Drop` in most cases. But there are some cases where it is useful, for example for types which directly manage a resource. That resource may be memory, it may be a file descriptor, it may be a network socket. Once a value of that type is no longer going to be used, it should “clean up” its resource by freeing the memory or closing the file or socket. This is the job of a destructor, and therefore the job of `Drop::drop`.

 ### Examples

 To see destructors in action, let’s take a look at the following program:

 
```
struct HasDrop;

impl Drop for HasDrop {
    fn drop(&mut self) {
        println!("Dropping HasDrop!");
    }
}

struct HasTwoDrops {
    one: HasDrop,
    two: HasDrop,
}

impl Drop for HasTwoDrops {
    fn drop(&mut self) {
        println!("Dropping HasTwoDrops!");
    }
}

fn main() {
    let _x = HasTwoDrops { one: HasDrop, two: HasDrop };
    println!("Running!");
}
```
 Rust will first call `Drop::drop` for `_x` and then for both `_x.one` and `_x.two`, meaning that running this will print

 
```
Running!
Dropping HasTwoDrops!
Dropping HasDrop!
Dropping HasDrop!

```
 Even if we remove the implementation of `Drop` for `HasTwoDrop`, the destructors of its fields are still called. This would result in

 
```
Running!
Dropping HasDrop!
Dropping HasDrop!

```

### You cannot call `Drop::drop` yourself

 Because `Drop::drop` is used to clean up a value, it may be dangerous to use this value after the method has been called. As `Drop::drop` does not take ownership of its input, Rust prevents misuse by not allowing you to call `Drop::drop` directly.

 In other words, if you tried to explicitly call `Drop::drop` in the above example, you’d get a compiler error.

 If you’d like to explicitly call the destructor of a value, [`mem::drop`](../mem/fn.drop "fn std::mem::drop") can be used instead.

 ### Drop order

 Which of our two `HasDrop` drops first, though? For structs, it’s the same order that they’re declared: first `one`, then `two`. If you’d like to try this yourself, you can modify `HasDrop` above to contain some data, like an integer, and then use it in the `println!` inside of `Drop`. This behavior is guaranteed by the language.

 Unlike for structs, local variables are dropped in reverse order:

 
```
struct Foo;

impl Drop for Foo {
    fn drop(&mut self) {
        println!("Dropping Foo!")
    }
}

struct Bar;

impl Drop for Bar {
    fn drop(&mut self) {
        println!("Dropping Bar!")
    }
}

fn main() {
    let _foo = Foo;
    let _bar = Bar;
}
```
 This will print

 
```
Dropping Bar!
Dropping Foo!

```
 Please see [the reference](../../reference/destructors) for the full rules.

 ### 
`Copy` and `Drop` are exclusive

 You cannot implement both [`Copy`](../marker/trait.copy "trait std::marker::Copy") and `Drop` on the same type. Types that are `Copy` get implicitly duplicated by the compiler, making it very hard to predict when, and how often destructors will be executed. As such, these types cannot have destructors.

 ### Drop check

 Dropping interacts with the borrow checker in subtle ways: when a type `T` is being implicitly dropped as some variable of this type goes out of scope, the borrow checker needs to ensure that calling `T`’s destructor at this moment is safe. In particular, it also needs to be safe to recursively drop all the fields of `T`. For example, it is crucial that code like the following is being rejected:

 ⓘ
```
use std::cell::Cell;

struct S<'a>(Cell<Option<&'a S<'a>>>, Box<i32>);
impl Drop for S<'_> {
    fn drop(&mut self) {
        if let Some(r) = self.0.get() {
            // Print the contents of the `Box` in `r`.
            println!("{}", r.1);
        }
    }
}

fn main() {
    // Set up two `S` that point to each other.
    let s1 = S(Cell::new(None), Box::new(42));
    let s2 = S(Cell::new(Some(&s1)), Box::new(42));
    s1.0.set(Some(&s2));
    // Now they both get dropped. But whichever is the 2nd one
    // to be dropped will access the `Box` in the first one,
    // which is a use-after-free!
}
```

 The Nomicon discusses the need for [drop check in more detail](https://doc.rust-lang.org/nomicon/dropck.html).

 To reject such code, the “drop check” analysis determines which types and lifetimes need to still be live when `T` gets dropped. The exact details of this analysis are not yet stably guaranteed and **subject to change**. Currently, the analysis works as follows:

 * If `T` has no drop glue, then trivially nothing is required to be live. This is the case if neither `T` nor any of its (recursive) fields have a destructor (`impl Drop`). [`PhantomData`](../marker/struct.phantomdata "struct std::marker::PhantomData") and [`ManuallyDrop`](../mem/struct.manuallydrop "struct std::mem::ManuallyDrop") are considered to never have a destructor, no matter their field type.
* If `T` has drop glue, then, for all types `U` that are *owned* by any field of `T`, recursively add the types and lifetimes that need to be live when `U` gets dropped. The set of owned types is determined by recursively traversing `T`:
	+ Recursively descend through `PhantomData`, `Box`, tuples, and arrays (including arrays of length 0).
	+ Stop at reference and raw pointer types as well as function pointers and function items; they do not own anything.
	+ Stop at non-composite types (type parameters that remain generic in the current context and base types such as integers and `bool`); these types are owned.
	+ When hitting an ADT with `impl Drop`, stop there; this type is owned.
	+ When hitting an ADT without `impl Drop`, recursively descend to its fields. (For an `enum`, consider all fields of all variants.)
* Furthermore, if `T` implements `Drop`, then all generic (lifetime and type) parameters of `T` must be live.

 In the above example, the last clause implies that `'a` must be live when `S<'a>` is dropped, and hence the example is rejected. If we remove the `impl Drop`, the liveness requirement disappears and the example is accepted.

 There exists an unstable way for a type to opt-out of the last clause; this is called “drop check eyepatch” or `may_dangle`. For more details on this nightly-only feature, see the [discussion in the Nomicon](https://doc.rust-lang.org/nomicon/phantom-data.html#an-exception-the-special-case-of-the-standard-library-and-its-unstable-may_dangle).

 Required Methods
----------------



[source](https://doc.rust-lang.org/src/core/ops/drop.rs.html#233)
```
fn drop(&mut self)
```

Executes the destructor for this type.

 This method is called implicitly when the value goes out of scope, and cannot be called explicitly (this is compiler error [E0040](https://doc.rust-lang.org/error_codes/E0040.html)). However, the [`mem::drop`](../mem/fn.drop "fn std::mem::drop") function in the prelude can be used to call the argument’s `Drop` implementation.

 When this method has been called, `self` has not yet been deallocated. That only happens after the method is over. If this wasn’t the case, `self` would be a dangling reference.

 ##### Panics

 Given that a [`panic!`](https://doc.rust-lang.org/core/macro.panic.html "macro core::panic") will call `drop` as it unwinds, any [`panic!`](https://doc.rust-lang.org/core/macro.panic.html "macro core::panic") in a `drop` implementation will likely abort.

 Note that even if this panics, the value is considered to be dropped; you must not cause `drop` to be called again. This is normally automatically handled by the compiler, but when using unsafe code, can sometimes occur unintentionally, particularly when using [`ptr::drop_in_place`](../ptr/fn.drop_in_place "fn std::ptr::drop_in_place").

 

Implementors
------------



[source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#699)1.13.0
```
impl Drop for CString
```
[source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#168-183)1.63.0
```
impl Drop for OwnedFd
```
[source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#364-371)1.63.0
```
impl Drop for OwnedHandleAvailable on Windows only.
```
[source](https://doc.rust-lang.org/src/std/os/windows/io/socket.rs.html#210-217)1.63.0
```
impl Drop for OwnedSocketAvailable on Windows only.
```
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2921)1.6.0
```
impl Drop for std::string::Drain<'_>
```
[source](https://doc.rust-lang.org/src/core/task/wake.rs.html#348)1.36.0
```
impl Drop for Waker
```
[source](https://doc.rust-lang.org/src/alloc/collections/binary_heap/mod.rs.html#1595)
```
impl<'a, T> Drop for DrainSorted<'a, T>
where
    T: Ord,
```
[source](https://doc.rust-lang.org/src/core/ffi/mod.rs.html#604)
```
impl<'f> Drop for VaListImpl<'f>
```
[source](https://doc.rust-lang.org/src/alloc/vec/splice.rs.html#54)1.21.0
```
impl<I, A> Drop for Splice<'_, I, A>
where
    I: Iterator,
    A: Allocator,
```
[source](https://doc.rust-lang.org/src/alloc/collections/btree/map.rs.html#1692)1.7.0
```
impl<K, V, A> Drop for std::collections::btree_map::IntoIter<K, V, A>
where
    A: Allocator + Clone,
```
[source](https://doc.rust-lang.org/src/alloc/collections/btree/map.rs.html#186)1.7.0
```
impl<K, V, A> Drop for BTreeMap<K, V, A>
where
    A: Allocator + Clone,
```
[source](https://doc.rust-lang.org/src/alloc/collections/btree/map.rs.html#1933)
```
impl<K, V, F, A> Drop for std::collections::btree_map::DrainFilter<'_, K, V, F, A>
where
    A: Allocator + Clone,
    F: FnMut(&K, &mut V) -> bool,
```
[source](https://doc.rust-lang.org/src/alloc/boxed/thin.rs.html#135)
```
impl<T> Drop for ThinBox<T>
where
    T: ?Sized,
```
[source](https://doc.rust-lang.org/src/alloc/collections/binary_heap/mod.rs.html#301)1.12.0
```
impl<T> Drop for PeekMut<'_, T>
where
    T: Ord,
```
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1578)
```
impl<T> Drop for Rc<T>
where
    T: ?Sized,
```
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2518)1.4.0
```
impl<T> Drop for std::rc::Weak<T>
where
    T: ?Sized,
```
[source](https://doc.rust-lang.org/src/std/sync/mpsc/mod.rs.html#1101-1103)
```
impl<T> Drop for Receiver<T>
```
[source](https://doc.rust-lang.org/src/std/sync/mpsc/mod.rs.html#631-633)
```
impl<T> Drop for Sender<T>
```
[source](https://doc.rust-lang.org/src/std/sync/mpsc/mod.rs.html#760-762)
```
impl<T> Drop for SyncSender<T>
```
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#1833)
```
impl<T> Drop for Arc<T>
where
    T: ?Sized,
```
[source](https://doc.rust-lang.org/src/std/sync/once_lock.rs.html#429-439)1.70.0
```
impl<T> Drop for OnceLock<T>
```
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2364)1.4.0
```
impl<T> Drop for std::sync::Weak<T>
where
    T: ?Sized,
```
[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1213)
```
impl<T, A> Drop for Box<T, A>
where
    A: Allocator,
    T: ?Sized,
```
[source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1067)
```
impl<T, A> Drop for LinkedList<T, A>
where
    A: Allocator,
```
[source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#123)
```
impl<T, A> Drop for VecDeque<T, A>
where
    A: Allocator,
```
[source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/drain.rs.html#94)1.6.0
```
impl<T, A> Drop for std::collections::vec_deque::Drain<'_, T, A>
where
    A: Allocator,
```
[source](https://doc.rust-lang.org/src/alloc/vec/drain.rs.html#174)1.6.0
```
impl<T, A> Drop for std::vec::Drain<'_, T, A>
where
    A: Allocator,
```
[source](https://doc.rust-lang.org/src/alloc/vec/into_iter.rs.html#398)
```
impl<T, A> Drop for std::vec::IntoIter<T, A>
where
    A: Allocator,
```
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3011)
```
impl<T, A> Drop for Vec<T, A>
where
    A: Allocator,
```
[source](https://doc.rust-lang.org/src/std/sync/lazy_lock.rs.html#162-172)
```
impl<T, F> Drop for LazyLock<T, F>
```
[source](https://doc.rust-lang.org/src/alloc/collections/btree/set.rs.html#1296)
```
impl<T, F, A> Drop for std::collections::btree_set::DrainFilter<'_, T, F, A>
where
    A: Allocator + Clone,
    F: FnMut(&T) -> bool,
```
[source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1853)
```
impl<T, F, A> Drop for std::collections::linked_list::DrainFilter<'_, T, F, A>
where
    A: Allocator,
    F: FnMut(&mut T) -> bool,
```
[source](https://doc.rust-lang.org/src/alloc/vec/drain_filter.rs.html#152)
```
impl<T, F, A> Drop for std::vec::DrainFilter<'_, T, F, A>
where
    A: Allocator,
    F: FnMut(&mut T) -> bool,
```
[source](https://doc.rust-lang.org/src/core/array/iter.rs.html#348)1.40.0
```
impl<T, const N: usize> Drop for std::array::IntoIter<T, N>
```
[source](https://doc.rust-lang.org/src/std/sync/mutex.rs.html#530-538)
```
impl<T: ?Sized> Drop for MutexGuard<'_, T>
```
[source](https://doc.rust-lang.org/src/std/sync/rwlock.rs.html#597-604)
```
impl<T: ?Sized> Drop for RwLockReadGuard<'_, T>
```
[source](https://doc.rust-lang.org/src/std/sync/rwlock.rs.html#607-615)
```
impl<T: ?Sized> Drop for RwLockWriteGuard<'_, T>
```
[source](https://doc.rust-lang.org/src/std/io/buffered/bufwriter.rs.html#667-674)
```
impl<W: Write> Drop for BufWriter<W>
```



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/ops/trait.Drop.html>

Enum std::net::IpAddr
=====================



```
pub enum IpAddr {
    V4(Ipv4Addr),
    V6(Ipv6Addr),
}
```

An IP address, either IPv4 or IPv6.

 This enum can contain either an [`Ipv4Addr`](struct.ipv4addr "struct std::net::Ipv4Addr") or an [`Ipv6Addr`](struct.ipv6addr "struct std::net::Ipv6Addr"), see their respective documentation for more details.

 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);
```
 Variants
--------




```
V4(Ipv4Addr)
```

An IPv4 address.

 

```
V6(Ipv6Addr)
```

An IPv6 address.

 

Implementations
---------------



[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#212)
```
impl IpAddr
```

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#230)1.12.0 (const: 1.50.0)
```
pub const fn is_unspecified(&self) -> bool
```

Returns [`true`](../primitive.bool "primitive bool") for the special ‘unspecified’ address.

 See the documentation for [`Ipv4Addr::is_unspecified()`](struct.ipv4addr#method.is_unspecified "method std::net::Ipv4Addr::is_unspecified") and [`Ipv6Addr::is_unspecified()`](struct.ipv6addr#method.is_unspecified "method std::net::Ipv6Addr::is_unspecified") for more details.

 ##### 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);
```
 
[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#254)1.12.0 (const: 1.50.0)
```
pub const fn is_loopback(&self) -> bool
```

Returns [`true`](../primitive.bool "primitive bool") if this is a loopback address.

 See the documentation for [`Ipv4Addr::is_loopback()`](struct.ipv4addr#method.is_loopback "method std::net::Ipv4Addr::is_loopback") and [`Ipv6Addr::is_loopback()`](struct.ipv6addr#method.is_loopback "method std::net::Ipv6Addr::is_loopback") for more details.

 ##### 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);
```
 
[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#280)const: [unstable](https://github.com/rust-lang/rust/issues/76205 "Tracking issue for const_ip")
```
pub fn is_global(&self) -> bool
```

🔬This is a nightly-only experimental API. (`ip` [#27709](https://github.com/rust-lang/rust/issues/27709))

Returns [`true`](../primitive.bool "primitive bool") if the address appears to be globally routable.

 See the documentation for [`Ipv4Addr::is_global()`](struct.ipv4addr#method.is_global "method std::net::Ipv4Addr::is_global") and [`Ipv6Addr::is_global()`](struct.ipv6addr#method.is_global "method std::net::Ipv6Addr::is_global") for more details.

 ##### 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);
```
 
[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#304)1.12.0 (const: 1.50.0)
```
pub const fn is_multicast(&self) -> bool
```

Returns [`true`](../primitive.bool "primitive bool") if this is a multicast address.

 See the documentation for [`Ipv4Addr::is_multicast()`](struct.ipv4addr#method.is_multicast "method std::net::Ipv4Addr::is_multicast") and [`Ipv6Addr::is_multicast()`](struct.ipv6addr#method.is_multicast "method std::net::Ipv6Addr::is_multicast") for more details.

 ##### 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);
```
 
[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#333)const: [unstable](https://github.com/rust-lang/rust/issues/76205 "Tracking issue for const_ip")
```
pub fn is_documentation(&self) -> bool
```

🔬This is a nightly-only experimental API. (`ip` [#27709](https://github.com/rust-lang/rust/issues/27709))

Returns [`true`](../primitive.bool "primitive bool") if this address is in a range designated for documentation.

 See the documentation for [`Ipv4Addr::is_documentation()`](struct.ipv4addr#method.is_documentation "method std::net::Ipv4Addr::is_documentation") and [`Ipv6Addr::is_documentation()`](struct.ipv6addr#method.is_documentation "method std::net::Ipv6Addr::is_documentation") for more details.

 ##### 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
);
```
 
[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#358)
```
pub const fn is_benchmarking(&self) -> bool
```

🔬This is a nightly-only experimental API. (`ip` [#27709](https://github.com/rust-lang/rust/issues/27709))

Returns [`true`](../primitive.bool "primitive bool") if this address is in a range designated for benchmarking.

 See the documentation for [`Ipv4Addr::is_benchmarking()`](struct.ipv4addr#method.is_benchmarking "method std::net::Ipv4Addr::is_benchmarking") and [`Ipv6Addr::is_benchmarking()`](struct.ipv6addr#method.is_benchmarking "method std::net::Ipv6Addr::is_benchmarking") for more details.

 ##### 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);
```
 
[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#382)1.16.0 (const: 1.50.0)
```
pub const fn is_ipv4(&self) -> bool
```

Returns [`true`](../primitive.bool "primitive bool") if this address is an [`IPv4` address](enum.ipaddr#variant.V4 "variant std::net::IpAddr::V4"), and [`false`](../primitive.bool "primitive bool") otherwise.

 ##### 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);
```
 
[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#403)1.16.0 (const: 1.50.0)
```
pub const fn is_ipv6(&self) -> bool
```

Returns [`true`](../primitive.bool "primitive bool") if this address is an [`IPv6` address](enum.ipaddr#variant.V6 "variant std::net::IpAddr::V6"), and [`false`](../primitive.bool "primitive bool") otherwise.

 ##### 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);
```
 
[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#425)const: [unstable](https://github.com/rust-lang/rust/issues/76205 "Tracking issue for const_ip")
```
pub fn to_canonical(&self) -> IpAddr
```

🔬This is a nightly-only experimental API. (`ip` [#27709](https://github.com/rust-lang/rust/issues/27709))

Converts this address to an `IpAddr::V4` if it is an IPv4-mapped IPv6 addresses, otherwise it return `self` as-is.

 ##### Examples

 
```
#![feature(ip)]
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};

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);
```
 

[source](https://doc.rust-lang.org/src/core/net/parser.rs.html#274)
```
impl IpAddr
```

[source](https://doc.rust-lang.org/src/core/net/parser.rs.html#289)
```
pub fn parse_ascii(b: &[u8]) -> Result<IpAddr, 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));
```
 


Trait Implementations
---------------------



[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#28)
```
impl Clone for IpAddr
```

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#28)
```
fn clone(&self) -> IpAddr
```
Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone)

[source](https://doc.rust-lang.org/src/core/clone.rs.html#129)1.0.0
```
fn clone_from(&mut self, source: &Self)
```
Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from)


[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#932)
```
impl Debug for IpAddr
```

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#933)
```
fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt)


[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#922)
```
impl Display for IpAddr
```

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#923)
```
fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter. [Read more](../fmt/trait.display#tymethod.fmt)


[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#2044)1.17.0
```
impl From<[u16; 8]> for IpAddr
```

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#2067)
```
fn from(segments: [u16; 8]) -> IpAddr
```

Creates an `IpAddr::V6` from an eight element 16-bit array.

 ##### Examples

 
```
use std::net::{IpAddr, Ipv6Addr};

let addr = IpAddr::from([
    525u16, 524u16, 523u16, 522u16,
    521u16, 520u16, 519u16, 518u16,
]);
assert_eq!(
    IpAddr::V6(Ipv6Addr::new(
        0x20d, 0x20c,
        0x20b, 0x20a,
        0x209, 0x208,
        0x207, 0x206
    )),
    addr
);
```
 

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#2015)1.17.0
```
impl From<[u8; 16]> for IpAddr
```

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#2038)
```
fn from(octets: [u8; 16]) -> IpAddr
```

Creates an `IpAddr::V6` from a sixteen element byte array.

 ##### Examples

 
```
use std::net::{IpAddr, Ipv6Addr};

let addr = IpAddr::from([
    25u8, 24u8, 23u8, 22u8, 21u8, 20u8, 19u8, 18u8,
    17u8, 16u8, 15u8, 14u8, 13u8, 12u8, 11u8, 10u8,
]);
assert_eq!(
    IpAddr::V6(Ipv6Addr::new(
        0x1918, 0x1716,
        0x1514, 0x1312,
        0x1110, 0x0f0e,
        0x0d0c, 0x0b0a
    )),
    addr
);
```
 

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#1125)1.17.0
```
impl From<[u8; 4]> for IpAddr
```

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#1137)
```
fn from(octets: [u8; 4]) -> IpAddr
```

Creates an `IpAddr::V4` from a four element byte array.

 ##### 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);
```
 

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#939)1.16.0
```
impl From<Ipv4Addr> for IpAddr
```

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#955)
```
fn from(ipv4: Ipv4Addr) -> IpAddr
```

Copies this address to a new `IpAddr::V4`.

 ##### Examples

 
```
use std::net::{IpAddr, Ipv4Addr};

let addr = Ipv4Addr::new(127, 0, 0, 1);

assert_eq!(
    IpAddr::V4(addr),
    IpAddr::from(addr)
)
```
 

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#961)1.16.0
```
impl From<Ipv6Addr> for IpAddr
```

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#977)
```
fn from(ipv6: Ipv6Addr) -> IpAddr
```

Copies this address to a new `IpAddr::V6`.

 ##### 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)
);
```
 

[source](https://doc.rust-lang.org/src/core/net/parser.rs.html#295)
```
impl FromStr for IpAddr
```


```
type Err = AddrParseError
```
The associated error which can be returned from parsing.
[source](https://doc.rust-lang.org/src/core/net/parser.rs.html#297)
```
fn from_str(s: &str) -> Result<IpAddr, AddrParseError>
```
Parses a string `s` to return a value of this type. [Read more](../str/trait.fromstr#tymethod.from_str)


[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#28)
```
impl Hash for IpAddr
```

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#28)
```
fn hash<__H>(&self, state: &mut __H)
where
    __H: Hasher,
```
Feeds this value into the given [`Hasher`](../hash/trait.hasher "trait std::hash::Hasher"). [Read more](../hash/trait.hash#tymethod.hash)

[source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#237-239)1.3.0
```
fn hash_slice<H>(data: &[Self], state: &mut H)
where
    H: Hasher,
    Self: Sized,
```
Feeds a slice of this type into the given [`Hasher`](../hash/trait.hasher "trait std::hash::Hasher"). [Read more](../hash/trait.hash#method.hash_slice)


[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#28)
```
impl Ord for IpAddr
```

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#28)
```
fn cmp(&self, other: &IpAddr) -> Ordering
```
This method returns an [`Ordering`](../cmp/enum.ordering "enum std::cmp::Ordering") between `self` and `other`. [Read more](../cmp/trait.ord#tymethod.cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#790-792)1.21.0
```
fn max(self, other: Self) -> Self
where
    Self: Sized,
```
Compares and returns the maximum of two values. [Read more](../cmp/trait.ord#method.max)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#810-812)1.21.0
```
fn min(self, other: Self) -> Self
where
    Self: Sized,
```
Compares and returns the minimum of two values. [Read more](../cmp/trait.ord#method.min)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#835-838)1.50.0
```
fn clamp(self, min: Self, max: Self) -> Self
where
    Self: Sized + PartialOrd<Self>,
```
Restrict a value to a certain interval. [Read more](../cmp/trait.ord#method.clamp)


[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#28)
```
impl PartialEq<IpAddr> for IpAddr
```

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#28)
```
fn eq(&self, other: &IpAddr) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#226)1.0.0
```
fn ne(&self, other: &Rhs) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#1022)1.16.0
```
impl PartialEq<IpAddr> for Ipv4Addr
```

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#1024)
```
fn eq(&self, other: &IpAddr) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#226)1.0.0
```
fn ne(&self, other: &Rhs) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#1853)1.16.0
```
impl PartialEq<IpAddr> for Ipv6Addr
```

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#1855)
```
fn eq(&self, other: &IpAddr) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#226)1.0.0
```
fn ne(&self, other: &Rhs) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#1011)1.16.0
```
impl PartialEq<Ipv4Addr> for IpAddr
```

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#1013)
```
fn eq(&self, other: &Ipv4Addr) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#226)1.0.0
```
fn ne(&self, other: &Rhs) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#1864)1.16.0
```
impl PartialEq<Ipv6Addr> for IpAddr
```

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#1866)
```
fn eq(&self, other: &Ipv6Addr) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#226)1.0.0
```
fn ne(&self, other: &Rhs) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#28)
```
impl PartialOrd<IpAddr> for IpAddr
```

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#28)
```
fn partial_cmp(&self, other: &IpAddr) -> Option<Ordering>
```
This method returns an ordering between `self` and `other` values if one exists. [Read more](../cmp/trait.partialord#tymethod.partial_cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1067)1.0.0
```
fn lt(&self, other: &Rhs) -> bool
```
This method tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](../cmp/trait.partialord#method.lt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1084)1.0.0
```
fn le(&self, other: &Rhs) -> bool
```
This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](../cmp/trait.partialord#method.le)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1100)1.0.0
```
fn gt(&self, other: &Rhs) -> bool
```
This method tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](../cmp/trait.partialord#method.gt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1117)1.0.0
```
fn ge(&self, other: &Rhs) -> bool
```
This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](../cmp/trait.partialord#method.ge)


[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#1052)1.16.0
```
impl PartialOrd<IpAddr> for Ipv4Addr
```

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#1054)
```
fn partial_cmp(&self, other: &IpAddr) -> Option<Ordering>
```
This method returns an ordering between `self` and `other` values if one exists. [Read more](../cmp/trait.partialord#tymethod.partial_cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1067)1.0.0
```
fn lt(&self, other: &Rhs) -> bool
```
This method tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](../cmp/trait.partialord#method.lt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1084)1.0.0
```
fn le(&self, other: &Rhs) -> bool
```
This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](../cmp/trait.partialord#method.le)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1100)1.0.0
```
fn gt(&self, other: &Rhs) -> bool
```
This method tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](../cmp/trait.partialord#method.gt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1117)1.0.0
```
fn ge(&self, other: &Rhs) -> bool
```
This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](../cmp/trait.partialord#method.ge)


[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#1894)1.16.0
```
impl PartialOrd<IpAddr> for Ipv6Addr
```

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#1896)
```
fn partial_cmp(&self, other: &IpAddr) -> Option<Ordering>
```
This method returns an ordering between `self` and `other` values if one exists. [Read more](../cmp/trait.partialord#tymethod.partial_cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1067)1.0.0
```
fn lt(&self, other: &Rhs) -> bool
```
This method tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](../cmp/trait.partialord#method.lt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1084)1.0.0
```
fn le(&self, other: &Rhs) -> bool
```
This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](../cmp/trait.partialord#method.le)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1100)1.0.0
```
fn gt(&self, other: &Rhs) -> bool
```
This method tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](../cmp/trait.partialord#method.gt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1117)1.0.0
```
fn ge(&self, other: &Rhs) -> bool
```
This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](../cmp/trait.partialord#method.ge)


[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#1041)1.16.0
```
impl PartialOrd<Ipv4Addr> for IpAddr
```

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#1043)
```
fn partial_cmp(&self, other: &Ipv4Addr) -> Option<Ordering>
```
This method returns an ordering between `self` and `other` values if one exists. [Read more](../cmp/trait.partialord#tymethod.partial_cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1067)1.0.0
```
fn lt(&self, other: &Rhs) -> bool
```
This method tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](../cmp/trait.partialord#method.lt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1084)1.0.0
```
fn le(&self, other: &Rhs) -> bool
```
This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](../cmp/trait.partialord#method.le)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1100)1.0.0
```
fn gt(&self, other: &Rhs) -> bool
```
This method tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](../cmp/trait.partialord#method.gt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1117)1.0.0
```
fn ge(&self, other: &Rhs) -> bool
```
This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](../cmp/trait.partialord#method.ge)


[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#1883)1.16.0
```
impl PartialOrd<Ipv6Addr> for IpAddr
```

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#1885)
```
fn partial_cmp(&self, other: &Ipv6Addr) -> Option<Ordering>
```
This method returns an ordering between `self` and `other` values if one exists. [Read more](../cmp/trait.partialord#tymethod.partial_cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1067)1.0.0
```
fn lt(&self, other: &Rhs) -> bool
```
This method tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](../cmp/trait.partialord#method.lt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1084)1.0.0
```
fn le(&self, other: &Rhs) -> bool
```
This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](../cmp/trait.partialord#method.le)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1100)1.0.0
```
fn gt(&self, other: &Rhs) -> bool
```
This method tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](../cmp/trait.partialord#method.gt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1117)1.0.0
```
fn ge(&self, other: &Rhs) -> bool
```
This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](../cmp/trait.partialord#method.ge)


[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#28)
```
impl Copy for IpAddr
```
[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#28)
```
impl Eq for IpAddr
```
[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#28)
```
impl StructuralEq for IpAddr
```
[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#28)
```
impl StructuralPartialEq for IpAddr
```


Auto Trait Implementations
--------------------------




```
impl RefUnwindSafe for IpAddr
```

```
impl Send for IpAddr
```

```
impl Sync for IpAddr
```

```
impl Unpin for IpAddr
```

```
impl UnwindSafe for IpAddr
```


Blanket Implementations
-----------------------



[source](https://doc.rust-lang.org/src/core/any.rs.html#200)
```
impl<T> Any for T
where
    T: 'static + ?Sized,
```

[source](https://doc.rust-lang.org/src/core/any.rs.html#201)
```
fn type_id(&self) -> TypeId
```
Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#208)
```
impl<T> Borrow<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#210)
```
fn borrow(&self) -> &T
```
Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#216)
```
impl<T> BorrowMut<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#217)
```
fn borrow_mut(&mut self) -> &mut T
```
Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#723)
```
impl<T> From<T> for T
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#726)
```
fn from(t: T) -> T
```

Returns the argument unchanged.

 

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#707)
```
impl<T, U> Into<U> for T
where
    U: From<T>,
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#716)
```
fn into(self) -> U
```

Calls `U::from(self)`.

 That is, this conversion is whatever the implementation of `[From](../convert/trait.from "trait std::convert::From")<T> for U` chooses to do.

 

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#82)
```
impl<T> ToOwned for T
where
    T: Clone,
```


```
type Owned = T
```
The resulting type after obtaining ownership.
[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#87)
```
fn to_owned(&self) -> T
```
Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned)

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#91)
```
fn clone_into(&self, target: &mut T)
```
Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2513)
```
impl<T> ToString for T
where
    T: Display + ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2519)
```
default fn to_string(&self) -> String
```
Converts the given value to a `String`. [Read more](../string/trait.tostring#tymethod.to_string)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#763)
```
impl<T, U> TryFrom<U> for T
where
    U: Into<T>,
```


```
type Error = Infallible
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#770)
```
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#748)
```
impl<T, U> TryInto<U> for T
where
    U: TryFrom<T>,
```


```
type Error = <U as TryFrom<T>>::Error
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#755)
```
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
```
Performs the conversion.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/net/enum.IpAddr.html>

Enum std::option::Option
========================



```
pub enum Option<T> {
    None,
    Some(T),
}
```

The `Option` type. See [the module level documentation](index "mod std::option") for more.

 Variants
--------




```
None
```

No value.

 

```
Some(T)
```

Some value of type `T`.

 

Implementations
---------------



[source](https://doc.rust-lang.org/src/core/option.rs.html#578)
```
impl<T> Option<T>
```

[source](https://doc.rust-lang.org/src/core/option.rs.html#598)const: 1.48.0
```
pub const fn is_some(&self) -> bool
```

Returns `true` if the option is a [`Some`](enum.option#variant.Some "variant std::option::Option::Some") value.

 ##### Examples

 
```
let x: Option<u32> = Some(2);
assert_eq!(x.is_some(), true);

let x: Option<u32> = None;
assert_eq!(x.is_some(), false);
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#619)1.70.0
```
pub fn is_some_and(self, f: impl FnOnce(T) -> bool) -> bool
```

Returns `true` if the option is a [`Some`](enum.option#variant.Some "variant std::option::Option::Some") and the value inside of it matches a predicate.

 ##### Examples

 
```
let x: Option<u32> = Some(2);
assert_eq!(x.is_some_and(|x| x > 1), true);

let x: Option<u32> = Some(0);
assert_eq!(x.is_some_and(|x| x > 1), false);

let x: Option<u32> = None;
assert_eq!(x.is_some_and(|x| x > 1), false);
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#642)const: 1.48.0
```
pub const fn is_none(&self) -> bool
```

Returns `true` if the option is a [`None`](enum.option#variant.None "variant std::option::Option::None") value.

 ##### Examples

 
```
let x: Option<u32> = Some(2);
assert_eq!(x.is_none(), false);

let x: Option<u32> = None;
assert_eq!(x.is_none(), true);
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#673)const: 1.48.0
```
pub const fn as_ref(&self) -> Option<&T>
```

Converts from `&Option<T>` to `Option<&T>`.

 ##### Examples

 Calculates the length of an `Option<[String](../string/struct.string "String")>` as an `Option<[usize](../primitive.usize "primitive usize")>` without moving the [`String`](../string/struct.string "String"). The [`map`](enum.option#method.map "method std::option::Option::map") method takes the `self` argument by value, consuming the original, so this technique uses `as_ref` to first take an `Option` to a reference to the value inside the original.

 
```
let text: Option<String> = Some("Hello, world!".to_string());
// First, cast `Option<String>` to `Option<&String>` with `as_ref`,
// then consume *that* with `map`, leaving `text` on the stack.
let text_length: Option<usize> = text.as_ref().map(|s| s.len());
println!("still can print text: {text:?}");
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#695)const: [unstable](https://github.com/rust-lang/rust/issues/67441 "Tracking issue for const_option")
```
pub fn as_mut(&mut self) -> Option<&mut T>
```

Converts from `&mut Option<T>` to `Option<&mut T>`.

 ##### Examples

 
```
let mut x = Some(2);
match x.as_mut() {
    Some(v) => *v = 42,
    None => {},
}
assert_eq!(x, Some(42));
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#709)1.33.0 (const: [unstable](https://github.com/rust-lang/rust/issues/91930 "Tracking issue for const_option_ext"))
```
pub fn as_pin_ref(self: Pin<&Option<T>>) -> Option<Pin<&T>>
```

Converts from `[Pin](../pin/struct.pin "struct std::pin::Pin")<[&](../primitive.reference "shared reference")Option<T>>` to `Option<[Pin](../pin/struct.pin "struct std::pin::Pin")<[&](../primitive.reference "shared reference")T>>`.

 
[source](https://doc.rust-lang.org/src/core/option.rs.html#725)1.33.0 (const: [unstable](https://github.com/rust-lang/rust/issues/91930 "Tracking issue for const_option_ext"))
```
pub fn as_pin_mut(self: Pin<&mut Option<T>>) -> Option<Pin<&mut T>>
```

Converts from `[Pin](../pin/struct.pin "struct std::pin::Pin")<[&mut](../primitive.reference "mutable reference") Option<T>>` to `Option<[Pin](../pin/struct.pin "struct std::pin::Pin")<[&mut](../primitive.reference "mutable reference") T>>`.

 
[source](https://doc.rust-lang.org/src/core/option.rs.html#767)
```
pub fn as_slice(&self) -> &[T]
```

🔬This is a nightly-only experimental API. (`option_as_slice` [#108545](https://github.com/rust-lang/rust/issues/108545))

Returns a slice of the contained value, if any. If this is `None`, an empty slice is returned. This can be useful to have a single type of iterator over an `Option` or slice.

 Note: Should you have an `Option<&T>` and wish to get a slice of `T`, you can unpack it via `opt.map_or(&[], std::slice::from_ref)`.

 ##### Examples

 
```
#![feature(option_as_slice)]

assert_eq!(
    [Some(1234).as_slice(), None.as_slice()],
    [&[1234][..], &[][..]],
);
```
 The inverse of this function is (discounting borrowing) [`[_]::first`](../primitive.slice#method.first "method slice::first"):

 
```
#![feature(option_as_slice)]

for i in [Some(1234_u16), None] {
    assert_eq!(i.as_ref(), i.as_slice().first());
}
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#827)
```
pub fn as_mut_slice(&mut self) -> &mut [T]
```

🔬This is a nightly-only experimental API. (`option_as_slice` [#108545](https://github.com/rust-lang/rust/issues/108545))

Returns a mutable slice of the contained value, if any. If this is `None`, an empty slice is returned. This can be useful to have a single type of iterator over an `Option` or slice.

 Note: Should you have an `Option<&mut T>` instead of a `&mut Option<T>`, which this method takes, you can obtain a mutable slice via `opt.map_or(&mut [], std::slice::from_mut)`.

 ##### Examples

 
```
#![feature(option_as_slice)]

assert_eq!(
    [Some(1234).as_mut_slice(), None.as_mut_slice()],
    [&mut [1234][..], &mut [][..]],
);
```
 The result is a mutable slice of zero or one items that points into our original `Option`:

 
```
#![feature(option_as_slice)]

let mut x = Some(1234);
x.as_mut_slice()[0] += 1;
assert_eq!(x, Some(1235));
```
 The inverse of this method (discounting borrowing) is [`[_]::first_mut`](../primitive.slice#method.first_mut "method slice::first_mut"):

 
```
#![feature(option_as_slice)]

assert_eq!(Some(123).as_mut_slice().first_mut(), Some(&mut 123))
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#895)const: [unstable](https://github.com/rust-lang/rust/issues/67441 "Tracking issue for const_option")
```
pub fn expect(self, msg: &str) -> T
```

Returns the contained [`Some`](enum.option#variant.Some "variant std::option::Option::Some") value, consuming the `self` value.

 ##### Panics

 Panics if the value is a [`None`](enum.option#variant.None "variant std::option::Option::None") with a custom panic message provided by `msg`.

 ##### Examples

 
```
let x = Some("value");
assert_eq!(x.expect("fruits are healthy"), "value");
```
 ⓘ
```
let x: Option<&str> = None;
x.expect("fruits are healthy"); // panics with `fruits are healthy`
```

 ##### Recommended Message Style

 We recommend that `expect` messages are used to describe the reason you *expect* the `Option` should be `Some`.

 ⓘ
```
let item = slice.get(0)
    .expect("slice should not be empty");
```

 **Hint**: If you’re having trouble remembering how to phrase expect 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”.

 For more detail on expect message styles and the reasoning behind our recommendation please refer to the section on [“Common Message Styles”](../error/index#common-message-styles) in the [`std::error`](../error/index) module docs.

 
[source](https://doc.rust-lang.org/src/core/option.rs.html#932)const: [unstable](https://github.com/rust-lang/rust/issues/67441 "Tracking issue for const_option")
```
pub fn unwrap(self) -> T
```

Returns the contained [`Some`](enum.option#variant.Some "variant std::option::Option::Some") value, consuming the `self` value.

 Because this function may panic, its use is generally discouraged. Instead, prefer to use pattern matching and handle the [`None`](enum.option#variant.None "variant std::option::Option::None") case explicitly, or call [`unwrap_or`](enum.option#method.unwrap_or "method std::option::Option::unwrap_or"), [`unwrap_or_else`](enum.option#method.unwrap_or_else "method std::option::Option::unwrap_or_else"), or [`unwrap_or_default`](enum.option#method.unwrap_or_default "method std::option::Option::unwrap_or_default").

 ##### Panics

 Panics if the self value equals [`None`](enum.option#variant.None "variant std::option::Option::None").

 ##### Examples

 
```
let x = Some("air");
assert_eq!(x.unwrap(), "air");
```
 ⓘ
```
let x: Option<&str> = None;
assert_eq!(x.unwrap(), "air"); // fails
```

 
[source](https://doc.rust-lang.org/src/core/option.rs.html#955)
```
pub fn unwrap_or(self, default: T) -> T
```

Returns the contained [`Some`](enum.option#variant.Some "variant std::option::Option::Some") value or a provided default.

 Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing the result of a function call, it is recommended to use [`unwrap_or_else`](enum.option#method.unwrap_or_else "method std::option::Option::unwrap_or_else"), which is lazily evaluated.

 ##### Examples

 
```
assert_eq!(Some("car").unwrap_or("bike"), "car");
assert_eq!(None.unwrap_or("bike"), "bike");
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#973-975)
```
pub fn unwrap_or_else<F>(self, f: F) -> T
where
    F: FnOnce() -> T,
```

Returns the contained [`Some`](enum.option#variant.Some "variant std::option::Option::Some") value or computes it from a closure.

 ##### Examples

 
```
let k = 10;
assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#1004-1006)
```
pub fn unwrap_or_default(self) -> T
where
    T: Default,
```

Returns the contained [`Some`](enum.option#variant.Some "variant std::option::Option::Some") value or a default.

 Consumes the `self` argument then, if [`Some`](enum.option#variant.Some "variant std::option::Option::Some"), returns the contained value, otherwise if [`None`](enum.option#variant.None "variant std::option::Option::None"), returns the [default value](../default/trait.default#tymethod.default "associated function std::default::Default::default") for that type.

 ##### Examples

 
```
let x: Option<u32> = None;
let y: Option<u32> = Some(12);

assert_eq!(x.unwrap_or_default(), 0);
assert_eq!(y.unwrap_or_default(), 12);
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#1038)1.58.0 (const: [unstable](https://github.com/rust-lang/rust/issues/91930 "Tracking issue for const_option_ext"))
```
pub unsafe fn unwrap_unchecked(self) -> T
```

Returns the contained [`Some`](enum.option#variant.Some "variant std::option::Option::Some") value, consuming the `self` value, without checking that the value is not [`None`](enum.option#variant.None "variant std::option::Option::None").

 ##### Safety

 Calling this method on [`None`](enum.option#variant.None "variant std::option::Option::None") is *[undefined behavior](../../reference/behavior-considered-undefined)*.

 ##### Examples

 
```
let x = Some("air");
assert_eq!(unsafe { x.unwrap_unchecked() }, "air");
```
 
```
let x: Option<&str> = None;
assert_eq!(unsafe { x.unwrap_unchecked() }, "air"); // Undefined behavior!
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#1070-1072)
```
pub fn map<U, F>(self, f: F) -> Option<U>
where
    F: FnOnce(T) -> U,
```

Maps an `Option<T>` to `Option<U>` by applying a function to a contained value (if `Some`) or returns `None` (if `None`).

 ##### Examples

 Calculates the length of an `Option<[String](../string/struct.string "String")>` as an `Option<[usize](../primitive.usize "primitive usize")>`, consuming the original:

 
```
let maybe_some_string = Some(String::from("Hello, World!"));
// `Option::map` takes self *by value*, consuming `maybe_some_string`
let maybe_some_len = maybe_some_string.map(|s| s.len());
assert_eq!(maybe_some_len, Some(13));

let x: Option<&str> = None;
assert_eq!(x.map(|s| s.len()), None);
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#1097-1099)
```
pub fn inspect<F>(self, f: F) -> Option<T>
where
    F: FnOnce(&T),
```

🔬This is a nightly-only experimental API. (`result_option_inspect` [#91345](https://github.com/rust-lang/rust/issues/91345))

Calls the provided closure with a reference to the contained value (if [`Some`](enum.option#variant.Some "variant std::option::Option::Some")).

 ##### Examples

 
```
#![feature(result_option_inspect)]

let v = vec![1, 2, 3, 4, 5];

// prints "got: 4"
let x: Option<&usize> = v.get(3).inspect(|x| println!("got: {x}"));

// prints nothing
let x: Option<&usize> = v.get(5).inspect(|x| println!("got: {x}"));
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#1128-1130)
```
pub fn map_or<U, F>(self, default: U, f: F) -> U
where
    F: FnOnce(T) -> U,
```

Returns the provided default result (if none), or applies a function to the contained value (if any).

 Arguments passed to `map_or` are eagerly evaluated; if you are passing the result of a function call, it is recommended to use [`map_or_else`](enum.option#method.map_or_else "method std::option::Option::map_or_else"), which is lazily evaluated.

 ##### Examples

 
```
let x = Some("foo");
assert_eq!(x.map_or(42, |v| v.len()), 3);

let x: Option<&str> = None;
assert_eq!(x.map_or(42, |v| v.len()), 42);
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#1154-1157)
```
pub fn map_or_else<U, D, F>(self, default: D, f: F) -> U
where
    D: FnOnce() -> U,
    F: FnOnce(T) -> U,
```

Computes a default function result (if none), or applies a different function to the contained value (if any).

 ##### Examples

 
```
let k = 21;

let x = Some("foo");
assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);

let x: Option<&str> = None;
assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#1188)
```
pub fn ok_or<E>(self, err: E) -> Result<T, E>
```

Transforms the `Option<T>` into a [`Result<T, E>`](../result/enum.result "enum std::result::Result"), mapping [`Some(v)`](enum.option#variant.Some "variant std::option::Option::Some") to [`Ok(v)`](../result/enum.result#variant.Ok "variant std::result::Result::Ok") and [`None`](enum.option#variant.None "variant std::option::Option::None") to [`Err(err)`](../result/enum.result#variant.Err "variant std::result::Result::Err").

 Arguments passed to `ok_or` are eagerly evaluated; if you are passing the result of a function call, it is recommended to use [`ok_or_else`](enum.option#method.ok_or_else "method std::option::Option::ok_or_else"), which is lazily evaluated.

 ##### Examples

 
```
let x = Some("foo");
assert_eq!(x.ok_or(0), Ok("foo"));

let x: Option<&str> = None;
assert_eq!(x.ok_or(0), Err(0));
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#1213-1215)
```
pub fn ok_or_else<E, F>(self, err: F) -> Result<T, E>
where
    F: FnOnce() -> E,
```

Transforms the `Option<T>` into a [`Result<T, E>`](../result/enum.result "enum std::result::Result"), mapping [`Some(v)`](enum.option#variant.Some "variant std::option::Option::Some") to [`Ok(v)`](../result/enum.result#variant.Ok "variant std::result::Result::Ok") and [`None`](enum.option#variant.None "variant std::option::Option::None") to [`Err(err())`](../result/enum.result#variant.Err "variant std::result::Result::Err").

 ##### Examples

 
```
let x = Some("foo");
assert_eq!(x.ok_or_else(|| 0), Ok("foo"));

let x: Option<&str> = None;
assert_eq!(x.ok_or_else(|| 0), Err(0));
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#1239-1241)1.40.0
```
pub fn as_deref(&self) -> Option<&<T as Deref>::Target>
where
    T: Deref,
```

Converts from `Option<T>` (or `&Option<T>`) to `Option<&T::Target>`.

 Leaves the original Option in-place, creating a new one with a reference to the original one, additionally coercing the contents via [`Deref`](../ops/trait.deref "trait std::ops::Deref").

 ##### Examples

 
```
let x: Option<String> = Some("hey".to_owned());
assert_eq!(x.as_deref(), Some("hey"));

let x: Option<String> = None;
assert_eq!(x.as_deref(), None);
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#1265-1267)1.40.0
```
pub fn as_deref_mut(&mut self) -> Option<&mut <T as Deref>::Target>
where
    T: DerefMut,
```

Converts from `Option<T>` (or `&mut Option<T>`) to `Option<&mut T::Target>`.

 Leaves the original `Option` in-place, creating a new one containing a mutable reference to the inner type’s [`Deref::Target`](../ops/trait.deref#associatedtype.Target "associated type std::ops::Deref::Target") type.

 ##### Examples

 
```
let mut x: Option<String> = Some("hey".to_owned());
assert_eq!(x.as_deref_mut().map(|x| {
    x.make_ascii_uppercase();
    x
}), Some("HEY".to_owned().as_mut_str()));
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#1293)const: [unstable](https://github.com/rust-lang/rust/issues/67441 "Tracking issue for const_option")
```
pub fn iter(&self) -> Iter<'_, T> ⓘ
```

Returns an iterator over the possibly contained value.

 ##### Examples

 
```
let x = Some(4);
assert_eq!(x.iter().next(), Some(&4));

let x: Option<u32> = None;
assert_eq!(x.iter().next(), None);
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#1314)
```
pub fn iter_mut(&mut self) -> IterMut<'_, T> ⓘ
```

Returns a mutable iterator over the possibly contained value.

 ##### Examples

 
```
let mut x = Some(4);
match x.iter_mut().next() {
    Some(v) => *v = 42,
    None => {},
}
assert_eq!(x, Some(42));

let mut x: Option<u32> = None;
assert_eq!(x.iter_mut().next(), None);
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#1351)
```
pub fn and<U>(self, optb: Option<U>) -> Option<U>
```

Returns [`None`](enum.option#variant.None "variant std::option::Option::None") if the option is [`None`](enum.option#variant.None "variant std::option::Option::None"), otherwise returns `optb`.

 Arguments passed to `and` are eagerly evaluated; if you are passing the result of a function call, it is recommended to use [`and_then`](enum.option#method.and_then "method std::option::Option::and_then"), which is lazily evaluated.

 ##### Examples

 
```
let x = Some(2);
let y: Option<&str> = None;
assert_eq!(x.and(y), None);

let x: Option<u32> = None;
let y = Some("foo");
assert_eq!(x.and(y), None);

let x = Some(2);
let y = Some("foo");
assert_eq!(x.and(y), Some("foo"));

let x: Option<u32> = None;
let y: Option<&str> = None;
assert_eq!(x.and(y), None);
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#1388-1390)
```
pub fn and_then<U, F>(self, f: F) -> Option<U>
where
    F: FnOnce(T) -> Option<U>,
```

Returns [`None`](enum.option#variant.None "variant std::option::Option::None") if the option is [`None`](enum.option#variant.None "variant std::option::Option::None"), otherwise calls `f` with the wrapped value and returns the result.

 Some languages call this operation flatmap.

 ##### Examples

 
```
fn sq_then_to_string(x: u32) -> Option<String> {
    x.checked_mul(x).map(|sq| sq.to_string())
}

assert_eq!(Some(2).and_then(sq_then_to_string), Some(4.to_string()));
assert_eq!(Some(1_000_000).and_then(sq_then_to_string), None); // overflowed!
assert_eq!(None.and_then(sq_then_to_string), None);
```
 Often used to chain fallible operations that may return [`None`](enum.option#variant.None "variant std::option::Option::None").

 
```
let arr_2d = [["A0", "A1"], ["B0", "B1"]];

let item_0_1 = arr_2d.get(0).and_then(|row| row.get(1));
assert_eq!(item_0_1, Some(&"A1"));

let item_2_0 = arr_2d.get(2).and_then(|row| row.get(0));
assert_eq!(item_2_0, None);
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#1424-1426)1.27.0
```
pub fn filter<P>(self, predicate: P) -> Option<T>
where
    P: FnOnce(&T) -> bool,
```

Returns [`None`](enum.option#variant.None "variant std::option::Option::None") if the option is [`None`](enum.option#variant.None "variant std::option::Option::None"), otherwise calls `predicate` with the wrapped value and returns:

 * [`Some(t)`](enum.option#variant.Some "variant std::option::Option::Some") if `predicate` returns `true` (where `t` is the wrapped value), and
* [`None`](enum.option#variant.None "variant std::option::Option::None") if `predicate` returns `false`.

 This function works similar to [`Iterator::filter()`](../iter/trait.iterator#method.filter "method std::iter::Iterator::filter"). You can imagine the `Option<T>` being an iterator over one or zero elements. `filter()` lets you decide which elements to keep.

 ##### Examples

 
```
fn is_even(n: &i32) -> bool {
    n % 2 == 0
}

assert_eq!(None.filter(is_even), None);
assert_eq!(Some(3).filter(is_even), None);
assert_eq!(Some(4).filter(is_even), Some(4));
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#1465)
```
pub fn or(self, optb: Option<T>) -> Option<T>
```

Returns the option if it contains a value, otherwise returns `optb`.

 Arguments passed to `or` are eagerly evaluated; if you are passing the result of a function call, it is recommended to use [`or_else`](enum.option#method.or_else "method std::option::Option::or_else"), which is lazily evaluated.

 ##### Examples

 
```
let x = Some(2);
let y = None;
assert_eq!(x.or(y), Some(2));

let x = None;
let y = Some(100);
assert_eq!(x.or(y), Some(100));

let x = Some(2);
let y = Some(100);
assert_eq!(x.or(y), Some(2));

let x: Option<u32> = None;
let y = None;
assert_eq!(x.or(y), None);
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#1487-1489)
```
pub fn or_else<F>(self, f: F) -> Option<T>
where
    F: FnOnce() -> Option<T>,
```

Returns the option if it contains a value, otherwise calls `f` and returns the result.

 ##### Examples

 
```
fn nobody() -> Option<&'static str> { None }
fn vikings() -> Option<&'static str> { Some("vikings") }

assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
assert_eq!(None.or_else(vikings), Some("vikings"));
assert_eq!(None.or_else(nobody), None);
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#1520)1.37.0
```
pub fn xor(self, optb: Option<T>) -> Option<T>
```

Returns [`Some`](enum.option#variant.Some "variant std::option::Option::Some") if exactly one of `self`, `optb` is [`Some`](enum.option#variant.Some "variant std::option::Option::Some"), otherwise returns [`None`](enum.option#variant.None "variant std::option::Option::None").

 ##### Examples

 
```
let x = Some(2);
let y: Option<u32> = None;
assert_eq!(x.xor(y), Some(2));

let x: Option<u32> = None;
let y = Some(2);
assert_eq!(x.xor(y), Some(2));

let x = Some(2);
let y = Some(2);
assert_eq!(x.xor(y), None);

let x: Option<u32> = None;
let y: Option<u32> = None;
assert_eq!(x.xor(y), None);
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#1554)1.53.0
```
pub fn insert(&mut self, value: T) -> &mut T
```

Inserts `value` into the option, then returns a mutable reference to it.

 If the option already contains a value, the old value is dropped.

 See also [`Option::get_or_insert`](enum.option#method.get_or_insert "method std::option::Option::get_or_insert"), which doesn’t update the value if the option already contains [`Some`](enum.option#variant.Some "variant std::option::Option::Some").

 ##### Example

 
```
let mut opt = None;
let val = opt.insert(1);
assert_eq!(*val, 1);
assert_eq!(opt.unwrap(), 1);
let val = opt.insert(2);
assert_eq!(*val, 2);
*val = 3;
assert_eq!(opt.unwrap(), 3);
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#1583)1.20.0
```
pub fn get_or_insert(&mut self, value: T) -> &mut T
```

Inserts `value` into the option if it is [`None`](enum.option#variant.None "variant std::option::Option::None"), then returns a mutable reference to the contained value.

 See also [`Option::insert`](enum.option#method.insert "method std::option::Option::insert"), which updates the value even if the option already contains [`Some`](enum.option#variant.Some "variant std::option::Option::Some").

 ##### Examples

 
```
let mut x = None;

{
    let y: &mut u32 = x.get_or_insert(5);
    assert_eq!(y, &5);

    *y = 7;
}

assert_eq!(x, Some(7));
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#1614-1616)
```
pub fn get_or_insert_default(&mut self) -> &mut T
where
    T: Default,
```

🔬This is a nightly-only experimental API. (`option_get_or_insert_default` [#82901](https://github.com/rust-lang/rust/issues/82901))

Inserts the default value into the option if it is [`None`](enum.option#variant.None "variant std::option::Option::None"), then returns a mutable reference to the contained value.

 ##### Examples

 
```
#![feature(option_get_or_insert_default)]

let mut x = None;

{
    let y: &mut u32 = x.get_or_insert_default();
    assert_eq!(y, &0);

    *y = 7;
}

assert_eq!(x, Some(7));
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#1640-1642)1.20.0
```
pub fn get_or_insert_with<F>(&mut self, f: F) -> &mut T
where
    F: FnOnce() -> T,
```

Inserts a value computed from `f` into the option if it is [`None`](enum.option#variant.None "variant std::option::Option::None"), then returns a mutable reference to the contained value.

 ##### Examples

 
```
let mut x = None;

{
    let y: &mut u32 = x.get_or_insert_with(|| 5);
    assert_eq!(y, &5);

    *y = 7;
}

assert_eq!(x, Some(7));
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#1675)const: [unstable](https://github.com/rust-lang/rust/issues/67441 "Tracking issue for const_option")
```
pub fn take(&mut self) -> Option<T>
```

Takes the value out of the option, leaving a [`None`](enum.option#variant.None "variant std::option::Option::None") in its place.

 ##### Examples

 
```
let mut x = Some(2);
let y = x.take();
assert_eq!(x, None);
assert_eq!(y, Some(2));

let mut x: Option<u32> = None;
let y = x.take();
assert_eq!(x, None);
assert_eq!(y, None);
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#1700)1.31.0 (const: [unstable](https://github.com/rust-lang/rust/issues/67441 "Tracking issue for const_option"))
```
pub fn replace(&mut self, value: T) -> Option<T>
```

Replaces the actual value in the option by the value given in parameter, returning the old value if present, leaving a [`Some`](enum.option#variant.Some "variant std::option::Option::Some") in its place without deinitializing either one.

 ##### Examples

 
```
let mut x = Some(2);
let old = x.replace(5);
assert_eq!(x, Some(5));
assert_eq!(old, Some(2));

let mut x = None;
let old = x.replace(3);
assert_eq!(x, Some(3));
assert_eq!(old, None);
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#1720)1.46.0
```
pub fn zip<U>(self, other: Option<U>) -> Option<(T, U)>
```

Zips `self` with another `Option`.

 If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some((s, o))`. Otherwise, `None` is returned.

 ##### Examples

 
```
let x = Some(1);
let y = Some("hi");
let z = None::<u8>;

assert_eq!(x.zip(y), Some((1, "hi")));
assert_eq!(x.zip(z), None);
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#1756-1758)
```
pub fn zip_with<U, F, R>(self, other: Option<U>, f: F) -> Option<R>
where
    F: FnOnce(T, U) -> R,
```

🔬This is a nightly-only experimental API. (`option_zip` [#70086](https://github.com/rust-lang/rust/issues/70086))

Zips `self` and another `Option` with function `f`.

 If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some(f(s, o))`. Otherwise, `None` is returned.

 ##### Examples

 
```
#![feature(option_zip)]

#[derive(Debug, PartialEq)]
struct Point {
    x: f64,
    y: f64,
}

impl Point {
    fn new(x: f64, y: f64) -> Self {
        Self { x, y }
    }
}

let x = Some(17.5);
let y = Some(42.7);

assert_eq!(x.zip_with(y, Point::new), Some(Point { x: 17.5, y: 42.7 }));
assert_eq!(x.zip_with(None, Point::new), None);
```
 

[source](https://doc.rust-lang.org/src/core/option.rs.html#1767)
```
impl<T, U> Option<(T, U)>
```

[source](https://doc.rust-lang.org/src/core/option.rs.html#1784)1.66.0
```
pub fn unzip(self) -> (Option<T>, Option<U>)
```

Unzips an option containing a tuple of two options.

 If `self` is `Some((a, b))` this method returns `(Some(a), Some(b))`. Otherwise, `(None, None)` is returned.

 ##### Examples

 
```
let x = Some((1, "hi"));
let y = None::<(u8, u32)>;

assert_eq!(x.unzip(), (Some(1), Some("hi")));
assert_eq!(y.unzip(), (None, None));
```
 

[source](https://doc.rust-lang.org/src/core/option.rs.html#1792)
```
impl<T> Option<&T>
```

[source](https://doc.rust-lang.org/src/core/option.rs.html#1808-1810)1.35.0 (const: [unstable](https://github.com/rust-lang/rust/issues/67441 "Tracking issue for const_option"))
```
pub fn copied(self) -> Option<T>
where
    T: Copy,
```

Maps an `Option<&T>` to an `Option<T>` by copying the contents of the option.

 ##### Examples

 
```
let x = 12;
let opt_x = Some(&x);
assert_eq!(opt_x, Some(&12));
let copied = opt_x.copied();
assert_eq!(copied, Some(12));
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#1834-1836)
```
pub fn cloned(self) -> Option<T>
where
    T: Clone,
```

Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the option.

 ##### Examples

 
```
let x = 12;
let opt_x = Some(&x);
assert_eq!(opt_x, Some(&12));
let cloned = opt_x.cloned();
assert_eq!(cloned, Some(12));
```
 

[source](https://doc.rust-lang.org/src/core/option.rs.html#1845)
```
impl<T> Option<&mut T>
```

[source](https://doc.rust-lang.org/src/core/option.rs.html#1861-1863)1.35.0 (const: [unstable](https://github.com/rust-lang/rust/issues/91930 "Tracking issue for const_option_ext"))
```
pub fn copied(self) -> Option<T>
where
    T: Copy,
```

Maps an `Option<&mut T>` to an `Option<T>` by copying the contents of the option.

 ##### Examples

 
```
let mut x = 12;
let opt_x = Some(&mut x);
assert_eq!(opt_x, Some(&mut 12));
let copied = opt_x.copied();
assert_eq!(copied, Some(12));
```
 
[source](https://doc.rust-lang.org/src/core/option.rs.html#1885-1887)1.26.0
```
pub fn cloned(self) -> Option<T>
where
    T: Clone,
```

Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the option.

 ##### Examples

 
```
let mut x = 12;
let opt_x = Some(&mut x);
assert_eq!(opt_x, Some(&mut 12));
let cloned = opt_x.cloned();
assert_eq!(cloned, Some(12));
```
 

[source](https://doc.rust-lang.org/src/core/option.rs.html#1896)
```
impl<T, E> Option<Result<T, E>>
```

[source](https://doc.rust-lang.org/src/core/option.rs.html#1916)1.33.0 (const: [unstable](https://github.com/rust-lang/rust/issues/67441 "Tracking issue for const_option"))
```
pub fn transpose(self) -> Result<Option<T>, E>
```

Transposes an `Option` of a [`Result`](../result/enum.result "enum std::result::Result") into a [`Result`](../result/enum.result "enum std::result::Result") of an `Option`.

 [`None`](enum.option#variant.None "variant std::option::Option::None") will be mapped to `[Ok](../result/enum.result#variant.Ok "variant std::result::Result::Ok")([None](enum.option#variant.None "variant std::option::Option::None"))`. `[Some](enum.option#variant.Some "variant std::option::Option::Some")([Ok](../result/enum.result#variant.Ok "variant std::result::Result::Ok")(_))` and `[Some](enum.option#variant.Some "variant std::option::Option::Some")([Err](../result/enum.result#variant.Err "variant std::result::Result::Err")(_))` will be mapped to `[Ok](../result/enum.result#variant.Ok "variant std::result::Result::Ok")([Some](enum.option#variant.Some "variant std::option::Option::Some")(_))` and `[Err](../result/enum.result#variant.Err "variant std::result::Result::Err")(_)`.

 ##### Examples

 
```
#[derive(Debug, Eq, PartialEq)]
struct SomeErr;

let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
assert_eq!(x, y.transpose());
```
 

[source](https://doc.rust-lang.org/src/core/option.rs.html#2453)
```
impl<T> Option<Option<T>>
```

[source](https://doc.rust-lang.org/src/core/option.rs.html#2481)1.40.0 (const: [unstable](https://github.com/rust-lang/rust/issues/67441 "Tracking issue for const_option"))
```
pub fn flatten(self) -> Option<T>
```

Converts from `Option<Option<T>>` to `Option<T>`.

 ##### Examples

 Basic usage:

 
```
let x: Option<Option<u32>> = Some(Some(6));
assert_eq!(Some(6), x.flatten());

let x: Option<Option<u32>> = Some(None);
assert_eq!(None, x.flatten());

let x: Option<Option<u32>> = None;
assert_eq!(None, x.flatten());
```
 Flattening only removes one level of nesting at a time:

 
```
let x: Option<Option<Option<u32>>> = Some(Some(Some(6)));
assert_eq!(Some(Some(6)), x.flatten());
assert_eq!(Some(6), x.flatten().flatten());
```
 


Trait Implementations
---------------------



[source](https://doc.rust-lang.org/src/core/option.rs.html#1940)
```
impl<T> Clone for Option<T>
where
    T: Clone,
```

[source](https://doc.rust-lang.org/src/core/option.rs.html#1945)
```
fn clone(&self) -> Option<T>
```
Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone)

[source](https://doc.rust-lang.org/src/core/option.rs.html#1953)
```
fn clone_from(&mut self, source: &Option<T>)
```
Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from)


[source](https://doc.rust-lang.org/src/core/option.rs.html#559)
```
impl<T> Debug for Option<T>
where
    T: Debug,
```

[source](https://doc.rust-lang.org/src/core/option.rs.html#559)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt)


[source](https://doc.rust-lang.org/src/core/option.rs.html#1962)
```
impl<T> Default for Option<T>
```

[source](https://doc.rust-lang.org/src/core/option.rs.html#1972)
```
fn default() -> Option<T>
```

Returns [`None`](enum.option#variant.None "variant std::option::Option::None").

 ##### Examples

 
```
let opt: Option<u32> = Option::default();
assert!(opt.is_none());
```
 

[source](https://doc.rust-lang.org/src/core/option.rs.html#2038)1.30.0
```
impl<'a, T> From<&'a Option<T>> for Option<&'a T>
```

[source](https://doc.rust-lang.org/src/core/option.rs.html#2059)
```
fn from(o: &'a Option<T>) -> Option<&'a T>
```

Converts from `&Option<T>` to `Option<&T>`.

 ##### Examples

 Converts an `[Option](enum.option "enum std::option::Option")<[String](../string/struct.string "String")>` into an `[Option](enum.option "enum std::option::Option")<[usize](../primitive.usize "primitive usize")>`, preserving the original. The [`map`](enum.option#method.map "method std::option::Option::map") method takes the `self` argument by value, consuming the original, so this technique uses `from` to first take an [`Option`](enum.option "enum std::option::Option") to a reference to the value inside the original.

 
```
let s: Option<String> = Some(String::from("Hello, Rustaceans!"));
let o: Option<usize> = Option::from(&s).map(|ss: &String| ss.len());

println!("Can still print s: {s:?}");

assert_eq!(o, Some(18));
```
 

[source](https://doc.rust-lang.org/src/core/option.rs.html#2065)1.30.0
```
impl<'a, T> From<&'a mut Option<T>> for Option<&'a mut T>
```

[source](https://doc.rust-lang.org/src/core/option.rs.html#2081)
```
fn from(o: &'a mut Option<T>) -> Option<&'a mut T>
```

Converts from `&mut Option<T>` to `Option<&mut T>`

 ##### Examples

 
```
let mut s = Some(String::from("Hello"));
let o: Option<&mut String> = Option::from(&mut s);

match o {
    Some(t) => *t = String::from("Hello, Rustaceans!"),
    None => (),
}

assert_eq!(s, Some(String::from("Hello, Rustaceans!")));
```
 

[source](https://doc.rust-lang.org/src/core/option.rs.html#2022)1.12.0
```
impl<T> From<T> for Option<T>
```

[source](https://doc.rust-lang.org/src/core/option.rs.html#2032)
```
fn from(val: T) -> Option<T>
```

Moves `val` into a new [`Some`](enum.option#variant.Some "variant std::option::Option::Some").

 ##### Examples

 
```
let o: Option<u8> = Option::from(67);

assert_eq!(Some(67), o);
```
 

[source](https://doc.rust-lang.org/src/core/option.rs.html#2341)
```
impl<A, V> FromIterator<Option<A>> for Option<V>
where
    V: FromIterator<A>,
```

[source](https://doc.rust-lang.org/src/core/option.rs.html#2403)
```
fn from_iter<I>(iter: I) -> Option<V>
where
    I: IntoIterator<Item = Option<A>>,
```

Takes each element in the [`Iterator`](../iter/trait.iterator "trait std::iter::Iterator"): if it is [`None`](enum.option#variant.None "variant std::option::Option::None"), no further elements are taken, and the [`None`](enum.option#variant.None "variant std::option::Option::None") is returned. Should no [`None`](enum.option#variant.None "variant std::option::Option::None") occur, a container of type `V` containing the values of each [`Option`](enum.option "enum std::option::Option") is returned.

 ##### Examples

 Here is an example which increments every integer in a vector. We use the checked variant of `add` that returns `None` when the calculation would result in an overflow.

 
```
let items = vec![0_u16, 1, 2];

let res: Option<Vec<u16>> = items
    .iter()
    .map(|x| x.checked_add(1))
    .collect();

assert_eq!(res, Some(vec![1, 2, 3]));
```
 As you can see, this will return the expected, valid items.

 Here is another example that tries to subtract one from another list of integers, this time checking for underflow:

 
```
let items = vec![2_u16, 1, 0];

let res: Option<Vec<u16>> = items
    .iter()
    .map(|x| x.checked_sub(1))
    .collect();

assert_eq!(res, None);
```
 Since the last element is zero, it would underflow. Thus, the resulting value is `None`.

 Here is a variation on the previous example, showing that no further elements are taken from `iter` after the first `None`.

 
```
let items = vec![3_u16, 2, 1, 10];

let mut shared = 0;

let res: Option<Vec<u16>> = items
    .iter()
    .map(|x| { shared += x; x.checked_sub(2) })
    .collect();

assert_eq!(res, None);
assert_eq!(shared, 6);
```
 Since the third element caused an underflow, no further elements were taken, so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.

 

[source](https://doc.rust-lang.org/src/core/option.rs.html#2431)
```
impl<T> FromResidual<<Option<T> as Try>::Residual> for Option<T>
```

[source](https://doc.rust-lang.org/src/core/option.rs.html#2433)
```
fn from_residual(residual: Option<Infallible>) -> Option<T>
```

🔬This is a nightly-only experimental API. (`try_trait_v2` [#84277](https://github.com/rust-lang/rust/issues/84277))
Constructs the type from a compatible `Residual` type. [Read more](../ops/trait.fromresidual#tymethod.from_residual)


[source](https://doc.rust-lang.org/src/core/option.rs.html#2441)
```
impl<T> FromResidual<Yeet<()>> for Option<T>
```

[source](https://doc.rust-lang.org/src/core/option.rs.html#2443)
```
fn from_residual(_: Yeet<()>) -> Option<T>
```

🔬This is a nightly-only experimental API. (`try_trait_v2` [#84277](https://github.com/rust-lang/rust/issues/84277))
Constructs the type from a compatible `Residual` type. [Read more](../ops/trait.fromresidual#tymethod.from_residual)


[source](https://doc.rust-lang.org/src/core/option.rs.html#559)
```
impl<T> Hash for Option<T>
where
    T: Hash,
```

[source](https://doc.rust-lang.org/src/core/option.rs.html#559)
```
fn hash<__H>(&self, state: &mut __H)
where
    __H: Hasher,
```
Feeds this value into the given [`Hasher`](../hash/trait.hasher "trait std::hash::Hasher"). [Read more](../hash/trait.hash#tymethod.hash)

[source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#237-239)1.3.0
```
fn hash_slice<H>(data: &[Self], state: &mut H)
where
    H: Hasher,
    Self: Sized,
```
Feeds a slice of this type into the given [`Hasher`](../hash/trait.hasher "trait std::hash::Hasher"). [Read more](../hash/trait.hash#method.hash_slice)


[source](https://doc.rust-lang.org/src/core/option.rs.html#2002)1.4.0
```
impl<'a, T> IntoIterator for &'a Option<T>
```


```
type Item = &'a T
```
The type of the elements being iterated over.

```
type IntoIter = Iter<'a, T>
```
Which kind of iterator are we turning this into?
[source](https://doc.rust-lang.org/src/core/option.rs.html#2006)
```
fn into_iter(self) -> Iter<'a, T> ⓘ
```
Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter)


[source](https://doc.rust-lang.org/src/core/option.rs.html#2012)1.4.0
```
impl<'a, T> IntoIterator for &'a mut Option<T>
```


```
type Item = &'a mut T
```
The type of the elements being iterated over.

```
type IntoIter = IterMut<'a, T>
```
Which kind of iterator are we turning this into?
[source](https://doc.rust-lang.org/src/core/option.rs.html#2016)
```
fn into_iter(self) -> IterMut<'a, T> ⓘ
```
Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter)


[source](https://doc.rust-lang.org/src/core/option.rs.html#1978)
```
impl<T> IntoIterator for Option<T>
```

[source](https://doc.rust-lang.org/src/core/option.rs.html#1996)
```
fn into_iter(self) -> IntoIter<T> ⓘ
```

Returns a consuming iterator over the possibly contained value.

 ##### Examples

 
```
let x = Some("string");
let v: Vec<&str> = x.into_iter().collect();
assert_eq!(v, ["string"]);

let x = None;
let v: Vec<&str> = x.into_iter().collect();
assert!(v.is_empty());
```
 

```
type Item = T
```
The type of the elements being iterated over.

```
type IntoIter = IntoIter<T>
```
Which kind of iterator are we turning this into?

[source](https://doc.rust-lang.org/src/core/option.rs.html#559)
```
impl<T> Ord for Option<T>
where
    T: Ord,
```

[source](https://doc.rust-lang.org/src/core/option.rs.html#559)
```
fn cmp(&self, other: &Option<T>) -> Ordering
```
This method returns an [`Ordering`](../cmp/enum.ordering "enum std::cmp::Ordering") between `self` and `other`. [Read more](../cmp/trait.ord#tymethod.cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#790-792)1.21.0
```
fn max(self, other: Self) -> Self
where
    Self: Sized,
```
Compares and returns the maximum of two values. [Read more](../cmp/trait.ord#method.max)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#810-812)1.21.0
```
fn min(self, other: Self) -> Self
where
    Self: Sized,
```
Compares and returns the minimum of two values. [Read more](../cmp/trait.ord#method.min)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#835-838)1.50.0
```
fn clamp(self, min: Self, max: Self) -> Self
where
    Self: Sized + PartialOrd<Self>,
```
Restrict a value to a certain interval. [Read more](../cmp/trait.ord#method.clamp)


[source](https://doc.rust-lang.org/src/core/option.rs.html#2089)
```
impl<T> PartialEq<Option<T>> for Option<T>
where
    T: PartialEq<T>,
```

[source](https://doc.rust-lang.org/src/core/option.rs.html#2091)
```
fn eq(&self, other: &Option<T>) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#226)
```
fn ne(&self, other: &Rhs) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/option.rs.html#559)
```
impl<T> PartialOrd<Option<T>> for Option<T>
where
    T: PartialOrd<T>,
```

[source](https://doc.rust-lang.org/src/core/option.rs.html#559)
```
fn partial_cmp(&self, other: &Option<T>) -> Option<Ordering>
```
This method returns an ordering between `self` and `other` values if one exists. [Read more](../cmp/trait.partialord#tymethod.partial_cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1067)
```
fn lt(&self, other: &Rhs) -> bool
```
This method tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](../cmp/trait.partialord#method.lt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1084)
```
fn le(&self, other: &Rhs) -> bool
```
This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](../cmp/trait.partialord#method.le)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1100)
```
fn gt(&self, other: &Rhs) -> bool
```
This method tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](../cmp/trait.partialord#method.gt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1117)
```
fn ge(&self, other: &Rhs) -> bool
```
This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](../cmp/trait.partialord#method.ge)


[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#244)1.37.0
```
impl<T, U> Product<Option<U>> for Option<T>
where
    T: Product<U>,
```

[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#265-267)
```
fn product<I>(iter: I) -> Option<T>
where
    I: Iterator<Item = Option<U>>,
```

Takes each element in the [`Iterator`](../iter/trait.iterator "trait std::iter::Iterator"): if it is a [`None`](enum.option#variant.None "variant std::option::Option::None"), no further elements are taken, and the [`None`](enum.option#variant.None "variant std::option::Option::None") is returned. Should no [`None`](enum.option#variant.None "variant std::option::Option::None") occur, the product of all elements is returned.

 ##### Examples

 This multiplies each number in a vector of strings, if a string could not be parsed the operation returns `None`:

 
```
let nums = vec!["5", "10", "1", "2"];
let total: Option<usize> = nums.iter().map(|w| w.parse::<usize>().ok()).product();
assert_eq!(total, Some(100));
let nums = vec!["5", "10", "one", "2"];
let total: Option<usize> = nums.iter().map(|w| w.parse::<usize>().ok()).product();
assert_eq!(total, None);
```
 

[source](https://doc.rust-lang.org/src/core/option.rs.html#2449)
```
impl<T> Residual<T> for Option<Infallible>
```


```
type TryType = Option<T>
```

🔬This is a nightly-only experimental API. (`try_trait_v2_residual` [#91285](https://github.com/rust-lang/rust/issues/91285))
The “return” type of this meta-function.

[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#214)1.37.0
```
impl<T, U> Sum<Option<U>> for Option<T>
where
    T: Sum<U>,
```

[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#235-237)
```
fn sum<I>(iter: I) -> Option<T>
where
    I: Iterator<Item = Option<U>>,
```

Takes each element in the [`Iterator`](../iter/trait.iterator "trait std::iter::Iterator"): if it is a [`None`](enum.option#variant.None "variant std::option::Option::None"), no further elements are taken, and the [`None`](enum.option#variant.None "variant std::option::Option::None") is returned. Should no [`None`](enum.option#variant.None "variant std::option::Option::None") occur, the sum of all elements is returned.

 ##### Examples

 This sums up the position of the character ‘a’ in a vector of strings, if a word did not have the character ‘a’ the operation returns `None`:

 
```
let words = vec!["have", "a", "great", "day"];
let total: Option<usize> = words.iter().map(|w| w.find('a')).sum();
assert_eq!(total, Some(5));
let words = vec!["have", "a", "good", "day"];
let total: Option<usize> = words.iter().map(|w| w.find('a')).sum();
assert_eq!(total, None);
```
 

[source](https://doc.rust-lang.org/src/core/option.rs.html#2412)
```
impl<T> Try for Option<T>
```


```
type Output = T
```

🔬This is a nightly-only experimental API. (`try_trait_v2` [#84277](https://github.com/rust-lang/rust/issues/84277))
The type of the value produced by `?` when *not* short-circuiting.

```
type Residual = Option<Infallible>
```

🔬This is a nightly-only experimental API. (`try_trait_v2` [#84277](https://github.com/rust-lang/rust/issues/84277))
The type of the value passed to [`FromResidual::from_residual`](../ops/trait.fromresidual#tymethod.from_residual "associated function std::ops::FromResidual::from_residual") as part of `?` when short-circuiting. [Read more](../ops/trait.try#associatedtype.Residual)

[source](https://doc.rust-lang.org/src/core/option.rs.html#2417)
```
fn from_output(output: <Option<T> as Try>::Output) -> Option<T>
```

🔬This is a nightly-only experimental API. (`try_trait_v2` [#84277](https://github.com/rust-lang/rust/issues/84277))
Constructs the type from its `Output` type. [Read more](../ops/trait.try#tymethod.from_output)

[source](https://doc.rust-lang.org/src/core/option.rs.html#2422)
```
fn branch(
    self
) -> ControlFlow<<Option<T> as Try>::Residual, <Option<T> as Try>::Output>
```

🔬This is a nightly-only experimental API. (`try_trait_v2` [#84277](https://github.com/rust-lang/rust/issues/84277))
Used in `?` to decide whether the operator should produce a value (because this returned [`ControlFlow::Continue`](../ops/enum.controlflow#variant.Continue "variant std::ops::ControlFlow::Continue")) or propagate a value back to the caller (because this returned [`ControlFlow::Break`](../ops/enum.controlflow#variant.Break "variant std::ops::ControlFlow::Break")). [Read more](../ops/trait.try#tymethod.branch)


[source](https://doc.rust-lang.org/src/core/option.rs.html#559)
```
impl<T> Copy for Option<T>
where
    T: Copy,
```
[source](https://doc.rust-lang.org/src/core/option.rs.html#559)
```
impl<T> Eq for Option<T>
where
    T: Eq,
```
[source](https://doc.rust-lang.org/src/core/option.rs.html#559)
```
impl<T> StructuralEq for Option<T>
```
[source](https://doc.rust-lang.org/src/core/option.rs.html#2087)
```
impl<T> StructuralPartialEq for Option<T>
```


Auto Trait Implementations
--------------------------




```
impl<T> RefUnwindSafe for Option<T>
where
    T: RefUnwindSafe,
```

```
impl<T> Send for Option<T>
where
    T: Send,
```

```
impl<T> Sync for Option<T>
where
    T: Sync,
```

```
impl<T> Unpin for Option<T>
where
    T: Unpin,
```

```
impl<T> UnwindSafe for Option<T>
where
    T: UnwindSafe,
```


Blanket Implementations
-----------------------



[source](https://doc.rust-lang.org/src/core/any.rs.html#200)
```
impl<T> Any for T
where
    T: 'static + ?Sized,
```

[source](https://doc.rust-lang.org/src/core/any.rs.html#201)
```
fn type_id(&self) -> TypeId
```
Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#208)
```
impl<T> Borrow<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#210)
```
fn borrow(&self) -> &T
```
Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#216)
```
impl<T> BorrowMut<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#217)
```
fn borrow_mut(&mut self) -> &mut T
```
Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#740)
```
impl<T> From<!> for T
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#741)
```
fn from(t: !) -> T
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#723)
```
impl<T> From<T> for T
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#726)
```
fn from(t: T) -> T
```

Returns the argument unchanged.

 

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#707)
```
impl<T, U> Into<U> for T
where
    U: From<T>,
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#716)
```
fn into(self) -> U
```

Calls `U::from(self)`.

 That is, this conversion is whatever the implementation of `[From](../convert/trait.from "trait std::convert::From")<T> for U` chooses to do.

 

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#82)
```
impl<T> ToOwned for T
where
    T: Clone,
```


```
type Owned = T
```
The resulting type after obtaining ownership.
[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#87)
```
fn to_owned(&self) -> T
```
Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned)

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#91)
```
fn clone_into(&self, target: &mut T)
```
Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#763)
```
impl<T, U> TryFrom<U> for T
where
    U: Into<T>,
```


```
type Error = Infallible
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#770)
```
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#748)
```
impl<T, U> TryInto<U> for T
where
    U: TryFrom<T>,
```


```
type Error = <U as TryFrom<T>>::Error
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#755)
```
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
```
Performs the conversion.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/option/enum.Option.html>

Module std::collections
=======================


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`](../vec/struct.vec "struct std::vec::Vec") or [`HashMap`](hash_map/struct.hashmap "struct std::collections::hash_map::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`](../vec/struct.vec "struct std::vec::Vec"), [`VecDeque`](struct.vecdeque "struct std::collections::VecDeque"), [`LinkedList`](struct.linkedlist "struct std::collections::LinkedList")
* Maps: [`HashMap`](hash_map/struct.hashmap "struct std::collections::hash_map::HashMap"), [`BTreeMap`](struct.btreemap "struct std::collections::BTreeMap")
* Sets: [`HashSet`](hash_set/struct.hashset "struct std::collections::hash_set::HashSet"), [`BTreeSet`](struct.btreeset "struct std::collections::BTreeSet")
* Misc: [`BinaryHeap`](struct.binaryheap "struct std::collections::BinaryHeap")

 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.

 #### Use a `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.

 #### Use a `VecDeque` when:

 * You want a [`Vec`](../vec/struct.vec "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).

 #### Use a `LinkedList` when:

 * You want a [`Vec`](../vec/struct.vec "struct std::vec::Vec") or [`VecDeque`](struct.vecdeque "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.

 #### Use a `HashMap` when:

 * You want to associate arbitrary keys with an arbitrary value.
* You want a cache.
* You want a map, with no extra functionality.

 #### Use a `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.

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

 #### Use a `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.

 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 follow a few conventions. For all operations, the collection’s size is denoted by n. If another collection is involved in the operation, it contains m elements. Operations which have an *amortized* cost are suffixed with a `*`. Operations with an *expected* cost are suffixed with a `~`.

 All amortized costs are for the potential need to resize when capacity is exhausted. If a resize occurs it will take *O*(*n*) time. Our collections never automatically shrink, so removal operations aren’t amortized. Over a sufficiently large series of operations, the average cost per operation will deterministically equal the given cost.

 Only [`HashMap`](hash_map/struct.hashmap "struct std::collections::hash_map::HashMap") has expected costs, due to the probabilistic nature of hashing. It is theoretically possible, though very unlikely, for [`HashMap`](hash_map/struct.hashmap "struct std::collections::hash_map::HashMap") to experience worse performance.

 ### Sequences





|  | get(i) | insert(i) | remove(i) | append | split\_off(i) |
| --- | --- | --- | --- | --- | --- |
| [`Vec`](../vec/struct.vec "struct std::vec::Vec") | *O*(1) | *O*(*n*-*i*)\* | *O*(*n*-*i*) | *O*(*m*)\* | *O*(*n*-*i*) |
| [`VecDeque`](struct.vecdeque "struct std::collections::VecDeque") | *O*(1) | *O*(min(*i*, *n*-*i*))\* | *O*(min(*i*, *n*-*i*)) | *O*(*m*)\* | *O*(min(*i*, *n*-*i*)) |
| [`LinkedList`](struct.linkedlist "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*)) |

  Note that where ties occur, [`Vec`](../vec/struct.vec "struct std::vec::Vec") is generally going to be faster than [`VecDeque`](struct.vecdeque "struct std::collections::VecDeque"), and [`VecDeque`](struct.vecdeque "struct std::collections::VecDeque") is generally going to be faster than [`LinkedList`](struct.linkedlist "struct std::collections::LinkedList").

 ### Maps

 For Sets, all operations have the cost of the equivalent Map operation.

 


|  | get | insert | remove | range | append |
| --- | --- | --- | --- | --- | --- |
| [`HashMap`](hash_map/struct.hashmap "struct std::collections::hash_map::HashMap") | *O*(1)~ | *O*(1)~\* | *O*(1)~ | N/A | N/A |
| [`BTreeMap`](struct.btreemap "struct std::collections::BTreeMap") | *O*(log(*n*)) | *O*(log(*n*)) | *O*(log(*n*)) | *O*(log(*n*)) | *O*(*n*+*m*) |

 
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.

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

 ### Iterators

 [Iterators](../iter/index "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`](../vec/struct.vec "struct std::vec::Vec"), this means the items will be yielded in increasing order of index starting at 0. For ordered collections like [`BTreeMap`](struct.btreemap "struct std::collections::BTreeMap"), this means that the items will be yielded in sorted order. For unordered collections like [`HashMap`](hash_map/struct.hashmap "struct std::collections::hash_map::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:?}");
}
```
 `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;
}
```
 `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](../iter/trait.intoiterator "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);
```
 
```
use std::collections::VecDeque;

let vec = [1, 2, 3, 4];
let buf: VecDeque<_> = vec.into_iter().collect();
```
 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:?}");
}
```
 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`](../iter/trait.iterator#method.collect "method std::iter::Iterator::collect") or [`extend`](../iter/trait.extend#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.

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

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

 ##### 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}");
}
```
 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.

 ##### 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;
    }
}
```
 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<H: Hasher>(&self, h: &mut H) { self.a.hash(h); }
}

impl PartialOrd for Foo {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> { 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");
```
 Modules
-------


* [binary\_heap](binary_heap/index "mod std::collections::binary_heap")
A priority queue implemented with a binary heap.
* [btree\_map](btree_map/index "mod std::collections::btree_map")
An ordered map based on a B-Tree.
* [btree\_set](btree_set/index "mod std::collections::btree_set")
An ordered set based on a B-Tree.
* [hash\_map](hash_map/index "mod std::collections::hash_map")
A hash map implemented with quadratic probing and SIMD lookup.
* [hash\_set](hash_set/index "mod std::collections::hash_set")
A hash set implemented as a `HashMap` where the value is `()`.
* [linked\_list](linked_list/index "mod std::collections::linked_list")
A doubly-linked list with owned nodes.
* [vec\_deque](vec_deque/index "mod std::collections::vec_deque")
A double-ended queue (deque) implemented with a growable ring buffer.


Structs
-------


* [BTreeMap](struct.btreemap "struct std::collections::BTreeMap")
An ordered map based on a [B-Tree](https://en.wikipedia.org/wiki/B-tree).
* [BTreeSet](struct.btreeset "struct std::collections::BTreeSet")
An ordered set based on a B-Tree.
* [BinaryHeap](struct.binaryheap "struct std::collections::BinaryHeap")
A priority queue implemented with a binary heap.
* [HashMap](struct.hashmap "struct std::collections::HashMap")
A [hash map](index#use-a-hashmap-when "mod std::collections") implemented with quadratic probing and SIMD lookup.
* [HashSet](struct.hashset "struct std::collections::HashSet")
A [hash set](index#use-the-set-variant-of-any-of-these-maps-when "mod std::collections") implemented as a `HashMap` where the value is `()`.
* [LinkedList](struct.linkedlist "struct std::collections::LinkedList")
A doubly-linked list with owned nodes.
* [TryReserveError](struct.tryreserveerror "struct std::collections::TryReserveError")
The error type for `try_reserve` methods.
* [VecDeque](struct.vecdeque "struct std::collections::VecDeque")
A double-ended queue implemented with a growable ring buffer.


Enums
-----


* [TryReserveErrorKind](enum.tryreserveerrorkind "enum std::collections::TryReserveErrorKind")Experimental

Details of the allocation that caused a `TryReserveError`



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/collections/index.html>

Introduction
============

 This book is the primary reference for the Rust programming language. It provides three kinds of material:

 * Chapters that informally describe each language construct and their use.
* Chapters that informally describe the memory model, concurrency model, runtime services, linkage model, and debugging facilities.
* Appendix chapters providing rationale and references to languages that influenced the design.

  Warning: This book is incomplete. Documenting everything takes a while. See the [GitHub issues](https://github.com/rust-lang/reference/issues) for what is not documented in this book.

  Rust releases
-------------

 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](../std/index), 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/](index). 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/index.html).

 What *The Reference* is not
---------------------------

 This book does not serve as an introduction to the language. Background familiarity with the language is assumed. A separate [book](../index) is available to help acquire such background familiarity.

 This book also does not serve as a reference to the [standard library](../std/index) 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/rustc/index.html). Cargo has a [book](https://doc.rust-lang.org/cargo/index.html) that contains a [reference](https://doc.rust-lang.org/cargo/reference/index.html). There are a few pages such as <linkage> 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/unstable-book/index.html).

 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.

 Finally, this book is not normative. It may include details that are specific to `rustc` itself, and should not be taken as a specification for the Rust language. We intend to produce such a book someday, and until then, the reference is the closest thing we have to one.

 How to use this book
--------------------

 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](expressions#temporaries) is defined in the [expressions chapter](expressions), 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.

 ### Conventions

 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.
* Differences in the language by which edition the crate is compiled under are in a blockquote that start with the words "Edition Differences:" in **bold**.

 
>  **Edition Differences**: In the 2015 edition, this syntax is valid that is disallowed as of the 2018 edition.
> 
>
* Notes that contain useful information about the state of the book or point out useful, but mostly out of scope, information are in blockquotes that start with the word "Note:" in **bold**.

 
>  **Note**: This is an example note.
> 
>
* 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 `<code>` 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 structure is in blockquotes with either "Lexer" or "Syntax" in **bold superscript** as the first line.

 
>  **Syntax**  
>  *ExampleGrammar*:  
>  `~` [*Expression*](expressions)  
>  | `box` [*Expression*](expressions)
> 
>  

 See [Notation](notation) for more detail.

 Contributing
------------

 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. We also want the reference to be as normative as possible, so if you see anything that is wrong or is non-normative but not specifically called out, please also [file an issue](https://github.com/rust-lang/reference/issues).



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/index.html>

Trait std::process::Termination
===============================



```
pub trait Termination {
    // Required method
    fn report(self) -> ExitCode;
}
```

A trait for implementing arbitrary return types in the `main` function.

 The C-main function only supports returning integers. So, every type implementing the `Termination` trait has to be converted to an integer.

 The default implementations are returning `libc::EXIT_SUCCESS` to indicate a successful execution. In case of a failure, `libc::EXIT_FAILURE` is returned.

 Because different runtimes have different specifications on the return value of the `main` function, this trait is likely to be available only on standard library’s runtime for convenience. Other runtimes are not required to provide similar functionality.

 Required Methods
----------------



[source](https://doc.rust-lang.org/src/std/process.rs.html#2238)
```
fn report(self) -> ExitCode
```

Is called to get the representation of the value as status code. This status code is returned to the operating system.

 

Implementors
------------



[source](https://doc.rust-lang.org/src/std/process.rs.html#2257-2261)
```
impl Termination for Infallible
```
[source](https://doc.rust-lang.org/src/std/process.rs.html#2250-2254)
```
impl Termination for !
```
[source](https://doc.rust-lang.org/src/std/process.rs.html#2242-2247)
```
impl Termination for ()
```
[source](https://doc.rust-lang.org/src/std/process.rs.html#2264-2269)
```
impl Termination for ExitCode
```
[source](https://doc.rust-lang.org/src/std/process.rs.html#2272-2282)
```
impl<T: Termination, E: Debug> Termination for Result<T, E>
```



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/process/trait.Termination.html>

Primitive Type str
==================


String slices.

 *[See also the `std::str` module](str/index "mod std::str").*

 The `str` type, also called a ‘string slice’, is the most primitive string type. It is usually seen in its borrowed form, `&str`. It is also the type of string literals, `&'static str`.

 String slices are always valid UTF-8.

 Basic Usage
-----------

 String literals are string slices:

 
```
let hello_world = "Hello, World!";
```
 Here we have declared a string slice initialized with a string literal. String literals have a static lifetime, which means the string `hello_world` is guaranteed to be valid for the duration of the entire program. We can explicitly specify `hello_world`’s lifetime as well:

 
```
let hello_world: &'static str = "Hello, world!";
```
 Representation
--------------

 A `&str` is made up of two components: a pointer to some bytes, and a length. You can look at these with the [`as_ptr`](primitive.str#method.as_ptr "method str::as_ptr") and [`len`](primitive.str#method.len "method str::len") methods:

 
```
use std::slice;
use std::str;

let story = "Once upon a time...";

let ptr = story.as_ptr();
let len = story.len();

// story has nineteen bytes
assert_eq!(19, len);

// We can re-build a str out of ptr and len. This is all unsafe because
// we are responsible for making sure the two components are valid:
let s = unsafe {
    // First, we build a &[u8]...
    let slice = slice::from_raw_parts(ptr, len);

    // ... and then convert that slice into a string slice
    str::from_utf8(slice)
};

assert_eq!(s, Ok(story));
```
 Note: This example shows the internals of `&str`. `unsafe` should not be used to get a string slice under normal circumstances. Use `as_str` instead.

 Implementations
---------------



[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#137)
```
impl str
```

[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#160)const: 1.39.0
```
pub const fn len(&self) -> usize
```

Returns the length of `self`.

 This length is in bytes, not [`char`](primitive.char "primitive char")s or graphemes. In other words, it might not be what a human considers the length of the string.

 ##### Examples

 Basic usage:

 
```
let len = "foo".len();
assert_eq!(3, len);

assert_eq!("ƒoo".len(), 4); // fancy f!
assert_eq!("ƒoo".chars().count(), 3);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#181)const: 1.39.0
```
pub const fn is_empty(&self) -> bool
```

Returns `true` if `self` has a length of zero bytes.

 ##### Examples

 Basic usage:

 
```
let s = "";
assert!(s.is_empty());

let s = "not empty";
assert!(!s.is_empty());
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#211)1.9.0
```
pub fn is_char_boundary(&self, index: usize) -> bool
```

Checks that `index`-th byte is the first byte in a UTF-8 code point sequence or the end of the string.

 The start and end of the string (when `index == self.len()`) are considered to be boundaries.

 Returns `false` if `index` is greater than `self.len()`.

 ##### Examples

 
```
let s = "Löwe 老虎 Léopard";
assert!(s.is_char_boundary(0));
// start of `老`
assert!(s.is_char_boundary(6));
assert!(s.is_char_boundary(s.len()));

// second byte of `ö`
assert!(!s.is_char_boundary(2));

// third byte of `老`
assert!(!s.is_char_boundary(8));
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#258)
```
pub fn floor_char_boundary(&self, index: usize) -> usize
```

🔬This is a nightly-only experimental API. (`round_char_boundary` [#93743](https://github.com/rust-lang/rust/issues/93743))

Finds the closest `x` not exceeding `index` where `is_char_boundary(x)` is `true`.

 This method can help you truncate a string so that it’s still valid UTF-8, but doesn’t exceed a given number of bytes. Note that this is done purely at the character level and can still visually split graphemes, even though the underlying characters aren’t split. For example, the emoji 🧑‍🔬 (scientist) could be split so that the string only includes 🧑 (person) instead.

 ##### Examples

 
```
#![feature(round_char_boundary)]
let s = "❤️🧡💛💚💙💜";
assert_eq!(s.len(), 26);
assert!(!s.is_char_boundary(13));

let closest = s.floor_char_boundary(13);
assert_eq!(closest, 10);
assert_eq!(&s[..closest], "❤️🧡");
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#297)
```
pub fn ceil_char_boundary(&self, index: usize) -> usize
```

🔬This is a nightly-only experimental API. (`round_char_boundary` [#93743](https://github.com/rust-lang/rust/issues/93743))

Finds the closest `x` not below `index` where `is_char_boundary(x)` is `true`.

 This method is the natural complement to [`floor_char_boundary`](primitive.str#method.floor_char_boundary "method str::floor_char_boundary"). See that method for more details.

 ##### Panics

 Panics if `index > self.len()`.

 ##### Examples

 
```
#![feature(round_char_boundary)]
let s = "❤️🧡💛💚💙💜";
assert_eq!(s.len(), 26);
assert!(!s.is_char_boundary(13));

let closest = s.ceil_char_boundary(13);
assert_eq!(closest, 14);
assert_eq!(&s[..closest], "❤️🧡💛");
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#325)const: 1.39.0
```
pub const fn as_bytes(&self) -> &[u8] ⓘ
```

Converts a string slice to a byte slice. To convert the byte slice back into a string slice, use the [`from_utf8`](str/fn.from_utf8 "fn std::str::from_utf8") function.

 ##### Examples

 Basic usage:

 
```
let bytes = "bors".as_bytes();
assert_eq!(b"bors", bytes);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#369)1.20.0
```
pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] ⓘ
```

Converts a mutable string slice to a mutable byte slice.

 ##### Safety

 The caller must ensure that the content of the slice is valid UTF-8 before the borrow ends and the underlying `str` is used.

 Use of a `str` whose contents are not valid UTF-8 is undefined behavior.

 ##### Examples

 Basic usage:

 
```
let mut s = String::from("Hello");
let bytes = unsafe { s.as_bytes_mut() };

assert_eq!(b"Hello", bytes);
```
 Mutability:

 
```
let mut s = String::from("🗻∈🌏");

unsafe {
    let bytes = s.as_bytes_mut();

    bytes[0] = 0xF0;
    bytes[1] = 0x9F;
    bytes[2] = 0x8D;
    bytes[3] = 0x94;
}

assert_eq!("🍔∈🌏", s);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#400)const: 1.32.0
```
pub const fn as_ptr(&self) -> *const u8
```

Converts a string slice to a raw pointer.

 As string slices are a slice of bytes, the raw pointer points to a [`u8`](primitive.u8 "primitive u8"). This pointer will be pointing to the first byte of the string slice.

 The caller must ensure that the returned pointer is never written to. If you need to mutate the contents of the string slice, use [`as_mut_ptr`](primitive.str#method.as_mut_ptr "method str::as_mut_ptr").

 ##### Examples

 Basic usage:

 
```
let s = "Hello";
let ptr = s.as_ptr();
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#415)1.36.0
```
pub fn as_mut_ptr(&mut self) -> *mut u8
```

Converts a mutable string slice to a raw pointer.

 As string slices are a slice of bytes, the raw pointer points to a [`u8`](primitive.u8 "primitive u8"). This pointer will be pointing to the first byte of the string slice.

 It is your responsibility to make sure that the string slice only gets modified in a way that it remains valid UTF-8.

 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#440)1.20.0
```
pub fn get<I>(&self, i: I) -> Option<&<I as SliceIndex<str>>::Output>
where
    I: SliceIndex<str>,
```

Returns a subslice of `str`.

 This is the non-panicking alternative to indexing the `str`. Returns [`None`](option/enum.option#variant.None "variant std::option::Option::None") whenever equivalent indexing operation would panic.

 ##### Examples

 
```
let v = String::from("🗻∈🌏");

assert_eq!(Some("🗻"), v.get(0..4));

// indices not on UTF-8 sequence boundaries
assert!(v.get(1..).is_none());
assert!(v.get(..8).is_none());

// out of bounds
assert!(v.get(..42).is_none());
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#472)1.20.0
```
pub fn get_mut<I>(
    &mut self,
    i: I
) -> Option<&mut <I as SliceIndex<str>>::Output>
where
    I: SliceIndex<str>,
```

Returns a mutable subslice of `str`.

 This is the non-panicking alternative to indexing the `str`. Returns [`None`](option/enum.option#variant.None "variant std::option::Option::None") whenever equivalent indexing operation would panic.

 ##### Examples

 
```
let mut v = String::from("hello");
// correct length
assert!(v.get_mut(0..5).is_some());
// out of bounds
assert!(v.get_mut(..42).is_none());
assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));

assert_eq!("hello", v);
{
    let s = v.get_mut(0..2);
    let s = s.map(|s| {
        s.make_ascii_uppercase();
        &*s
    });
    assert_eq!(Some("HE"), s);
}
assert_eq!("HEllo", v);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#504)1.20.0
```
pub unsafe fn get_unchecked<I>(&self, i: I) -> &<I as SliceIndex<str>>::Output
where
    I: SliceIndex<str>,
```

Returns an unchecked subslice of `str`.

 This is the unchecked alternative to indexing the `str`.

 ##### Safety

 Callers of this function are responsible that these preconditions are satisfied:

 * The starting index must not exceed the ending index;
* Indexes must be within bounds of the original slice;
* Indexes must lie on UTF-8 sequence boundaries.

 Failing that, the returned string slice may reference invalid memory or violate the invariants communicated by the `str` type.

 ##### Examples

 
```
let v = "🗻∈🌏";
unsafe {
    assert_eq!("🗻", v.get_unchecked(0..4));
    assert_eq!("∈", v.get_unchecked(4..7));
    assert_eq!("🌏", v.get_unchecked(7..11));
}
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#539)1.20.0
```
pub unsafe fn get_unchecked_mut<I>(
    &mut self,
    i: I
) -> &mut <I as SliceIndex<str>>::Output
where
    I: SliceIndex<str>,
```

Returns a mutable, unchecked subslice of `str`.

 This is the unchecked alternative to indexing the `str`.

 ##### Safety

 Callers of this function are responsible that these preconditions are satisfied:

 * The starting index must not exceed the ending index;
* Indexes must be within bounds of the original slice;
* Indexes must lie on UTF-8 sequence boundaries.

 Failing that, the returned string slice may reference invalid memory or violate the invariants communicated by the `str` type.

 ##### Examples

 
```
let mut v = String::from("🗻∈🌏");
unsafe {
    assert_eq!("🗻", v.get_unchecked_mut(0..4));
    assert_eq!("∈", v.get_unchecked_mut(4..7));
    assert_eq!("🌏", v.get_unchecked_mut(7..11));
}
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#592)
```
pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str
```

👎Deprecated since 1.29.0: use `get_unchecked(begin..end)` instead

Creates a string slice from another string slice, bypassing safety checks.

 This is generally not recommended, use with caution! For a safe alternative see [`str`](primitive.str "primitive str") and [`Index`](ops/trait.index "trait std::ops::Index").

 This new slice goes from `begin` to `end`, including `begin` but excluding `end`.

 To get a mutable string slice instead, see the [`slice_mut_unchecked`](primitive.str#method.slice_mut_unchecked "method str::slice_mut_unchecked") method.

 ##### Safety

 Callers of this function are responsible that three preconditions are satisfied:

 * `begin` must not exceed `end`.
* `begin` and `end` must be byte positions within the string slice.
* `begin` and `end` must lie on UTF-8 sequence boundaries.

 ##### Examples

 Basic usage:

 
```
let s = "Löwe 老虎 Léopard";

unsafe {
    assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
}

let s = "Hello, world!";

unsafe {
    assert_eq!("world", s.slice_unchecked(7, 12));
}
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#625)1.5.0
```
pub unsafe fn slice_mut_unchecked(
    &mut self,
    begin: usize,
    end: usize
) -> &mut str
```

👎Deprecated since 1.29.0: use `get_unchecked_mut(begin..end)` instead

Creates a string slice from another string slice, bypassing safety checks. This is generally not recommended, use with caution! For a safe alternative see [`str`](primitive.str "primitive str") and [`IndexMut`](ops/trait.indexmut "trait std::ops::IndexMut").

 This new slice goes from `begin` to `end`, including `begin` but excluding `end`.

 To get an immutable string slice instead, see the [`slice_unchecked`](primitive.str#method.slice_unchecked "method str::slice_unchecked") method.

 ##### Safety

 Callers of this function are responsible that three preconditions are satisfied:

 * `begin` must not exceed `end`.
* `begin` and `end` must be byte positions within the string slice.
* `begin` and `end` must lie on UTF-8 sequence boundaries.

 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#665)1.4.0
```
pub fn split_at(&self, mid: usize) -> (&str, &str)
```

Divide one string slice into two at an index.

 The argument, `mid`, should be a byte offset from the start of the string. It must also be on the boundary of a UTF-8 code point.

 The two slices returned go from the start of the string slice to `mid`, and from `mid` to the end of the string slice.

 To get mutable string slices instead, see the [`split_at_mut`](primitive.str#method.split_at_mut "method str::split_at_mut") method.

 ##### Panics

 Panics if `mid` is not on a UTF-8 code point boundary, or if it is past the end of the last code point of the string slice.

 ##### Examples

 Basic usage:

 
```
let s = "Per Martin-Löf";

let (first, last) = s.split_at(3);

assert_eq!("Per", first);
assert_eq!(" Martin-Löf", last);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#709)1.4.0
```
pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str)
```

Divide one mutable string slice into two at an index.

 The argument, `mid`, should be a byte offset from the start of the string. It must also be on the boundary of a UTF-8 code point.

 The two slices returned go from the start of the string slice to `mid`, and from `mid` to the end of the string slice.

 To get immutable string slices instead, see the [`split_at`](primitive.str#method.split_at "method str::split_at") method.

 ##### Panics

 Panics if `mid` is not on a UTF-8 code point boundary, or if it is past the end of the last code point of the string slice.

 ##### Examples

 Basic usage:

 
```
let mut s = "Per Martin-Löf".to_string();
{
    let (first, last) = s.split_at_mut(3);
    first.make_ascii_uppercase();
    assert_eq!("PER", first);
    assert_eq!(" Martin-Löf", last);
}
assert_eq!("PER Martin-Löf", s);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#775)
```
pub fn chars(&self) -> Chars<'_> ⓘ
```

Returns an iterator over the [`char`](primitive.char "primitive char")s of a string slice.

 As a string slice consists of valid UTF-8, we can iterate through a string slice by [`char`](primitive.char "primitive char"). This method returns such an iterator.

 It’s important to remember that [`char`](primitive.char "primitive char") represents a Unicode Scalar Value, and might not match your idea of what a ‘character’ is. Iteration over grapheme clusters may be what you actually want. This functionality is not provided by Rust’s standard library, check crates.io instead.

 ##### Examples

 Basic usage:

 
```
let word = "goodbye";

let count = word.chars().count();
assert_eq!(7, count);

let mut chars = word.chars();

assert_eq!(Some('g'), chars.next());
assert_eq!(Some('o'), chars.next());
assert_eq!(Some('o'), chars.next());
assert_eq!(Some('d'), chars.next());
assert_eq!(Some('b'), chars.next());
assert_eq!(Some('y'), chars.next());
assert_eq!(Some('e'), chars.next());

assert_eq!(None, chars.next());
```
 Remember, [`char`](primitive.char "primitive char")s might not match your intuition about characters:

 
```
let y = "y̆";

let mut chars = y.chars();

assert_eq!(Some('y'), chars.next()); // not 'y̆'
assert_eq!(Some('\u{0306}'), chars.next());

assert_eq!(None, chars.next());
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#832)
```
pub fn char_indices(&self) -> CharIndices<'_> ⓘ
```

Returns an iterator over the [`char`](primitive.char "primitive char")s of a string slice, and their positions.

 As a string slice consists of valid UTF-8, we can iterate through a string slice by [`char`](primitive.char "primitive char"). This method returns an iterator of both these [`char`](primitive.char "primitive char")s, as well as their byte positions.

 The iterator yields tuples. The position is first, the [`char`](primitive.char "primitive char") is second.

 ##### Examples

 Basic usage:

 
```
let word = "goodbye";

let count = word.char_indices().count();
assert_eq!(7, count);

let mut char_indices = word.char_indices();

assert_eq!(Some((0, 'g')), char_indices.next());
assert_eq!(Some((1, 'o')), char_indices.next());
assert_eq!(Some((2, 'o')), char_indices.next());
assert_eq!(Some((3, 'd')), char_indices.next());
assert_eq!(Some((4, 'b')), char_indices.next());
assert_eq!(Some((5, 'y')), char_indices.next());
assert_eq!(Some((6, 'e')), char_indices.next());

assert_eq!(None, char_indices.next());
```
 Remember, [`char`](primitive.char "primitive char")s might not match your intuition about characters:

 
```
let yes = "y̆es";

let mut char_indices = yes.char_indices();

assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
assert_eq!(Some((1, '\u{0306}')), char_indices.next());

// note the 3 here - the last character took up two bytes
assert_eq!(Some((3, 'e')), char_indices.next());
assert_eq!(Some((4, 's')), char_indices.next());

assert_eq!(None, char_indices.next());
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#857)
```
pub fn bytes(&self) -> Bytes<'_> ⓘ
```

An iterator over the bytes of a string slice.

 As a string slice consists of a sequence of bytes, we can iterate through a string slice by byte. This method returns such an iterator.

 ##### Examples

 Basic usage:

 
```
let mut bytes = "bors".bytes();

assert_eq!(Some(b'b'), bytes.next());
assert_eq!(Some(b'o'), bytes.next());
assert_eq!(Some(b'r'), bytes.next());
assert_eq!(Some(b's'), bytes.next());

assert_eq!(None, bytes.next());
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#909)1.1.0
```
pub fn split_whitespace(&self) -> SplitWhitespace<'_> ⓘ
```

Splits a string slice by whitespace.

 The iterator returned will return string slices that are sub-slices of the original string slice, separated by any amount of whitespace.

 ‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property `White_Space`. If you only want to split on ASCII whitespace instead, use [`split_ascii_whitespace`](primitive.str#method.split_ascii_whitespace "method str::split_ascii_whitespace").

 ##### Examples

 Basic usage:

 
```
let mut iter = "A few words".split_whitespace();

assert_eq!(Some("A"), iter.next());
assert_eq!(Some("few"), iter.next());
assert_eq!(Some("words"), iter.next());

assert_eq!(None, iter.next());
```
 All kinds of whitespace are considered:

 
```
let mut iter = " Mary   had\ta\u{2009}little  \n\t lamb".split_whitespace();
assert_eq!(Some("Mary"), iter.next());
assert_eq!(Some("had"), iter.next());
assert_eq!(Some("a"), iter.next());
assert_eq!(Some("little"), iter.next());
assert_eq!(Some("lamb"), iter.next());

assert_eq!(None, iter.next());
```
 If the string is empty or all whitespace, the iterator yields no string slices:

 
```
assert_eq!("".split_whitespace().next(), None);
assert_eq!("   ".split_whitespace().next(), None);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#958)1.34.0
```
pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_> ⓘ
```

Splits a string slice by ASCII whitespace.

 The iterator returned will return string slices that are sub-slices of the original string slice, separated by any amount of ASCII whitespace.

 To split by Unicode `Whitespace` instead, use [`split_whitespace`](primitive.str#method.split_whitespace "method str::split_whitespace").

 ##### Examples

 Basic usage:

 
```
let mut iter = "A few words".split_ascii_whitespace();

assert_eq!(Some("A"), iter.next());
assert_eq!(Some("few"), iter.next());
assert_eq!(Some("words"), iter.next());

assert_eq!(None, iter.next());
```
 All kinds of ASCII whitespace are considered:

 
```
let mut iter = " Mary   had\ta little  \n\t lamb".split_ascii_whitespace();
assert_eq!(Some("Mary"), iter.next());
assert_eq!(Some("had"), iter.next());
assert_eq!(Some("a"), iter.next());
assert_eq!(Some("little"), iter.next());
assert_eq!(Some("lamb"), iter.next());

assert_eq!(None, iter.next());
```
 If the string is empty or all ASCII whitespace, the iterator yields no string slices:

 
```
assert_eq!("".split_ascii_whitespace().next(), None);
assert_eq!("   ".split_ascii_whitespace().next(), None);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1006)
```
pub fn lines(&self) -> Lines<'_> ⓘ
```

An iterator over the lines of a string, as string slices.

 Lines are split at line endings that are either newlines (`\n`) or sequences of a carriage return followed by a line feed (`\r\n`).

 Line terminators are not included in the lines returned by the iterator.

 The final line ending is optional. A string that ends with a final line ending will return the same lines as an otherwise identical string without a final line ending.

 ##### Examples

 Basic usage:

 
```
let text = "foo\r\nbar\n\nbaz\n";
let mut lines = text.lines();

assert_eq!(Some("foo"), lines.next());
assert_eq!(Some("bar"), lines.next());
assert_eq!(Some(""), lines.next());
assert_eq!(Some("baz"), lines.next());

assert_eq!(None, lines.next());
```
 The final line ending isn’t required:

 
```
let text = "foo\nbar\n\r\nbaz";
let mut lines = text.lines();

assert_eq!(Some("foo"), lines.next());
assert_eq!(Some("bar"), lines.next());
assert_eq!(Some(""), lines.next());
assert_eq!(Some("baz"), lines.next());

assert_eq!(None, lines.next());
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1015)
```
pub fn lines_any(&self) -> LinesAny<'_> ⓘ
```

👎Deprecated since 1.4.0: use lines() instead now

An iterator over the lines of a string.

 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1036)1.8.0
```
pub fn encode_utf16(&self) -> EncodeUtf16<'_> ⓘ
```

Returns an iterator of `u16` over the string encoded as UTF-16.

 ##### Examples

 Basic usage:

 
```
let text = "Zażółć gęślą jaźń";

let utf8_len = text.len();
let utf16_len = text.encode_utf16().count();

assert!(utf16_len <= utf8_len);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1063)
```
pub fn contains<'a, P>(&'a self, pat: P) -> bool
where
    P: Pattern<'a>,
```

Returns `true` if the given pattern matches a sub-slice of this string slice.

 Returns `false` if it does not.

 The [pattern](str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](primitive.char "primitive char"), a slice of [`char`](primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Examples

 Basic usage:

 
```
let bananas = "bananas";

assert!(bananas.contains("nana"));
assert!(!bananas.contains("apples"));
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1089)
```
pub fn starts_with<'a, P>(&'a self, pat: P) -> bool
where
    P: Pattern<'a>,
```

Returns `true` if the given pattern matches a prefix of this string slice.

 Returns `false` if it does not.

 The [pattern](str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](primitive.char "primitive char"), a slice of [`char`](primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Examples

 Basic usage:

 
```
let bananas = "bananas";

assert!(bananas.starts_with("bana"));
assert!(!bananas.starts_with("nana"));
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1115-1117)
```
pub fn ends_with<'a, P>(&'a self, pat: P) -> bool
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
```

Returns `true` if the given pattern matches a suffix of this string slice.

 Returns `false` if it does not.

 The [pattern](str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](primitive.char "primitive char"), a slice of [`char`](primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Examples

 Basic usage:

 
```
let bananas = "bananas";

assert!(bananas.ends_with("anas"));
assert!(!bananas.ends_with("nana"));
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1166)
```
pub fn find<'a, P>(&'a self, pat: P) -> Option<usize>
where
    P: Pattern<'a>,
```

Returns the byte index of the first character of this string slice that matches the pattern.

 Returns [`None`](option/enum.option#variant.None "variant std::option::Option::None") if the pattern doesn’t match.

 The [pattern](str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](primitive.char "primitive char"), a slice of [`char`](primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Examples

 Simple patterns:

 
```
let s = "Löwe 老虎 Léopard Gepardi";

assert_eq!(s.find('L'), Some(0));
assert_eq!(s.find('é'), Some(14));
assert_eq!(s.find("pard"), Some(17));
```
 More complex patterns using point-free style and closures:

 
```
let s = "Löwe 老虎 Léopard";

assert_eq!(s.find(char::is_whitespace), Some(5));
assert_eq!(s.find(char::is_lowercase), Some(1));
assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
```
 Not finding the pattern:

 
```
let s = "Löwe 老虎 Léopard";
let x: &[_] = &['1', '2'];

assert_eq!(s.find(x), None);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1212-1214)
```
pub fn rfind<'a, P>(&'a self, pat: P) -> Option<usize>
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
```

Returns the byte index for the first character of the last match of the pattern in this string slice.

 Returns [`None`](option/enum.option#variant.None "variant std::option::Option::None") if the pattern doesn’t match.

 The [pattern](str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](primitive.char "primitive char"), a slice of [`char`](primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Examples

 Simple patterns:

 
```
let s = "Löwe 老虎 Léopard Gepardi";

assert_eq!(s.rfind('L'), Some(13));
assert_eq!(s.rfind('é'), Some(14));
assert_eq!(s.rfind("pard"), Some(24));
```
 More complex patterns with closures:

 
```
let s = "Löwe 老虎 Léopard";

assert_eq!(s.rfind(char::is_whitespace), Some(12));
assert_eq!(s.rfind(char::is_lowercase), Some(20));
```
 Not finding the pattern:

 
```
let s = "Löwe 老虎 Léopard";
let x: &[_] = &['1', '2'];

assert_eq!(s.rfind(x), None);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1334)
```
pub fn split<'a, P>(&'a self, pat: P) -> Split<'a, P> ⓘ
where
    P: Pattern<'a>,
```

An iterator over substrings of this string slice, separated by characters matched by a pattern.

 The [pattern](str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](primitive.char "primitive char"), a slice of [`char`](primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Iterator behavior

 The returned iterator will be a [`DoubleEndedIterator`](iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator") if the pattern allows a reverse search and forward/reverse search yields the same elements. This is true for, e.g., [`char`](primitive.char "primitive char"), but not for `&str`.

 If the pattern allows a reverse search but its results might differ from a forward search, the [`rsplit`](primitive.str#method.rsplit "method str::rsplit") method can be used.

 ##### Examples

 Simple patterns:

 
```
let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);

let v: Vec<&str> = "".split('X').collect();
assert_eq!(v, [""]);

let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
assert_eq!(v, ["lion", "", "tiger", "leopard"]);

let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
assert_eq!(v, ["lion", "tiger", "leopard"]);

let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
assert_eq!(v, ["abc", "def", "ghi"]);

let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
assert_eq!(v, ["lion", "tiger", "leopard"]);
```
 If the pattern is a slice of chars, split on each occurrence of any of the characters:

 
```
let v: Vec<&str> = "2020-11-03 23:59".split(&['-', ' ', ':', '@'][..]).collect();
assert_eq!(v, ["2020", "11", "03", "23", "59"]);
```
 A more complex pattern, using a closure:

 
```
let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
assert_eq!(v, ["abc", "def", "ghi"]);
```
 If a string contains multiple contiguous separators, you will end up with empty strings in the output:

 
```
let x = "||||a||b|c".to_string();
let d: Vec<_> = x.split('|').collect();

assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
```
 Contiguous separators are separated by the empty string.

 
```
let x = "(///)".to_string();
let d: Vec<_> = x.split('/').collect();

assert_eq!(d, &["(", "", "", ")"]);
```
 Separators at the start or end of a string are neighbored by empty strings.

 
```
let d: Vec<_> = "010".split("0").collect();
assert_eq!(d, &["", "1", ""]);
```
 When the empty string is used as a separator, it separates every character in the string, along with the beginning and end of the string.

 
```
let f: Vec<_> = "rust".split("").collect();
assert_eq!(f, &["", "r", "u", "s", "t", ""]);
```
 Contiguous separators can lead to possibly surprising behavior when whitespace is used as the separator. This code is correct:

 
```
let x = "    a  b c".to_string();
let d: Vec<_> = x.split(' ').collect();

assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
```
 It does *not* give you:

 ⓘ
```
assert_eq!(d, &["a", "b", "c"]);
```

 Use [`split_whitespace`](primitive.str#method.split_whitespace "method str::split_whitespace") for this behavior.

 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1374)1.51.0
```
pub fn split_inclusive<'a, P>(&'a self, pat: P) -> SplitInclusive<'a, P> ⓘ
where
    P: Pattern<'a>,
```

An iterator over substrings of this string slice, separated by characters matched by a pattern. Differs from the iterator produced by `split` in that `split_inclusive` leaves the matched part as the terminator of the substring.

 The [pattern](str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](primitive.char "primitive char"), a slice of [`char`](primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Examples

 
```
let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb."
    .split_inclusive('\n').collect();
assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb."]);
```
 If the last element of the string is matched, that element will be considered the terminator of the preceding substring. That substring will be the last item returned by the iterator.

 
```
let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb.\n"
    .split_inclusive('\n').collect();
assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb.\n"]);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1429-1431)
```
pub fn rsplit<'a, P>(&'a self, pat: P) -> RSplit<'a, P> ⓘ
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
```

An iterator over substrings of the given string slice, separated by characters matched by a pattern and yielded in reverse order.

 The [pattern](str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](primitive.char "primitive char"), a slice of [`char`](primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Iterator behavior

 The returned iterator requires that the pattern supports a reverse search, and it will be a [`DoubleEndedIterator`](iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator") if a forward/reverse search yields the same elements.

 For iterating from the front, the [`split`](primitive.str#method.split "method str::split") method can be used.

 ##### Examples

 Simple patterns:

 
```
let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);

let v: Vec<&str> = "".rsplit('X').collect();
assert_eq!(v, [""]);

let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
assert_eq!(v, ["leopard", "tiger", "", "lion"]);

let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
assert_eq!(v, ["leopard", "tiger", "lion"]);
```
 A more complex pattern, using a closure:

 
```
let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
assert_eq!(v, ["ghi", "def", "abc"]);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1480)
```
pub fn split_terminator<'a, P>(&'a self, pat: P) -> SplitTerminator<'a, P> ⓘ
where
    P: Pattern<'a>,
```

An iterator over substrings of the given string slice, separated by characters matched by a pattern.

 The [pattern](str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](primitive.char "primitive char"), a slice of [`char`](primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 Equivalent to [`split`](primitive.str#method.split "method str::split"), except that the trailing substring is skipped if empty.

 This method can be used for string data that is *terminated*, rather than *separated* by a pattern.

 ##### Iterator behavior

 The returned iterator will be a [`DoubleEndedIterator`](iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator") if the pattern allows a reverse search and forward/reverse search yields the same elements. This is true for, e.g., [`char`](primitive.char "primitive char"), but not for `&str`.

 If the pattern allows a reverse search but its results might differ from a forward search, the [`rsplit_terminator`](primitive.str#method.rsplit_terminator "method str::rsplit_terminator") method can be used.

 ##### Examples

 Basic usage:

 
```
let v: Vec<&str> = "A.B.".split_terminator('.').collect();
assert_eq!(v, ["A", "B"]);

let v: Vec<&str> = "A..B..".split_terminator(".").collect();
assert_eq!(v, ["A", "", "B", ""]);

let v: Vec<&str> = "A.B:C.D".split_terminator(&['.', ':'][..]).collect();
assert_eq!(v, ["A", "B", "C", "D"]);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1526-1528)
```
pub fn rsplit_terminator<'a, P>(&'a self, pat: P) -> RSplitTerminator<'a, P> ⓘ
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
```

An iterator over substrings of `self`, separated by characters matched by a pattern and yielded in reverse order.

 The [pattern](str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](primitive.char "primitive char"), a slice of [`char`](primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 Equivalent to [`split`](primitive.str#method.split "method str::split"), except that the trailing substring is skipped if empty.

 This method can be used for string data that is *terminated*, rather than *separated* by a pattern.

 ##### Iterator behavior

 The returned iterator requires that the pattern supports a reverse search, and it will be double ended if a forward/reverse search yields the same elements.

 For iterating from the front, the [`split_terminator`](primitive.str#method.split_terminator "method str::split_terminator") method can be used.

 ##### Examples

 
```
let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
assert_eq!(v, ["B", "A"]);

let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
assert_eq!(v, ["", "B", "", "A"]);

let v: Vec<&str> = "A.B:C.D".rsplit_terminator(&['.', ':'][..]).collect();
assert_eq!(v, ["D", "C", "B", "A"]);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1581)
```
pub fn splitn<'a, P>(&'a self, n: usize, pat: P) -> SplitN<'a, P> ⓘ
where
    P: Pattern<'a>,
```

An iterator over substrings of the given string slice, separated by a pattern, restricted to returning at most `n` items.

 If `n` substrings are returned, the last substring (the `n`th substring) will contain the remainder of the string.

 The [pattern](str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](primitive.char "primitive char"), a slice of [`char`](primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Iterator behavior

 The returned iterator will not be double ended, because it is not efficient to support.

 If the pattern allows a reverse search, the [`rsplitn`](primitive.str#method.rsplitn "method str::rsplitn") method can be used.

 ##### Examples

 Simple patterns:

 
```
let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
assert_eq!(v, ["Mary", "had", "a little lambda"]);

let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
assert_eq!(v, ["lion", "", "tigerXleopard"]);

let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
assert_eq!(v, ["abcXdef"]);

let v: Vec<&str> = "".splitn(1, 'X').collect();
assert_eq!(v, [""]);
```
 A more complex pattern, using a closure:

 
```
let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
assert_eq!(v, ["abc", "defXghi"]);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1630-1632)
```
pub fn rsplitn<'a, P>(&'a self, n: usize, pat: P) -> RSplitN<'a, P> ⓘ
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
```

An iterator over substrings of this string slice, separated by a pattern, starting from the end of the string, restricted to returning at most `n` items.

 If `n` substrings are returned, the last substring (the `n`th substring) will contain the remainder of the string.

 The [pattern](str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](primitive.char "primitive char"), a slice of [`char`](primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Iterator behavior

 The returned iterator will not be double ended, because it is not efficient to support.

 For splitting from the front, the [`splitn`](primitive.str#method.splitn "method str::splitn") method can be used.

 ##### Examples

 Simple patterns:

 
```
let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
assert_eq!(v, ["lamb", "little", "Mary had a"]);

let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
assert_eq!(v, ["leopard", "tiger", "lionX"]);

let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
assert_eq!(v, ["leopard", "lion::tiger"]);
```
 A more complex pattern, using a closure:

 
```
let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
assert_eq!(v, ["ghi", "abc1def"]);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1650)1.52.0
```
pub fn split_once<'a, P>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)>
where
    P: Pattern<'a>,
```

Splits the string on the first occurrence of the specified delimiter and returns prefix before delimiter and suffix after delimiter.

 ##### Examples

 
```
assert_eq!("cfg".split_once('='), None);
assert_eq!("cfg=".split_once('='), Some(("cfg", "")));
assert_eq!("cfg=foo".split_once('='), Some(("cfg", "foo")));
assert_eq!("cfg=foo=bar".split_once('='), Some(("cfg", "foo=bar")));
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1668-1670)1.52.0
```
pub fn rsplit_once<'a, P>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)>
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
```

Splits the string on the last occurrence of the specified delimiter and returns prefix before delimiter and suffix after delimiter.

 ##### Examples

 
```
assert_eq!("cfg".rsplit_once('='), None);
assert_eq!("cfg=foo".rsplit_once('='), Some(("cfg", "foo")));
assert_eq!("cfg=foo=bar".rsplit_once('='), Some(("cfg=foo", "bar")));
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1710)1.2.0
```
pub fn matches<'a, P>(&'a self, pat: P) -> Matches<'a, P> ⓘ
where
    P: Pattern<'a>,
```

An iterator over the disjoint matches of a pattern within the given string slice.

 The [pattern](str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](primitive.char "primitive char"), a slice of [`char`](primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Iterator behavior

 The returned iterator will be a [`DoubleEndedIterator`](iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator") if the pattern allows a reverse search and forward/reverse search yields the same elements. This is true for, e.g., [`char`](primitive.char "primitive char"), but not for `&str`.

 If the pattern allows a reverse search but its results might differ from a forward search, the [`rmatches`](primitive.str#method.matches "method str::matches") method can be used.

 ##### Examples

 Basic usage:

 
```
let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
assert_eq!(v, ["abc", "abc", "abc"]);

let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
assert_eq!(v, ["1", "2", "3"]);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1746-1748)1.2.0
```
pub fn rmatches<'a, P>(&'a self, pat: P) -> RMatches<'a, P> ⓘ
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
```

An iterator over the disjoint matches of a pattern within this string slice, yielded in reverse order.

 The [pattern](str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](primitive.char "primitive char"), a slice of [`char`](primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Iterator behavior

 The returned iterator requires that the pattern supports a reverse search, and it will be a [`DoubleEndedIterator`](iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator") if a forward/reverse search yields the same elements.

 For iterating from the front, the [`matches`](primitive.str#method.matches "method str::matches") method can be used.

 ##### Examples

 Basic usage:

 
```
let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
assert_eq!(v, ["abc", "abc", "abc"]);

let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
assert_eq!(v, ["3", "2", "1"]);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1792)1.5.0
```
pub fn match_indices<'a, P>(&'a self, pat: P) -> MatchIndices<'a, P> ⓘ
where
    P: Pattern<'a>,
```

An iterator over the disjoint matches of a pattern within this string slice as well as the index that the match starts at.

 For matches of `pat` within `self` that overlap, only the indices corresponding to the first match are returned.

 The [pattern](str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](primitive.char "primitive char"), a slice of [`char`](primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Iterator behavior

 The returned iterator will be a [`DoubleEndedIterator`](iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator") if the pattern allows a reverse search and forward/reverse search yields the same elements. This is true for, e.g., [`char`](primitive.char "primitive char"), but not for `&str`.

 If the pattern allows a reverse search but its results might differ from a forward search, the [`rmatch_indices`](primitive.str#method.rmatch_indices "method str::rmatch_indices") method can be used.

 ##### Examples

 Basic usage:

 
```
let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);

let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
assert_eq!(v, [(1, "abc"), (4, "abc")]);

let v: Vec<_> = "ababa".match_indices("aba").collect();
assert_eq!(v, [(0, "aba")]); // only the first `aba`
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1834-1836)1.5.0
```
pub fn rmatch_indices<'a, P>(&'a self, pat: P) -> RMatchIndices<'a, P> ⓘ
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
```

An iterator over the disjoint matches of a pattern within `self`, yielded in reverse order along with the index of the match.

 For matches of `pat` within `self` that overlap, only the indices corresponding to the last match are returned.

 The [pattern](str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](primitive.char "primitive char"), a slice of [`char`](primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Iterator behavior

 The returned iterator requires that the pattern supports a reverse search, and it will be a [`DoubleEndedIterator`](iter/trait.doubleendediterator "trait std::iter::DoubleEndedIterator") if a forward/reverse search yields the same elements.

 For iterating from the front, the [`match_indices`](primitive.str#method.match_indices "method str::match_indices") method can be used.

 ##### Examples

 Basic usage:

 
```
let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);

let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
assert_eq!(v, [(4, "abc"), (1, "abc")]);

let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
assert_eq!(v, [(2, "aba")]); // only the last `aba`
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1860)
```
pub fn trim(&self) -> &str
```

Returns a string slice with leading and trailing whitespace removed.

 ‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property `White_Space`, which includes newlines.

 ##### Examples

 Basic usage:

 
```
let s = "\n Hello\tworld\t\n";

assert_eq!("Hello\tworld", s.trim());
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1899)1.30.0
```
pub fn trim_start(&self) -> &str
```

Returns a string slice with leading whitespace removed.

 ‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property `White_Space`, which includes newlines.

 ##### Text directionality

 A string is a sequence of bytes. `start` in this context means the first position of that byte string; for a left-to-right language like English or Russian, this will be left side, and for right-to-left languages like Arabic or Hebrew, this will be the right side.

 ##### Examples

 Basic usage:

 
```
let s = "\n Hello\tworld\t\n";
assert_eq!("Hello\tworld\t\n", s.trim_start());
```
 Directionality:

 
```
let s = "  English  ";
assert!(Some('E') == s.trim_start().chars().next());

let s = "  עברית  ";
assert!(Some('ע') == s.trim_start().chars().next());
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1938)1.30.0
```
pub fn trim_end(&self) -> &str
```

Returns a string slice with trailing whitespace removed.

 ‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property `White_Space`, which includes newlines.

 ##### Text directionality

 A string is a sequence of bytes. `end` in this context means the last position of that byte string; for a left-to-right language like English or Russian, this will be right side, and for right-to-left languages like Arabic or Hebrew, this will be the left side.

 ##### Examples

 Basic usage:

 
```
let s = "\n Hello\tworld\t\n";
assert_eq!("\n Hello\tworld", s.trim_end());
```
 Directionality:

 
```
let s = "  English  ";
assert!(Some('h') == s.trim_end().chars().rev().next());

let s = "  עברית  ";
assert!(Some('ת') == s.trim_end().chars().rev().next());
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#1978)
```
pub fn trim_left(&self) -> &str
```

👎Deprecated since 1.33.0: superseded by `trim_start`

Returns a string slice with leading whitespace removed.

 ‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property `White_Space`.

 ##### Text directionality

 A string is a sequence of bytes. ‘Left’ in this context means the first position of that byte string; for a language like Arabic or Hebrew which are ‘right to left’ rather than ‘left to right’, this will be the *right* side, not the left.

 ##### Examples

 Basic usage:

 
```
let s = " Hello\tworld\t";

assert_eq!("Hello\tworld\t", s.trim_left());
```
 Directionality:

 
```
let s = "  English";
assert!(Some('E') == s.trim_left().chars().next());

let s = "  עברית";
assert!(Some('ע') == s.trim_left().chars().next());
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2018)
```
pub fn trim_right(&self) -> &str
```

👎Deprecated since 1.33.0: superseded by `trim_end`

Returns a string slice with trailing whitespace removed.

 ‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property `White_Space`.

 ##### Text directionality

 A string is a sequence of bytes. ‘Right’ in this context means the last position of that byte string; for a language like Arabic or Hebrew which are ‘right to left’ rather than ‘left to right’, this will be the *left* side, not the right.

 ##### Examples

 Basic usage:

 
```
let s = " Hello\tworld\t";

assert_eq!(" Hello\tworld", s.trim_right());
```
 Directionality:

 
```
let s = "English  ";
assert!(Some('h') == s.trim_right().chars().rev().next());

let s = "עברית  ";
assert!(Some('ת') == s.trim_right().chars().rev().next());
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2051-2053)
```
pub fn trim_matches<'a, P>(&'a self, pat: P) -> &'a str
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: DoubleEndedSearcher<'a>,
```

Returns a string slice with all prefixes and suffixes that match a pattern repeatedly removed.

 The [pattern](str/pattern/index "mod std::str::pattern") can be a [`char`](primitive.char "primitive char"), a slice of [`char`](primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Examples

 Simple patterns:

 
```
assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");

let x: &[_] = &['1', '2'];
assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
```
 A more complex pattern, using a closure:

 
```
assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2100)1.30.0
```
pub fn trim_start_matches<'a, P>(&'a self, pat: P) -> &'a str
where
    P: Pattern<'a>,
```

Returns a string slice with all prefixes that match a pattern repeatedly removed.

 The [pattern](str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](primitive.char "primitive char"), a slice of [`char`](primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Text directionality

 A string is a sequence of bytes. `start` in this context means the first position of that byte string; for a left-to-right language like English or Russian, this will be left side, and for right-to-left languages like Arabic or Hebrew, this will be the right side.

 ##### Examples

 Basic usage:

 
```
assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11");
assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123");

let x: &[_] = &['1', '2'];
assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12");
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2133)1.45.0
```
pub fn strip_prefix<'a, P>(&'a self, prefix: P) -> Option<&'a str>
where
    P: Pattern<'a>,
```

Returns a string slice with the prefix removed.

 If the string starts with the pattern `prefix`, returns substring after the prefix, wrapped in `Some`. Unlike `trim_start_matches`, this method removes the prefix exactly once.

 If the string does not start with `prefix`, returns `None`.

 The [pattern](str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](primitive.char "primitive char"), a slice of [`char`](primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Examples

 
```
assert_eq!("foo:bar".strip_prefix("foo:"), Some("bar"));
assert_eq!("foo:bar".strip_prefix("bar"), None);
assert_eq!("foofoo".strip_prefix("foo"), Some("foo"));
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2160-2163)1.45.0
```
pub fn strip_suffix<'a, P>(&'a self, suffix: P) -> Option<&'a str>
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
```

Returns a string slice with the suffix removed.

 If the string ends with the pattern `suffix`, returns the substring before the suffix, wrapped in `Some`. Unlike `trim_end_matches`, this method removes the suffix exactly once.

 If the string does not end with `suffix`, returns `None`.

 The [pattern](str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](primitive.char "primitive char"), a slice of [`char`](primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Examples

 
```
assert_eq!("bar:foo".strip_suffix(":foo"), Some("bar"));
assert_eq!("bar:foo".strip_suffix("bar"), None);
assert_eq!("foofoo".strip_suffix("foo"), Some("foo"));
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2204-2206)1.30.0
```
pub fn trim_end_matches<'a, P>(&'a self, pat: P) -> &'a str
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
```

Returns a string slice with all suffixes that match a pattern repeatedly removed.

 The [pattern](str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](primitive.char "primitive char"), a slice of [`char`](primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Text directionality

 A string is a sequence of bytes. `end` in this context means the last position of that byte string; for a left-to-right language like English or Russian, this will be right side, and for right-to-left languages like Arabic or Hebrew, this will be the left side.

 ##### Examples

 Simple patterns:

 
```
assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar");
assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");

let x: &[_] = &['1', '2'];
assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar");
```
 A more complex pattern, using a closure:

 
```
assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo");
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2250)
```
pub fn trim_left_matches<'a, P>(&'a self, pat: P) -> &'a str
where
    P: Pattern<'a>,
```

👎Deprecated since 1.33.0: superseded by `trim_start_matches`

Returns a string slice with all prefixes that match a pattern repeatedly removed.

 The [pattern](str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](primitive.char "primitive char"), a slice of [`char`](primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Text directionality

 A string is a sequence of bytes. ‘Left’ in this context means the first position of that byte string; for a language like Arabic or Hebrew which are ‘right to left’ rather than ‘left to right’, this will be the *right* side, not the left.

 ##### Examples

 Basic usage:

 
```
assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");

let x: &[_] = &['1', '2'];
assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2293-2295)
```
pub fn trim_right_matches<'a, P>(&'a self, pat: P) -> &'a str
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
```

👎Deprecated since 1.33.0: superseded by `trim_end_matches`

Returns a string slice with all suffixes that match a pattern repeatedly removed.

 The [pattern](str/pattern/index "mod std::str::pattern") can be a `&str`, [`char`](primitive.char "primitive char"), a slice of [`char`](primitive.char "primitive char")s, or a function or closure that determines if a character matches.

 ##### Text directionality

 A string is a sequence of bytes. ‘Right’ in this context means the last position of that byte string; for a language like Arabic or Hebrew which are ‘right to left’ rather than ‘left to right’, this will be the *left* side, not the right.

 ##### Examples

 Simple patterns:

 
```
assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");

let x: &[_] = &['1', '2'];
assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
```
 A more complex pattern, using a closure:

 
```
assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2345)
```
pub fn parse<F>(&self) -> Result<F, <F as FromStr>::Err>
where
    F: FromStr,
```

Parses this string slice into another type.

 Because `parse` is so general, it can cause problems with type inference. As such, `parse` is one of the few times you’ll see the syntax affectionately known as the ‘turbofish’: `::<>`. This helps the inference algorithm understand specifically which type you’re trying to parse into.

 `parse` can parse into any type that implements the [`FromStr`](str/trait.fromstr "trait std::str::FromStr") trait.

 ##### Errors

 Will return [`Err`](str/trait.fromstr#associatedtype.Err "associated type std::str::FromStr::Err") if it’s not possible to parse this string slice into the desired type.

 ##### Examples

 Basic usage

 
```
let four: u32 = "4".parse().unwrap();

assert_eq!(4, four);
```
 Using the ‘turbofish’ instead of annotating `four`:

 
```
let four = "4".parse::<u32>();

assert_eq!(Ok(4), four);
```
 Failing to parse:

 
```
let nope = "j".parse::<u32>();

assert!(nope.is_err());
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2364)1.23.0 (const: [unstable](https://github.com/rust-lang/rust/issues/111090 "Tracking issue for const_slice_is_ascii"))
```
pub fn is_ascii(&self) -> bool
```

Checks if all characters in this string are within the ASCII range.

 ##### Examples

 
```
let ascii = "hello!\n";
let non_ascii = "Grüße, Jürgen ❤";

assert!(ascii.is_ascii());
assert!(!non_ascii.is_ascii());
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2376)
```
pub const fn as_ascii(&self) -> Option<&[AsciiChar]>
```

🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998))

If this string slice [`is_ascii`](primitive.str#method.is_ascii "method str::is_ascii"), returns it as a slice of [ASCII characters](ascii/enum.char "enum std::ascii::Char"), otherwise returns `None`.

 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2396)1.23.0
```
pub fn eq_ignore_ascii_case(&self, other: &str) -> bool
```

Checks that two strings are an ASCII case-insensitive match.

 Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`, but without allocating and copying temporaries.

 ##### Examples

 
```
assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2421)1.23.0
```
pub fn make_ascii_uppercase(&mut self)
```

Converts this string to its ASCII upper case equivalent in-place.

 ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, but non-ASCII letters are unchanged.

 To return a new uppercased value without modifying the existing one, use [`to_ascii_uppercase()`](#method.to_ascii_uppercase).

 ##### Examples

 
```
let mut s = String::from("Grüße, Jürgen ❤");

s.make_ascii_uppercase();

assert_eq!("GRüßE, JüRGEN ❤", s);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2448)1.23.0
```
pub fn make_ascii_lowercase(&mut self)
```

Converts this string to its ASCII lower case equivalent in-place.

 ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’, but non-ASCII letters are unchanged.

 To return a new lowercased value without modifying the existing one, use [`to_ascii_lowercase()`](#method.to_ascii_lowercase).

 ##### Examples

 
```
let mut s = String::from("GRÜßE, JÜRGEN ❤");

s.make_ascii_lowercase();

assert_eq!("grÜße, jÜrgen ❤", s);
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2491)1.34.0
```
pub fn escape_debug(&self) -> EscapeDebug<'_> ⓘ
```

Return an iterator that escapes each char in `self` with [`char::escape_debug`](primitive.char#method.escape_debug "method char::escape_debug").

 Note: only extended grapheme codepoints that begin the string will be escaped.

 ##### Examples

 As an iterator:

 
```
for c in "❤\n!".escape_debug() {
    print!("{c}");
}
println!();
```
 Using `println!` directly:

 
```
println!("{}", "❤\n!".escape_debug());
```
 Both are equivalent to:

 
```
println!("❤\\n!");
```
 Using `to_string`:

 
```
assert_eq!("❤\n!".escape_debug().to_string(), "❤\\n!");
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2537)1.34.0
```
pub fn escape_default(&self) -> EscapeDefault<'_> ⓘ
```

Return an iterator that escapes each char in `self` with [`char::escape_default`](primitive.char#method.escape_default "method char::escape_default").

 ##### Examples

 As an iterator:

 
```
for c in "❤\n!".escape_default() {
    print!("{c}");
}
println!();
```
 Using `println!` directly:

 
```
println!("{}", "❤\n!".escape_default());
```
 Both are equivalent to:

 
```
println!("\\u{{2764}}\\n!");
```
 Using `to_string`:

 
```
assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!");
```
 
[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2575)1.34.0
```
pub fn escape_unicode(&self) -> EscapeUnicode<'_> ⓘ
```

Return an iterator that escapes each char in `self` with [`char::escape_unicode`](primitive.char#method.escape_unicode "method char::escape_unicode").

 ##### Examples

 As an iterator:

 
```
for c in "❤\n!".escape_unicode() {
    print!("{c}");
}
println!();
```
 Using `println!` directly:

 
```
println!("{}", "❤\n!".escape_unicode());
```
 Both are equivalent to:

 
```
println!("\\u{{2764}}\\u{{a}}\\u{{21}}");
```
 Using `to_string`:

 
```
assert_eq!("❤\n!".escape_unicode().to_string(), "\\u{2764}\\u{a}\\u{21}");
```
 

[source](https://doc.rust-lang.org/src/alloc/str.rs.html#221)
```
impl str
```

Methods for string slices.

 

[source](https://doc.rust-lang.org/src/alloc/str.rs.html#238)1.20.0
```
pub fn into_boxed_bytes(self: Box<str, Global>) -> Box<[u8], Global>
```

Converts a `Box<str>` into a `Box<[u8]>` without copying or allocating.

 ##### Examples

 Basic usage:

 
```
let s = "this is a string";
let boxed_str = s.to_owned().into_boxed_str();
let boxed_bytes = boxed_str.into_boxed_bytes();
assert_eq!(*boxed_bytes, *s.as_bytes());
```
 
[source](https://doc.rust-lang.org/src/alloc/str.rs.html#271)
```
pub fn replace<'a, P>(&'a self, from: P, to: &str) -> String
where
    P: Pattern<'a>,
```

Replaces all matches of a pattern with another string.

 `replace` creates a new [`String`](string/struct.string "struct std::string::String"), and copies the data from this string slice into it. While doing so, it attempts to find matches of a pattern. If it finds any, it replaces them with the replacement string slice.

 ##### Examples

 Basic usage:

 
```
let s = "this is old";

assert_eq!("this is new", s.replace("old", "new"));
assert_eq!("than an old", s.replace("is", "an"));
```
 When the pattern doesn’t match, it returns this string slice as [`String`](string/struct.string "struct std::string::String"):

 
```
let s = "this is old";
assert_eq!(s, s.replace("cookie monster", "little lamb"));
```
 
[source](https://doc.rust-lang.org/src/alloc/str.rs.html#311)1.16.0
```
pub fn replacen<'a, P>(&'a self, pat: P, to: &str, count: usize) -> String
where
    P: Pattern<'a>,
```

Replaces first N matches of a pattern with another string.

 `replacen` creates a new [`String`](string/struct.string "struct std::string::String"), and copies the data from this string slice into it. While doing so, it attempts to find matches of a pattern. If it finds any, it replaces them with the replacement string slice at most `count` times.

 ##### Examples

 Basic usage:

 
```
let s = "foo foo 123 foo";
assert_eq!("new new 123 foo", s.replacen("foo", "new", 2));
assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3));
assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric, "new", 1));
```
 When the pattern doesn’t match, it returns this string slice as [`String`](string/struct.string "struct std::string::String"):

 
```
let s = "this is old";
assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));
```
 
[source](https://doc.rust-lang.org/src/alloc/str.rs.html#368)1.2.0
```
pub fn to_lowercase(&self) -> String
```

Returns the lowercase equivalent of this string slice, as a new [`String`](string/struct.string "struct std::string::String").

 ‘Lowercase’ is defined according to the terms of the Unicode Derived Core Property `Lowercase`.

 Since some characters can expand into multiple characters when changing the case, this function returns a [`String`](string/struct.string "struct std::string::String") instead of modifying the parameter in-place.

 ##### Examples

 Basic usage:

 
```
let s = "HELLO";

assert_eq!("hello", s.to_lowercase());
```
 A tricky example, with sigma:

 
```
let sigma = "Σ";

assert_eq!("σ", sigma.to_lowercase());

// but at the end of a word, it's ς, not σ:
let odysseus = "ὈΔΥΣΣΕΎΣ";

assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());
```
 Languages without case are not changed:

 
```
let new_year = "农历新年";

assert_eq!(new_year, new_year.to_lowercase());
```
 
[source](https://doc.rust-lang.org/src/alloc/str.rs.html#459)1.2.0
```
pub fn to_uppercase(&self) -> String
```

Returns the uppercase equivalent of this string slice, as a new [`String`](string/struct.string "struct std::string::String").

 ‘Uppercase’ is defined according to the terms of the Unicode Derived Core Property `Uppercase`.

 Since some characters can expand into multiple characters when changing the case, this function returns a [`String`](string/struct.string "struct std::string::String") instead of modifying the parameter in-place.

 ##### Examples

 Basic usage:

 
```
let s = "hello";

assert_eq!("HELLO", s.to_uppercase());
```
 Scripts without case are not changed:

 
```
let new_year = "农历新年";

assert_eq!(new_year, new_year.to_uppercase());
```
 One character can become multiple:

 
```
let s = "tschüß";

assert_eq!("TSCHÜSS", s.to_uppercase());
```
 
[source](https://doc.rust-lang.org/src/alloc/str.rs.html#502)1.4.0
```
pub fn into_string(self: Box<str, Global>) -> String
```

Converts a [`Box<str>`](boxed/struct.box "struct std::boxed::Box") into a [`String`](string/struct.string "struct std::string::String") without copying or allocating.

 ##### Examples

 Basic usage:

 
```
let string = String::from("birthday gift");
let boxed_str = string.clone().into_boxed_str();

assert_eq!(boxed_str.into_string(), string);
```
 
[source](https://doc.rust-lang.org/src/alloc/str.rs.html#531)1.16.0
```
pub fn repeat(&self, n: usize) -> String
```

Creates a new [`String`](string/struct.string "struct std::string::String") by repeating a string `n` times.

 ##### Panics

 This function will panic if the capacity would overflow.

 ##### Examples

 Basic usage:

 
```
assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
```
 A panic upon overflow:

 ⓘ
```
// this will panic at runtime
let huge = "0123456789abcdef".repeat(usize::MAX);
```

 
[source](https://doc.rust-lang.org/src/alloc/str.rs.html#561)1.23.0
```
pub fn to_ascii_uppercase(&self) -> String
```

Returns a copy of this string where each character is mapped to its ASCII upper case equivalent.

 ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, but non-ASCII letters are unchanged.

 To uppercase the value in-place, use [`make_ascii_uppercase`](primitive.str#method.make_ascii_uppercase "method str::make_ascii_uppercase").

 To uppercase ASCII characters in addition to non-ASCII characters, use [`to_uppercase`](#method.to_uppercase).

 ##### Examples

 
```
let s = "Grüße, Jürgen ❤";

assert_eq!("GRüßE, JüRGEN ❤", s.to_ascii_uppercase());
```
 
[source](https://doc.rust-lang.org/src/alloc/str.rs.html#593)1.23.0
```
pub fn to_ascii_lowercase(&self) -> String
```

Returns a copy of this string where each character is mapped to its ASCII lower case equivalent.

 ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’, but non-ASCII letters are unchanged.

 To lowercase the value in-place, use [`make_ascii_lowercase`](primitive.str#method.make_ascii_lowercase "method str::make_ascii_lowercase").

 To lowercase ASCII characters in addition to non-ASCII characters, use [`to_lowercase`](#method.to_lowercase).

 ##### Examples

 
```
let s = "Grüße, Jürgen ❤";

assert_eq!("grüße, jürgen ❤", s.to_ascii_lowercase());
```
 


Trait Implementations
---------------------



[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#439)1.14.0
```
impl<'a> Add<&'a str> for Cow<'a, str>
```


```
type Output = Cow<'a, str>
```
The resulting type after applying the `+` operator.
[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#443)
```
fn add(self, rhs: &'a str) -> <Cow<'a, str> as Add<&'a str>>::Output
```
Performs the `+` operation. [Read more](ops/trait.add#tymethod.add)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2321)
```
impl Add<&str> for String
```

Implements the `+` operator for concatenating two strings.

 This consumes the `String` on the left-hand side and re-uses its buffer (growing it if necessary). This is done to avoid allocating a new `String` and copying the entire contents on every operation, which would lead to *O*(*n*^2) running time when building an *n*-byte string by repeated concatenation.

 The string on the right-hand side is only borrowed; its contents are copied into the returned `String`.

 #### Examples

 Concatenating two `String`s takes the first by value and borrows the second:

 
```
let a = String::from("hello");
let b = String::from(" world");
let c = a + &b;
// `a` is moved and can no longer be used here.
```
 If you want to keep using the first `String`, you can clone it and append to the clone instead:

 
```
let a = String::from("hello");
let b = String::from(" world");
let c = a.clone() + &b;
// `a` is still valid here.
```
 Concatenating `&str` slices can be done by converting the first to a `String`:

 
```
let a = "hello";
let b = " world";
let c = a.to_string() + b;
```
 


```
type Output = String
```
The resulting type after applying the `+` operator.
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2325)
```
fn add(self, other: &str) -> String
```
Performs the `+` operation. [Read more](ops/trait.add#tymethod.add)


[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#463)1.14.0
```
impl<'a> AddAssign<&'a str> for Cow<'a, str>
```

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#464)
```
fn add_assign(&mut self, rhs: &'a str)
```
Performs the `+=` operation. [Read more](ops/trait.addassign#tymethod.add_assign)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2336)1.12.0
```
impl AddAssign<&str> for String
```

Implements the `+=` operator for appending to a `String`.

 This has the same behavior as the [`push_str`](string/struct.string#method.push_str "method std::string::String::push_str") method.

 

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2338)
```
fn add_assign(&mut self, other: &str)
```
Performs the `+=` operation. [Read more](ops/trait.addassign#tymethod.add_assign)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2644)1.43.0
```
impl AsMut<str> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2646)
```
fn as_mut(&mut self) -> &mut str
```
Converts this type into a mutable reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#804)1.51.0
```
impl AsMut<str> for str
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#806)
```
fn as_mut(&mut self) -> &mut str
```
Converts this type into a mutable reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2581)
```
impl AsRef<[u8]> for str
```

[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2583)
```
fn as_ref(&self) -> &[u8] ⓘ
```
Converts this type into a shared reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1318-1323)
```
impl AsRef<OsStr> for str
```

[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1320-1322)
```
fn as_ref(&self) -> &OsStr
```
Converts this type into a shared reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/std/path.rs.html#3149-3154)
```
impl AsRef<Path> for str
```

[source](https://doc.rust-lang.org/src/std/path.rs.html#3151-3153)
```
fn as_ref(&self) -> &Path
```
Converts this type into a shared reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2954)1.55.0
```
impl<'a> AsRef<str> for Drain<'a>
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2955)
```
fn as_ref(&self) -> &str
```
Converts this type into a shared reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2636)
```
impl AsRef<str> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2638)
```
fn as_ref(&self) -> &str
```
Converts this type into a shared reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#796)
```
impl AsRef<str> for str
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#798)
```
fn as_ref(&self) -> &str
```
Converts this type into a shared reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/std/ascii.rs.html#207-211)
```
impl AsciiExt for str
```


```
type Owned = String
```

👎Deprecated since 1.26.0: use inherent methods instead
Container type for copied ASCII characters.
[source](https://doc.rust-lang.org/src/std/ascii.rs.html#210)
```
fn is_ascii(&self) -> bool
```

👎Deprecated since 1.26.0: use inherent methods instead
Checks if the value is within the ASCII range. [Read more](ascii/trait.asciiext#tymethod.is_ascii)

[source](https://doc.rust-lang.org/src/std/ascii.rs.html#210)
```
fn to_ascii_uppercase(&self) -> Self::Owned
```

👎Deprecated since 1.26.0: use inherent methods instead
Makes a copy of the value in its ASCII upper case equivalent. [Read more](ascii/trait.asciiext#tymethod.to_ascii_uppercase)

[source](https://doc.rust-lang.org/src/std/ascii.rs.html#210)
```
fn to_ascii_lowercase(&self) -> Self::Owned
```

👎Deprecated since 1.26.0: use inherent methods instead
Makes a copy of the value in its ASCII lower case equivalent. [Read more](ascii/trait.asciiext#tymethod.to_ascii_lowercase)

[source](https://doc.rust-lang.org/src/std/ascii.rs.html#210)
```
fn eq_ignore_ascii_case(&self, o: &Self) -> bool
```

👎Deprecated since 1.26.0: use inherent methods instead
Checks that two values are an ASCII case-insensitive match. [Read more](ascii/trait.asciiext#tymethod.eq_ignore_ascii_case)

[source](https://doc.rust-lang.org/src/std/ascii.rs.html#210)
```
fn make_ascii_uppercase(&mut self)
```

👎Deprecated since 1.26.0: use inherent methods instead
Converts this type to its ASCII upper case equivalent in-place. [Read more](ascii/trait.asciiext#tymethod.make_ascii_uppercase)

[source](https://doc.rust-lang.org/src/std/ascii.rs.html#210)
```
fn make_ascii_lowercase(&mut self)
```

👎Deprecated since 1.26.0: use inherent methods instead
Converts this type to its ASCII lower case equivalent in-place. [Read more](ascii/trait.asciiext#tymethod.make_ascii_lowercase)


[source](https://doc.rust-lang.org/src/alloc/str.rs.html#188)
```
impl Borrow<str> for String
```

[source](https://doc.rust-lang.org/src/alloc/str.rs.html#190)
```
fn borrow(&self) -> &str
```
Immutably borrows from an owned value. [Read more](borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/alloc/str.rs.html#196)1.36.0
```
impl BorrowMut<str> for String
```

[source](https://doc.rust-lang.org/src/alloc/str.rs.html#198)
```
fn borrow_mut(&mut self) -> &mut str
```
Mutably borrows from an owned value. [Read more](borrow/trait.borrowmut#tymethod.borrow_mut)


[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1305)1.3.0
```
impl Clone for Box<str, Global>
```

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1306)
```
fn clone(&self) -> Box<str, Global>
```
Returns a copy of the value. [Read more](clone/trait.clone#tymethod.clone)

[source](https://doc.rust-lang.org/src/core/clone.rs.html#129)
```
fn clone_from(&mut self, source: &Self)
```
Performs copy-assignment from `source`. [Read more](clone/trait.clone#method.clone_from)


[source](https://doc.rust-lang.org/src/alloc/str.rs.html#61)
```
impl<S> Concat<str> for [S]
where
    S: Borrow<str>,
```

Note: `str` in `Concat<str>` is not meaningful here. This type parameter of the trait only exists to enable another impl.

 


```
type Output = String
```

🔬This is a nightly-only experimental API. (`slice_concat_trait` [#27747](https://github.com/rust-lang/rust/issues/27747))
The resulting type after concatenation
[source](https://doc.rust-lang.org/src/alloc/str.rs.html#64)
```
fn concat(slice: &[S]) -> String
```

🔬This is a nightly-only experimental API. (`slice_concat_trait` [#27747](https://github.com/rust-lang/rust/issues/27747))
Implementation of [`[T]::concat`](primitive.slice#method.concat "method slice::concat")


[source](https://doc.rust-lang.org/src/core/fmt/mod.rs.html#2312)
```
impl Debug for str
```

[source](https://doc.rust-lang.org/src/core/fmt/mod.rs.html#2313)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter. [Read more](fmt/trait.debug#tymethod.fmt)


[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2598)1.28.0
```
impl Default for &mut str
```

[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2601)
```
fn default() -> &mut str
```

Creates an empty mutable str

 

[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2589)
```
impl Default for &str
```

[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2592)
```
fn default() -> &str
```

Creates an empty str

 

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1241)1.17.0
```
impl Default for Box<str, Global>
```

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1243)
```
fn default() -> Box<str, Global>
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/fmt/mod.rs.html#2337)
```
impl Display for str
```

[source](https://doc.rust-lang.org/src/core/fmt/mod.rs.html#2338)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter. [Read more](fmt/trait.display#tymethod.fmt)


[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2663)
```
impl !Error for &str
```

[source](https://doc.rust-lang.org/src/core/error.rs.html#84)1.30.0
```
fn source(&self) -> Option<&(dyn Error + 'static)>
```
The lower-level source of this error, if any. [Read more](error/trait.error#method.source)

[source](https://doc.rust-lang.org/src/core/error.rs.html#110)
```
fn description(&self) -> &str
```

👎Deprecated since 1.42.0: use the Display impl or to\_string()
 [Read more](error/trait.error#method.description)

[source](https://doc.rust-lang.org/src/core/error.rs.html#120)
```
fn cause(&self) -> Option<&dyn Error>
```

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
[source](https://doc.rust-lang.org/src/core/error.rs.html#194)
```
fn provide<'a>(&'a self, demand: &mut Demand<'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](error/trait.error#method.provide)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2120)
```
impl<'a> Extend<&'a str> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2121)
```
fn extend<I>(&mut self, iter: I)
where
    I: IntoIterator<Item = &'a str>,
```
Extends a collection with the contents of an iterator. [Read more](iter/trait.extend#tymethod.extend)

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2126)
```
fn extend_one(&mut self, s: &'a str)
```

🔬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/src/core/iter/traits/collect.rs.html#389)
```
fn extend_reserve(&mut self, additional: usize)
```

🔬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](iter/trait.extend#method.extend_reserve)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2765)
```
impl<'a> From<&'a str> for Cow<'a, str>
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2779)
```
fn from(s: &'a str) -> Cow<'a, str>
```

Converts a string slice into a [`Borrowed`](borrow/enum.cow#variant.Borrowed "borrow::Cow::Borrowed") variant. No heap allocation is performed, and the string is not copied.

 ##### Example

 
```
assert_eq!(Cow::from("eggplant"), Cow::Borrowed("eggplant"));
```
 

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2673)1.44.0
```
impl From<&mut str> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2678)
```
fn from(s: &mut str) -> String
```

Converts a `&mut str` into a [`String`](string/struct.string "struct std::string::String").

 The result is allocated on the heap.

 

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2691)1.21.0
```
impl From<&str> for Arc<str>
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2702)
```
fn from(v: &str) -> Arc<str>
```

Allocate a reference-counted `str` and copy `v` into it.

 ##### Example

 
```
let shared: Arc<str> = Arc::from("eggplant");
assert_eq!("eggplant", &shared[..]);
```
 

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2347)1.6.0
```
impl From<&str> for Box<dyn Error + 'static, Global>
```

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2362)
```
fn from(err: &str) -> Box<dyn Error + 'static, Global>
```

Converts a [`str`](primitive.str "primitive str") into a box of dyn [`Error`](error/trait.error "trait std::error::Error").

 ##### Examples

 
```
use std::error::Error;
use std::mem;

let a_str_error = "a str error";
let a_boxed_error = Box::<dyn Error>::from(a_str_error);
assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
```
 

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2323)
```
impl<'a> From<&str> for Box<dyn Error + Sync + Send + 'a, Global>
```

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2340)
```
fn from(err: &str) -> Box<dyn Error + Sync + Send + 'a, Global>
```

Converts a [`str`](primitive.str "primitive str") into a box of dyn [`Error`](error/trait.error "trait std::error::Error") + [`Send`](marker/trait.send "trait std::marker::Send") + [`Sync`](marker/trait.sync "trait std::marker::Sync").

 ##### Examples

 
```
use std::error::Error;
use std::mem;

let a_str_error = "a str error";
let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
assert!(
    mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
```
 

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1527)1.17.0
```
impl From<&str> for Box<str, Global>
```

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1540)
```
fn from(s: &str) -> Box<str, Global>
```

Converts a `&str` into a `Box<str>`

 This conversion allocates on the heap and performs a copy of `s`.

 ##### Examples

 
```
let boxed: Box<str> = Box::from("hello");
println!("{boxed}");
```
 

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1949)1.21.0
```
impl From<&str> for Rc<str>
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1960)
```
fn from(v: &str) -> Rc<str>
```

Allocate a reference-counted string slice and copy `v` into it.

 ##### Example

 
```
let shared: Rc<str> = Rc::from("statue");
assert_eq!("statue", &shared[..]);
```
 

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2661)
```
impl From<&str> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2666)
```
fn from(s: &str) -> String
```

Converts a `&str` into a [`String`](string/struct.string "struct std::string::String").

 The result is allocated on the heap.

 

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3201)
```
impl From<&str> for Vec<u8, Global>
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3209)
```
fn from(s: &str) -> Vec<u8, Global> ⓘ
```

Allocate a `Vec<u8>` and fill it with a UTF-8 string.

 ##### Examples

 
```
assert_eq!(Vec::from("123"), vec![b'1', b'2', b'3']);
```
 

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1547)1.45.0
```
impl From<Cow<'_, str>> for Box<str, Global>
```

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1572)
```
fn from(cow: Cow<'_, str>) -> Box<str, Global>
```

Converts a `Cow<'_, str>` into a `Box<str>`

 When `cow` is the `Cow::Borrowed` variant, this conversion allocates on the heap and copies the underlying `str`. Otherwise, it will try to reuse the owned `String`’s allocation.

 ##### Examples

 
```
use std::borrow::Cow;

let unboxed = Cow::Borrowed("hello");
let boxed: Box<str> = Box::from(unboxed);
println!("{boxed}");
```
 
```
let unboxed = Cow::Owned("hello".to_string());
let boxed: Box<str> = Box::from(unboxed);
println!("{boxed}");
```
 

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2720)1.20.0
```
impl From<String> for Box<str, Global>
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2734)
```
fn from(s: String) -> Box<str, Global>
```

Converts the given [`String`](string/struct.string "struct std::string::String") to a boxed `str` slice that is owned.

 ##### Examples

 Basic usage:

 
```
let s1: String = String::from("hello world");
let s2: Box<str> = Box::from(s1);
let s3: String = String::from(s2);

assert_eq!("hello world", s3)
```
 

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2022)
```
impl<'a> FromIterator<&'a str> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2023)
```
fn from_iter<I>(iter: I) -> String
where
    I: IntoIterator<Item = &'a str>,
```
Creates a value from an iterator. [Read more](iter/trait.fromiterator#tymethod.from_iter)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2839)1.12.0
```
impl<'a, 'b> FromIterator<&'b str> for Cow<'a, str>
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2840)
```
fn from_iter<I>(it: I) -> Cow<'a, str>
where
    I: IntoIterator<Item = &'b str>,
```
Creates a value from an iterator. [Read more](iter/trait.fromiterator#tymethod.from_iter)


[source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#859)
```
impl Hash for str
```

[source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#861)
```
fn hash<H>(&self, state: &mut H)
where
    H: Hasher,
```
Feeds this value into the given [`Hasher`](hash/trait.hasher "trait std::hash::Hasher"). [Read more](hash/trait.hash#tymethod.hash)


[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#53)
```
impl<I> Index<I> for str
where
    I: SliceIndex<str>,
```


```
type Output = <I as SliceIndex<str>>::Output
```
The returned type after indexing.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#60)
```
fn index(&self, index: I) -> &<I as SliceIndex<str>>::Output
```
Performs the indexing (`container[index]`) operation. [Read more](ops/trait.index#tymethod.index)


[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#66)
```
impl<I> IndexMut<I> for str
where
    I: SliceIndex<str>,
```

[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#71)
```
fn index_mut(&mut self, index: I) -> &mut <I as SliceIndex<str>>::Output
```
Performs the mutable indexing (`container[index]`) operation. [Read more](ops/trait.indexmut#tymethod.index_mut)


[source](https://doc.rust-lang.org/src/alloc/str.rs.html#71)
```
impl<S> Join<&str> for [S]
where
    S: Borrow<str>,
```


```
type Output = String
```

🔬This is a nightly-only experimental API. (`slice_concat_trait` [#27747](https://github.com/rust-lang/rust/issues/27747))
The resulting type after concatenation
[source](https://doc.rust-lang.org/src/alloc/str.rs.html#74)
```
fn join(slice: &[S], sep: &str) -> String
```

🔬This is a nightly-only experimental API. (`slice_concat_trait` [#27747](https://github.com/rust-lang/rust/issues/27747))
Implementation of [`[T]::join`](primitive.slice#method.join "method slice::join")


[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#19)
```
impl Ord for str
```

Implements ordering of strings.

 Strings are ordered [lexicographically](cmp/trait.ord#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.

 

[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#21)
```
fn cmp(&self, other: &str) -> Ordering
```
This method returns an [`Ordering`](cmp/enum.ordering "enum std::cmp::Ordering") between `self` and `other`. [Read more](cmp/trait.ord#tymethod.cmp)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2241)
```
impl<'a, 'b> PartialEq<&'a str> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2241)
```
fn eq(&self, other: &&'a str) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2241)
```
fn ne(&self, other: &&'a str) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2245)
```
impl<'a, 'b> PartialEq<&'b str> for Cow<'a, str>
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2245)
```
fn eq(&self, other: &&'b str) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2245)
```
fn ne(&self, other: &&'b str) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#580-585)1.29.0
```
impl PartialEq<&str> for OsString
```

[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#582-584)
```
fn eq(&self, other: &&str) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#226)
```
fn ne(&self, other: &Rhs) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2245)
```
impl<'a, 'b> PartialEq<Cow<'a, str>> for &'b str
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2245)
```
fn eq(&self, other: &Cow<'a, str>) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2245)
```
fn ne(&self, other: &Cow<'a, str>) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2243)
```
impl<'a, 'b> PartialEq<Cow<'a, str>> for str
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2243)
```
fn eq(&self, other: &Cow<'a, str>) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2243)
```
fn ne(&self, other: &Cow<'a, str>) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1147-1152)
```
impl PartialEq<OsStr> for str
```

[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1149-1151)
```
fn eq(&self, other: &OsStr) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#226)
```
fn ne(&self, other: &Rhs) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#588-593)1.29.0
```
impl<'a> PartialEq<OsString> for &'a str
```

[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#590-592)
```
fn eq(&self, other: &OsString) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#226)
```
fn ne(&self, other: &Rhs) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#572-577)
```
impl PartialEq<OsString> for str
```

[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#574-576)
```
fn eq(&self, other: &OsString) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#226)
```
fn ne(&self, other: &Rhs) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2241)
```
impl<'a, 'b> PartialEq<String> for &'a str
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2241)
```
fn eq(&self, other: &String) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2241)
```
fn ne(&self, other: &String) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2240)
```
impl<'a, 'b> PartialEq<String> for str
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2240)
```
fn eq(&self, other: &String) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2240)
```
fn ne(&self, other: &String) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2243)
```
impl<'a, 'b> PartialEq<str> for Cow<'a, str>
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2243)
```
fn eq(&self, other: &str) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2243)
```
fn ne(&self, other: &str) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1139-1144)
```
impl PartialEq<str> for OsStr
```

[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1141-1143)
```
fn eq(&self, other: &str) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#226)
```
fn ne(&self, other: &Rhs) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#564-569)
```
impl PartialEq<str> for OsString
```

[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#566-568)
```
fn eq(&self, other: &str) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#226)
```
fn ne(&self, other: &Rhs) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2240)
```
impl<'a, 'b> PartialEq<str> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2240)
```
fn eq(&self, other: &str) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2240)
```
fn ne(&self, other: &str) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#27)
```
impl PartialEq<str> for str
```

[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#29)
```
fn eq(&self, other: &str) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#226)
```
fn ne(&self, other: &Rhs) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1182-1187)
```
impl PartialOrd<str> for OsStr
```

[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1184-1186)
```
fn partial_cmp(&self, other: &str) -> Option<Ordering>
```
This method returns an ordering between `self` and `other` values if one exists. [Read more](cmp/trait.partialord#tymethod.partial_cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1067)
```
fn lt(&self, other: &Rhs) -> bool
```
This method tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](cmp/trait.partialord#method.lt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1084)
```
fn le(&self, other: &Rhs) -> bool
```
This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](cmp/trait.partialord#method.le)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1100)
```
fn gt(&self, other: &Rhs) -> bool
```
This method tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](cmp/trait.partialord#method.gt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1117)
```
fn ge(&self, other: &Rhs) -> bool
```
This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](cmp/trait.partialord#method.ge)


[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#623-628)
```
impl PartialOrd<str> for OsString
```

[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#625-627)
```
fn partial_cmp(&self, other: &str) -> Option<Ordering>
```
This method returns an ordering between `self` and `other` values if one exists. [Read more](cmp/trait.partialord#tymethod.partial_cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1067)
```
fn lt(&self, other: &Rhs) -> bool
```
This method tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](cmp/trait.partialord#method.lt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1084)
```
fn le(&self, other: &Rhs) -> bool
```
This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](cmp/trait.partialord#method.le)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1100)
```
fn gt(&self, other: &Rhs) -> bool
```
This method tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](cmp/trait.partialord#method.gt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1117)
```
fn ge(&self, other: &Rhs) -> bool
```
This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](cmp/trait.partialord#method.ge)


[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#45)
```
impl PartialOrd<str> for str
```

Implements comparison operations on strings.

 Strings are compared [lexicographically](cmp/trait.ord#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.

 

[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#47)
```
fn partial_cmp(&self, other: &str) -> Option<Ordering>
```
This method returns an ordering between `self` and `other` values if one exists. [Read more](cmp/trait.partialord#tymethod.partial_cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1067)
```
fn lt(&self, other: &Rhs) -> bool
```
This method tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](cmp/trait.partialord#method.lt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1084)
```
fn le(&self, other: &Rhs) -> bool
```
This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](cmp/trait.partialord#method.le)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1100)
```
fn gt(&self, other: &Rhs) -> bool
```
This method tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](cmp/trait.partialord#method.gt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1117)
```
fn ge(&self, other: &Rhs) -> bool
```
This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](cmp/trait.partialord#method.ge)


[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#936)
```
impl<'a, 'b> Pattern<'a> for &'b str
```

Non-allocating substring search.

 Will handle the pattern `""` as returning empty matches at each character boundary.

 #### Examples

 
```
assert_eq!("Hello world".find("world"), Some(6));
```
 

[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#946)
```
fn is_prefix_of(self, haystack: &'a str) -> bool
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))

Checks whether the pattern matches at the front of the haystack.

 
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#952)
```
fn is_contained_in(self, haystack: &'a str) -> bool
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))

Checks whether the pattern matches anywhere in the haystack

 
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#978)
```
fn strip_prefix_of(self, haystack: &'a str) -> Option<&'a str>
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))

Removes the pattern from the front of haystack, if it matches.

 
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#989)
```
fn is_suffix_of(self, haystack: &'a str) -> bool
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))

Checks whether the pattern matches at the back of the haystack.

 
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#995)
```
fn strip_suffix_of(self, haystack: &'a str) -> Option<&'a str>
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))

Removes the pattern from the back of haystack, if it matches.

 

```
type Searcher = StrSearcher<'a, 'b>
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Associated searcher for this pattern
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#940)
```
fn into_searcher(self, haystack: &'a str) -> StrSearcher<'a, 'b>
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Constructs the associated searcher from `self` and the `haystack` to search in.

[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#162)1.20.0 (const: unstable)
```
impl SliceIndex<str> for Range<usize>
```

Implements substring slicing with syntax `&self[begin .. end]` or `&mut self[begin .. end]`.

 Returns a slice of the given string from the byte range [`begin`, `end`).

 This operation is *O*(1).

 Prior to 1.20.0, these indexing operations were still supported by direct implementation of `Index` and `IndexMut`.

 #### Panics

 Panics if `begin` or `end` does not point to the starting byte offset of a character (as defined by `is_char_boundary`), if `begin > end`, or if `end > len`.

 #### Examples

 
```
let s = "Löwe 老虎 Léopard";
assert_eq!(&s[0 .. 1], "L");

assert_eq!(&s[1 .. 9], "öwe 老");

// these will panic:
// byte 2 lies within `ö`:
// &s[2 ..3];

// byte 8 lies within `老`
// &s[1 .. 8];

// byte 100 is outside the string
// &s[3 .. 100];
```
 


```
type Output = str
```
The output type returned by methods.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#165)const: unstable
```
fn get(self, slice: &str) -> Option<&<Range<usize> as SliceIndex<str>>::Output>
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, if in bounds.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#179)const: unstable
```
fn get_mut(
    self,
    slice: &mut str
) -> Option<&mut <Range<usize> as SliceIndex<str>>::Output>
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, if in bounds.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#192)const: unstable
```
unsafe fn get_unchecked(
    self,
    slice: *const str
) -> *const <Range<usize> as SliceIndex<str>>::Output
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, without performing any bounds checking. Calling this method with an out-of-bounds index or a dangling `slice` pointer is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#215)const: unstable
```
unsafe fn get_unchecked_mut(
    self,
    slice: *mut str
) -> *mut <Range<usize> as SliceIndex<str>>::Output
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, without performing any bounds checking. Calling this method with an out-of-bounds index or a dangling `slice` pointer is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#231)const: unstable
```
fn index(self, slice: &str) -> &<Range<usize> as SliceIndex<str>>::Output ⓘ
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, panicking if out of bounds.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#239)const: unstable
```
fn index_mut(
    self,
    slice: &mut str
) -> &mut <Range<usize> as SliceIndex<str>>::Output ⓘ
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, panicking if out of bounds.

[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#341)1.20.0 (const: unstable)
```
impl SliceIndex<str> for RangeFrom<usize>
```

Implements substring slicing with syntax `&self[begin ..]` or `&mut self[begin ..]`.

 Returns a slice of the given string from the byte range [`begin`, `len`). Equivalent to `&self[begin .. len]` or `&mut self[begin .. len]`.

 This operation is *O*(1).

 Prior to 1.20.0, these indexing operations were still supported by direct implementation of `Index` and `IndexMut`.

 #### Panics

 Panics if `begin` does not point to the starting byte offset of a character (as defined by `is_char_boundary`), or if `begin > len`.

 


```
type Output = str
```
The output type returned by methods.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#344)const: unstable
```
fn get(
    self,
    slice: &str
) -> Option<&<RangeFrom<usize> as SliceIndex<str>>::Output>
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, if in bounds.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#354)const: unstable
```
fn get_mut(
    self,
    slice: &mut str
) -> Option<&mut <RangeFrom<usize> as SliceIndex<str>>::Output>
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, if in bounds.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#364)const: unstable
```
unsafe fn get_unchecked(
    self,
    slice: *const str
) -> *const <RangeFrom<usize> as SliceIndex<str>>::Output
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, without performing any bounds checking. Calling this method with an out-of-bounds index or a dangling `slice` pointer is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#370)const: unstable
```
unsafe fn get_unchecked_mut(
    self,
    slice: *mut str
) -> *mut <RangeFrom<usize> as SliceIndex<str>>::Output
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, without performing any bounds checking. Calling this method with an out-of-bounds index or a dangling `slice` pointer is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#376)const: unstable
```
fn index(self, slice: &str) -> &<RangeFrom<usize> as SliceIndex<str>>::Output ⓘ
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, panicking if out of bounds.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#384)const: unstable
```
fn index_mut(
    self,
    slice: &mut str
) -> &mut <RangeFrom<usize> as SliceIndex<str>>::Output ⓘ
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, panicking if out of bounds.

[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#97)1.20.0 (const: unstable)
```
impl SliceIndex<str> for RangeFull
```

Implements substring slicing with syntax `&self[..]` or `&mut self[..]`.

 Returns a slice of the whole string, i.e., returns `&self` or `&mut self`. Equivalent to `&self[0 .. len]` or `&mut self[0 .. len]`. Unlike other indexing operations, this can never panic.

 This operation is *O*(1).

 Prior to 1.20.0, these indexing operations were still supported by direct implementation of `Index` and `IndexMut`.

 Equivalent to `&self[0 .. len]` or `&mut self[0 .. len]`.

 


```
type Output = str
```
The output type returned by methods.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#100)const: unstable
```
fn get(self, slice: &str) -> Option<&<RangeFull as SliceIndex<str>>::Output>
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, if in bounds.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#104)const: unstable
```
fn get_mut(
    self,
    slice: &mut str
) -> Option<&mut <RangeFull as SliceIndex<str>>::Output>
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, if in bounds.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#108)const: unstable
```
unsafe fn get_unchecked(
    self,
    slice: *const str
) -> *const <RangeFull as SliceIndex<str>>::Output
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, without performing any bounds checking. Calling this method with an out-of-bounds index or a dangling `slice` pointer is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#112)const: unstable
```
unsafe fn get_unchecked_mut(
    self,
    slice: *mut str
) -> *mut <RangeFull as SliceIndex<str>>::Output
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, without performing any bounds checking. Calling this method with an out-of-bounds index or a dangling `slice` pointer is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#116)const: unstable
```
fn index(self, slice: &str) -> &<RangeFull as SliceIndex<str>>::Output
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, panicking if out of bounds.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#120)const: unstable
```
fn index_mut(
    self,
    slice: &mut str
) -> &mut <RangeFull as SliceIndex<str>>::Output
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, panicking if out of bounds.

[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#413)1.26.0 (const: unstable)
```
impl SliceIndex<str> for RangeInclusive<usize>
```

Implements substring slicing with syntax `&self[begin ..= end]` or `&mut self[begin ..= end]`.

 Returns a slice of the given string from the byte range [`begin`, `end`]. Equivalent to `&self [begin .. end + 1]` or `&mut self[begin .. end + 1]`, except if `end` has the maximum value for `usize`.

 This operation is *O*(1).

 #### Panics

 Panics if `begin` does not point to the starting byte offset of a character (as defined by `is_char_boundary`), if `end` does not point to the ending byte offset of a character (`end + 1` is either a starting byte offset or equal to `len`), if `begin > end`, or if `end >= len`.

 


```
type Output = str
```
The output type returned by methods.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#416)const: unstable
```
fn get(
    self,
    slice: &str
) -> Option<&<RangeInclusive<usize> as SliceIndex<str>>::Output>
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, if in bounds.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#420)const: unstable
```
fn get_mut(
    self,
    slice: &mut str
) -> Option<&mut <RangeInclusive<usize> as SliceIndex<str>>::Output>
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, if in bounds.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#424)const: unstable
```
unsafe fn get_unchecked(
    self,
    slice: *const str
) -> *const <RangeInclusive<usize> as SliceIndex<str>>::Output
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, without performing any bounds checking. Calling this method with an out-of-bounds index or a dangling `slice` pointer is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#429)const: unstable
```
unsafe fn get_unchecked_mut(
    self,
    slice: *mut str
) -> *mut <RangeInclusive<usize> as SliceIndex<str>>::Output
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, without performing any bounds checking. Calling this method with an out-of-bounds index or a dangling `slice` pointer is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#434)const: unstable
```
fn index(
    self,
    slice: &str
) -> &<RangeInclusive<usize> as SliceIndex<str>>::Output ⓘ
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, panicking if out of bounds.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#441)const: unstable
```
fn index_mut(
    self,
    slice: &mut str
) -> &mut <RangeInclusive<usize> as SliceIndex<str>>::Output ⓘ
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, panicking if out of bounds.

[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#272)1.20.0 (const: unstable)
```
impl SliceIndex<str> for RangeTo<usize>
```

Implements substring slicing with syntax `&self[.. end]` or `&mut self[.. end]`.

 Returns a slice of the given string from the byte range [0, `end`). Equivalent to `&self[0 .. end]` or `&mut self[0 .. end]`.

 This operation is *O*(1).

 Prior to 1.20.0, these indexing operations were still supported by direct implementation of `Index` and `IndexMut`.

 #### Panics

 Panics if `end` does not point to the starting byte offset of a character (as defined by `is_char_boundary`), or if `end > len`.

 


```
type Output = str
```
The output type returned by methods.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#275)const: unstable
```
fn get(
    self,
    slice: &str
) -> Option<&<RangeTo<usize> as SliceIndex<str>>::Output>
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, if in bounds.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#285)const: unstable
```
fn get_mut(
    self,
    slice: &mut str
) -> Option<&mut <RangeTo<usize> as SliceIndex<str>>::Output>
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, if in bounds.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#295)const: unstable
```
unsafe fn get_unchecked(
    self,
    slice: *const str
) -> *const <RangeTo<usize> as SliceIndex<str>>::Output
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, without performing any bounds checking. Calling this method with an out-of-bounds index or a dangling `slice` pointer is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#300)const: unstable
```
unsafe fn get_unchecked_mut(
    self,
    slice: *mut str
) -> *mut <RangeTo<usize> as SliceIndex<str>>::Output
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, without performing any bounds checking. Calling this method with an out-of-bounds index or a dangling `slice` pointer is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#305)const: unstable
```
fn index(self, slice: &str) -> &<RangeTo<usize> as SliceIndex<str>>::Output
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, panicking if out of bounds.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#313)const: unstable
```
fn index_mut(
    self,
    slice: &mut str
) -> &mut <RangeTo<usize> as SliceIndex<str>>::Output
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, panicking if out of bounds.

[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#465)1.26.0 (const: unstable)
```
impl SliceIndex<str> for RangeToInclusive<usize>
```

Implements substring slicing with syntax `&self[..= end]` or `&mut self[..= end]`.

 Returns a slice of the given string from the byte range [0, `end`]. Equivalent to `&self [0 .. end + 1]`, except if `end` has the maximum value for `usize`.

 This operation is *O*(1).

 #### Panics

 Panics if `end` does not point to the ending byte offset of a character (`end + 1` is either a starting byte offset as defined by `is_char_boundary`, or equal to `len`), or if `end >= len`.

 


```
type Output = str
```
The output type returned by methods.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#468)const: unstable
```
fn get(
    self,
    slice: &str
) -> Option<&<RangeToInclusive<usize> as SliceIndex<str>>::Output>
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, if in bounds.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#472)const: unstable
```
fn get_mut(
    self,
    slice: &mut str
) -> Option<&mut <RangeToInclusive<usize> as SliceIndex<str>>::Output>
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, if in bounds.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#476)const: unstable
```
unsafe fn get_unchecked(
    self,
    slice: *const str
) -> *const <RangeToInclusive<usize> as SliceIndex<str>>::Output
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, without performing any bounds checking. Calling this method with an out-of-bounds index or a dangling `slice` pointer is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#481)const: unstable
```
unsafe fn get_unchecked_mut(
    self,
    slice: *mut str
) -> *mut <RangeToInclusive<usize> as SliceIndex<str>>::Output
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, without performing any bounds checking. Calling this method with an out-of-bounds index or a dangling `slice` pointer is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#486)const: unstable
```
fn index(
    self,
    slice: &str
) -> &<RangeToInclusive<usize> as SliceIndex<str>>::Output
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, panicking if out of bounds.
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#490)const: unstable
```
fn index_mut(
    self,
    slice: &mut str
) -> &mut <RangeToInclusive<usize> as SliceIndex<str>>::Output
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, panicking if out of bounds.

[source](https://doc.rust-lang.org/src/alloc/str.rs.html#205)
```
impl ToOwned for str
```


```
type Owned = String
```
The resulting type after obtaining ownership.
[source](https://doc.rust-lang.org/src/alloc/str.rs.html#208)
```
fn to_owned(&self) -> String
```
Creates owned data from borrowed data, usually by cloning. [Read more](borrow/trait.toowned#tymethod.to_owned)

[source](https://doc.rust-lang.org/src/alloc/str.rs.html#212)
```
fn clone_into(&self, target: &mut String)
```
Uses borrowed data to replace owned data, usually by cloning. [Read more](borrow/trait.toowned#method.clone_into)


[source](https://doc.rust-lang.org/src/std/net/socket_addr.rs.html#280-290)
```
impl ToSocketAddrs for str
```


```
type Iter = IntoIter<SocketAddr, Global>
```
Returned iterator over socket addresses which this type may correspond to.
[source](https://doc.rust-lang.org/src/std/net/socket_addr.rs.html#282-289)
```
fn to_socket_addrs(&self) -> Result<IntoIter<SocketAddr>>
```
Converts this object to an iterator of resolved [`SocketAddr`](net/enum.socketaddr "enum std::net::SocketAddr")s. [Read more](net/trait.tosocketaddrs#tymethod.to_socket_addrs)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2601)1.9.0
```
impl ToString for str
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2603)
```
fn to_string(&self) -> String
```
Converts the given value to a `String`. [Read more](string/trait.tostring#tymethod.to_string)


[source](https://doc.rust-lang.org/src/core/marker.rs.html#989-1000)
```
impl ConstParamTy for str
```
[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#35)
```
impl Eq for str
```
[source](https://doc.rust-lang.org/src/core/marker.rs.html#262-273)
```
impl StructuralEq for str
```


Auto Trait Implementations
--------------------------




```
impl RefUnwindSafe for str
```

```
impl Send for str
```

```
impl !Sized for str
```

```
impl Sync for str
```

```
impl Unpin for str
```

```
impl UnwindSafe for str
```


Blanket Implementations
-----------------------



[source](https://doc.rust-lang.org/src/core/any.rs.html#200)
```
impl<T> Any for T
where
    T: 'static + ?Sized,
```

[source](https://doc.rust-lang.org/src/core/any.rs.html#201)
```
fn type_id(&self) -> TypeId
```
Gets the `TypeId` of `self`. [Read more](any/trait.any#tymethod.type_id)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#208)
```
impl<T> Borrow<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#210)
```
fn borrow(&self) -> &T
```
Immutably borrows from an owned value. [Read more](borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#216)
```
impl<T> BorrowMut<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#217)
```
fn borrow_mut(&mut self) -> &mut T
```
Mutably borrows from an owned value. [Read more](borrow/trait.borrowmut#tymethod.borrow_mut)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2513)
```
impl<T> ToString for T
where
    T: Display + ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2519)
```
default fn to_string(&self) -> String
```
Converts the given value to a `String`. [Read more](string/trait.tostring#tymethod.to_string)




 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/primitive.str.html>

Struct std::vec::Vec
====================



```
pub struct Vec<T, A = Global>
where
    A: Allocator,{ /* private fields */ }
```

A contiguous growable array type, written as `Vec<T>`, short for ‘vector’.

 Examples
--------

 
```
let mut vec = Vec::new();
vec.push(1);
vec.push(2);

assert_eq!(vec.len(), 2);
assert_eq!(vec[0], 1);

assert_eq!(vec.pop(), Some(2));
assert_eq!(vec.len(), 1);

vec[0] = 7;
assert_eq!(vec[0], 7);

vec.extend([1, 2, 3]);

for x in &vec {
    println!("{x}");
}
assert_eq!(vec, [7, 1, 2, 3]);
```
 The [`vec!`](../macro.vec "macro std::vec") macro is provided for convenient initialization:

 
```
let mut vec1 = vec![1, 2, 3];
vec1.push(4);
let vec2 = Vec::from([1, 2, 3, 4]);
assert_eq!(vec1, vec2);
```
 It can also initialize each element of a `Vec<T>` with a given value. This may be more efficient than performing allocation and initialization in separate steps, especially when initializing a vector of zeros:

 
```
let vec = vec![0; 5];
assert_eq!(vec, [0, 0, 0, 0, 0]);

// The following is equivalent, but potentially slower:
let mut vec = Vec::with_capacity(5);
vec.resize(5, 0);
assert_eq!(vec, [0, 0, 0, 0, 0]);
```
 For more information, see [Capacity and Reallocation](#capacity-and-reallocation).

 Use a `Vec<T>` as an efficient stack:

 
```
let mut stack = Vec::new();

stack.push(1);
stack.push(2);
stack.push(3);

while let Some(top) = stack.pop() {
    // Prints 3, 2, 1
    println!("{top}");
}
```
 Indexing
--------

 The `Vec` type allows to access values by index, because it implements the [`Index`](../ops/trait.index "trait std::ops::Index") trait. An example will be more explicit:

 
```
let v = vec![0, 2, 4, 6];
println!("{}", v[1]); // it will display '2'
```
 However be careful: if you try to access an index which isn’t in the `Vec`, your software will panic! You cannot do this:

 ⓘ
```
let v = vec![0, 2, 4, 6];
println!("{}", v[6]); // it will panic!
```

 Use [`get`](../primitive.slice#method.get "method slice::get") and [`get_mut`](../primitive.slice#method.get_mut "method slice::get_mut") if you want to check whether the index is in the `Vec`.

 Slicing
-------

 A `Vec` can be mutable. On the other hand, slices are read-only objects. To get a [slice](../primitive.slice "primitive slice"), use [`&`](../primitive.reference "primitive reference"). Example:

 
```
fn read_slice(slice: &[usize]) {
    // ...
}

let v = vec![0, 1];
read_slice(&v);

// ... and that's all!
// you can also do it like this:
let u: &[usize] = &v;
// or like this:
let u: &[_] = &v;
```
 In Rust, it’s more common to pass slices as arguments rather than vectors when you just want to provide read access. The same goes for [`String`](../string/struct.string "struct std::string::String") and [`&str`](../primitive.str "primitive str").

 Capacity and reallocation
-------------------------

 The capacity of a vector is the amount of space allocated for any future elements that will be added onto the vector. This is not to be confused with the *length* of a vector, which specifies the number of actual elements within the vector. If a vector’s length exceeds its capacity, its capacity will automatically be increased, but its elements will have to be reallocated.

 For example, a vector with capacity 10 and length 0 would be an empty vector with space for 10 more elements. Pushing 10 or fewer elements onto the vector will not change its capacity or cause reallocation to occur. However, if the vector’s length is increased to 11, it will have to reallocate, which can be slow. For this reason, it is recommended to use [`Vec::with_capacity`](struct.vec#method.with_capacity "associated function std::vec::Vec::with_capacity") whenever possible to specify how big the vector is expected to get.

 Guarantees
----------

 Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees about its design. This ensures that it’s as low-overhead as possible in the general case, and can be correctly manipulated in primitive ways by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`. If additional type parameters are added (e.g., to support custom allocators), overriding their defaults may change the behavior.

 Most fundamentally, `Vec` is and always will be a (pointer, capacity, length) triplet. No more, no less. The order of these fields is completely unspecified, and you should use the appropriate methods to modify these. The pointer will never be null, so this type is null-pointer-optimized.

 However, the pointer might not actually point to allocated memory. In particular, if you construct a `Vec` with capacity 0 via [`Vec::new`](struct.vec#method.new "associated function std::vec::Vec::new"), [`vec![]`](../macro.vec "macro std::vec"), [`Vec::with_capacity(0)`](struct.vec#method.with_capacity "associated function std::vec::Vec::with_capacity"), or by calling [`shrink_to_fit`](struct.vec#method.shrink_to_fit "method std::vec::Vec::shrink_to_fit") on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized types inside a `Vec`, it will not allocate space for them. *Note that in this case the `Vec` might not report a [`capacity`](struct.vec#method.capacity "method std::vec::Vec::capacity") of 0*. `Vec` will allocate if and only if `[mem::size\_of::<T>](../mem/fn.size_of "fn std::mem::size_of")() * [capacity](struct.vec#method.capacity "method std::vec::Vec::capacity")() > 0`. In general, `Vec`’s allocation details are very subtle — if you intend to allocate memory using a `Vec` and use it for something else (either to pass to unsafe code, or to build your own memory-backed collection), be sure to deallocate this memory by using `from_raw_parts` to recover the `Vec` and then dropping it.

 If a `Vec` *has* allocated memory, then the memory it points to is on the heap (as defined by the allocator Rust is configured to use by default), and its pointer points to [`len`](struct.vec#method.len "method std::vec::Vec::len") initialized, contiguous elements in order (what you would see if you coerced it to a slice), followed by `[capacity](struct.vec#method.capacity "method std::vec::Vec::capacity") - [len](struct.vec#method.len "method std::vec::Vec::len")` logically uninitialized, contiguous elements.

 A vector containing the elements `'a'` and `'b'` with capacity 4 can be visualized as below. The top part is the `Vec` struct, it contains a pointer to the head of the allocation in the heap, length and capacity. The bottom part is the allocation on the heap, a contiguous memory block.

 
```
            ptr      len  capacity
       +--------+--------+--------+
       | 0x0123 |      2 |      4 |
       +--------+--------+--------+
            |
            v
Heap   +--------+--------+--------+--------+
       |    'a' |    'b' | uninit | uninit |
       +--------+--------+--------+--------+

```
 * **uninit** represents memory that is not initialized, see [`MaybeUninit`](../mem/union.maybeuninit "union std::mem::MaybeUninit").
* Note: the ABI is not stable and `Vec` makes no guarantees about its memory layout (including the order of fields).

 `Vec` will never perform a “small optimization” where elements are actually stored on the stack for two reasons:

 * It would make it more difficult for unsafe code to correctly manipulate a `Vec`. The contents of a `Vec` wouldn’t have a stable address if it were only moved, and it would be more difficult to determine if a `Vec` had actually allocated memory.
* It would penalize the general case, incurring an additional branch on every access.

 `Vec` will never automatically shrink itself, even if completely empty. This ensures no unnecessary allocations or deallocations occur. Emptying a `Vec` and then filling it back up to the same [`len`](struct.vec#method.len "method std::vec::Vec::len") should incur no calls to the allocator. If you wish to free up unused memory, use [`shrink_to_fit`](struct.vec#method.shrink_to_fit "method std::vec::Vec::shrink_to_fit") or [`shrink_to`](struct.vec#method.shrink_to "method std::vec::Vec::shrink_to").

 [`push`](struct.vec#method.push "method std::vec::Vec::push") and [`insert`](struct.vec#method.insert "method std::vec::Vec::insert") will never (re)allocate if the reported capacity is sufficient. [`push`](struct.vec#method.push "method std::vec::Vec::push") and [`insert`](struct.vec#method.insert "method std::vec::Vec::insert") *will* (re)allocate if `[len](struct.vec#method.len "method std::vec::Vec::len") == [capacity](struct.vec#method.capacity "method std::vec::Vec::capacity")`. That is, the reported capacity is completely accurate, and can be relied on. It can even be used to manually free the memory allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even when not necessary.

 `Vec` does not guarantee any particular growth strategy when reallocating when full, nor when [`reserve`](struct.vec#method.reserve "method std::vec::Vec::reserve") is called. The current strategy is basic and it may prove desirable to use a non-constant growth factor. Whatever strategy is used will of course guarantee *O*(1) amortized [`push`](struct.vec#method.push "method std::vec::Vec::push").

 `vec![x; n]`, `vec![a, b, c, d]`, and [`Vec::with_capacity(n)`](struct.vec#method.with_capacity "associated function std::vec::Vec::with_capacity"), will all produce a `Vec` with exactly the requested capacity. If `[len](struct.vec#method.len "method std::vec::Vec::len") == [capacity](struct.vec#method.capacity "method std::vec::Vec::capacity")`, (as is the case for the [`vec!`](../macro.vec "macro std::vec") macro), then a `Vec<T>` can be converted to and from a [`Box<[T]>`](../boxed/struct.box "struct std::boxed::Box") without reallocating or moving the elements.

 `Vec` will not specifically overwrite any data that is removed from it, but also won’t specifically preserve it. Its uninitialized memory is scratch space that it may use however it wants. It will generally just do whatever is most efficient or otherwise easy to implement. Do not rely on removed data to be erased for security purposes. Even if you drop a `Vec`, its buffer may simply be reused by another allocation. Even if you zero a `Vec`’s memory first, that might not actually happen because the optimizer does not consider this a side-effect that must be preserved. There is one case which we will not break, however: using `unsafe` code to write to the excess capacity, and then increasing the length to match, is always valid.

 Currently, `Vec` does not guarantee the order in which elements are dropped. The order has changed in the past and may change again.

 Implementations
---------------



[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#405)
```
impl<T> Vec<T, Global>
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#420)const: 1.39.0
```
pub const fn new() -> Vec<T, Global>
```

Constructs a new, empty `Vec<T>`.

 The vector will not allocate until elements are pushed onto it.

 ##### Examples

 
```
let mut vec: Vec<i32> = Vec::new();
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#478)
```
pub fn with_capacity(capacity: usize) -> Vec<T, Global>
```

Constructs a new, empty `Vec<T>` with at least the specified capacity.

 The vector 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 0, the vector will not allocate.

 It is important to note that although the returned vector has the minimum *capacity* specified, the vector will have a zero *length*. For an explanation of the difference between length and capacity, see *[Capacity and reallocation](#capacity-and-reallocation)*.

 If it is important to know the exact allocated capacity of a `Vec`, always use the [`capacity`](struct.vec#method.capacity "method std::vec::Vec::capacity") method after construction.

 For `Vec<T>` where `T` is a zero-sized type, there will be no allocation and the capacity will always be `usize::MAX`.

 ##### Panics

 Panics if the new capacity exceeds `isize::MAX` bytes.

 ##### Examples

 
```
let mut vec = Vec::with_capacity(10);

// The vector contains no items, even though it has capacity for more
assert_eq!(vec.len(), 0);
assert!(vec.capacity() >= 10);

// These are all done without reallocating...
for i in 0..10 {
    vec.push(i);
}
assert_eq!(vec.len(), 10);
assert!(vec.capacity() >= 10);

// ...but this may make the vector reallocate
vec.push(11);
assert_eq!(vec.len(), 11);
assert!(vec.capacity() >= 11);

// A vector of a zero-sized type will always over-allocate, since no
// allocation is necessary
let vec_units = Vec::<()>::with_capacity(10);
assert_eq!(vec_units.capacity(), usize::MAX);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#587)
```
pub unsafe fn from_raw_parts(
    ptr: *mut T,
    length: usize,
    capacity: usize
) -> Vec<T, Global>
```

Creates a `Vec<T>` directly from a pointer, a capacity, and a length.

 ##### Safety

 This is highly unsafe, due to the number of invariants that aren’t checked:

 * `ptr` must have been allocated using the global allocator, such as via the [`alloc::alloc`](../alloc/fn.alloc "fn std::alloc::alloc") function.
* `T` needs to have the same alignment as what `ptr` was allocated with. (`T` having a less strict alignment is not sufficient, the alignment really needs to be equal to satisfy the [`dealloc`](../alloc/trait.globalalloc#tymethod.dealloc "method std::alloc::GlobalAlloc::dealloc") requirement that memory must be allocated and deallocated with the same layout.)
* The size of `T` times the `capacity` (ie. the allocated size in bytes) needs to be the same size as the pointer was allocated with. (Because similar to alignment, [`dealloc`](../alloc/trait.globalalloc#tymethod.dealloc "method std::alloc::GlobalAlloc::dealloc") must be called with the same layout `size`.)
* `length` needs to be less than or equal to `capacity`.
* The first `length` values must be properly initialized values of type `T`.
* `capacity` needs to be the capacity that the pointer was allocated with.
* The allocated size in bytes must be no larger than `isize::MAX`. See the safety documentation of [`pointer::offset`](../primitive.pointer#method.offset "method pointer::offset").

 These requirements are always upheld by any `ptr` that has been allocated via `Vec<T>`. Other allocation sources are allowed if the invariants are upheld.

 Violating these may cause problems like corrupting the allocator’s internal data structures. For example it is normally **not** safe to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`, doing so is only safe if the array was initially allocated by a `Vec` or `String`. It’s also not safe to build one from a `Vec<u16>` and its length, because the allocator cares about the alignment, and these two types have different alignments. The buffer was allocated with alignment 2 (for `u16`), but after turning it into a `Vec<u8>` it’ll be deallocated with alignment 1. To avoid these issues, it is often preferable to do casting/transmuting using [`slice::from_raw_parts`](../slice/fn.from_raw_parts "fn std::slice::from_raw_parts") instead.

 The ownership of `ptr` is effectively transferred to the `Vec<T>` which may then deallocate, reallocate or change the contents of memory pointed to by the pointer at will. Ensure that nothing else uses the pointer after calling this function.

 ##### Examples

 
```
use std::ptr;
use std::mem;

let v = vec![1, 2, 3];

// Prevent running `v`'s destructor so we are in complete control
// of the allocation.
let mut v = mem::ManuallyDrop::new(v);

// Pull out the various important pieces of information about `v`
let p = v.as_mut_ptr();
let len = v.len();
let cap = v.capacity();

unsafe {
    // Overwrite memory with 4, 5, 6
    for i in 0..len {
        ptr::write(p.add(i), 4 + i);
    }

    // Put everything back together into a Vec
    let rebuilt = Vec::from_raw_parts(p, len, cap);
    assert_eq!(rebuilt, [4, 5, 6]);
}
```
 Using memory that was allocated elsewhere:

 
```
#![feature(allocator_api)]

use std::alloc::{AllocError, Allocator, Global, Layout};

fn main() {
    let layout = Layout::array::<u32>(16).expect("overflow cannot happen");

    let vec = unsafe {
        let mem = match Global.allocate(layout) {
            Ok(mem) => mem.cast::<u32>().as_ptr(),
            Err(AllocError) => return,
        };

        mem.write(1_000_000);

        Vec::from_raw_parts_in(mem, 1, 16, Global)
    };

    assert_eq!(vec, &[1_000_000]);
    assert_eq!(vec.capacity(), 16);
}
```
 

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#592)
```
impl<T, A> Vec<T, A>
where
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#609)
```
pub const fn new_in(alloc: A) -> Vec<T, A>
```

🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838))

Constructs a new, empty `Vec<T, A>`.

 The vector will not allocate until elements are pushed onto it.

 ##### Examples

 
```
#![feature(allocator_api)]

use std::alloc::System;

let mut vec: Vec<i32, _> = Vec::new_in(System);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#671)
```
pub fn with_capacity_in(capacity: usize, alloc: A) -> Vec<T, A>
```

🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838))

Constructs a new, empty `Vec<T, A>` with at least the specified capacity with the provided allocator.

 The vector 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 0, the vector will not allocate.

 It is important to note that although the returned vector has the minimum *capacity* specified, the vector will have a zero *length*. For an explanation of the difference between length and capacity, see *[Capacity and reallocation](#capacity-and-reallocation)*.

 If it is important to know the exact allocated capacity of a `Vec`, always use the [`capacity`](struct.vec#method.capacity "method std::vec::Vec::capacity") method after construction.

 For `Vec<T, A>` where `T` is a zero-sized type, there will be no allocation and the capacity will always be `usize::MAX`.

 ##### Panics

 Panics if the new capacity exceeds `isize::MAX` bytes.

 ##### Examples

 
```
#![feature(allocator_api)]

use std::alloc::System;

let mut vec = Vec::with_capacity_in(10, System);

// The vector contains no items, even though it has capacity for more
assert_eq!(vec.len(), 0);
assert!(vec.capacity() >= 10);

// These are all done without reallocating...
for i in 0..10 {
    vec.push(i);
}
assert_eq!(vec.len(), 10);
assert!(vec.capacity() >= 10);

// ...but this may make the vector reallocate
vec.push(11);
assert_eq!(vec.len(), 11);
assert!(vec.capacity() >= 11);

// A vector of a zero-sized type will always over-allocate, since no
// allocation is necessary
let vec_units = Vec::<(), System>::with_capacity_in(10, System);
assert_eq!(vec_units.capacity(), usize::MAX);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#782)
```
pub unsafe fn from_raw_parts_in(
    ptr: *mut T,
    length: usize,
    capacity: usize,
    alloc: A
) -> Vec<T, A>
```

🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838))

Creates a `Vec<T, A>` directly from a pointer, a capacity, a length, and an allocator.

 ##### Safety

 This is highly unsafe, due to the number of invariants that aren’t checked:

 * `ptr` must be [*currently allocated*](../alloc/trait.allocator#currently-allocated-memory "trait std::alloc::Allocator") via the given allocator `alloc`.
* `T` needs to have the same alignment as what `ptr` was allocated with. (`T` having a less strict alignment is not sufficient, the alignment really needs to be equal to satisfy the [`dealloc`](../alloc/trait.globalalloc#tymethod.dealloc "method std::alloc::GlobalAlloc::dealloc") requirement that memory must be allocated and deallocated with the same layout.)
* The size of `T` times the `capacity` (ie. the allocated size in bytes) needs to be the same size as the pointer was allocated with. (Because similar to alignment, [`dealloc`](../alloc/trait.globalalloc#tymethod.dealloc "method std::alloc::GlobalAlloc::dealloc") must be called with the same layout `size`.)
* `length` needs to be less than or equal to `capacity`.
* The first `length` values must be properly initialized values of type `T`.
* `capacity` needs to [*fit*](../alloc/trait.allocator#memory-fitting "trait std::alloc::Allocator") the layout size that the pointer was allocated with.
* The allocated size in bytes must be no larger than `isize::MAX`. See the safety documentation of [`pointer::offset`](../primitive.pointer#method.offset "method pointer::offset").

 These requirements are always upheld by any `ptr` that has been allocated via `Vec<T, A>`. Other allocation sources are allowed if the invariants are upheld.

 Violating these may cause problems like corrupting the allocator’s internal data structures. For example it is **not** safe to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`. It’s also not safe to build one from a `Vec<u16>` and its length, because the allocator cares about the alignment, and these two types have different alignments. The buffer was allocated with alignment 2 (for `u16`), but after turning it into a `Vec<u8>` it’ll be deallocated with alignment 1.

 The ownership of `ptr` is effectively transferred to the `Vec<T>` which may then deallocate, reallocate or change the contents of memory pointed to by the pointer at will. Ensure that nothing else uses the pointer after calling this function.

 ##### Examples

 
```
#![feature(allocator_api)]

use std::alloc::System;

use std::ptr;
use std::mem;

let mut v = Vec::with_capacity_in(3, System);
v.push(1);
v.push(2);
v.push(3);

// Prevent running `v`'s destructor so we are in complete control
// of the allocation.
let mut v = mem::ManuallyDrop::new(v);

// Pull out the various important pieces of information about `v`
let p = v.as_mut_ptr();
let len = v.len();
let cap = v.capacity();
let alloc = v.allocator();

unsafe {
    // Overwrite memory with 4, 5, 6
    for i in 0..len {
        ptr::write(p.add(i), 4 + i);
    }

    // Put everything back together into a Vec
    let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone());
    assert_eq!(rebuilt, [4, 5, 6]);
}
```
 Using memory that was allocated elsewhere:

 
```
use std::alloc::{alloc, Layout};

fn main() {
    let layout = Layout::array::<u32>(16).expect("overflow cannot happen");
    let vec = unsafe {
        let mem = alloc(layout).cast::<u32>();
        if mem.is_null() {
            return;
        }

        mem.write(1_000_000);

        Vec::from_raw_parts(mem, 1, 16)
    };

    assert_eq!(vec, &[1_000_000]);
    assert_eq!(vec.capacity(), 16);
}
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#819)
```
pub fn into_raw_parts(self) -> (*mut T, usize, usize)
```

🔬This is a nightly-only experimental API. (`vec_into_raw_parts` [#65816](https://github.com/rust-lang/rust/issues/65816))

Decomposes a `Vec<T>` into its raw components.

 Returns the raw pointer to the underlying data, the length of the vector (in elements), and the allocated capacity of the data (in elements). These are the same arguments in the same order as the arguments to [`from_raw_parts`](struct.vec#method.from_raw_parts "associated function std::vec::Vec::from_raw_parts").

 After calling this function, the caller is responsible for the memory previously managed by the `Vec`. The only way to do this is to convert the raw pointer, length, and capacity back into a `Vec` with the [`from_raw_parts`](struct.vec#method.from_raw_parts "associated function std::vec::Vec::from_raw_parts") function, allowing the destructor to perform the cleanup.

 ##### Examples

 
```
#![feature(vec_into_raw_parts)]
let v: Vec<i32> = vec![-1, 0, 1];

let (ptr, len, cap) = v.into_raw_parts();

let rebuilt = unsafe {
    // We can now make changes to the components, such as
    // transmuting the raw pointer to a compatible type.
    let ptr = ptr as *mut u32;

    Vec::from_raw_parts(ptr, len, cap)
};
assert_eq!(rebuilt, [4294967295, 0, 1]);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#863)
```
pub fn into_raw_parts_with_alloc(self) -> (*mut T, usize, usize, A)
```

🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838))

Decomposes a `Vec<T>` into its raw components.

 Returns the raw pointer to the underlying data, the length of the vector (in elements), the allocated capacity of the data (in elements), and the allocator. These are the same arguments in the same order as the arguments to [`from_raw_parts_in`](struct.vec#method.from_raw_parts_in "associated function std::vec::Vec::from_raw_parts_in").

 After calling this function, the caller is responsible for the memory previously managed by the `Vec`. The only way to do this is to convert the raw pointer, length, and capacity back into a `Vec` with the [`from_raw_parts_in`](struct.vec#method.from_raw_parts_in "associated function std::vec::Vec::from_raw_parts_in") function, allowing the destructor to perform the cleanup.

 ##### Examples

 
```
#![feature(allocator_api, vec_into_raw_parts)]

use std::alloc::System;

let mut v: Vec<i32, System> = Vec::new_in(System);
v.push(-1);
v.push(0);
v.push(1);

let (ptr, len, cap, alloc) = v.into_raw_parts_with_alloc();

let rebuilt = unsafe {
    // We can now make changes to the components, such as
    // transmuting the raw pointer to a compatible type.
    let ptr = ptr as *mut u32;

    Vec::from_raw_parts_in(ptr, len, cap, alloc)
};
assert_eq!(rebuilt, [4294967295, 0, 1]);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#884)
```
pub fn capacity(&self) -> usize
```

Returns the total number of elements the vector can hold without reallocating.

 ##### Examples

 
```
let mut vec: Vec<i32> = Vec::with_capacity(10);
vec.push(42);
assert!(vec.capacity() >= 10);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#907)
```
pub fn reserve(&mut self, additional: usize)
```

Reserves capacity for at least `additional` more elements to be inserted in the given `Vec<T>`. The collection may reserve more space to speculatively avoid frequent reallocations. After calling `reserve`, capacity will be greater than or equal to `self.len() + additional`. Does nothing if capacity is already sufficient.

 ##### Panics

 Panics if the new capacity exceeds `isize::MAX` bytes.

 ##### Examples

 
```
let mut vec = vec![1];
vec.reserve(10);
assert!(vec.capacity() >= 11);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#937)
```
pub fn reserve_exact(&mut self, additional: usize)
```

Reserves the minimum capacity for at least `additional` more elements to be inserted in the given `Vec<T>`. Unlike [`reserve`](struct.vec#method.reserve "method std::vec::Vec::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.

 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 [`reserve`](struct.vec#method.reserve "method std::vec::Vec::reserve") if future insertions are expected.

 ##### Panics

 Panics if the new capacity exceeds `isize::MAX` bytes.

 ##### Examples

 
```
let mut vec = vec![1];
vec.reserve_exact(10);
assert!(vec.capacity() >= 11);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#974)1.57.0
```
pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>
```

Tries to reserve capacity for at least `additional` more elements to be inserted in the given `Vec<T>`. The collection may reserve more space to speculatively avoid frequent reallocations. 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.

 ##### Errors

 If the capacity overflows, or the allocator reports a failure, then an error is returned.

 ##### Examples

 
```
use std::collections::TryReserveError;

fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
    let mut output = Vec::new();

    // Pre-reserve the memory, exiting if we can't
    output.try_reserve(data.len())?;

    // Now we know this can't OOM in the middle of our complex work
    output.extend(data.iter().map(|&val| {
        val * 2 + 5 // very complicated
    }));

    Ok(output)
}
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#1017)1.57.0
```
pub fn try_reserve_exact(
    &mut self,
    additional: usize
) -> Result<(), TryReserveError>
```

Tries to reserve the minimum capacity for at least `additional` elements to be inserted in the given `Vec<T>`. Unlike [`try_reserve`](struct.vec#method.try_reserve "method std::vec::Vec::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`](struct.vec#method.try_reserve "method std::vec::Vec::try_reserve") if future insertions are expected.

 ##### Errors

 If the capacity overflows, or the allocator reports a failure, then an error is returned.

 ##### Examples

 
```
use std::collections::TryReserveError;

fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
    let mut output = Vec::new();

    // Pre-reserve the memory, exiting if we can't
    output.try_reserve_exact(data.len())?;

    // Now we know this can't OOM in the middle of our complex work
    output.extend(data.iter().map(|&val| {
        val * 2 + 5 // very complicated
    }));

    Ok(output)
}
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#1037)
```
pub fn shrink_to_fit(&mut self)
```

Shrinks the capacity of the vector as much as possible.

 It will drop down as close as possible to the length but the allocator may still inform the vector that there is space for a few more elements.

 ##### Examples

 
```
let mut vec = Vec::with_capacity(10);
vec.extend([1, 2, 3]);
assert!(vec.capacity() >= 10);
vec.shrink_to_fit();
assert!(vec.capacity() >= 3);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#1066)1.56.0
```
pub fn shrink_to(&mut self, min_capacity: usize)
```

Shrinks the capacity of the vector 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.

 ##### Examples

 
```
let mut vec = Vec::with_capacity(10);
vec.extend([1, 2, 3]);
assert!(vec.capacity() >= 10);
vec.shrink_to(4);
assert!(vec.capacity() >= 4);
vec.shrink_to(0);
assert!(vec.capacity() >= 3);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#1099)
```
pub fn into_boxed_slice(self) -> Box<[T], A>
```

Converts the vector into [`Box<[T]>`](../boxed/struct.box "struct std::boxed::Box").

 If the vector has excess capacity, its items will be moved into a newly-allocated buffer with exactly the right capacity.

 ##### Examples

 
```
let v = vec![1, 2, 3];

let slice = v.into_boxed_slice();
```
 Any excess capacity is removed:

 
```
let mut vec = Vec::with_capacity(10);
vec.extend([1, 2, 3]);

assert!(vec.capacity() >= 10);
let slice = vec.into_boxed_slice();
assert_eq!(slice.into_vec().capacity(), 3);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#1152)
```
pub fn truncate(&mut self, len: usize)
```

Shortens the vector, keeping the first `len` elements and dropping the rest.

 If `len` is greater than the vector’s current length, this has no effect.

 The [`drain`](struct.vec#method.drain "method std::vec::Vec::drain") method can emulate `truncate`, but causes the excess elements to be returned instead of dropped.

 Note that this method has no effect on the allocated capacity of the vector.

 ##### Examples

 Truncating a five element vector to two elements:

 
```
let mut vec = vec![1, 2, 3, 4, 5];
vec.truncate(2);
assert_eq!(vec, [1, 2]);
```
 No truncation occurs when `len` is greater than the vector’s current length:

 
```
let mut vec = vec![1, 2, 3];
vec.truncate(8);
assert_eq!(vec, [1, 2, 3]);
```
 Truncating when `len == 0` is equivalent to calling the [`clear`](struct.vec#method.clear "method std::vec::Vec::clear") method.

 
```
let mut vec = vec![1, 2, 3];
vec.truncate(0);
assert_eq!(vec, []);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#1187)1.7.0
```
pub fn as_slice(&self) -> &[T]
```

Extracts a slice containing the entire vector.

 Equivalent to `&s[..]`.

 ##### Examples

 
```
use std::io::{self, Write};
let buffer = vec![1, 2, 3, 5, 8];
io::sink().write(buffer.as_slice()).unwrap();
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#1204)1.7.0
```
pub fn as_mut_slice(&mut self) -> &mut [T]
```

Extracts a mutable slice of the entire vector.

 Equivalent to `&mut s[..]`.

 ##### Examples

 
```
use std::io::{self, Read};
let mut buffer = vec![0; 3];
io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#1236)1.37.0
```
pub fn as_ptr(&self) -> *const T
```

Returns a raw pointer to the vector’s buffer, or a dangling raw pointer valid for zero sized reads if the vector didn’t allocate.

 The caller must ensure that the vector outlives the pointer this function returns, or else it will end up pointing to garbage. Modifying the vector may cause its buffer to be reallocated, which would also make any pointers to it invalid.

 The caller must also ensure that the memory the pointer (non-transitively) points to is never written to (except inside an `UnsafeCell`) using this pointer or any pointer derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`](struct.vec#method.as_mut_ptr "method std::vec::Vec::as_mut_ptr").

 ##### Examples

 
```
let x = vec![1, 2, 4];
let x_ptr = x.as_ptr();

unsafe {
    for i in 0..x.len() {
        assert_eq!(*x_ptr.add(i), 1 << i);
    }
}
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#1269)1.37.0
```
pub fn as_mut_ptr(&mut self) -> *mut T
```

Returns an unsafe mutable pointer to the vector’s buffer, or a dangling raw pointer valid for zero sized reads if the vector didn’t allocate.

 The caller must ensure that the vector outlives the pointer this function returns, or else it will end up pointing to garbage. Modifying the vector may cause its buffer to be reallocated, which would also make any pointers to it invalid.

 ##### Examples

 
```
// Allocate vector big enough for 4 elements.
let size = 4;
let mut x: Vec<i32> = Vec::with_capacity(size);
let x_ptr = x.as_mut_ptr();

// Initialize elements via raw pointer writes, then set length.
unsafe {
    for i in 0..size {
        *x_ptr.add(i) = i as i32;
    }
    x.set_len(size);
}
assert_eq!(&*x, &[0, 1, 2, 3]);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#1278)
```
pub fn allocator(&self) -> &A
```

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

 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#1362)
```
pub unsafe fn set_len(&mut self, new_len: usize)
```

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`](struct.vec#method.truncate "method std::vec::Vec::truncate"), [`resize`](struct.vec#method.resize "method std::vec::Vec::resize"), [`extend`](../iter/trait.extend#tymethod.extend "method std::iter::Extend::extend"), or [`clear`](struct.vec#method.clear "method std::vec::Vec::clear").

 ##### Safety

 * `new_len` must be less than or equal to [`capacity()`](struct.vec#method.capacity "method std::vec::Vec::capacity").
* The elements at `old_len..new_len` must be initialized.

 ##### Examples

 This method can be useful for situations in which the vector is serving as a buffer for other code, particularly over FFI:

 
```
pub fn get_dictionary(&self) -> Option<Vec<u8>> {
    // Per the FFI method's docs, "32768 bytes is always enough".
    let mut dict = Vec::with_capacity(32_768);
    let mut dict_length = 0;
    // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
    // 1. `dict_length` elements were initialized.
    // 2. `dict_length` <= the capacity (32_768)
    // which makes `set_len` safe to call.
    unsafe {
        // Make the FFI call...
        let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
        if r == Z_OK {
            // ...and update the length to what was initialized.
            dict.set_len(dict_length);
            Some(dict)
        } else {
            None
        }
    }
}
```
 While the following example is sound, there is a memory leak since the inner vectors were not freed prior to the `set_len` call:

 
```
let mut vec = vec![vec![1, 0, 0],
                   vec![0, 1, 0],
                   vec![0, 0, 1]];
// SAFETY:
// 1. `old_len..0` is empty so no elements need to be initialized.
// 2. `0 <= capacity` always holds whatever `capacity` is.
unsafe {
    vec.set_len(0);
}
```
 Normally, here, one would use [`clear`](struct.vec#method.clear "method std::vec::Vec::clear") instead to correctly drop the contents and thus not leak memory.

 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#1394)
```
pub fn swap_remove(&mut self, index: usize) -> T
```

Removes an element from the vector and returns it.

 The removed element is replaced by the last element of the vector.

 This does not preserve ordering, but is *O*(1). If you need to preserve the element order, use [`remove`](struct.vec#method.remove "method std::vec::Vec::remove") instead.

 ##### Panics

 Panics if `index` is out of bounds.

 ##### Examples

 
```
let mut v = vec!["foo", "bar", "baz", "qux"];

assert_eq!(v.swap_remove(1), "bar");
assert_eq!(v, ["foo", "qux", "baz"]);

assert_eq!(v.swap_remove(0), "foo");
assert_eq!(v, ["baz", "qux"]);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#1435)
```
pub fn insert(&mut self, index: usize, element: T)
```

Inserts an element at position `index` within the vector, shifting all elements after it to the right.

 ##### Panics

 Panics if `index > len`.

 ##### Examples

 
```
let mut vec = vec![1, 2, 3];
vec.insert(1, 4);
assert_eq!(vec, [1, 4, 2, 3]);
vec.insert(4, 5);
assert_eq!(vec, [1, 4, 2, 3, 5]);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#1496)
```
pub fn remove(&mut self, index: usize) -> T
```

Removes and returns the element at position `index` within the vector, shifting all elements after it to the left.

 Note: Because this shifts over the remaining elements, it has a worst-case performance of *O*(*n*). If you don’t need the order of elements to be preserved, use [`swap_remove`](struct.vec#method.swap_remove "method std::vec::Vec::swap_remove") instead. If you’d like to remove elements from the beginning of the `Vec`, consider using [`VecDeque::pop_front`](../collections/struct.vecdeque#method.pop_front "method std::collections::VecDeque::pop_front") instead.

 ##### Panics

 Panics if `index` is out of bounds.

 ##### Examples

 
```
let mut v = vec![1, 2, 3];
assert_eq!(v.remove(1), 2);
assert_eq!(v, [1, 3]);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#1551-1553)
```
pub fn retain<F>(&mut self, f: F)
where
    F: FnMut(&T) -> bool,
```

Retains only the elements specified by the predicate.

 In other words, remove all elements `e` for which `f(&e)` returns `false`. This method operates in place, visiting each element exactly once in the original order, and preserves the order of the retained elements.

 ##### Examples

 
```
let mut vec = vec![1, 2, 3, 4];
vec.retain(|&x| x % 2 == 0);
assert_eq!(vec, [2, 4]);
```
 Because the elements are visited exactly once in the original order, external state may be used to decide which elements to keep.

 
```
let mut vec = vec![1, 2, 3, 4, 5];
let keep = [false, true, true, false, true];
let mut iter = keep.iter();
vec.retain(|_| *iter.next().unwrap());
assert_eq!(vec, [2, 3, 5]);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#1577-1579)1.61.0
```
pub fn retain_mut<F>(&mut self, f: F)
where
    F: FnMut(&mut T) -> bool,
```

Retains only the elements specified by the predicate, passing a mutable reference to it.

 In other words, remove all elements `e` such that `f(&mut e)` returns `false`. This method operates in place, visiting each element exactly once in the original order, and preserves the order of the retained elements.

 ##### Examples

 
```
let mut vec = vec![1, 2, 3, 4];
vec.retain_mut(|x| if *x <= 3 {
    *x += 1;
    true
} else {
    false
});
assert_eq!(vec, [2, 3, 4]);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#1686-1689)1.16.0
```
pub fn dedup_by_key<F, K>(&mut self, key: F)
where
    F: FnMut(&mut T) -> K,
    K: PartialEq<K>,
```

Removes all but the first of consecutive elements in the vector that resolve to the same key.

 If the vector is sorted, this removes all duplicates.

 ##### Examples

 
```
let mut vec = vec![10, 20, 21, 30, 20];

vec.dedup_by_key(|i| *i / 10);

assert_eq!(vec, [10, 20, 30, 20]);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#1713-1715)1.16.0
```
pub fn dedup_by<F>(&mut self, same_bucket: F)
where
    F: FnMut(&mut T, &mut T) -> bool,
```

Removes all but the first of consecutive elements in the vector satisfying a given equality relation.

 The `same_bucket` function is passed references to two elements from the vector and must determine if the elements compare equal. The elements are passed in opposite order from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.

 If the vector is sorted, this removes all duplicates.

 ##### Examples

 
```
let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];

vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));

assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#1824)
```
pub fn push(&mut self, value: T)
```

Appends an element to the back of a collection.

 ##### Panics

 Panics if the new capacity exceeds `isize::MAX` bytes.

 ##### Examples

 
```
let mut vec = vec![1, 2];
vec.push(3);
assert_eq!(vec, [1, 2, 3]);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#1870)
```
pub fn push_within_capacity(&mut self, value: T) -> Result<(), T>
```

🔬This is a nightly-only experimental API. (`vec_push_within_capacity` [#100486](https://github.com/rust-lang/rust/issues/100486))

Appends an element if there is sufficient spare capacity, otherwise an error is returned with the element.

 Unlike [`push`](struct.vec#method.push "method std::vec::Vec::push") this method will not reallocate when there’s insufficient capacity. The caller should use [`reserve`](struct.vec#method.reserve "method std::vec::Vec::reserve") or [`try_reserve`](struct.vec#method.try_reserve "method std::vec::Vec::try_reserve") to ensure that there is enough capacity.

 ##### Examples

 A manual, panic-free alternative to [`FromIterator`](../iter/trait.fromiterator "trait std::iter::FromIterator"):

 
```
#![feature(vec_push_within_capacity)]

use std::collections::TryReserveError;
fn from_iter_fallible<T>(iter: impl Iterator<Item=T>) -> Result<Vec<T>, TryReserveError> {
    let mut vec = Vec::new();
    for value in iter {
        if let Err(value) = vec.push_within_capacity(value) {
            vec.try_reserve(1)?;
            // this cannot fail, the previous line either returned or added at least 1 free slot
            let _ = vec.push_within_capacity(value);
        }
    }
    Ok(vec)
}
assert_eq!(from_iter_fallible(0..100), Ok(Vec::from_iter(0..100)));
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#1899)
```
pub fn pop(&mut self) -> Option<T>
```

Removes the last element from a vector and returns it, or [`None`](../option/enum.option#variant.None "variant std::option::Option::None") if it is empty.

 If you’d like to pop the first element, consider using [`VecDeque::pop_front`](../collections/struct.vecdeque#method.pop_front "method std::collections::VecDeque::pop_front") instead.

 ##### Examples

 
```
let mut vec = vec![1, 2, 3];
assert_eq!(vec.pop(), Some(3));
assert_eq!(vec, [1, 2]);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#1928)1.4.0
```
pub fn append(&mut self, other: &mut Vec<T, A>)
```

Moves all the elements of `other` into `self`, leaving `other` empty.

 ##### Panics

 Panics if the new capacity exceeds `isize::MAX` bytes.

 ##### Examples

 
```
let mut vec = vec![1, 2, 3];
let mut vec2 = vec![4, 5, 6];
vec.append(&mut vec2);
assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
assert_eq!(vec2, []);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#1977-1979)1.6.0
```
pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A> ⓘ
where
    R: RangeBounds<usize>,
```

Removes the specified range from the vector in bulk, returning all removed elements as an iterator. If the iterator is dropped before being fully consumed, it drops the remaining removed elements.

 The returned iterator keeps a mutable borrow on the vector to optimize its implementation.

 ##### Panics

 Panics if the starting point is greater than the end point or if the end point is greater than the length of the vector.

 ##### Leaking

 If the returned iterator goes out of scope without being dropped (due to [`mem::forget`](../mem/fn.forget "fn std::mem::forget"), for example), the vector may have lost and leaked elements arbitrarily, including elements outside the range.

 ##### Examples

 
```
let mut v = vec![1, 2, 3];
let u: Vec<_> = v.drain(1..).collect();
assert_eq!(v, &[1]);
assert_eq!(u, &[2, 3]);

// A full range clears the vector, like `clear()` does
v.drain(..);
assert_eq!(v, &[]);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2023)
```
pub fn clear(&mut self)
```

Clears the vector, removing all values.

 Note that this method has no effect on the allocated capacity of the vector.

 ##### Examples

 
```
let mut v = vec![1, 2, 3];

v.clear();

assert!(v.is_empty());
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2049)
```
pub fn len(&self) -> usize
```

Returns the number of elements in the vector, also referred to as its ‘length’.

 ##### Examples

 
```
let a = vec![1, 2, 3];
assert_eq!(a.len(), 3);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2065)
```
pub fn is_empty(&self) -> bool
```

Returns `true` if the vector contains no elements.

 ##### Examples

 
```
let mut v = Vec::new();
assert!(v.is_empty());

v.push(1);
assert!(!v.is_empty());
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2091-2093)1.4.0
```
pub fn split_off(&mut self, at: usize) -> Vec<T, A>
where
    A: Clone,
```

Splits the collection into two at the given index.

 Returns a newly allocated vector containing the elements in the range `[at, len)`. After the call, the original vector will be left containing the elements `[0, at)` with its previous capacity unchanged.

 ##### Panics

 Panics if `at > len`.

 ##### Examples

 
```
let mut vec = vec![1, 2, 3];
let vec2 = vec.split_off(1);
assert_eq!(vec, [1]);
assert_eq!(vec2, [2, 3]);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2154-2156)1.33.0
```
pub fn resize_with<F>(&mut self, new_len: usize, f: F)
where
    F: FnMut() -> T,
```

Resizes the `Vec` in-place so that `len` is equal to `new_len`.

 If `new_len` is greater than `len`, the `Vec` is extended by the difference, with each additional slot filled with the result of calling the closure `f`. The return values from `f` will end up in the `Vec` in the order they have been generated.

 If `new_len` is less than `len`, the `Vec` is simply truncated.

 This method uses a closure to create new values on every push. If you’d rather [`Clone`](../clone/trait.clone "trait std::clone::Clone") a given value, use [`Vec::resize`](struct.vec#method.resize "method std::vec::Vec::resize"). If you want to use the [`Default`](../default/trait.default "trait std::default::Default") trait to generate values, you can pass [`Default::default`](../default/trait.default#tymethod.default "associated function std::default::Default::default") as the second argument.

 ##### Examples

 
```
let mut vec = vec![1, 2, 3];
vec.resize_with(5, Default::default);
assert_eq!(vec, [1, 2, 3, 0, 0]);

let mut vec = vec![];
let mut p = 1;
vec.resize_with(4, || { p *= 2; p });
assert_eq!(vec, [2, 4, 8, 16]);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2191-2193)1.47.0
```
pub fn leak<'a>(self) -> &'a mut [T]
where
    A: 'a,
```

Consumes and leaks the `Vec`, returning a mutable reference to the contents, `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime `'a`. If the type has only static references, or none at all, then this may be chosen to be `'static`.

 As of Rust 1.57, this method does not reallocate or shrink the `Vec`, so the leaked allocation may include unused capacity that is not part of the returned slice.

 This function is mainly useful for data that lives for the remainder of the program’s life. Dropping the returned reference will cause a memory leak.

 ##### Examples

 Simple usage:

 
```
let x = vec![1, 2, 3];
let static_ref: &'static mut [usize] = x.leak();
static_ref[0] += 1;
assert_eq!(static_ref, &[2, 2, 3]);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2229)1.60.0
```
pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>]
```

Returns the remaining spare capacity of the vector as a slice of `MaybeUninit<T>`.

 The returned slice can be used to fill the vector with data (e.g. by reading from a file) before marking the data as initialized using the [`set_len`](struct.vec#method.set_len "method std::vec::Vec::set_len") method.

 ##### Examples

 
```
// Allocate vector big enough for 10 elements.
let mut v = Vec::with_capacity(10);

// Fill in the first 3 elements.
let uninit = v.spare_capacity_mut();
uninit[0].write(0);
uninit[1].write(1);
uninit[2].write(2);

// Mark the first 3 elements of the vector as being initialized.
unsafe {
    v.set_len(3);
}

assert_eq!(&v, &[0, 1, 2]);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2294)
```
pub fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>])
```

🔬This is a nightly-only experimental API. (`vec_split_at_spare` [#81944](https://github.com/rust-lang/rust/issues/81944))

Returns vector content as a slice of `T`, along with the remaining spare capacity of the vector as a slice of `MaybeUninit<T>`.

 The returned spare capacity slice can be used to fill the vector with data (e.g. by reading from a file) before marking the data as initialized using the [`set_len`](struct.vec#method.set_len "method std::vec::Vec::set_len") method.

 Note that this is a low-level API, which should be used with care for optimization purposes. If you need to append data to a `Vec` you can use [`push`](struct.vec#method.push "method std::vec::Vec::push"), [`extend`](struct.vec#method.extend "method std::vec::Vec::extend"), [`extend_from_slice`](struct.vec#method.extend_from_slice "method std::vec::Vec::extend_from_slice"), [`extend_from_within`](struct.vec#method.extend_from_within "method std::vec::Vec::extend_from_within"), [`insert`](struct.vec#method.insert "method std::vec::Vec::insert"), [`append`](struct.vec#method.append "method std::vec::Vec::append"), [`resize`](struct.vec#method.resize "method std::vec::Vec::resize") or [`resize_with`](struct.vec#method.resize_with "method std::vec::Vec::resize_with"), depending on your exact needs.

 ##### Examples

 
```
#![feature(vec_split_at_spare)]

let mut v = vec![1, 1, 2];

// Reserve additional space big enough for 10 elements.
v.reserve(10);

let (init, uninit) = v.split_at_spare_mut();
let sum = init.iter().copied().sum::<u32>();

// Fill in the next 4 elements.
uninit[0].write(sum);
uninit[1].write(sum * 2);
uninit[2].write(sum * 3);
uninit[3].write(sum * 4);

// Mark the 4 elements of the vector as being initialized.
unsafe {
    let len = v.len();
    v.set_len(len + 4);
}

assert_eq!(&v, &[1, 1, 2, 4, 8, 12, 16]);
```
 

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2328)
```
impl<T, A> Vec<T, A>
where
    T: Clone,
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2354)1.5.0
```
pub fn resize(&mut self, new_len: usize, value: T)
```

Resizes the `Vec` in-place so that `len` is equal to `new_len`.

 If `new_len` is greater than `len`, the `Vec` is extended by the difference, with each additional slot filled with `value`. If `new_len` is less than `len`, the `Vec` is simply truncated.

 This method requires `T` to implement [`Clone`](../clone/trait.clone "trait std::clone::Clone"), in order to be able to clone the passed value. If you need more flexibility (or want to rely on [`Default`](../default/trait.default "trait std::default::Default") instead of [`Clone`](../clone/trait.clone "trait std::clone::Clone")), use [`Vec::resize_with`](struct.vec#method.resize_with "method std::vec::Vec::resize_with"). If you only need to resize to a smaller size, use [`Vec::truncate`](struct.vec#method.truncate "method std::vec::Vec::truncate").

 ##### Examples

 
```
let mut vec = vec!["hello"];
vec.resize(3, "world");
assert_eq!(vec, ["hello", "world", "world"]);

let mut vec = vec![1, 2, 3, 4];
vec.resize(2, 0);
assert_eq!(vec, [1, 2]);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2385)1.6.0
```
pub fn extend_from_slice(&mut self, other: &[T])
```

Clones and appends all elements in a slice to the `Vec`.

 Iterates over the slice `other`, clones each element, and then appends it to this `Vec`. The `other` slice is traversed in-order.

 Note that this function is same as [`extend`](struct.vec#method.extend "method std::vec::Vec::extend") except that it is specialized to work with slices instead. If and when Rust gets specialization this function will likely be deprecated (but still available).

 ##### Examples

 
```
let mut vec = vec![1];
vec.extend_from_slice(&[2, 3, 4]);
assert_eq!(vec, [1, 2, 3, 4]);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2412-2414)1.53.0
```
pub fn extend_from_within<R>(&mut self, src: R)
where
    R: RangeBounds<usize>,
```

Copies elements from `src` range to the end of the vector.

 ##### Panics

 Panics if the starting point is greater than the end point or if the end point is greater than the length of the vector.

 ##### Examples

 
```
let mut vec = vec![0, 1, 2, 3, 4];

vec.extend_from_within(2..);
assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4]);

vec.extend_from_within(..2);
assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1]);

vec.extend_from_within(4..8);
assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1, 4, 2, 3, 4]);
```
 

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2427)
```
impl<T, A, const N: usize> Vec<[T; N], A>
where
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2450)
```
pub fn into_flattened(self) -> Vec<T, A>
```

🔬This is a nightly-only experimental API. (`slice_flatten` [#95629](https://github.com/rust-lang/rust/issues/95629))

Takes a `Vec<[T; N]>` and flattens it into a `Vec<T>`.

 ##### Panics

 Panics if the length of the resulting vector would overflow a `usize`.

 This is only possible when flattening a vector of arrays of zero-sized types, and thus tends to be irrelevant in practice. If `size_of::<T>() > 0`, this will never panic.

 ##### Examples

 
```
#![feature(slice_flatten)]

let mut vec = vec![[1, 2, 3], [4, 5, 6], [7, 8, 9]];
assert_eq!(vec.pop(), Some([7, 8, 9]));

let mut flattened = vec.into_flattened();
assert_eq!(flattened.pop(), Some(6));
```
 

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2520)
```
impl<T, A> Vec<T, A>
where
    T: PartialEq<T>,
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2537)
```
pub fn dedup(&mut self)
```

Removes consecutive repeated elements in the vector according to the [`PartialEq`](../cmp/trait.partialeq "trait std::cmp::PartialEq") trait implementation.

 If the vector is sorted, this removes all duplicates.

 ##### Examples

 
```
let mut vec = vec![1, 2, 2, 3, 2];

vec.dedup();

assert_eq!(vec, [1, 2, 3, 2]);
```
 

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2799)
```
impl<T, A> Vec<T, A>
where
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2897-2900)1.21.0
```
pub fn splice<R, I>(
    &mut self,
    range: R,
    replace_with: I
) -> Splice<'_, <I as IntoIterator>::IntoIter, A> ⓘ
where
    R: RangeBounds<usize>,
    I: IntoIterator<Item = T>,
```

Creates a splicing iterator that replaces the specified range in the vector with the given `replace_with` iterator and yields the removed items. `replace_with` does not need to be the same length as `range`.

 `range` is removed even if the iterator is not consumed until the end.

 It is unspecified how many elements are removed from the vector if the `Splice` value is leaked.

 The input iterator `replace_with` is only consumed when the `Splice` value is dropped.

 This is optimal if:

 * The tail (elements in the vector after `range`) is empty,
* or `replace_with` yields fewer or equal elements than `range`’s length
* or the lower bound of its `size_hint()` is exact.

 Otherwise, a temporary vector is allocated and the tail is moved twice.

 ##### Panics

 Panics if the starting point is greater than the end point or if the end point is greater than the length of the vector.

 ##### Examples

 
```
let mut v = vec![1, 2, 3, 4];
let new = [7, 8, 9];
let u: Vec<_> = v.splice(1..3, new).collect();
assert_eq!(v, &[1, 7, 8, 9, 4]);
assert_eq!(u, &[2, 3]);
```
 
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2950-2952)
```
pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F, A> ⓘ
where
    F: FnMut(&mut T) -> bool,
```

🔬This is a nightly-only experimental API. (`drain_filter` [#43244](https://github.com/rust-lang/rust/issues/43244))

Creates an iterator which uses a closure to determine if an element should be removed.

 If the closure returns true, then the element is removed and yielded. If the closure returns false, the element will remain in the vector and will not be yielded by the iterator.

 Using this method is equivalent to the following code:

 
```
let mut i = 0;
while i < vec.len() {
    if some_predicate(&mut vec[i]) {
        let val = vec.remove(i);
        // your code here
    } else {
        i += 1;
    }
}

```
 But `drain_filter` is easier to use. `drain_filter` is also more efficient, because it can backshift the elements of the array in bulk.

 Note that `drain_filter` also lets you mutate every element in the filter closure, regardless of whether you choose to keep or remove it.

 ##### Examples

 Splitting an array into evens and odds, reusing the original allocation:

 
```
#![feature(drain_filter)]
let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];

let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
let odds = numbers;

assert_eq!(evens, vec![2, 4, 6, 8, 14]);
assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
```
 


Methods from [Deref](../ops/trait.deref "trait std::ops::Deref")<Target = [[T]](../primitive.slice)>
----------------------------------------------------------------------------------------------------


[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4570)
```
pub fn sort_floats(&mut self)
```

🔬This is a nightly-only experimental API. (`sort_floats` [#93396](https://github.com/rust-lang/rust/issues/93396))

Sorts the slice of floats.

 This sort is in-place (i.e. does not allocate), *O*(*n* \* log(*n*)) worst-case, and uses the ordering defined by [`f32::total_cmp`](../primitive.f32#method.total_cmp "method f32::total_cmp").

 ##### Current implementation

 This uses the same sorting algorithm as [`sort_unstable_by`](../primitive.slice#method.sort_unstable_by "method slice::sort_unstable_by").

 ##### Examples

 
```
#![feature(sort_floats)]
let mut v = [2.6, -5e-8, f32::NAN, 8.29, f32::INFINITY, -1.0, 0.0, -f32::INFINITY, -0.0];

v.sort_floats();
let sorted = [-f32::INFINITY, -1.0, -5e-8, -0.0, 0.0, 2.6, 8.29, f32::INFINITY, f32::NAN];
assert_eq!(&v[..8], &sorted[..8]);
assert!(v[8].is_nan());
```
 
[source](https://doc.rust-lang.org/src/core/ascii/ascii_char.rs.html#544)
```
pub fn as_str(&self) -> &str
```

🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998))

Views this slice of ASCII characters as a UTF-8 `str`.

 
[source](https://doc.rust-lang.org/src/core/ascii/ascii_char.rs.html#555)
```
pub fn as_bytes(&self) -> &[u8] ⓘ
```

🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998))

Views this slice of ASCII characters as a slice of `u8` bytes.

 
[source](https://doc.rust-lang.org/src/core/slice/ascii.rs.html#16)1.23.0
```
pub fn is_ascii(&self) -> bool
```

Checks if all bytes in this slice are within the ASCII range.

 
[source](https://doc.rust-lang.org/src/core/slice/ascii.rs.html#25)
```
pub fn as_ascii(&self) -> Option<&[AsciiChar]>
```

🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998))

If this slice [`is_ascii`](../primitive.slice#method.is_ascii "method slice::is_ascii"), returns it as a slice of [ASCII characters](../ascii/enum.char "enum std::ascii::Char"), otherwise returns `None`.

 
[source](https://doc.rust-lang.org/src/core/slice/ascii.rs.html#43)
```
pub unsafe fn as_ascii_unchecked(&self) -> &[AsciiChar]
```

🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998))

Converts this slice of bytes into a slice of ASCII characters, without checking whether they’re valid.

 ##### Safety

 Every byte in the slice must be in `0..=127`, or else this is UB.

 
[source](https://doc.rust-lang.org/src/core/slice/ascii.rs.html#57)1.23.0
```
pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool
```

Checks that two slices are an ASCII case-insensitive match.

 Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`, but without allocating and copying temporaries.

 
[source](https://doc.rust-lang.org/src/core/slice/ascii.rs.html#72)1.23.0
```
pub fn make_ascii_uppercase(&mut self)
```

Converts this slice to its ASCII upper case equivalent in-place.

 ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, but non-ASCII letters are unchanged.

 To return a new uppercased value without modifying the existing one, use [`to_ascii_uppercase`](#method.to_ascii_uppercase).

 
[source](https://doc.rust-lang.org/src/core/slice/ascii.rs.html#89)1.23.0
```
pub fn make_ascii_lowercase(&mut self)
```

Converts this slice to its ASCII lower case equivalent in-place.

 ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’, but non-ASCII letters are unchanged.

 To return a new lowercased value without modifying the existing one, use [`to_ascii_lowercase`](#method.to_ascii_lowercase).

 
[source](https://doc.rust-lang.org/src/core/slice/ascii.rs.html#109)1.60.0
```
pub fn escape_ascii(&self) -> EscapeAscii<'_> ⓘ
```

Returns an iterator that produces an escaped version of this slice, treating it as an ASCII string.

 ##### Examples

 
```

let s = b"0\t\r\n'\"\\\x9d";
let escaped = s.escape_ascii().to_string();
assert_eq!(escaped, "0\\t\\r\\n\\'\\\"\\\\\\x9d");
```
 
[source](https://doc.rust-lang.org/src/core/slice/ascii.rs.html#128)
```
pub fn trim_ascii_start(&self) -> &[u8] ⓘ
```

🔬This is a nightly-only experimental API. (`byte_slice_trim_ascii` [#94035](https://github.com/rust-lang/rust/issues/94035))

Returns a byte slice with leading ASCII whitespace bytes removed.

 ‘Whitespace’ refers to the definition used by `u8::is_ascii_whitespace`.

 ##### Examples

 
```
#![feature(byte_slice_trim_ascii)]

assert_eq!(b" \t hello world\n".trim_ascii_start(), b"hello world\n");
assert_eq!(b"  ".trim_ascii_start(), b"");
assert_eq!(b"".trim_ascii_start(), b"");
```
 
[source](https://doc.rust-lang.org/src/core/slice/ascii.rs.html#157)
```
pub fn trim_ascii_end(&self) -> &[u8] ⓘ
```

🔬This is a nightly-only experimental API. (`byte_slice_trim_ascii` [#94035](https://github.com/rust-lang/rust/issues/94035))

Returns a byte slice with trailing ASCII whitespace bytes removed.

 ‘Whitespace’ refers to the definition used by `u8::is_ascii_whitespace`.

 ##### Examples

 
```
#![feature(byte_slice_trim_ascii)]

assert_eq!(b"\r hello world\n ".trim_ascii_end(), b"\r hello world");
assert_eq!(b"  ".trim_ascii_end(), b"");
assert_eq!(b"".trim_ascii_end(), b"");
```
 
[source](https://doc.rust-lang.org/src/core/slice/ascii.rs.html#187)
```
pub fn trim_ascii(&self) -> &[u8] ⓘ
```

🔬This is a nightly-only experimental API. (`byte_slice_trim_ascii` [#94035](https://github.com/rust-lang/rust/issues/94035))

Returns a byte slice with leading and trailing ASCII whitespace bytes removed.

 ‘Whitespace’ refers to the definition used by `u8::is_ascii_whitespace`.

 ##### Examples

 
```
#![feature(byte_slice_trim_ascii)]

assert_eq!(b"\r hello world\n ".trim_ascii(), b"hello world");
assert_eq!(b"  ".trim_ascii(), b"");
assert_eq!(b"".trim_ascii(), b"");
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4599)
```
pub fn sort_floats(&mut self)
```

🔬This is a nightly-only experimental API. (`sort_floats` [#93396](https://github.com/rust-lang/rust/issues/93396))

Sorts the slice of floats.

 This sort is in-place (i.e. does not allocate), *O*(*n* \* log(*n*)) worst-case, and uses the ordering defined by [`f64::total_cmp`](../primitive.f64#method.total_cmp "method f64::total_cmp").

 ##### Current implementation

 This uses the same sorting algorithm as [`sort_unstable_by`](../primitive.slice#method.sort_unstable_by "method slice::sort_unstable_by").

 ##### Examples

 
```
#![feature(sort_floats)]
let mut v = [2.6, -5e-8, f64::NAN, 8.29, f64::INFINITY, -1.0, 0.0, -f64::INFINITY, -0.0];

v.sort_floats();
let sorted = [-f64::INFINITY, -1.0, -5e-8, -0.0, 0.0, 2.6, 8.29, f64::INFINITY, f64::NAN];
assert_eq!(&v[..8], &sorted[..8]);
assert!(v[8].is_nan());
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4495)
```
pub fn flatten(&self) -> &[T]
```

🔬This is a nightly-only experimental API. (`slice_flatten` [#95629](https://github.com/rust-lang/rust/issues/95629))

Takes a `&[[T; N]]`, and flattens it to a `&[T]`.

 ##### Panics

 This panics if the length of the resulting slice would overflow a `usize`.

 This is only possible when flattening a slice of arrays of zero-sized types, and thus tends to be irrelevant in practice. If `size_of::<T>() > 0`, this will never panic.

 ##### Examples

 
```
#![feature(slice_flatten)]

assert_eq!([[1, 2, 3], [4, 5, 6]].flatten(), &[1, 2, 3, 4, 5, 6]);

assert_eq!(
    [[1, 2, 3], [4, 5, 6]].flatten(),
    [[1, 2], [3, 4], [5, 6]].flatten(),
);

let slice_of_empty_arrays: &[[i32; 0]] = &[[], [], [], [], []];
assert!(slice_of_empty_arrays.flatten().is_empty());

let empty_slice_of_arrays: &[[u32; 10]] = &[];
assert!(empty_slice_of_arrays.flatten().is_empty());
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4533)
```
pub fn flatten_mut(&mut self) -> &mut [T]
```

🔬This is a nightly-only experimental API. (`slice_flatten` [#95629](https://github.com/rust-lang/rust/issues/95629))

Takes a `&mut [[T; N]]`, and flattens it to a `&mut [T]`.

 ##### Panics

 This panics if the length of the resulting slice would overflow a `usize`.

 This is only possible when flattening a slice of arrays of zero-sized types, and thus tends to be irrelevant in practice. If `size_of::<T>() > 0`, this will never panic.

 ##### Examples

 
```
#![feature(slice_flatten)]

fn add_5_to_all(slice: &mut [i32]) {
    for i in slice {
        *i += 5;
    }
}

let mut array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
add_5_to_all(array.flatten_mut());
assert_eq!(array, [[6, 7, 8], [9, 10, 11], [12, 13, 14]]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#141)
```
pub fn len(&self) -> usize
```

Returns the number of elements in the slice.

 ##### Examples

 
```
let a = [1, 2, 3];
assert_eq!(a.len(), 3);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#157)
```
pub fn is_empty(&self) -> bool
```

Returns `true` if the slice has a length of 0.

 ##### Examples

 
```
let a = [1, 2, 3];
assert!(!a.is_empty());
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#176)
```
pub fn first(&self) -> Option<&T>
```

Returns the first element of the slice, or `None` if it is empty.

 ##### Examples

 
```
let v = [10, 40, 30];
assert_eq!(Some(&10), v.first());

let w: &[i32] = &[];
assert_eq!(None, w.first());
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#196)
```
pub fn first_mut(&mut self) -> Option<&mut T>
```

Returns a mutable pointer to the first element of the slice, or `None` if it is empty.

 ##### Examples

 
```
let x = &mut [0, 1, 2];

if let Some(first) = x.first_mut() {
    *first = 5;
}
assert_eq!(x, &[5, 1, 2]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#216)1.5.0
```
pub fn split_first(&self) -> Option<(&T, &[T])>
```

Returns the first and all the rest of the elements of the slice, or `None` if it is empty.

 ##### Examples

 
```
let x = &[0, 1, 2];

if let Some((first, elements)) = x.split_first() {
    assert_eq!(first, &0);
    assert_eq!(elements, &[1, 2]);
}
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#238)1.5.0
```
pub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])>
```

Returns the first and all the rest of the elements of the slice, or `None` if it is empty.

 ##### Examples

 
```
let x = &mut [0, 1, 2];

if let Some((first, elements)) = x.split_first_mut() {
    *first = 3;
    elements[0] = 4;
    elements[1] = 5;
}
assert_eq!(x, &[3, 4, 5]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#258)1.5.0
```
pub fn split_last(&self) -> Option<(&T, &[T])>
```

Returns the last and all the rest of the elements of the slice, or `None` if it is empty.

 ##### Examples

 
```
let x = &[0, 1, 2];

if let Some((last, elements)) = x.split_last() {
    assert_eq!(last, &2);
    assert_eq!(elements, &[0, 1]);
}
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#280)1.5.0
```
pub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])>
```

Returns the last and all the rest of the elements of the slice, or `None` if it is empty.

 ##### Examples

 
```
let x = &mut [0, 1, 2];

if let Some((last, elements)) = x.split_last_mut() {
    *last = 3;
    elements[0] = 4;
    elements[1] = 5;
}
assert_eq!(x, &[4, 5, 3]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#299)
```
pub fn last(&self) -> Option<&T>
```

Returns the last element of the slice, or `None` if it is empty.

 ##### Examples

 
```
let v = [10, 40, 30];
assert_eq!(Some(&30), v.last());

let w: &[i32] = &[];
assert_eq!(None, w.last());
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#319)
```
pub fn last_mut(&mut self) -> Option<&mut T>
```

Returns a mutable pointer to the last item in the slice.

 ##### Examples

 
```
let x = &mut [0, 1, 2];

if let Some(last) = x.last_mut() {
    *last = 10;
}
assert_eq!(x, &[0, 1, 10]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#342)
```
pub fn first_chunk<const N: usize>(&self) -> Option<&[T; N]>
```

🔬This is a nightly-only experimental API. (`slice_first_last_chunk` [#111774](https://github.com/rust-lang/rust/issues/111774))

Returns the first `N` elements of the slice, or `None` if it has fewer than `N` elements.

 ##### Examples

 
```
#![feature(slice_first_last_chunk)]

let u = [10, 40, 30];
assert_eq!(Some(&[10, 40]), u.first_chunk::<2>());

let v: &[i32] = &[10];
assert_eq!(None, v.first_chunk::<2>());

let w: &[i32] = &[];
assert_eq!(Some(&[]), w.first_chunk::<0>());
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#371)
```
pub fn first_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>
```

🔬This is a nightly-only experimental API. (`slice_first_last_chunk` [#111774](https://github.com/rust-lang/rust/issues/111774))

Returns a mutable reference to the first `N` elements of the slice, or `None` if it has fewer than `N` elements.

 ##### Examples

 
```
#![feature(slice_first_last_chunk)]

let x = &mut [0, 1, 2];

if let Some(first) = x.first_chunk_mut::<2>() {
    first[0] = 5;
    first[1] = 4;
}
assert_eq!(x, &[5, 4, 2]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#400)
```
pub fn split_first_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])>
```

🔬This is a nightly-only experimental API. (`slice_first_last_chunk` [#111774](https://github.com/rust-lang/rust/issues/111774))

Returns the first `N` elements of the slice and the remainder, or `None` if it has fewer than `N` elements.

 ##### Examples

 
```
#![feature(slice_first_last_chunk)]

let x = &[0, 1, 2];

if let Some((first, elements)) = x.split_first_chunk::<2>() {
    assert_eq!(first, &[0, 1]);
    assert_eq!(elements, &[2]);
}
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#433-435)
```
pub fn split_first_chunk_mut<const N: usize>(
    &mut self
) -> Option<(&mut [T; N], &mut [T])>
```

🔬This is a nightly-only experimental API. (`slice_first_last_chunk` [#111774](https://github.com/rust-lang/rust/issues/111774))

Returns a mutable reference to the first `N` elements of the slice and the remainder, or `None` if it has fewer than `N` elements.

 ##### Examples

 
```
#![feature(slice_first_last_chunk)]

let x = &mut [0, 1, 2];

if let Some((first, elements)) = x.split_first_chunk_mut::<2>() {
    first[0] = 3;
    first[1] = 4;
    elements[0] = 5;
}
assert_eq!(x, &[3, 4, 5]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#467)
```
pub fn split_last_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])>
```

🔬This is a nightly-only experimental API. (`slice_first_last_chunk` [#111774](https://github.com/rust-lang/rust/issues/111774))

Returns the last `N` elements of the slice and the remainder, or `None` if it has fewer than `N` elements.

 ##### Examples

 
```
#![feature(slice_first_last_chunk)]

let x = &[0, 1, 2];

if let Some((last, elements)) = x.split_last_chunk::<2>() {
    assert_eq!(last, &[1, 2]);
    assert_eq!(elements, &[0]);
}
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#499-501)
```
pub fn split_last_chunk_mut<const N: usize>(
    &mut self
) -> Option<(&mut [T; N], &mut [T])>
```

🔬This is a nightly-only experimental API. (`slice_first_last_chunk` [#111774](https://github.com/rust-lang/rust/issues/111774))

Returns the last and all the rest of the elements of the slice, or `None` if it is empty.

 ##### Examples

 
```
#![feature(slice_first_last_chunk)]

let x = &mut [0, 1, 2];

if let Some((last, elements)) = x.split_last_chunk_mut::<2>() {
    last[0] = 3;
    last[1] = 4;
    elements[0] = 5;
}
assert_eq!(x, &[5, 3, 4]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#534)
```
pub fn last_chunk<const N: usize>(&self) -> Option<&[T; N]>
```

🔬This is a nightly-only experimental API. (`slice_first_last_chunk` [#111774](https://github.com/rust-lang/rust/issues/111774))

Returns the last element of the slice, or `None` if it is empty.

 ##### Examples

 
```
#![feature(slice_first_last_chunk)]

let u = [10, 40, 30];
assert_eq!(Some(&[40, 30]), u.last_chunk::<2>());

let v: &[i32] = &[10];
assert_eq!(None, v.last_chunk::<2>());

let w: &[i32] = &[];
assert_eq!(Some(&[]), w.last_chunk::<0>());
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#566)
```
pub fn last_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>
```

🔬This is a nightly-only experimental API. (`slice_first_last_chunk` [#111774](https://github.com/rust-lang/rust/issues/111774))

Returns a mutable pointer to the last item in the slice.

 ##### Examples

 
```
#![feature(slice_first_last_chunk)]

let x = &mut [0, 1, 2];

if let Some(last) = x.last_chunk_mut::<2>() {
    last[0] = 10;
    last[1] = 20;
}
assert_eq!(x, &[0, 10, 20]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#601-603)
```
pub fn get<I>(&self, index: I) -> Option<&<I as SliceIndex<[T]>>::Output>
where
    I: SliceIndex<[T]>,
```

Returns a reference to an element or subslice depending on the type of index.

 * If given a position, returns a reference to the element at that position or `None` if out of bounds.
* If given a range, returns the subslice corresponding to that range, or `None` if out of bounds.

 ##### Examples

 
```
let v = [10, 40, 30];
assert_eq!(Some(&40), v.get(1));
assert_eq!(Some(&[10, 40][..]), v.get(0..2));
assert_eq!(None, v.get(3));
assert_eq!(None, v.get(0..4));
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#626-628)
```
pub fn get_mut<I>(
    &mut self,
    index: I
) -> Option<&mut <I as SliceIndex<[T]>>::Output>
where
    I: SliceIndex<[T]>,
```

Returns a mutable reference to an element or subslice depending on the type of index (see [`get`](../primitive.slice#method.get "method slice::get")) or `None` if the index is out of bounds.

 ##### Examples

 
```
let x = &mut [0, 1, 2];

if let Some(elem) = x.get_mut(1) {
    *elem = 42;
}
assert_eq!(x, &[0, 42, 2]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#658-660)
```
pub unsafe fn get_unchecked<I>(
    &self,
    index: I
) -> &<I as SliceIndex<[T]>>::Output
where
    I: SliceIndex<[T]>,
```

Returns a reference to an element or subslice, without doing bounds checking.

 For a safe alternative see [`get`](../primitive.slice#method.get "method slice::get").

 ##### Safety

 Calling this method with an out-of-bounds index is *[undefined behavior](../../reference/behavior-considered-undefined)* even if the resulting reference is not used.

 ##### Examples

 
```
let x = &[1, 2, 4];

unsafe {
    assert_eq!(x.get_unchecked(1), &2);
}
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#695-697)
```
pub unsafe fn get_unchecked_mut<I>(
    &mut self,
    index: I
) -> &mut <I as SliceIndex<[T]>>::Output
where
    I: SliceIndex<[T]>,
```

Returns a mutable reference to an element or subslice, without doing bounds checking.

 For a safe alternative see [`get_mut`](../primitive.slice#method.get_mut "method slice::get_mut").

 ##### Safety

 Calling this method with an out-of-bounds index is *[undefined behavior](../../reference/behavior-considered-undefined)* even if the resulting reference is not used.

 ##### Examples

 
```
let x = &mut [1, 2, 4];

unsafe {
    let elem = x.get_unchecked_mut(1);
    *elem = 13;
}
assert_eq!(x, &[1, 13, 4]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#735)
```
pub fn as_ptr(&self) -> *const T
```

Returns a raw pointer to the slice’s buffer.

 The caller must ensure that the slice outlives the pointer this function returns, or else it will end up pointing to garbage.

 The caller must also ensure that the memory the pointer (non-transitively) points to is never written to (except inside an `UnsafeCell`) using this pointer or any pointer derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`](../primitive.slice#method.as_mut_ptr "method slice::as_mut_ptr").

 Modifying the container referenced by this slice may cause its buffer to be reallocated, which would also make any pointers to it invalid.

 ##### Examples

 
```
let x = &[1, 2, 4];
let x_ptr = x.as_ptr();

unsafe {
    for i in 0..x.len() {
        assert_eq!(x.get_unchecked(i), &*x_ptr.add(i));
    }
}
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#765)
```
pub fn as_mut_ptr(&mut self) -> *mut T
```

Returns an unsafe mutable pointer to the slice’s buffer.

 The caller must ensure that the slice outlives the pointer this function returns, or else it will end up pointing to garbage.

 Modifying the container referenced by this slice may cause its buffer to be reallocated, which would also make any pointers to it invalid.

 ##### Examples

 
```
let x = &mut [1, 2, 4];
let x_ptr = x.as_mut_ptr();

unsafe {
    for i in 0..x.len() {
        *x_ptr.add(i) += 2;
    }
}
assert_eq!(x, &[3, 4, 6]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#801)1.48.0
```
pub fn as_ptr_range(&self) -> Range<*const T> ⓘ
```

Returns the two raw pointers spanning the slice.

 The returned range is half-open, which means that the end pointer points *one past* the last element of the slice. This way, an empty slice is represented by two equal pointers, and the difference between the two pointers represents the size of the slice.

 See [`as_ptr`](../primitive.slice#method.as_ptr "method slice::as_ptr") for warnings on using these pointers. The end pointer requires extra caution, as it does not point to a valid element in the slice.

 This function is useful for interacting with foreign interfaces which use two pointers to refer to a range of elements in memory, as is common in C++.

 It can also be useful to check if a pointer to an element refers to an element of this slice:

 
```
let a = [1, 2, 3];
let x = &a[1] as *const _;
let y = &5 as *const _;

assert!(a.as_ptr_range().contains(&x));
assert!(!a.as_ptr_range().contains(&y));
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#845)1.48.0
```
pub fn as_mut_ptr_range(&mut self) -> Range<*mut T> ⓘ
```

Returns the two unsafe mutable pointers spanning the slice.

 The returned range is half-open, which means that the end pointer points *one past* the last element of the slice. This way, an empty slice is represented by two equal pointers, and the difference between the two pointers represents the size of the slice.

 See [`as_mut_ptr`](../primitive.slice#method.as_mut_ptr "method slice::as_mut_ptr") for warnings on using these pointers. The end pointer requires extra caution, as it does not point to a valid element in the slice.

 This function is useful for interacting with foreign interfaces which use two pointers to refer to a range of elements in memory, as is common in C++.

 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#874)
```
pub fn swap(&mut self, a: usize, b: usize)
```

Swaps two elements in the slice.

 ##### Arguments

 * a - The index of the first element
* b - The index of the second element

 ##### Panics

 Panics if `a` or `b` are out of bounds.

 ##### Examples

 
```
let mut v = ["a", "b", "c", "d", "e"];
v.swap(2, 4);
assert!(v == ["a", "b", "e", "d", "c"]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#917)
```
pub unsafe fn swap_unchecked(&mut self, a: usize, b: usize)
```

🔬This is a nightly-only experimental API. (`slice_swap_unchecked` [#88539](https://github.com/rust-lang/rust/issues/88539))

Swaps two elements in the slice, without doing bounds checking.

 For a safe alternative see [`swap`](../primitive.slice#method.swap "method slice::swap").

 ##### Arguments

 * a - The index of the first element
* b - The index of the second element

 ##### Safety

 Calling this method with an out-of-bounds index is *[undefined behavior](../../reference/behavior-considered-undefined)*. The caller has to ensure that `a < self.len()` and `b < self.len()`.

 ##### Examples

 
```
#![feature(slice_swap_unchecked)]

let mut v = ["a", "b", "c", "d"];
// SAFETY: we know that 1 and 3 are both indices of the slice
unsafe { v.swap_unchecked(1, 3) };
assert!(v == ["a", "d", "c", "b"]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#941)
```
pub fn reverse(&mut self)
```

Reverses the order of elements in the slice, in place.

 ##### Examples

 
```
let mut v = [1, 2, 3];
v.reverse();
assert!(v == [3, 2, 1]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#999)
```
pub fn iter(&self) -> Iter<'_, T> ⓘ
```

Returns an iterator over the slice.

 The iterator yields all items from start to end.

 ##### Examples

 
```
let x = &[1, 2, 4];
let mut iterator = x.iter();

assert_eq!(iterator.next(), Some(&1));
assert_eq!(iterator.next(), Some(&2));
assert_eq!(iterator.next(), Some(&4));
assert_eq!(iterator.next(), None);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1018)
```
pub fn iter_mut(&mut self) -> IterMut<'_, T> ⓘ
```

Returns an iterator that allows modifying each value.

 The iterator yields all items from start to end.

 ##### Examples

 
```
let x = &mut [1, 2, 4];
for elem in x.iter_mut() {
    *elem += 2;
}
assert_eq!(x, &[3, 4, 6]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1067)
```
pub fn windows(&self, size: usize) -> Windows<'_, T> ⓘ
```

Returns an iterator over all contiguous windows of length `size`. The windows overlap. If the slice is shorter than `size`, the iterator returns no values.

 ##### Panics

 Panics if `size` is 0.

 ##### Examples

 
```
let slice = ['r', 'u', 's', 't'];
let mut iter = slice.windows(2);
assert_eq!(iter.next().unwrap(), &['r', 'u']);
assert_eq!(iter.next().unwrap(), &['u', 's']);
assert_eq!(iter.next().unwrap(), &['s', 't']);
assert!(iter.next().is_none());
```
 If the slice is shorter than `size`:

 
```
let slice = ['f', 'o', 'o'];
let mut iter = slice.windows(4);
assert!(iter.next().is_none());
```
 There’s no `windows_mut`, as that existing would let safe code violate the “only one `&mut` at a time to the same thing” rule. However, you can sometimes use [`Cell::as_slice_of_cells`](../cell/struct.cell#method.as_slice_of_cells "method std::cell::Cell::as_slice_of_cells") in conjunction with `windows` to accomplish something similar:

 
```
use std::cell::Cell;

let mut array = ['R', 'u', 's', 't', ' ', '2', '0', '1', '5'];
let slice = &mut array[..];
let slice_of_cells: &[Cell<char>] = Cell::from_mut(slice).as_slice_of_cells();
for w in slice_of_cells.windows(3) {
    Cell::swap(&w[0], &w[2]);
}
assert_eq!(array, ['s', 't', ' ', '2', '0', '1', '5', 'u', 'R']);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1102)
```
pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T> ⓘ
```

Returns an iterator over `chunk_size` elements of the slice at a time, starting at the beginning of the slice.

 The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the slice, then the last chunk will not have length `chunk_size`.

 See [`chunks_exact`](../primitive.slice#method.chunks_exact "method slice::chunks_exact") for a variant of this iterator that returns chunks of always exactly `chunk_size` elements, and [`rchunks`](../primitive.slice#method.rchunks "method slice::rchunks") for the same iterator but starting at the end of the slice.

 ##### Panics

 Panics if `chunk_size` is 0.

 ##### Examples

 
```
let slice = ['l', 'o', 'r', 'e', 'm'];
let mut iter = slice.chunks(2);
assert_eq!(iter.next().unwrap(), &['l', 'o']);
assert_eq!(iter.next().unwrap(), &['r', 'e']);
assert_eq!(iter.next().unwrap(), &['m']);
assert!(iter.next().is_none());
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1141)
```
pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, T> ⓘ
```

Returns an iterator over `chunk_size` elements of the slice at a time, starting at the beginning of the slice.

 The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the length of the slice, then the last chunk will not have length `chunk_size`.

 See [`chunks_exact_mut`](../primitive.slice#method.chunks_exact_mut "method slice::chunks_exact_mut") for a variant of this iterator that returns chunks of always exactly `chunk_size` elements, and [`rchunks_mut`](../primitive.slice#method.rchunks_mut "method slice::rchunks_mut") for the same iterator but starting at the end of the slice.

 ##### Panics

 Panics if `chunk_size` is 0.

 ##### Examples

 
```
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;

for chunk in v.chunks_mut(2) {
    for elem in chunk.iter_mut() {
        *elem += count;
    }
    count += 1;
}
assert_eq!(v, &[1, 1, 2, 2, 3]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1179)1.31.0
```
pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T> ⓘ
```

Returns an iterator over `chunk_size` elements of the slice at a time, starting at the beginning of the slice.

 The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved from the `remainder` function of the iterator.

 Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the resulting code better than in the case of [`chunks`](../primitive.slice#method.chunks "method slice::chunks").

 See [`chunks`](../primitive.slice#method.chunks "method slice::chunks") for a variant of this iterator that also returns the remainder as a smaller chunk, and [`rchunks_exact`](../primitive.slice#method.rchunks_exact "method slice::rchunks_exact") for the same iterator but starting at the end of the slice.

 ##### Panics

 Panics if `chunk_size` is 0.

 ##### Examples

 
```
let slice = ['l', 'o', 'r', 'e', 'm'];
let mut iter = slice.chunks_exact(2);
assert_eq!(iter.next().unwrap(), &['l', 'o']);
assert_eq!(iter.next().unwrap(), &['r', 'e']);
assert!(iter.next().is_none());
assert_eq!(iter.remainder(), &['m']);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1222)1.31.0
```
pub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, T> ⓘ
```

Returns an iterator over `chunk_size` elements of the slice at a time, starting at the beginning of the slice.

 The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved from the `into_remainder` function of the iterator.

 Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the resulting code better than in the case of [`chunks_mut`](../primitive.slice#method.chunks_mut "method slice::chunks_mut").

 See [`chunks_mut`](../primitive.slice#method.chunks_mut "method slice::chunks_mut") for a variant of this iterator that also returns the remainder as a smaller chunk, and [`rchunks_exact_mut`](../primitive.slice#method.rchunks_exact_mut "method slice::rchunks_exact_mut") for the same iterator but starting at the end of the slice.

 ##### Panics

 Panics if `chunk_size` is 0.

 ##### Examples

 
```
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;

for chunk in v.chunks_exact_mut(2) {
    for elem in chunk.iter_mut() {
        *elem += count;
    }
    count += 1;
}
assert_eq!(v, &[1, 1, 2, 2, 0]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1257)
```
pub unsafe fn as_chunks_unchecked<const N: usize>(&self) -> &[[T; N]]
```

🔬This is a nightly-only experimental API. (`slice_as_chunks` [#74985](https://github.com/rust-lang/rust/issues/74985))

Splits the slice into a slice of `N`-element arrays, assuming that there’s no remainder.

 ##### Safety

 This may only be called when

 * The slice splits exactly into `N`-element chunks (aka `self.len() % N == 0`).
* `N != 0`.

 ##### Examples

 
```
#![feature(slice_as_chunks)]
let slice: &[char] = &['l', 'o', 'r', 'e', 'm', '!'];
let chunks: &[[char; 1]] =
    // SAFETY: 1-element chunks never have remainder
    unsafe { slice.as_chunks_unchecked() };
assert_eq!(chunks, &[['l'], ['o'], ['r'], ['e'], ['m'], ['!']]);
let chunks: &[[char; 3]] =
    // SAFETY: The slice length (6) is a multiple of 3
    unsafe { slice.as_chunks_unchecked() };
assert_eq!(chunks, &[['l', 'o', 'r'], ['e', 'm', '!']]);

// These would be unsound:
// let chunks: &[[_; 5]] = slice.as_chunks_unchecked() // The slice length is not a multiple of 5
// let chunks: &[[_; 0]] = slice.as_chunks_unchecked() // Zero-length chunks are never allowed
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1305)
```
pub fn as_chunks<const N: usize>(&self) -> (&[[T; N]], &[T])
```

🔬This is a nightly-only experimental API. (`slice_as_chunks` [#74985](https://github.com/rust-lang/rust/issues/74985))

Splits the slice into a slice of `N`-element arrays, starting at the beginning of the slice, and a remainder slice with length strictly less than `N`.

 ##### Panics

 Panics if `N` is 0. This check will most probably get changed to a compile time error before this method gets stabilized.

 ##### Examples

 
```
#![feature(slice_as_chunks)]
let slice = ['l', 'o', 'r', 'e', 'm'];
let (chunks, remainder) = slice.as_chunks();
assert_eq!(chunks, &[['l', 'o'], ['r', 'e']]);
assert_eq!(remainder, &['m']);
```
 If you expect the slice to be an exact multiple, you can combine `let`-`else` with an empty slice pattern:

 
```
#![feature(slice_as_chunks)]
let slice = ['R', 'u', 's', 't'];
let (chunks, []) = slice.as_chunks::<2>() else {
    panic!("slice didn't have even length")
};
assert_eq!(chunks, &[['R', 'u'], ['s', 't']]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1337)
```
pub fn as_rchunks<const N: usize>(&self) -> (&[T], &[[T; N]])
```

🔬This is a nightly-only experimental API. (`slice_as_chunks` [#74985](https://github.com/rust-lang/rust/issues/74985))

Splits the slice into a slice of `N`-element arrays, starting at the end of the slice, and a remainder slice with length strictly less than `N`.

 ##### Panics

 Panics if `N` is 0. This check will most probably get changed to a compile time error before this method gets stabilized.

 ##### Examples

 
```
#![feature(slice_as_chunks)]
let slice = ['l', 'o', 'r', 'e', 'm'];
let (remainder, chunks) = slice.as_rchunks();
assert_eq!(remainder, &['l']);
assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1377)
```
pub fn array_chunks<const N: usize>(&self) -> ArrayChunks<'_, T, N> ⓘ
```

🔬This is a nightly-only experimental API. (`array_chunks` [#74985](https://github.com/rust-lang/rust/issues/74985))

Returns an iterator over `N` elements of the slice at a time, starting at the beginning of the slice.

 The chunks are array references and do not overlap. If `N` does not divide the length of the slice, then the last up to `N-1` elements will be omitted and can be retrieved from the `remainder` function of the iterator.

 This method is the const generic equivalent of [`chunks_exact`](../primitive.slice#method.chunks_exact "method slice::chunks_exact").

 ##### Panics

 Panics if `N` is 0. This check will most probably get changed to a compile time error before this method gets stabilized.

 ##### Examples

 
```
#![feature(array_chunks)]
let slice = ['l', 'o', 'r', 'e', 'm'];
let mut iter = slice.array_chunks();
assert_eq!(iter.next().unwrap(), &['l', 'o']);
assert_eq!(iter.next().unwrap(), &['r', 'e']);
assert!(iter.next().is_none());
assert_eq!(iter.remainder(), &['m']);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1414)
```
pub unsafe fn as_chunks_unchecked_mut<const N: usize>(
    &mut self
) -> &mut [[T; N]]
```

🔬This is a nightly-only experimental API. (`slice_as_chunks` [#74985](https://github.com/rust-lang/rust/issues/74985))

Splits the slice into a slice of `N`-element arrays, assuming that there’s no remainder.

 ##### Safety

 This may only be called when

 * The slice splits exactly into `N`-element chunks (aka `self.len() % N == 0`).
* `N != 0`.

 ##### Examples

 
```
#![feature(slice_as_chunks)]
let slice: &mut [char] = &mut ['l', 'o', 'r', 'e', 'm', '!'];
let chunks: &mut [[char; 1]] =
    // SAFETY: 1-element chunks never have remainder
    unsafe { slice.as_chunks_unchecked_mut() };
chunks[0] = ['L'];
assert_eq!(chunks, &[['L'], ['o'], ['r'], ['e'], ['m'], ['!']]);
let chunks: &mut [[char; 3]] =
    // SAFETY: The slice length (6) is a multiple of 3
    unsafe { slice.as_chunks_unchecked_mut() };
chunks[1] = ['a', 'x', '?'];
assert_eq!(slice, &['L', 'o', 'r', 'a', 'x', '?']);

// These would be unsound:
// let chunks: &[[_; 5]] = slice.as_chunks_unchecked_mut() // The slice length is not a multiple of 5
// let chunks: &[[_; 0]] = slice.as_chunks_unchecked_mut() // Zero-length chunks are never allowed
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1457)
```
pub fn as_chunks_mut<const N: usize>(&mut self) -> (&mut [[T; N]], &mut [T])
```

🔬This is a nightly-only experimental API. (`slice_as_chunks` [#74985](https://github.com/rust-lang/rust/issues/74985))

Splits the slice into a slice of `N`-element arrays, starting at the beginning of the slice, and a remainder slice with length strictly less than `N`.

 ##### Panics

 Panics if `N` is 0. This check will most probably get changed to a compile time error before this method gets stabilized.

 ##### Examples

 
```
#![feature(slice_as_chunks)]
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;

let (chunks, remainder) = v.as_chunks_mut();
remainder[0] = 9;
for chunk in chunks {
    *chunk = [count; 2];
    count += 1;
}
assert_eq!(v, &[1, 1, 2, 2, 9]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1495)
```
pub fn as_rchunks_mut<const N: usize>(&mut self) -> (&mut [T], &mut [[T; N]])
```

🔬This is a nightly-only experimental API. (`slice_as_chunks` [#74985](https://github.com/rust-lang/rust/issues/74985))

Splits the slice into a slice of `N`-element arrays, starting at the end of the slice, and a remainder slice with length strictly less than `N`.

 ##### Panics

 Panics if `N` is 0. This check will most probably get changed to a compile time error before this method gets stabilized.

 ##### Examples

 
```
#![feature(slice_as_chunks)]
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;

let (remainder, chunks) = v.as_rchunks_mut();
remainder[0] = 9;
for chunk in chunks {
    *chunk = [count; 2];
    count += 1;
}
assert_eq!(v, &[9, 1, 1, 2, 2]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1537)
```
pub fn array_chunks_mut<const N: usize>(&mut self) -> ArrayChunksMut<'_, T, N> ⓘ
```

🔬This is a nightly-only experimental API. (`array_chunks` [#74985](https://github.com/rust-lang/rust/issues/74985))

Returns an iterator over `N` elements of the slice at a time, starting at the beginning of the slice.

 The chunks are mutable array references and do not overlap. If `N` does not divide the length of the slice, then the last up to `N-1` elements will be omitted and can be retrieved from the `into_remainder` function of the iterator.

 This method is the const generic equivalent of [`chunks_exact_mut`](../primitive.slice#method.chunks_exact_mut "method slice::chunks_exact_mut").

 ##### Panics

 Panics if `N` is 0. This check will most probably get changed to a compile time error before this method gets stabilized.

 ##### Examples

 
```
#![feature(array_chunks)]
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;

for chunk in v.array_chunks_mut() {
    *chunk = [count; 2];
    count += 1;
}
assert_eq!(v, &[1, 1, 2, 2, 0]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1570)
```
pub fn array_windows<const N: usize>(&self) -> ArrayWindows<'_, T, N> ⓘ
```

🔬This is a nightly-only experimental API. (`array_windows` [#75027](https://github.com/rust-lang/rust/issues/75027))

Returns an iterator over overlapping windows of `N` elements of a slice, starting at the beginning of the slice.

 This is the const generic equivalent of [`windows`](../primitive.slice#method.windows "method slice::windows").

 If `N` is greater than the size of the slice, it will return no windows.

 ##### Panics

 Panics if `N` is 0. This check will most probably get changed to a compile time error before this method gets stabilized.

 ##### Examples

 
```
#![feature(array_windows)]
let slice = [0, 1, 2, 3];
let mut iter = slice.array_windows();
assert_eq!(iter.next().unwrap(), &[0, 1]);
assert_eq!(iter.next().unwrap(), &[1, 2]);
assert_eq!(iter.next().unwrap(), &[2, 3]);
assert!(iter.next().is_none());
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1605)1.31.0
```
pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T> ⓘ
```

Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end of the slice.

 The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the slice, then the last chunk will not have length `chunk_size`.

 See [`rchunks_exact`](../primitive.slice#method.rchunks_exact "method slice::rchunks_exact") for a variant of this iterator that returns chunks of always exactly `chunk_size` elements, and [`chunks`](../primitive.slice#method.chunks "method slice::chunks") for the same iterator but starting at the beginning of the slice.

 ##### Panics

 Panics if `chunk_size` is 0.

 ##### Examples

 
```
let slice = ['l', 'o', 'r', 'e', 'm'];
let mut iter = slice.rchunks(2);
assert_eq!(iter.next().unwrap(), &['e', 'm']);
assert_eq!(iter.next().unwrap(), &['o', 'r']);
assert_eq!(iter.next().unwrap(), &['l']);
assert!(iter.next().is_none());
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1644)1.31.0
```
pub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, T> ⓘ
```

Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end of the slice.

 The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the length of the slice, then the last chunk will not have length `chunk_size`.

 See [`rchunks_exact_mut`](../primitive.slice#method.rchunks_exact_mut "method slice::rchunks_exact_mut") for a variant of this iterator that returns chunks of always exactly `chunk_size` elements, and [`chunks_mut`](../primitive.slice#method.chunks_mut "method slice::chunks_mut") for the same iterator but starting at the beginning of the slice.

 ##### Panics

 Panics if `chunk_size` is 0.

 ##### Examples

 
```
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;

for chunk in v.rchunks_mut(2) {
    for elem in chunk.iter_mut() {
        *elem += count;
    }
    count += 1;
}
assert_eq!(v, &[3, 2, 2, 1, 1]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1684)1.31.0
```
pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T> ⓘ
```

Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end of the slice.

 The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved from the `remainder` function of the iterator.

 Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the resulting code better than in the case of [`rchunks`](../primitive.slice#method.rchunks "method slice::rchunks").

 See [`rchunks`](../primitive.slice#method.rchunks "method slice::rchunks") for a variant of this iterator that also returns the remainder as a smaller chunk, and [`chunks_exact`](../primitive.slice#method.chunks_exact "method slice::chunks_exact") for the same iterator but starting at the beginning of the slice.

 ##### Panics

 Panics if `chunk_size` is 0.

 ##### Examples

 
```
let slice = ['l', 'o', 'r', 'e', 'm'];
let mut iter = slice.rchunks_exact(2);
assert_eq!(iter.next().unwrap(), &['e', 'm']);
assert_eq!(iter.next().unwrap(), &['o', 'r']);
assert!(iter.next().is_none());
assert_eq!(iter.remainder(), &['l']);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1728)1.31.0
```
pub fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, T> ⓘ
```

Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end of the slice.

 The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved from the `into_remainder` function of the iterator.

 Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the resulting code better than in the case of [`chunks_mut`](../primitive.slice#method.chunks_mut "method slice::chunks_mut").

 See [`rchunks_mut`](../primitive.slice#method.rchunks_mut "method slice::rchunks_mut") for a variant of this iterator that also returns the remainder as a smaller chunk, and [`chunks_exact_mut`](../primitive.slice#method.chunks_exact_mut "method slice::chunks_exact_mut") for the same iterator but starting at the beginning of the slice.

 ##### Panics

 Panics if `chunk_size` is 0.

 ##### Examples

 
```
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;

for chunk in v.rchunks_exact_mut(2) {
    for elem in chunk.iter_mut() {
        *elem += count;
    }
    count += 1;
}
assert_eq!(v, &[0, 2, 2, 1, 1]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1771-1773)
```
pub fn group_by<F>(&self, pred: F) -> GroupBy<'_, T, F> ⓘ
where
    F: FnMut(&T, &T) -> bool,
```

🔬This is a nightly-only experimental API. (`slice_group_by` [#80552](https://github.com/rust-lang/rust/issues/80552))

Returns an iterator over the slice producing non-overlapping runs of elements using the predicate to separate them.

 The predicate is called on two elements following themselves, it means the predicate is called on `slice[0]` and `slice[1]` then on `slice[1]` and `slice[2]` and so on.

 ##### Examples

 
```
#![feature(slice_group_by)]

let slice = &[1, 1, 1, 3, 3, 2, 2, 2];

let mut iter = slice.group_by(|a, b| a == b);

assert_eq!(iter.next(), Some(&[1, 1, 1][..]));
assert_eq!(iter.next(), Some(&[3, 3][..]));
assert_eq!(iter.next(), Some(&[2, 2, 2][..]));
assert_eq!(iter.next(), None);
```
 This method can be used to extract the sorted subslices:

 
```
#![feature(slice_group_by)]

let slice = &[1, 1, 2, 3, 2, 3, 2, 3, 4];

let mut iter = slice.group_by(|a, b| a <= b);

assert_eq!(iter.next(), Some(&[1, 1, 2, 3][..]));
assert_eq!(iter.next(), Some(&[2, 3][..]));
assert_eq!(iter.next(), Some(&[2, 3, 4][..]));
assert_eq!(iter.next(), None);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1816-1818)
```
pub fn group_by_mut<F>(&mut self, pred: F) -> GroupByMut<'_, T, F> ⓘ
where
    F: FnMut(&T, &T) -> bool,
```

🔬This is a nightly-only experimental API. (`slice_group_by` [#80552](https://github.com/rust-lang/rust/issues/80552))

Returns an iterator over the slice producing non-overlapping mutable runs of elements using the predicate to separate them.

 The predicate is called on two elements following themselves, it means the predicate is called on `slice[0]` and `slice[1]` then on `slice[1]` and `slice[2]` and so on.

 ##### Examples

 
```
#![feature(slice_group_by)]

let slice = &mut [1, 1, 1, 3, 3, 2, 2, 2];

let mut iter = slice.group_by_mut(|a, b| a == b);

assert_eq!(iter.next(), Some(&mut [1, 1, 1][..]));
assert_eq!(iter.next(), Some(&mut [3, 3][..]));
assert_eq!(iter.next(), Some(&mut [2, 2, 2][..]));
assert_eq!(iter.next(), None);
```
 This method can be used to extract the sorted subslices:

 
```
#![feature(slice_group_by)]

let slice = &mut [1, 1, 2, 3, 2, 3, 2, 3, 4];

let mut iter = slice.group_by_mut(|a, b| a <= b);

assert_eq!(iter.next(), Some(&mut [1, 1, 2, 3][..]));
assert_eq!(iter.next(), Some(&mut [2, 3][..]));
assert_eq!(iter.next(), Some(&mut [2, 3, 4][..]));
assert_eq!(iter.next(), None);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1862)
```
pub fn split_at(&self, mid: usize) -> (&[T], &[T])
```

Divides one slice into two at an index.

 The first will contain all indices from `[0, mid)` (excluding the index `mid` itself) and the second will contain all indices from `[mid, len)` (excluding the index `len` itself).

 ##### Panics

 Panics if `mid > len`.

 ##### Examples

 
```
let v = [1, 2, 3, 4, 5, 6];

{
   let (left, right) = v.split_at(0);
   assert_eq!(left, []);
   assert_eq!(right, [1, 2, 3, 4, 5, 6]);
}

{
    let (left, right) = v.split_at(2);
    assert_eq!(left, [1, 2]);
    assert_eq!(right, [3, 4, 5, 6]);
}

{
    let (left, right) = v.split_at(6);
    assert_eq!(left, [1, 2, 3, 4, 5, 6]);
    assert_eq!(right, []);
}
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1895)
```
pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T])
```

Divides one mutable slice into two at an index.

 The first will contain all indices from `[0, mid)` (excluding the index `mid` itself) and the second will contain all indices from `[mid, len)` (excluding the index `len` itself).

 ##### Panics

 Panics if `mid > len`.

 ##### Examples

 
```
let mut v = [1, 0, 3, 0, 5, 6];
let (left, right) = v.split_at_mut(2);
assert_eq!(left, [1, 0]);
assert_eq!(right, [3, 0, 5, 6]);
left[1] = 2;
right[1] = 4;
assert_eq!(v, [1, 2, 3, 4, 5, 6]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1948)
```
pub unsafe fn split_at_unchecked(&self, mid: usize) -> (&[T], &[T])
```

🔬This is a nightly-only experimental API. (`slice_split_at_unchecked` [#76014](https://github.com/rust-lang/rust/issues/76014))

Divides one slice into two at an index, without doing bounds checking.

 The first will contain all indices from `[0, mid)` (excluding the index `mid` itself) and the second will contain all indices from `[mid, len)` (excluding the index `len` itself).

 For a safe alternative see [`split_at`](../primitive.slice#method.split_at "method slice::split_at").

 ##### Safety

 Calling this method with an out-of-bounds index is *[undefined behavior](../../reference/behavior-considered-undefined)* even if the resulting reference is not used. The caller has to ensure that `0 <= mid <= self.len()`.

 ##### Examples

 
```
#![feature(slice_split_at_unchecked)]

let v = [1, 2, 3, 4, 5, 6];

unsafe {
   let (left, right) = v.split_at_unchecked(0);
   assert_eq!(left, []);
   assert_eq!(right, [1, 2, 3, 4, 5, 6]);
}

unsafe {
    let (left, right) = v.split_at_unchecked(2);
    assert_eq!(left, [1, 2]);
    assert_eq!(right, [3, 4, 5, 6]);
}

unsafe {
    let (left, right) = v.split_at_unchecked(6);
    assert_eq!(left, [1, 2, 3, 4, 5, 6]);
    assert_eq!(right, []);
}
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2003)
```
pub unsafe fn split_at_mut_unchecked(
    &mut self,
    mid: usize
) -> (&mut [T], &mut [T])
```

🔬This is a nightly-only experimental API. (`slice_split_at_unchecked` [#76014](https://github.com/rust-lang/rust/issues/76014))

Divides one mutable slice into two at an index, without doing bounds checking.

 The first will contain all indices from `[0, mid)` (excluding the index `mid` itself) and the second will contain all indices from `[mid, len)` (excluding the index `len` itself).

 For a safe alternative see [`split_at_mut`](../primitive.slice#method.split_at_mut "method slice::split_at_mut").

 ##### Safety

 Calling this method with an out-of-bounds index is *[undefined behavior](../../reference/behavior-considered-undefined)* even if the resulting reference is not used. The caller has to ensure that `0 <= mid <= self.len()`.

 ##### Examples

 
```
#![feature(slice_split_at_unchecked)]

let mut v = [1, 0, 3, 0, 5, 6];
// scoped to restrict the lifetime of the borrows
unsafe {
    let (left, right) = v.split_at_mut_unchecked(2);
    assert_eq!(left, [1, 0]);
    assert_eq!(right, [3, 0, 5, 6]);
    left[1] = 2;
    right[1] = 4;
}
assert_eq!(v, [1, 2, 3, 4, 5, 6]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2059)
```
pub fn split_array_ref<const N: usize>(&self) -> (&[T; N], &[T])
```

🔬This is a nightly-only experimental API. (`split_array` [#90091](https://github.com/rust-lang/rust/issues/90091))

Divides one slice into an array and a remainder slice at an index.

 The array will contain all indices from `[0, N)` (excluding the index `N` itself) and the slice will contain all indices from `[N, len)` (excluding the index `len` itself).

 ##### Panics

 Panics if `N > len`.

 ##### Examples

 
```
#![feature(split_array)]

let v = &[1, 2, 3, 4, 5, 6][..];

{
   let (left, right) = v.split_array_ref::<0>();
   assert_eq!(left, &[]);
   assert_eq!(right, [1, 2, 3, 4, 5, 6]);
}

{
    let (left, right) = v.split_array_ref::<2>();
    assert_eq!(left, &[1, 2]);
    assert_eq!(right, [3, 4, 5, 6]);
}

{
    let (left, right) = v.split_array_ref::<6>();
    assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
    assert_eq!(right, []);
}
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2092)
```
pub fn split_array_mut<const N: usize>(&mut self) -> (&mut [T; N], &mut [T])
```

🔬This is a nightly-only experimental API. (`split_array` [#90091](https://github.com/rust-lang/rust/issues/90091))

Divides one mutable slice into an array and a remainder slice at an index.

 The array will contain all indices from `[0, N)` (excluding the index `N` itself) and the slice will contain all indices from `[N, len)` (excluding the index `len` itself).

 ##### Panics

 Panics if `N > len`.

 ##### Examples

 
```
#![feature(split_array)]

let mut v = &mut [1, 0, 3, 0, 5, 6][..];
let (left, right) = v.split_array_mut::<2>();
assert_eq!(left, &mut [1, 0]);
assert_eq!(right, [3, 0, 5, 6]);
left[1] = 2;
right[1] = 4;
assert_eq!(v, [1, 2, 3, 4, 5, 6]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2137)
```
pub fn rsplit_array_ref<const N: usize>(&self) -> (&[T], &[T; N])
```

🔬This is a nightly-only experimental API. (`split_array` [#90091](https://github.com/rust-lang/rust/issues/90091))

Divides one slice into an array and a remainder slice at an index from the end.

 The slice will contain all indices from `[0, len - N)` (excluding the index `len - N` itself) and the array will contain all indices from `[len - N, len)` (excluding the index `len` itself).

 ##### Panics

 Panics if `N > len`.

 ##### Examples

 
```
#![feature(split_array)]

let v = &[1, 2, 3, 4, 5, 6][..];

{
   let (left, right) = v.rsplit_array_ref::<0>();
   assert_eq!(left, [1, 2, 3, 4, 5, 6]);
   assert_eq!(right, &[]);
}

{
    let (left, right) = v.rsplit_array_ref::<2>();
    assert_eq!(left, [1, 2, 3, 4]);
    assert_eq!(right, &[5, 6]);
}

{
    let (left, right) = v.rsplit_array_ref::<6>();
    assert_eq!(left, []);
    assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
}
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2171)
```
pub fn rsplit_array_mut<const N: usize>(&mut self) -> (&mut [T], &mut [T; N])
```

🔬This is a nightly-only experimental API. (`split_array` [#90091](https://github.com/rust-lang/rust/issues/90091))

Divides one mutable slice into an array and a remainder slice at an index from the end.

 The slice will contain all indices from `[0, len - N)` (excluding the index `N` itself) and the array will contain all indices from `[len - N, len)` (excluding the index `len` itself).

 ##### Panics

 Panics if `N > len`.

 ##### Examples

 
```
#![feature(split_array)]

let mut v = &mut [1, 0, 3, 0, 5, 6][..];
let (left, right) = v.rsplit_array_mut::<4>();
assert_eq!(left, [1, 0]);
assert_eq!(right, &mut [3, 0, 5, 6]);
left[1] = 2;
right[1] = 4;
assert_eq!(v, [1, 2, 3, 4, 5, 6]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2220-2222)
```
pub fn split<F>(&self, pred: F) -> Split<'_, T, F> ⓘ
where
    F: FnMut(&T) -> bool,
```

Returns an iterator over subslices separated by elements that match `pred`. The matched element is not contained in the subslices.

 ##### Examples

 
```
let slice = [10, 40, 33, 20];
let mut iter = slice.split(|num| num % 3 == 0);

assert_eq!(iter.next().unwrap(), &[10, 40]);
assert_eq!(iter.next().unwrap(), &[20]);
assert!(iter.next().is_none());
```
 If the first element is matched, an empty slice will be the first item returned by the iterator. Similarly, if the last element in the slice is matched, an empty slice will be the last item returned by the iterator:

 
```
let slice = [10, 40, 33];
let mut iter = slice.split(|num| num % 3 == 0);

assert_eq!(iter.next().unwrap(), &[10, 40]);
assert_eq!(iter.next().unwrap(), &[]);
assert!(iter.next().is_none());
```
 If two matched elements are directly adjacent, an empty slice will be present between them:

 
```
let slice = [10, 6, 33, 20];
let mut iter = slice.split(|num| num % 3 == 0);

assert_eq!(iter.next().unwrap(), &[10]);
assert_eq!(iter.next().unwrap(), &[]);
assert_eq!(iter.next().unwrap(), &[20]);
assert!(iter.next().is_none());
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2242-2244)
```
pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, T, F> ⓘ
where
    F: FnMut(&T) -> bool,
```

Returns an iterator over mutable subslices separated by elements that match `pred`. The matched element is not contained in the subslices.

 ##### Examples

 
```
let mut v = [10, 40, 30, 20, 60, 50];

for group in v.split_mut(|num| *num % 3 == 0) {
    group[0] = 1;
}
assert_eq!(v, [1, 40, 30, 1, 60, 1]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2278-2280)1.51.0
```
pub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<'_, T, F> ⓘ
where
    F: FnMut(&T) -> bool,
```

Returns an iterator over subslices separated by elements that match `pred`. The matched element is contained in the end of the previous subslice as a terminator.

 ##### Examples

 
```
let slice = [10, 40, 33, 20];
let mut iter = slice.split_inclusive(|num| num % 3 == 0);

assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
assert_eq!(iter.next().unwrap(), &[20]);
assert!(iter.next().is_none());
```
 If the last element of the slice is matched, that element will be considered the terminator of the preceding slice. That slice will be the last item returned by the iterator.

 
```
let slice = [3, 10, 40, 33];
let mut iter = slice.split_inclusive(|num| num % 3 == 0);

assert_eq!(iter.next().unwrap(), &[3]);
assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
assert!(iter.next().is_none());
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2302-2304)1.51.0
```
pub fn split_inclusive_mut<F>(&mut self, pred: F) -> SplitInclusiveMut<'_, T, F> ⓘ
where
    F: FnMut(&T) -> bool,
```

Returns an iterator over mutable subslices separated by elements that match `pred`. The matched element is contained in the previous subslice as a terminator.

 ##### Examples

 
```
let mut v = [10, 40, 30, 20, 60, 50];

for group in v.split_inclusive_mut(|num| *num % 3 == 0) {
    let terminator_idx = group.len()-1;
    group[terminator_idx] = 1;
}
assert_eq!(v, [10, 40, 1, 20, 1, 1]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2338-2340)1.27.0
```
pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F> ⓘ
where
    F: FnMut(&T) -> bool,
```

Returns an iterator over subslices separated by elements that match `pred`, starting at the end of the slice and working backwards. The matched element is not contained in the subslices.

 ##### Examples

 
```
let slice = [11, 22, 33, 0, 44, 55];
let mut iter = slice.rsplit(|num| *num == 0);

assert_eq!(iter.next().unwrap(), &[44, 55]);
assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
assert_eq!(iter.next(), None);
```
 As with `split()`, if the first or last element is matched, an empty slice will be the first (or last) item returned by the iterator.

 
```
let v = &[0, 1, 1, 2, 3, 5, 8];
let mut it = v.rsplit(|n| *n % 2 == 0);
assert_eq!(it.next().unwrap(), &[]);
assert_eq!(it.next().unwrap(), &[3, 5]);
assert_eq!(it.next().unwrap(), &[1, 1]);
assert_eq!(it.next().unwrap(), &[]);
assert_eq!(it.next(), None);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2364-2366)1.27.0
```
pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, T, F> ⓘ
where
    F: FnMut(&T) -> bool,
```

Returns an iterator over mutable subslices separated by elements that match `pred`, starting at the end of the slice and working backwards. The matched element is not contained in the subslices.

 ##### Examples

 
```
let mut v = [100, 400, 300, 200, 600, 500];

let mut count = 0;
for group in v.rsplit_mut(|num| *num % 3 == 0) {
    count += 1;
    group[0] = count;
}
assert_eq!(v, [3, 400, 300, 2, 600, 1]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2392-2394)
```
pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F> ⓘ
where
    F: FnMut(&T) -> bool,
```

Returns an iterator over subslices separated by elements that match `pred`, limited to returning at most `n` items. The matched element is not contained in the subslices.

 The last element returned, if any, will contain the remainder of the slice.

 ##### Examples

 Print the slice split once by numbers divisible by 3 (i.e., `[10, 40]`, `[20, 60, 50]`):

 
```
let v = [10, 40, 30, 20, 60, 50];

for group in v.splitn(2, |num| *num % 3 == 0) {
    println!("{group:?}");
}
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2418-2420)
```
pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, T, F> ⓘ
where
    F: FnMut(&T) -> bool,
```

Returns an iterator over mutable subslices separated by elements that match `pred`, limited to returning at most `n` items. The matched element is not contained in the subslices.

 The last element returned, if any, will contain the remainder of the slice.

 ##### Examples

 
```
let mut v = [10, 40, 30, 20, 60, 50];

for group in v.splitn_mut(2, |num| *num % 3 == 0) {
    group[0] = 1;
}
assert_eq!(v, [1, 40, 30, 1, 60, 50]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2447-2449)
```
pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F> ⓘ
where
    F: FnMut(&T) -> bool,
```

Returns an iterator over subslices separated by elements that match `pred` limited to returning at most `n` items. This starts at the end of the slice and works backwards. The matched element is not contained in the subslices.

 The last element returned, if any, will contain the remainder of the slice.

 ##### Examples

 Print the slice split once, starting from the end, by numbers divisible by 3 (i.e., `[50]`, `[10, 40, 30, 20]`):

 
```
let v = [10, 40, 30, 20, 60, 50];

for group in v.rsplitn(2, |num| *num % 3 == 0) {
    println!("{group:?}");
}
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2474-2476)
```
pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, T, F> ⓘ
where
    F: FnMut(&T) -> bool,
```

Returns an iterator over subslices separated by elements that match `pred` limited to returning at most `n` items. This starts at the end of the slice and works backwards. The matched element is not contained in the subslices.

 The last element returned, if any, will contain the remainder of the slice.

 ##### Examples

 
```
let mut s = [10, 40, 30, 20, 60, 50];

for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
    group[0] = 1;
}
assert_eq!(s, [1, 40, 30, 20, 60, 1]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2509-2511)
```
pub fn contains(&self, x: &T) -> bool
where
    T: PartialEq<T>,
```

Returns `true` if the slice contains an element with the given value.

 This operation is *O*(*n*).

 Note that if you have a sorted slice, [`binary_search`](../primitive.slice#method.binary_search "method slice::binary_search") may be faster.

 ##### Examples

 
```
let v = [10, 40, 30];
assert!(v.contains(&30));
assert!(!v.contains(&50));
```
 If you do not have a `&T`, but some other value that you can compare with one (for example, `String` implements `PartialEq<str>`), you can use `iter().any`:

 
```
let v = [String::from("hello"), String::from("world")]; // slice of `String`
assert!(v.iter().any(|e| e == "hello")); // search with `&str`
assert!(!v.iter().any(|e| e == "hi"));
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2538-2540)
```
pub fn starts_with(&self, needle: &[T]) -> bool
where
    T: PartialEq<T>,
```

Returns `true` if `needle` is a prefix of the slice.

 ##### Examples

 
```
let v = [10, 40, 30];
assert!(v.starts_with(&[10]));
assert!(v.starts_with(&[10, 40]));
assert!(!v.starts_with(&[50]));
assert!(!v.starts_with(&[10, 50]));
```
 Always returns `true` if `needle` is an empty slice:

 
```
let v = &[10, 40, 30];
assert!(v.starts_with(&[]));
let v: &[u8] = &[];
assert!(v.starts_with(&[]));
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2568-2570)
```
pub fn ends_with(&self, needle: &[T]) -> bool
where
    T: PartialEq<T>,
```

Returns `true` if `needle` is a suffix of the slice.

 ##### Examples

 
```
let v = [10, 40, 30];
assert!(v.ends_with(&[30]));
assert!(v.ends_with(&[40, 30]));
assert!(!v.ends_with(&[50]));
assert!(!v.ends_with(&[50, 30]));
```
 Always returns `true` if `needle` is an empty slice:

 
```
let v = &[10, 40, 30];
assert!(v.ends_with(&[]));
let v: &[u8] = &[];
assert!(v.ends_with(&[]));
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2598-2600)1.51.0
```
pub fn strip_prefix<P>(&self, prefix: &P) -> Option<&[T]>
where
    P: SlicePattern<Item = T> + ?Sized,
    T: PartialEq<T>,
```

Returns a subslice with the prefix removed.

 If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`. If `prefix` is empty, simply returns the original slice.

 If the slice does not start with `prefix`, returns `None`.

 ##### Examples

 
```
let v = &[10, 40, 30];
assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..]));
assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..]));
assert_eq!(v.strip_prefix(&[50]), None);
assert_eq!(v.strip_prefix(&[10, 50]), None);

let prefix : &str = "he";
assert_eq!(b"hello".strip_prefix(prefix.as_bytes()),
           Some(b"llo".as_ref()));
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2632-2634)1.51.0
```
pub fn strip_suffix<P>(&self, suffix: &P) -> Option<&[T]>
where
    P: SlicePattern<Item = T> + ?Sized,
    T: PartialEq<T>,
```

Returns a subslice with the suffix removed.

 If the slice ends with `suffix`, returns the subslice before the suffix, wrapped in `Some`. If `suffix` is empty, simply returns the original slice.

 If the slice does not end with `suffix`, returns `None`.

 ##### Examples

 
```
let v = &[10, 40, 30];
assert_eq!(v.strip_suffix(&[30]), Some(&[10, 40][..]));
assert_eq!(v.strip_suffix(&[40, 30]), Some(&[10][..]));
assert_eq!(v.strip_suffix(&[50]), None);
assert_eq!(v.strip_suffix(&[50, 30]), None);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2716-2718)
```
pub fn binary_search(&self, x: &T) -> Result<usize, usize>
where
    T: Ord,
```

Binary searches this slice for a given element. If the slice is not sorted, the returned result is unspecified and meaningless.

 If the value is found then [`Result::Ok`](../result/enum.result#variant.Ok "variant std::result::Result::Ok") is returned, containing the index of the matching element. If there are multiple matches, then any one of the matches could be returned. The index is chosen deterministically, but is subject to change in future versions of Rust. If the value is not found then [`Result::Err`](../result/enum.result#variant.Err "variant std::result::Result::Err") is returned, containing the index where a matching element could be inserted while maintaining sorted order.

 See also [`binary_search_by`](../primitive.slice#method.binary_search_by "method slice::binary_search_by"), [`binary_search_by_key`](../primitive.slice#method.binary_search_by_key "method slice::binary_search_by_key"), and [`partition_point`](../primitive.slice#method.partition_point "method slice::partition_point").

 ##### Examples

 Looks up a series of four elements. The first is found, with a uniquely determined position; the second and third are not found; the fourth could match any position in `[1, 4]`.

 
```
let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];

assert_eq!(s.binary_search(&13),  Ok(9));
assert_eq!(s.binary_search(&4),   Err(7));
assert_eq!(s.binary_search(&100), Err(13));
let r = s.binary_search(&1);
assert!(match r { Ok(1..=4) => true, _ => false, });
```
 If you want to find that whole *range* of matching items, rather than an arbitrary matching one, that can be done using [`partition_point`](../primitive.slice#method.partition_point "method slice::partition_point"):

 
```
let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];

let low = s.partition_point(|x| x < &1);
assert_eq!(low, 1);
let high = s.partition_point(|x| x <= &1);
assert_eq!(high, 5);
let r = s.binary_search(&1);
assert!((low..high).contains(&r.unwrap()));

assert!(s[..low].iter().all(|&x| x < 1));
assert!(s[low..high].iter().all(|&x| x == 1));
assert!(s[high..].iter().all(|&x| x > 1));

// For something not found, the "range" of equal items is empty
assert_eq!(s.partition_point(|x| x < &11), 9);
assert_eq!(s.partition_point(|x| x <= &11), 9);
assert_eq!(s.binary_search(&11), Err(9));
```
 If you want to insert an item to a sorted vector, while maintaining sort order, consider using [`partition_point`](../primitive.slice#method.partition_point "method slice::partition_point"):

 
```
let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
let num = 42;
let idx = s.partition_point(|&x| x < num);
// The above is equivalent to `let idx = s.binary_search(&num).unwrap_or_else(|x| x);`
s.insert(idx, num);
assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2767-2769)
```
pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
where
    F: FnMut(&'a T) -> Ordering,
```

Binary searches this slice with a comparator function.

 The comparator function should return an order code that indicates whether its argument is `Less`, `Equal` or `Greater` the desired target. If the slice is not sorted or if the comparator function does not implement an order consistent with the sort order of the underlying slice, the returned result is unspecified and meaningless.

 If the value is found then [`Result::Ok`](../result/enum.result#variant.Ok "variant std::result::Result::Ok") is returned, containing the index of the matching element. If there are multiple matches, then any one of the matches could be returned. The index is chosen deterministically, but is subject to change in future versions of Rust. If the value is not found then [`Result::Err`](../result/enum.result#variant.Err "variant std::result::Result::Err") is returned, containing the index where a matching element could be inserted while maintaining sorted order.

 See also [`binary_search`](../primitive.slice#method.binary_search "method slice::binary_search"), [`binary_search_by_key`](../primitive.slice#method.binary_search_by_key "method slice::binary_search_by_key"), and [`partition_point`](../primitive.slice#method.partition_point "method slice::partition_point").

 ##### Examples

 Looks up a series of four elements. The first is found, with a uniquely determined position; the second and third are not found; the fourth could match any position in `[1, 4]`.

 
```
let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];

let seek = 13;
assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
let seek = 4;
assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
let seek = 100;
assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
let seek = 1;
let r = s.binary_search_by(|probe| probe.cmp(&seek));
assert!(match r { Ok(1..=4) => true, _ => false, });
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2856-2859)1.10.0
```
pub fn binary_search_by_key<'a, B, F>(
    &'a self,
    b: &B,
    f: F
) -> Result<usize, usize>
where
    F: FnMut(&'a T) -> B,
    B: Ord,
```

Binary searches this slice with a key extraction function.

 Assumes that the slice is sorted by the key, for instance with [`sort_by_key`](../primitive.slice#method.sort_by_key "method slice::sort_by_key") using the same key extraction function. If the slice is not sorted by the key, the returned result is unspecified and meaningless.

 If the value is found then [`Result::Ok`](../result/enum.result#variant.Ok "variant std::result::Result::Ok") is returned, containing the index of the matching element. If there are multiple matches, then any one of the matches could be returned. The index is chosen deterministically, but is subject to change in future versions of Rust. If the value is not found then [`Result::Err`](../result/enum.result#variant.Err "variant std::result::Result::Err") is returned, containing the index where a matching element could be inserted while maintaining sorted order.

 See also [`binary_search`](../primitive.slice#method.binary_search "method slice::binary_search"), [`binary_search_by`](../primitive.slice#method.binary_search_by "method slice::binary_search_by"), and [`partition_point`](../primitive.slice#method.partition_point "method slice::partition_point").

 ##### Examples

 Looks up a series of four elements in a slice of pairs sorted by their second elements. The first is found, with a uniquely determined position; the second and third are not found; the fourth could match any position in `[1, 4]`.

 
```
let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
         (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
         (1, 21), (2, 34), (4, 55)];

assert_eq!(s.binary_search_by_key(&13, |&(a, b)| b),  Ok(9));
assert_eq!(s.binary_search_by_key(&4, |&(a, b)| b),   Err(7));
assert_eq!(s.binary_search_by_key(&100, |&(a, b)| b), Err(13));
let r = s.binary_search_by_key(&1, |&(a, b)| b);
assert!(match r { Ok(1..=4) => true, _ => false, });
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2892-2894)1.20.0
```
pub fn sort_unstable(&mut self)
where
    T: Ord,
```

Sorts the slice, but might not preserve the order of equal elements.

 This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not allocate), and *O*(*n* \* log(*n*)) worst-case.

 ##### Current implementation

 The current algorithm is based on [pattern-defeating quicksort](https://github.com/orlp/pdqsort) by Orson Peters, which combines the fast average case of randomized quicksort with the fast worst case of heapsort, while achieving linear time on slices with certain patterns. It uses some randomization to avoid degenerate cases, but with a fixed seed to always provide deterministic behavior.

 It is typically faster than stable sorting, except in a few special cases, e.g., when the slice consists of several concatenated sorted sequences.

 ##### Examples

 
```
let mut v = [-5, 4, 1, -3, 2];

v.sort_unstable();
assert!(v == [-5, -3, 1, 2, 4]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2947-2949)1.20.0
```
pub fn sort_unstable_by<F>(&mut self, compare: F)
where
    F: FnMut(&T, &T) -> Ordering,
```

Sorts the slice with a comparator function, but might not preserve the order of equal elements.

 This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not allocate), and *O*(*n* \* log(*n*)) worst-case.

 The comparator function must define a total ordering for the elements in the slice. If the ordering is not total, the order of the elements is unspecified. An order is a total order if it is (for all `a`, `b` and `c`):

 * total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b` is true, and
* transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.

 For example, while [`f64`](../primitive.f64 "primitive f64") doesn’t implement [`Ord`](../cmp/trait.ord "trait std::cmp::Ord") because `NaN != NaN`, we can use `partial_cmp` as our sort function when we know the slice doesn’t contain a `NaN`.

 
```
let mut floats = [5f64, 4.0, 1.0, 3.0, 2.0];
floats.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap());
assert_eq!(floats, [1.0, 2.0, 3.0, 4.0, 5.0]);
```
 ##### Current implementation

 The current algorithm is based on [pattern-defeating quicksort](https://github.com/orlp/pdqsort) by Orson Peters, which combines the fast average case of randomized quicksort with the fast worst case of heapsort, while achieving linear time on slices with certain patterns. It uses some randomization to avoid degenerate cases, but with a fixed seed to always provide deterministic behavior.

 It is typically faster than stable sorting, except in a few special cases, e.g., when the slice consists of several concatenated sorted sequences.

 ##### Examples

 
```
let mut v = [5, 4, 1, 3, 2];
v.sort_unstable_by(|a, b| a.cmp(b));
assert!(v == [1, 2, 3, 4, 5]);

// reverse sorting
v.sort_unstable_by(|a, b| b.cmp(a));
assert!(v == [5, 4, 3, 2, 1]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2985-2988)1.20.0
```
pub fn sort_unstable_by_key<K, F>(&mut self, f: F)
where
    F: FnMut(&T) -> K,
    K: Ord,
```

Sorts the slice with a key extraction function, but might not preserve the order of equal elements.

 This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not allocate), and *O*(m \* *n* \* log(*n*)) worst-case, where the key function is *O*(*m*).

 ##### Current implementation

 The current algorithm is based on [pattern-defeating quicksort](https://github.com/orlp/pdqsort) by Orson Peters, which combines the fast average case of randomized quicksort with the fast worst case of heapsort, while achieving linear time on slices with certain patterns. It uses some randomization to avoid degenerate cases, but with a fixed seed to always provide deterministic behavior.

 Due to its key calling strategy, [`sort_unstable_by_key`](#method.sort_unstable_by_key) is likely to be slower than [`sort_by_cached_key`](#method.sort_by_cached_key) in cases where the key function is expensive.

 ##### Examples

 
```
let mut v = [-5i32, 4, 1, -3, 2];

v.sort_unstable_by_key(|k| k.abs());
assert!(v == [1, 2, -3, 4, -5]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3035-3037)1.49.0
```
pub fn select_nth_unstable(
    &mut self,
    index: usize
) -> (&mut [T], &mut T, &mut [T])
where
    T: Ord,
```

Reorder the slice such that the element at `index` is at its final sorted position.

 This reordering has the additional property that any value at position `i < index` will be less than or equal to any value at a position `j > index`. Additionally, this reordering is unstable (i.e. any number of equal elements may end up at position `index`), in-place (i.e. does not allocate), and *O*(*n*) on average. The worst-case performance is *O*(*n* log *n*). This function is also known as “kth element” in other libraries.

 It returns a triplet of the following from the reordered slice: the subslice prior to `index`, the element at `index`, and the subslice after `index`; accordingly, the values in those two subslices will respectively all be less-than-or-equal-to and greater-than-or-equal-to the value of the element at `index`.

 ##### Current implementation

 The current algorithm is an introselect implementation based on Pattern Defeating Quicksort, which is also the basis for [`sort_unstable`](../primitive.slice#method.sort_unstable "method slice::sort_unstable"). The fallback algorithm is Median of Medians using Tukey’s Ninther for pivot selection, which guarantees linear runtime for all inputs.

 ##### Panics

 Panics when `index >= len()`, meaning it always panics on empty slices.

 ##### Examples

 
```
let mut v = [-5i32, 4, 1, -3, 2];

// Find the median
v.select_nth_unstable(2);

// We are only guaranteed the slice will be one of the following, based on the way we sort
// about the specified index.
assert!(v == [-3, -5, 1, 2, 4] ||
        v == [-5, -3, 1, 2, 4] ||
        v == [-3, -5, 1, 4, 2] ||
        v == [-5, -3, 1, 4, 2]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3087-3093)1.49.0
```
pub fn select_nth_unstable_by<F>(
    &mut self,
    index: usize,
    compare: F
) -> (&mut [T], &mut T, &mut [T])
where
    F: FnMut(&T, &T) -> Ordering,
```

Reorder the slice with a comparator function such that the element at `index` is at its final sorted position.

 This reordering has the additional property that any value at position `i < index` will be less than or equal to any value at a position `j > index` using the comparator function. Additionally, this reordering is unstable (i.e. any number of equal elements may end up at position `index`), in-place (i.e. does not allocate), and *O*(*n*) on average. The worst-case performance is *O*(*n* log *n*). This function is also known as “kth element” in other libraries.

 It returns a triplet of the following from the slice reordered according to the provided comparator function: the subslice prior to `index`, the element at `index`, and the subslice after `index`; accordingly, the values in those two subslices will respectively all be less-than-or-equal-to and greater-than-or-equal-to the value of the element at `index`.

 ##### Current implementation

 The current algorithm is an introselect implementation based on Pattern Defeating Quicksort, which is also the basis for [`sort_unstable`](../primitive.slice#method.sort_unstable "method slice::sort_unstable"). The fallback algorithm is Median of Medians using Tukey’s Ninther for pivot selection, which guarantees linear runtime for all inputs.

 ##### Panics

 Panics when `index >= len()`, meaning it always panics on empty slices.

 ##### Examples

 
```
let mut v = [-5i32, 4, 1, -3, 2];

// Find the median as if the slice were sorted in descending order.
v.select_nth_unstable_by(2, |a, b| b.cmp(a));

// We are only guaranteed the slice will be one of the following, based on the way we sort
// about the specified index.
assert!(v == [2, 4, 1, -5, -3] ||
        v == [2, 4, 1, -3, -5] ||
        v == [4, 2, 1, -5, -3] ||
        v == [4, 2, 1, -3, -5]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3142-3149)1.49.0
```
pub fn select_nth_unstable_by_key<K, F>(
    &mut self,
    index: usize,
    f: F
) -> (&mut [T], &mut T, &mut [T])
where
    F: FnMut(&T) -> K,
    K: Ord,
```

Reorder the slice with a key extraction function such that the element at `index` is at its final sorted position.

 This reordering has the additional property that any value at position `i < index` will be less than or equal to any value at a position `j > index` using the key extraction function. Additionally, this reordering is unstable (i.e. any number of equal elements may end up at position `index`), in-place (i.e. does not allocate), and *O*(*n*) on average. The worst-case performance is *O*(*n* log *n*). This function is also known as “kth element” in other libraries.

 It returns a triplet of the following from the slice reordered according to the provided key extraction function: the subslice prior to `index`, the element at `index`, and the subslice after `index`; accordingly, the values in those two subslices will respectively all be less-than-or-equal-to and greater-than-or-equal-to the value of the element at `index`.

 ##### Current implementation

 The current algorithm is based on the quickselect portion of the same quicksort algorithm used for [`sort_unstable`](../primitive.slice#method.sort_unstable "method slice::sort_unstable").

 ##### Panics

 Panics when `index >= len()`, meaning it always panics on empty slices.

 ##### Examples

 
```
let mut v = [-5i32, 4, 1, -3, 2];

// Return the median as if the array were sorted according to absolute value.
v.select_nth_unstable_by_key(2, |a| a.abs());

// We are only guaranteed the slice will be one of the following, based on the way we sort
// about the specified index.
assert!(v == [1, 2, -3, 4, -5] ||
        v == [1, 2, -3, -5, 4] ||
        v == [2, 1, -3, 4, -5] ||
        v == [2, 1, -3, -5, 4]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3176-3178)
```
pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])
where
    T: PartialEq<T>,
```

🔬This is a nightly-only experimental API. (`slice_partition_dedup` [#54279](https://github.com/rust-lang/rust/issues/54279))

Moves all consecutive repeated elements to the end of the slice according to the [`PartialEq`](../cmp/trait.partialeq "trait std::cmp::PartialEq") trait implementation.

 Returns two slices. The first contains no consecutive repeated elements. The second contains all the duplicates in no specified order.

 If the slice is sorted, the first returned slice contains no duplicates.

 ##### Examples

 
```
#![feature(slice_partition_dedup)]

let mut slice = [1, 2, 2, 3, 3, 2, 1, 1];

let (dedup, duplicates) = slice.partition_dedup();

assert_eq!(dedup, [1, 2, 3, 2, 1]);
assert_eq!(duplicates, [2, 3, 1]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3210-3212)
```
pub fn partition_dedup_by<F>(&mut self, same_bucket: F) -> (&mut [T], &mut [T])
where
    F: FnMut(&mut T, &mut T) -> bool,
```

🔬This is a nightly-only experimental API. (`slice_partition_dedup` [#54279](https://github.com/rust-lang/rust/issues/54279))

Moves all but the first of consecutive elements to the end of the slice satisfying a given equality relation.

 Returns two slices. The first contains no consecutive repeated elements. The second contains all the duplicates in no specified order.

 The `same_bucket` function is passed references to two elements from the slice and must determine if the elements compare equal. The elements are passed in opposite order from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is moved at the end of the slice.

 If the slice is sorted, the first returned slice contains no duplicates.

 ##### Examples

 
```
#![feature(slice_partition_dedup)]

let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"];

let (dedup, duplicates) = slice.partition_dedup_by(|a, b| a.eq_ignore_ascii_case(b));

assert_eq!(dedup, ["foo", "BAZ", "Bar", "baz"]);
assert_eq!(duplicates, ["bar", "Foo", "BAZ"]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3336-3339)
```
pub fn partition_dedup_by_key<K, F>(&mut self, key: F) -> (&mut [T], &mut [T])
where
    F: FnMut(&mut T) -> K,
    K: PartialEq<K>,
```

🔬This is a nightly-only experimental API. (`slice_partition_dedup` [#54279](https://github.com/rust-lang/rust/issues/54279))

Moves all but the first of consecutive elements to the end of the slice that resolve to the same key.

 Returns two slices. The first contains no consecutive repeated elements. The second contains all the duplicates in no specified order.

 If the slice is sorted, the first returned slice contains no duplicates.

 ##### Examples

 
```
#![feature(slice_partition_dedup)]

let mut slice = [10, 20, 21, 30, 30, 20, 11, 13];

let (dedup, duplicates) = slice.partition_dedup_by_key(|i| *i / 10);

assert_eq!(dedup, [10, 20, 30, 20, 11]);
assert_eq!(duplicates, [21, 30, 13]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3375)1.26.0
```
pub fn rotate_left(&mut self, mid: usize)
```

Rotates the slice in-place such that the first `mid` elements of the slice move to the end while the last `self.len() - mid` elements move to the front. After calling `rotate_left`, the element previously at index `mid` will become the first element in the slice.

 ##### Panics

 This function will panic if `mid` is greater than the length of the slice. Note that `mid == self.len()` does *not* panic and is a no-op rotation.

 ##### Complexity

 Takes linear (in `self.len()`) time.

 ##### Examples

 
```
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
a.rotate_left(2);
assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
```
 Rotating a subslice:

 
```
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
a[1..5].rotate_left(1);
assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3418)1.26.0
```
pub fn rotate_right(&mut self, k: usize)
```

Rotates the slice in-place such that the first `self.len() - k` elements of the slice move to the end while the last `k` elements move to the front. After calling `rotate_right`, the element previously at index `self.len() - k` will become the first element in the slice.

 ##### Panics

 This function will panic if `k` is greater than the length of the slice. Note that `k == self.len()` does *not* panic and is a no-op rotation.

 ##### Complexity

 Takes linear (in `self.len()`) time.

 ##### Examples

 
```
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
a.rotate_right(2);
assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
```
 Rotate a subslice:

 
```
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
a[1..5].rotate_right(1);
assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3441-3443)1.50.0
```
pub fn fill(&mut self, value: T)
where
    T: Clone,
```

Fills `self` with elements by cloning `value`.

 ##### Examples

 
```
let mut buf = vec![0; 10];
buf.fill(1);
assert_eq!(buf, vec![1; 10]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3465-3467)1.51.0
```
pub fn fill_with<F>(&mut self, f: F)
where
    F: FnMut() -> T,
```

Fills `self` with elements returned by calling a closure repeatedly.

 This method uses a closure to create new values. If you’d rather [`Clone`](../clone/trait.clone "trait std::clone::Clone") a given value, use [`fill`](../primitive.slice#method.fill "method slice::fill"). If you want to use the [`Default`](../default/trait.default "trait std::default::Default") trait to generate values, you can pass [`Default::default`](../default/trait.default#tymethod.default "associated function std::default::Default::default") as the argument.

 ##### Examples

 
```
let mut buf = vec![1; 10];
buf.fill_with(Default::default);
assert_eq!(buf, vec![0; 10]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3528-3530)1.7.0
```
pub fn clone_from_slice(&mut self, src: &[T])
where
    T: Clone,
```

Copies the elements from `src` into `self`.

 The length of `src` must be the same as `self`.

 ##### Panics

 This function will panic if the two slices have different lengths.

 ##### Examples

 Cloning two elements from a slice into another:

 
```
let src = [1, 2, 3, 4];
let mut dst = [0, 0];

// Because the slices have to be the same length,
// we slice the source slice from four elements
// to two. It will panic if we don't do this.
dst.clone_from_slice(&src[2..]);

assert_eq!(src, [1, 2, 3, 4]);
assert_eq!(dst, [3, 4]);
```
 Rust enforces that there can only be one mutable reference with no immutable references to a particular piece of data in a particular scope. Because of this, attempting to use `clone_from_slice` on a single slice will result in a compile failure:

 ⓘ
```
let mut slice = [1, 2, 3, 4, 5];

slice[..2].clone_from_slice(&slice[3..]); // compile fail!
```

 To work around this, we can use [`split_at_mut`](../primitive.slice#method.split_at_mut "method slice::split_at_mut") to create two distinct sub-slices from a slice:

 
```
let mut slice = [1, 2, 3, 4, 5];

{
    let (left, right) = slice.split_at_mut(2);
    left.clone_from_slice(&right[1..]);
}

assert_eq!(slice, [4, 5, 3, 4, 5]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3592-3594)1.9.0
```
pub fn copy_from_slice(&mut self, src: &[T])
where
    T: Copy,
```

Copies all elements from `src` into `self`, using a memcpy.

 The length of `src` must be the same as `self`.

 If `T` does not implement `Copy`, use [`clone_from_slice`](../primitive.slice#method.clone_from_slice "method slice::clone_from_slice").

 ##### Panics

 This function will panic if the two slices have different lengths.

 ##### Examples

 Copying two elements from a slice into another:

 
```
let src = [1, 2, 3, 4];
let mut dst = [0, 0];

// Because the slices have to be the same length,
// we slice the source slice from four elements
// to two. It will panic if we don't do this.
dst.copy_from_slice(&src[2..]);

assert_eq!(src, [1, 2, 3, 4]);
assert_eq!(dst, [3, 4]);
```
 Rust enforces that there can only be one mutable reference with no immutable references to a particular piece of data in a particular scope. Because of this, attempting to use `copy_from_slice` on a single slice will result in a compile failure:

 ⓘ
```
let mut slice = [1, 2, 3, 4, 5];

slice[..2].copy_from_slice(&slice[3..]); // compile fail!
```

 To work around this, we can use [`split_at_mut`](../primitive.slice#method.split_at_mut "method slice::split_at_mut") to create two distinct sub-slices from a slice:

 
```
let mut slice = [1, 2, 3, 4, 5];

{
    let (left, right) = slice.split_at_mut(2);
    left.copy_from_slice(&right[1..]);
}

assert_eq!(slice, [4, 5, 3, 4, 5]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3646-3648)1.37.0
```
pub fn copy_within<R>(&mut self, src: R, dest: usize)
where
    R: RangeBounds<usize>,
    T: Copy,
```

Copies elements from one part of the slice to another part of itself, using a memmove.

 `src` is the range within `self` to copy from. `dest` is the starting index of the range within `self` to copy to, which will have the same length as `src`. The two ranges may overlap. The ends of the two ranges must be less than or equal to `self.len()`.

 ##### Panics

 This function will panic if either range exceeds the end of the slice, or if the end of `src` is before the start.

 ##### Examples

 Copying four bytes within a slice:

 
```
let mut bytes = *b"Hello, World!";

bytes.copy_within(1..5, 8);

assert_eq!(&bytes, b"Hello, Wello!");
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3713)1.27.0
```
pub fn swap_with_slice(&mut self, other: &mut [T])
```

Swaps all elements in `self` with those in `other`.

 The length of `other` must be the same as `self`.

 ##### Panics

 This function will panic if the two slices have different lengths.

 ##### Example

 Swapping two elements across slices:

 
```
let mut slice1 = [0, 0];
let mut slice2 = [1, 2, 3, 4];

slice1.swap_with_slice(&mut slice2[2..]);

assert_eq!(slice1, [3, 4]);
assert_eq!(slice2, [1, 2, 0, 0]);
```
 Rust enforces that there can only be one mutable reference to a particular piece of data in a particular scope. Because of this, attempting to use `swap_with_slice` on a single slice will result in a compile failure:

 ⓘ
```
let mut slice = [1, 2, 3, 4, 5];
slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
```

 To work around this, we can use [`split_at_mut`](../primitive.slice#method.split_at_mut "method slice::split_at_mut") to create two distinct mutable sub-slices from a slice:

 
```
let mut slice = [1, 2, 3, 4, 5];

{
    let (left, right) = slice.split_at_mut(2);
    left.swap_with_slice(&mut right[1..]);
}

assert_eq!(slice, [4, 5, 3, 1, 2]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3793)1.30.0
```
pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T])
```

Transmute the slice to a slice of another type, ensuring alignment of the types is maintained.

 This method splits the slice into three distinct slices: prefix, correctly aligned middle slice of a new type, and the suffix slice. How exactly the slice is split up is not specified; the middle part may be smaller than necessary. However, if this fails to return a maximal middle part, that is because code is running in a context where performance does not matter, such as a sanitizer attempting to find alignment bugs. Regular code running in a default (debug or release) execution *will* return a maximal middle part.

 This method has no purpose when either input element `T` or output element `U` are zero-sized and will return the original slice without splitting anything.

 ##### Safety

 This method is essentially a `transmute` with respect to the elements in the returned middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.

 ##### Examples

 Basic usage:

 
```
unsafe {
    let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
    let (prefix, shorts, suffix) = bytes.align_to::<u16>();
    // less_efficient_algorithm_for_bytes(prefix);
    // more_efficient_algorithm_for_aligned_shorts(shorts);
    // less_efficient_algorithm_for_bytes(suffix);
}
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3855)1.30.0
```
pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T])
```

Transmute the mutable slice to a mutable slice of another type, ensuring alignment of the types is maintained.

 This method splits the slice into three distinct slices: prefix, correctly aligned middle slice of a new type, and the suffix slice. How exactly the slice is split up is not specified; the middle part may be smaller than necessary. However, if this fails to return a maximal middle part, that is because code is running in a context where performance does not matter, such as a sanitizer attempting to find alignment bugs. Regular code running in a default (debug or release) execution *will* return a maximal middle part.

 This method has no purpose when either input element `T` or output element `U` are zero-sized and will return the original slice without splitting anything.

 ##### Safety

 This method is essentially a `transmute` with respect to the elements in the returned middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.

 ##### Examples

 Basic usage:

 
```
unsafe {
    let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
    let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
    // less_efficient_algorithm_for_bytes(prefix);
    // more_efficient_algorithm_for_aligned_shorts(shorts);
    // less_efficient_algorithm_for_bytes(suffix);
}
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3950-3954)
```
pub fn as_simd<const LANES: usize>(&self) -> (&[T], &[Simd<T, LANES>], &[T])
where
    Simd<T, LANES>: AsRef<[T; LANES]>,
    T: SimdElement,
    LaneCount<LANES>: SupportedLaneCount,
```

🔬This is a nightly-only experimental API. (`portable_simd` [#86656](https://github.com/rust-lang/rust/issues/86656))

Split a slice into a prefix, a middle of aligned SIMD types, and a suffix.

 This is a safe wrapper around [`slice::align_to`](../primitive.slice#method.align_to "method slice::align_to"), so has the same weak postconditions as that method. You’re only assured that `self.len() == prefix.len() + middle.len() * LANES + suffix.len()`.

 Notably, all of the following are possible:

 * `prefix.len() >= LANES`.
* `middle.is_empty()` despite `self.len() >= 3 * LANES`.
* `suffix.len() >= LANES`.

 That said, this is a safe method, so if you’re only writing safe code, then this can at most cause incorrect logic, not unsoundness.

 ##### Panics

 This will panic if the size of the SIMD type is different from `LANES` times that of the scalar.

 At the time of writing, the trait restrictions on `Simd<T, LANES>` keeps that from ever happening, as only power-of-two numbers of lanes are supported. It’s possible that, in the future, those restrictions might be lifted in a way that would make it possible to see panics from this method for something like `LANES == 3`.

 ##### Examples

 
```
#![feature(portable_simd)]
use core::simd::SimdFloat;

let short = &[1, 2, 3];
let (prefix, middle, suffix) = short.as_simd::<4>();
assert_eq!(middle, []); // Not enough elements for anything in the middle

// They might be split in any possible way between prefix and suffix
let it = prefix.iter().chain(suffix).copied();
assert_eq!(it.collect::<Vec<_>>(), vec![1, 2, 3]);

fn basic_simd_sum(x: &[f32]) -> f32 {
    use std::ops::Add;
    use std::simd::f32x4;
    let (prefix, middle, suffix) = x.as_simd();
    let sums = f32x4::from_array([
        prefix.iter().copied().sum(),
        0.0,
        0.0,
        suffix.iter().copied().sum(),
    ]);
    let sums = middle.iter().copied().fold(sums, f32x4::add);
    sums.reduce_sum()
}

let numbers: Vec<f32> = (1..101).map(|x| x as _).collect();
assert_eq!(basic_simd_sum(&numbers[1..99]), 4949.0);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3995-3999)
```
pub fn as_simd_mut<const LANES: usize>(
    &mut self
) -> (&mut [T], &mut [Simd<T, LANES>], &mut [T])
where
    Simd<T, LANES>: AsMut<[T; LANES]>,
    T: SimdElement,
    LaneCount<LANES>: SupportedLaneCount,
```

🔬This is a nightly-only experimental API. (`portable_simd` [#86656](https://github.com/rust-lang/rust/issues/86656))

Split a mutable slice into a mutable prefix, a middle of aligned SIMD types, and a mutable suffix.

 This is a safe wrapper around [`slice::align_to_mut`](../primitive.slice#method.align_to_mut "method slice::align_to_mut"), so has the same weak postconditions as that method. You’re only assured that `self.len() == prefix.len() + middle.len() * LANES + suffix.len()`.

 Notably, all of the following are possible:

 * `prefix.len() >= LANES`.
* `middle.is_empty()` despite `self.len() >= 3 * LANES`.
* `suffix.len() >= LANES`.

 That said, this is a safe method, so if you’re only writing safe code, then this can at most cause incorrect logic, not unsoundness.

 This is the mutable version of [`slice::as_simd`](../primitive.slice#method.as_simd "method slice::as_simd"); see that for examples.

 ##### Panics

 This will panic if the size of the SIMD type is different from `LANES` times that of the scalar.

 At the time of writing, the trait restrictions on `Simd<T, LANES>` keeps that from ever happening, as only power-of-two numbers of lanes are supported. It’s possible that, in the future, those restrictions might be lifted in a way that would make it possible to see panics from this method for something like `LANES == 3`.

 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4035-4037)
```
pub fn is_sorted(&self) -> bool
where
    T: PartialOrd<T>,
```

🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485))

Checks if the elements of this slice are sorted.

 That is, for each element `a` and its following element `b`, `a <= b` must hold. If the slice yields exactly zero or one element, `true` is returned.

 Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition implies that this function returns `false` if any two consecutive items are not comparable.

 ##### Examples

 
```
#![feature(is_sorted)]
let empty: [i32; 0] = [];

assert!([1, 2, 2, 9].is_sorted());
assert!(![1, 3, 2, 4].is_sorted());
assert!([0].is_sorted());
assert!(empty.is_sorted());
assert!(![0.0, 1.0, f32::NAN].is_sorted());
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4051-4053)
```
pub fn is_sorted_by<'a, F>(&'a self, compare: F) -> bool
where
    F: FnMut(&'a T, &'a T) -> Option<Ordering>,
```

🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485))

Checks if the elements of this slice are sorted using the given comparator function.

 Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare` function to determine the ordering of two elements. Apart from that, it’s equivalent to [`is_sorted`](../primitive.slice#method.is_sorted "method slice::is_sorted"); see its documentation for more information.

 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4077-4080)
```
pub fn is_sorted_by_key<'a, F, K>(&'a self, f: F) -> bool
where
    F: FnMut(&'a T) -> K,
    K: PartialOrd<K>,
```

🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485))

Checks if the elements of this slice are sorted using the given key extraction function.

 Instead of comparing the slice’s elements directly, this function compares the keys of the elements, as determined by `f`. Apart from that, it’s equivalent to [`is_sorted`](../primitive.slice#method.is_sorted "method slice::is_sorted"); see its documentation for more information.

 ##### Examples

 
```
#![feature(is_sorted)]

assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));
assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4136-4138)1.52.0
```
pub fn partition_point<P>(&self, pred: P) -> usize
where
    P: FnMut(&T) -> bool,
```

Returns the index of the partition point according to the given predicate (the index of the first element of the second partition).

 The slice is assumed to be partitioned according to the given predicate. This means that all elements for which the predicate returns true are at the start of the slice and all elements for which the predicate returns false are at the end. For example, `[7, 15, 3, 5, 4, 12, 6]` is partitioned under the predicate `x % 2 != 0` (all odd numbers are at the start, all even at the end).

 If this slice is not partitioned, the returned result is unspecified and meaningless, as this method performs a kind of binary search.

 See also [`binary_search`](../primitive.slice#method.binary_search "method slice::binary_search"), [`binary_search_by`](../primitive.slice#method.binary_search_by "method slice::binary_search_by"), and [`binary_search_by_key`](../primitive.slice#method.binary_search_by_key "method slice::binary_search_by_key").

 ##### Examples

 
```
let v = [1, 2, 3, 3, 5, 6, 7];
let i = v.partition_point(|&x| x < 5);

assert_eq!(i, 4);
assert!(v[..i].iter().all(|&x| x < 5));
assert!(v[i..].iter().all(|&x| !(x < 5)));
```
 If all elements of the slice match the predicate, including if the slice is empty, then the length of the slice will be returned:

 
```
let a = [2, 4, 8];
assert_eq!(a.partition_point(|x| x < &100), a.len());
let a: [i32; 0] = [];
assert_eq!(a.partition_point(|x| x < &100), 0);
```
 If you want to insert an item to a sorted vector, while maintaining sort order:

 
```
let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
let num = 42;
let idx = s.partition_point(|&x| x < num);
s.insert(idx, num);
assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4194)
```
pub fn take<R, 'a>(self: &mut &'a [T], range: R) -> Option<&'a [T]>
where
    R: OneSidedRange<usize>,
```

🔬This is a nightly-only experimental API. (`slice_take` [#62280](https://github.com/rust-lang/rust/issues/62280))

Removes the subslice corresponding to the given range and returns a reference to it.

 Returns `None` and does not modify the slice if the given range is out of bounds.

 Note that this method only accepts one-sided ranges such as `2..` or `..6`, but not `2..6`.

 ##### Examples

 Taking the first three elements of a slice:

 
```
#![feature(slice_take)]

let mut slice: &[_] = &['a', 'b', 'c', 'd'];
let mut first_three = slice.take(..3).unwrap();

assert_eq!(slice, &['d']);
assert_eq!(first_three, &['a', 'b', 'c']);
```
 Taking the last two elements of a slice:

 
```
#![feature(slice_take)]

let mut slice: &[_] = &['a', 'b', 'c', 'd'];
let mut tail = slice.take(2..).unwrap();

assert_eq!(slice, &['a', 'b']);
assert_eq!(tail, &['c', 'd']);
```
 Getting `None` when `range` is out of bounds:

 
```
#![feature(slice_take)]

let mut slice: &[_] = &['a', 'b', 'c', 'd'];

assert_eq!(None, slice.take(5..));
assert_eq!(None, slice.take(..5));
assert_eq!(None, slice.take(..=4));
let expected: &[char] = &['a', 'b', 'c', 'd'];
assert_eq!(Some(expected), slice.take(..4));
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4263-4266)
```
pub fn take_mut<R, 'a>(self: &mut &'a mut [T], range: R) -> Option<&'a mut [T]>
where
    R: OneSidedRange<usize>,
```

🔬This is a nightly-only experimental API. (`slice_take` [#62280](https://github.com/rust-lang/rust/issues/62280))

Removes the subslice corresponding to the given range and returns a mutable reference to it.

 Returns `None` and does not modify the slice if the given range is out of bounds.

 Note that this method only accepts one-sided ranges such as `2..` or `..6`, but not `2..6`.

 ##### Examples

 Taking the first three elements of a slice:

 
```
#![feature(slice_take)]

let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
let mut first_three = slice.take_mut(..3).unwrap();

assert_eq!(slice, &mut ['d']);
assert_eq!(first_three, &mut ['a', 'b', 'c']);
```
 Taking the last two elements of a slice:

 
```
#![feature(slice_take)]

let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
let mut tail = slice.take_mut(2..).unwrap();

assert_eq!(slice, &mut ['a', 'b']);
assert_eq!(tail, &mut ['c', 'd']);
```
 Getting `None` when `range` is out of bounds:

 
```
#![feature(slice_take)]

let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];

assert_eq!(None, slice.take_mut(5..));
assert_eq!(None, slice.take_mut(..5));
assert_eq!(None, slice.take_mut(..=4));
let expected: &mut [_] = &mut ['a', 'b', 'c', 'd'];
assert_eq!(Some(expected), slice.take_mut(..4));
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4302)
```
pub fn take_first<'a>(self: &mut &'a [T]) -> Option<&'a T>
```

🔬This is a nightly-only experimental API. (`slice_take` [#62280](https://github.com/rust-lang/rust/issues/62280))

Removes the first element of the slice and returns a reference to it.

 Returns `None` if the slice is empty.

 ##### Examples

 
```
#![feature(slice_take)]

let mut slice: &[_] = &['a', 'b', 'c'];
let first = slice.take_first().unwrap();

assert_eq!(slice, &['b', 'c']);
assert_eq!(first, &'a');
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4327)
```
pub fn take_first_mut<'a>(self: &mut &'a mut [T]) -> Option<&'a mut T>
```

🔬This is a nightly-only experimental API. (`slice_take` [#62280](https://github.com/rust-lang/rust/issues/62280))

Removes the first element of the slice and returns a mutable reference to it.

 Returns `None` if the slice is empty.

 ##### Examples

 
```
#![feature(slice_take)]

let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
let first = slice.take_first_mut().unwrap();
*first = 'd';

assert_eq!(slice, &['b', 'c']);
assert_eq!(first, &'d');
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4351)
```
pub fn take_last<'a>(self: &mut &'a [T]) -> Option<&'a T>
```

🔬This is a nightly-only experimental API. (`slice_take` [#62280](https://github.com/rust-lang/rust/issues/62280))

Removes the last element of the slice and returns a reference to it.

 Returns `None` if the slice is empty.

 ##### Examples

 
```
#![feature(slice_take)]

let mut slice: &[_] = &['a', 'b', 'c'];
let last = slice.take_last().unwrap();

assert_eq!(slice, &['a', 'b']);
assert_eq!(last, &'c');
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4376)
```
pub fn take_last_mut<'a>(self: &mut &'a mut [T]) -> Option<&'a mut T>
```

🔬This is a nightly-only experimental API. (`slice_take` [#62280](https://github.com/rust-lang/rust/issues/62280))

Removes the last element of the slice and returns a mutable reference to it.

 Returns `None` if the slice is empty.

 ##### Examples

 
```
#![feature(slice_take)]

let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
let last = slice.take_last_mut().unwrap();
*last = 'd';

assert_eq!(slice, &['a', 'b']);
assert_eq!(last, &'d');
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4410-4413)
```
pub unsafe fn get_many_unchecked_mut<const N: usize>(
    &mut self,
    indices: [usize; N]
) -> [&mut T; N]
```

🔬This is a nightly-only experimental API. (`get_many_mut` [#104642](https://github.com/rust-lang/rust/issues/104642))

Returns mutable references to many indices at once, without doing any checks.

 For a safe alternative see [`get_many_mut`](../primitive.slice#method.get_many_mut "method slice::get_many_mut").

 ##### Safety

 Calling this method with overlapping or out-of-bounds indices is *[undefined behavior](../../reference/behavior-considered-undefined)* even if the resulting references are not used.

 ##### Examples

 
```
#![feature(get_many_mut)]

let x = &mut [1, 2, 4];

unsafe {
    let [a, b] = x.get_many_unchecked_mut([0, 2]);
    *a *= 10;
    *b *= 100;
}
assert_eq!(x, &[10, 2, 400]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4452-4455)
```
pub fn get_many_mut<const N: usize>(
    &mut self,
    indices: [usize; N]
) -> Result<[&mut T; N], GetManyMutError<N>>
```

🔬This is a nightly-only experimental API. (`get_many_mut` [#104642](https://github.com/rust-lang/rust/issues/104642))

Returns mutable references to many indices at once.

 Returns an error if any index is out-of-bounds, or if the same index was passed more than once.

 ##### Examples

 
```
#![feature(get_many_mut)]

let v = &mut [1, 2, 3];
if let Ok([a, b]) = v.get_many_mut([0, 2]) {
    *a = 413;
    *b = 612;
}
assert_eq!(v, &[413, 2, 612]);
```
 
[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#207-209)
```
pub fn sort(&mut self)
where
    T: Ord,
```

Sorts the slice.

 This sort is stable (i.e., does not reorder equal elements) and *O*(*n* \* log(*n*)) worst-case.

 When applicable, unstable sorting is preferred because it is generally faster than stable sorting and it doesn’t allocate auxiliary memory. See [`sort_unstable`](../primitive.slice#method.sort_unstable "method slice::sort_unstable").

 ##### Current implementation

 The current algorithm is an adaptive, iterative merge sort inspired by [timsort](https://en.wikipedia.org/wiki/Timsort). It is designed to be very fast in cases where the slice is nearly sorted, or consists of two or more sorted sequences concatenated one after another.

 Also, it allocates temporary storage half the size of `self`, but for short slices a non-allocating insertion sort is used instead.

 ##### Examples

 
```
let mut v = [-5, 4, 1, -3, 2];

v.sort();
assert!(v == [-5, -3, 1, 2, 4]);
```
 
[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#263-265)
```
pub fn sort_by<F>(&mut self, compare: F)
where
    F: FnMut(&T, &T) -> Ordering,
```

Sorts the slice with a comparator function.

 This sort is stable (i.e., does not reorder equal elements) and *O*(*n* \* log(*n*)) worst-case.

 The comparator function must define a total ordering for the elements in the slice. If the ordering is not total, the order of the elements is unspecified. An order is a total order if it is (for all `a`, `b` and `c`):

 * total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b` is true, and
* transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.

 For example, while [`f64`](../primitive.f64 "primitive f64") doesn’t implement [`Ord`](../cmp/trait.ord "trait std::cmp::Ord") because `NaN != NaN`, we can use `partial_cmp` as our sort function when we know the slice doesn’t contain a `NaN`.

 
```
let mut floats = [5f64, 4.0, 1.0, 3.0, 2.0];
floats.sort_by(|a, b| a.partial_cmp(b).unwrap());
assert_eq!(floats, [1.0, 2.0, 3.0, 4.0, 5.0]);
```
 When applicable, unstable sorting is preferred because it is generally faster than stable sorting and it doesn’t allocate auxiliary memory. See [`sort_unstable_by`](../primitive.slice#method.sort_unstable_by "method slice::sort_unstable_by").

 ##### Current implementation

 The current algorithm is an adaptive, iterative merge sort inspired by [timsort](https://en.wikipedia.org/wiki/Timsort). It is designed to be very fast in cases where the slice is nearly sorted, or consists of two or more sorted sequences concatenated one after another.

 Also, it allocates temporary storage half the size of `self`, but for short slices a non-allocating insertion sort is used instead.

 ##### Examples

 
```
let mut v = [5, 4, 1, 3, 2];
v.sort_by(|a, b| a.cmp(b));
assert!(v == [1, 2, 3, 4, 5]);

// reverse sorting
v.sort_by(|a, b| b.cmp(a));
assert!(v == [5, 4, 3, 2, 1]);
```
 
[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#305-308)1.7.0
```
pub fn sort_by_key<K, F>(&mut self, f: F)
where
    F: FnMut(&T) -> K,
    K: Ord,
```

Sorts the slice with a key extraction function.

 This sort is stable (i.e., does not reorder equal elements) and *O*(*m* \* *n* \* log(*n*)) worst-case, where the key function is *O*(*m*).

 For expensive key functions (e.g. functions that are not simple property accesses or basic operations), [`sort_by_cached_key`](../primitive.slice#method.sort_by_cached_key "method slice::sort_by_cached_key") is likely to be significantly faster, as it does not recompute element keys.

 When applicable, unstable sorting is preferred because it is generally faster than stable sorting and it doesn’t allocate auxiliary memory. See [`sort_unstable_by_key`](../primitive.slice#method.sort_unstable_by_key "method slice::sort_unstable_by_key").

 ##### Current implementation

 The current algorithm is an adaptive, iterative merge sort inspired by [timsort](https://en.wikipedia.org/wiki/Timsort). It is designed to be very fast in cases where the slice is nearly sorted, or consists of two or more sorted sequences concatenated one after another.

 Also, it allocates temporary storage half the size of `self`, but for short slices a non-allocating insertion sort is used instead.

 ##### Examples

 
```
let mut v = [-5i32, 4, 1, -3, 2];

v.sort_by_key(|k| k.abs());
assert!(v == [1, 2, -3, 4, -5]);
```
 
[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#352-355)1.34.0
```
pub fn sort_by_cached_key<K, F>(&mut self, f: F)
where
    F: FnMut(&T) -> K,
    K: Ord,
```

Sorts the slice with a key extraction function.

 During sorting, the key function is called at most once per element, by using temporary storage to remember the results of key evaluation. The order of calls to the key function is unspecified and may change in future versions of the standard library.

 This sort is stable (i.e., does not reorder equal elements) and *O*(*m* \* *n* + *n* \* log(*n*)) worst-case, where the key function is *O*(*m*).

 For simple key functions (e.g., functions that are property accesses or basic operations), [`sort_by_key`](../primitive.slice#method.sort_by_key "method slice::sort_by_key") is likely to be faster.

 ##### Current implementation

 The current algorithm is based on [pattern-defeating quicksort](https://github.com/orlp/pdqsort) by Orson Peters, which combines the fast average case of randomized quicksort with the fast worst case of heapsort, while achieving linear time on slices with certain patterns. It uses some randomization to avoid degenerate cases, but with a fixed seed to always provide deterministic behavior.

 In the worst case, the algorithm allocates temporary storage in a `Vec<(K, usize)>` the length of the slice.

 ##### Examples

 
```
let mut v = [-5i32, 4, 32, -3, 2];

v.sort_by_cached_key(|k| k.to_string());
assert!(v == [-3, -5, 2, 32, 4]);
```
 
[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#412-414)
```
pub fn to_vec(&self) -> Vec<T, Global>
where
    T: Clone,
```

Copies `self` into a new `Vec`.

 ##### Examples

 
```
let s = [10, 40, 30];
let x = s.to_vec();
// Here, `s` and `x` can be modified independently.
```
 
[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#436-438)
```
pub fn to_vec_in<A>(&self, alloc: A) -> Vec<T, A>
where
    A: Allocator,
    T: Clone,
```

🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838))

Copies `self` into a new `Vec` with an allocator.

 ##### Examples

 
```
#![feature(allocator_api)]

use std::alloc::System;

let s = [10, 40, 30];
let x = s.to_vec_in(System);
// Here, `s` and `x` can be modified independently.
```
 
[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#489-491)1.40.0
```
pub fn repeat(&self, n: usize) -> Vec<T, Global>
where
    T: Copy,
```

Creates a vector by copying a slice `n` times.

 ##### Panics

 This function will panic if the capacity would overflow.

 ##### Examples

 Basic usage:

 
```
assert_eq!([1, 2].repeat(3), vec![1, 2, 1, 2, 1, 2]);
```
 A panic upon overflow:

 ⓘ
```
// this will panic at runtime
b"0123456789abcdef".repeat(usize::MAX);
```

 
[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#557-559)
```
pub fn concat<Item>(&self) -> <[T] as Concat<Item>>::Output ⓘ
where
    [T]: Concat<Item>,
    Item: ?Sized,
```

Flattens a slice of `T` into a single value `Self::Output`.

 ##### Examples

 
```
assert_eq!(["hello", "world"].concat(), "helloworld");
assert_eq!([[1, 2], [3, 4]].concat(), [1, 2, 3, 4]);
```
 
[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#576-578)1.3.0
```
pub fn join<Separator>(
    &self,
    sep: Separator
) -> <[T] as Join<Separator>>::Output ⓘ
where
    [T]: Join<Separator>,
```

Flattens a slice of `T` into a single value `Self::Output`, placing a given separator between each.

 ##### Examples

 
```
assert_eq!(["hello", "world"].join(" "), "hello world");
assert_eq!([[1, 2], [3, 4]].join(&0), [1, 2, 0, 3, 4]);
assert_eq!([[1, 2], [3, 4]].join(&[0, 0][..]), [1, 2, 0, 0, 3, 4]);
```
 
[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#596-598)
```
pub fn connect<Separator>(
    &self,
    sep: Separator
) -> <[T] as Join<Separator>>::Output ⓘ
where
    [T]: Join<Separator>,
```

👎Deprecated since 1.3.0: renamed to join

Flattens a slice of `T` into a single value `Self::Output`, placing a given separator between each.

 ##### Examples

 
```
assert_eq!(["hello", "world"].connect(" "), "hello world");
assert_eq!([[1, 2], [3, 4]].connect(&0), [1, 2, 0, 3, 4]);
```
 
[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#621)1.23.0
```
pub fn to_ascii_uppercase(&self) -> Vec<u8, Global> ⓘ
```

Returns a vector containing a copy of this slice where each byte is mapped to its ASCII upper case equivalent.

 ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, but non-ASCII letters are unchanged.

 To uppercase the value in-place, use [`make_ascii_uppercase`](../primitive.slice#method.make_ascii_uppercase "method slice::make_ascii_uppercase").

 
[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#642)1.23.0
```
pub fn to_ascii_lowercase(&self) -> Vec<u8, Global> ⓘ
```

Returns a vector containing a copy of this slice where each byte is mapped to its ASCII lower case equivalent.

 ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’, but non-ASCII letters are unchanged.

 To lowercase the value in-place, use [`make_ascii_lowercase`](../primitive.slice#method.make_ascii_lowercase "method slice::make_ascii_lowercase").

 
Trait Implementations
---------------------



[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3062)1.5.0
```
impl<T, A> AsMut<[T]> for Vec<T, A>
where
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3063)
```
fn as_mut(&mut self) -> &mut [T]
```
Converts this type into a mutable reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3048)1.5.0
```
impl<T, A> AsMut<Vec<T, A>> for Vec<T, A>
where
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3049)
```
fn as_mut(&mut self) -> &mut Vec<T, A>
```
Converts this type into a mutable reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3055)
```
impl<T, A> AsRef<[T]> for Vec<T, A>
where
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3056)
```
fn as_ref(&self) -> &[T]
```
Converts this type into a shared reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3041)
```
impl<T, A> AsRef<Vec<T, A>> for Vec<T, A>
where
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3042)
```
fn as_ref(&self) -> &Vec<T, A>
```
Converts this type into a shared reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#772)
```
impl<T, A> Borrow<[T]> for Vec<T, A>
where
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#773)
```
fn borrow(&self) -> &[T]
```
Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#779)
```
impl<T, A> BorrowMut<[T]> for Vec<T, A>
where
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#780)
```
fn borrow_mut(&mut self) -> &mut [T]
```
Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut)


[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2639)
```
impl<T, A> Clone for Vec<T, A>
where
    T: Clone,
    A: Allocator + Clone,
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2641)
```
fn clone(&self) -> Vec<T, A>
```
Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone)

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2656)
```
fn clone_from(&mut self, other: &Vec<T, A>)
```
Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from)


[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3034)
```
impl<T, A> Debug for Vec<T, A>
where
    T: Debug,
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3035)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt)


[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3024)
```
impl<T> Default for Vec<T, Global>
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3028)
```
fn default() -> Vec<T, Global>
```

Creates an empty `Vec<T>`.

 The vector will not allocate until elements are pushed onto it.

 

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2620)
```
impl<T, A> Deref for Vec<T, A>
where
    A: Allocator,
```


```
type Target = [T]
```
The resulting type after dereferencing.
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2624)
```
fn deref(&self) -> &[T]
```
Dereferences the value.

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2630)
```
impl<T, A> DerefMut for Vec<T, A>
where
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2632)
```
fn deref_mut(&mut self) -> &mut [T]
```
Mutably dereferences the value.

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3011)
```
impl<T, A> Drop for Vec<T, A>
where
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3012)
```
fn drop(&mut self)
```
Executes the destructor for this type. [Read more](../ops/trait.drop#tymethod.drop)


[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2973)1.2.0
```
impl<'a, T, A> Extend<&'a T> for Vec<T, A>
where
    T: Copy + 'a,
    A: Allocator + 'a,
```

Extend implementation that copies elements out of references before pushing them onto the Vec.

 This implementation is specialized for slice iterators, where it uses [`copy_from_slice`](../primitive.slice#method.copy_from_slice "method slice::copy_from_slice") to append the entire slice at once.

 

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2974)
```
fn extend<I>(&mut self, iter: I)
where
    I: IntoIterator<Item = &'a T>,
```
Extends a collection with the contents of an iterator. [Read more](../iter/trait.extend#tymethod.extend)

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2979)
```
fn extend_one(&mut self, _: &'a 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/src/alloc/vec/mod.rs.html#2984)
```
fn extend_reserve(&mut self, additional: usize)
```

🔬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](../iter/trait.extend#method.extend_reserve)


[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2782)
```
impl<T, A> Extend<T> for Vec<T, A>
where
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2784)
```
fn extend<I>(&mut self, iter: I)
where
    I: IntoIterator<Item = T>,
```
Extends a collection with the contents of an iterator. [Read more](../iter/trait.extend#tymethod.extend)

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2789)
```
fn 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/src/alloc/vec/mod.rs.html#2794)
```
fn extend_reserve(&mut self, additional: usize)
```

🔬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](../iter/trait.extend#method.extend_reserve)


[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3070)
```
impl<T> From<&[T]> for Vec<T, Global>
where
    T: Clone,
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3079)
```
fn from(s: &[T]) -> Vec<T, Global>
```

Allocate a `Vec<T>` and fill it by cloning `s`’s items.

 ##### Examples

 
```
assert_eq!(Vec::from(&[1, 2, 3][..]), vec![1, 2, 3]);
```
 

[source](https://doc.rust-lang.org/src/alloc/vec/cow.rs.html#32)1.28.0
```
impl<'a, T> From<&'a Vec<T, Global>> for Cow<'a, [T]>
where
    T: Clone,
```

[source](https://doc.rust-lang.org/src/alloc/vec/cow.rs.html#39)
```
fn from(v: &'a Vec<T, Global>) -> Cow<'a, [T]>
```

Creates a [`Borrowed`](../borrow/enum.cow#variant.Borrowed "variant std::borrow::Cow::Borrowed") variant of [`Cow`](../borrow/enum.cow "enum std::borrow::Cow") from a reference to [`Vec`](struct.vec "struct std::vec::Vec").

 This conversion does not allocate or clone the data.

 

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3090)1.19.0
```
impl<T> From<&mut [T]> for Vec<T, Global>
where
    T: Clone,
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3099)
```
fn from(s: &mut [T]) -> Vec<T, Global>
```

Allocate a `Vec<T>` and fill it by cloning `s`’s items.

 ##### Examples

 
```
assert_eq!(Vec::from(&mut [1, 2, 3][..]), vec![1, 2, 3]);
```
 

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3201)
```
impl From<&str> for Vec<u8, Global>
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3209)
```
fn from(s: &str) -> Vec<u8, Global> ⓘ
```

Allocate a `Vec<u8>` and fill it with a UTF-8 string.

 ##### Examples

 
```
assert_eq!(Vec::from("123"), vec![b'1', b'2', b'3']);
```
 

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3110)1.44.0
```
impl<T, const N: usize> From<[T; N]> for Vec<T, Global>
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3119)
```
fn from(s: [T; N]) -> Vec<T, Global>
```

Allocate a `Vec<T>` and move `s`’s items into it.

 ##### Examples

 
```
assert_eq!(Vec::from([1, 2, 3]), vec![1, 2, 3]);
```
 

[source](https://doc.rust-lang.org/src/alloc/collections/binary_heap/mod.rs.html#1668)1.5.0
```
impl<T> From<BinaryHeap<T>> for Vec<T, Global>
```

[source](https://doc.rust-lang.org/src/alloc/collections/binary_heap/mod.rs.html#1673)
```
fn from(heap: BinaryHeap<T>) -> Vec<T, Global>
```

Converts a `BinaryHeap<T>` into a `Vec<T>`.

 This conversion requires no data movement or allocation, and has constant time complexity.

 

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3156)1.18.0
```
impl<T, A> From<Box<[T], A>> for Vec<T, A>
where
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3166)
```
fn from(s: Box<[T], A>) -> Vec<T, A>
```

Convert a boxed slice into a vector by transferring ownership of the existing heap allocation.

 ##### Examples

 
```
let b: Box<[i32]> = vec![1, 2, 3].into_boxed_slice();
assert_eq!(Vec::from(b), vec![1, 2, 3]);
```
 

[source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#726)1.7.0
```
impl From<CString> for Vec<u8, Global>
```

[source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#731)
```
fn from(s: CString) -> Vec<u8, Global> ⓘ
```

Converts a [`CString`](../ffi/struct.cstring "struct std::ffi::CString") into a `[Vec](struct.vec "struct std::vec::Vec")<[u8](../primitive.u8 "primitive u8")>`.

 The conversion consumes the [`CString`](../ffi/struct.cstring "struct std::ffi::CString"), and removes the terminating NUL byte.

 

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3130)1.14.0
```
impl<'a, T> From<Cow<'a, [T]>> for Vec<T, Global>
where
    [T]: ToOwned<Owned = Vec<T, Global>>,
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3148)
```
fn from(s: Cow<'a, [T]>) -> Vec<T, Global>
```

Convert a clone-on-write slice into a vector.

 If `s` already owns a `Vec<T>`, it will be returned directly. If `s` is borrowing a slice, a new `Vec<T>` will be allocated and filled by cloning `s`’s items into it.

 ##### Examples

 
```
let o: Cow<'_, [i32]> = Cow::Owned(vec![1, 2, 3]);
let b: Cow<'_, [i32]> = Cow::Borrowed(&[1, 2, 3]);
assert_eq!(Vec::from(o), Vec::from(b));
```
 

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2854)1.14.0
```
impl From<String> for Vec<u8, Global>
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2869)
```
fn from(string: String) -> Vec<u8, Global> ⓘ
```

Converts the given [`String`](../string/struct.string "struct std::string::String") to a vector [`Vec`](struct.vec "struct std::vec::Vec") that holds values of type [`u8`](../primitive.u8 "primitive u8").

 ##### Examples

 Basic usage:

 
```
let s1 = String::from("hello world");
let v1 = Vec::from(s1);

for b in v1 {
    println!("{b}");
}
```
 

[source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#798)1.43.0
```
impl From<Vec<NonZeroU8, Global>> for CString
```

[source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#802)
```
fn from(v: Vec<NonZeroU8, Global>) -> CString
```

Converts a `[Vec](struct.vec "struct std::vec::Vec")<[NonZeroU8](../num/struct.nonzerou8 "struct std::num::NonZeroU8")>` into a [`CString`](../ffi/struct.cstring "struct std::ffi::CString") without copying nor checking for inner null bytes.

 

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3175)1.20.0
```
impl<T, A> From<Vec<T, A>> for Box<[T], A>
where
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3194)
```
fn from(v: Vec<T, A>) -> Box<[T], A>
```

Convert a vector into a boxed slice.

 If `v` has excess capacity, its items will be moved into a newly-allocated buffer with exactly the right capacity.

 ##### Examples

 
```
assert_eq!(Box::from(vec![1, 2, 3]), vec![1, 2, 3].into_boxed_slice());
```
 Any excess capacity is removed:

 
```
let mut vec = Vec::with_capacity(10);
vec.extend([1, 2, 3]);

assert_eq!(Box::from(vec), vec![1, 2, 3].into_boxed_slice());
```
 

[source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2836)1.10.0
```
impl<T, A> From<Vec<T, A>> for VecDeque<T, A>
where
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2846)
```
fn from(other: Vec<T, A>) -> VecDeque<T, A>
```

Turn a [`Vec<T>`](struct.vec "struct std::vec::Vec") into a [`VecDeque<T>`](../collections/struct.vecdeque "struct std::collections::VecDeque").

 This conversion is guaranteed to run in *O*(1) time and to not re-allocate the `Vec`’s buffer or allocate any additional memory.

 

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2748)1.21.0
```
impl<T> From<Vec<T, Global>> for Arc<[T]>
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2760)
```
fn from(v: Vec<T, Global>) -> Arc<[T]>
```

Allocate a reference-counted slice and move `v`’s items into it.

 ##### Example

 
```
let unique: Vec<i32> = vec![1, 2, 3];
let shared: Arc<[i32]> = Arc::from(unique);
assert_eq!(&[1, 2, 3], &shared[..]);
```
 

[source](https://doc.rust-lang.org/src/alloc/collections/binary_heap/mod.rs.html#1640)1.5.0
```
impl<T> From<Vec<T, Global>> for BinaryHeap<T>
where
    T: Ord,
```

[source](https://doc.rust-lang.org/src/alloc/collections/binary_heap/mod.rs.html#1644)
```
fn from(vec: Vec<T, Global>) -> BinaryHeap<T>
```

Converts a `Vec<T>` into a `BinaryHeap<T>`.

 This conversion happens in-place, and has *O*(*n*) time complexity.

 

[source](https://doc.rust-lang.org/src/alloc/vec/cow.rs.html#19)1.8.0
```
impl<'a, T> From<Vec<T, Global>> for Cow<'a, [T]>
where
    T: Clone,
```

[source](https://doc.rust-lang.org/src/alloc/vec/cow.rs.html#26)
```
fn from(v: Vec<T, Global>) -> Cow<'a, [T]>
```

Creates an [`Owned`](../borrow/enum.cow#variant.Owned "variant std::borrow::Cow::Owned") variant of [`Cow`](../borrow/enum.cow "enum std::borrow::Cow") from an owned instance of [`Vec`](struct.vec "struct std::vec::Vec").

 This conversion does not allocate or clone the data.

 

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2006)1.21.0
```
impl<T> From<Vec<T, Global>> for Rc<[T]>
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2018)
```
fn from(v: Vec<T, Global>) -> Rc<[T]>
```

Allocate a reference-counted slice and move `v`’s items into it.

 ##### Example

 
```
let original: Box<Vec<i32>> = Box::new(vec![1, 2, 3]);
let shared: Rc<Vec<i32>> = Rc::from(original);
assert_eq!(vec![1, 2, 3], *shared);
```
 

[source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2853)1.10.0
```
impl<T, A> From<VecDeque<T, A>> for Vec<T, A>
where
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2883)
```
fn from(other: VecDeque<T, A>) -> Vec<T, A>
```

Turn a [`VecDeque<T>`](../collections/struct.vecdeque "struct std::collections::VecDeque") into a [`Vec<T>`](struct.vec "struct std::vec::Vec").

 This never needs to re-allocate, but does need to do *O*(*n*) data movement if the circular buffer doesn’t happen to be at the beginning of the allocation.

 ##### Examples

 
```
use std::collections::VecDeque;

// This one is *O*(1).
let deque: VecDeque<_> = (1..5).collect();
let ptr = deque.as_slices().0.as_ptr();
let vec = Vec::from(deque);
assert_eq!(vec, [1, 2, 3, 4]);
assert_eq!(vec.as_ptr(), ptr);

// This one needs data rearranging.
let mut deque: VecDeque<_> = (1..5).collect();
deque.push_front(9);
deque.push_front(8);
let ptr = deque.as_slices().1.as_ptr();
let vec = Vec::from(deque);
assert_eq!(vec, [8, 9, 1, 2, 3, 4]);
assert_eq!(vec.as_ptr(), ptr);
```
 

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2708)
```
impl<T> FromIterator<T> for Vec<T, Global>
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2710)
```
fn from_iter<I>(iter: I) -> Vec<T, Global>
where
    I: IntoIterator<Item = T>,
```
Creates a value from an iterator. [Read more](../iter/trait.fromiterator#tymethod.from_iter)


[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2673)
```
impl<T, A> Hash for Vec<T, A>
where
    T: Hash,
    A: Allocator,
```

The hash of a vector is the same as that of the corresponding slice, as required by the `core::borrow::Borrow` implementation.

 
```
use std::hash::BuildHasher;

let b = std::collections::hash_map::RandomState::new();
let v: Vec<u8> = vec![0xa8, 0x3c, 0x09];
let s: &[u8] = &[0xa8, 0x3c, 0x09];
assert_eq!(b.hash_one(v), b.hash_one(s));
```
 

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2675)
```
fn hash<H>(&self, state: &mut H)
where
    H: Hasher,
```
Feeds this value into the given [`Hasher`](../hash/trait.hasher "trait std::hash::Hasher"). [Read more](../hash/trait.hash#tymethod.hash)

[source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#237-239)1.3.0
```
fn hash_slice<H>(data: &[Self], state: &mut H)
where
    H: Hasher,
    Self: Sized,
```
Feeds a slice of this type into the given [`Hasher`](../hash/trait.hasher "trait std::hash::Hasher"). [Read more](../hash/trait.hash#method.hash_slice)


[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2685)
```
impl<T, I, A> Index<I> for Vec<T, A>
where
    I: SliceIndex<[T]>,
    A: Allocator,
```


```
type Output = <I as SliceIndex<[T]>>::Output
```
The returned type after indexing.
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2689)
```
fn index(&self, index: I) -> &<Vec<T, A> as Index<I>>::Output ⓘ
```
Performs the indexing (`container[index]`) operation. [Read more](../ops/trait.index#tymethod.index)


[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2699)
```
impl<T, I, A> IndexMut<I> for Vec<T, A>
where
    I: SliceIndex<[T]>,
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2701)
```
fn index_mut(&mut self, index: I) -> &mut <Vec<T, A> as Index<I>>::Output ⓘ
```
Performs the mutable indexing (`container[index]`) operation. [Read more](../ops/trait.indexmut#tymethod.index_mut)


[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2761)
```
impl<'a, T, A> IntoIterator for &'a Vec<T, A>
where
    A: Allocator,
```


```
type Item = &'a T
```
The type of the elements being iterated over.

```
type IntoIter = Iter<'a, T>
```
Which kind of iterator are we turning this into?
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2765)
```
fn into_iter(self) -> <&'a Vec<T, A> as IntoIterator>::IntoIter ⓘ
```
Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter)


[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2771)
```
impl<'a, T, A> IntoIterator for &'a mut Vec<T, A>
where
    A: Allocator,
```


```
type Item = &'a mut T
```
The type of the elements being iterated over.

```
type IntoIter = IterMut<'a, T>
```
Which kind of iterator are we turning this into?
[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2775)
```
fn into_iter(self) -> <&'a mut Vec<T, A> as IntoIterator>::IntoIter ⓘ
```
Creates an iterator from a value. [Read more](../iter/trait.intoiterator#tymethod.into_iter)


[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2716)
```
impl<T, A> IntoIterator for Vec<T, A>
where
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2737)
```
fn into_iter(self) -> <Vec<T, A> as IntoIterator>::IntoIter ⓘ
```

Creates a consuming iterator, that is, one that moves each value out of the vector (from start to end). The vector cannot be used after calling this.

 ##### Examples

 
```
let v = vec!["a".to_string(), "b".to_string()];
let mut v_iter = v.into_iter();

let first_element: Option<String> = v_iter.next();

assert_eq!(first_element, Some("a".to_string()));
assert_eq!(v_iter.next(), Some("b".to_string()));
assert_eq!(v_iter.next(), None);
```
 

```
type Item = T
```
The type of the elements being iterated over.

```
type IntoIter = IntoIter<T, A>
```
Which kind of iterator are we turning this into?

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3003)
```
impl<T, A> Ord for Vec<T, A>
where
    T: Ord,
    A: Allocator,
```

Implements ordering of vectors, [lexicographically](../cmp/trait.ord#lexicographical-comparison "trait std::cmp::Ord").

 

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3005)
```
fn cmp(&self, other: &Vec<T, A>) -> Ordering
```
This method returns an [`Ordering`](../cmp/enum.ordering "enum std::cmp::Ordering") between `self` and `other`. [Read more](../cmp/trait.ord#tymethod.cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#790-792)1.21.0
```
fn max(self, other: Self) -> Self
where
    Self: Sized,
```
Compares and returns the maximum of two values. [Read more](../cmp/trait.ord#method.max)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#810-812)1.21.0
```
fn min(self, other: Self) -> Self
where
    Self: Sized,
```
Compares and returns the minimum of two values. [Read more](../cmp/trait.ord#method.min)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#835-838)1.50.0
```
fn clamp(self, min: Self, max: Self) -> Self
where
    Self: Sized + PartialOrd<Self>,
```
Restrict a value to a certain interval. [Read more](../cmp/trait.ord#method.clamp)


[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#24)
```
impl<T, U, A> PartialEq<&[U]> for Vec<T, A>
where
    A: Allocator,
    T: PartialEq<U>,
```

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#24)
```
fn eq(&self, other: &&[U]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#24)
```
fn ne(&self, other: &&[U]) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#37)
```
impl<T, U, A, const N: usize> PartialEq<&[U; N]> for Vec<T, A>
where
    A: Allocator,
    T: PartialEq<U>,
```

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#37)
```
fn eq(&self, other: &&[U; N]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#37)
```
fn ne(&self, other: &&[U; N]) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#25)
```
impl<T, U, A> PartialEq<&mut [U]> for Vec<T, A>
where
    A: Allocator,
    T: PartialEq<U>,
```

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#25)
```
fn eq(&self, other: &&mut [U]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#25)
```
fn ne(&self, other: &&mut [U]) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#28)1.48.0
```
impl<T, U, A> PartialEq<[U]> for Vec<T, A>
where
    A: Allocator,
    T: PartialEq<U>,
```

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#28)
```
fn eq(&self, other: &[U]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#28)
```
fn ne(&self, other: &[U]) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#36)
```
impl<T, U, A, const N: usize> PartialEq<[U; N]> for Vec<T, A>
where
    A: Allocator,
    T: PartialEq<U>,
```

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#36)
```
fn eq(&self, other: &[U; N]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#36)
```
fn ne(&self, other: &[U; N]) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#26)1.46.0
```
impl<T, U, A> PartialEq<Vec<U, A>> for &[T]
where
    A: Allocator,
    T: PartialEq<U>,
```

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#26)
```
fn eq(&self, other: &Vec<U, A>) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#26)
```
fn ne(&self, other: &Vec<U, A>) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#27)1.46.0
```
impl<T, U, A> PartialEq<Vec<U, A>> for &mut [T]
where
    A: Allocator,
    T: PartialEq<U>,
```

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#27)
```
fn eq(&self, other: &Vec<U, A>) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#27)
```
fn ne(&self, other: &Vec<U, A>) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#29)1.48.0
```
impl<T, U, A> PartialEq<Vec<U, A>> for [T]
where
    A: Allocator,
    T: PartialEq<U>,
```

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#29)
```
fn eq(&self, other: &Vec<U, A>) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#29)
```
fn ne(&self, other: &Vec<U, A>) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#31)
```
impl<T, U, A> PartialEq<Vec<U, A>> for Cow<'_, [T]>
where
    A: Allocator,
    T: PartialEq<U> + Clone,
```

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#31)
```
fn eq(&self, other: &Vec<U, A>) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#31)
```
fn ne(&self, other: &Vec<U, A>) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2701)1.17.0
```
impl<T, U, A> PartialEq<Vec<U, A>> for VecDeque<T, A>
where
    A: Allocator,
    T: PartialEq<U>,
```

[source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2701)
```
fn eq(&self, other: &Vec<U, A>) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#226)
```
fn ne(&self, other: &Rhs) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#23)
```
impl<T, U, A1, A2> PartialEq<Vec<U, A2>> for Vec<T, A1>
where
    A1: Allocator,
    A2: Allocator,
    T: PartialEq<U>,
```

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#23)
```
fn eq(&self, other: &Vec<U, A2>) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#23)
```
fn ne(&self, other: &Vec<U, A2>) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2991)
```
impl<T, A> PartialOrd<Vec<T, A>> for Vec<T, A>
where
    T: PartialOrd<T>,
    A: Allocator,
```

Implements comparison of vectors, [lexicographically](../cmp/trait.ord#lexicographical-comparison "trait std::cmp::Ord").

 

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2993)
```
fn partial_cmp(&self, other: &Vec<T, A>) -> Option<Ordering>
```
This method returns an ordering between `self` and `other` values if one exists. [Read more](../cmp/trait.partialord#tymethod.partial_cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1067)
```
fn lt(&self, other: &Rhs) -> bool
```
This method tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](../cmp/trait.partialord#method.lt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1084)
```
fn le(&self, other: &Rhs) -> bool
```
This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](../cmp/trait.partialord#method.le)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1100)
```
fn gt(&self, other: &Rhs) -> bool
```
This method tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](../cmp/trait.partialord#method.gt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1117)
```
fn ge(&self, other: &Rhs) -> bool
```
This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](../cmp/trait.partialord#method.ge)


[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3215)1.48.0
```
impl<T, A, const N: usize> TryFrom<Vec<T, A>> for [T; N]
where
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3244)
```
fn try_from(vec: Vec<T, A>) -> Result<[T; N], Vec<T, A>>
```

Gets the entire contents of the `Vec<T>` as an array, if its size exactly matches that of the requested array.

 ##### Examples

 
```
assert_eq!(vec![1, 2, 3].try_into(), Ok([1, 2, 3]));
assert_eq!(<Vec<i32>>::new().try_into(), Ok([]));
```
 If the length doesn’t match, the input comes back in `Err`:

 
```
let r: Result<[i32; 4], _> = (0..10).collect::<Vec<_>>().try_into();
assert_eq!(r, Err(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
```
 If you’re fine with just getting a prefix of the `Vec<T>`, you can call [`.truncate(N)`](struct.vec#method.truncate "method std::vec::Vec::truncate") first.

 
```
let mut v = String::from("hello world").into_bytes();
v.sort();
v.truncate(2);
let [a, b]: [_; 2] = v.try_into().unwrap();
assert_eq!(a, b' ');
assert_eq!(b, b'd');
```
 

```
type Error = Vec<T, A>
```
The type returned in the event of a conversion error.

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1663)1.66.0
```
impl<T, const N: usize> TryFrom<Vec<T, Global>> for Box<[T; N], Global>
```

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1684)
```
fn try_from(
    vec: Vec<T, Global>
) -> Result<Box<[T; N], Global>, <Box<[T; N], Global> as TryFrom<Vec<T, Global>>>::Error>
```

Attempts to convert a `Vec<T>` into a `Box<[T; N]>`.

 Like [`Vec::into_boxed_slice`](struct.vec#method.into_boxed_slice "method std::vec::Vec::into_boxed_slice"), this is in-place if `vec.capacity() == N`, but will require a reallocation otherwise.

 ##### Errors

 Returns the original `Vec<T>` in the `Err` variant if `boxed_slice.len()` does not equal `N`.

 ##### Examples

 This can be used with [`vec!`](../macro.vec "macro std::vec") to create an array on the heap:

 
```
let state: Box<[f32; 100]> = vec![1.0; 100].try_into().unwrap();
assert_eq!(state.len(), 100);
```
 

```
type Error = Vec<T, Global>
```
The type returned in the event of a conversion error.

[source](https://doc.rust-lang.org/src/std/io/impls.rs.html#393-425)
```
impl<A: Allocator> Write for Vec<u8, A>
```

Write is implemented for `Vec<u8>` by appending to the vector. The vector will grow as needed.

 

[source](https://doc.rust-lang.org/src/std/io/impls.rs.html#395-398)
```
fn write(&mut self, buf: &[u8]) -> Result<usize>
```
Write a buffer into this writer, returning how many bytes were written. [Read more](../io/trait.write#tymethod.write)

[source](https://doc.rust-lang.org/src/std/io/impls.rs.html#401-408)
```
fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize>
```
Like [`write`](../io/trait.write#tymethod.write "method std::io::Write::write"), except that it writes from a slice of buffers. [Read more](../io/trait.write#method.write_vectored)

[source](https://doc.rust-lang.org/src/std/io/impls.rs.html#411-413)
```
fn is_write_vectored(&self) -> bool
```

🔬This is a nightly-only experimental API. (`can_vector` [#69941](https://github.com/rust-lang/rust/issues/69941))
Determines if this `Write`r has an efficient [`write_vectored`](../io/trait.write#method.write_vectored "method std::io::Write::write_vectored") implementation. [Read more](../io/trait.write#method.is_write_vectored)

[source](https://doc.rust-lang.org/src/std/io/impls.rs.html#416-419)
```
fn write_all(&mut self, buf: &[u8]) -> Result<()>
```
Attempts to write an entire buffer into this writer. [Read more](../io/trait.write#method.write_all)

[source](https://doc.rust-lang.org/src/std/io/impls.rs.html#422-424)
```
fn flush(&mut self) -> Result<()>
```
Flush this output stream, ensuring that all intermediately buffered contents reach their destination. [Read more](../io/trait.write#tymethod.flush)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1636-1654)
```
fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<()>
```

🔬This is a nightly-only experimental API. (`write_all_vectored` [#70436](https://github.com/rust-lang/rust/issues/70436))
Attempts to write multiple buffers into this writer. [Read more](../io/trait.write#method.write_all_vectored)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1692-1724)
```
fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result<()>
```
Writes a formatted string into this writer, returning any error encountered. [Read more](../io/trait.write#method.write_fmt)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1748-1753)
```
fn by_ref(&mut self) -> &mut Self
where
    Self: Sized,
```
Creates a “by reference” adapter for this instance of `Write`. [Read more](../io/trait.write#method.by_ref)


[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2999)
```
impl<T, A> Eq for Vec<T, A>
where
    T: Eq,
    A: Allocator,
```


Auto Trait Implementations
--------------------------




```
impl<T, A> RefUnwindSafe for Vec<T, A>
where
    A: RefUnwindSafe,
    T: RefUnwindSafe,
```

```
impl<T, A> Send for Vec<T, A>
where
    A: Send,
    T: Send,
```

```
impl<T, A> Sync for Vec<T, A>
where
    A: Sync,
    T: Sync,
```

```
impl<T, A> Unpin for Vec<T, A>
where
    A: Unpin,
    T: Unpin,
```

```
impl<T, A> UnwindSafe for Vec<T, A>
where
    A: UnwindSafe,
    T: UnwindSafe,
```


Blanket Implementations
-----------------------



[source](https://doc.rust-lang.org/src/core/any.rs.html#200)
```
impl<T> Any for T
where
    T: 'static + ?Sized,
```

[source](https://doc.rust-lang.org/src/core/any.rs.html#201)
```
fn type_id(&self) -> TypeId
```
Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#208)
```
impl<T> Borrow<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#210)
```
fn borrow(&self) -> &T
```
Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#216)
```
impl<T> BorrowMut<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#217)
```
fn borrow_mut(&mut self) -> &mut T
```
Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#723)
```
impl<T> From<T> for T
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#726)
```
fn from(t: T) -> T
```

Returns the argument unchanged.

 

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#707)
```
impl<T, U> Into<U> for T
where
    U: From<T>,
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#716)
```
fn into(self) -> U
```

Calls `U::from(self)`.

 That is, this conversion is whatever the implementation of `[From](../convert/trait.from "trait std::convert::From")<T> for U` chooses to do.

 

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#82)
```
impl<T> ToOwned for T
where
    T: Clone,
```


```
type Owned = T
```
The resulting type after obtaining ownership.
[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#87)
```
fn to_owned(&self) -> T
```
Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned)

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#91)
```
fn clone_into(&self, target: &mut T)
```
Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#763)
```
impl<T, U> TryFrom<U> for T
where
    U: Into<T>,
```


```
type Error = Infallible
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#770)
```
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#748)
```
impl<T, U> TryInto<U> for T
where
    U: TryFrom<T>,
```


```
type Error = <U as TryFrom<T>>::Error
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#755)
```
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
```
Performs the conversion.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/vec/struct.Vec.html>

Module std::sync::atomic
========================


Atomic types

 Atomic types provide primitive shared-memory communication between threads, and are the building blocks of other concurrent types.

 Rust atomics currently follow the same rules as [C++20 atomics](https://en.cppreference.com/w/cpp/atomic), specifically `atomic_ref`. Basically, creating a *shared reference* to one of the Rust atomic types corresponds to creating an `atomic_ref` in C++; the `atomic_ref` is destroyed when the lifetime of the shared reference ends. (A Rust atomic type that is exclusively owned or behind a mutable reference does *not* correspond to an “atomic object” in C++, since it can be accessed via non-atomic operations.)

 This module defines atomic versions of a select number of primitive types, including [`AtomicBool`](struct.atomicbool "struct std::sync::atomic::AtomicBool"), [`AtomicIsize`](struct.atomicisize "struct std::sync::atomic::AtomicIsize"), [`AtomicUsize`](struct.atomicusize "struct std::sync::atomic::AtomicUsize"), [`AtomicI8`](struct.atomici8 "struct std::sync::atomic::AtomicI8"), [`AtomicU16`](struct.atomicu16 "struct std::sync::atomic::AtomicU16"), etc. Atomic types present operations that, when used correctly, synchronize updates between threads.

 Each method takes an [`Ordering`](enum.ordering "enum std::sync::atomic::Ordering") which represents the strength of the memory barrier for that operation. These orderings are the same as the [C++20 atomic orderings](https://en.cppreference.com/w/cpp/atomic/memory_order). For more information see the [nomicon](https://doc.rust-lang.org/nomicon/atomics.html).

 Atomic variables are safe to share between threads (they implement [`Sync`](../../marker/trait.sync "trait std::marker::Sync")) but they do not themselves provide the mechanism for sharing and follow the [threading model](../../thread/index#the-threading-model) of Rust. The most common way to share an atomic variable is to put it into an [`Arc`](../struct.arc) (an atomically-reference-counted shared pointer).

 Atomic types may be stored in static variables, initialized using the constant initializers like [`AtomicBool::new`](struct.atomicbool#method.new "associated function std::sync::atomic::AtomicBool::new"). Atomic statics are often used for lazy global initialization.

 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.

 Examples
--------

 A simple spinlock:

 
```
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::SeqCst);
    });

    // Wait for the other thread to release the lock
    while spinlock.load(Ordering::SeqCst) != 0 {
        hint::spin_loop();
    }

    if let Err(panic) = thread.join() {
        println!("Thread had an error: {panic:?}");
    }
}
```
 Keep a global count of live threads:

 
```
use std::sync::atomic::{AtomicUsize, Ordering};

static GLOBAL_THREAD_COUNT: AtomicUsize = AtomicUsize::new(0);

let old_thread_count = GLOBAL_THREAD_COUNT.fetch_add(1, Ordering::SeqCst);
println!("live threads: {}", old_thread_count + 1);
```
 Structs
-------


* [AtomicBool](struct.atomicbool "struct std::sync::atomic::AtomicBool")
A boolean type which can be safely shared between threads.
* [AtomicI8](struct.atomici8 "struct std::sync::atomic::AtomicI8")
An integer type which can be safely shared between threads.
* [AtomicI16](struct.atomici16 "struct std::sync::atomic::AtomicI16")
An integer type which can be safely shared between threads.
* [AtomicI32](struct.atomici32 "struct std::sync::atomic::AtomicI32")
An integer type which can be safely shared between threads.
* [AtomicI64](struct.atomici64 "struct std::sync::atomic::AtomicI64")
An integer type which can be safely shared between threads.
* [AtomicIsize](struct.atomicisize "struct std::sync::atomic::AtomicIsize")
An integer type which can be safely shared between threads.
* [AtomicPtr](struct.atomicptr "struct std::sync::atomic::AtomicPtr")
A raw pointer type which can be safely shared between threads.
* [AtomicU8](struct.atomicu8 "struct std::sync::atomic::AtomicU8")
An integer type which can be safely shared between threads.
* [AtomicU16](struct.atomicu16 "struct std::sync::atomic::AtomicU16")
An integer type which can be safely shared between threads.
* [AtomicU32](struct.atomicu32 "struct std::sync::atomic::AtomicU32")
An integer type which can be safely shared between threads.
* [AtomicU64](struct.atomicu64 "struct std::sync::atomic::AtomicU64")
An integer type which can be safely shared between threads.
* [AtomicUsize](struct.atomicusize "struct std::sync::atomic::AtomicUsize")
An integer type which can be safely shared between threads.


Enums
-----


* [Ordering](enum.ordering "enum std::sync::atomic::Ordering")
Atomic memory orderings


Constants
---------


* [ATOMIC\_I8\_INIT](constant.atomic_i8_init "constant std::sync::atomic::ATOMIC_I8_INIT")DeprecatedExperimental

An atomic integer initialized to `0`.
* [ATOMIC\_I16\_INIT](constant.atomic_i16_init "constant std::sync::atomic::ATOMIC_I16_INIT")DeprecatedExperimental

An atomic integer initialized to `0`.
* [ATOMIC\_I32\_INIT](constant.atomic_i32_init "constant std::sync::atomic::ATOMIC_I32_INIT")DeprecatedExperimental

An atomic integer initialized to `0`.
* [ATOMIC\_I64\_INIT](constant.atomic_i64_init "constant std::sync::atomic::ATOMIC_I64_INIT")DeprecatedExperimental

An atomic integer initialized to `0`.
* [ATOMIC\_U8\_INIT](constant.atomic_u8_init "constant std::sync::atomic::ATOMIC_U8_INIT")DeprecatedExperimental

An atomic integer initialized to `0`.
* [ATOMIC\_U16\_INIT](constant.atomic_u16_init "constant std::sync::atomic::ATOMIC_U16_INIT")DeprecatedExperimental

An atomic integer initialized to `0`.
* [ATOMIC\_U32\_INIT](constant.atomic_u32_init "constant std::sync::atomic::ATOMIC_U32_INIT")DeprecatedExperimental

An atomic integer initialized to `0`.
* [ATOMIC\_U64\_INIT](constant.atomic_u64_init "constant std::sync::atomic::ATOMIC_U64_INIT")DeprecatedExperimental

An atomic integer initialized to `0`.
* [ATOMIC\_BOOL\_INIT](constant.atomic_bool_init "constant std::sync::atomic::ATOMIC_BOOL_INIT")Deprecated

An [`AtomicBool`](struct.atomicbool "struct std::sync::atomic::AtomicBool") initialized to `false`.
* [ATOMIC\_ISIZE\_INIT](constant.atomic_isize_init "constant std::sync::atomic::ATOMIC_ISIZE_INIT")Deprecated

An atomic integer initialized to `0`.
* [ATOMIC\_USIZE\_INIT](constant.atomic_usize_init "constant std::sync::atomic::ATOMIC_USIZE_INIT")Deprecated

An atomic integer initialized to `0`.


Functions
---------


* [compiler\_fence](fn.compiler_fence "fn std::sync::atomic::compiler_fence")
A compiler memory fence.
* [fence](fn.fence "fn std::sync::atomic::fence")
An atomic fence.
* [spin\_loop\_hint](fn.spin_loop_hint "fn std::sync::atomic::spin_loop_hint")Deprecated

Signals the processor that it is inside a busy-wait spin-loop (“spin lock”).



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/sync/atomic/index.html>

Unions
======

 
>  **Syntax**  
>  *Union* :  
>  `union` [IDENTIFIER](../identifiers) [*GenericParams*](generics)? [*WhereClause*](generics#where-clauses)? `{`[*StructFields*](structs) `}`
> 
>  

 A union declaration uses the same syntax as a struct declaration, except with `union` in place of `struct`.

 
```
#![allow(unused)]
fn main() {
#[repr(C)]
union MyUnion {
    f1: u32,
    f2: f32,
}
}
```
 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.

 Union field types are restricted to the following subset of types:

 * `Copy` types
* References (`&T` and `&mut T` for arbitrary `T`)
* `ManuallyDrop<T>` (for arbitrary `T`)
* Tuples and arrays containing only allowed union field types

 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.

 Initialization of a union
-------------------------

 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 };
}
```
 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 };
}
```
 Reading and writing union fields
--------------------------------

 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. Reading a union field reads the bits of the union at the field's type. Fields might have a non-zero offset (except when [the C representation](../type-layout#reprc-unions) is used); in that case the bits starting at the offset of the fields are read. 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](../behavior-considered-undefined). For example, reading the value `3` from a field of the [boolean type](../types/boolean) is undefined behavior. Effectively, writing to and then reading from a union with [the C representation](../type-layout#reprc-unions) is analogous to a [`transmute`](../../std/mem/fn.transmute) from the type used for writing to the type used for reading.

 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.

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

 Pattern matching on unions
--------------------------

 Another way to access union fields is to use pattern matching. Pattern matching on union fields uses the same syntax as struct patterns, except that the pattern must specify exactly one field. 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); }
        }
    }
}
}
```
 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,
        }
    }
}
}
```
 References to union fields
--------------------------

 Since union fields share common storage, gaining write access to one field of a union can give write access to all its remaining fields. 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);
}
}
```
 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).



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/items/unions.html>

Macros By Example
=================

 
>  **Syntax**  
>  *MacroRulesDefinition* :  
>  `macro_rules` `!` [IDENTIFIER](identifiers) *MacroRulesDef*
> 
>  *MacroRulesDef* :  
>  `(` *MacroRules* `)` `;`  
>  | `[` *MacroRules* `]` `;`  
>  | `{` *MacroRules* `}`
> 
>  *MacroRules* :  
>  *MacroRule* ( `;` *MacroRule* )\* `;`?
> 
>  *MacroRule* :  
>  *MacroMatcher* `=>` *MacroTranscriber*
> 
>  *MacroMatcher* :  
>  `(` *MacroMatch*\* `)`  
>  | `[` *MacroMatch*\* `]`  
>  | `{` *MacroMatch*\* `}`
> 
>  *MacroMatch* :  
>  [*Token*](tokens)*except `$` and [delimiters](tokens#delimiters)*  
>  | *MacroMatcher*  
>  | `$` ( [IDENTIFIER\_OR\_KEYWORD](identifiers) *except `crate`* | [RAW\_IDENTIFIER](identifiers) | `_` ) `:` *MacroFragSpec*  
>  | `$` `(` *MacroMatch*+ `)` *MacroRepSep*? *MacroRepOp*
> 
>  *MacroFragSpec* :  
>  `block` | `expr` | `ident` | `item` | `lifetime` | `literal`  
>  | `meta` | `pat` | `pat_param` | `path` | `stmt` | `tt` | `ty` | `vis`
> 
>  *MacroRepSep* :  
>  [*Token*](tokens)*except [delimiters](tokens#delimiters) and MacroRepOp*
> 
>  *MacroRepOp* :  
>  `*` | `+` | `?`
> 
>  *MacroTranscriber* :  
>  [*DelimTokenTree*](macros)
> 
>  

 `macro_rules` allows users to define syntax extension in a declarative way. We call such extensions "macros by example" or simply "macros".

 Each macro by example has a name, and one or more *rules*. Each rule has two parts: a *matcher*, describing the syntax that it matches, and a *transcriber*, describing the syntax that will replace a successfully matched invocation. Both the matcher and the transcriber must be surrounded by delimiters. Macros can expand to expressions, statements, items (including traits, impls, and foreign items), types, or patterns.

 Transcribing
------------

 When a macro is invoked, the macro expander looks up macro invocations by name, and tries each macro rule in turn. It transcribes the first successful match; if this results in an error, then future matches are not tried. When matching, no lookahead is performed; if the compiler cannot unambiguously determine how to parse the macro invocation one token at a time, then it is an error. In the following example, the compiler does not look ahead past the identifier to see if the following token is a `)`, even though that would allow it to parse the invocation unambiguously:

 
```
#![allow(unused)]
fn main() {
macro_rules! ambiguity {
    ($($i:ident)* $j:ident) => { };
}

ambiguity!(error); // Error: local ambiguity
}
```
 In both the matcher and the transcriber, the `$` token is used to invoke special behaviours from the macro engine (described below in [Metavariables](#metavariables) and [Repetitions](#repetitions)). Tokens that aren't part of such an invocation are matched and transcribed literally, with one exception. The exception is that the outer delimiters for the matcher will match any pair of delimiters. Thus, for instance, the matcher `(())` will match `{()}` but not `{{}}`. The character `$` cannot be matched or transcribed literally.

 ### Forwarding a matched fragment

 When forwarding a matched fragment to another macro-by-example, matchers in the second macro will see an opaque AST of the fragment type. The second macro can't use literal tokens to match the fragments in the matcher, only a fragment specifier of the same type. The `ident`, `lifetime`, and `tt` fragment types are an exception, and *can* be matched by literal tokens. The following illustrates this restriction:

 
```
#![allow(unused)]
fn main() {
macro_rules! foo {
    ($l:expr) => { bar!($l); }
// ERROR:               ^^ no rules expected this token in macro call
}

macro_rules! bar {
    (3) => {}
}

foo!(3);
}
```
 The following illustrates how tokens can be directly matched after matching a `tt` fragment:

 
```
#![allow(unused)]
fn main() {
// compiles OK
macro_rules! foo {
    ($l:tt) => { bar!($l); }
}

macro_rules! bar {
    (3) => {}
}

foo!(3);
}
```
 Metavariables
-------------

 In the matcher, `$` *name* `:` *fragment-specifier* matches a Rust syntax fragment of the kind specified and binds it to the metavariable `$`*name*. Valid fragment specifiers are:

 * `item`: an [*Item*](items)
* `block`: a [*BlockExpression*](expressions/block-expr)
* `stmt`: a [*Statement*](statements) without the trailing semicolon (except for item statements that require semicolons)
* `pat_param`: a [*PatternNoTopAlt*](patterns)
* `pat`: at least any [*PatternNoTopAlt*](patterns), and possibly more depending on edition
* `expr`: an [*Expression*](expressions)
* `ty`: a [*Type*](types#type-expressions)
* `ident`: an [IDENTIFIER\_OR\_KEYWORD](identifiers) or [RAW\_IDENTIFIER](identifiers)
* `path`: a [*TypePath*](paths#paths-in-types) style path
* `tt`: a [*TokenTree*](macros#macro-invocation) (a single [token](tokens) or tokens in matching delimiters `()`, `[]`, or `{}`)
* `meta`: an [*Attr*](attributes), the contents of an attribute
* `lifetime`: a [LIFETIME\_TOKEN](tokens#lifetimes-and-loop-labels)
* `vis`: a possibly empty [*Visibility*](visibility-and-privacy) qualifier
* `literal`: matches `-`?[*LiteralExpression*](expressions/literal-expr)

 In the transcriber, metavariables are referred to simply by `$`*name*, since the fragment kind is specified in the matcher. Metavariables are replaced with the syntax element that matched them. The keyword metavariable `$crate` can be used to refer to the current crate; see [Hygiene](#hygiene) below. Metavariables can be transcribed more than once or not at all.

 For reasons of backwards compatibility, though `_` [is also an expression](expressions/underscore-expr), a standalone underscore is not matched by the `expr` fragment specifier. However, `_` is matched by the `expr` fragment specifier when it appears as a subexpression.

 
>  **Edition Differences**: Starting with the 2021 edition, `pat` fragment-specifiers match top-level or-patterns (that is, they accept [*Pattern*](patterns)).
> 
>  Before the 2021 edition, they match exactly the same fragments as `pat_param` (that is, they accept [*PatternNoTopAlt*](patterns)).
> 
>  The relevant edition is the one in effect for the `macro_rules!` definition.
> 
>  

 Repetitions
-----------

 In both the matcher and transcriber, repetitions are indicated by placing the tokens to be repeated inside `$(`…`)`, followed by a repetition operator, optionally with a separator token between. The separator token can be any token other than a delimiter or one of the repetition operators, but `;` and `,` are the most common. For instance, `$( $i:ident ),*` represents any number of identifiers separated by commas. Nested repetitions are permitted.

 The repetition operators are:

 * `*` — indicates any number of repetitions.
* `+` — indicates any number but at least one.
* `?` — indicates an optional fragment with zero or one occurrence.

 Since `?` represents at most one occurrence, it cannot be used with a separator.

 The repeated fragment both matches and transcribes to the specified number of the fragment, separated by the separator token. Metavariables are matched to every repetition of their corresponding fragment. For instance, the `$( $i:ident ),*` example above matches `$i` to all of the identifiers in the list.

 During transcription, additional restrictions apply to repetitions so that the compiler knows how to expand them properly:

 1. A metavariable must appear in exactly the same number, kind, and nesting order of repetitions in the transcriber as it did in the matcher. So for the matcher `$( $i:ident ),*`, the transcribers `=> { $i }`, `=> { $( $( $i)* )* }`, and `=> { $( $i )+ }` are all illegal, but `=> { $( $i );* }` is correct and replaces a comma-separated list of identifiers with a semicolon-separated list.
2. Each repetition in the transcriber must contain at least one metavariable to decide how many times to expand it. If multiple metavariables appear in the same repetition, they must be bound to the same number of fragments. For instance, `( $( $i:ident ),* ; $( $j:ident ),* ) => (( $( ($i,$j) ),* ))` must bind the same number of `$i` fragments as `$j` fragments. This means that invoking the macro with `(a, b, c; d, e, f)` is legal and expands to `((a,d), (b,e), (c,f))`, but `(a, b, c; d, e)` is illegal because it does not have the same number. This requirement applies to every layer of nested repetitions.

 Scoping, Exporting, and Importing
---------------------------------

 For historical reasons, the scoping of macros by example does not work entirely like items. Macros have two forms of scope: textual scope, and path-based scope. Textual scope is based on the order that things appear in source files, or even across multiple files, and is the default scoping. It is explained further below. Path-based scope works exactly the same way that item scoping does. The scoping, exporting, and importing of macros is controlled largely by attributes.

 When a macro is invoked by an unqualified identifier (not part of a multi-part path), it is first looked up in textual scoping. If this does not yield any results, then it is looked up in path-based scoping. If the macro's name is qualified with a path, then it is only looked up in path-based scoping.

 
```
use lazy_static::lazy_static; // Path-based import.

macro_rules! lazy_static { // Textual definition.
    (lazy) => {};
}

lazy_static!{lazy} // Textual lookup finds our macro first.
self::lazy_static!{} // Path-based lookup ignores our macro, finds imported one.
```
 ### Textual Scope

 Textual scope is based largely on the order that things appear in source files, and works similarly to the scope of local variables declared with `let` except it also applies at the module level. When `macro_rules!` is used to define a macro, the macro enters the scope after the definition (note that it can still be used recursively, since names are looked up from the invocation site), up until its surrounding scope, typically a module, is closed. This can enter child modules and even span across multiple files:

 
```
//// src/lib.rs
mod has_macro {
    // m!{} // Error: m is not in scope.

    macro_rules! m {
        () => {};
    }
    m!{} // OK: appears after declaration of m.

    mod uses_macro;
}

// m!{} // Error: m is not in scope.

//// src/has_macro/uses_macro.rs

m!{} // OK: appears after declaration of m in src/lib.rs
```
 It is not an error to define a macro multiple times; the most recent declaration will shadow the previous one unless it has gone out of scope.

 
```
#![allow(unused)]
fn main() {
macro_rules! m {
    (1) => {};
}

m!(1);

mod inner {
    m!(1);

    macro_rules! m {
        (2) => {};
    }
    // m!(1); // Error: no rule matches '1'
    m!(2);

    macro_rules! m {
        (3) => {};
    }
    m!(3);
}

m!(1);
}
```
 Macros can be declared and used locally inside functions as well, and work similarly:

 
```
#![allow(unused)]
fn main() {
fn foo() {
    // m!(); // Error: m is not in scope.
    macro_rules! m {
        () => {};
    }
    m!();
}


// m!(); // Error: m is not in scope.
}
```
 ### The `macro_use` attribute

 The *`macro_use` attribute* has two purposes. First, it can be used to make a module's macro scope not end when the module is closed, by applying it to a module:

 
```
#![allow(unused)]
fn main() {
#[macro_use]
mod inner {
    macro_rules! m {
        () => {};
    }
}

m!();
}
```
 Second, it can be used to import macros from another crate, by attaching it to an `extern crate` declaration appearing in the crate's root module. Macros imported this way are imported into the [`macro_use` prelude](names/preludes#macro_use-prelude), not textually, which means that they can be shadowed by any other name. While macros imported by `#[macro_use]` can be used before the import statement, in case of a conflict, the last macro imported wins. Optionally, a list of macros to import can be specified using the [*MetaListIdents*](attributes#meta-item-attribute-syntax) syntax; this is not supported when `#[macro_use]` is applied to a module.

 
```
#[macro_use(lazy_static)] // Or #[macro_use] to import all macros.
extern crate lazy_static;

lazy_static!{}
// self::lazy_static!{} // Error: lazy_static is not defined in `self`
```
 Macros to be imported with `#[macro_use]` must be exported with `#[macro_export]`, which is described below.

 ### Path-Based Scope

 By default, a macro has no path-based scope. However, if it has the `#[macro_export]` attribute, then it is declared in the crate root scope and can be referred to normally as such:

 
```
#![allow(unused)]
fn main() {
self::m!();
m!(); // OK: Path-based lookup finds m in the current module.

mod inner {
    super::m!();
    crate::m!();
}

mod mac {
    #[macro_export]
    macro_rules! m {
        () => {};
    }
}
}
```
 Macros labeled with `#[macro_export]` are always `pub` and can be referred to by other crates, either by path or by `#[macro_use]` as described above.

 Hygiene
-------

 By default, all identifiers referred to in a macro are expanded as-is, and are looked up at the macro's invocation site. This can lead to issues if a macro refers to an item or macro which isn't in scope at the invocation site. To alleviate this, the `$crate` metavariable can be used at the start of a path to force lookup to occur inside the crate defining the macro.

 
```
//// Definitions in the `helper_macro` crate.
#[macro_export]
macro_rules! helped {
    // () => { helper!() } // This might lead to an error due to 'helper' not being in scope.
    () => { $crate::helper!() }
}

#[macro_export]
macro_rules! helper {
    () => { () }
}

//// Usage in another crate.
// Note that `helper_macro::helper` is not imported!
use helper_macro::helped;

fn unit() {
    helped!();
}
```
 Note that, because `$crate` refers to the current crate, it must be used with a fully qualified module path when referring to non-macro items:

 
```
#![allow(unused)]
fn main() {
pub mod inner {
    #[macro_export]
    macro_rules! call_foo {
        () => { $crate::inner::foo() };
    }

    pub fn foo() {}
}
}
```
 Additionally, even though `$crate` allows a macro to refer to items within its own crate when expanding, its use has no effect on visibility. An item or macro referred to must still be visible from the invocation site. In the following example, any attempt to invoke `call_foo!()` from outside its crate will fail because `foo()` is not public.

 
```
#![allow(unused)]
fn main() {
#[macro_export]
macro_rules! call_foo {
    () => { $crate::foo() };
}

fn foo() {}
}
```
 
>  **Version & Edition Differences**: Prior to Rust 1.30, `$crate` and `local_inner_macros` (below) were unsupported. They were added alongside path-based imports of macros (described above), to ensure that helper macros did not need to be manually imported by users of a macro-exporting crate. Crates written for earlier versions of Rust that use helper macros need to be modified to use `$crate` or `local_inner_macros` to work well with path-based imports.
> 
>  

 When a macro is exported, the `#[macro_export]` attribute can have the `local_inner_macros` keyword added to automatically prefix all contained macro invocations with `$crate::`. This is intended primarily as a tool to migrate code written before `$crate` was added to the language to work with Rust 2018's path-based imports of macros. Its use is discouraged in new code.

 
```
#![allow(unused)]
fn main() {
#[macro_export(local_inner_macros)]
macro_rules! helped {
    () => { helper!() } // Automatically converted to $crate::helper!().
}

#[macro_export]
macro_rules! helper {
    () => { () }
}
}
```
 Follow-set Ambiguity Restrictions
---------------------------------

 The parser used by the macro system is reasonably powerful, but it is limited in order to prevent ambiguity in current or future versions of the language. In particular, in addition to the rule about ambiguous expansions, a nonterminal matched by a metavariable must be followed by a token which has been decided can be safely used after that kind of match.

 As an example, a macro matcher like `$i:expr [ , ]` could in theory be accepted in Rust today, since `[,]` cannot be part of a legal expression and therefore the parse would always be unambiguous. However, because `[` can start trailing expressions, `[` is not a character which can safely be ruled out as coming after an expression. If `[,]` were accepted in a later version of Rust, this matcher would become ambiguous or would misparse, breaking working code. Matchers like `$i:expr,` or `$i:expr;` would be legal, however, because `,` and `;` are legal expression separators. The specific rules are:

 * `expr` and `stmt` may only be followed by one of: `=>`, `,`, or `;`.
* `pat_param` may only be followed by one of: `=>`, `,`, `=`, `|`, `if`, or `in`.
* `pat` may only be followed by one of: `=>`, `,`, `=`, `if`, or `in`.
* `path` and `ty` may only be followed by one of: `=>`, `,`, `=`, `|`, `;`, `:`, `>`, `>>`, `[`, `{`, `as`, `where`, or a macro variable of `block` fragment specifier.
* `vis` may only be followed by one of: `,`, an identifier other than a non-raw `priv`, any token that can begin a type, or a metavariable with a `ident`, `ty`, or `path` fragment specifier.
* All other fragment specifiers have no restrictions.

 
>  **Edition Differences**: Before the 2021 edition, `pat` may also be followed by `|`.
> 
>  

 When repetitions are involved, then the rules apply to every possible number of expansions, taking separators into account. This means:

 * If the repetition includes a separator, that separator must be able to follow the contents of the repetition.
* If the repetition can repeat multiple times (`*` or `+`), then the contents must be able to follow themselves.
* The contents of the repetition must be able to follow whatever comes before, and whatever comes after must be able to follow the contents of the repetition.
* If the repetition can match zero times (`*` or `?`), then whatever comes after must be able to follow whatever comes before.

 For more detail, see the [formal specification](macro-ambiguity).



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/macros-by-example.html>

Struct std::thread::Builder
===========================



```
pub struct Builder { /* private fields */ }
```

Thread factory, which can be used in order to configure the properties of a new thread.

 Methods can be chained on it in order to configure it.

 The two configurations available are:

 * [`name`](struct.builder#method.name "method std::thread::Builder::name"): specifies an [associated name for the thread](index#naming-threads)
* [`stack_size`](struct.builder#method.stack_size "method std::thread::Builder::stack_size"): specifies the [desired stack size for the thread](index#stack-size)

 The [`spawn`](struct.builder#method.spawn "method std::thread::Builder::spawn") method will take ownership of the builder and create an [`io::Result`](../io/type.result "type std::io::Result") to the thread handle with the given configuration.

 The [`thread::spawn`](fn.spawn "fn std::thread::spawn") free function uses a `Builder` with default configuration and [`unwrap`](../result/enum.result#method.unwrap "method std::result::Result::unwrap")s its return value.

 You may want to use [`spawn`](struct.builder#method.spawn "method std::thread::Builder::spawn") instead of [`thread::spawn`](fn.spawn "fn std::thread::spawn"), when you want to recover from a failure to launch a thread, indeed the free function will panic where the `Builder` method will return a [`io::Result`](../io/type.result "type std::io::Result").

 Examples
--------

 
```
use std::thread;

let builder = thread::Builder::new();

let handler = builder.spawn(|| {
    // thread code
}).unwrap();

handler.join().unwrap();
```
 Implementations
---------------



[source](https://doc.rust-lang.org/src/std/thread/scoped.rs.html#198-257)
```
impl Builder
```

[source](https://doc.rust-lang.org/src/std/thread/scoped.rs.html#246-256)1.63.0
```
pub fn spawn_scoped<'scope, 'env, F, T>(
    self,
    scope: &'scope Scope<'scope, 'env>,
    f: F
) -> Result<ScopedJoinHandle<'scope, T>>
where
    F: FnOnce() -> T + Send + 'scope,
    T: Send + 'scope,
```

Spawns a new scoped thread using the settings set through this `Builder`.

 Unlike [`Scope::spawn`](struct.scope#method.spawn "method std::thread::Scope::spawn"), this method yields an [`io::Result`](../io/type.result "type std::io::Result") to capture any failure to create the thread at the OS level.

 ##### Panics

 Panics if a thread name was set and it contained null bytes.

 ##### Example

 
```
use std::thread;

let mut a = vec![1, 2, 3];
let mut x = 0;

thread::scope(|s| {
    thread::Builder::new()
        .name("first".to_string())
        .spawn_scoped(s, ||
    {
        println!("hello from the {:?} scoped thread", thread::current().name());
        // We can borrow `a` here.
        dbg!(&a);
    })
    .unwrap();
    thread::Builder::new()
        .name("second".to_string())
        .spawn_scoped(s, ||
    {
        println!("hello from the {:?} scoped thread", thread::current().name());
        // We can even mutably borrow `x` here,
        // because no other threads are using it.
        x += a[0] + a[2];
    })
    .unwrap();
    println!("hello from the main thread");
});

// After the scope, we can modify and access our variables again:
a.push(4);
assert_eq!(x, a.len());
```
 

[source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#270-574)
```
impl Builder
```

[source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#290-292)
```
pub fn new() -> Builder
```

Generates the base configuration for spawning a thread, from which configuration methods can be chained.

 ##### Examples

 
```
use std::thread;

let builder = thread::Builder::new()
                              .name("foo".into())
                              .stack_size(32 * 1024);

let handler = builder.spawn(|| {
    // thread code
}).unwrap();

handler.join().unwrap();
```
 
[source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#319-322)
```
pub fn name(self, name: String) -> Builder
```

Names the thread-to-be. Currently the name is used for identification only in panic messages.

 The name must not contain null bytes (`\0`).

 For more information about named threads, see [this module-level documentation](index#naming-threads).

 ##### Examples

 
```
use std::thread;

let builder = thread::Builder::new()
    .name("foo".into());

let handler = builder.spawn(|| {
    assert_eq!(thread::current().name(), Some("foo"))
}).unwrap();

handler.join().unwrap();
```
 
[source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#342-345)
```
pub fn stack_size(self, size: usize) -> Builder
```

Sets the size of the stack (in bytes) for the new thread.

 The actual stack size may be greater than this value if the platform specifies a minimal stack size.

 For more information about the stack size for threads, see [this module-level documentation](index#stack-size).

 ##### Examples

 
```
use std::thread;

let builder = thread::Builder::new().stack_size(32 * 1024);
```
 
[source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#383-390)
```
pub fn spawn<F, T>(self, f: F) -> Result<JoinHandle<T>>
where
    F: FnOnce() -> T + Send + 'static,
    T: Send + 'static,
```

Spawns a new thread by taking ownership of the `Builder`, and returns an [`io::Result`](../io/type.result "type std::io::Result") to its [`JoinHandle`](struct.joinhandle "struct std::thread::JoinHandle").

 The spawned thread may outlive the caller (unless the caller thread is the main thread; the whole process is terminated when the main thread finishes). The join handle can be used to block on termination of the spawned thread, including recovering its panics.

 For a more complete documentation see [`thread::spawn`](fn.spawn "fn std::thread::spawn").

 ##### Errors

 Unlike the [`spawn`](fn.spawn "fn std::thread::spawn") free function, this method yields an [`io::Result`](../io/type.result "type std::io::Result") to capture any failure to create the thread at the OS level.

 ##### Panics

 Panics if a thread name was set and it contained null bytes.

 ##### Examples

 
```
use std::thread;

let builder = thread::Builder::new();

let handler = builder.spawn(|| {
    // thread code
}).unwrap();

handler.join().unwrap();
```
 
[source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#451-458)
```
pub unsafe fn spawn_unchecked<'a, F, T>(self, f: F) -> Result<JoinHandle<T>>
where
    F: FnOnce() -> T + Send + 'a,
    T: Send + 'a,
```

🔬This is a nightly-only experimental API. (`thread_spawn_unchecked` [#55132](https://github.com/rust-lang/rust/issues/55132))

Spawns a new thread without any lifetime restrictions by taking ownership of the `Builder`, and returns an [`io::Result`](../io/type.result "type std::io::Result") to its [`JoinHandle`](struct.joinhandle "struct std::thread::JoinHandle").

 The spawned thread may outlive the caller (unless the caller thread is the main thread; the whole process is terminated when the main thread finishes). The join handle can be used to block on termination of the spawned thread, including recovering its panics.

 This method is identical to [`thread::Builder::spawn`](struct.builder#method.spawn "method std::thread::Builder::spawn"), except for the relaxed lifetime bounds, which render it unsafe. For a more complete documentation see [`thread::spawn`](fn.spawn "fn std::thread::spawn").

 ##### Errors

 Unlike the [`spawn`](fn.spawn "fn std::thread::spawn") free function, this method yields an [`io::Result`](../io/type.result "type std::io::Result") to capture any failure to create the thread at the OS level.

 ##### Panics

 Panics if a thread name was set and it contained null bytes.

 ##### Safety

 The caller has to ensure that the spawned thread does not outlive any references in the supplied thread closure and its return type. This can be guaranteed in two ways:

 * ensure that [`join`](struct.joinhandle#method.join "method std::thread::JoinHandle::join") is called before any referenced data is dropped
* use only types with `'static` lifetime bounds, i.e., those with no or only `'static` references (both [`thread::Builder::spawn`](struct.builder#method.spawn "method std::thread::Builder::spawn") and [`thread::spawn`](fn.spawn "fn std::thread::spawn") enforce this property statically)

 ##### Examples

 
```
#![feature(thread_spawn_unchecked)]
use std::thread;

let builder = thread::Builder::new();

let x = 1;
let thread_x = &x;

let handler = unsafe {
    builder.spawn_unchecked(move || {
        println!("x = {}", *thread_x);
    }).unwrap()
};

// caller has to ensure `join()` is called, otherwise
// it is possible to access freed memory if `x` gets
// dropped before the thread closure is executed!
handler.join().unwrap();
```
 


Trait Implementations
---------------------



[source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#262)
```
impl Debug for Builder
```

[source](https://doc.rust-lang.org/src/std/thread/mod.rs.html#262)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result
```
Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt)



Auto Trait Implementations
--------------------------




```
impl RefUnwindSafe for Builder
```

```
impl Send for Builder
```

```
impl Sync for Builder
```

```
impl Unpin for Builder
```

```
impl UnwindSafe for Builder
```


Blanket Implementations
-----------------------



[source](https://doc.rust-lang.org/src/core/any.rs.html#200)
```
impl<T> Any for T
where
    T: 'static + ?Sized,
```

[source](https://doc.rust-lang.org/src/core/any.rs.html#201)
```
fn type_id(&self) -> TypeId
```
Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#208)
```
impl<T> Borrow<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#210)
```
fn borrow(&self) -> &T
```
Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#216)
```
impl<T> BorrowMut<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#217)
```
fn borrow_mut(&mut self) -> &mut T
```
Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#723)
```
impl<T> From<T> for T
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#726)
```
fn from(t: T) -> T
```

Returns the argument unchanged.

 

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#707)
```
impl<T, U> Into<U> for T
where
    U: From<T>,
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#716)
```
fn into(self) -> U
```

Calls `U::from(self)`.

 That is, this conversion is whatever the implementation of `[From](../convert/trait.from "trait std::convert::From")<T> for U` chooses to do.

 

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#763)
```
impl<T, U> TryFrom<U> for T
where
    U: Into<T>,
```


```
type Error = Infallible
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#770)
```
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#748)
```
impl<T, U> TryInto<U> for T
where
    U: TryFrom<T>,
```


```
type Error = <U as TryFrom<T>>::Error
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#755)
```
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
```
Performs the conversion.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/thread/struct.Builder.html>

Notation
========

 Grammar
-------

 The following notations are used by the *Lexer* and *Syntax* grammar snippets:

 


| Notation | Examples | Meaning |
| --- | --- | --- |
| CAPITAL | KW\_IF, INTEGER\_LITERAL | A token produced by the lexer |
| *ItalicCamelCase* | *LetStatement*, *Item* | A syntactical production |
| `string` | `x`, `while`, `*` | The exact character(s) |
| \x | \n, \r, \t, \0 | The character represented by this escape |
| x? | `pub`? | An optional item |
| x\* | *OuterAttribute*\* | 0 or more of x |
| x+ | *MacroMatch*+ | 1 or more of x |
| xa..b | HEX\_DIGIT1..6 | a to b repetitions of x |
| | | `u8` | `u16`, Block | Item | Either one or another |
| [ ] | [`b` `B`] | Any of the characters listed |
| [ - ] | [`a`-`z`] | Any of the characters in the range |
| ~[ ] | ~[`b` `B`] | Any characters, except those listed |
| ~`string` | ~`\n`, ~`*/` | Any characters, except this sequence |
| ( ) | (`,` *Parameter*)? | Groups items |

  String table productions
------------------------

 Some rules in the grammar — notably [unary operators](expressions/operator-expr#borrow-operators), [binary operators](expressions/operator-expr#arithmetic-and-logical-binary-operators), and <keywords> — are given in a simplified form: as a listing of printable strings. These cases form a subset of the rules regarding the [token](tokens) rule, and are assumed to be the result of a lexical-analysis phase feeding the parser, driven by a DFA, operating over the disjunction of all such string table entries.

 When such a string in `monospace` font occurs inside the grammar, it is an implicit reference to a single member of such a string table production. See <tokens> for more information.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/notation.html>

Lexical structure
=================



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/lexical-structure.html>

Input format
============

 Rust input is interpreted as a sequence of Unicode code points encoded in UTF-8.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/input-format.html>

Keywords
========

 Rust divides keywords into three categories:

 * [strict](#strict-keywords)
* [reserved](#reserved-keywords)
* [weak](#weak-keywords)

 Strict keywords
---------------

 These keywords can only be used in their correct contexts. They cannot be used as the names of:

 * [Items](items)
* [Variables](variables) and function parameters
* Fields and [variants](items/enumerations)
* [Type parameters](types/parameters)
* Lifetime parameters or [loop labels](expressions/loop-expr#loop-labels)
* [Macros](macros) or <attributes>
* [Macro placeholders](macros-by-example)
* [Crates](crates-and-source-files)

 
>  **Lexer:**  
>  KW\_AS : `as`  
>  KW\_BREAK : `break`  
>  KW\_CONST : `const`  
>  KW\_CONTINUE : `continue`  
>  KW\_CRATE : `crate`  
>  KW\_ELSE : `else`  
>  KW\_ENUM : `enum`  
>  KW\_EXTERN : `extern`  
>  KW\_FALSE : `false`  
>  KW\_FN : `fn`  
>  KW\_FOR : `for`  
>  KW\_IF : `if`  
>  KW\_IMPL : `impl`  
>  KW\_IN : `in`  
>  KW\_LET : `let`  
>  KW\_LOOP : `loop`  
>  KW\_MATCH : `match`  
>  KW\_MOD : `mod`  
>  KW\_MOVE : `move`  
>  KW\_MUT : `mut`  
>  KW\_PUB : `pub`  
>  KW\_REF : `ref`  
>  KW\_RETURN : `return`  
>  KW\_SELFVALUE : `self`  
>  KW\_SELFTYPE : `Self`  
>  KW\_STATIC : `static`  
>  KW\_STRUCT : `struct`  
>  KW\_SUPER : `super`  
>  KW\_TRAIT : `trait`  
>  KW\_TRUE : `true`  
>  KW\_TYPE : `type`  
>  KW\_UNSAFE : `unsafe`  
>  KW\_USE : `use`  
>  KW\_WHERE : `where`  
>  KW\_WHILE : `while`
> 
>  

 The following keywords were added beginning in the 2018 edition.

 
>  **Lexer 2018+**  
>  KW\_ASYNC : `async`  
>  KW\_AWAIT : `await`  
>  KW\_DYN : `dyn`
> 
>  

 Reserved keywords
-----------------

 These keywords aren't used yet, but they are reserved for future use. They have the same restrictions as strict keywords. The reasoning behind this is to make current programs forward compatible with future versions of Rust by forbidding them to use these keywords.

 
>  **Lexer**  
>  KW\_ABSTRACT : `abstract`  
>  KW\_BECOME : `become`  
>  KW\_BOX : `box`  
>  KW\_DO : `do`  
>  KW\_FINAL : `final`  
>  KW\_MACRO : `macro`  
>  KW\_OVERRIDE : `override`  
>  KW\_PRIV : `priv`  
>  KW\_TYPEOF : `typeof`  
>  KW\_UNSIZED : `unsized`  
>  KW\_VIRTUAL : `virtual`  
>  KW\_YIELD : `yield`
> 
>  

 The following keywords are reserved beginning in the 2018 edition.

 
>  **Lexer 2018+**  
>  KW\_TRY : `try`
> 
>  

 Weak keywords
-------------

 These keywords have special meaning only in certain contexts. For example, it is possible to declare a variable or method with the name `union`.

 * `macro_rules` is used to create custom <macros>.
* `union` is used to declare a [union](items/unions) and is only a keyword when used in a union declaration.
* `'static` is used for the static lifetime and cannot be used as a [generic lifetime parameter](items/generics) or [loop label](expressions/loop-expr#loop-labels)

 
```
// error[E0262]: invalid lifetime parameter name: `'static`
fn invalid_lifetime_parameter<'static>(s: &'static str) -> &'static str { s }

```
* In the 2015 edition, [`dyn`](types/trait-object) is a keyword when used in a type position followed by a path that does not start with `::`.

 Beginning in the 2018 edition, `dyn` has been promoted to a strict keyword.

 
>  **Lexer**  
>  KW\_MACRO\_RULES : `macro_rules`  
>  KW\_UNION : `union`  
>  KW\_STATICLIFETIME : `'static`
> 
>  **Lexer 2015**  
>  KW\_DYN : `dyn`
> 
>  



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/keywords.html>

Identifiers
===========

 
>  **Lexer:**  
>  IDENTIFIER\_OR\_KEYWORD :  
>  XID\_Start XID\_Continue\*  
>  | `_` XID\_Continue+
> 
>  RAW\_IDENTIFIER : `r#` IDENTIFIER\_OR\_KEYWORD *Except `crate`, `self`, `super`, `Self`*
> 
>  NON\_KEYWORD\_IDENTIFIER : IDENTIFIER\_OR\_KEYWORD *Except a [strict](keywords#strict-keywords) or [reserved](keywords#reserved-keywords) keyword*
> 
>  IDENTIFIER :  
>  NON\_KEYWORD\_IDENTIFIER | RAW\_IDENTIFIER
> 
>  

 Identifiers follow the specification in [Unicode Standard Annex #31](https://www.unicode.org/reports/tr31/tr31-37.html) for Unicode version 15.0, with the additions described below. Some examples of identifiers:

 * `foo`
* `_identifier`
* `r#true`
* `Москва`
* `東京`

 The profile used from UAX #31 is:

 * Start := [`XID_Start`](http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5B%3AXID_Start%3A%5D&abb=on&g=&i=), plus the underscore character (U+005F)
* Continue := [`XID_Continue`](http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5B%3AXID_Continue%3A%5D&abb=on&g=&i=)
* Medial := empty

 with the additional constraint that a single underscore character is not an identifier.

 
>  **Note**: Identifiers starting with an underscore are typically used to indicate an identifier that is intentionally unused, and will silence the unused warning in `rustc`.
> 
>  

 Identifiers may not be a [strict](keywords#strict-keywords) or [reserved](keywords#reserved-keywords) keyword without the `r#` prefix described below in [raw identifiers](#raw-identifiers).

 Zero width non-joiner (ZWNJ U+200C) and zero width joiner (ZWJ U+200D) characters are not allowed in identifiers.

 Identifiers are restricted to the ASCII subset of [`XID_Start`](http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5B%3AXID_Start%3A%5D&abb=on&g=&i=) and [`XID_Continue`](http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5B%3AXID_Continue%3A%5D&abb=on&g=&i=) in the following situations:

 * [`extern crate`](items/extern-crates) declarations
* External crate names referenced in a [path](paths)
* [Module](items/modules) names loaded from the filesystem without a [`path` attribute](items/modules#the-path-attribute)
* [`no_mangle`](abi#the-no_mangle-attribute) attributed items
* Item names in [external blocks](items/external-blocks)

 Normalization
-------------

 Identifiers are normalized using Normalization Form C (NFC) as defined in [Unicode Standard Annex #15](https://www.unicode.org/reports/tr15/tr15-53.html). Two identifiers are equal if their NFC forms are equal.

 [Procedural](procedural-macros) and [declarative](macros-by-example) macros receive normalized identifiers in their input.

 Raw identifiers
---------------

 A raw identifier is like a normal identifier, but prefixed by `r#`. (Note that the `r#` prefix is not included as part of the actual identifier.) Unlike a normal identifier, a raw identifier may be any strict or reserved keyword except the ones listed above for `RAW_IDENTIFIER`.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/identifiers.html>

Comments
========

 
>  **Lexer**  
>  LINE\_COMMENT :  
>  `//` (~[`/` `!` `\n`] | `//`) ~`\n`\*  
>  | `//`
> 
>  BLOCK\_COMMENT :  
>  `/*` (~[`*` `!`] | `**` | *BlockCommentOrDoc*) (*BlockCommentOrDoc* | ~`*/`)\* `*/`  
>  | `/**/`  
>  | `/***/`
> 
>  INNER\_LINE\_DOC :  
>  `//!` ~[`\n` *IsolatedCR*]\*
> 
>  INNER\_BLOCK\_DOC :  
>  `/*!` ( *BlockCommentOrDoc* | ~[`*/` *IsolatedCR*] )\* `*/`
> 
>  OUTER\_LINE\_DOC :  
>  `///` (~`/` ~[`\n` *IsolatedCR*]\*)?
> 
>  OUTER\_BLOCK\_DOC :  
>  `/**` (~`*` | *BlockCommentOrDoc* ) (*BlockCommentOrDoc* | ~[`*/` *IsolatedCR*])\* `*/`
> 
>  *BlockCommentOrDoc* :  
>  BLOCK\_COMMENT  
>  | OUTER\_BLOCK\_DOC  
>  | INNER\_BLOCK\_DOC
> 
>  *IsolatedCR* :  
>  *A `\r` not followed by a `\n`*
> 
>  

 Non-doc comments
----------------

 Comments follow the general C++ style of line (`//`) and block (`/* ... */`) comment forms. Nested block comments are supported.

 Non-doc comments are interpreted as a form of whitespace.

 Doc comments
------------

 Line doc comments beginning with exactly *three* slashes (`///`), and block doc comments (`/** ... */`), both inner doc comments, are interpreted as a special syntax for [`doc` attributes](https://doc.rust-lang.org/rustdoc/the-doc-attribute.html). That is, they are equivalent to writing `#[doc="..."]` around the body of the comment, i.e., `/// Foo` turns into `#[doc="Foo"]` and `/** Bar */` turns into `#[doc="Bar"]`.

 Line comments beginning with `//!` and block comments `/*! ... */` are doc comments that apply to the parent of the comment, rather than the item that follows. That is, they are equivalent to writing `#![doc="..."]` around the body of the comment. `//!` comments are usually used to document modules that occupy a source file.

 Isolated CRs (`\r`), i.e. not followed by LF (`\n`), are not allowed in doc comments.

 Examples
--------

 
```
#![allow(unused)]
fn main() {
//! A doc comment that applies to the implicit anonymous module of this crate

pub mod outer_module {

    //!  - Inner line doc
    //!! - Still an inner line doc (but with a bang at the beginning)

    /*!  - Inner block doc */
    /*!! - Still an inner block doc (but with a bang at the beginning) */

    //   - Only a comment
    ///  - Outer line doc (exactly 3 slashes)
    //// - Only a comment

    /*   - Only a comment */
    /**  - Outer block doc (exactly) 2 asterisks */
    /*** - Only a comment */

    pub mod inner_module {}

    pub mod nested_comments {
        /* In Rust /* we can /* nest comments */ */ */

        // All three types of block comments can contain or be nested inside
        // any other type:

        /*   /* */  /** */  /*! */  */
        /*!  /* */  /** */  /*! */  */
        /**  /* */  /** */  /*! */  */
        pub mod dummy_item {}
    }

    pub mod degenerate_cases {
        // empty inner line doc
        //!

        // empty inner block doc
        /*!*/

        // empty line comment
        //

        // empty outer line doc
        ///

        // empty block comment
        /**/

        pub mod dummy_item {}

        // empty 2-asterisk block isn't a doc block, it is a block comment
        /***/

    }

    /* The next one isn't allowed because outer doc comments
       require an item that will receive the doc */

    /// Where is my item?
  mod boo {}
}
}
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/comments.html>

Whitespace
==========

 Whitespace is any non-empty string containing only characters that have the [`Pattern_White_Space`](https://www.unicode.org/reports/tr31/) Unicode property, namely:

 * `U+0009` (horizontal tab, `'\t'`)
* `U+000A` (line feed, `'\n'`)
* `U+000B` (vertical tab)
* `U+000C` (form feed)
* `U+000D` (carriage return, `'\r'`)
* `U+0020` (space, `' '`)
* `U+0085` (next line)
* `U+200E` (left-to-right mark)
* `U+200F` (right-to-left mark)
* `U+2028` (line separator)
* `U+2029` (paragraph separator)

 Rust is a "free-form" language, meaning that all forms of whitespace serve only to separate *tokens* in the grammar, and have no semantic significance.

 A Rust program has identical meaning if each whitespace element is replaced with any other legal whitespace element, such as a single space character.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/whitespace.html>

Tokens
======

 Tokens are primitive productions in the grammar defined by regular (non-recursive) languages. Rust source input can be broken down into the following kinds of tokens:

 * [Keywords](keywords)
* [Identifiers](identifiers)
* [Literals](#literals)
* [Lifetimes](#lifetimes-and-loop-labels)
* [Punctuation](#punctuation)
* [Delimiters](#delimiters)

 Within this documentation's grammar, "simple" tokens are given in [string table production](notation#string-table-productions) form, and appear in `monospace` font.

 Literals
--------

 Literals are tokens used in [literal expressions](expressions/literal-expr).

 ### Examples

 #### Characters and strings

 


|  | Example | `#` sets\* | Characters | Escapes |
| --- | --- | --- | --- | --- |
| [Character](#character-literals) | `'H'` | 0 | All Unicode | [Quote](#quote-escapes) & [ASCII](#ascii-escapes) & [Unicode](#unicode-escapes) |
| [String](#string-literals) | `"hello"` | 0 | All Unicode | [Quote](#quote-escapes) & [ASCII](#ascii-escapes) & [Unicode](#unicode-escapes) |
| [Raw string](#raw-string-literals) | `r#"hello"#` | <256 | All Unicode | `N/A` |
| [Byte](#byte-literals) | `b'H'` | 0 | All ASCII | [Quote](#quote-escapes) & [Byte](#byte-escapes) |
| [Byte string](#byte-string-literals) | `b"hello"` | 0 | All ASCII | [Quote](#quote-escapes) & [Byte](#byte-escapes) |
| [Raw byte string](#raw-byte-string-literals) | `br#"hello"#` | <256 | All ASCII | `N/A` |

  \* The number of `#`s on each side of the same literal must be equivalent.

 #### ASCII escapes

 


|  | Name |
| --- | --- |
| `\x41` | 7-bit character code (exactly 2 digits, up to 0x7F) |
| `\n` | Newline |
| `\r` | Carriage return |
| `\t` | Tab |
| `\\` | Backslash |
| `\0` | Null |

  #### Byte escapes

 


|  | Name |
| --- | --- |
| `\x7F` | 8-bit character code (exactly 2 digits) |
| `\n` | Newline |
| `\r` | Carriage return |
| `\t` | Tab |
| `\\` | Backslash |
| `\0` | Null |

  #### Unicode escapes

 


|  | Name |
| --- | --- |
| `\u{7FFF}` | 24-bit Unicode character code (up to 6 digits) |

  #### Quote escapes

 


|  | Name |
| --- | --- |
| `\'` | Single quote |
| `\"` | Double quote |

  #### Numbers

 


| [Number literals](#number-literals)`*` | Example | Exponentiation |
| --- | --- | --- |
| Decimal integer | `98_222` | `N/A` |
| Hex integer | `0xff` | `N/A` |
| Octal integer | `0o77` | `N/A` |
| Binary integer | `0b1111_0000` | `N/A` |
| Floating-point | `123.0E+77` | `Optional` |

  `*` All number literals allow `_` as a visual separator: `1_234.0E+18f64`

 #### Suffixes

 A suffix is a sequence of characters following the primary part of a literal (without intervening whitespace), of the same form as a non-raw identifier or keyword.

 
>  **Lexer**  
>  SUFFIX : IDENTIFIER\_OR\_KEYWORD  
>  SUFFIX\_NO\_E : SUFFIX *not beginning with `e` or `E`*
> 
>  

 Any kind of literal (string, integer, etc) with any suffix is valid as a token.

 A literal token with any suffix can be passed to a macro without producing an error. The macro itself will decide how to interpret such a token and whether to produce an error or not. In particular, the `literal` fragment specifier for by-example macros matches literal tokens with arbitrary suffixes.

 
```
#![allow(unused)]
fn main() {
macro_rules! blackhole { ($tt:tt) => () }
macro_rules! blackhole_lit { ($l:literal) => () }

blackhole!("string"suffix); // OK
blackhole_lit!(1suffix); // OK
}
```
 However, suffixes on literal tokens which are interpreted as literal expressions or patterns are restricted. Any suffixes are rejected on non-numeric literal tokens, and numeric literal tokens are accepted only with suffixes from the list below.

 


| Integer | Floating-point |
| --- | --- |
| `u8`, `i8`, `u16`, `i16`, `u32`, `i32`, `u64`, `i64`, `u128`, `i128`, `usize`, `isize` | `f32`, `f64` |

  ### Character and string literals

 #### Character literals

 
>  **Lexer**  
>  CHAR\_LITERAL :  
>  `'` ( ~[`'` `\` \n \r \t] | QUOTE\_ESCAPE | ASCII\_ESCAPE | UNICODE\_ESCAPE ) `'` SUFFIX?
> 
>  QUOTE\_ESCAPE :  
>  `\'` | `\"`
> 
>  ASCII\_ESCAPE :  
>  `\x` OCT\_DIGIT HEX\_DIGIT  
>  | `\n` | `\r` | `\t` | `\\` | `\0`
> 
>  UNICODE\_ESCAPE :  
>  `\u{` ( HEX\_DIGIT `_`\* )1..6 `}`
> 
>  

 A *character literal* is a single Unicode character enclosed within two `U+0027` (single-quote) characters, with the exception of `U+0027` itself, which must be *escaped* by a preceding `U+005C` character (`\`).

 #### String literals

 
>  **Lexer**  
>  STRING\_LITERAL :  
>  `"` (  
>  ~[`"` `\` *IsolatedCR*]  
>  | QUOTE\_ESCAPE  
>  | ASCII\_ESCAPE  
>  | UNICODE\_ESCAPE  
>  | STRING\_CONTINUE  
>  )\* `"` SUFFIX?
> 
>  STRING\_CONTINUE :  
>  `\` *followed by* \n
> 
>  

 A *string literal* is a sequence of any Unicode characters enclosed within two `U+0022` (double-quote) characters, with the exception of `U+0022` itself, which must be *escaped* by a preceding `U+005C` character (`\`).

 Line-breaks are allowed in string literals. A line-break is either a newline (`U+000A`) or a pair of carriage return and newline (`U+000D`, `U+000A`). Both byte sequences are normally translated to `U+000A`, but as a special exception, when an unescaped `U+005C` character (`\`) occurs immediately before a line break, then the line break character(s), and all immediately following (`U+0020`), `\t` (`U+0009`), `\n` (`U+000A`) and `\r` (`U+0000D`) characters are ignored. Thus `a`, `b` and `c` are equal:

 
```
#![allow(unused)]
fn main() {
let a = "foobar";
let b = "foo\
         bar";
let c = "foo\

     bar";

assert_eq!(a, b);
assert_eq!(b, c);
}
```
 
>  Note: Rust skipping additional newlines (like in example `c`) is potentially confusing and unexpected. This behavior may be adjusted in the future. Until a decision is made, it is recommended to avoid relying on this, i.e. skipping multiple newlines with line continuations. See [this issue](https://github.com/rust-lang/reference/pull/1042) for more information.
> 
>  

 #### Character escapes

 Some additional *escapes* are available in either character or non-raw string literals. An escape starts with a `U+005C` (`\`) and continues with one of the following forms:

 * A *7-bit code point escape* starts with `U+0078` (`x`) and is followed by exactly two *hex digits* with value up to `0x7F`. It denotes the ASCII character with value equal to the provided hex value. Higher values are not permitted because it is ambiguous whether they mean Unicode code points or byte values.
* A *24-bit code point escape* starts with `U+0075` (`u`) and is followed by up to six *hex digits* surrounded by braces `U+007B` (`{`) and `U+007D` (`}`). It denotes the Unicode code point equal to the provided hex value.
* A *whitespace escape* is one of the characters `U+006E` (`n`), `U+0072` (`r`), or `U+0074` (`t`), denoting the Unicode values `U+000A` (LF), `U+000D` (CR) or `U+0009` (HT) respectively.
* The *null escape* is the character `U+0030` (`0`) and denotes the Unicode value `U+0000` (NUL).
* The *backslash escape* is the character `U+005C` (`\`) which must be escaped in order to denote itself.

 #### Raw string literals

 
>  **Lexer**  
>  RAW\_STRING\_LITERAL :  
>  `r` RAW\_STRING\_CONTENT SUFFIX?
> 
>  RAW\_STRING\_CONTENT :  
>  `"` ( ~ *IsolatedCR* )\* (non-greedy) `"`  
>  | `#` RAW\_STRING\_CONTENT `#`
> 
>  

 Raw string literals do not process any escapes. They start with the character `U+0072` (`r`), followed by fewer than 256 of the character `U+0023` (`#`) and a `U+0022` (double-quote) character. The *raw string body* can contain any sequence of Unicode characters and is terminated only by another `U+0022` (double-quote) character, followed by the same number of `U+0023` (`#`) characters that preceded the opening `U+0022` (double-quote) character.

 All Unicode characters contained in the raw string body represent themselves, the characters `U+0022` (double-quote) (except when followed by at least as many `U+0023` (`#`) characters as were used to start the raw string literal) or `U+005C` (`\`) do not have any special meaning.

 Examples for string literals:

 
```
#![allow(unused)]
fn main() {
"foo"; r"foo";                     // foo
"\"foo\""; r#""foo""#;             // "foo"

"foo #\"# bar";
r##"foo #"# bar"##;                // foo #"# bar

"\x52"; "R"; r"R";                 // R
"\\x52"; r"\x52";                  // \x52
}
```
 ### Byte and byte string literals

 #### Byte literals

 
>  **Lexer**  
>  BYTE\_LITERAL :  
>  `b'` ( ASCII\_FOR\_CHAR | BYTE\_ESCAPE ) `'` SUFFIX?
> 
>  ASCII\_FOR\_CHAR :  
>  *any ASCII (i.e. 0x00 to 0x7F), except* `'`, `\`, \n, \r or \t
> 
>  BYTE\_ESCAPE :  
>  `\x` HEX\_DIGIT HEX\_DIGIT  
>  | `\n` | `\r` | `\t` | `\\` | `\0` | `\'` | `\"`
> 
>  

 A *byte literal* is a single ASCII character (in the `U+0000` to `U+007F` range) or a single *escape* preceded by the characters `U+0062` (`b`) and `U+0027` (single-quote), and followed by the character `U+0027`. If the character `U+0027` is present within the literal, it must be *escaped* by a preceding `U+005C` (`\`) character. It is equivalent to a `u8` unsigned 8-bit integer *number literal*.

 #### Byte string literals

 
>  **Lexer**  
>  BYTE\_STRING\_LITERAL :  
>  `b"` ( ASCII\_FOR\_STRING | BYTE\_ESCAPE | STRING\_CONTINUE )\* `"` SUFFIX?
> 
>  ASCII\_FOR\_STRING :  
>  *any ASCII (i.e 0x00 to 0x7F), except* `"`, `\` *and IsolatedCR*
> 
>  

 A non-raw *byte string literal* is a sequence of ASCII characters and *escapes*, preceded by the characters `U+0062` (`b`) and `U+0022` (double-quote), and followed by the character `U+0022`. If the character `U+0022` is present within the literal, it must be *escaped* by a preceding `U+005C` (`\`) character. Alternatively, a byte string literal can be a *raw byte string literal*, defined below. The type of a byte string literal of length `n` is `&'static [u8; n]`.

 Some additional *escapes* are available in either byte or non-raw byte string literals. An escape starts with a `U+005C` (`\`) and continues with one of the following forms:

 * A *byte escape* escape starts with `U+0078` (`x`) and is followed by exactly two *hex digits*. It denotes the byte equal to the provided hex value.
* A *whitespace escape* is one of the characters `U+006E` (`n`), `U+0072` (`r`), or `U+0074` (`t`), denoting the bytes values `0x0A` (ASCII LF), `0x0D` (ASCII CR) or `0x09` (ASCII HT) respectively.
* The *null escape* is the character `U+0030` (`0`) and denotes the byte value `0x00` (ASCII NUL).
* The *backslash escape* is the character `U+005C` (`\`) which must be escaped in order to denote its ASCII encoding `0x5C`.

 #### Raw byte string literals

 
>  **Lexer**  
>  RAW\_BYTE\_STRING\_LITERAL :  
>  `br` RAW\_BYTE\_STRING\_CONTENT SUFFIX?
> 
>  RAW\_BYTE\_STRING\_CONTENT :  
>  `"` ASCII\* (non-greedy) `"`  
>  | `#` RAW\_BYTE\_STRING\_CONTENT `#`
> 
>  ASCII :  
>  *any ASCII (i.e. 0x00 to 0x7F)*
> 
>  

 Raw byte string literals do not process any escapes. They start with the character `U+0062` (`b`), followed by `U+0072` (`r`), followed by fewer than 256 of the character `U+0023` (`#`), and a `U+0022` (double-quote) character. The *raw string body* can contain any sequence of ASCII characters and is terminated only by another `U+0022` (double-quote) character, followed by the same number of `U+0023` (`#`) characters that preceded the opening `U+0022` (double-quote) character. A raw byte string literal can not contain any non-ASCII byte.

 All characters contained in the raw string body represent their ASCII encoding, the characters `U+0022` (double-quote) (except when followed by at least as many `U+0023` (`#`) characters as were used to start the raw string literal) or `U+005C` (`\`) do not have any special meaning.

 Examples for byte string literals:

 
```
#![allow(unused)]
fn main() {
b"foo"; br"foo";                     // foo
b"\"foo\""; br#""foo""#;             // "foo"

b"foo #\"# bar";
br##"foo #"# bar"##;                 // foo #"# bar

b"\x52"; b"R"; br"R";                // R
b"\\x52"; br"\x52";                  // \x52
}
```
 ### Number literals

 A *number literal* is either an *integer literal* or a *floating-point literal*. The grammar for recognizing the two kinds of literals is mixed.

 #### Integer literals

 
>  **Lexer**  
>  INTEGER\_LITERAL :  
>  ( DEC\_LITERAL | BIN\_LITERAL | OCT\_LITERAL | HEX\_LITERAL ) SUFFIX\_NO\_E?
> 
>  DEC\_LITERAL :  
>  DEC\_DIGIT (DEC\_DIGIT|`_`)\*
> 
>  BIN\_LITERAL :  
>  `0b` (BIN\_DIGIT|`_`)\* BIN\_DIGIT (BIN\_DIGIT|`_`)\*
> 
>  OCT\_LITERAL :  
>  `0o` (OCT\_DIGIT|`_`)\* OCT\_DIGIT (OCT\_DIGIT|`_`)\*
> 
>  HEX\_LITERAL :  
>  `0x` (HEX\_DIGIT|`_`)\* HEX\_DIGIT (HEX\_DIGIT|`_`)\*
> 
>  BIN\_DIGIT : [`0`-`1`]
> 
>  OCT\_DIGIT : [`0`-`7`]
> 
>  DEC\_DIGIT : [`0`-`9`]
> 
>  HEX\_DIGIT : [`0`-`9` `a`-`f` `A`-`F`]
> 
>  

 An *integer literal* has one of four forms:

 * A *decimal literal* starts with a *decimal digit* and continues with any mixture of *decimal digits* and *underscores*.
* A *hex literal* starts with the character sequence `U+0030` `U+0078` (`0x`) and continues as any mixture (with at least one digit) of hex digits and underscores.
* An *octal literal* starts with the character sequence `U+0030` `U+006F` (`0o`) and continues as any mixture (with at least one digit) of octal digits and underscores.
* A *binary literal* starts with the character sequence `U+0030` `U+0062` (`0b`) and continues as any mixture (with at least one digit) of binary digits and underscores.

 Like any literal, an integer literal may be followed (immediately, without any spaces) by a suffix as described above. The suffix may not begin with `e` or `E`, as that would be interpreted as the exponent of a floating-point literal. See [literal expressions](expressions/literal-expr) for the effect of these suffixes.

 Examples of integer literals which are accepted as literal expressions:

 
```
#![allow(unused)]
fn main() {
#![allow(overflowing_literals)]
123;
123i32;
123u32;
123_u32;

0xff;
0xff_u8;
0x01_f32; // integer 7986, not floating-point 1.0
0x01_e3;  // integer 483, not floating-point 1000.0

0o70;
0o70_i16;

0b1111_1111_1001_0000;
0b1111_1111_1001_0000i64;
0b________1;

0usize;

// These are too big for their type, but are accepted as literal expressions.
128_i8;
256_u8;

// This is an integer literal, accepted as a floating-point literal expression.
5f32;
}
```
 Note that `-1i8`, for example, is analyzed as two tokens: `-` followed by `1i8`.

 Examples of integer literals which are not accepted as literal expressions:

 
```
#![allow(unused)]
fn main() {
#[cfg(FALSE)] {
0invalidSuffix;
123AFB43;
0b010a;
0xAB_CD_EF_GH;
0b1111_f32;
}
}
```
 #### Tuple index

 
>  **Lexer**  
>  TUPLE\_INDEX:   
>  INTEGER\_LITERAL
> 
>  

 A tuple index is used to refer to the fields of [tuples](types/tuple), [tuple structs](items/structs), and [tuple variants](items/enumerations).

 Tuple indices are compared with the literal token directly. Tuple indices start with `0` and each successive index increments the value by `1` as a decimal value. Thus, only decimal values will match, and the value must not have any extra `0` prefix characters.

 
```
#![allow(unused)]
fn main() {
let example = ("dog", "cat", "horse");
let dog = example.0;
let cat = example.1;
// The following examples are invalid.
let cat = example.01;  // ERROR no field named `01`
let horse = example.0b10;  // ERROR no field named `0b10`
}
```
 
>  **Note**: Tuple indices may include certain suffixes, but this is not intended to be valid, and may be removed in a future version. See <https://github.com/rust-lang/rust/issues/60210> for more information.
> 
>  

 #### Floating-point literals

 
>  **Lexer**  
>  FLOAT\_LITERAL :  
>  DEC\_LITERAL `.` *(not immediately followed by `.`, `_` or an XID\_Start character)*  
>  | DEC\_LITERAL `.` DEC\_LITERAL SUFFIX\_NO\_E?  
>  | DEC\_LITERAL (`.` DEC\_LITERAL)? FLOAT\_EXPONENT SUFFIX?
> 
>  FLOAT\_EXPONENT :  
>  (`e`|`E`) (`+`|`-`)? (DEC\_DIGIT|`_`)\* DEC\_DIGIT (DEC\_DIGIT|`_`)\*
> 
>  

 A *floating-point literal* has one of two forms:

 * A *decimal literal* followed by a period character `U+002E` (`.`). This is optionally followed by another decimal literal, with an optional *exponent*.
* A single *decimal literal* followed by an *exponent*.

 Like integer literals, a floating-point literal may be followed by a suffix, so long as the pre-suffix part does not end with `U+002E` (`.`). The suffix may not begin with `e` or `E` if the literal does not include an exponent. See [literal expressions](expressions/literal-expr) for the effect of these suffixes.

 Examples of floating-point literals which are accepted as literal expressions:

 
```
#![allow(unused)]
fn main() {
123.0f64;
0.1f64;
0.1f32;
12E+99_f64;
let x: f64 = 2.;
}
```
 This last example is different because it is not possible to use the suffix syntax with a floating point literal ending in a period. `2.f64` would attempt to call a method named `f64` on `2`.

 Note that `-1.0`, for example, is analyzed as two tokens: `-` followed by `1.0`.

 Examples of floating-point literals which are not accepted as literal expressions:

 
```
#![allow(unused)]
fn main() {
#[cfg(FALSE)] {
2.0f80;
2e5f80;
2e5e6;
2.0e5e6;
1.3e10u64;
}
}
```
 #### Reserved forms similar to number literals

 
>  **Lexer**  
>  RESERVED\_NUMBER :  
>  BIN\_LITERAL [`2`-`9`​]  
>  | OCT\_LITERAL [`8`-`9`​]  
>  | ( BIN\_LITERAL | OCT\_LITERAL | HEX\_LITERAL ) `.`   
>  *(not immediately followed by `.`, `_` or an XID\_Start character)*  
>  | ( BIN\_LITERAL | OCT\_LITERAL ) (`e`|`E`)  
>  | `0b` `_`\* *end of input or not BIN\_DIGIT*  
>  | `0o` `_`\* *end of input or not OCT\_DIGIT*  
>  | `0x` `_`\* *end of input or not HEX\_DIGIT*  
>  | DEC\_LITERAL ( . DEC\_LITERAL)? (`e`|`E`) (`+`|`-`)? *end of input or not DEC\_DIGIT*
> 
>  

 The following lexical forms similar to number literals are *reserved forms*. Due to the possible ambiguity these raise, they are rejected by the tokenizer instead of being interpreted as separate tokens.

 * An unsuffixed binary or octal literal followed, without intervening whitespace, by a decimal digit out of the range for its radix.
* An unsuffixed binary, octal, or hexadecimal literal followed, without intervening whitespace, by a period character (with the same restrictions on what follows the period as for floating-point literals).
* An unsuffixed binary or octal literal followed, without intervening whitespace, by the character `e` or `E`.
* Input which begins with one of the radix prefixes but is not a valid binary, octal, or hexadecimal literal (because it contains no digits).
* Input which has the form of a floating-point literal with no digits in the exponent.

 Examples of reserved forms:

 
```
#![allow(unused)]
fn main() {
0b0102;  // this is not `0b010` followed by `2`
0o1279;  // this is not `0o127` followed by `9`
0x80.0;  // this is not `0x80` followed by `.` and `0`
0b101e;  // this is not a suffixed literal, or `0b101` followed by `e`
0b;      // this is not an integer literal, or `0` followed by `b`
0b_;     // this is not an integer literal, or `0` followed by `b_`
2e;      // this is not a floating-point literal, or `2` followed by `e`
2.0e;    // this is not a floating-point literal, or `2.0` followed by `e`
2em;     // this is not a suffixed literal, or `2` followed by `em`
2.0em;   // this is not a suffixed literal, or `2.0` followed by `em`
}
```
 Lifetimes and loop labels
-------------------------

 
>  **Lexer**  
>  LIFETIME\_TOKEN :  
>  `'` [IDENTIFIER\_OR\_KEYWORD](identifiers)  
>  | `'_`
> 
>  LIFETIME\_OR\_LABEL :  
>  `'` [NON\_KEYWORD\_IDENTIFIER](identifiers)
> 
>  

 Lifetime parameters and [loop labels](expressions/loop-expr) use LIFETIME\_OR\_LABEL tokens. Any LIFETIME\_TOKEN will be accepted by the lexer, and for example, can be used in macros.

 Punctuation
-----------

 Punctuation symbol tokens are listed here for completeness. Their individual usages and meanings are defined in the linked pages.

 


| Symbol | Name | Usage |
| --- | --- | --- |
| `+` | Plus | [Addition](expressions/operator-expr#arithmetic-and-logical-binary-operators), [Trait Bounds](trait-bounds), [Macro Kleene Matcher](macros-by-example) |
| `-` | Minus | [Subtraction](expressions/operator-expr#arithmetic-and-logical-binary-operators), [Negation](expressions/operator-expr#negation-operators) |
| `*` | Star | [Multiplication](expressions/operator-expr#arithmetic-and-logical-binary-operators), [Dereference](expressions/operator-expr#the-dereference-operator), [Raw Pointers](types/pointer#raw-pointers-const-and-mut), [Macro Kleene Matcher](macros-by-example), [Use wildcards](items/use-declarations) |
| `/` | Slash | [Division](expressions/operator-expr#arithmetic-and-logical-binary-operators) |
| `%` | Percent | [Remainder](expressions/operator-expr#arithmetic-and-logical-binary-operators) |
| `^` | Caret | [Bitwise and Logical XOR](expressions/operator-expr#arithmetic-and-logical-binary-operators) |
| `!` | Not | [Bitwise and Logical NOT](expressions/operator-expr#negation-operators), [Macro Calls](macros-by-example), [Inner Attributes](attributes), [Never Type](types/never), [Negative impls](items/implementations) |
| `&` | And | [Bitwise and Logical AND](expressions/operator-expr#arithmetic-and-logical-binary-operators), [Borrow](expressions/operator-expr#borrow-operators), [References](types/pointer), [Reference patterns](patterns#reference-patterns) |
| `|` | Or | [Bitwise and Logical OR](expressions/operator-expr#arithmetic-and-logical-binary-operators), [Closures](expressions/closure-expr), Patterns in [match](expressions/match-expr), [if let](expressions/if-expr#if-let-expressions), and [while let](expressions/loop-expr#predicate-pattern-loops) |
| `&&` | AndAnd | [Lazy AND](expressions/operator-expr#lazy-boolean-operators), [Borrow](expressions/operator-expr#borrow-operators), [References](types/pointer), [Reference patterns](patterns#reference-patterns) |
| `||` | OrOr | [Lazy OR](expressions/operator-expr#lazy-boolean-operators), [Closures](expressions/closure-expr) |
| `<<` | Shl | [Shift Left](expressions/operator-expr#arithmetic-and-logical-binary-operators), [Nested Generics](items/generics) |
| `>>` | Shr | [Shift Right](expressions/operator-expr#arithmetic-and-logical-binary-operators), [Nested Generics](items/generics) |
| `+=` | PlusEq | [Addition assignment](expressions/operator-expr#compound-assignment-expressions) |
| `-=` | MinusEq | [Subtraction assignment](expressions/operator-expr#compound-assignment-expressions) |
| `*=` | StarEq | [Multiplication assignment](expressions/operator-expr#compound-assignment-expressions) |
| `/=` | SlashEq | [Division assignment](expressions/operator-expr#compound-assignment-expressions) |
| `%=` | PercentEq | [Remainder assignment](expressions/operator-expr#compound-assignment-expressions) |
| `^=` | CaretEq | [Bitwise XOR assignment](expressions/operator-expr#compound-assignment-expressions) |
| `&=` | AndEq | [Bitwise And assignment](expressions/operator-expr#compound-assignment-expressions) |
| `|=` | OrEq | [Bitwise Or assignment](expressions/operator-expr#compound-assignment-expressions) |
| `<<=` | ShlEq | [Shift Left assignment](expressions/operator-expr#compound-assignment-expressions) |
| `>>=` | ShrEq | [Shift Right assignment](expressions/operator-expr#compound-assignment-expressions), [Nested Generics](items/generics) |
| `=` | Eq | [Assignment](expressions/operator-expr#assignment-expressions), [Attributes](attributes), Various type definitions |
| `==` | EqEq | [Equal](expressions/operator-expr#comparison-operators) |
| `!=` | Ne | [Not Equal](expressions/operator-expr#comparison-operators) |
| `>` | Gt | [Greater than](expressions/operator-expr#comparison-operators), [Generics](items/generics), [Paths](paths) |
| `<` | Lt | [Less than](expressions/operator-expr#comparison-operators), [Generics](items/generics), [Paths](paths) |
| `>=` | Ge | [Greater than or equal to](expressions/operator-expr#comparison-operators), [Generics](items/generics) |
| `<=` | Le | [Less than or equal to](expressions/operator-expr#comparison-operators) |
| `@` | At | [Subpattern binding](patterns#identifier-patterns) |
| `_` | Underscore | [Wildcard patterns](patterns#wildcard-pattern), [Inferred types](types/inferred), Unnamed items in [constants](items/constant-items), [extern crates](items/extern-crates), [use declarations](items/use-declarations), and [destructuring assignment](expressions/underscore-expr) |
| `.` | Dot | [Field access](expressions/field-expr), [Tuple index](expressions/tuple-expr#tuple-indexing-expressions) |
| `..` | DotDot | [Range](expressions/range-expr), [Struct expressions](expressions/struct-expr), [Patterns](patterns), [Range Patterns](patterns#range-patterns) |
| `...` | DotDotDot | [Variadic functions](items/external-blocks), [Range patterns](patterns#range-patterns) |
| `..=` | DotDotEq | [Inclusive Range](expressions/range-expr), [Range patterns](patterns#range-patterns) |
| `,` | Comma | Various separators |
| `;` | Semi | Terminator for various items and statements, [Array types](types/array) |
| `:` | Colon | Various separators |
| `::` | PathSep | [Path separator](paths) |
| `->` | RArrow | [Function return type](items/functions), [Closure return type](expressions/closure-expr), [Function pointer type](types/function-pointer) |
| `=>` | FatArrow | [Match arms](expressions/match-expr), [Macros](macros-by-example) |
| `#` | Pound | [Attributes](attributes) |
| `$` | Dollar | [Macros](macros-by-example) |
| `?` | Question | [Question mark operator](expressions/operator-expr#the-question-mark-operator), [Questionably sized](trait-bounds#sized), [Macro Kleene Matcher](macros-by-example) |
| `~` | Tilde | The tilde operator has been unused since before Rust 1.0, but its token may still be used |

  Delimiters
----------

 Bracket punctuation is used in various parts of the grammar. An open bracket must always be paired with a close bracket. Brackets and the tokens within them are referred to as "token trees" in [macros](macros-by-example). The three types of brackets are:

 


| Bracket | Type |
| --- | --- |
| `{` `}` | Curly braces |
| `[` `]` | Square brackets |
| `(` `)` | Parentheses |

  Reserved prefixes
-----------------

 
>  **Lexer 2021+**  
>  RESERVED\_TOKEN\_DOUBLE\_QUOTE : ( IDENTIFIER\_OR\_KEYWORD *Except `b` or `r` or `br`* | `_` ) `"`  
>  RESERVED\_TOKEN\_SINGLE\_QUOTE : ( IDENTIFIER\_OR\_KEYWORD *Except `b`* | `_` ) `'`  
>  RESERVED\_TOKEN\_POUND : ( IDENTIFIER\_OR\_KEYWORD *Except `r` or `br`* | `_` ) `#`
> 
>  

 Some lexical forms known as *reserved prefixes* are reserved for future use.

 Source input which would otherwise be lexically interpreted as a non-raw identifier (or a keyword or `_`) which is immediately followed by a `#`, `'`, or `"` character (without intervening whitespace) is identified as a reserved prefix.

 Note that raw identifiers, raw string literals, and raw byte string literals may contain a `#` character but are not interpreted as containing a reserved prefix.

 Similarly the `r`, `b`, and `br` prefixes used in raw string literals, byte literals, byte string literals, and raw byte string literals are not interpreted as reserved prefixes.

 
>  **Edition Differences**: Starting with the 2021 edition, reserved prefixes are reported as an error by the lexer (in particular, they cannot be passed to macros).
> 
>  Before the 2021 edition, reserved prefixes are accepted by the lexer and interpreted as multiple tokens (for example, one token for the identifier or keyword, followed by a `#` token).
> 
>  Examples accepted in all editions:
> 
>  
> ```
> #![allow(unused)]
> fn main() {
> macro_rules! lexes {($($_:tt)*) => {}}
> lexes!{a #foo}
> lexes!{continue 'foo}
> lexes!{match "..." {}}
> lexes!{r#let#foo}         // three tokens: r#let # foo
> }
> ```
>  Examples accepted before the 2021 edition but rejected later:
> 
>  
> ```
> #![allow(unused)]
> fn main() {
> macro_rules! lexes {($($_:tt)*) => {}}
> lexes!{a#foo}
> lexes!{continue'foo}
> lexes!{match"..." {}}
> }
> ```
>  



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/tokens.html>

Macros
======

 The functionality and syntax of Rust can be extended with custom definitions called macros. They are given names, and invoked through a consistent syntax: `some_extension!(...)`.

 There are two ways to define new macros:

 * [Macros by Example](macros-by-example) define new syntax in a higher-level, declarative way.
* [Procedural Macros](procedural-macros) define function-like macros, custom derives, and custom attributes using functions that operate on input tokens.

 Macro Invocation
----------------

 
>  **Syntax**  
>  *MacroInvocation* :  
>  [*SimplePath*](paths#simple-paths) `!` *DelimTokenTree*
> 
>  *DelimTokenTree* :  
>  `(` *TokenTree*\* `)`  
>  | `[` *TokenTree*\* `]`  
>  | `{` *TokenTree*\* `}`
> 
>  *TokenTree* :  
>  [*Token*](tokens)*except [delimiters](tokens#delimiters)* | *DelimTokenTree*
> 
>  *MacroInvocationSemi* :  
>  [*SimplePath*](paths#simple-paths) `!` `(` *TokenTree*\* `)` `;`  
>  | [*SimplePath*](paths#simple-paths) `!` `[` *TokenTree*\* `]` `;`  
>  | [*SimplePath*](paths#simple-paths) `!` `{` *TokenTree*\* `}`
> 
>  

 A macro invocation expands a macro at compile time and replaces the invocation with the result of the macro. Macros may be invoked in the following situations:

 * [Expressions](expressions) and <statements>
* [Patterns](patterns)
* [Types](types)
* [Items](items) including [associated items](items/associated-items)
* [`macro_rules`](macros-by-example) transcribers
* [External blocks](items/external-blocks)

 When used as an item or a statement, the *MacroInvocationSemi* form is used where a semicolon is required at the end when not using curly braces. [Visibility qualifiers](visibility-and-privacy) are never allowed before a macro invocation or [`macro_rules`](macros-by-example) definition.

 
```
#![allow(unused)]
fn main() {
// Used as an expression.
let x = vec![1,2,3];

// Used as a statement.
println!("Hello!");

// Used in a pattern.
macro_rules! pat {
    ($i:ident) => (Some($i))
}

if let pat!(x) = Some(1) {
    assert_eq!(x, 1);
}

// Used in a type.
macro_rules! Tuple {
    { $A:ty, $B:ty } => { ($A, $B) };
}

type N2 = Tuple!(i32, i32);

// Used as an item.
use std::cell::RefCell;
thread_local!(static FOO: RefCell<u32> = RefCell::new(1));

// Used as an associated item.
macro_rules! const_maker {
    ($t:ty, $v:tt) => { const CONST: $t = $v; };
}
trait T {
    const_maker!{i32, 7}
}

// Macro calls within macros.
macro_rules! example {
    () => { println!("Macro call in a macro!") };
}
// Outer macro `example` is expanded, then inner macro `println` is expanded.
example!();
}
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/macros.html>

Procedural Macros
=================

 *Procedural macros* allow creating syntax extensions as execution of a function. Procedural macros come in one of three flavors:

 * [Function-like macros](#function-like-procedural-macros) - `custom!(...)`
* [Derive macros](#derive-macros) - `#[derive(CustomDerive)]`
* [Attribute macros](#attribute-macros) - `#[CustomAttribute]`

 Procedural macros allow you to run code at compile time that operates over Rust syntax, both consuming and producing Rust syntax. You can sort of think of procedural macros as functions from an AST to another AST.

 Procedural macros must be defined in a crate with the [crate type](linkage) of `proc-macro`.

 
>  **Note**: When using Cargo, Procedural macro crates are defined with the `proc-macro` key in your manifest:
> 
>  
> ```
> [lib]
> proc-macro = true
> 
> ```
>  

 As functions, they must either return syntax, panic, or loop endlessly. Returned syntax either replaces or adds the syntax depending on the kind of procedural macro. Panics are caught by the compiler and are turned into a compiler error. Endless loops are not caught by the compiler which hangs the compiler.

 Procedural macros run during compilation, and thus have the same resources that the compiler has. For example, standard input, error, and output are the same that the compiler has access to. Similarly, file access is the same. Because of this, procedural macros have the same security concerns that [Cargo's build scripts](https://doc.rust-lang.org/cargo/reference/build-scripts.html) have.

 Procedural macros have two ways of reporting errors. The first is to panic. The second is to emit a [`compile_error`](../std/macro.compile_error) macro invocation.

 ### The `proc_macro` crate

 Procedural macro crates almost always will link to the compiler-provided [`proc_macro` crate](https://doc.rust-lang.org/proc_macro/index.html). The `proc_macro` crate provides types required for writing procedural macros and facilities to make it easier.

 This crate primarily contains a [`TokenStream`](https://doc.rust-lang.org/proc_macro/struct.TokenStream.html) type. Procedural macros operate over *token streams* instead of AST nodes, which is a far more stable interface over time for both the compiler and for procedural macros to target. A *token stream* is roughly equivalent to `Vec<TokenTree>` where a `TokenTree` can roughly be thought of as lexical token. For example `foo` is an `Ident` token, `.` is a `Punct` token, and `1.2` is a `Literal` token. The `TokenStream` type, unlike `Vec<TokenTree>`, is cheap to clone.

 All tokens have an associated `Span`. A `Span` is an opaque value that cannot be modified but can be manufactured. `Span`s represent an extent of source code within a program and are primarily used for error reporting. While you cannot modify a `Span` itself, you can always change the `Span` *associated* with any token, such as through getting a `Span` from another token.

 ### Procedural macro hygiene

 Procedural macros are *unhygienic*. This means they behave as if the output token stream was simply written inline to the code it's next to. This means that it's affected by external items and also affects external imports.

 Macro authors need to be careful to ensure their macros work in as many contexts as possible given this limitation. This often includes using absolute paths to items in libraries (for example, `::std::option::Option` instead of `Option`) or by ensuring that generated functions have names that are unlikely to clash with other functions (like `__internal_foo` instead of `foo`).

 ### Function-like procedural macros

 *Function-like procedural macros* are procedural macros that are invoked using the macro invocation operator (`!`).

 These macros are defined by a [public](visibility-and-privacy) [function](items/functions) with the `proc_macro` [attribute](attributes) and a signature of `(TokenStream) -> TokenStream`. The input [`TokenStream`](https://doc.rust-lang.org/proc_macro/struct.TokenStream.html) is what is inside the delimiters of the macro invocation and the output [`TokenStream`](https://doc.rust-lang.org/proc_macro/struct.TokenStream.html) replaces the entire macro invocation.

 For example, the following macro definition ignores its input and outputs a function `answer` into its scope.

 
```
#![crate_type = "proc-macro"]
extern crate proc_macro;
use proc_macro::TokenStream;

#[proc_macro]
pub fn make_answer(_item: TokenStream) -> TokenStream {
    "fn answer() -> u32 { 42 }".parse().unwrap()
}
```
 And then we use it in a binary crate to print "42" to standard output.

 
```
extern crate proc_macro_examples;
use proc_macro_examples::make_answer;

make_answer!();

fn main() {
    println!("{}", answer());
}
```
 Function-like procedural macros may be invoked in any macro invocation position, which includes <statements>, <expressions>, <patterns>, [type expressions](types#type-expressions), [item](items) positions, including items in [`extern` blocks](items/external-blocks), inherent and trait [implementations](items/implementations), and [trait definitions](items/traits).

 ### Derive macros

 *Derive macros* define new inputs for the [`derive` attribute](attributes/derive). These macros can create new <items> given the token stream of a [struct](items/structs), [enum](items/enumerations), or [union](items/unions). They can also define [derive macro helper attributes](#derive-macro-helper-attributes).

 Custom derive macros are defined by a [public](visibility-and-privacy) [function](items/functions) with the `proc_macro_derive` attribute and a signature of `(TokenStream) -> TokenStream`.

 The input [`TokenStream`](https://doc.rust-lang.org/proc_macro/struct.TokenStream.html) is the token stream of the item that has the `derive` attribute on it. The output [`TokenStream`](https://doc.rust-lang.org/proc_macro/struct.TokenStream.html) must be a set of items that are then appended to the [module](items/modules) or [block](expressions/block-expr) that the item from the input [`TokenStream`](https://doc.rust-lang.org/proc_macro/struct.TokenStream.html) is in.

 The following is an example of a derive macro. Instead of doing anything useful with its input, it just appends a function `answer`.

 
```
#![crate_type = "proc-macro"]
extern crate proc_macro;
use proc_macro::TokenStream;

#[proc_macro_derive(AnswerFn)]
pub fn derive_answer_fn(_item: TokenStream) -> TokenStream {
    "fn answer() -> u32 { 42 }".parse().unwrap()
}
```
 And then using said derive macro:

 
```
extern crate proc_macro_examples;
use proc_macro_examples::AnswerFn;

#[derive(AnswerFn)]
struct Struct;

fn main() {
    assert_eq!(42, answer());
}
```
 #### Derive macro helper attributes

 Derive macros can add additional <attributes> into the scope of the [item](items) they are on. Said attributes are called *derive macro helper attributes*. These attributes are [inert](attributes#active-and-inert-attributes), and their only purpose is to be fed into the derive macro that defined them. That said, they can be seen by all macros.

 The way to define helper attributes is to put an `attributes` key in the `proc_macro_derive` macro with a comma separated list of identifiers that are the names of the helper attributes.

 For example, the following derive macro defines a helper attribute `helper`, but ultimately doesn't do anything with it.

 
```
#![crate_type="proc-macro"]
extern crate proc_macro;
use proc_macro::TokenStream;

#[proc_macro_derive(HelperAttr, attributes(helper))]
pub fn derive_helper_attr(_item: TokenStream) -> TokenStream {
    TokenStream::new()
}
```
 And then usage on the derive macro on a struct:

 
```
#[derive(HelperAttr)]
struct Struct {
    #[helper] field: ()
}
```
 ### Attribute macros

 *Attribute macros* define new [outer attributes](attributes) which can be attached to <items>, including items in [`extern` blocks](items/external-blocks), inherent and trait [implementations](items/implementations), and [trait definitions](items/traits).

 Attribute macros are defined by a [public](visibility-and-privacy) [function](items/functions) with the `proc_macro_attribute` [attribute](attributes) that has a signature of `(TokenStream, TokenStream) -> TokenStream`. The first [`TokenStream`](https://doc.rust-lang.org/proc_macro/struct.TokenStream.html) is the delimited token tree following the attribute's name, not including the outer delimiters. If the attribute is written as a bare attribute name, the attribute [`TokenStream`](https://doc.rust-lang.org/proc_macro/struct.TokenStream.html) is empty. The second [`TokenStream`](https://doc.rust-lang.org/proc_macro/struct.TokenStream.html) is the rest of the [item](items) including other <attributes> on the [item](items). The returned [`TokenStream`](https://doc.rust-lang.org/proc_macro/struct.TokenStream.html) replaces the [item](items) with an arbitrary number of <items>.

 For example, this attribute macro takes the input stream and returns it as is, effectively being the no-op of attributes.

 
```
#![crate_type = "proc-macro"]
extern crate proc_macro;
use proc_macro::TokenStream;

#[proc_macro_attribute]
pub fn return_as_is(_attr: TokenStream, item: TokenStream) -> TokenStream {
    item
}
```
 This following example shows the stringified [`TokenStream`s](https://doc.rust-lang.org/proc_macro/struct.TokenStream.html) that the attribute macros see. The output will show in the output of the compiler. The output is shown in the comments after the function prefixed with "out:".

 
```
// my-macro/src/lib.rs
extern crate proc_macro;
use proc_macro::TokenStream;

#[proc_macro_attribute]
pub fn show_streams(attr: TokenStream, item: TokenStream) -> TokenStream {
    println!("attr: \"{}\"", attr.to_string());
    println!("item: \"{}\"", item.to_string());
    item
}
```
 
```
// src/lib.rs
extern crate my_macro;

use my_macro::show_streams;

// Example: Basic function
#[show_streams]
fn invoke1() {}
// out: attr: ""
// out: item: "fn invoke1() {}"

// Example: Attribute with input
#[show_streams(bar)]
fn invoke2() {}
// out: attr: "bar"
// out: item: "fn invoke2() {}"

// Example: Multiple tokens in the input
#[show_streams(multiple => tokens)]
fn invoke3() {}
// out: attr: "multiple => tokens"
// out: item: "fn invoke3() {}"

// Example:
#[show_streams { delimiters }]
fn invoke4() {}
// out: attr: "delimiters"
// out: item: "fn invoke4() {}"
```
 ### Declarative macro tokens and procedural macro tokens

 Declarative `macro_rules` macros and procedural macros use similar, but different definitions for tokens (or rather [`TokenTree`s](https://doc.rust-lang.org/proc_macro/enum.TokenTree.html).)

 Token trees in `macro_rules` (corresponding to `tt` matchers) are defined as

 * Delimited groups (`(...)`, `{...}`, etc)
* All operators supported by the language, both single-character and multi-character ones (`+`, `+=`).
	+ Note that this set doesn't include the single quote `'`.
* Literals (`"string"`, `1`, etc)
	+ Note that negation (e.g. `-1`) is never a part of such literal tokens, but a separate operator token.
* Identifiers, including keywords (`ident`, `r#ident`, `fn`)
* Lifetimes (`'ident`)
* Metavariable substitutions in `macro_rules` (e.g. `$my_expr` in `macro_rules! mac { ($my_expr: expr) => { $my_expr } }` after the `mac`'s expansion, which will be considered a single token tree regardless of the passed expression)

 Token trees in procedural macros are defined as

 * Delimited groups (`(...)`, `{...}`, etc)
* All punctuation characters used in operators supported by the language (`+`, but not `+=`), and also the single quote `'` character (typically used in lifetimes, see below for lifetime splitting and joining behavior)
* Literals (`"string"`, `1`, etc)
	+ Negation (e.g. `-1`) is supported as a part of integer and floating point literals.
* Identifiers, including keywords (`ident`, `r#ident`, `fn`)

 Mismatches between these two definitions are accounted for when token streams are passed to and from procedural macros.   
 Note that the conversions below may happen lazily, so they might not happen if the tokens are not actually inspected.

 When passed to a proc-macro

 * All multi-character operators are broken into single characters.
* Lifetimes are broken into a `'` character and an identifier.
* All metavariable substitutions are represented as their underlying token streams.
	+ Such token streams may be wrapped into delimited groups ([`Group`](https://doc.rust-lang.org/proc_macro/struct.Group.html)) with implicit delimiters ([`Delimiter::None`](https://doc.rust-lang.org/proc_macro/enum.Delimiter.html#variant.None)) when it's necessary for preserving parsing priorities.
	+ `tt` and `ident` substitutions are never wrapped into such groups and always represented as their underlying token trees.

 When emitted from a proc macro

 * Punctuation characters are glued into multi-character operators when applicable.
* Single quotes `'` joined with identifiers are glued into lifetimes.
* Negative literals are converted into two tokens (the `-` and the literal) possibly wrapped into a delimited group ([`Group`](https://doc.rust-lang.org/proc_macro/struct.Group.html)) with implicit delimiters ([`Delimiter::None`](https://doc.rust-lang.org/proc_macro/enum.Delimiter.html#variant.None)) when it's necessary for preserving parsing priorities.

 Note that neither declarative nor procedural macros support doc comment tokens (e.g. `/// Doc`), so they are always converted to token streams representing their equivalent `#[doc = r"str"]` attributes when passed to macros.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/procedural-macros.html>

Crates and source files
=======================

 
>  **Syntax**  
>  *Crate* :  
>  UTF8BOM?  
>  SHEBANG?  
>  [*InnerAttribute*](attributes)\*  
>  [*Item*](items)\*
> 
>  

 
>  **Lexer**  
>  UTF8BOM : `\uFEFF`  
>  SHEBANG : `#!` ~`\n`+[†](#shebang)
> 
>  

 
>  Note: Although Rust, like any other language, can be implemented by an interpreter as well as a compiler, the only existing implementation is a compiler, and the language has always been designed to be compiled. For these reasons, this section assumes a compiler.
> 
>  

 Rust's semantics obey a *phase distinction* between compile-time and run-time.[1](#phase-distinction) Semantic rules that have a *static interpretation* govern the success or failure of compilation, while semantic rules that have a *dynamic interpretation* govern the behavior of the program at run-time.

 The compilation model centers on artifacts called *crates*. Each compilation processes a single crate in source form, and if successful, produces a single crate in binary form: either an executable or some sort of library.[2](#cratesourcefile)

 A *crate* is a unit of compilation and linking, as well as versioning, distribution, and runtime loading. A crate contains a *tree* of nested [module](items/modules) scopes. The top level of this tree is a module that is anonymous (from the point of view of paths within the module) and any item within a crate has a canonical [module path](paths) denoting its location within the crate's module tree.

 The Rust compiler is always invoked with a single source file as input, and always produces a single output crate. The processing of that source file may result in other source files being loaded as modules. Source files have the extension `.rs`.

 A Rust source file describes a module, the name and location of which — in the module tree of the current crate — are defined from outside the source file: either by an explicit [*Module*](items/modules) item in a referencing source file, or by the name of the crate itself. Every source file is a module, but not every module needs its own source file: [module definitions](items/modules) can be nested within one file.

 Each source file contains a sequence of zero or more [*Item*](items) definitions, and may optionally begin with any number of <attributes> that apply to the containing module, most of which influence the behavior of the compiler. The anonymous crate module can have additional attributes that apply to the crate as a whole.

 
```
#![allow(unused)]
fn main() {
// Specify the crate name.
#![crate_name = "projx"]

// Specify the type of output artifact.
#![crate_type = "lib"]

// Turn on a warning.
// This can be done in any module, not just the anonymous crate module.
#![warn(non_camel_case_types)]
}
```
 Byte order mark
---------------

 The optional [*UTF8 byte order mark*](https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8) (UTF8BOM production) indicates that the file is encoded in UTF8. It can only occur at the beginning of the file and is ignored by the compiler.

 Shebang
-------

 A source file can have a [*shebang*](https://en.wikipedia.org/wiki/Shebang_(Unix)) (SHEBANG production), which indicates to the operating system what program to use to execute this file. It serves essentially to treat the source file as an executable script. The shebang can only occur at the beginning of the file (but after the optional *UTF8BOM*). It is ignored by the compiler. For example:

 
```
#!/usr/bin/env rustx

fn main() {
    println!("Hello!");
}
```
 A restriction is imposed on the shebang syntax to avoid confusion with an [attribute](attributes). The `#!` characters must not be followed by a `[` token, ignoring intervening <comments> or <whitespace>. If this restriction fails, then it is not treated as a shebang, but instead as the start of an attribute.

 Preludes and `no_std`
---------------------

 This section has been moved to the [Preludes chapter](names/preludes).

 Main Functions
--------------

 A crate that contains a `main` [function](items/functions) can be compiled to an executable. If a `main` function is present, it must take no arguments, must not declare any [trait or lifetime bounds](trait-bounds), must not have any [where clauses](items/generics#where-clauses), and its return type must implement the [`Termination`](../std/process/trait.termination) trait.

 
```
fn main() {}
```
 
```
fn main() -> ! {
    std::process::exit(0);
}
```
 
```
fn main() -> impl std::process::Termination {
    std::process::ExitCode::SUCCESS
}
```
 
>  **Note**: Types with implementations of [`Termination`](../std/process/trait.termination) in the standard library include:
> 
>  * `()`
> * [`!`](types/never)
> * [`Infallible`](../std/convert/enum.infallible)
> * [`ExitCode`](../std/process/struct.exitcode)
> * `Result<T, E> where T: Termination, E: Debug`
> 
>  

 ### The `no_main` attribute

 The *`no_main` [attribute](attributes)* may be applied at the crate level to disable emitting the `main` symbol for an executable binary. This is useful when some other object being linked to defines `main`.

 The `crate_name` attribute
--------------------------

 The *`crate_name` [attribute](attributes)* may be applied at the crate level to specify the name of the crate with the [*MetaNameValueStr*](attributes#meta-item-attribute-syntax) syntax.

 
```
#![allow(unused)]
#![crate_name = "mycrate"]
fn main() {
}
```
 The crate name must not be empty, and must only contain [Unicode alphanumeric](../std/primitive.char#method.is_alphanumeric) or `_` (U+005F) characters.

 
1 This distinction would also exist in an interpreter. Static checks like syntactic analysis, type checking, and lints should happen before the program is executed regardless of when it is executed.

  
2 A crate is somewhat analogous to an *assembly* in the ECMA-335 CLI model, a *library* in the SML/NJ Compilation Manager, a *unit* in the Owens and Flatt module system, or a *configuration* in Mesa.

 

 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/crates-and-source-files.html>

Conditional compilation
=======================

 
>  **Syntax**  
>  *ConfigurationPredicate* :  
>  *ConfigurationOption*  
>  | *ConfigurationAll*  
>  | *ConfigurationAny*  
>  | *ConfigurationNot*
> 
>  *ConfigurationOption* :  
>  [IDENTIFIER](identifiers) (`=` ([STRING\_LITERAL](tokens#string-literals) | [RAW\_STRING\_LITERAL](tokens#raw-string-literals)))?
> 
>  *ConfigurationAll*  
>  `all` `(` *ConfigurationPredicateList*? `)`
> 
>  *ConfigurationAny*  
>  `any` `(` *ConfigurationPredicateList*? `)`
> 
>  *ConfigurationNot*  
>  `not` `(` *ConfigurationPredicate* `)`
> 
>  *ConfigurationPredicateList*  
>  *ConfigurationPredicate* (`,` *ConfigurationPredicate*)\* `,`?
> 
>  

 *Conditionally compiled source code* is source code that may or may not be considered a part of the source code depending on certain conditions. Source code can be conditionally compiled using the <attributes> [`cfg`](#the-cfg-attribute) and [`cfg_attr`](#the-cfg_attr-attribute) and the built-in [`cfg` macro](#the-cfg-macro). These conditions are based on the target architecture of the compiled crate, arbitrary values passed to the compiler, and a few other miscellaneous things further described below in detail.

 Each form of conditional compilation takes a *configuration predicate* that evaluates to true or false. The predicate is one of the following:

 * A configuration option. It is true if the option is set and false if it is unset.
* `all()` with a comma separated list of configuration predicates. It is false if at least one predicate is false. If there are no predicates, it is true.
* `any()` with a comma separated list of configuration predicates. It is true if at least one predicate is true. If there are no predicates, it is false.
* `not()` with a configuration predicate. It is true if its predicate is false and false if its predicate is true.

 *Configuration options* are names and key-value pairs that are either set or unset. Names are written as a single identifier such as, for example, `unix`. Key-value pairs are written as an identifier, `=`, and then a string. For example, `target_arch = "x86_64"` is a configuration option.

 
>  **Note**: Whitespace around the `=` is ignored. `foo="bar"` and `foo = "bar"` are equivalent configuration options.
> 
>  

 Keys are not unique in the set of key-value configuration options. For example, both `feature = "std"` and `feature = "serde"` can be set at the same time.

 Set Configuration Options
-------------------------

 Which configuration options are set is determined statically during the compilation of the crate. Certain options are *compiler-set* based on data about the compilation. Other options are *arbitrarily-set*, set based on input passed to the compiler outside of the code. It is not possible to set a configuration option from within the source code of the crate being compiled.

 
>  **Note**: For `rustc`, arbitrary-set configuration options are set using the [`--cfg`](https://doc.rust-lang.org/rustc/command-line-arguments.html#--cfg-configure-the-compilation-environment) flag.
> 
>  

 
>  **Note**: Configuration options with the key `feature` are a convention used by [Cargo](https://doc.rust-lang.org/cargo/reference/features.html) for specifying compile-time options and optional dependencies.
> 
>  

  Warning: It is possible for arbitrarily-set configuration options to have the same value as compiler-set configuration options. For example, it is possible to do `rustc --cfg "unix" program.rs` while compiling to a Windows target, and have both `unix` and `windows` configuration options set at the same time. It is unwise to actually do this.

  ### `target_arch`

 Key-value option set once with the target's CPU architecture. The value is similar to the first element of the platform's target triple, but not identical.

 Example values:

 * `"x86"`
* `"x86_64"`
* `"mips"`
* `"powerpc"`
* `"powerpc64"`
* `"arm"`
* `"aarch64"`

 ### `target_feature`

 Key-value option set for each platform feature available for the current compilation target.

 Example values:

 * `"avx"`
* `"avx2"`
* `"crt-static"`
* `"rdrand"`
* `"sse"`
* `"sse2"`
* `"sse4.1"`

 See the [`target_feature` attribute](attributes/codegen#the-target_feature-attribute) for more details on the available features. An additional feature of `crt-static` is available to the `target_feature` option to indicate that a [static C runtime](linkage#static-and-dynamic-c-runtimes) is available.

 ### `target_os`

 Key-value option set once with the target's operating system. This value is similar to the second and third element of the platform's target triple.

 Example values:

 * `"windows"`
* `"macos"`
* `"ios"`
* `"linux"`
* `"android"`
* `"freebsd"`
* `"dragonfly"`
* `"openbsd"`
* `"netbsd"`

 ### `target_family`

 Key-value option providing a more generic description of a target, such as the family of the operating systems or architectures that the target generally falls into. Any number of `target_family` key-value pairs can be set.

 Example values:

 * `"unix"`
* `"windows"`
* `"wasm"`

 ### 
`unix` and `windows`

 `unix` is set if `target_family = "unix"` is set and `windows` is set if `target_family = "windows"` is set.

 ### `target_env`

 Key-value option set with further disambiguating information about the target platform with information about the ABI or `libc` used. For historical reasons, this value is only defined as not the empty-string when actually needed for disambiguation. Thus, for example, on many GNU platforms, this value will be empty. This value is similar to the fourth element of the platform's target triple. One difference is that embedded ABIs such as `gnueabihf` will simply define `target_env` as `"gnu"`.

 Example values:

 * `""`
* `"gnu"`
* `"msvc"`
* `"musl"`
* `"sgx"`

 ### `target_endian`

 Key-value option set once with either a value of "little" or "big" depending on the endianness of the target's CPU.

 ### `target_pointer_width`

 Key-value option set once with the target's pointer width in bits.

 Example values:

 * `"16"`
* `"32"`
* `"64"`

 ### `target_vendor`

 Key-value option set once with the vendor of the target.

 Example values:

 * `"apple"`
* `"fortanix"`
* `"pc"`
* `"unknown"`

 ### `target_has_atomic`

 Key-value option set for each bit width that the target supports atomic loads, stores, and compare-and-swap operations.

 When this cfg is present, all of the stable [`core::sync::atomic`](https://doc.rust-lang.org/core/sync/atomic/index.html) APIs are available for the relevant atomic width.

 Possible values:

 * `"8"`
* `"16"`
* `"32"`
* `"64"`
* `"128"`
* `"ptr"`

 ### `test`

 Enabled when compiling the test harness. Done with `rustc` by using the [`--test`](https://doc.rust-lang.org/rustc/command-line-arguments.html#--test-build-a-test-harness) flag. See [Testing](attributes/testing) for more on testing support.

 ### `debug_assertions`

 Enabled by default when compiling without optimizations. This can be used to enable extra debugging code in development but not in production. For example, it controls the behavior of the standard library's [`debug_assert!`](../std/macro.debug_assert) macro.

 ### `proc_macro`

 Set when the crate being compiled is being compiled with the `proc_macro` [crate type](linkage).

 ### `panic`

 Key-value option set depending on the panic strategy. Note that more values may be added in the future.

 Example values:

 * `"abort"`
* `"unwind"`

 Forms of conditional compilation
--------------------------------

 ### The `cfg` attribute

 
>  **Syntax**  
>  *CfgAttrAttribute* :  
>  `cfg` `(` *ConfigurationPredicate* `)`
> 
>  

 The `cfg` [attribute](attributes) conditionally includes the thing it is attached to based on a configuration predicate.

 It is written as `cfg`, `(`, a configuration predicate, and finally `)`.

 If the predicate is true, the thing is rewritten to not have the `cfg` attribute on it. If the predicate is false, the thing is removed from the source code.

 Some examples on functions:

 
```
#![allow(unused)]
fn main() {
// The function is only included in the build when compiling for macOS
#[cfg(target_os = "macos")]
fn macos_only() {
  // ...
}

// This function is only included when either foo or bar is defined
#[cfg(any(foo, bar))]
fn needs_foo_or_bar() {
  // ...
}

// This function is only included when compiling for a unixish OS with a 32-bit
// architecture
#[cfg(all(unix, target_pointer_width = "32"))]
fn on_32bit_unix() {
  // ...
}

// This function is only included when foo is not defined
#[cfg(not(foo))]
fn needs_not_foo() {
  // ...
}

// This function is only included when the panic strategy is set to unwind
#[cfg(panic = "unwind")]
fn when_unwinding() {
  // ...
}

}
```
 The `cfg` attribute is allowed anywhere attributes are allowed.

 ### The `cfg_attr` attribute

 
>  **Syntax**  
>  *CfgAttrAttribute* :  
>  `cfg_attr` `(` *ConfigurationPredicate* `,` *CfgAttrs*? `)`
> 
>  *CfgAttrs* :  
>  [*Attr*](attributes) (`,` [*Attr*](attributes))\* `,`?
> 
>  

 The `cfg_attr` [attribute](attributes) conditionally includes <attributes> based on a configuration predicate.

 When the configuration predicate is true, this attribute expands out to the attributes listed after the predicate. For example, the following module will either be found at `linux.rs` or `windows.rs` based on the target.

 
```
#[cfg_attr(target_os = "linux", path = "linux.rs")]
#[cfg_attr(windows, path = "windows.rs")]
mod os;
```
 Zero, one, or more attributes may be listed. Multiple attributes will each be expanded into separate attributes. For example:

 
```
#[cfg_attr(feature = "magic", sparkles, crackles)]
fn bewitched() {}

// When the `magic` feature flag is enabled, the above will expand to:
#[sparkles]
#[crackles]
fn bewitched() {}
```
 
>  **Note**: The `cfg_attr` can expand to another `cfg_attr`. For example, `#[cfg_attr(target_os = "linux", cfg_attr(feature = "multithreaded", some_other_attribute))]` is valid. This example would be equivalent to `#[cfg_attr(all(target_os = "linux", feature ="multithreaded"), some_other_attribute)]`.
> 
>  

 The `cfg_attr` attribute is allowed anywhere attributes are allowed.

 ### The `cfg` macro

 The built-in `cfg` macro takes in a single configuration predicate and evaluates to the `true` literal when the predicate is true and the `false` literal when it is false.

 For example:

 
```
#![allow(unused)]
fn main() {
let machine_kind = if cfg!(unix) {
  "unix"
} else if cfg!(windows) {
  "windows"
} else {
  "unknown"
};

println!("I'm running on a {} machine!", machine_kind);
}
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/conditional-compilation.html>

Items
=====

 
>  **Syntax:**  
>  *Item*:  
>  [*OuterAttribute*](attributes)\*  
>  *VisItem*  
>  | *MacroItem*
> 
>  *VisItem*:  
>  [*Visibility*](visibility-and-privacy)?  
>  (  
>  [*Module*](items/modules)  
>  | [*ExternCrate*](items/extern-crates)  
>  | [*UseDeclaration*](items/use-declarations)  
>  | [*Function*](items/functions)  
>  | [*TypeAlias*](items/type-aliases)  
>  | [*Struct*](items/structs)  
>  | [*Enumeration*](items/enumerations)  
>  | [*Union*](items/unions)  
>  | [*ConstantItem*](items/constant-items)  
>  | [*StaticItem*](items/static-items)  
>  | [*Trait*](items/traits)  
>  | [*Implementation*](items/implementations)  
>  | [*ExternBlock*](items/external-blocks)  
>  )
> 
>  *MacroItem*:  
>  [*MacroInvocationSemi*](macros#macro-invocation)  
>  | [*MacroRulesDefinition*](macros-by-example)
> 
>  

 An *item* is a component of a crate. Items are organized within a crate by a nested set of [modules](items/modules). Every crate has a single "outermost" anonymous module; all further items within the crate have <paths> within the module tree of the crate.

 Items are entirely determined at compile-time, generally remain fixed during execution, and may reside in read-only memory.

 There are several kinds of items:

 * [modules](items/modules)
* [`extern crate` declarations](items/extern-crates)
* [`use` declarations](items/use-declarations)
* [function definitions](items/functions)
* [type definitions](items/type-aliases)
* [struct definitions](items/structs)
* [enumeration definitions](items/enumerations)
* [union definitions](items/unions)
* [constant items](items/constant-items)
* [static items](items/static-items)
* [trait definitions](items/traits)
* [implementations](items/implementations)
* [`extern` blocks](items/external-blocks)

 Some items form an implicit scope for the declaration of sub-items. In other words, within a function or module, declarations of items can (in many cases) be mixed with the statements, control blocks, and similar artifacts that otherwise compose the item body. The meaning of these scoped items is the same as if the item was declared outside the scope — it is still a static item — except that the item's *path name* within the module namespace is qualified by the name of the enclosing item, or is private to the enclosing item (in the case of functions). The grammar specifies the exact locations in which sub-item declarations may appear.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/items.html>

Modules
=======

 
>  **Syntax:**  
>  *Module* :  
>  `unsafe`? `mod` [IDENTIFIER](../identifiers) `;`  
>  | `unsafe`? `mod` [IDENTIFIER](../identifiers) `{`  
>  [*InnerAttribute*](../attributes)\*  
>  [*Item*](../items)\*  
>  `}`
> 
>  

 A module is a container for zero or more [items](../items).

 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. 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!();
    }
}
}
```
 Modules and types share the same namespace. Declaring a named type with the same name as a module in scope is forbidden: that is, a type definition, trait, struct, enumeration, union, type parameter or crate can't shadow the name of a module in scope, or vice versa. Items brought into scope with `use` also have this restriction.

 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.

 Module Source Filenames
-----------------------

 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](../paths). 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` |  |

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

 ### The `path` attribute

 The directories and files used for loading external file modules can be influenced with the `path` attribute.

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

  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;
}
```
 Attributes on Modules
---------------------

 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.

 The built-in attributes that have meaning on a module are [`cfg`](../conditional-compilation), [`deprecated`](../attributes/diagnostics#the-deprecated-attribute), [`doc`](https://doc.rust-lang.org/rustdoc/the-doc-attribute.html), [the lint check attributes](../attributes/diagnostics#lint-check-attributes), [`path`](#the-path-attribute), and [`no_implicit_prelude`](../names/preludes#the-no_implicit_prelude-attribute). Modules also accept macro attributes.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/items/modules.html>

Extern crate declarations
=========================

 
>  **Syntax:**  
>  *ExternCrate* :  
>  `extern` `crate` *CrateRef* *AsClause*? `;`
> 
>  *CrateRef* :  
>  [IDENTIFIER](../identifiers) | `self`
> 
>  *AsClause* :  
>  `as` ( [IDENTIFIER](../identifiers) | `_` )
> 
>  

 An *`extern crate` declaration* specifies a dependency on an external crate. The external crate is then bound into the declaring scope as the [identifier](../identifiers) provided in the `extern crate` declaration. Additionally, if the `extern crate` appears in the crate root, then the crate name is also added to the [extern prelude](../names/preludes#extern-prelude), making it automatically in scope in all modules. The `as` clause can be used to bind the imported crate to a different name.

 The external crate is resolved to a specific `soname` at compile time, and a runtime linkage requirement to that `soname` is passed to the linker for loading at runtime. The `soname` is resolved at compile time by scanning the compiler's library path and matching the optional `crate_name` provided against the [`crate_name` attributes](../crates-and-source-files#the-crate_name-attribute) that were declared on the external crate when it was compiled. If no `crate_name` is provided, a default `name` attribute is assumed, equal to the [identifier](../identifiers) given in the `extern crate` declaration.

 The `self` crate may be imported which creates a binding to the current crate. In this case the `as` clause must be used to specify the name to bind it to.

 Three examples of `extern crate` declarations:

 
```
extern crate pcre;

extern crate std; // equivalent to: extern crate std as std;

extern crate std as ruststd; // linking to 'std' under another name
```
 When naming Rust crates, hyphens are disallowed. However, Cargo packages may make use of them. In such case, when `Cargo.toml` doesn't specify a crate name, Cargo will transparently replace `-` with `_` (Refer to [RFC 940](https://github.com/rust-lang/rfcs/blob/master/text/0940-hyphens-considered-harmful.md) for more details).

 Here is an example:

 
```
// Importing the Cargo package hello-world
extern crate hello_world; // hyphen replaced with an underscore
```
 Extern Prelude
--------------

 This section has been moved to [Preludes — Extern Prelude](../names/preludes#extern-prelude).

 Underscore Imports
------------------

 An external crate dependency can be declared without binding its name in scope by using an underscore with the form `extern crate foo as _`. This may be useful for crates that only need to be linked, but are never referenced, and will avoid being reported as unused.

 The [`macro_use` attribute](../macros-by-example#the-macro_use-attribute) works as usual and imports the macro names into the [`macro_use` prelude](../names/preludes#macro_use-prelude).

 The `no_link` attribute
-----------------------

 The *`no_link` attribute* may be specified on an `extern crate` item to prevent linking the crate into the output. This is commonly used to load a crate to access only its macros.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/items/extern-crates.html>

Use declarations
================

 
>  **Syntax:**  
>  *UseDeclaration* :  
>  `use` *UseTree* `;`
> 
>  *UseTree* :  
>  ([*SimplePath*](../paths#simple-paths)? `::`)? `*`  
>  | ([*SimplePath*](../paths#simple-paths)? `::`)? `{` (*UseTree* ( `,` *UseTree* )\* `,`?)? `}`  
>  | [*SimplePath*](../paths#simple-paths) ( `as` ( [IDENTIFIER](../identifiers) | `_` ) )?
> 
>  

 A *use declaration* creates one or more local name bindings synonymous with some other [path](../paths). Usually a `use` declaration is used to shorten the path required to refer to a module item. These declarations may appear in <modules> and [blocks](../expressions/block-expr), usually at the top.

 Use declarations support a number of convenient shortcuts:

 * 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` 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}};`

 An example of `use` declarations:

 
```
use std::collections::hash_map::{self, HashMap};

fn foo<T>(_: T){}
fn bar(map1: HashMap<String, usize>, map2: hash_map::HashMap<String, usize>){}

fn main() {
    // use declarations can also exist inside of functions
    use std::option::Option::{Some, None};

    // Equivalent to 'foo(vec![std::option::Option::Some(1.0f64),
    // std::option::Option::None]);'
    foo(vec![Some(1.0f64), None]);

    // Both `hash_map` and `HashMap` are in scope.
    let map1 = HashMap::new();
    let map2 = hash_map::HashMap::new();
    bar(map1, map2);
}
```
 
`use` Visibility
-----------------

 Like items, `use` declarations are private to the containing module, by default. Also like items, a `use` declaration can be public, if qualified by the `pub` keyword. Such a `use` declaration serves to *re-export* a name. A public `use` declaration can therefore *redirect* some public name to a different target definition: even a definition with a private canonical path, inside a different module. If a sequence of such redirections form a cycle or cannot be resolved unambiguously, they represent a compile-time error.

 An example of re-exporting:

 
```
mod quux {
    pub use self::foo::{bar, baz};
    pub mod foo {
        pub fn bar() {}
        pub fn baz() {}
    }
}

fn main() {
    quux::bar();
    quux::baz();
}
```
 In this example, the module `quux` re-exports two public names defined in `foo`.

 
`use` Paths
------------

 
>  **Note**: This section is incomplete.
> 
>  

 Some examples of what will and will not work for `use` items:

 
```
#![allow(unused_imports)]
use std::path::{self, Path, PathBuf};  // good: std is a crate name
use crate::foo::baz::foobaz;    // good: foo is at the root of the crate

mod foo {

    pub mod example {
        pub mod iter {}
    }

    use crate::foo::example::iter; // good: foo is at crate root
//  use example::iter;      // bad in 2015 edition: relative paths are not allowed without `self`; good in 2018 edition
    use self::baz::foobaz;  // good: self refers to module 'foo'
    use crate::foo::bar::foobar;   // good: foo is at crate root

    pub mod bar {
        pub fn foobar() { }
    }

    pub mod baz {
        use super::bar::foobar; // good: super refers to module 'foo'
        pub fn foobaz() { }
    }
}

fn main() {}
```
 
>  **Edition Differences**: In the 2015 edition, `use` paths also allow accessing items in the crate root. Using the example above, the following `use` paths work in 2015 but not 2018:
> 
>  
> ```
> mod foo {
>     pub mod example { pub mod iter {} }
>     pub mod baz { pub fn foobaz() {} }
> }
> use foo::example::iter;
> use ::foo::baz::foobaz;
> fn main() {}
> ```
>  The 2015 edition does not allow use declarations to reference the [extern prelude](../names/preludes#extern-prelude). Thus [`extern crate`](extern-crates) declarations are still required in 2015 to reference an external crate in a use declaration. Beginning with the 2018 edition, use declarations can specify an external crate dependency the same way `extern crate` can.
> 
>  In the 2018 edition, if an in-scope item has the same name as an external crate, then `use` of that crate name requires a leading `::` to unambiguously select the crate name. This is to retain compatibility with potential future changes. 
> 
>  
> ```
> // use std::fs; // Error, this is ambiguous.
> use ::std::fs;  // Imports from the `std` crate, not the module below.
> use self::std::fs as self_fs;  // Imports the module below.
> 
> mod std {
>     pub mod fs {}
> }
> fn main() {}
> ```
>  

 Underscore Imports
------------------

 Items can be imported without binding to a name by using an underscore with the form `use path as _`. This is particularly useful to import a trait so that its methods may be used without importing the trait's symbol, for example if the trait's symbol may conflict with another symbol. Another example is to link an external crate without importing its name.

 Asterisk glob imports will import items imported with `_` in their unnameable form.

 
```
mod foo {
    pub trait Zoo {
        fn zoo(&self) {}
    }

    impl<T> Zoo for T {}
}

use self::foo::Zoo as _;
struct Zoo;  // Underscore import avoids name conflict with this item.

fn main() {
    let z = Zoo;
    z.zoo();
}
```
 The unique, unnameable symbols are created after macro expansion so that macros may safely emit multiple references to `_` imports. For example, the following should not produce an error:

 
```
#![allow(unused)]
fn main() {
macro_rules! m {
    ($item: item) => { $item $item }
}

m!(use std as _;);
// This expands to:
// use std as _;
// use std as _;
}
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/items/use-declarations.html>

Functions
=========

 
>  **Syntax**  
>  *Function* :  
>  *FunctionQualifiers* `fn` [IDENTIFIER](../identifiers) [*GenericParams*](generics)?  
>  `(` *FunctionParameters*? `)`  
>  *FunctionReturnType*? [*WhereClause*](generics#where-clauses)?  
>  ( [*BlockExpression*](../expressions/block-expr) | `;` )
> 
>  *FunctionQualifiers* :  
>  `const`? `async`[1](#async-edition)? `unsafe`? (`extern` *Abi*?)?
> 
>  *Abi* :  
>  [STRING\_LITERAL](../tokens#string-literals) | [RAW\_STRING\_LITERAL](../tokens#raw-string-literals)
> 
>  *FunctionParameters* :  
>  *SelfParam* `,`?  
>  | (*SelfParam* `,`)? *FunctionParam* (`,` *FunctionParam*)\* `,`?
> 
>  *SelfParam* :  
>  [*OuterAttribute*](../attributes)\* ( *ShorthandSelf* | *TypedSelf* )
> 
>  *ShorthandSelf* :  
>  (`&` | `&` [*Lifetime*](../trait-bounds))? `mut`? `self`
> 
>  *TypedSelf* :  
>  `mut`? `self` `:` [*Type*](../types#type-expressions)
> 
>  *FunctionParam* :  
>  [*OuterAttribute*](../attributes)\* ( *FunctionParamPattern* | `...` | [*Type*](../types#type-expressions) [2](#fn-param-2015) )
> 
>  *FunctionParamPattern* :  
>  [*PatternNoTopAlt*](../patterns) `:` ( [*Type*](../types#type-expressions) | `...` )
> 
>  *FunctionReturnType* :  
>  `->` [*Type*](../types#type-expressions)
> 
>  
> 1 The `async` qualifier is not allowed in the 2015 edition.
> 
>   
> 2 Function parameters with only a type are only allowed in an associated function of a [trait item](traits) in the 2015 edition.
> 
>   

 A *function* consists of a [block](../expressions/block-expr), along with a name, a set of parameters, and an output type. Other than a name, all these are optional. Functions are declared with the keyword `fn`. Functions may declare a set of *input* [*variables*](../variables) as parameters, through which the caller passes arguments into the function, and the *output* [*type*](../types#type-expressions) of the value the function will return to its caller on completion. If the output type is not explicitly stated, it is the [unit type](../types/tuple).

 When referred to, a *function* yields a first-class *value* of the corresponding zero-sized [*function item type*](../types/function-item), which when called evaluates to a direct call to the function.

 For example, this is a simple function:

 
```
#![allow(unused)]
fn main() {
fn answer_to_life_the_universe_and_everything() -> i32 {
    return 42;
}
}
```
 Function parameters
-------------------

 Function parameters are irrefutable [patterns](../patterns), so any pattern that is valid in an else-less `let` binding is also valid as a parameter:

 
```
#![allow(unused)]
fn main() {
fn first((value, _): (i32, i32)) -> i32 { value }
}
```
 If the first parameter is a *SelfParam*, this indicates that the function is a [method](associated-items#methods). Functions with a self parameter may only appear as an [associated function](associated-items#associated-functions-and-methods) in a [trait](traits) or [implementation](implementations).

 A parameter with the `...` token indicates a [variadic function](external-blocks#variadic-functions), and may only be used as the last parameter of an [external block](external-blocks) function. The variadic parameter may have an optional identifier, such as `args: ...`.

 Function body
-------------

 The block of a function is conceptually wrapped in a block that binds the argument patterns and then `return`s the value of the function's block. This means that the tail expression of the block, if evaluated, ends up being returned to the caller. As usual, an explicit return expression within the body of the function will short-cut that implicit return, if reached.

 For example, the function above behaves as if it was written as:

 
```
// argument_0 is the actual first argument passed from the caller
let (value, _) = argument_0;
return {
    value
};
```
 Functions without a body block are terminated with a semicolon. This form may only appear in a [trait](traits) or [external block](external-blocks).

 Generic functions
-----------------

 A *generic function* allows one or more *parameterized types* to appear in its signature. Each type parameter must be explicitly declared in an angle-bracket-enclosed and comma-separated list, following the function name.

 
```
#![allow(unused)]
fn main() {
// foo is generic over A and B

fn foo<A, B>(x: A, y: B) {
}
}
```
 Inside the function signature and body, the name of the type parameter can be used as a type name. [Trait](traits) bounds can be specified for type parameters to allow methods with that trait to be called on values of that type. This is specified using the `where` syntax:

 
```
#![allow(unused)]
fn main() {
use std::fmt::Debug;
fn foo<T>(x: T) where T: Debug {
}
}
```
 When a generic function is referenced, its type is instantiated based on the context of the reference. For example, calling the `foo` function here:

 
```
#![allow(unused)]
fn main() {
use std::fmt::Debug;

fn foo<T>(x: &[T]) where T: Debug {
    // details elided
}

foo(&[1, 2]);
}
```
 will instantiate type parameter `T` with `i32`.

 The type parameters can also be explicitly supplied in a trailing [path](../paths) component after the function name. This might be necessary if there is not sufficient context to determine the type parameters. For example, `mem::size_of::<u32>() == 4`.

 Extern function qualifier
-------------------------

 The `extern` function qualifier allows providing function *definitions* that can be called with a particular ABI:

 
```
extern "ABI" fn foo() { /* ... */ }
```
 These are often used in combination with [external block](external-blocks) items which provide function *declarations* that can be used to call functions without providing their *definition*:

 
```
extern "ABI" {
  fn foo(); /* no body */
}
unsafe { foo() }
```
 When `"extern" Abi?*` is omitted from `FunctionQualifiers` in function items, the ABI `"Rust"` is assigned. For example:

 
```
#![allow(unused)]
fn main() {
fn foo() {}
}
```
 is equivalent to:

 
```
#![allow(unused)]
fn main() {
extern "Rust" fn foo() {}
}
```
 Functions can be called by foreign code, and using an ABI that differs from Rust allows, for example, to provide functions that can be called from other programming languages like C:

 
```
#![allow(unused)]
fn main() {
// Declares a function with the "C" ABI
extern "C" fn new_i32() -> i32 { 0 }

// Declares a function with the "stdcall" ABI
#[cfg(target_arch = "x86_64")]
extern "stdcall" fn new_i32_stdcall() -> i32 { 0 }
}
```
 Just as with [external block](external-blocks), when the `extern` keyword is used and the `"ABI"` is omitted, the ABI used defaults to `"C"`. That is, this:

 
```
#![allow(unused)]
fn main() {
extern fn new_i32() -> i32 { 0 }
let fptr: extern fn() -> i32 = new_i32;
}
```
 is equivalent to:

 
```
#![allow(unused)]
fn main() {
extern "C" fn new_i32() -> i32 { 0 }
let fptr: extern "C" fn() -> i32 = new_i32;
}
```
 Functions with an ABI that differs from `"Rust"` do not support unwinding in the exact same way that Rust does. Therefore, unwinding past the end of functions with such ABIs causes the process to abort.

 
>  **Note**: The LLVM backend of the `rustc` implementation aborts the process by executing an illegal instruction.
> 
>  

 Const functions
---------------

 Functions qualified with the `const` keyword are [const functions](../const_eval#const-functions), as are [tuple struct](structs) and [tuple variant](enumerations) constructors. *Const functions* can be called from within [const contexts](../const_eval#const-context).

 Const functions may use the [`extern`](#extern-function-qualifier) function qualifier, but only with the `"Rust"` and `"C"` ABIs.

 Const functions are not allowed to be [async](#async-functions).

 Async functions
---------------

 Functions may be qualified as async, and this can also be combined with the `unsafe` qualifier:

 
```
#![allow(unused)]
fn main() {
async fn regular_example() { }
async unsafe fn unsafe_example() { }
}
```
 Async functions do no work when called: instead, they capture their arguments into a future. When polled, that future will execute the function's body.

 An async function is roughly equivalent to a function that returns [`impl Future`](../types/impl-trait) and with an [`async move` block](../expressions/block-expr#async-blocks) as its body:

 
```
#![allow(unused)]
fn main() {
// Source
async fn example(x: &str) -> usize {
    x.len()
}
}
```
 is roughly equivalent to:

 
```
#![allow(unused)]
fn main() {
use std::future::Future;
// Desugared
fn example<'a>(x: &'a str) -> impl Future<Output = usize> + 'a {
    async move { x.len() }
}
}
```
 The actual desugaring is more complex:

 * The return type in the desugaring is assumed to capture all lifetime parameters from the `async fn` declaration. This can be seen in the desugared example above, which explicitly outlives, and hence captures, `'a`.
* The [`async move` block](../expressions/block-expr#async-blocks) in the body captures all function parameters, including those that are unused or bound to a `_` pattern. This ensures that function parameters are dropped in the same order as they would be if the function were not async, except that the drop occurs when the returned future has been fully awaited.

 For more information on the effect of async, see [`async` blocks](../expressions/block-expr#async-blocks).

 
>  **Edition differences**: Async functions are only available beginning with Rust 2018.
> 
>  

 ### Combining `async` and `unsafe`

 It is legal to declare a function that is both async and unsafe. The resulting function is unsafe to call and (like any async function) returns a future. This future is just an ordinary future and thus an `unsafe` context is not required to "await" it:

 
```
#![allow(unused)]
fn main() {
// Returns a future that, when awaited, dereferences `x`.
//
// Soundness condition: `x` must be safe to dereference until
// the resulting future is complete.
async unsafe fn unsafe_example(x: *const i32) -> i32 {
  *x
}

async fn safe_example() {
    // An `unsafe` block is required to invoke the function initially:
    let p = 22;
    let future = unsafe { unsafe_example(&p) };

    // But no `unsafe` block required here. This will
    // read the value of `p`:
    let q = future.await;
}
}
```
 Note that this behavior is a consequence of the desugaring to a function that returns an `impl Future` -- in this case, the function we desugar to is an `unsafe` function, but the return value remains the same.

 Unsafe is used on an async function in precisely the same way that it is used on other functions: it indicates that the function imposes some additional obligations on its caller to ensure soundness. As in any other unsafe function, these conditions may extend beyond the initial call itself -- in the snippet above, for example, the `unsafe_example` function took a pointer `x` as argument, and then (when awaited) dereferenced that pointer. This implies that `x` would have to be valid until the future is finished executing, and it is the caller's responsibility to ensure that.

 Attributes on functions
-----------------------

 [Outer attributes](../attributes) are allowed on functions. [Inner attributes](../attributes) are allowed directly after the `{` inside its [block](../expressions/block-expr).

 This example shows an inner attribute on a function. The function is documented with just the word "Example".

 
```
#![allow(unused)]
fn main() {
fn documented() {
    #![doc = "Example"]
}
}
```
 
>  Note: Except for lints, it is idiomatic to only use outer attributes on function items.
> 
>  

 The attributes that have meaning on a function are [`cfg`](../conditional-compilation#the-cfg-attribute), [`cfg_attr`](../conditional-compilation#the-cfg_attr-attribute), [`deprecated`](../attributes/diagnostics#the-deprecated-attribute), [`doc`](https://doc.rust-lang.org/rustdoc/the-doc-attribute.html), [`export_name`](../abi#the-export_name-attribute), [`link_section`](../abi#the-link_section-attribute), [`no_mangle`](../abi#the-no_mangle-attribute), [the lint check attributes](../attributes/diagnostics#lint-check-attributes), [`must_use`](../attributes/diagnostics#the-must_use-attribute), [the procedural macro attributes](../procedural-macros), [the testing attributes](../attributes/testing), and [the optimization hint attributes](../attributes/codegen#optimization-hints). Functions also accept attributes macros.

 Attributes on function parameters
---------------------------------

 [Outer attributes](../attributes) are allowed on function parameters and the permitted [built-in attributes](../attributes#built-in-attributes-index) are restricted to `cfg`, `cfg_attr`, `allow`, `warn`, `deny`, and `forbid`.

 
```
#![allow(unused)]
fn main() {
fn len(
    #[cfg(windows)] slice: &[u16],
    #[cfg(not(windows))] slice: &[u8],
) -> usize {
    slice.len()
}
}
```
 Inert helper attributes used by procedural macro attributes applied to items are also allowed but be careful to not include these inert attributes in your final `TokenStream`.

 For example, the following code defines an inert `some_inert_attribute` attribute that is not formally defined anywhere and the `some_proc_macro_attribute` procedural macro is responsible for detecting its presence and removing it from the output token stream.

 
```
#[some_proc_macro_attribute]
fn foo_oof(#[some_inert_attribute] arg: u8) {
}
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/items/functions.html>

Type aliases
============

 
>  **Syntax**  
>  *TypeAlias* :  
>  `type` [IDENTIFIER](../identifiers) [*GenericParams*](generics)? ( `:` [*TypeParamBounds*](../trait-bounds) )? [*WhereClause*](generics#where-clauses)? ( `=` [*Type*](../types#type-expressions) [*WhereClause*](generics#where-clauses)?)? `;`
> 
>  

 A *type alias* defines a new name for an existing [type](../types). Type aliases are declared with the keyword `type`. Every value has a single, specific type, but may implement several different traits, or 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);
}
```
 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
}
```
 A type alias, when not used as an associated type, must include a [*Type*](../types#type-expressions) and may not include [*TypeParamBounds*](../trait-bounds).

 A type alias, when used as an [associated type](associated-items#associated-types) in a [trait](traits), must not include a [*Type*](../types#type-expressions) specification but may include [*TypeParamBounds*](../trait-bounds).

 A type alias, when used as an [associated type](associated-items#associated-types) in a [trait impl](implementations#trait-implementations), must include a [*Type*](../types#type-expressions) specification and may not include [*TypeParamBounds*](../trait-bounds).

 Where clauses before the equals sign on a type alias in a [trait impl](implementations#trait-implementations) (like `type TypeAlias<T> where T: Foo = Bar<T>`) are deprecated. Where clauses after the equals sign (like `type TypeAlias<T> = Bar<T> where T: Foo`) are preferred.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/items/type-aliases.html>

Structs
=======

 
>  **Syntax**  
>  *Struct* :  
>  *StructStruct*  
>  | *TupleStruct*
> 
>  *StructStruct* :  
>  `struct` [IDENTIFIER](../identifiers) [*GenericParams*](generics)? [*WhereClause*](generics#where-clauses)? ( `{` *StructFields*? `}` | `;` )
> 
>  *TupleStruct* :  
>  `struct` [IDENTIFIER](../identifiers) [*GenericParams*](generics)? `(` *TupleFields*? `)` [*WhereClause*](generics#where-clauses)? `;`
> 
>  *StructFields* :  
>  *StructField* (`,` *StructField*)\* `,`?
> 
>  *StructField* :  
>  [*OuterAttribute*](../attributes)\*  
>  [*Visibility*](../visibility-and-privacy)?  
>  [IDENTIFIER](../identifiers) `:` [*Type*](../types#type-expressions)
> 
>  *TupleFields* :  
>  *TupleField* (`,` *TupleField*)\* `,`?
> 
>  *TupleField* :  
>  [*OuterAttribute*](../attributes)\*  
>  [*Visibility*](../visibility-and-privacy)?  
>  [*Type*](../types#type-expressions)
> 
>  

 A *struct* is a nominal [struct type](../types/struct) defined with the keyword `struct`.

 An example of a `struct` item and its use:

 
```
#![allow(unused)]
fn main() {
struct Point {x: i32, y: i32}
let p = Point {x: 10, y: 11};
let px: i32 = p.x;
}
```
 A *tuple struct* is a nominal [tuple type](../types/tuple), also defined with the keyword `struct`. For example:

 
```
#![allow(unused)]
fn main() {
struct Point(i32, i32);
let p = Point(10, 11);
let px: i32 = match p { Point(x, _) => x };
}
```
 A *unit-like struct* is a struct without any fields, defined by leaving off the list of fields entirely. Such a struct implicitly defines a constant of its type with the same name. For example:

 
```
#![allow(unused)]
fn main() {
struct Cookie;
let c = [Cookie, Cookie {}, Cookie, Cookie {}];
}
```
 is equivalent to

 
```
#![allow(unused)]
fn main() {
struct Cookie {}
const Cookie: Cookie = Cookie {};
let c = [Cookie, Cookie {}, Cookie, Cookie {}];
}
```
 The precise memory layout of a struct is not specified. One can specify a particular layout using the [`repr` attribute](../type-layout#representations).



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/items/structs.html>

Enumerations
============

 
>  **Syntax**  
>  *Enumeration* :  
>  `enum` [IDENTIFIER](../identifiers) [*GenericParams*](generics)? [*WhereClause*](generics#where-clauses)? `{` *EnumItems*? `}`
> 
>  *EnumItems* :  
>  *EnumItem* ( `,` *EnumItem* )\* `,`?
> 
>  *EnumItem* :  
>  *OuterAttribute*\* [*Visibility*](../visibility-and-privacy)?  
>  [IDENTIFIER](../identifiers) ( *EnumItemTuple* | *EnumItemStruct* )? *EnumItemDiscriminant*?
> 
>  *EnumItemTuple* :  
>  `(` [*TupleFields*](structs)? `)`
> 
>  *EnumItemStruct* :  
>  `{` [*StructFields*](structs)? `}`
> 
>  *EnumItemDiscriminant* :  
>  `=` [*Expression*](../expressions)
> 
>  

 An *enumeration*, also referred to as an *enum*, is a simultaneous definition of a nominal [enumerated type](../types/enum) as well as a set of *constructors*, that can be used to create or pattern-match values of the corresponding enumerated type.

 Enumerations are declared with the keyword `enum`.

 An example of an `enum` item and its use:

 
```
#![allow(unused)]
fn main() {
enum Animal {
    Dog,
    Cat,
}

let mut a: Animal = Animal::Dog;
a = Animal::Cat;
}
```
 Enum constructors can have either named or unnamed fields:

 
```
#![allow(unused)]
fn main() {
enum Animal {
    Dog(String, f64),
    Cat { name: String, weight: f64 },
}

let mut a: Animal = Animal::Dog("Cocoa".to_string(), 37.2);
a = Animal::Cat { name: "Spotty".to_string(), weight: 2.7 };
}
```
 In this example, `Cat` is a *struct-like enum variant*, whereas `Dog` is simply called an enum variant.

 An enum where no constructors contain fields are called a *field-less enum*. For example, this is a fieldless enum:

 
```
#![allow(unused)]
fn main() {
enum Fieldless {
    Tuple(),
    Struct{},
    Unit,
}
}
```
 If a field-less enum only contains unit variants, the enum is called an *unit-only enum*. For example:

 
```
#![allow(unused)]
fn main() {
enum Enum {
    Foo = 3,
    Bar = 2,
    Baz = 1,
}
}
```
 Discriminants
-------------

 Each enum instance has a *discriminant*: an integer logically associated to it that is used to determine which variant it holds.

 Under the [default representation](../type-layout#the-default-representation), the discriminant is interpreted as an `isize` value. However, the compiler is allowed to use a smaller type (or another means of distinguishing variants) in its actual memory layout.

 ### Assigning discriminant values

 #### Explicit discriminants

 In two circumstances, the discriminant of a variant may be explicitly set by following the variant name with `=` and a [constant expression](../const_eval#constant-expressions):

 1. if the enumeration is "[unit-only](#unit-only-enum)".
2. if a [primitive representation](../type-layout#primitive-representations) is used. For example:

 
```
#![allow(unused)]
fn main() {
#[repr(u8)]
enum Enum {
    Unit = 3,
    Tuple(u16),
    Struct {
        a: u8,
        b: u16,
    } = 1,
}
}
```

 #### Implicit discriminants

 If a discriminant for a variant is not specified, then it is set to one higher than the discriminant of the previous variant in the declaration. If the discriminant of the first variant in the declaration is unspecified, then it is set to zero.

 
```
#![allow(unused)]
fn main() {
enum Foo {
    Bar,            // 0
    Baz = 123,      // 123
    Quux,           // 124
}

let baz_discriminant = Foo::Baz as u32;
assert_eq!(baz_discriminant, 123);
}
```
 #### Restrictions

 It is an error when two variants share the same discriminant.

 
```
#![allow(unused)]
fn main() {
enum SharedDiscriminantError {
    SharedA = 1,
    SharedB = 1
}

enum SharedDiscriminantError2 {
    Zero,       // 0
    One,        // 1
    OneToo = 1  // 1 (collision with previous!)
}
}
```
 It is also an error to have an unspecified discriminant where the previous discriminant is the maximum value for the size of the discriminant.

 
```
#![allow(unused)]
fn main() {
#[repr(u8)]
enum OverflowingDiscriminantError {
    Max = 255,
    MaxPlusOne // Would be 256, but that overflows the enum.
}

#[repr(u8)]
enum OverflowingDiscriminantError2 {
    MaxMinusOne = 254, // 254
    Max,               // 255
    MaxPlusOne         // Would be 256, but that overflows the enum.
}
}
```
 ### Accessing discriminant

 #### Via `mem::discriminant`

 [`mem::discriminant`](../../std/mem/fn.discriminant) returns an opaque reference to the discriminant of an enum value which can be compared. This cannot be used to get the value of the discriminant.

 #### Casting

 If an enumeration is [unit-only](#unit-only-enum) (with no tuple and struct variants), then its discriminant can be directly accessed with a [numeric cast](../expressions/operator-expr#semantics); e.g.:

 
```
#![allow(unused)]
fn main() {
enum Enum {
    Foo,
    Bar,
    Baz,
}

assert_eq!(0, Enum::Foo as isize);
assert_eq!(1, Enum::Bar as isize);
assert_eq!(2, Enum::Baz as isize);
}
```
 [Field-less enums](#field-less-enum) can be casted if they do not have explicit discriminants, or where only unit variants are explicit.

 
```
#![allow(unused)]
fn main() {
enum Fieldless {
    Tuple(),
    Struct{},
    Unit,
}

assert_eq!(0, Fieldless::Tuple() as isize);
assert_eq!(1, Fieldless::Struct{} as isize);
assert_eq!(2, Fieldless::Unit as isize);

#[repr(u8)]
enum FieldlessWithDiscrimants {
    First = 10,
    Tuple(),
    Second = 20,
    Struct{},
    Unit,
}

assert_eq!(10, FieldlessWithDiscrimants::First as u8);
assert_eq!(11, FieldlessWithDiscrimants::Tuple() as u8);
assert_eq!(20, FieldlessWithDiscrimants::Second as u8);
assert_eq!(21, FieldlessWithDiscrimants::Struct{} as u8);
assert_eq!(22, FieldlessWithDiscrimants::Unit as u8);
}
```
 #### Pointer casting

 If the enumeration specifies a [primitive representation](../type-layout#primitive-representations), then the discriminant may be reliably accessed via unsafe pointer casting:

 
```
#![allow(unused)]
fn main() {
#[repr(u8)]
enum Enum {
    Unit,
    Tuple(bool),
    Struct{a: bool},
}

impl Enum {
    fn discriminant(&self) -> u8 {
        unsafe { *(self as *const Self as *const u8) }
    }
}

let unit_like = Enum::Unit;
let tuple_like = Enum::Tuple(true);
let struct_like = Enum::Struct{a: false};

assert_eq!(0, unit_like.discriminant());
assert_eq!(1, tuple_like.discriminant());
assert_eq!(2, struct_like.discriminant());
}
```
 Zero-variant enums
------------------

 Enums with zero variants are known as *zero-variant enums*. As they have no valid values, they cannot be instantiated.

 
```
#![allow(unused)]
fn main() {
enum ZeroVariants {}
}
```
 Zero-variant enums are equivalent to the [never type](../types/never), but they cannot be coerced into other types.

 
```
#![allow(unused)]
fn main() {
enum ZeroVariants {}
let x: ZeroVariants = panic!();
let y: u32 = x; // mismatched type error
}
```
 Variant visibility
------------------

 Enum variants syntactically allow a [*Visibility*](../visibility-and-privacy) annotation, but this is rejected when the enum is validated. This allows items to be parsed with a unified syntax across different contexts where they are used.

 
```
#![allow(unused)]
fn main() {
macro_rules! mac_variant {
    ($vis:vis $name:ident) => {
        enum $name {
            $vis Unit,

            $vis Tuple(u8, u16),

            $vis Struct { f: u8 },
        }
    }
}

// Empty `vis` is allowed.
mac_variant! { E }

// This is allowed, since it is removed before being validated.
#[cfg(FALSE)]
enum E {
    pub U,
    pub(crate) T(u8),
    pub(super) T { f: String }
}
}
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/items/enumerations.html>

Constant items
==============

 
>  **Syntax**  
>  *ConstantItem* :  
>  `const` ( [IDENTIFIER](../identifiers) | `_` ) `:` [*Type*](../types#type-expressions) ( `=` [*Expression*](../expressions) )? `;`
> 
>  

 A *constant item* is an optionally named *[constant value](../const_eval#constant-expressions)* which is not associated with a specific memory location in the program. Constants are essentially inlined wherever they are used, meaning that they are copied directly into the relevant context when used. This includes usage of constants from external crates, and non-[`Copy`](../special-types-and-traits#copy) types. References to the same constant are not necessarily guaranteed to refer to the same memory address.

 Constants must be explicitly typed. The type must have a `'static` lifetime: any references in the initializer must have `'static` lifetimes.

 Constants may refer to the address of other constants, in which case the address will have elided lifetimes where applicable, otherwise – in most cases – defaulting to the `static` lifetime. (See [static lifetime elision](../lifetime-elision#static-lifetime-elision).) The compiler is, however, still at liberty to translate the constant many times, so the address referred to may not be stable.

 
```
#![allow(unused)]
fn main() {
const BIT1: u32 = 1 << 0;
const BIT2: u32 = 1 << 1;

const BITS: [u32; 2] = [BIT1, BIT2];
const STRING: &'static str = "bitstring";

struct BitsNStrings<'a> {
    mybits: [u32; 2],
    mystring: &'a str,
}

const BITS_N_STRINGS: BitsNStrings<'static> = BitsNStrings {
    mybits: BITS,
    mystring: STRING,
};
}
```
 The constant expression may only be omitted in a [trait definition](traits).

 Constants with Destructors
--------------------------

 Constants can contain destructors. Destructors are run when the value goes out of scope.

 
```
#![allow(unused)]
fn main() {
struct TypeWithDestructor(i32);

impl Drop for TypeWithDestructor {
    fn drop(&mut self) {
        println!("Dropped. Held {}.", self.0);
    }
}

const ZERO_WITH_DESTRUCTOR: TypeWithDestructor = TypeWithDestructor(0);

fn create_and_drop_zero_with_destructor() {
    let x = ZERO_WITH_DESTRUCTOR;
    // x gets dropped at end of function, calling drop.
    // prints "Dropped. Held 0.".
}
}
```
 Unnamed constant
----------------

 Unlike an [associated constant](associated-items#associated-constants), a [free](../glossary#free-item) constant may be unnamed by using an underscore instead of the name. For example:

 
```
#![allow(unused)]
fn main() {
const _: () =  { struct _SameNameTwice; };

// OK although it is the same name as above:
const _: () =  { struct _SameNameTwice; };
}
```
 As with [underscore imports](use-declarations#underscore-imports), macros may safely emit the same unnamed constant in the same scope more than once. For example, the following should not produce an error:

 
```
#![allow(unused)]
fn main() {
macro_rules! m {
    ($item: item) => { $item $item }
}

m!(const _: () = (););
// This expands to:
// const _: () = ();
// const _: () = ();
}
```
 Evaluation
----------

 [Free](../glossary#free-item) constants are always [evaluated](../const_eval) at compile-time to surface panics. This happens even within an unused function:

 
```
#![allow(unused)]
fn main() {
// Compile-time panic
const PANIC: () = std::unimplemented!();

fn unused_generic_function<T>() {
    // A failing compile-time assertion
    const _: () = assert!(usize::BITS == 0);
}
}
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/items/constant-items.html>

Static items
============

 
>  **Syntax**  
>  *StaticItem* :  
>  `static` `mut`? [IDENTIFIER](../identifiers) `:` [*Type*](../types#type-expressions) ( `=` [*Expression*](../expressions) )? `;`
> 
>  

 A *static item* is similar to a [constant](constant-items), except that it represents a precise memory location in the program. All references to the static refer to the same memory location. Static items have the `static` lifetime, which outlives all other lifetimes in a Rust program. Static items do not call [`drop`](../destructors) at the end of the program.

 The static initializer is a [constant expression](../const_eval#constant-expressions) evaluated at compile time. Static initializers may refer to other statics.

 Non-`mut` static items that contain a type that is not [interior mutable](../interior-mutability) may be placed in read-only memory.

 All access to a static is safe, but there are a number of restrictions on statics:

 * The type must have the `Sync` trait bound to allow thread-safe access.
* Constants cannot refer to statics.

 The initializer expression must be omitted in an [external block](external-blocks), and must be provided for free static items.

 Statics & generics
------------------

 A static item defined in a generic scope (for example in a blanket or default implementation) will result in exactly one static item being defined, as if the static definition was pulled out of the current scope into the module. There will *not* be one item per monomorphization.

 This code:

 
```
use std::sync::atomic::{AtomicUsize, Ordering};

trait Tr {
    fn default_impl() {
        static COUNTER: AtomicUsize = AtomicUsize::new(0);
        println!("default_impl: counter was {}", COUNTER.fetch_add(1, Ordering::Relaxed));
    }

    fn blanket_impl();
}

struct Ty1 {}
struct Ty2 {}

impl<T> Tr for T {
    fn blanket_impl() {
        static COUNTER: AtomicUsize = AtomicUsize::new(0);
        println!("blanket_impl: counter was {}", COUNTER.fetch_add(1, Ordering::Relaxed));
    }
}

fn main() {
    <Ty1 as Tr>::default_impl();
    <Ty2 as Tr>::default_impl();
    <Ty1 as Tr>::blanket_impl();
    <Ty2 as Tr>::blanket_impl();
}
```
 prints

 
```
default_impl: counter was 0
default_impl: counter was 1
blanket_impl: counter was 0
blanket_impl: counter was 1

```
 Mutable statics
---------------

 If a static item is declared with the `mut` keyword, then it is allowed to be modified by the program. One of Rust's goals is to make concurrency bugs hard to run into, and this is obviously a very large source of race conditions or other bugs. For this reason, an `unsafe` block is required when either reading or writing a mutable static variable. Care should be taken to ensure that modifications to a mutable static are safe with respect to other threads running in the same process.

 Mutable statics are still very useful, however. They can be used with C libraries and can also be bound from C libraries in an `extern` block.

 
```
#![allow(unused)]
fn main() {
fn atomic_add(_: &mut u32, _: u32) -> u32 { 2 }

static mut LEVELS: u32 = 0;

// This violates the idea of no shared state, and this doesn't internally
// protect against races, so this function is `unsafe`
unsafe fn bump_levels_unsafe1() -> u32 {
    let ret = LEVELS;
    LEVELS += 1;
    return ret;
}

// Assuming that we have an atomic_add function which returns the old value,
// this function is "safe" but the meaning of the return value may not be what
// callers expect, so it's still marked as `unsafe`
unsafe fn bump_levels_unsafe2() -> u32 {
    return atomic_add(&mut LEVELS, 1);
}
}
```
 Mutable statics have the same restrictions as normal statics, except that the type does not have to implement the `Sync` trait.

 Using Statics or Consts
-----------------------

 It can be confusing whether or not you should use a constant item or a static item. Constants should, in general, be preferred over statics unless one of the following are true:

 * Large amounts of data are being stored
* The single-address property of statics is required.
* Interior mutability is required.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/items/static-items.html>

Traits
======

 
>  **Syntax**  
>  *Trait* :  
>  `unsafe`? `trait` [IDENTIFIER](../identifiers) [*GenericParams*](generics)? ( `:` [*TypeParamBounds*](../trait-bounds)? )? [*WhereClause*](generics#where-clauses)? `{`  
>  [*InnerAttribute*](../attributes)\*  
>  [*AssociatedItem*](associated-items)\*  
>  `}`
> 
>  

 A *trait* describes an abstract interface that types can implement. This interface consists of [associated items](associated-items), which come in three varieties:

 * [functions](associated-items#associated-functions-and-methods)
* [types](associated-items#associated-types)
* [constants](associated-items#associated-constants)

 All traits define an implicit type parameter `Self` that refers to "the type that is implementing this interface". Traits may also contain additional type parameters. These type parameters, including `Self`, may be constrained by other traits and so forth [as usual](generics).

 Traits are implemented for specific types through separate <implementations>.

 Trait functions may omit the function body by replacing it with a semicolon. This indicates that the implementation must define the function. If the trait function defines a body, this definition acts as a default for any implementation which does not override it. Similarly, associated constants may omit the equals sign and expression to indicate implementations must define the constant value. Associated types must never define the type, the type may only be specified in an implementation.

 
```
#![allow(unused)]
fn main() {
// Examples of associated trait items with and without definitions.
trait Example {
    const CONST_NO_DEFAULT: i32;
    const CONST_WITH_DEFAULT: i32 = 99;
    type TypeNoDefault;
    fn method_without_default(&self);
    fn method_with_default(&self) {}
}
}
```
 Trait functions are not allowed to be [`async`](functions#async-functions) or [`const`](functions#const-functions).

 Trait bounds
------------

 Generic items may use traits as [bounds](../trait-bounds) on their type parameters.

 Generic Traits
--------------

 Type parameters can be specified for a trait to make it generic. These appear after the trait name, using the same syntax used in [generic functions](functions#generic-functions).

 
```
#![allow(unused)]
fn main() {
trait Seq<T> {
    fn len(&self) -> u32;
    fn elt_at(&self, n: u32) -> T;
    fn iter<F>(&self, f: F) where F: Fn(T);
}
}
```
 Object Safety
-------------

 Object safe traits can be the base trait of a [trait object](../types/trait-object). A trait is *object safe* if it has the following qualities (defined in [RFC 255](https://github.com/rust-lang/rfcs/blob/master/text/0255-object-safety.md)):

 * All [supertraits](#supertraits) must also be object safe.
* `Sized` must not be a [supertrait](#supertraits). In other words, it must not require `Self: Sized`.
* It must not have any associated constants.
* It must not have any associated types with generics.
* All associated functions must either be dispatchable from a trait object or be explicitly non-dispatchable:
	+ Dispatchable functions require:
		- Not have any type parameters (although lifetime parameters are allowed),
		- Be a [method](associated-items#methods) that does not use `Self` except in the type of the receiver.
		- Have a receiver with one of the following types:
			* `&Self` (i.e. `&self`)
			* `&mut Self` (i.e `&mut self`)
			* [`Box<Self>`](../special-types-and-traits#boxt)
			* [`Rc<Self>`](../special-types-and-traits#rct)
			* [`Arc<Self>`](../special-types-and-traits#arct)
			* [`Pin<P>`](../special-types-and-traits#pinp) where `P` is one of the types above
		- Does not have a `where Self: Sized` bound (receiver type of `Self` (i.e. `self`) implies this).
	+ Explicitly non-dispatchable functions require:
		- Have a `where Self: Sized` bound (receiver type of `Self` (i.e. `self`) implies this).

 
```
#![allow(unused)]
fn main() {
use std::rc::Rc;
use std::sync::Arc;
use std::pin::Pin;
// Examples of object safe methods.
trait TraitMethods {
    fn by_ref(self: &Self) {}
    fn by_ref_mut(self: &mut Self) {}
    fn by_box(self: Box<Self>) {}
    fn by_rc(self: Rc<Self>) {}
    fn by_arc(self: Arc<Self>) {}
    fn by_pin(self: Pin<&Self>) {}
    fn with_lifetime<'a>(self: &'a Self) {}
    fn nested_pin(self: Pin<Arc<Self>>) {}
}
struct S;
impl TraitMethods for S {}
let t: Box<dyn TraitMethods> = Box::new(S);
}
```
 
```
#![allow(unused)]
fn main() {
// This trait is object-safe, but these methods cannot be dispatched on a trait object.
trait NonDispatchable {
    // Non-methods cannot be dispatched.
    fn foo() where Self: Sized {}
    // Self type isn't known until runtime.
    fn returns(&self) -> Self where Self: Sized;
    // `other` may be a different concrete type of the receiver.
    fn param(&self, other: Self) where Self: Sized {}
    // Generics are not compatible with vtables.
    fn typed<T>(&self, x: T) where Self: Sized {}
}

struct S;
impl NonDispatchable for S {
    fn returns(&self) -> Self where Self: Sized { S }
}
let obj: Box<dyn NonDispatchable> = Box::new(S);
obj.returns(); // ERROR: cannot call with Self return
obj.param(S);  // ERROR: cannot call with Self parameter
obj.typed(1);  // ERROR: cannot call with generic type
}
```
 
```
#![allow(unused)]
fn main() {
use std::rc::Rc;
// Examples of non-object safe traits.
trait NotObjectSafe {
    const CONST: i32 = 1;  // ERROR: cannot have associated const

    fn foo() {}  // ERROR: associated function without Sized
    fn returns(&self) -> Self; // ERROR: Self in return type
    fn typed<T>(&self, x: T) {} // ERROR: has generic type parameters
    fn nested(self: Rc<Box<Self>>) {} // ERROR: nested receiver not yet supported
}

struct S;
impl NotObjectSafe for S {
    fn returns(&self) -> Self { S }
}
let obj: Box<dyn NotObjectSafe> = Box::new(S); // ERROR
}
```
 
```
#![allow(unused)]
fn main() {
// Self: Sized traits are not object-safe.
trait TraitWithSize where Self: Sized {}

struct S;
impl TraitWithSize for S {}
let obj: Box<dyn TraitWithSize> = Box::new(S); // ERROR
}
```
 
```
#![allow(unused)]
fn main() {
// Not object safe if `Self` is a type argument.
trait Super<A> {}
trait WithSelf: Super<Self> where Self: Sized {}

struct S;
impl<A> Super<A> for S {}
impl WithSelf for S {}
let obj: Box<dyn WithSelf> = Box::new(S); // ERROR: cannot use `Self` type parameter
}
```
 Supertraits
-----------

 **Supertraits** are traits that are required to be implemented for a type to implement a specific trait. Furthermore, anywhere a [generic](generics) or [trait object](../types/trait-object) is bounded by a trait, it has access to the associated items of its supertraits.

 Supertraits are declared by trait bounds on the `Self` type of a trait and transitively the supertraits of the traits declared in those trait bounds. It is an error for a trait to be its own supertrait.

 The trait with a supertrait is called a **subtrait** of its supertrait.

 The following is an example of declaring `Shape` to be a supertrait of `Circle`.

 
```
#![allow(unused)]
fn main() {
trait Shape { fn area(&self) -> f64; }
trait Circle : Shape { fn radius(&self) -> f64; }
}
```
 And the following is the same example, except using [where clauses](generics#where-clauses).

 
```
#![allow(unused)]
fn main() {
trait Shape { fn area(&self) -> f64; }
trait Circle where Self: Shape { fn radius(&self) -> f64; }
}
```
 This next example gives `radius` a default implementation using the `area` function from `Shape`.

 
```
#![allow(unused)]
fn main() {
trait Shape { fn area(&self) -> f64; }
trait Circle where Self: Shape {
    fn radius(&self) -> f64 {
        // A = pi * r^2
        // so algebraically,
        // r = sqrt(A / pi)
        (self.area() /std::f64::consts::PI).sqrt()
    }
}
}
```
 This next example calls a supertrait method on a generic parameter.

 
```
#![allow(unused)]
fn main() {
trait Shape { fn area(&self) -> f64; }
trait Circle : Shape { fn radius(&self) -> f64; }
fn print_area_and_radius<C: Circle>(c: C) {
    // Here we call the area method from the supertrait `Shape` of `Circle`.
    println!("Area: {}", c.area());
    println!("Radius: {}", c.radius());
}
}
```
 Similarly, here is an example of calling supertrait methods on trait objects.

 
```
#![allow(unused)]
fn main() {
trait Shape { fn area(&self) -> f64; }
trait Circle : Shape { fn radius(&self) -> f64; }
struct UnitCircle;
impl Shape for UnitCircle { fn area(&self) -> f64 { std::f64::consts::PI } }
impl Circle for UnitCircle { fn radius(&self) -> f64 { 1.0 } }
let circle = UnitCircle;
let circle = Box::new(circle) as Box<dyn Circle>;
let nonsense = circle.radius() * circle.area();
}
```
 Unsafe traits
-------------

 Traits items that begin with the `unsafe` keyword indicate that *implementing* the trait may be [unsafe](../unsafety). It is safe to use a correctly implemented unsafe trait. The [trait implementation](implementations#trait-implementations) must also begin with the `unsafe` keyword.

 [`Sync`](../special-types-and-traits#sync) and [`Send`](../special-types-and-traits#send) are examples of unsafe traits.

 Parameter patterns
------------------

 Function or method declarations without a body only allow [IDENTIFIER](../identifiers) or `_` [wild card](../patterns#wildcard-pattern) patterns. `mut` [IDENTIFIER](../identifiers) is currently allowed, but it is deprecated and will become a hard error in the future.

 In the 2015 edition, the pattern for a trait function or method parameter is optional:

 
```
#![allow(unused)]
fn main() {
// 2015 Edition
trait T {
    fn f(i32);  // Parameter identifiers are not required.
}
}
```
 The kinds of patterns for parameters is limited to one of the following:

 * [IDENTIFIER](../identifiers)
* `mut` [IDENTIFIER](../identifiers)
* [`_`](../patterns#wildcard-pattern)
* `&` [IDENTIFIER](../identifiers)
* `&&` [IDENTIFIER](../identifiers)

 Beginning in the 2018 edition, function or method parameter patterns are no longer optional. Also, all irrefutable patterns are allowed as long as there is a body. Without a body, the limitations listed above are still in effect.

 
```
#![allow(unused)]
fn main() {
trait T {
    fn f1((a, b): (i32, i32)) {}
    fn f2(_: (i32, i32));  // Cannot use tuple pattern without a body.
}
}
```
 Item visibility
---------------

 Trait items syntactically allow a [*Visibility*](../visibility-and-privacy) annotation, but this is rejected when the trait is validated. This allows items to be parsed with a unified syntax across different contexts where they are used. As an example, an empty `vis` macro fragment specifier can be used for trait items, where the macro rule may be used in other situations where visibility is allowed.

 
```
macro_rules! create_method {
    ($vis:vis $name:ident) => {
        $vis fn $name(&self) {}
    };
}

trait T1 {
    // Empty `vis` is allowed.
    create_method! { method_of_t1 }
}

struct S;

impl S {
    // Visibility is allowed here.
    create_method! { pub method_of_s }
}

impl T1 for S {}

fn main() {
    let s = S;
    s.method_of_t1();
    s.method_of_s();
}
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/items/traits.html>

Implementations
===============

 
>  **Syntax**  
>  *Implementation* :  
>  *InherentImpl* | *TraitImpl*
> 
>  *InherentImpl* :  
>  `impl` [*GenericParams*](generics)? [*Type*](../types#type-expressions) [*WhereClause*](generics#where-clauses)? `{`  
>  [*InnerAttribute*](../attributes)\*  
>  [*AssociatedItem*](associated-items)\*  
>  `}`
> 
>  *TraitImpl* :  
>  `unsafe`? `impl` [*GenericParams*](generics)? `!`? [*TypePath*](../paths#paths-in-types) `for` [*Type*](../types#type-expressions)  
>  [*WhereClause*](generics#where-clauses)?  
>  `{`  
>  [*InnerAttribute*](../attributes)\*  
>  [*AssociatedItem*](associated-items)\*  
>  `}`
> 
>  

 An *implementation* is an item that associates items with an *implementing type*. Implementations are defined with the keyword `impl` and contain functions that belong to an instance of the type that is being implemented or to the type statically.

 There are two types of implementations:

 * inherent implementations
* [trait](traits) implementations

 Inherent Implementations
------------------------

 An inherent implementation is defined as the sequence of the `impl` keyword, generic type declarations, a path to a nominal type, a where clause, and a bracketed set of associable items.

 The nominal type is called the *implementing type* and the associable items are the *associated items* to the implementing type.

 Inherent implementations associate the contained items to the implementing type. Inherent implementations can contain [associated functions](associated-items#associated-functions-and-methods) (including [methods](associated-items#methods)) and [associated constants](associated-items#associated-constants). They cannot contain associated type aliases.

 The [path](../paths) to an associated item is any path to the implementing type, followed by the associated item's identifier as the final path component.

 A type can also have multiple inherent implementations. An implementing type must be defined within the same crate as the original type definition.

 
```
pub mod color {
    pub struct Color(pub u8, pub u8, pub u8);

    impl Color {
        pub const WHITE: Color = Color(255, 255, 255);
    }
}

mod values {
    use super::color::Color;
    impl Color {
        pub fn red() -> Color {
            Color(255, 0, 0)
        }
    }
}

pub use self::color::Color;
fn main() {
    // Actual path to the implementing type and impl in the same module.
    color::Color::WHITE;

    // Impl blocks in different modules are still accessed through a path to the type.
    color::Color::red();

    // Re-exported paths to the implementing type also work.
    Color::red();

    // Does not work, because use in `values` is not pub.
    // values::Color::red();
}
```
 Trait Implementations
---------------------

 A *trait implementation* is defined like an inherent implementation except that the optional generic type declarations are followed by a [trait](traits), followed by the keyword `for`, followed by a path to a nominal type.

 The trait is known as the *implemented trait*. The implementing type implements the implemented trait.

 A trait implementation must define all non-default associated items declared by the implemented trait, may redefine default associated items defined by the implemented trait, and cannot define any other items.

 The path to the associated items is `<` followed by a path to the implementing type followed by `as` followed by a path to the trait followed by `>` as a path component followed by the associated item's path component.

 [Unsafe traits](traits#unsafe-traits) require the trait implementation to begin with the `unsafe` keyword.

 
```
#![allow(unused)]
fn main() {
#[derive(Copy, Clone)]
struct Point {x: f64, y: f64};
type Surface = i32;
struct BoundingBox {x: f64, y: f64, width: f64, height: f64};
trait Shape { fn draw(&self, s: Surface); fn bounding_box(&self) -> BoundingBox; }
fn do_draw_circle(s: Surface, c: Circle) { }
struct Circle {
    radius: f64,
    center: Point,
}

impl Copy for Circle {}

impl Clone for Circle {
    fn clone(&self) -> Circle { *self }
}

impl Shape for Circle {
    fn draw(&self, s: Surface) { do_draw_circle(s, *self); }
    fn bounding_box(&self) -> BoundingBox {
        let r = self.radius;
        BoundingBox {
            x: self.center.x - r,
            y: self.center.y - r,
            width: 2.0 * r,
            height: 2.0 * r,
        }
    }
}
}
```
 ### Trait Implementation Coherence

 A trait implementation is considered incoherent if either the orphan rules check fails or there are overlapping implementation instances.

 Two trait implementations overlap when there is a non-empty intersection of the traits the implementation is for, the implementations can be instantiated with the same type. 

 #### Orphan rules

 Given `impl<P1..=Pn> Trait<T1..=Tn> for T0`, an `impl` is valid only if at least one of the following is true:

 * `Trait` is a [local trait](../glossary#local-trait)
* All of
	+ At least one of the types `T0..=Tn` must be a [local type](../glossary#local-type). Let `Ti` be the first such type.
	+ No [uncovered type](../glossary#uncovered-type) parameters `P1..=Pn` may appear in `T0..Ti` (excluding `Ti`)

 Only the appearance of *uncovered* type parameters is restricted. Note that for the purposes of coherence, [fundamental types](../glossary#fundamental-type-constructors) are special. The `T` in `Box<T>` is not considered covered, and `Box<LocalType>` is considered local.

 Generic Implementations
-----------------------

 An implementation can take [generic parameters](generics), which can be used in the rest of the implementation. Implementation parameters are written directly after the `impl` keyword.

 
```
#![allow(unused)]
fn main() {
trait Seq<T> { fn dummy(&self, _: T) { } }
impl<T> Seq<T> for Vec<T> {
    /* ... */
}
impl Seq<bool> for u32 {
    /* Treat the integer as a sequence of bits */
}
}
```
 Generic parameters *constrain* an implementation if the parameter appears at least once in one of:

 * The implemented trait, if it has one
* The implementing type
* As an [associated type](associated-items#associated-types) in the [bounds](../trait-bounds) of a type that contains another parameter that constrains the implementation

 Type and const parameters must always constrain the implementation. Lifetimes must constrain the implementation if the lifetime is used in an associated type.

 Examples of constraining situations:

 
```
#![allow(unused)]
fn main() {
trait Trait{}
trait GenericTrait<T> {}
trait HasAssocType { type Ty; }
struct Struct;
struct GenericStruct<T>(T);
struct ConstGenericStruct<const N: usize>([(); N]);
// T constrains by being an argument to GenericTrait.
impl<T> GenericTrait<T> for i32 { /* ... */ }

// T constrains by being an arguement to GenericStruct
impl<T> Trait for GenericStruct<T> { /* ... */ }

// Likewise, N constrains by being an argument to ConstGenericStruct
impl<const N: usize> Trait for ConstGenericStruct<N> { /* ... */ }

// T constrains by being in an associated type in a bound for type `U` which is
// itself a generic parameter constraining the trait.
impl<T, U> GenericTrait<U> for u32 where U: HasAssocType<Ty = T> { /* ... */ }

// Like previous, except the type is `(U, isize)`. `U` appears inside the type
// that includes `T`, and is not the type itself.
impl<T, U> GenericStruct<U> where (U, isize): HasAssocType<Ty = T> { /* ... */ }
}
```
 Examples of non-constraining situations:

 
```
#![allow(unused)]
fn main() {
// The rest of these are errors, since they have type or const parameters that
// do not constrain.

// T does not constrain since it does not appear at all.
impl<T> Struct { /* ... */ }

// N does not constrain for the same reason.
impl<const N: usize> Struct { /* ... */ }

// Usage of T inside the implementation does not constrain the impl.
impl<T> Struct {
    fn uses_t(t: &T) { /* ... */ }
}

// T is used as an associated type in the bounds for U, but U does not constrain.
impl<T, U> Struct where U: HasAssocType<Ty = T> { /* ... */ }

// T is used in the bounds, but not as an associated type, so it does not constrain.
impl<T, U> GenericTrait<U> for u32 where U: GenericTrait<T> {}
}
```
 Example of an allowed unconstraining lifetime parameter:

 
```
#![allow(unused)]
fn main() {
struct Struct;
impl<'a> Struct {}
}
```
 Example of a disallowed unconstraining lifetime parameter:

 
```
#![allow(unused)]
fn main() {
struct Struct;
trait HasAssocType { type Ty; }
impl<'a> HasAssocType for Struct {
    type Ty = &'a Struct;
}
}
```
 Attributes on Implementations
-----------------------------

 Implementations may contain outer [attributes](../attributes) before the `impl` keyword and inner [attributes](../attributes) inside the brackets that contain the associated items. Inner attributes must come before any associated items. The attributes that have meaning here are [`cfg`](../conditional-compilation), [`deprecated`](../attributes/diagnostics#the-deprecated-attribute), [`doc`](https://doc.rust-lang.org/rustdoc/the-doc-attribute.html), and [the lint check attributes](../attributes/diagnostics#lint-check-attributes).



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/items/implementations.html>

External blocks
===============

 
>  **Syntax**  
>  *ExternBlock* :  
>  `unsafe`? `extern` [*Abi*](functions)? `{`  
>  [*InnerAttribute*](../attributes)\*  
>  *ExternalItem*\*  
>  `}`
> 
>  *ExternalItem* :  
>  [*OuterAttribute*](../attributes)\* (  
>  [*MacroInvocationSemi*](../macros#macro-invocation)  
>  | ( [*Visibility*](../visibility-and-privacy)? ( [*StaticItem*](static-items) | [*Function*](functions) ) )  
>  )
> 
>  

 External blocks provide *declarations* of items that are not *defined* in the current crate and are the basis of Rust's foreign function interface. These are akin to unchecked imports.

 Two kinds of item *declarations* are allowed in external blocks: <functions> and [statics](static-items). Calling functions or accessing statics that are declared in external blocks is only allowed in an `unsafe` context.

 The `unsafe` keyword is syntactically allowed to appear before the `extern` 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.

 Functions
---------

 Functions within external blocks are declared in the same way as other Rust functions, with the exception that they must not have a body and are instead terminated by a semicolon. Patterns are not allowed in parameters, only [IDENTIFIER](../identifiers) or `_` may be used. Function qualifiers (`const`, `async`, `unsafe`, and `extern`) are not allowed.

 Functions within external blocks may be called by Rust code, just like functions defined in Rust. The Rust compiler automatically translates between the Rust ABI and the foreign ABI.

 A function declared in an extern block is implicitly `unsafe`. When coerced to a function pointer, a function declared in an extern block has type `unsafe extern "abi" for<'l1, ..., 'lm> fn(A1, ..., An) -> R`, where `'l1`, ... `'lm` are its lifetime parameters, `A1`, ..., `An` are the declared types of its parameters and `R` is the declared return type.

 Statics
-------

 Statics within external blocks are declared in the same way as [statics](static-items) outside of external blocks, except that they do not have an expression initializing their value. It is `unsafe` to access a static item declared in an extern block, whether or not it's mutable, because there is nothing guaranteeing that the bit pattern at the static's memory is valid for the type it is declared with, since some arbitrary (e.g. C) code is in charge of initializing the static.

 Extern statics can be either immutable or mutable just like [statics](static-items) outside of external blocks. An immutable static *must* be initialized before any Rust code is executed. It is not enough for the static to be initialized before Rust code reads from it.

 ABI
---

 By default external blocks assume that the library they are calling uses the standard C ABI on the specific platform. Other ABIs may be specified using an `abi` string, as shown here:

 
```
#![allow(unused)]
fn main() {
// Interface to the Windows API
extern "stdcall" { }
}
```
 There are three ABI strings which are cross-platform, and which all compilers are guaranteed to support:

 * `extern "Rust"` -- The default ABI when you write a normal `fn foo()` in any Rust code.
* `extern "C"` -- This is the same as `extern fn foo()`; whatever the default your C compiler supports.
* `extern "system"` -- Usually the same as `extern "C"`, except on Win32, in which case it's `"stdcall"`, or what you should use to link to the Windows API itself

 There are also some platform-specific ABI strings:

 * `extern "cdecl"` -- The default for x86\_32 C code.
* `extern "stdcall"` -- The default for the Win32 API on x86\_32.
* `extern "win64"` -- The default for C code on x86\_64 Windows.
* `extern "sysv64"` -- The default for C code on non-Windows x86\_64.
* `extern "aapcs"` -- The default for ARM.
* `extern "fastcall"` -- The `fastcall` ABI -- corresponds to MSVC's `__fastcall` and GCC and clang's `__attribute__((fastcall))`
* `extern "vectorcall"` -- The `vectorcall` ABI -- corresponds to MSVC's `__vectorcall` and clang's `__attribute__((vectorcall))`
* `extern "efiapi"` -- The ABI used for [UEFI](https://uefi.org/specifications) functions.

 Variadic functions
------------------

 Functions within external blocks may be variadic by specifying `...` as the last argument. There must be at least one parameter before the variadic parameter. The variadic parameter may optionally be specified with an identifier.

 
```
#![allow(unused)]
fn main() {
extern "C" {
    fn foo(x: i32, ...);
    fn with_name(format: *const u8, args: ...);
}
}
```
 Attributes on extern blocks
---------------------------

 The following [attributes](../attributes) control the behavior of external blocks.

 ### The `link` attribute

 The *`link` attribute* specifies the name of a native library that the compiler should link with for the items within an `extern` block. It uses the [*MetaListNameValueStr*](../attributes#meta-item-attribute-syntax) syntax to specify its inputs. The `name` key is the name of the native library to link. The `kind` key is an optional value which specifies the kind of library with the following possible values:

 * `dylib` — Indicates a dynamic library. This is the default if `kind` is not specified.
* `static` — Indicates a static library.
* `framework` — Indicates a macOS framework. This is only valid for macOS targets.
* `raw-dylib` — Indicates a dynamic library where the compiler will generate an import library to link against (see [`dylib` versus `raw-dylib`](#dylib-versus-raw-dylib) below for details). This is only valid for Windows targets.

 The `name` key must be included if `kind` is specified.

 The optional `modifiers` argument is a way to specify linking modifiers for the library to link. Modifiers are specified as a comma-delimited string with each modifier prefixed with either a `+` or `-` to indicate that the modifier is enabled or disabled, respectively. Specifying multiple `modifiers` arguments in a single `link` attribute, or multiple identical modifiers in the same `modifiers` argument is not currently supported.   
 Example: `#[link(name = "mylib", kind = "static", modifiers = "+whole-archive")`.

 The `wasm_import_module` key may be used to specify the [WebAssembly module](https://webassembly.github.io/spec/core/syntax/modules.html) name for the items within an `extern` block when importing symbols from the host environment. The default module name is `env` if `wasm_import_module` is not specified.

 
```
#[link(name = "crypto")]
extern {
    // …
}

#[link(name = "CoreFoundation", kind = "framework")]
extern {
    // …
}

#[link(wasm_import_module = "foo")]
extern {
    // …
}
```
 It is valid to add the `link` attribute on an empty extern block. You can use this to satisfy the linking requirements of extern blocks elsewhere in your code (including upstream crates) instead of adding the attribute to each extern block.

 #### Linking modifiers: `bundle`

 This modifier is only compatible with the `static` linking kind. Using any other kind will result in a compiler error.

 When building a rlib or staticlib `+bundle` means that the native static library will be packed into the rlib or staticlib archive, and then retrieved from there during linking of the final binary.

 When building a rlib `-bundle` means that the native static library is registered as a dependency of that rlib "by name", and object files from it are included only during linking of the final binary, the file search by that name is also performed during final linking.   
 When building a staticlib `-bundle` means that the native static library is simply not included into the archive and some higher level build system will need to add it later during linking of the final binary.

 This modifier has no effect when building other targets like executables or dynamic libraries.

 The default for this modifier is `+bundle`.

 More implementation details about this modifier can be found in [`bundle` documentation for rustc](https://doc.rust-lang.org/rustc/command-line-arguments.html#linking-modifiers-bundle).

 #### Linking modifiers: `whole-archive`

 This modifier is only compatible with the `static` linking kind. Using any other kind will result in a compiler error.

 `+whole-archive` means that the static library is linked as a whole archive without throwing any object files away.

 The default for this modifier is `-whole-archive`.

 More implementation details about this modifier can be found in [`whole-archive` documentation for rustc](https://doc.rust-lang.org/rustc/command-line-arguments.html#linking-modifiers-whole-archive).

 ### Linking modifiers: `verbatim`

 This modifier is compatible with all linking kinds.

 `+verbatim` means that rustc itself won't add any target-specified library prefixes or suffixes (like `lib` or `.a`) to the library name, and will try its best to ask for the same thing from the linker.

 `-verbatim` means that rustc will either add a target-specific prefix and suffix to the library name before passing it to linker, or won't prevent linker from implicitly adding it.

 The default for this modifier is `-verbatim`.

 More implementation details about this modifier can be found in [`verbatim` documentation for rustc](https://doc.rust-lang.org/rustc/command-line-arguments.html#linking-modifiers-verbatim).

 #### 
`dylib` versus `raw-dylib`

 On Windows, linking against a dynamic library requires that an import library is provided to the linker: this is a special static library that declares all of the symbols exported by the dynamic library in such a way that the linker knows that they have to be dynamically loaded at runtime.

 Specifying `kind = "dylib"` instructs the Rust compiler to link an import library based on the `name` key. The linker will then use its normal library resolution logic to find that import library. Alternatively, specifying `kind = "raw-dylib"` instructs the compiler to generate an import library during compilation and provide that to the linker instead.

 `raw-dylib` is only supported on Windows. Using it when targeting other platforms will result in a compiler error.

 #### The `import_name_type` key

 On x86 Windows, names of functions are "decorated" (i.e., have a specific prefix and/or suffix added) to indicate their calling convention. For example, a `stdcall` calling convention function with the name `fn1` that has no arguments would be decorated as `_fn1@0`. However, the [PE Format](https://learn.microsoft.com/windows/win32/debug/pe-format#import-name-type) does also permit names to have no prefix or be undecorated. Additionally, the MSVC and GNU toolchains use different decorations for the same calling conventions which means, by default, some Win32 functions cannot be called using the `raw-dylib` link kind via the GNU toolchain.

 To allow for these differences, when using the `raw-dylib` link kind you may also specify the `import_name_type` key with one of the following values to change how functions are named in the generated import library:

 * `decorated`: The function name will be fully-decorated using the MSVC toolchain format.
* `noprefix`: The function name will be decorated using the MSVC toolchain format, but skipping the leading `?`, `@`, or optionally `_`.
* `undecorated`: The function name will not be decorated.

 If the `import_name_type` key is not specified, then the function name will be fully-decorated using the target toolchain's format.

 Variables are never decorated and so the `import_name_type` key has no effect on how they are named in the generated import library.

 The `import_name_type` key is only supported on x86 Windows. Using it when targeting other platforms will result in a compiler error.

 ### The `link_name` attribute

 The *`link_name` attribute* may be specified on declarations inside an `extern` block to indicate the symbol to import for the given function or static. It uses the [*MetaNameValueStr*](../attributes#meta-item-attribute-syntax) syntax to specify the name of the symbol.

 
```
#![allow(unused)]
fn main() {
extern {
    #[link_name = "actual_symbol_name"]
    fn name_in_rust();
}
}
```
 Using this attribute with the `link_ordinal` attribute will result in a compiler error.

 ### The `link_ordinal` attribute

 The *`link_ordinal` attribute* can be applied on declarations inside an `extern` block to indicate the numeric ordinal to use when generating the import library to link against. An ordinal is a unique number per symbol exported by a dynamic library on Windows and can be used when the library is being loaded to find that symbol rather than having to look it up by name.

  Warning: `link_ordinal` should only be used in cases where the ordinal of the symbol is known to be stable: if the ordinal of a symbol is not explicitly set when its containing binary is built then one will be automatically assigned to it, and that assigned ordinal may change between builds of the binary.

  
```
#[link(name = "exporter", kind = "raw-dylib")]
extern "stdcall" {
    #[link_ordinal(15)]
    fn imported_function_stdcall(i: i32);
}
```
 This attribute is only used with the `raw-dylib` linking kind. Using any other kind will result in a compiler error.

 Using this attribute with the `link_name` attribute will result in a compiler error.

 ### Attributes on function parameters

 Attributes on extern function parameters follow the same rules and restrictions as [regular function parameters](functions#attributes-on-function-parameters).



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/items/external-blocks.html>

Generic parameters
==================

 
>  **Syntax**  
>  *GenericParams* :  
>  `<` `>`  
>  | `<` (*GenericParam* `,`)\* *GenericParam* `,`? `>`
> 
>  *GenericParam* :  
>  [*OuterAttribute*](../attributes)\* ( *LifetimeParam* | *TypeParam* | *ConstParam* )
> 
>  *LifetimeParam* :  
>  [LIFETIME\_OR\_LABEL](../tokens#lifetimes-and-loop-labels) ( `:` [*LifetimeBounds*](../trait-bounds) )?
> 
>  *TypeParam* :  
>  [IDENTIFIER](../identifiers)( `:` [*TypeParamBounds*](../trait-bounds)? )? ( `=` [*Type*](../types#type-expressions) )?
> 
>  *ConstParam*:  
>  `const` [IDENTIFIER](../identifiers) `:` [*Type*](../types#type-expressions) ( `=` *[Block](../expressions/block-expr)* | [IDENTIFIER](../identifiers) | -?[LITERAL](../expressions/literal-expr) )?
> 
>  

 [Functions](functions), [type aliases](type-aliases), <structs>, <enumerations>, <unions>, <traits>, and <implementations> may be *parameterized* by types, constants, and lifetimes. These parameters are listed in angle brackets (`<...>`), usually immediately after the name of the item and before its definition. For implementations, which don't have a name, they come directly after `impl`. The order of generic parameters is restricted to lifetime parameters and then type and const parameters intermixed.

 Some examples of items with type, const, and lifetime parameters:

 
```
#![allow(unused)]
fn main() {
fn foo<'a, T>() {}
trait A<U> {}
struct Ref<'a, T> where T: 'a { r: &'a T }
struct InnerArray<T, const N: usize>([T; N]);
struct EitherOrderWorks<const N: bool, U>(U);
}
```
 Generic parameters are in scope within the item definition where they are declared. They are not in scope for items declared within the body of a function as described in [item declarations](../statements#item-declarations).

 [References](../types/pointer#shared-references-), [raw pointers](../types/pointer#raw-pointers-const-and-mut), [arrays](../types/array), [slices](../types/slice), [tuples](../types/tuple), and [function pointers](../types/function-pointer) have lifetime or type parameters as well, but are not referred to with path syntax.

 ### Const generics

 *Const generic parameters* allow items to be generic over constant values. The const identifier introduces a name for the constant parameter, and all instances of the item must be instantiated with a value of the given type.

 The only allowed types of const parameters are `u8`, `u16`, `u32`, `u64`, `u128`, `usize`, `i8`, `i16`, `i32`, `i64`, `i128`, `isize`, `char` and `bool`.

 Const parameters can be used anywhere a [const item](constant-items) can be used, with the exception that when used in a [type](../types) or [array repeat expression](../expressions/array-expr), it must be standalone (as described below). That is, they are allowed in the following places:

 1. As an applied const to any type which forms a part of the signature of the item in question.
2. As part of a const expression used to define an [associated const](associated-items#associated-constants), or as a parameter to an [associated type](associated-items#associated-types).
3. As a value in any runtime expression in the body of any functions in the item.
4. As a parameter to any type used in the body of any functions in the item.
5. As a part of the type of any fields in the item.

 
```
#![allow(unused)]
fn main() {
// Examples where const generic parameters can be used.

// Used in the signature of the item itself.
fn foo<const N: usize>(arr: [i32; N]) {
    // Used as a type within a function body.
    let x: [i32; N];
    // Used as an expression.
    println!("{}", N * 2);
}

// Used as a field of a struct.
struct Foo<const N: usize>([i32; N]);

impl<const N: usize> Foo<N> {
    // Used as an associated constant.
    const CONST: usize = N * 4;
}

trait Trait {
    type Output;
}

impl<const N: usize> Trait for Foo<N> {
    // Used as an associated type.
    type Output = [i32; N];
}
}
```
 
```
#![allow(unused)]
fn main() {
// Examples where const generic parameters cannot be used.
fn foo<const N: usize>() {
    // Cannot use in item definitions within a function body.
    const BAD_CONST: [usize; N] = [1; N];
    static BAD_STATIC: [usize; N] = [1; N];
    fn inner(bad_arg: [usize; N]) {
        let bad_value = N * 2;
    }
    type BadAlias = [usize; N];
    struct BadStruct([usize; N]);
}
}
```
 As a further restriction, const parameters may only appear as a standalone argument inside of a [type](../types) or [array repeat expression](../expressions/array-expr). In those contexts, they may only be used as a single segment [path expression](../expressions/path-expr), possibly inside a [block](../expressions/block-expr) (such as `N` or `{N}`). That is, they cannot be combined with other expressions.

 
```
#![allow(unused)]
fn main() {
// Examples where const parameters may not be used.

// Not allowed to combine in other expressions in types, such as the
// arithmetic expression in the return type here.
fn bad_function<const N: usize>() -> [u8; {N + 1}] {
    // Similarly not allowed for array repeat expressions.
    [1; {N + 1}]
}
}
```
 A const argument in a [path](../paths) specifies the const value to use for that item. The argument must be a [const expression](../const_eval#constant-expressions) of the type ascribed to the const parameter. The const expression must be a [block expression](../expressions/block-expr) (surrounded with braces) unless it is a single path segment (an [IDENTIFIER](../identifiers)) or a [literal](../expressions/literal-expr) (with a possibly leading `-` token).

 
>  **Note**: This syntactic restriction is necessary to avoid requiring infinite lookahead when parsing an expression inside of a type.
> 
>  

 
```
#![allow(unused)]
fn main() {
fn double<const N: i32>() {
    println!("doubled: {}", N * 2);
}

const SOME_CONST: i32 = 12;

fn example() {
    // Example usage of a const argument.
    double::<9>();
    double::<-123>();
    double::<{7 + 8}>();
    double::<SOME_CONST>();
    double::<{ SOME_CONST + 5 }>();
}
}
```
 When there is ambiguity if a generic argument could be resolved as either a type or const argument, it is always resolved as a type. Placing the argument in a block expression can force it to be interpreted as a const argument.

 
```
#![allow(unused)]
fn main() {
type N = u32;
struct Foo<const N: usize>;
// The following is an error, because `N` is interpreted as the type alias `N`.
fn foo<const N: usize>() -> Foo<N> { todo!() } // ERROR
// Can be fixed by wrapping in braces to force it to be interpreted as the `N`
// const parameter:
fn bar<const N: usize>() -> Foo<{ N }> { todo!() } // ok
}
```
 Unlike type and lifetime parameters, const parameters can be declared without being used inside of a parameterized item, with the exception of implementations as described in [generic implementations](implementations#generic-implementations):

 
```
#![allow(unused)]
fn main() {
// ok
struct Foo<const N: usize>;
enum Bar<const M: usize> { A, B }

// ERROR: unused parameter
struct Baz<T>;
struct Biz<'a>;
struct Unconstrained;
impl<const N: usize> Unconstrained {}
}
```
 When resolving a trait bound obligation, the exhaustiveness of all implementations of const parameters is not considered when determining if the bound is satisfied. For example, in the following, even though all possible const values for the `bool` type are implemented, it is still an error that the trait bound is not satisfied:

 
```
#![allow(unused)]
fn main() {
struct Foo<const B: bool>;
trait Bar {}
impl Bar for Foo<true> {}
impl Bar for Foo<false> {}

fn needs_bar(_: impl Bar) {}
fn generic<const B: bool>() {
    let v = Foo::<B>;
    needs_bar(v); // ERROR: trait bound `Foo<B>: Bar` is not satisfied
}
}
```
 Where clauses
-------------

 
>  **Syntax**  
>  *WhereClause* :  
>  `where` ( *WhereClauseItem* `,` )\* *WhereClauseItem* ?
> 
>  *WhereClauseItem* :  
>  *LifetimeWhereClauseItem*  
>  | *TypeBoundWhereClauseItem*
> 
>  *LifetimeWhereClauseItem* :  
>  [*Lifetime*](../trait-bounds) `:` [*LifetimeBounds*](../trait-bounds)
> 
>  *TypeBoundWhereClauseItem* :  
>  [*ForLifetimes*](../trait-bounds#higher-ranked-trait-bounds)? [*Type*](../types#type-expressions) `:` [*TypeParamBounds*](../trait-bounds)?
> 
>  

 *Where clauses* provide another way to specify bounds on type and lifetime parameters as well as a way to specify bounds on types that aren't type parameters.

 The `for` keyword can be used to introduce [higher-ranked lifetimes](../trait-bounds#higher-ranked-trait-bounds). It only allows [*LifetimeParam*](#generic-parameters) parameters.

 
```
#![allow(unused)]
fn main() {
struct A<T>
where
    T: Iterator,            // Could use A<T: Iterator> instead
    T::Item: Copy,          // Bound on an associated type
    String: PartialEq<T>,   // Bound on `String`, using the type parameter
    i32: Default,           // Allowed, but not useful
{
    f: T,
}
}
```
 Attributes
----------

 Generic lifetime and type parameters allow [attributes](../attributes) on them. There are no built-in attributes that do anything in this position, although custom derive attributes may give meaning to it.

 This example shows using a custom derive attribute to modify the meaning of a generic parameter.

 
```
// Assume that the derive for MyFlexibleClone declared `my_flexible_clone` as
// an attribute it understands.
#[derive(MyFlexibleClone)]
struct Foo<#[my_flexible_clone(unbounded)] H> {
    a: *const H
}
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/items/generics.html>

Associated Items
================

 
>  **Syntax**  
>  *AssociatedItem* :  
>  [*OuterAttribute*](../attributes)\* (  
>  [*MacroInvocationSemi*](../macros#macro-invocation)  
>  | ( [*Visibility*](../visibility-and-privacy)? ( [*TypeAlias*](type-aliases) | [*ConstantItem*](constant-items) | [*Function*](functions) ) )  
>  )
> 
>  

 *Associated Items* are the items declared in <traits> or defined in <implementations>. They are called this because they are defined on an associate type — the type in the implementation. They are a subset of the kinds of items you can declare in a module. Specifically, there are [associated functions](#associated-functions-and-methods) (including methods), [associated types](#associated-types), and [associated constants](#associated-constants).

 Associated items are useful when the associated item logically is related to the associating item. For example, the `is_some` method on `Option` is intrinsically related to Options, so should be associated.

 Every associated item kind comes in two varieties: definitions that contain the actual implementation and declarations that declare signatures for definitions.

 It is the declarations that make up the contract of traits and what is available on generic types.

 Associated functions and methods
--------------------------------

 *Associated functions* are <functions> associated with a type.

 An *associated function declaration* declares a signature for an associated function definition. It is written as a function item, except the function body is replaced with a `;`.

 The identifier is the name of the function. The generics, parameter list, return type, and where clause of the associated function must be the same as the associated function declarations's.

 An *associated function definition* defines a function associated with another type. It is written the same as a [function item](../types/function-item).

 An example of a common associated function is a `new` function that returns a value of the type the associated function is associated with.

 
```
struct Struct {
    field: i32
}

impl Struct {
    fn new() -> Struct {
        Struct {
            field: 0i32
        }
    }
}

fn main () {
    let _struct = Struct::new();
}
```
 When the associated function is declared on a trait, the function can also be called with a [path](../paths) that is a path to the trait appended by the name of the trait. When this happens, it is substituted for `<_ as Trait>::function_name`.

 
```
#![allow(unused)]
fn main() {
trait Num {
    fn from_i32(n: i32) -> Self;
}

impl Num for f64 {
    fn from_i32(n: i32) -> f64 { n as f64 }
}

// These 4 are all equivalent in this case.
let _: f64 = Num::from_i32(42);
let _: f64 = <_ as Num>::from_i32(42);
let _: f64 = <f64 as Num>::from_i32(42);
let _: f64 = f64::from_i32(42);
}
```
 ### Methods

 Associated functions whose first parameter is named `self` are called *methods* and may be invoked using the [method call operator](../expressions/method-call-expr), for example, `x.foo()`, as well as the usual function call notation.

 If the type of the `self` parameter is specified, it is limited to types resolving to one generated by the following grammar (where `'lt` denotes some arbitrary lifetime):

 
```
P = &'lt S | &'lt mut S | Box<S> | Rc<S> | Arc<S> | Pin<P>
S = Self | P

```
 The `Self` terminal in this grammar denotes a type resolving to the implementing type. This can also include the contextual type alias `Self`, other type aliases, or associated type projections resolving to the implementing type.

 
```
#![allow(unused)]
fn main() {
use std::rc::Rc;
use std::sync::Arc;
use std::pin::Pin;
// Examples of methods implemented on struct `Example`.
struct Example;
type Alias = Example;
trait Trait { type Output; }
impl Trait for Example { type Output = Example; }
impl Example {
    fn by_value(self: Self) {}
    fn by_ref(self: &Self) {}
    fn by_ref_mut(self: &mut Self) {}
    fn by_box(self: Box<Self>) {}
    fn by_rc(self: Rc<Self>) {}
    fn by_arc(self: Arc<Self>) {}
    fn by_pin(self: Pin<&Self>) {}
    fn explicit_type(self: Arc<Example>) {}
    fn with_lifetime<'a>(self: &'a Self) {}
    fn nested<'a>(self: &mut &'a Arc<Rc<Box<Alias>>>) {}
    fn via_projection(self: <Example as Trait>::Output) {}
}
}
```
 Shorthand syntax can be used without specifying a type, which have the following equivalents:

 


| Shorthand | Equivalent |
| --- | --- |
| `self` | `self: Self` |
| `&'lifetime self` | `self: &'lifetime Self` |
| `&'lifetime mut self` | `self: &'lifetime mut Self` |

  
>  **Note**: Lifetimes can be, and usually are, elided with this shorthand.
> 
>  

 If the `self` parameter is prefixed with `mut`, it becomes a mutable variable, similar to regular parameters using a `mut` [identifier pattern](../patterns#identifier-patterns). For example:

 
```
#![allow(unused)]
fn main() {
trait Changer: Sized {
    fn change(mut self) {}
    fn modify(mut self: Box<Self>) {}
}
}
```
 As an example of methods on a trait, consider the following:

 
```
#![allow(unused)]
fn main() {
type Surface = i32;
type BoundingBox = i32;
trait Shape {
    fn draw(&self, surface: Surface);
    fn bounding_box(&self) -> BoundingBox;
}
}
```
 This defines a trait with two methods. All values that have <implementations> of this trait while the trait is in scope can have their `draw` and `bounding_box` methods called.

 
```
#![allow(unused)]
fn main() {
type Surface = i32;
type BoundingBox = i32;
trait Shape {
    fn draw(&self, surface: Surface);
    fn bounding_box(&self) -> BoundingBox;
}

struct Circle {
    // ...
}

impl Shape for Circle {
    // ...
  fn draw(&self, _: Surface) {}
  fn bounding_box(&self) -> BoundingBox { 0i32 }
}

impl Circle {
    fn new() -> Circle { Circle{} }
}

let circle_shape = Circle::new();
let bounding_box = circle_shape.bounding_box();
}
```
 
>  **Edition Differences**: In the 2015 edition, it is possible to declare trait methods with anonymous parameters (e.g. `fn foo(u8)`). This is deprecated and an error as of the 2018 edition. All parameters must have an argument name.
> 
>  

 #### Attributes on method parameters

 Attributes on method parameters follow the same rules and restrictions as [regular function parameters](functions#attributes-on-function-parameters).

 Associated Types
----------------

 *Associated types* are [type aliases](type-aliases) associated with another type. Associated types cannot be defined in [inherent implementations](implementations#inherent-implementations) nor can they be given a default implementation in traits.

 An *associated type declaration* declares a signature for associated type definitions. It is written in one of the following forms, where `Assoc` is the name of the associated type, `Params` is a comma-separated list of type, lifetime or const parameters, `Bounds` is a plus-separated list of trait bounds that the associated type must meet, and `WhereBounds` is a comma-separated list of bounds that the parameters must meet:

 
```
type Assoc;
type Assoc: Bounds;
type Assoc<Params>;
type Assoc<Params>: Bounds;
type Assoc<Params> where WhereBounds;
type Assoc<Params>: Bounds where WhereBounds;
```
 The identifier is the name of the declared type alias. The optional trait bounds must be fulfilled by the implementations of the type alias. There is an implicit [`Sized`](../special-types-and-traits#sized) bound on associated types that can be relaxed using the special `?Sized` bound.

 An *associated type definition* defines a type alias for the implementation of a trait on a type. They are written similarly to an *associated type declaration*, but cannot contain `Bounds`, but instead must contain a `Type`:

 
```
type Assoc = Type;
type Assoc<Params> = Type; // the type `Type` here may reference `Params`
type Assoc<Params> = Type where WhereBounds;
type Assoc<Params> where WhereBounds = Type; // deprecated, prefer the form above
```
 If a type `Item` has an associated type `Assoc` from a trait `Trait`, then `<Item as Trait>::Assoc` is a type that is an alias of the type specified in the associated type definition. Furthermore, if `Item` is a type parameter, then `Item::Assoc` can be used in type parameters.

 Associated types may include [generic parameters](generics) and [where clauses](generics#where-clauses); these are often referred to as *generic associated types*, or *GATs*. If the type `Thing` has an associated type `Item` from a trait `Trait` with the generics `<'a>` , the type can be named like `<Thing as Trait>::Item<'x>`, where `'x` is some lifetime in scope. In this case, `'x` will be used wherever `'a` appears in the associated type definitions on impls.

 
```
trait AssociatedType {
    // Associated type declaration
    type Assoc;
}

struct Struct;

struct OtherStruct;

impl AssociatedType for Struct {
    // Associated type definition
    type Assoc = OtherStruct;
}

impl OtherStruct {
    fn new() -> OtherStruct {
        OtherStruct
    }
}

fn main() {
    // Usage of the associated type to refer to OtherStruct as <Struct as AssociatedType>::Assoc
    let _other_struct: OtherStruct = <Struct as AssociatedType>::Assoc::new();
}
```
 An example of associated types with generics and where clauses:

 
```
struct ArrayLender<'a, T>(&'a mut [T; 16]);

trait Lend {
    // Generic associated type declaration
    type Lender<'a> where Self: 'a;
    fn lend<'a>(&'a mut self) -> Self::Lender<'a>;
}

impl<T> Lend for [T; 16] {
    // Generic associated type definition
    type Lender<'a> = ArrayLender<'a, T> where Self: 'a;

    fn lend<'a>(&'a mut self) -> Self::Lender<'a> {
        ArrayLender(self)
    }
}

fn borrow<'a, T: Lend>(array: &'a mut T) -> <T as Lend>::Lender<'a> {
    array.lend()
}


fn main() {
    let mut array = [0usize; 16];
    let lender = borrow(&mut array);
}
```
 ### Associated Types Container Example

 Consider the following example of a `Container` trait. Notice that the type is available for use in the method signatures:

 
```
#![allow(unused)]
fn main() {
trait Container {
    type E;
    fn empty() -> Self;
    fn insert(&mut self, elem: Self::E);
}
}
```
 In order for a type to implement this trait, it must not only provide implementations for every method, but it must specify the type `E`. Here's an implementation of `Container` for the standard library type `Vec`:

 
```
#![allow(unused)]
fn main() {
trait Container {
    type E;
    fn empty() -> Self;
    fn insert(&mut self, elem: Self::E);
}
impl<T> Container for Vec<T> {
    type E = T;
    fn empty() -> Vec<T> { Vec::new() }
    fn insert(&mut self, x: T) { self.push(x); }
}
}
```
 ### Relationship between `Bounds` and `WhereBounds`

 In this example:

 
```
#![allow(unused)]
fn main() {
use std::fmt::Debug;
trait Example {
    type Output<T>: Ord where T: Debug;
}
}
```
 Given a reference to the associated type like `<X as Example>::Output<Y>`, the associated type itself must be `Ord`, and the type `Y` must be `Debug`.

 ### Required where clauses on generic associated types

 Generic associated type declarations on traits currently may require a list of where clauses, dependent on functions in the trait and how the GAT is used. These rules may be loosened in the future; updates can be found [on the generic associated types initiative repository](https://rust-lang.github.io/generic-associated-types-initiative/explainer/required_bounds.html).

 In a few words, these where clauses are required in order to maximize the allowed definitions of the associated type in impls. To do this, any clauses that *can be proven to hold* on functions (using the parameters of the function or trait) where a GAT appears as an input or output must also be written on the GAT itself.

 
```
#![allow(unused)]
fn main() {
trait LendingIterator {
    type Item<'x> where Self: 'x;
    fn next<'a>(&'a mut self) -> Self::Item<'a>;
}
}
```
 In the above, on the `next` function, we can prove that `Self: 'a`, because of the implied bounds from `&'a mut self`; therefore, we must write the equivalent bound on the GAT itself: `where Self: 'x`.

 When there are multiple functions in a trait that use the GAT, then the *intersection* of the bounds from the different functions are used, rather than the union.

 
```
#![allow(unused)]
fn main() {
trait Check<T> {
    type Checker<'x>;
    fn create_checker<'a>(item: &'a T) -> Self::Checker<'a>;
    fn do_check(checker: Self::Checker<'_>);
}
}
```
 In this example, no bounds are required on the `type Checker<'a>;`. While we know that `T: 'a` on `create_checker`, we do not know that on `do_check`. However, if `do_check` was commented out, then the `where T: 'x` bound would be required on `Checker`.

 The bounds on associated types also propagate required where clauses.

 
```
#![allow(unused)]
fn main() {
trait Iterable {
    type Item<'a> where Self: 'a;
    type Iterator<'a>: Iterator<Item = Self::Item<'a>> where Self: 'a;
    fn iter<'a>(&'a self) -> Self::Iterator<'a>;
}
}
```
 Here, `where Self: 'a` is required on `Item` because of `iter`. However, `Item` is used in the bounds of `Iterator`, the `where Self: 'a` clause is also required there.

 Finally, any explicit uses of `'static` on GATs in the trait do not count towards the required bounds.

 
```
#![allow(unused)]
fn main() {
trait StaticReturn {
    type Y<'a>;
    fn foo(&self) -> Self::Y<'static>;
}
}
```
 Associated Constants
--------------------

 *Associated constants* are [constants](constant-items) associated with a type.

 An *associated constant declaration* declares a signature for associated constant definitions. It is written as `const`, then an identifier, then `:`, then a type, finished by a `;`.

 The identifier is the name of the constant used in the path. The type is the type that the definition has to implement.

 An *associated constant definition* defines a constant associated with a type. It is written the same as a [constant item](constant-items).

 Associated constant definitions undergo [constant evaluation](../const_eval) only when referenced. Further, definitions that include [generic parameters](generics) are evaluated after monomorphization.

 
```
struct Struct;
struct GenericStruct<const ID: i32>;

impl Struct {
    // Definition not immediately evaluated
    const PANIC: () = panic!("compile-time panic");
}

impl<const ID: i32> GenericStruct<ID> {
    // Definition not immediately evaluated
    const NON_ZERO: () = if ID == 0 {
        panic!("contradiction")
    };
}

fn main() {
    // Referencing Struct::PANIC causes compilation error
    let _ = Struct::PANIC;

    // Fine, ID is not 0
    let _ = GenericStruct::<1>::NON_ZERO;

    // Compilation error from evaluating NON_ZERO with ID=0
    let _ = GenericStruct::<0>::NON_ZERO;
}
```
 ### Associated Constants Examples

 A basic example:

 
```
trait ConstantId {
    const ID: i32;
}

struct Struct;

impl ConstantId for Struct {
    const ID: i32 = 1;
}

fn main() {
    assert_eq!(1, Struct::ID);
}
```
 Using default values:

 
```
trait ConstantIdDefault {
    const ID: i32 = 1;
}

struct Struct;
struct OtherStruct;

impl ConstantIdDefault for Struct {}

impl ConstantIdDefault for OtherStruct {
    const ID: i32 = 5;
}

fn main() {
    assert_eq!(1, Struct::ID);
    assert_eq!(5, OtherStruct::ID);
}
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/items/associated-items.html>

Testing attributes
==================

 The following [attributes](../attributes) are used for specifying functions for performing tests. Compiling a crate in "test" mode enables building the test functions along with a test harness for executing the tests. Enabling the test mode also enables the [`test` conditional compilation option](../conditional-compilation#test).

 The `test` attribute
--------------------

 The *`test` attribute* marks a function to be executed as a test. These functions are only compiled when in test mode. Test functions must be free, monomorphic functions that take no arguments, and the return type must implement the [`Termination`](../../std/process/trait.termination) trait, for example:

 * `()`
* `Result<T, E> where T: Termination, E: Debug`
* `!`

 
>  Note: The test mode is enabled by passing the `--test` argument to `rustc` or using `cargo test`.
> 
>  

 The test harness calls the returned value's [`report`](../../std/process/trait.termination#tymethod.report) method, and classifies the test as passed or failed depending on whether the resulting [`ExitCode`](../../std/process/struct.exitcode) represents successful termination. In particular:

 * Tests that return `()` pass as long as they terminate and do not panic.
* Tests that return a `Result<(), E>` pass as long as they return `Ok(())`.
* Tests that return `ExitCode::SUCCESS` pass, and tests that return `ExitCode::FAILURE` fail.
* Tests that do not terminate neither pass nor fail.

 
```
#![allow(unused)]
fn main() {
use std::io;
fn setup_the_thing() -> io::Result<i32> { Ok(1) }
fn do_the_thing(s: &i32) -> io::Result<()> { Ok(()) }
#[test]
fn test_the_thing() -> io::Result<()> {
    let state = setup_the_thing()?; // expected to succeed
    do_the_thing(&state)?;          // expected to succeed
    Ok(())
}
}
```
 The `ignore` attribute
----------------------

 A function annotated with the `test` attribute can also be annotated with the `ignore` attribute. The *`ignore` attribute* tells the test harness to not execute that function as a test. It will still be compiled when in test mode.

 The `ignore` attribute may optionally be written with the [*MetaNameValueStr*](../attributes#meta-item-attribute-syntax) syntax to specify a reason why the test is ignored.

 
```
#![allow(unused)]
fn main() {
#[test]
#[ignore = "not yet implemented"]
fn mytest() {
    // …
}
}
```
 
>  **Note**: The `rustc` test harness supports the `--include-ignored` flag to force ignored tests to be run.
> 
>  

 The `should_panic` attribute
----------------------------

 A function annotated with the `test` attribute that returns `()` can also be annotated with the `should_panic` attribute. The *`should_panic` attribute* makes the test only pass if it actually panics.

 The `should_panic` attribute may optionally take an input string that must appear within the panic message. If the string is not found in the message, then the test will fail. The string may be passed using the [*MetaNameValueStr*](../attributes#meta-item-attribute-syntax) syntax or the [*MetaListNameValueStr*](../attributes#meta-item-attribute-syntax) syntax with an `expected` field.

 
```
#![allow(unused)]
fn main() {
#[test]
#[should_panic(expected = "values don't match")]
fn mytest() {
    assert_eq!(1, 2, "values don't match");
}
}
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/attributes/testing.html>

Derive
======

 The *`derive` attribute* allows new [items](../items) to be automatically generated for data structures. It uses the [*MetaListPaths*](../attributes#meta-item-attribute-syntax) syntax to specify a list of traits to implement or paths to [derive macros](../procedural-macros#derive-macros) to process.

 For example, the following will create an [`impl` item](../items/implementations) for the [`PartialEq`](../../std/cmp/trait.partialeq) and [`Clone`](../../std/clone/trait.clone) traits for `Foo`, and the type parameter `T` will be given the `PartialEq` or `Clone` constraints for the appropriate `impl`:

 
```
#![allow(unused)]
fn main() {
#[derive(PartialEq, Clone)]
struct Foo<T> {
    a: i32,
    b: T,
}
}
```
 The generated `impl` for `PartialEq` is equivalent to

 
```
#![allow(unused)]
fn main() {
struct Foo<T> { a: i32, b: T }
impl<T: PartialEq> PartialEq for Foo<T> {
    fn eq(&self, other: &Foo<T>) -> bool {
        self.a == other.a && self.b == other.b
    }
}
}
```
 You can implement `derive` for your own traits through [procedural macros](../procedural-macros#derive-macros).

 The `automatically_derived` attribute
-------------------------------------

 The *`automatically_derived` attribute* is automatically added to [implementations](../items/implementations) created by the `derive` attribute for built-in traits. It has no direct effect, but it may be used by tools and diagnostic lints to detect these automatically generated implementations.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/attributes/derive.html>

Diagnostic attributes
=====================

 The following [attributes](../attributes) are used for controlling or generating diagnostic messages during compilation.

 Lint check attributes
---------------------

 A lint check names a potentially undesirable coding pattern, such as unreachable code or omitted documentation. The lint attributes `allow`, `warn`, `deny`, and `forbid` use the [*MetaListPaths*](../attributes#meta-item-attribute-syntax) syntax to specify a list of lint names to change the lint level for the entity to which the attribute applies.

 For any lint check `C`:

 * `allow(C)` overrides the check for `C` so that violations will go unreported,
* `warn(C)` warns about violations of `C` but continues compilation.
* `deny(C)` signals an error after encountering a violation of `C`,
* `forbid(C)` is the same as `deny(C)`, but also forbids changing the lint level afterwards,

 
>  Note: The lint checks supported by `rustc` can be found via `rustc -W help`, along with their default settings and are documented in the [rustc book](https://doc.rust-lang.org/rustc/lints/index.html).
> 
>  

 
```
#![allow(unused)]
fn main() {
pub mod m1 {
    // Missing documentation is ignored here
    #[allow(missing_docs)]
    pub fn undocumented_one() -> i32 { 1 }

    // Missing documentation signals a warning here
    #[warn(missing_docs)]
    pub fn undocumented_too() -> i32 { 2 }

    // Missing documentation signals an error here
    #[deny(missing_docs)]
    pub fn undocumented_end() -> i32 { 3 }
}
}
```
 Lint attributes can override the level specified from a previous attribute, as long as the level does not attempt to change a forbidden lint. Previous attributes are those from a higher level in the syntax tree, or from a previous attribute on the same entity as listed in left-to-right source order.

 This example shows how one can use `allow` and `warn` to toggle a particular check on and off:

 
```
#![allow(unused)]
fn main() {
#[warn(missing_docs)]
pub mod m2 {
    #[allow(missing_docs)]
    pub mod nested {
        // Missing documentation is ignored here
        pub fn undocumented_one() -> i32 { 1 }

        // Missing documentation signals a warning here,
        // despite the allow above.
        #[warn(missing_docs)]
        pub fn undocumented_two() -> i32 { 2 }
    }

    // Missing documentation signals a warning here
    pub fn undocumented_too() -> i32 { 3 }
}
}
```
 This example shows how one can use `forbid` to disallow uses of `allow` for that lint check:

 
```
#![allow(unused)]
fn main() {
#[forbid(missing_docs)]
pub mod m3 {
    // Attempting to toggle warning signals an error here
    #[allow(missing_docs)]
    /// Returns 2.
    pub fn undocumented_too() -> i32 { 2 }
}
}
```
 
>  Note: `rustc` allows setting lint levels on the [command-line](https://doc.rust-lang.org/rustc/lints/levels.html#via-compiler-flag), and also supports [setting caps](https://doc.rust-lang.org/rustc/lints/levels.html#capping-lints) on the lints that are reported.
> 
>  

 ### Lint groups

 Lints may be organized into named groups so that the level of related lints can be adjusted together. Using a named group is equivalent to listing out the lints within that group.

 
```
#![allow(unused)]
fn main() {
// This allows all lints in the "unused" group.
#[allow(unused)]
// This overrides the "unused_must_use" lint from the "unused"
// group to deny.
#[deny(unused_must_use)]
fn example() {
    // This does not generate a warning because the "unused_variables"
    // lint is in the "unused" group.
    let x = 1;
    // This generates an error because the result is unused and
    // "unused_must_use" is marked as "deny".
    std::fs::remove_file("some_file"); // ERROR: unused `Result` that must be used
}
}
```
 There is a special group named "warnings" which includes all lints at the "warn" level. The "warnings" group ignores attribute order and applies to all lints that would otherwise warn within the entity.

 
```
#![allow(unused)]
fn main() {
unsafe fn an_unsafe_fn() {}
// The order of these two attributes does not matter.
#[deny(warnings)]
// The unsafe_code lint is normally "allow" by default.
#[warn(unsafe_code)]
fn example_err() {
    // This is an error because the `unsafe_code` warning has
    // been lifted to "deny".
    unsafe { an_unsafe_fn() } // ERROR: usage of `unsafe` block
}
}
```
 ### Tool lint attributes

 Tool lints allows using scoped lints, to `allow`, `warn`, `deny` or `forbid` lints of certain tools.

 Tool lints only get checked when the associated tool is active. If a lint attribute, such as `allow`, references a nonexistent tool lint, the compiler will not warn about the nonexistent lint until you use the tool.

 Otherwise, they work just like regular lint attributes:

 
```
// set the entire `pedantic` clippy lint group to warn
#![warn(clippy::pedantic)]
// silence warnings from the `filter_map` clippy lint
#![allow(clippy::filter_map)]

fn main() {
    // ...
}

// silence the `cmp_nan` clippy lint just for this function
#[allow(clippy::cmp_nan)]
fn foo() {
    // ...
}
```
 
>  Note: `rustc` currently recognizes the tool lints for "[clippy](https://github.com/rust-lang/rust-clippy)" and "[rustdoc](https://doc.rust-lang.org/rustdoc/lints.html)".
> 
>  

 The `deprecated` attribute
--------------------------

 The *`deprecated` attribute* marks an item as deprecated. `rustc` will issue warnings on usage of `#[deprecated]` items. `rustdoc` will show item deprecation, including the `since` version and `note`, if available.

 The `deprecated` attribute has several forms:

 * `deprecated` — Issues a generic message.
* `deprecated = "message"` — Includes the given string in the deprecation message.
* [*MetaListNameValueStr*](../attributes#meta-item-attribute-syntax) syntax with two optional fields:
	+ `since` — Specifies a version number when the item was deprecated. `rustc` does not currently interpret the string, but external tools like [Clippy](https://github.com/rust-lang/rust-clippy) may check the validity of the value.
	+ `note` — Specifies a string that should be included in the deprecation message. This is typically used to provide an explanation about the deprecation and preferred alternatives.

 The `deprecated` attribute may be applied to any [item](../items), [trait item](../items/traits), [enum variant](../items/enumerations), [struct field](../items/structs), [external block item](../items/external-blocks), or [macro definition](../macros-by-example). It cannot be applied to [trait implementation items](../items/implementations#trait-implementations). When applied to an item containing other items, such as a [module](../items/modules) or [implementation](../items/implementations), all child items inherit the deprecation attribute.

 Here is an example:

 
```
#![allow(unused)]
fn main() {
#[deprecated(since = "5.2.0", note = "foo was rarely used. Users should instead use bar")]
pub fn foo() {}

pub fn bar() {}
}
```
 The [RFC](https://github.com/rust-lang/rfcs/blob/master/text/1270-deprecation.md) contains motivations and more details.

 The `must_use` attribute
------------------------

 The *`must_use` attribute* is used to issue a diagnostic warning when a value is not "used". It can be applied to user-defined composite types ([`struct`s](../items/structs), [`enum`s](../items/enumerations), and [`union`s](../items/unions)), [functions](../items/functions), and [traits](../items/traits).

 The `must_use` attribute may include a message by using the [*MetaNameValueStr*](../attributes#meta-item-attribute-syntax) syntax such as `#[must_use = "example message"]`. The message will be given alongside the warning.

 When used on user-defined composite types, if the [expression](../expressions) of an [expression statement](../statements#expression-statements) has that type, then the `unused_must_use` lint is violated.

 
```
#![allow(unused)]
fn main() {
#[must_use]
struct MustUse {
    // some fields
}

impl MustUse {
  fn new() -> MustUse { MustUse {} }
}

// Violates the `unused_must_use` lint.
MustUse::new();
}
```
 When used on a function, if the [expression](../expressions) of an [expression statement](../statements#expression-statements) is a [call expression](../expressions/call-expr) to that function, then the `unused_must_use` lint is violated.

 
```
#![allow(unused)]
fn main() {
#[must_use]
fn five() -> i32 { 5i32 }

// Violates the unused_must_use lint.
five();
}
```
 When used on a [trait declaration](../items/traits), a [call expression](../expressions/call-expr) of an [expression statement](../statements#expression-statements) to a function that returns an [impl trait](../types/impl-trait) or a [dyn trait](../types/trait-object) of that trait violates the `unused_must_use` lint.

 
```
#![allow(unused)]
fn main() {
#[must_use]
trait Critical {}
impl Critical for i32 {}

fn get_critical() -> impl Critical {
    4i32
}

// Violates the `unused_must_use` lint.
get_critical();
}
```
 When used on a function in a trait declaration, then the behavior also applies when the call expression is a function from an implementation of the trait.

 
```
#![allow(unused)]
fn main() {
trait Trait {
    #[must_use]
    fn use_me(&self) -> i32;
}

impl Trait for i32 {
    fn use_me(&self) -> i32 { 0i32 }
}

// Violates the `unused_must_use` lint.
5i32.use_me();
}
```
 When used on a function in a trait implementation, the attribute does nothing.

 
>  Note: Trivial no-op expressions containing the value will not violate the lint. Examples include wrapping the value in a type that does not implement [`Drop`](../special-types-and-traits#drop) and then not using that type and being the final expression of a [block expression](../expressions/block-expr) that is not used.
> 
>  
> ```
> #![allow(unused)]
> fn main() {
> #[must_use]
> fn five() -> i32 { 5i32 }
> 
> // None of these violate the unused_must_use lint.
> (five(),);
> Some(five());
> { five() };
> if true { five() } else { 0i32 };
> match true {
>     _ => five()
> };
> }
> ```
>  

 
>  Note: It is idiomatic to use a [let statement](../statements#let-statements) with a pattern of `_` when a must-used value is purposely discarded.
> 
>  
> ```
> #![allow(unused)]
> fn main() {
> #[must_use]
> fn five() -> i32 { 5i32 }
> 
> // Does not violate the unused_must_use lint.
> let _ = five();
> }
> ```
>  



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/attributes/diagnostics.html>

Code generation attributes
==========================

 The following [attributes](../attributes) are used for controlling code generation.

 Optimization hints
------------------

 The `cold` and `inline` [attributes](../attributes) give suggestions to generate code in a way that may be faster than what it would do without the hint. The attributes are only hints, and may be ignored.

 Both attributes can be used on [functions](../items/functions). When applied to a function in a [trait](../items/traits), they apply only to that function when used as a default function for a trait implementation and not to all trait implementations. The attributes have no effect on a trait function without a body.

 ### The `inline` attribute

 The *`inline` [attribute](../attributes)* suggests that a copy of the attributed function should be placed in the caller, rather than generating code to call the function where it is defined.

 
>  ***Note***: The `rustc` compiler automatically inlines functions based on internal heuristics. Incorrectly inlining functions can make the program slower, so this attribute should be used with care.
> 
>  

 There are three ways to use the inline attribute:

 * `#[inline]` *suggests* performing an inline expansion.
* `#[inline(always)]` *suggests* that an inline expansion should always be performed.
* `#[inline(never)]` *suggests* that an inline expansion should never be performed.

 
>  ***Note***: `#[inline]` in every form is a hint, with no *requirements* on the language to place a copy of the attributed function in the caller.
> 
>  

 ### The `cold` attribute

 The *`cold` [attribute](../attributes)* suggests that the attributed function is unlikely to be called.

 The `no_builtins` attribute
---------------------------

 The *`no_builtins` [attribute](../attributes)* may be applied at the crate level to disable optimizing certain code patterns to invocations of library functions that are assumed to exist.

 The `target_feature` attribute
------------------------------

 The *`target_feature` [attribute](../attributes)* may be applied to a function to enable code generation of that function for specific platform architecture features. It uses the [*MetaListNameValueStr*](../attributes#meta-item-attribute-syntax) syntax with a single key of `enable` whose value is a string of comma-separated feature names to enable.

 
```
#![allow(unused)]
fn main() {
#[cfg(target_feature = "avx2")]
#[target_feature(enable = "avx2")]
unsafe fn foo_avx2() {}
}
```
 Each [target architecture](../conditional-compilation#target_arch) has a set of features that may be enabled. It is an error to specify a feature for a target architecture that the crate is not being compiled for.

 It is [undefined behavior](../behavior-considered-undefined) to call a function that is compiled with a feature that is not supported on the current platform the code is running on, *except* if the platform explicitly documents this to be safe.

 Functions marked with `target_feature` are not inlined into a context that does not support the given features. The `#[inline(always)]` attribute may not be used with a `target_feature` attribute.

 ### Available features

 The following is a list of the available feature names.

 #### 
`x86` or `x86_64`

 Executing code with unsupported features is undefined behavior on this platform. Hence this platform requires that `#[target_feature]` is only applied to [`unsafe` functions](../unsafe-keyword).

 


| Feature | Implicitly Enables | Description |
| --- | --- | --- |
| `adx` |  | [ADX](https://en.wikipedia.org/wiki/Intel_ADX) — Multi-Precision Add-Carry Instruction Extensions |
| `aes` | `sse2` | [AES](https://en.wikipedia.org/wiki/AES_instruction_set) — Advanced Encryption Standard |
| `avx` | `sse4.2` | [AVX](https://en.wikipedia.org/wiki/Advanced_Vector_Extensions) — Advanced Vector Extensions |
| `avx2` | `avx` | [AVX2](https://en.wikipedia.org/wiki/Advanced_Vector_Extensions#AVX2) — Advanced Vector Extensions 2 |
| `bmi1` |  | [BMI1](https://en.wikipedia.org/wiki/Bit_Manipulation_Instruction_Sets) — Bit Manipulation Instruction Sets |
| `bmi2` |  | [BMI2](https://en.wikipedia.org/wiki/Bit_Manipulation_Instruction_Sets#BMI2) — Bit Manipulation Instruction Sets 2 |
| `cmpxchg16b` |  | [`cmpxchg16b`](https://www.felixcloutier.com/x86/cmpxchg8b:cmpxchg16b) - Compares and exchange 16 bytes (128 bits) of data atomically |
| `f16c` | `avx` | [F16C](https://en.wikipedia.org/wiki/F16C) — 16-bit floating point conversion instructions |
| `fma` | `avx` | [FMA3](https://en.wikipedia.org/wiki/FMA_instruction_set) — Three-operand fused multiply-add |
| `fxsr` |  | [`fxsave`](https://www.felixcloutier.com/x86/fxsave) and [`fxrstor`](https://www.felixcloutier.com/x86/fxrstor) — Save and restore x87 FPU, MMX Technology, and SSE State |
| `lzcnt` |  | [`lzcnt`](https://www.felixcloutier.com/x86/lzcnt) — Leading zeros count |
| `movbe` |  | [`movbe`](https://www.felixcloutier.com/x86/movbe) - Move data after swapping bytes |
| `pclmulqdq` | `sse2` | [`pclmulqdq`](https://www.felixcloutier.com/x86/pclmulqdq) — Packed carry-less multiplication quadword |
| `popcnt` |  | [`popcnt`](https://www.felixcloutier.com/x86/popcnt) — Count of bits set to 1 |
| `rdrand` |  | [`rdrand`](https://en.wikipedia.org/wiki/RdRand) — Read random number |
| `rdseed` |  | [`rdseed`](https://en.wikipedia.org/wiki/RdRand) — Read random seed |
| `sha` | `sse2` | [SHA](https://en.wikipedia.org/wiki/Intel_SHA_extensions) — Secure Hash Algorithm |
| `sse` |  | [SSE](https://en.wikipedia.org/wiki/Streaming_SIMD_Extensions) — Streaming SIMD Extensions |
| `sse2` | `sse` | [SSE2](https://en.wikipedia.org/wiki/SSE2) — Streaming SIMD Extensions 2 |
| `sse3` | `sse2` | [SSE3](https://en.wikipedia.org/wiki/SSE3) — Streaming SIMD Extensions 3 |
| `sse4.1` | `ssse3` | [SSE4.1](https://en.wikipedia.org/wiki/SSE4#SSE4.1) — Streaming SIMD Extensions 4.1 |
| `sse4.2` | `sse4.1` | [SSE4.2](https://en.wikipedia.org/wiki/SSE4#SSE4.2) — Streaming SIMD Extensions 4.2 |
| `ssse3` | `sse3` | [SSSE3](https://en.wikipedia.org/wiki/SSSE3) — Supplemental Streaming SIMD Extensions 3 |
| `xsave` |  | [`xsave`](https://www.felixcloutier.com/x86/xsave) — Save processor extended states |
| `xsavec` |  | [`xsavec`](https://www.felixcloutier.com/x86/xsavec) — Save processor extended states with compaction |
| `xsaveopt` |  | [`xsaveopt`](https://www.felixcloutier.com/x86/xsaveopt) — Save processor extended states optimized |
| `xsaves` |  | [`xsaves`](https://www.felixcloutier.com/x86/xsaves) — Save processor extended states supervisor |

  #### `aarch64`

 This platform requires that `#[target_feature]` is only applied to [`unsafe` functions](../unsafe-keyword).

 Further documentation on these features can be found in the [ARM Architecture Reference Manual](https://developer.arm.com/documentation/ddi0487/latest), or elsewhere on [developer.arm.com](https://developer.arm.com).

 
>  ***Note***: The following pairs of features should both be marked as enabled or disabled together if used:
> 
>  * `paca` and `pacg`, which LLVM currently implements as one feature.
> 
>  

 


| Feature | Implicitly Enables | Feature Name |
| --- | --- | --- |
| `aes` | `neon` | FEAT\_AES - Advanced SIMD AES instructions |
| `bf16` |  | FEAT\_BF16 - BFloat16 instructions |
| `bti` |  | FEAT\_BTI - Branch Target Identification |
| `crc` |  | FEAT\_CRC - CRC32 checksum instructions |
| `dit` |  | FEAT\_DIT - Data Independent Timing instructions |
| `dotprod` |  | FEAT\_DotProd - Advanced SIMD Int8 dot product instructions |
| `dpb` |  | FEAT\_DPB - Data cache clean to point of persistence |
| `dpb2` |  | FEAT\_DPB2 - Data cache clean to point of deep persistence |
| `f32mm` | `sve` | FEAT\_F32MM - SVE single-precision FP matrix multiply instruction |
| `f64mm` | `sve` | FEAT\_F64MM - SVE double-precision FP matrix multiply instruction |
| `fcma` | `neon` | FEAT\_FCMA - Floating point complex number support |
| `fhm` | `fp16` | FEAT\_FHM - Half-precision FP FMLAL instructions |
| `flagm` |  | FEAT\_FlagM - Conditional flag manipulation |
| `fp16` | `neon` | FEAT\_FP16 - Half-precision FP data processing |
| `frintts` |  | FEAT\_FRINTTS - Floating-point to int helper instructions |
| `i8mm` |  | FEAT\_I8MM - Int8 Matrix Multiplication |
| `jsconv` | `neon` | FEAT\_JSCVT - JavaScript conversion instruction |
| `lse` |  | FEAT\_LSE - Large System Extension |
| `lor` |  | FEAT\_LOR - Limited Ordering Regions extension |
| `mte` |  | FEAT\_MTE - Memory Tagging Extension |
| `neon` |  | FEAT\_FP & FEAT\_AdvSIMD - Floating Point and Advanced SIMD extension |
| `pan` |  | FEAT\_PAN - Privileged Access-Never extension |
| `paca` |  | FEAT\_PAuth - Pointer Authentication (address authentication) |
| `pacg` |  | FEAT\_PAuth - Pointer Authentication (generic authentication) |
| `pmuv3` |  | FEAT\_PMUv3 - Performance Monitors extension (v3) |
| `rand` |  | FEAT\_RNG - Random Number Generator |
| `ras` |  | FEAT\_RAS - Reliability, Availability and Serviceability extension |
| `rcpc` |  | FEAT\_LRCPC - Release consistent Processor Consistent |
| `rcpc2` | `rcpc` | FEAT\_LRCPC2 - RcPc with immediate offsets |
| `rdm` |  | FEAT\_RDM - Rounding Double Multiply accumulate |
| `sb` |  | FEAT\_SB - Speculation Barrier |
| `sha2` | `neon` | FEAT\_SHA1 & FEAT\_SHA256 - Advanced SIMD SHA instructions |
| `sha3` | `sha2` | FEAT\_SHA512 & FEAT\_SHA3 - Advanced SIMD SHA instructions |
| `sm4` | `neon` | FEAT\_SM3 & FEAT\_SM4 - Advanced SIMD SM3/4 instructions |
| `spe` |  | FEAT\_SPE - Statistical Profiling Extension |
| `ssbs` |  | FEAT\_SSBS - Speculative Store Bypass Safe |
| `sve` | `fp16` | FEAT\_SVE - Scalable Vector Extension |
| `sve2` | `sve` | FEAT\_SVE2 - Scalable Vector Extension 2 |
| `sve2-aes` | `sve2`, `aes` | FEAT\_SVE\_AES - SVE AES instructions |
| `sve2-sm4` | `sve2`, `sm4` | FEAT\_SVE\_SM4 - SVE SM4 instructions |
| `sve2-sha3` | `sve2`, `sha3` | FEAT\_SVE\_SHA3 - SVE SHA3 instructions |
| `sve2-bitperm` | `sve2` | FEAT\_SVE\_BitPerm - SVE Bit Permute |
| `tme` |  | FEAT\_TME - Transactional Memory Extension |
| `vh` |  | FEAT\_VHE - Virtualization Host Extensions |

  #### 
`wasm32` or `wasm64`

 `#[target_feature]` may be used with both safe and [`unsafe` functions](../unsafe-keyword) on Wasm platforms. It is impossible to cause undefined behavior via the `#[target_feature]` attribute because attempting to use instructions unsupported by the Wasm engine will fail at load time without the risk of being interpreted in a way different from what the compiler expected.

 


| Feature | Description |
| --- | --- |
| `simd128` | [WebAssembly simd proposal](https://github.com/webassembly/simd) |

  ### Additional information

 See the [`target_feature` conditional compilation option](../conditional-compilation#target_feature) for selectively enabling or disabling compilation of code based on compile-time settings. Note that this option is not affected by the `target_feature` attribute, and is only driven by the features enabled for the entire crate.

 See the [`is_x86_feature_detected`](../../std/arch/macro.is_x86_feature_detected) or [`is_aarch64_feature_detected`](../../std/arch/macro.is_aarch64_feature_detected) macros in the standard library for runtime feature detection on these platforms.

 
>  Note: `rustc` has a default set of features enabled for each target and CPU. The CPU may be chosen with the [`-C target-cpu`](https://doc.rust-lang.org/rustc/codegen-options/index.html#target-cpu) flag. Individual features may be enabled or disabled for an entire crate with the [`-C target-feature`](https://doc.rust-lang.org/rustc/codegen-options/index.html#target-feature) flag.
> 
>  

 The `track_caller` attribute
----------------------------

 The `track_caller` attribute may be applied to any function with [`"Rust"` ABI](../items/external-blocks#abi) with the exception of the entry point `fn main`. When applied to functions and methods in trait declarations, the attribute applies to all implementations. If the trait provides a default implementation with the attribute, then the attribute also applies to override implementations.

 When applied to a function in an `extern` block the attribute must also be applied to any linked implementations, otherwise undefined behavior results. When applied to a function which is made available to an `extern` block, the declaration in the `extern` block must also have the attribute, otherwise undefined behavior results.

 ### Behavior

 Applying the attribute to a function `f` allows code within `f` to get a hint of the [`Location`](https://doc.rust-lang.org/core/panic/struct.Location.html) of the "topmost" tracked call that led to `f`'s invocation. At the point of observation, an implementation behaves as if it walks up the stack from `f`'s frame to find the nearest frame of an *unattributed* function `outer`, and it returns the [`Location`](https://doc.rust-lang.org/core/panic/struct.Location.html) of the tracked call in `outer`.

 
```
#![allow(unused)]
fn main() {
#[track_caller]
fn f() {
    println!("{}", std::panic::Location::caller());
}
}
```
 
>  Note: `core` provides [`core::panic::Location::caller`](https://doc.rust-lang.org/core/panic/struct.Location.html#method.caller) for observing caller locations. It wraps the [`core::intrinsics::caller_location`](https://doc.rust-lang.org/core/intrinsics/fn.caller_location.html) intrinsic implemented by `rustc`.
> 
>  

 
>  Note: because the resulting `Location` is a hint, an implementation may halt its walk up the stack early. See [Limitations](#limitations) for important caveats.
> 
>  

 #### Examples

 When `f` is called directly by `calls_f`, code in `f` observes its callsite within `calls_f`:

 
```
#![allow(unused)]
fn main() {
#[track_caller]
fn f() {
    println!("{}", std::panic::Location::caller());
}
fn calls_f() {
    f(); // <-- f() prints this location
}
}
```
 When `f` is called by another attributed function `g` which is in turn called by `calls_g`, code in both `f` and `g` observes `g`'s callsite within `calls_g`:

 
```
#![allow(unused)]
fn main() {
#[track_caller]
fn f() {
    println!("{}", std::panic::Location::caller());
}
#[track_caller]
fn g() {
    println!("{}", std::panic::Location::caller());
    f();
}

fn calls_g() {
    g(); // <-- g() prints this location twice, once itself and once from f()
}
}
```
 When `g` is called by another attributed function `h` which is in turn called by `calls_h`, all code in `f`, `g`, and `h` observes `h`'s callsite within `calls_h`:

 
```
#![allow(unused)]
fn main() {
#[track_caller]
fn f() {
    println!("{}", std::panic::Location::caller());
}
#[track_caller]
fn g() {
    println!("{}", std::panic::Location::caller());
    f();
}
#[track_caller]
fn h() {
    println!("{}", std::panic::Location::caller());
    g();
}

fn calls_h() {
    h(); // <-- prints this location three times, once itself, once from g(), once from f()
}
}
```
 And so on.

 ### Limitations

 This information is a hint and implementations are not required to preserve it.

 In particular, coercing a function with `#[track_caller]` to a function pointer creates a shim which appears to observers to have been called at the attributed function's definition site, losing actual caller information across virtual calls. A common example of this coercion is the creation of a trait object whose methods are attributed.

 
>  Note: The aforementioned shim for function pointers is necessary because `rustc` implements `track_caller` in a codegen context by appending an implicit parameter to the function ABI, but this would be unsound for an indirect call because the parameter is not a part of the function's type and a given function pointer type may or may not refer to a function with the attribute. The creation of a shim hides the implicit parameter from callers of the function pointer, preserving soundness.
> 
>  

 The `instruction_set` attribute
-------------------------------

 The *`instruction_set` attribute* may be applied to a function to enable code generation for a specific instruction set supported by the target architecture. It uses the [*MetaListPath*](../attributes#meta-item-attribute-syntax) syntax and a path comprised of the architecture and instruction set to specify how to generate the code for architectures where a single program may utilize multiple instruction sets.

 The following values are available on targets for the `ARMv4` and `ARMv5te` architectures:

 * `arm::a32` - Uses ARM code.
* `arm::t32` - Uses Thumb code.

 
```
#[instruction_set(arm::a32)]
fn foo_arm_code() {}

#[instruction_set(arm::t32)]
fn bar_thumb_code() {}
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/attributes/codegen.html>

Limits
======

 The following [attributes](../attributes) affect compile-time limits.

 The `recursion_limit` attribute
-------------------------------

 The *`recursion_limit` attribute* may be applied at the [crate](../crates-and-source-files) level to set the maximum depth for potentially infinitely-recursive compile-time operations like macro expansion or auto-dereference. It uses the [*MetaNameValueStr*](../attributes#meta-item-attribute-syntax) syntax to specify the recursion depth.

 
>  Note: The default in `rustc` is 128.
> 
>  

 
```
#![allow(unused)]
#![recursion_limit = "4"]

fn main() {
macro_rules! a {
    () => { a!(1); };
    (1) => { a!(2); };
    (2) => { a!(3); };
    (3) => { a!(4); };
    (4) => { };
}

// This fails to expand because it requires a recursion depth greater than 4.
a!{}
}
```
 
```
#![allow(unused)]
#![recursion_limit = "1"]

fn main() {
// This fails because it requires two recursive steps to auto-dereference.
(|_: &u8| {})(&&&1);
}
```
 The `type_length_limit` attribute
---------------------------------

 The *`type_length_limit` attribute* limits the maximum number of type substitutions made when constructing a concrete type during monomorphization. It is applied at the [crate](../crates-and-source-files) level, and uses the [*MetaNameValueStr*](../attributes#meta-item-attribute-syntax) syntax to set the limit based on the number of type substitutions.

 
>  Note: The default in `rustc` is 1048576.
> 
>  

 
```
#![allow(unused)]
#![type_length_limit = "4"]

fn main() {
fn f<T>(x: T) {}

// This fails to compile because monomorphizing to
// `f::<((((i32,), i32), i32), i32)>` requires more than 4 type elements.
f(((((1,), 2), 3), 4));
}
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/attributes/limits.html>

Type system attributes
======================

 The following [attributes](../attributes) are used for changing how a type can be used.

 The `non_exhaustive` attribute
------------------------------

 The *`non_exhaustive` attribute* indicates that a type or variant may have more fields or variants added in the future. It can be applied to [`struct`s](../items/structs), [`enum`s](../items/enumerations), and `enum` variants.

 The `non_exhaustive` attribute uses the [*MetaWord*](../attributes#meta-item-attribute-syntax) syntax and thus does not take any inputs.

 Within the defining crate, `non_exhaustive` has no effect.

 
```
#![allow(unused)]
fn main() {
#[non_exhaustive]
pub struct Config {
    pub window_width: u16,
    pub window_height: u16,
}

#[non_exhaustive]
pub enum Error {
    Message(String),
    Other,
}

pub enum Message {
    #[non_exhaustive] Send { from: u32, to: u32, contents: String },
    #[non_exhaustive] Reaction(u32),
    #[non_exhaustive] Quit,
}

// Non-exhaustive structs can be constructed as normal within the defining crate.
let config = Config { window_width: 640, window_height: 480 };

// Non-exhaustive structs can be matched on exhaustively within the defining crate.
if let Config { window_width, window_height } = config {
    // ...
}

let error = Error::Other;
let message = Message::Reaction(3);

// Non-exhaustive enums can be matched on exhaustively within the defining crate.
match error {
    Error::Message(ref s) => { },
    Error::Other => { },
}

match message {
    // Non-exhaustive variants can be matched on exhaustively within the defining crate.
    Message::Send { from, to, contents } => { },
    Message::Reaction(id) => { },
    Message::Quit => { },
}
}
```
 Outside of the defining crate, types annotated with `non_exhaustive` have limitations that preserve backwards compatibility when new fields or variants are added.

 Non-exhaustive types cannot be constructed outside of the defining crate:

 * Non-exhaustive variants ([`struct`](../items/structs) or [`enum` variant](../items/enumerations)) cannot be constructed with a [*StructExpression*](../expressions/struct-expr) (including with [functional update syntax](../expressions/struct-expr#functional-update-syntax)).
* [`enum`](../items/enumerations) instances can be constructed.

 
```
// `Config`, `Error`, and `Message` are types defined in an upstream crate that have been
// annotated as `#[non_exhaustive]`.
use upstream::{Config, Error, Message};

// Cannot construct an instance of `Config`, if new fields were added in
// a new version of `upstream` then this would fail to compile, so it is
// disallowed.
let config = Config { window_width: 640, window_height: 480 };

// Can construct an instance of `Error`, new variants being introduced would
// not result in this failing to compile.
let error = Error::Message("foo".to_string());

// Cannot construct an instance of `Message::Send` or `Message::Reaction`,
// if new fields were added in a new version of `upstream` then this would
// fail to compile, so it is disallowed.
let message = Message::Send { from: 0, to: 1, contents: "foo".to_string(), };
let message = Message::Reaction(0);

// Cannot construct an instance of `Message::Quit`, if this were converted to
// a tuple-variant `upstream` then this would fail to compile.
let message = Message::Quit;
```
 There are limitations when matching on non-exhaustive types outside of the defining crate:

 * When pattern matching on a non-exhaustive variant ([`struct`](../items/structs) or [`enum` variant](../items/enumerations)), a [*StructPattern*](../patterns#struct-patterns) must be used which must include a `..`. Tuple variant constructor visibility is lowered to `min($vis, pub(crate))`.
* When pattern matching on a non-exhaustive [`enum`](../items/enumerations), matching on a variant does not contribute towards the exhaustiveness of the arms.

 
```
// `Config`, `Error`, and `Message` are types defined in an upstream crate that have been
// annotated as `#[non_exhaustive]`.
use upstream::{Config, Error, Message};

// Cannot match on a non-exhaustive enum without including a wildcard arm.
match error {
  Error::Message(ref s) => { },
  Error::Other => { },
  // would compile with: `_ => {},`
}

// Cannot match on a non-exhaustive struct without a wildcard.
if let Ok(Config { window_width, window_height }) = config {
    // would compile with: `..`
}

match message {
  // Cannot match on a non-exhaustive struct enum variant without including a wildcard.
  Message::Send { from, to, contents } => { },
  // Cannot match on a non-exhaustive tuple or unit enum variant.
  Message::Reaction(type) => { },
  Message::Quit => { },
}
```
 It's also not allowed to cast non-exhaustive types from foreign crates.

 
```
use othercrate::NonExhaustiveEnum;

// Cannot cast a non-exhaustive enum outside of its defining crate.
let _ = NonExhaustiveEnum::default() as u8;
```
 Non-exhaustive types are always considered inhabited in downstream crates.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/attributes/type_system.html>

Debugger attributes
===================

 The following [attributes](../attributes) are used for enhancing the debugging experience when using third-party debuggers like GDB or WinDbg.

 The `debugger_visualizer` attribute
-----------------------------------

 The *`debugger_visualizer` attribute* can be used to embed a debugger visualizer file into the debug information. This enables an improved debugger experience for displaying values in the debugger. It uses the [*MetaListNameValueStr*](../attributes#meta-item-attribute-syntax) syntax to specify its inputs, and must be specified as a crate attribute.

 ### Using `debugger_visualizer` with Natvis

 Natvis is an XML-based framework for Microsoft debuggers (such as Visual Studio and WinDbg) that uses declarative rules to customize the display of types. For detailed information on the Natvis format, refer to Microsoft's [Natvis documentation](https://docs.microsoft.com/en-us/visualstudio/debugger/create-custom-views-of-native-objects).

 This attribute only supports embedding Natvis files on `-windows-msvc` targets.

 The path to the Natvis file is specified with the `natvis_file` key, which is a path relative to the crate source file:

 
```
#![debugger_visualizer(natvis_file = "Rectangle.natvis")]

struct FancyRect {
    x: f32,
    y: f32,
    dx: f32,
    dy: f32,
}

fn main() {
    let fancy_rect = FancyRect { x: 10.0, y: 10.0, dx: 5.0, dy: 5.0 };
    println!("set breakpoint here");
}
```
 and `Rectangle.natvis` contains:

 
```
<?xml version="1.0" encoding="utf-8"?>
<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010">
    <Type Name="foo::FancyRect">
      <DisplayString>({x},{y}) + ({dx}, {dy})</DisplayString>
      <Expand>
        <Synthetic Name="LowerLeft">
          <DisplayString>({x}, {y})</DisplayString>
        </Synthetic>
        <Synthetic Name="UpperLeft">
          <DisplayString>({x}, {y + dy})</DisplayString>
        </Synthetic>
        <Synthetic Name="UpperRight">
          <DisplayString>({x + dx}, {y + dy})</DisplayString>
        </Synthetic>
        <Synthetic Name="LowerRight">
          <DisplayString>({x + dx}, {y})</DisplayString>
        </Synthetic>
      </Expand>
    </Type>
</AutoVisualizer>

```
 When viewed under WinDbg, the `fancy_rect` variable would be shown as follows:

 
```
> Variables:
  > fancy_rect: (10.0, 10.0) + (5.0, 5.0)
    > LowerLeft: (10.0, 10.0)
    > UpperLeft: (10.0, 15.0)
    > UpperRight: (15.0, 15.0)
    > LowerRight: (15.0, 10.0)

```
 ### Using `debugger_visualizer` with GDB

 GDB supports the use of a structured Python script, called a *pretty printer*, that describes how a type should be visualized in the debugger view. For detailed information on pretty printers, refer to GDB's [pretty printing documentation](https://sourceware.org/gdb/onlinedocs/gdb/Pretty-Printing.html).

 Embedded pretty printers are not automatically loaded when debugging a binary under GDB. There are two ways to enable auto-loading embedded pretty printers:

 1. Launch GDB with extra arguments to explicitly add a directory or binary to the auto-load safe path: `gdb -iex "add-auto-load-safe-path safe-path path/to/binary" path/to/binary` For more information, see GDB's [auto-loading documentation](https://sourceware.org/gdb/onlinedocs/gdb/Auto_002dloading-safe-path.html).
2. Create a file named `gdbinit` under `$HOME/.config/gdb` (you may need to create the directory if it doesn't already exist). Add the following line to that file: `add-auto-load-safe-path path/to/binary`.

 These scripts are embedded using the `gdb_script_file` key, which is a path relative to the crate source file.

 
```
#![debugger_visualizer(gdb_script_file = "printer.py")]

struct Person {
    name: String,
    age: i32,
}

fn main() {
    let bob = Person { name: String::from("Bob"), age: 10 };
    println!("set breakpoint here");
}
```
 and `printer.py` contains:

 
```
import gdb

class PersonPrinter:
    "Print a Person"

    def __init__(self, val):
        self.val = val
        self.name = val["name"]
        self.age = int(val["age"])

    def to_string(self):
        return "{} is {} years old.".format(self.name, self.age)

def lookup(val):
    lookup_tag = val.type.tag
    if lookup_tag is None:
        return None
    if "foo::Person" == lookup_tag:
        return PersonPrinter(val)

    return None

gdb.current_objfile().pretty_printers.append(lookup)

```
 When the crate's debug executable is passed into GDB[1](#rust-gdb), `print bob` will display:

 
```
"Bob" is 10 years old.

```
 
1 Note: This assumes you are using the `rust-gdb` script which configures pretty-printers for standard library types like `String`.

 

 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/attributes/debugger.html>

Statements and expressions
==========================

 Rust is *primarily* an expression language. This means that most forms of value-producing or effect-causing evaluation are directed by the uniform syntax category of *expressions*. Each kind of expression can typically *nest* within each other kind of expression, and rules for evaluation of expressions involve specifying both the value produced by the expression and the order in which its sub-expressions are themselves evaluated.

 In contrast, statements serve *mostly* to contain and explicitly sequence expression evaluation.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/statements-and-expressions.html>

Statements
==========

 
>  **Syntax**  
>  *Statement* :  
>  `;`  
>  | [*Item*](items)  
>  | [*LetStatement*](#let-statements)  
>  | [*ExpressionStatement*](#expression-statements)  
>  | [*MacroInvocationSemi*](macros#macro-invocation)
> 
>  

 A *statement* is a component of a [block](expressions/block-expr), which is in turn a component of an outer [expression](expressions) or [function](items/functions).

 Rust has two kinds of statement: [declaration statements](#declaration-statements) and [expression statements](#expression-statements).

 Declaration statements
----------------------

 A *declaration statement* is one that introduces one or more *names* into the enclosing statement block. The declared names may denote new variables or new <items>.

 The two kinds of declaration statements are item declarations and `let` statements.

 ### Item declarations

 An *item declaration statement* has a syntactic form identical to an [item declaration](items) within a [module](items/modules). Declaring an item within a statement block restricts its scope to the block containing the statement. The item is not given a [canonical path](paths#canonical-paths) nor are any sub-items it may declare. The exception to this is that associated items defined by [implementations](items/implementations) are still accessible in outer scopes as long as the item and, if applicable, trait are accessible. It is otherwise identical in meaning to declaring the item inside a module.

 There is no implicit capture of the containing function's generic parameters, parameters, and local variables. For example, `inner` may not access `outer_var`.

 
```
#![allow(unused)]
fn main() {
fn outer() {
  let outer_var = true;

  fn inner() { /* outer_var is not in scope here */ }

  inner();
}
}
```
 ### 
`let` statements

 
>  **Syntax**  
>  *LetStatement* :  
>  [*OuterAttribute*](attributes)\* `let` [*PatternNoTopAlt*](patterns) ( `:` [*Type*](types) )? (`=` [*Expression*](expressions) [†](#let-else-restriction) ( `else` [*BlockExpression*](expressions/block-expr)) ? ) ? `;`
> 
>  † When an `else` block is specified, the *Expression* must not be a [*LazyBooleanExpression*](expressions/operator-expr#lazy-boolean-operators), or end with a `}`.
> 
>  

 A *`let` statement* introduces a new set of <variables>, given by a [pattern](patterns). The pattern is followed optionally by a type annotation and then either ends, or is followed by an initializer expression plus an optional `else` block. When no type annotation is given, the compiler will infer the type, or signal an error if insufficient type information is available for definite inference. Any variables introduced by a variable declaration are visible from the point of declaration until the end of the enclosing block scope, except when they are shadowed by another variable declaration.

 If an `else` block is not present, the pattern must be irrefutable. If an `else` block is present, the pattern may be refutable. If the pattern does not match (this requires it to be refutable), the `else` block is executed. The `else` block must always diverge (evaluate to the [never type](types/never)).

 
```
#![allow(unused)]
fn main() {
let (mut v, w) = (vec![1, 2, 3], 42); // The bindings may be mut or const
let Some(t) = v.pop() else { // Refutable patterns require an else block
    panic!(); // The else block must diverge
};
let [u, v] = [v[0], v[1]] else { // This pattern is irrefutable, so the compiler
                                 // will lint as the else block is redundant.
    panic!();
};
}
```
 Expression statements
---------------------

 
>  **Syntax**  
>  *ExpressionStatement* :  
>  [*ExpressionWithoutBlock*](expressions) `;`  
>  | [*ExpressionWithBlock*](expressions) `;`?
> 
>  

 An *expression statement* is one that evaluates an [expression](expressions) and ignores its result. As a rule, an expression statement's purpose is to trigger the effects of evaluating its expression.

 An expression that consists of only a [block expression](expressions/block-expr) or control flow expression, if used in a context where a statement is permitted, can omit the trailing semicolon. This can cause an ambiguity between it being parsed as a standalone statement and as a part of another expression; in this case, it is parsed as a statement. The type of [*ExpressionWithBlock*](expressions) expressions when used as statements must be the unit type.

 
```
#![allow(unused)]
fn main() {
let mut v = vec![1, 2, 3];
v.pop();          // Ignore the element returned from pop
if v.is_empty() {
    v.push(5);
} else {
    v.remove(0);
}                 // Semicolon can be omitted.
[1];              // Separate expression statement, not an indexing expression.
}
```
 When the trailing semicolon is omitted, the result must be type `()`.

 
```
#![allow(unused)]
fn main() {
// bad: the block's type is i32, not ()
// Error: expected `()` because of default return type
// if true {
//   1
// }

// good: the block's type is i32
if true {
  1
} else {
  2
};
}
```
 Attributes on Statements
------------------------

 Statements accept [outer attributes](attributes). The attributes that have meaning on a statement are [`cfg`](conditional-compilation), and [the lint check attributes](attributes/diagnostics#lint-check-attributes).



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/statements.html>

Expressions
===========

 
>  **Syntax**  
>  *Expression* :  
>  *ExpressionWithoutBlock*  
>  | *ExpressionWithBlock*
> 
>  *ExpressionWithoutBlock* :  
>  [*OuterAttribute*](attributes)\*[†](#expression-attributes)  
>  (  
>  [*LiteralExpression*](expressions/literal-expr)  
>  | [*PathExpression*](expressions/path-expr)  
>  | [*OperatorExpression*](expressions/operator-expr)  
>  | [*GroupedExpression*](expressions/grouped-expr)  
>  | [*ArrayExpression*](expressions/array-expr)  
>  | [*AwaitExpression*](expressions/await-expr)  
>  | [*IndexExpression*](expressions/array-expr#array-and-slice-indexing-expressions)  
>  | [*TupleExpression*](expressions/tuple-expr)  
>  | [*TupleIndexingExpression*](expressions/tuple-expr#tuple-indexing-expressions)  
>  | [*StructExpression*](expressions/struct-expr)  
>  | [*CallExpression*](expressions/call-expr)  
>  | [*MethodCallExpression*](expressions/method-call-expr)  
>  | [*FieldExpression*](expressions/field-expr)  
>  | [*ClosureExpression*](expressions/closure-expr)  
>  | [*AsyncBlockExpression*](expressions/block-expr#async-blocks)  
>  | [*ContinueExpression*](expressions/loop-expr#continue-expressions)  
>  | [*BreakExpression*](expressions/loop-expr#break-expressions)  
>  | [*RangeExpression*](expressions/range-expr)  
>  | [*ReturnExpression*](expressions/return-expr)  
>  | [*UnderscoreExpression*](expressions/underscore-expr)  
>  | [*MacroInvocation*](macros#macro-invocation)  
>  )
> 
>  *ExpressionWithBlock* :  
>  [*OuterAttribute*](attributes)\*[†](#expression-attributes)  
>  (  
>  [*BlockExpression*](expressions/block-expr)  
>  | [*UnsafeBlockExpression*](expressions/block-expr#unsafe-blocks)  
>  | [*LoopExpression*](expressions/loop-expr)  
>  | [*IfExpression*](expressions/if-expr#if-expressions)  
>  | [*IfLetExpression*](expressions/if-expr#if-let-expressions)  
>  | [*MatchExpression*](expressions/match-expr)  
>  )
> 
>  

 An expression may have two roles: it always produces a *value*, and it may have *effects* (otherwise known as "side effects"). An expression *evaluates to* a value, and has effects during *evaluation*. Many expressions contain sub-expressions, called the *operands* of the expression. The meaning of each kind of expression dictates several things:

 * Whether or not to evaluate the operands when evaluating the expression
* The order in which to evaluate the operands
* How to combine the operands' values to obtain the value of the expression

 In this way, the structure of expressions dictates the structure of execution. Blocks are just another kind of expression, so blocks, statements, expressions, and blocks again can recursively nest inside each other to an arbitrary depth.

 
>  **Note**: We give names to the operands of expressions so that we may discuss them, but these names are not stable and may be changed.
> 
>  

 Expression precedence
---------------------

 The precedence of Rust operators and expressions is ordered as follows, going from strong to weak. Binary Operators at the same precedence level are grouped in the order given by their associativity.

 


| Operator/Expression | Associativity |
| --- | --- |
| Paths |  |
| Method calls |  |
| Field expressions | left to right |
| Function calls, array indexing |  |
| `?` |  |
| Unary `-` `*` `!` `&` `&mut` |  |
| `as` | left to right |
| `*` `/` `%` | left to right |
| `+` `-` | left to right |
| `<<` `>>` | left to right |
| `&` | left to right |
| `^` | left to right |
| `|` | left to right |
| `==` `!=` `<` `>` `<=` `>=` | Require parentheses |
| `&&` | left to right |
| `||` | left to right |
| `..` `..=` | Require parentheses |
| `=` `+=` `-=` `*=` `/=` `%=`  `&=` `|=` `^=` `<<=` `>>=` | right to left |
| `return` `break` closures |  |

  Evaluation order of operands
----------------------------

 The following list of expressions all evaluate their operands the same way, as described after the list. Other expressions either don't take operands or evaluate them conditionally as described on their respective pages.

 * Dereference expression
* Error propagation expression
* Negation expression
* Arithmetic and logical binary operators
* Comparison operators
* Type cast expression
* Grouped expression
* Array expression
* Await expression
* Index expression
* Tuple expression
* Tuple index expression
* Struct expression
* Call expression
* Method call expression
* Field expression
* Break expression
* Range expression
* Return expression

 The operands of these expressions are evaluated prior to applying the effects of the expression. Expressions taking multiple operands are evaluated left to right as written in the source code.

 
>  **Note**: Which subexpressions are the operands of an expression is determined by expression precedence as per the previous section.
> 
>  

 For example, the two `next` method calls will always be called in the same order:

 
```
#![allow(unused)]
fn main() {
// Using vec instead of array to avoid references
// since there is no stable owned array iterator
// at the time this example was written.
let mut one_two = vec![1, 2].into_iter();
assert_eq!(
    (1, 2),
    (one_two.next().unwrap(), one_two.next().unwrap())
);
}
```
 
>  **Note**: Since this is applied recursively, these expressions are also evaluated from innermost to outermost, ignoring siblings until there are no inner subexpressions.
> 
>  

 Place Expressions and Value Expressions
---------------------------------------

 Expressions are divided into two main categories: place expressions and value expressions; there is also a third, minor category of expressions called assignee expressions. Within each expression, operands may likewise occur in either place context or value context. The evaluation of an expression depends both on its own category and the context it occurs within.

 A *place expression* is an expression that represents a memory location. These expressions are [paths](expressions/path-expr) which refer to local variables, [static variables](items/static-items), [dereferences](expressions/operator-expr#the-dereference-operator) (`*expr`), [array indexing](expressions/array-expr#array-and-slice-indexing-expressions) expressions (`expr[expr]`), [field](expressions/field-expr) references (`expr.f`) and parenthesized place expressions. All other expressions are value expressions.

 A *value expression* is an expression that represents an actual value.

 The following contexts are *place expression* contexts:

 * The left operand of a [compound assignment](expressions/operator-expr#compound-assignment-expressions) expression.
* The operand of a unary [borrow](expressions/operator-expr#borrow-operators), [address-of](expressions/operator-expr#raw-address-of-operators) or [dereference](expressions/operator-expr#the-dereference-operator) operator.
* The operand of a field expression.
* The indexed operand of an array indexing expression.
* The operand of any [implicit borrow](#implicit-borrows).
* The initializer of a [let statement](statements#let-statements).
* The [scrutinee](glossary#scrutinee) of an [`if let`](expressions/if-expr#if-let-expressions), [`match`](expressions/match-expr), or [`while let`](expressions/loop-expr#predicate-pattern-loops) expression.
* The base of a [functional update](expressions/struct-expr#functional-update-syntax) struct expression.

 
>  Note: Historically, place expressions were called *lvalues* and value expressions were called *rvalues*.
> 
>  

 An *assignee expression* is an expression that appears in the left operand of an [assignment](expressions/operator-expr#assignment-expressions) expression. Explicitly, the assignee expressions are:

 * Place expressions.
* [Underscores](expressions/underscore-expr).
* [Tuples](expressions/tuple-expr) of assignee expressions.
* [Slices](expressions/array-expr) of assingee expressions.
* [Tuple structs](expressions/struct-expr) of assignee expressions.
* [Structs](expressions/struct-expr) of assignee expressions (with optionally named fields).
* [Unit structs](expressions/struct-expr).

 Arbitrary parenthesisation is permitted inside assignee expressions.

 ### Moved and copied types

 When a place expression is evaluated in a value expression context, or is bound by value in a pattern, it denotes the value held *in* that memory location. If the type of that value implements [`Copy`](special-types-and-traits#copy), then the value will be copied. In the remaining situations, if that type is [`Sized`](special-types-and-traits#sized), then it may be possible to move the value. Only the following place expressions may be moved out of:

 * [Variables](variables) which are not currently borrowed.
* [Temporary values](#temporaries).
* [Fields](expressions/field-expr) of a place expression which can be moved out of and don't implement [`Drop`](special-types-and-traits#drop).
* The result of [dereferencing](expressions/operator-expr#the-dereference-operator) an expression with type [`Box<T>`](../std/boxed/struct.box) and that can also be moved out of.

 After moving out of a place expression that evaluates to a local variable, the location is deinitialized and cannot be read from again until it is reinitialized. In all other cases, trying to use a place expression in a value expression context is an error.

 ### Mutability

 For a place expression to be [assigned](expressions/operator-expr#assignment-expressions) to, mutably [borrowed](expressions/operator-expr#borrow-operators), [implicitly mutably borrowed](#implicit-borrows), or bound to a pattern containing `ref mut`, it must be *mutable*. We call these *mutable place expressions*. In contrast, other place expressions are called *immutable place expressions*.

 The following expressions can be mutable place expression contexts:

 * Mutable <variables> which are not currently borrowed.
* [Mutable `static` items](items/static-items#mutable-statics).
* [Temporary values](#temporaries).
* [Fields](expressions/field-expr): this evaluates the subexpression in a mutable place expression context.
* [Dereferences](expressions/operator-expr#the-dereference-operator) of a `*mut T` pointer.
* Dereference of a variable, or field of a variable, with type `&mut T`. Note: This is an exception to the requirement of the next rule.
* Dereferences of a type that implements `DerefMut`: this then requires that the value being dereferenced is evaluated in a mutable place expression context.
* [Array indexing](expressions/array-expr#array-and-slice-indexing-expressions) of a type that implements `IndexMut`: this then evaluates the value being indexed, but not the index, in mutable place expression context.

 ### Temporaries

 When using a value expression in most place expression contexts, a temporary unnamed memory location is created and initialized to that value. The expression evaluates to that location instead, except if [promoted](destructors#constant-promotion) to a `static`. The [drop scope](destructors#drop-scopes) of the temporary is usually the end of the enclosing statement.

 ### Implicit Borrows

 Certain expressions will treat an expression as a place expression by implicitly borrowing it. For example, it is possible to compare two unsized [slices](types/slice) for equality directly, because the `==` operator implicitly borrows its operands:

 
```
#![allow(unused)]
fn main() {
let c = [1, 2, 3];
let d = vec![1, 2, 3];
let a: &[i32];
let b: &[i32];
a = &c;
b = &d;
// ...
*a == *b;
// Equivalent form:
::std::cmp::PartialEq::eq(&*a, &*b);
}
```
 Implicit borrows may be taken in the following expressions:

 * Left operand in [method-call](expressions/method-call-expr) expressions.
* Left operand in [field](expressions/field-expr) expressions.
* Left operand in [call expressions](expressions/call-expr).
* Left operand in [array indexing](expressions/array-expr#array-and-slice-indexing-expressions) expressions.
* Operand of the [dereference operator](expressions/operator-expr#the-dereference-operator) (`*`).
* Operands of [comparison](expressions/operator-expr#comparison-operators).
* Left operands of the [compound assignment](expressions/operator-expr#compound-assignment-expressions).

 Overloading Traits
------------------

 Many of the following operators and expressions can also be overloaded for other types using traits in `std::ops` or `std::cmp`. These traits also exist in `core::ops` and `core::cmp` with the same names.

 Expression Attributes
---------------------

 [Outer attributes](attributes) before an expression are allowed only in a few specific cases:

 * Before an expression used as a [statement](statements).
* Elements of [array expressions](expressions/array-expr), [tuple expressions](expressions/tuple-expr), [call expressions](expressions/call-expr), and tuple-style [struct](expressions/struct-expr) expressions.
* The tail expression of [block expressions](expressions/block-expr).

 They are never allowed before:

 * [Range](expressions/range-expr) expressions.
* Binary operator expressions ([*ArithmeticOrLogicalExpression*](expressions/operator-expr#arithmetic-and-logical-binary-operators), [*ComparisonExpression*](expressions/operator-expr#comparison-operators), [*LazyBooleanExpression*](expressions/operator-expr#lazy-boolean-operators), [*TypeCastExpression*](expressions/operator-expr#type-cast-expressions), [*AssignmentExpression*](expressions/operator-expr#assignment-expressions), [*CompoundAssignmentExpression*](expressions/operator-expr#compound-assignment-expressions)).



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/expressions.html>

Literal expressions
===================

 
>  **Syntax**  
>  *LiteralExpression* :  
>  [CHAR\_LITERAL](../tokens#character-literals)  
>  | [STRING\_LITERAL](../tokens#string-literals)  
>  | [RAW\_STRING\_LITERAL](../tokens#raw-string-literals)  
>  | [BYTE\_LITERAL](../tokens#byte-literals)  
>  | [BYTE\_STRING\_LITERAL](../tokens#byte-string-literals)  
>  | [RAW\_BYTE\_STRING\_LITERAL](../tokens#raw-byte-string-literals)  
>  | [INTEGER\_LITERAL](../tokens#integer-literals)  
>  | [FLOAT\_LITERAL](../tokens#floating-point-literals)  
>  | `true` | `false`
> 
>  

 A *literal expression* is an expression consisting of a single token, rather than a sequence of tokens, that immediately and directly denotes the value it evaluates to, rather than referring to it by name or some other evaluation rule.

 A literal is a form of [constant expression](../const_eval#constant-expressions), so is evaluated (primarily) at compile time.

 Each of the lexical [literal](../tokens#literals) forms described earlier can make up a literal expression, as can the keywords `true` and `false`.

 
```
#![allow(unused)]
fn main() {
"hello";   // string type
'5';       // character type
5;         // integer type
}
```
 Character literal expressions
-----------------------------

 A character literal expression consists of a single [CHAR\_LITERAL](../tokens#character-literals) token.

 
>  **Note**: This section is incomplete.
> 
>  

 String literal expressions
--------------------------

 A string literal expression consists of a single [STRING\_LITERAL](../tokens#string-literals) or [RAW\_STRING\_LITERAL](../tokens#raw-string-literals) token.

 
>  **Note**: This section is incomplete.
> 
>  

 Byte literal expressions
------------------------

 A byte literal expression consists of a single [BYTE\_LITERAL](../tokens#byte-literals) token.

 
>  **Note**: This section is incomplete.
> 
>  

 Byte string literal expressions
-------------------------------

 A string literal expression consists of a single [BYTE\_STRING\_LITERAL](../tokens#byte-string-literals) or [RAW\_BYTE\_STRING\_LITERAL](../tokens#raw-byte-string-literals) token.

 
>  **Note**: This section is incomplete.
> 
>  

 Integer literal expressions
---------------------------

 An integer literal expression consists of a single [INTEGER\_LITERAL](../tokens#integer-literals) token.

 If the token has a [suffix](../tokens#suffixes), the suffix must be the name of one of the [primitive integer types](../types/numeric): `u8`, `i8`, `u16`, `i16`, `u32`, `i32`, `u64`, `i64`, `u128`, `i128`, `usize`, or `isize`, and the expression has that type.

 If the token has no suffix, the expression's type is determined by type inference:

 * If an integer type can be *uniquely* determined from the surrounding program context, the expression has that type.
* If the program context under-constrains the type, it defaults to the signed 32-bit integer `i32`.
* If the program context over-constrains the type, it is considered a static type error.

 Examples of integer literal expressions:

 
```
#![allow(unused)]
fn main() {
123;                               // type i32
123i32;                            // type i32
123u32;                            // type u32
123_u32;                           // type u32
let a: u64 = 123;                  // type u64

0xff;                              // type i32
0xff_u8;                           // type u8

0o70;                              // type i32
0o70_i16;                          // type i16

0b1111_1111_1001_0000;             // type i32
0b1111_1111_1001_0000i64;          // type i64

0usize;                            // type usize
}
```
 The value of the expression is determined from the string representation of the token as follows:

 * An integer radix is chosen by inspecting the first two characters of the string, as follows:


	+ `0b` indicates radix 2
	+ `0o` indicates radix 8
	+ `0x` indicates radix 16
	+ otherwise the radix is 10.
* If the radix is not 10, the first two characters are removed from the string.
* Any suffix is removed from the string.
* Any underscores are removed from the string.
* The string is converted to a `u128` value as if by [`u128::from_str_radix`](https://doc.rust-lang.org/core/primitive.u128.html#method.from_str_radix) with the chosen radix. If the value does not fit in `u128`, it is a compiler error.
* The `u128` value is converted to the expression's type via a [numeric cast](operator-expr#numeric-cast).

 
>  **Note**: The final cast will truncate the value of the literal if it does not fit in the expression's type. `rustc` includes a [lint check](../attributes/diagnostics#lint-check-attributes) named `overflowing_literals`, defaulting to `deny`, which rejects expressions where this occurs.
> 
>  

 
>  **Note**: `-1i8`, for example, is an application of the [negation operator](operator-expr#negation-operators) to the literal expression `1i8`, not a single integer literal expression. See [Overflow](operator-expr#overflow) for notes on representing the most negative value for a signed type.
> 
>  

 Floating-point literal expressions
----------------------------------

 A floating-point literal expression has one of two forms:

 * a single [FLOAT\_LITERAL](../tokens#floating-point-literals) token
* a single [INTEGER\_LITERAL](../tokens#integer-literals) token which has a suffix and no radix indicator

 If the token has a [suffix](../tokens#suffixes), the suffix must be the name of one of the [primitive floating-point types](../types/numeric#floating-point-types): `f32` or `f64`, and the expression has that type.

 If the token has no suffix, the expression's type is determined by type inference:

 * If a floating-point type can be *uniquely* determined from the surrounding program context, the expression has that type.
* If the program context under-constrains the type, it defaults to `f64`.
* If the program context over-constrains the type, it is considered a static type error.

 Examples of floating-point literal expressions:

 
```
#![allow(unused)]
fn main() {
123.0f64;        // type f64
0.1f64;          // type f64
0.1f32;          // type f32
12E+99_f64;      // type f64
5f32;            // type f32
let x: f64 = 2.; // type f64
}
```
 The value of the expression is determined from the string representation of the token as follows:

 * Any suffix is removed from the string.
* Any underscores are removed from the string.
* The string is converted to the expression's type as if by [`f32::from_str`](https://doc.rust-lang.org/core/primitive.f32.html#method.from_str) or [`f64::from_str`](https://doc.rust-lang.org/core/primitive.f64.html#method.from_str).

 
>  **Note**: `-1.0`, for example, is an application of the [negation operator](operator-expr#negation-operators) to the literal expression `1.0`, not a single floating-point literal expression.
> 
>  

 
>  **Note**: `inf` and `NaN` are not literal tokens. The [`f32::INFINITY`](https://doc.rust-lang.org/core/primitive.f32.html#associatedconstant.INFINITY), [`f64::INFINITY`](https://doc.rust-lang.org/core/primitive.f64.html#associatedconstant.INFINITY), [`f32::NAN`](https://doc.rust-lang.org/core/primitive.f32.html#associatedconstant.NAN), and [`f64::NAN`](https://doc.rust-lang.org/core/primitive.f64.html#associatedconstant.NAN) constants can be used instead of literal expressions. In `rustc`, a literal large enough to be evaluated as infinite will trigger the `overflowing_literals` lint check.
> 
>  

 Boolean literal expressions
---------------------------

 A boolean literal expression consists of one of the keywords `true` or `false`.

 The expression's type is the primitive [boolean type](../types/boolean), and its value is:

 * true if the keyword is `true`
* false if the keyword is `false`



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/expressions/literal-expr.html>

Path expressions
================

 
>  **Syntax**  
>  *PathExpression* :  
>  [*PathInExpression*](../paths#paths-in-expressions)  
>  | [*QualifiedPathInExpression*](../paths#qualified-paths)
> 
>  

 A [path](../paths) used as an expression context denotes either a local variable or an item. Path expressions that resolve to local or static variables are [place expressions](../expressions#place-expressions-and-value-expressions), other paths are [value expressions](../expressions#place-expressions-and-value-expressions). Using a [`static mut`](../items/static-items#mutable-statics) variable requires an [`unsafe` block](block-expr#unsafe-blocks).

 
```
#![allow(unused)]
fn main() {
mod globals {
    pub static STATIC_VAR: i32 = 5;
    pub static mut STATIC_MUT_VAR: i32 = 7;
}
let local_var = 3;
local_var;
globals::STATIC_VAR;
unsafe { globals::STATIC_MUT_VAR };
let some_constructor = Some::<i32>;
let push_integer = Vec::<i32>::push;
let slice_reverse = <[i32]>::reverse;
}
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/expressions/path-expr.html>

Block expressions
=================

 
>  **Syntax**  
>  *BlockExpression* :  
>  `{`  
>  [*InnerAttribute*](../attributes)\*  
>  *Statements*?  
>  `}`
> 
>  *Statements* :  
>  [*Statement*](../statements)+  
>  | [*Statement*](../statements)+ [*ExpressionWithoutBlock*](../expressions)  
>  | [*ExpressionWithoutBlock*](../expressions)
> 
>  

 A *block expression*, or *block*, is a control flow expression and anonymous namespace scope for items and variable declarations. As a control flow expression, a block sequentially executes its component non-item declaration statements and then its final optional expression. As an anonymous namespace scope, item declarations are only in scope inside the block itself and variables declared by `let` statements are in scope from the next statement until the end of the block.

 The syntax for a block is `{`, then any [inner attributes](../attributes), then any number of [statements](../statements), then an optional expression, called the final operand, and finally a `}`.

 Statements are usually required to be followed by a semicolon, with two exceptions:

 1. Item declaration statements do not need to be followed by a semicolon.
2. Expression statements usually require a following semicolon except if its outer expression is a flow control expression.

 Furthermore, extra semicolons between statements are allowed, but these semicolons do not affect semantics.

 When evaluating a block expression, each statement, except for item declaration statements, is executed sequentially. Then the final operand is executed, if given.

 The type of a block is the type of the final operand, or `()` if the final operand is omitted.

 
```
#![allow(unused)]
fn main() {
fn fn_call() {}
let _: () = {
    fn_call();
};

let five: i32 = {
    fn_call();
    5
};

assert_eq!(5, five);
}
```
 
>  Note: As a control flow expression, if a block expression is the outer expression of an expression statement, the expected type is `()` unless it is followed immediately by a semicolon.
> 
>  

 Blocks are always [value expressions](../expressions#place-expressions-and-value-expressions) and evaluate the last operand in value expression context.

 
>  **Note**: This can be used to force moving a value if really needed. For example, the following example fails on the call to `consume_self` because the struct was moved out of `s` in the block expression.
> 
>  
> ```
> #![allow(unused)]
> fn main() {
> struct Struct;
> 
> impl Struct {
>     fn consume_self(self) {}
>     fn borrow_self(&self) {}
> }
> 
> fn move_by_block_expression() {
>     let s = Struct;
> 
>     // Move the value out of `s` in the block expression.
>     (&{ s }).borrow_self();
> 
>     // Fails to execute because `s` is moved out of.
>     s.consume_self();
> }
> }
> ```
>  

 
`async` blocks
---------------

 
>  **Syntax**  
>  *AsyncBlockExpression* :  
>  `async` `move`? *BlockExpression*
> 
>  

 An *async block* is a variant of a block expression which evaluates to a future. The final expression of the block, if present, determines the result value of the future.

 Executing an async block is similar to executing a closure expression: its immediate effect is to produce and return an anonymous type. Whereas closures return a type that implements one or more of the [`std::ops::Fn`](../../std/ops/trait.fn) traits, however, the type returned for an async block implements the [`std::future::Future`](../../std/future/trait.future) trait. The actual data format for this type is unspecified.

 
>  **Note:** The future type that rustc generates is roughly equivalent to an enum with one variant per `await` point, where each variant stores the data needed to resume from its corresponding point.
> 
>  

 
>  **Edition differences**: Async blocks are only available beginning with Rust 2018.
> 
>  

 ### Capture modes

 Async blocks capture variables from their environment using the same [capture modes](../types/closure#capture-modes) as closures. Like closures, when written `async { .. }` the capture mode for each variable will be inferred from the content of the block. `async move { .. }` blocks however will move all referenced variables into the resulting future.

 ### Async context

 Because async blocks construct a future, they define an **async context** which can in turn contain [`await` expressions](await-expr). Async contexts are established by async blocks as well as the bodies of async functions, whose semantics are defined in terms of async blocks.

 ### Control-flow operators

 Async blocks act like a function boundary, much like closures. Therefore, the `?` operator and `return` expressions both affect the output of the future, not the enclosing function or other context. That is, `return <expr>` from within an async block will return the result of `<expr>` as the output of the future. Similarly, if `<expr>?` propagates an error, that error is propagated as the result of the future.

 Finally, the `break` and `continue` keywords cannot be used to branch out from an async block. Therefore the following is illegal:

 
```
#![allow(unused)]
fn main() {
loop {
    async move {
        break; // error[E0267]: `break` inside of an `async` block
    }
}
}
```
 
`unsafe` blocks
----------------

 
>  **Syntax**  
>  *UnsafeBlockExpression* :  
>  `unsafe` *BlockExpression*
> 
>  

 *See [`unsafe` block](../unsafe-blocks) for more information on when to use `unsafe`*

 A block of code can be prefixed with the `unsafe` keyword to permit [unsafe operations](../unsafety). Examples:

 
```
#![allow(unused)]
fn main() {
unsafe {
    let b = [13u8, 17u8];
    let a = &b[0] as *const u8;
    assert_eq!(*a, 13);
    assert_eq!(*a.offset(1), 17);
}

unsafe fn an_unsafe_fn() -> i32 { 10 }
let a = unsafe { an_unsafe_fn() };
}
```
 Labelled block expressions
--------------------------

 Labelled block expressions are documented in the [Loops and other breakable expressions](loop-expr#labelled-block-expressions) section.

 Attributes on block expressions
-------------------------------

 [Inner attributes](../attributes) are allowed directly after the opening brace of a block expression in the following situations:

 * [Function](../items/functions) and [method](../items/associated-items#methods) bodies.
* Loop bodies ([`loop`](loop-expr#infinite-loops), [`while`](loop-expr#predicate-loops), [`while let`](loop-expr#predicate-pattern-loops), and [`for`](loop-expr#iterator-loops)).
* Block expressions used as a [statement](../statements).
* Block expressions as elements of [array expressions](array-expr), [tuple expressions](tuple-expr), [call expressions](call-expr), and tuple-style [struct](struct-expr) expressions.
* A block expression as the tail expression of another block expression.

 The attributes that have meaning on a block expression are [`cfg`](../conditional-compilation) and [the lint check attributes](../attributes/diagnostics#lint-check-attributes).

 For example, this function returns `true` on unix platforms and `false` on other platforms.

 
```
#![allow(unused)]
fn main() {
fn is_unix_platform() -> bool {
    #[cfg(unix)] { true }
    #[cfg(not(unix))] { false }
}
}
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/expressions/block-expr.html>

Grouped expressions
===================

 
>  **Syntax**  
>  *GroupedExpression* :  
>  `(` [*Expression*](../expressions) `)`
> 
>  

 A *parenthesized expression* wraps a single expression, evaluating to that expression. The syntax for a parenthesized expression is a `(`, then an expression, called the *enclosed operand*, and then a `)`.

 Parenthesized expressions evaluate to the value of the enclosed operand. Unlike other expressions, parenthesized expressions are both [place expressions and value expressions](../expressions#place-expressions-and-value-expressions). When the enclosed operand is a place expression, it is a place expression and when the enclosed operand is a value expression, it is a value expression.

 Parentheses can be used to explicitly modify the precedence order of subexpressions within an expression.

 An example of a parenthesized expression:

 
```
#![allow(unused)]
fn main() {
let x: i32 = 2 + 3 * 4; // not parenthesized
let y: i32 = (2 + 3) * 4; // parenthesized
assert_eq!(x, 14);
assert_eq!(y, 20);
}
```
 An example of a necessary use of parentheses is when calling a function pointer that is a member of a struct:

 
```
#![allow(unused)]
fn main() {
struct A {
   f: fn() -> &'static str
}
impl A {
   fn f(&self) -> &'static str {
       "The method f"
   }
}
let a = A{f: || "The field f"};

assert_eq!( a.f (), "The method f");
assert_eq!((a.f)(), "The field f");
}
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/expressions/grouped-expr.html>

Array and array index expressions
=================================

 Array expressions
-----------------

 
>  **Syntax**  
>  *ArrayExpression* :  
>  `[` *ArrayElements*? `]`
> 
>  *ArrayElements* :  
>  [*Expression*](../expressions) ( `,` [*Expression*](../expressions) )\* `,`?  
>  | [*Expression*](../expressions) `;` [*Expression*](../expressions)
> 
>  

 *Array expressions* construct [arrays](../types/array). Array expressions come in two forms.

 The first form lists out every value in the array. The syntax for this form is a comma-separated list of expressions of uniform type enclosed in square brackets. This produces an array containing each of these values in the order they are written.

 The syntax for the second form is two expressions separated by a semicolon (`;`) enclosed in square brackets. The expression before the `;` is called the *repeat operand*. The expression after the `;` is called the *length operand*. It must have type `usize` and be a [constant expression](../const_eval#constant-expressions), such as a [literal](../tokens#literals) or a [constant item](../items/constant-items). An array expression of this form creates an array with the length of the value of the length operand with each element being a copy of the repeat operand. That is, `[a; b]` creates an array containing `b` copies of the value of `a`. If the length operand has a value greater than 1 then this requires that the type of the repeat operand is [`Copy`](../special-types-and-traits#copy) or that it must be a [path](path-expr) to a constant item.

 When the repeat operand is a constant item, it is evaluated the length operand's value times. If that value is `0`, then the constant item is not evaluated at all. For expressions that are not a constant item, it is evaluated exactly once, and then the result is copied the length operand's value times.

 
```
#![allow(unused)]
fn main() {
[1, 2, 3, 4];
["a", "b", "c", "d"];
[0; 128];              // array with 128 zeros
[0u8, 0u8, 0u8, 0u8,];
[[1, 0, 0], [0, 1, 0], [0, 0, 1]]; // 2D array
const EMPTY: Vec<i32> = Vec::new();
[EMPTY; 2];
}
```
 Array and slice indexing expressions
------------------------------------

 
>  **Syntax**  
>  *IndexExpression* :  
>  [*Expression*](../expressions) `[` [*Expression*](../expressions) `]`
> 
>  

 [Array](../types/array) and [slice](../types/slice)-typed values can be indexed by writing a square-bracket-enclosed expression of type `usize` (the index) after them. When the array is mutable, the resulting [memory location](../expressions#place-expressions-and-value-expressions) can be assigned to.

 For other types an index expression `a[b]` is equivalent to `*std::ops::Index::index(&a, b)`, or `*std::ops::IndexMut::index_mut(&mut a, b)` in a mutable place expression context. Just as with methods, Rust will also insert dereference operations on `a` repeatedly to find an implementation.

 Indices are zero-based for arrays and slices. Array access is a [constant expression](../const_eval#constant-expressions), so bounds can be checked at compile-time with a constant index value. Otherwise a check will be performed at run-time that will put the thread in a *panicked state* if it fails.

 
```
#![allow(unused)]
fn main() {
// lint is deny by default.
#![warn(unconditional_panic)]

([1, 2, 3, 4])[2];        // Evaluates to 3

let b = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];
b[1][2];                  // multidimensional array indexing

let x = (["a", "b"])[10]; // warning: index out of bounds

let n = 10;
let y = (["a", "b"])[n];  // panics

let arr = ["a", "b"];
arr[10];                  // warning: index out of bounds
}
```
 The array index expression can be implemented for types other than arrays and slices by implementing the [Index](../../std/ops/trait.index) and [IndexMut](../../std/ops/trait.indexmut) traits.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/expressions/array-expr.html>

Tuple and tuple indexing expressions
====================================

 Tuple expressions
-----------------

 
>  **Syntax**  
>  *TupleExpression* :  
>  `(` *TupleElements*? `)`
> 
>  *TupleElements* :  
>  ( [*Expression*](../expressions) `,` )+ [*Expression*](../expressions)?
> 
>  

 A *tuple expression* constructs [tuple values](../types/tuple).

 The syntax for tuple expressions is a parenthesized, comma separated list of expressions, called the *tuple initializer operands*. 1-ary tuple expressions require a comma after their tuple initializer operand to be disambiguated with a [parenthetical expression](grouped-expr).

 Tuple expressions are a [value expression](../expressions#place-expressions-and-value-expressions) that evaluate into a newly constructed value of a tuple type. The number of tuple initializer operands is the arity of the constructed tuple. Tuple expressions without any tuple initializer operands produce the unit tuple. For other tuple expressions, the first written tuple initializer operand initializes the field `0` and subsequent operands initializes the next highest field. For example, in the tuple expression `('a', 'b', 'c')`, `'a'` initializes the value of the field `0`, `'b'` field `1`, and `'c'` field `2`.

 Examples of tuple expressions and their types:

 


| Expression | Type |
| --- | --- |
| `()` | `()` (unit) |
| `(0.0, 4.5)` | `(f64, f64)` |
| `("x".to_string(), )` | `(String, )` |
| `("a", 4usize, true)` | `(&'static str, usize, bool)` |

  Tuple indexing expressions
--------------------------

 
>  **Syntax**  
>  *TupleIndexingExpression* :  
>  [*Expression*](../expressions) `.` [TUPLE\_INDEX](../tokens#tuple-index)
> 
>  

 A *tuple indexing expression* accesses fields of [tuples](../types/tuple) and [tuple structs](../types/struct).

 The syntax for a tuple index expression is an expression, called the *tuple operand*, then a `.`, then finally a tuple index. The syntax for the *tuple index* is a [decimal literal](../tokens#integer-literals) with no leading zeros, underscores, or suffix. For example `0` and `2` are valid tuple indices but not `01`, `0_`, nor `0i32`.

 The type of the tuple operand must be a [tuple type](../types/tuple) or a [tuple struct](../types/struct). The tuple index must be a name of a field of the type of the tuple operand.

 Evaluation of tuple index expressions has no side effects beyond evaluation of its tuple operand. As a [place expression](../expressions#place-expressions-and-value-expressions), it evaluates to the location of the field of the tuple operand with the same name as the tuple index.

 Examples of tuple indexing expressions:

 
```
#![allow(unused)]
fn main() {
// Indexing a tuple
let pair = ("a string", 2);
assert_eq!(pair.1, 2);

// Indexing a tuple struct
struct Point(f32, f32);
let point = Point(1.0, 0.0);
assert_eq!(point.0, 1.0);
assert_eq!(point.1, 0.0);
}
```
 
>  **Note**: Unlike field access expressions, tuple index expressions can be the function operand of a [call expression](call-expr) as it cannot be confused with a method call since method names cannot be numbers.
> 
>  

 
>  **Note**: Although arrays and slices also have elements, you must use an [array or slice indexing expression](array-expr#array-and-slice-indexing-expressions) or a [slice pattern](../patterns#slice-patterns) to access their elements.
> 
>  



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/expressions/tuple-expr.html>

Struct expressions
==================

 
>  **Syntax**  
>  *StructExpression* :  
>  *StructExprStruct*  
>  | *StructExprTuple*  
>  | *StructExprUnit*
> 
>  *StructExprStruct* :  
>  [*PathInExpression*](../paths#paths-in-expressions) `{` (*StructExprFields* | *StructBase*)? `}`
> 
>  *StructExprFields* :  
>  *StructExprField* (`,` *StructExprField*)\* (`,` *StructBase* | `,`?)
> 
>  *StructExprField* :  
>  [*OuterAttribute*](../attributes) \*  
>  (  
>  [IDENTIFIER](../identifiers)  
>  | ([IDENTIFIER](../identifiers) | [TUPLE\_INDEX](../tokens#tuple-index)) `:` [*Expression*](../expressions)  
>  )
> 
>  *StructBase* :  
>  `..` [*Expression*](../expressions)
> 
>  *StructExprTuple* :  
>  [*PathInExpression*](../paths#paths-in-expressions) `(`  
>  ( [*Expression*](../expressions) (`,` [*Expression*](../expressions))\* `,`? )?  
>  `)`
> 
>  *StructExprUnit* : [*PathInExpression*](../paths#paths-in-expressions)
> 
>  

 A *struct expression* creates a struct, enum, or union value. It consists of a path to a [struct](../items/structs), [enum variant](../items/enumerations), or [union](../items/unions) item followed by the values for the fields of the item. There are three forms of struct expressions: struct, tuple, and unit.

 The following are examples of struct expressions:

 
```
#![allow(unused)]
fn main() {
struct Point { x: f64, y: f64 }
struct NothingInMe { }
struct TuplePoint(f64, f64);
mod game { pub struct User<'a> { pub name: &'a str, pub age: u32, pub score: usize } }
struct Cookie; fn some_fn<T>(t: T) {}
Point {x: 10.0, y: 20.0};
NothingInMe {};
TuplePoint(10.0, 20.0);
TuplePoint { 0: 10.0, 1: 20.0 }; // Results in the same value as the above line
let u = game::User {name: "Joe", age: 35, score: 100_000};
some_fn::<Cookie>(Cookie);
}
```
 Field struct expression
-----------------------

 A struct expression with fields enclosed in curly braces allows you to specify the value for each individual field in any order. The field name is separated from its value with a colon.

 A value of a [union](../items/unions) type can only be created using this syntax, and it must specify exactly one field.

 Functional update syntax
------------------------

 A struct expression that constructs a value of a struct type can terminate with the syntax `..` followed by an expression to denote a functional update. The expression following `..` (the base) must have the same struct type as the new struct type being formed.

 The entire expression uses the given values for the fields that were specified and moves or copies the remaining fields from the base expression. As with all struct expressions, all of the fields of the struct must be [visible](../visibility-and-privacy), even those not explicitly named.

 
```
#![allow(unused)]
fn main() {
struct Point3d { x: i32, y: i32, z: i32 }
let mut base = Point3d {x: 1, y: 2, z: 3};
let y_ref = &mut base.y;
Point3d {y: 0, z: 10, .. base}; // OK, only base.x is accessed
drop(y_ref);
}
```
 Struct expressions with curly braces can't be used directly in a [loop](loop-expr) or [if](if-expr#if-expressions) expression's head, or in the [scrutinee](../glossary#scrutinee) of an [if let](if-expr#if-let-expressions) or [match](match-expr) expression. However, struct expressions can be used in these situations if they are within another expression, for example inside [parentheses](grouped-expr).

 The field names can be decimal integer values to specify indices for constructing tuple structs. This can be used with base structs to fill out the remaining indices not specified:

 
```
#![allow(unused)]
fn main() {
struct Color(u8, u8, u8);
let c1 = Color(0, 0, 0);  // Typical way of creating a tuple struct.
let c2 = Color{0: 255, 1: 127, 2: 0};  // Specifying fields by index.
let c3 = Color{1: 0, ..c2};  // Fill out all other fields using a base struct.
}
```
 ### Struct field init shorthand

 When initializing a data structure (struct, enum, union) with named (but not numbered) fields, it is allowed to write `fieldname` as a shorthand for `fieldname: fieldname`. This allows a compact syntax with less duplication. For example:

 
```
#![allow(unused)]
fn main() {
struct Point3d { x: i32, y: i32, z: i32 }
let x = 0;
let y_value = 0;
let z = 0;
Point3d { x: x, y: y_value, z: z };
Point3d { x, y: y_value, z };
}
```
 Tuple struct expression
-----------------------

 A struct expression with fields enclosed in parentheses constructs a tuple struct. Though it is listed here as a specific expression for completeness, it is equivalent to a [call expression](call-expr) to the tuple struct's constructor. For example:

 
```
#![allow(unused)]
fn main() {
struct Position(i32, i32, i32);
Position(0, 0, 0);  // Typical way of creating a tuple struct.
let c = Position;  // `c` is a function that takes 3 arguments.
let pos = c(8, 6, 7);  // Creates a `Position` value.
}
```
 Unit struct expression
----------------------

 A unit struct expression is just the path to a unit struct item. This refers to the unit struct's implicit constant of its value. The unit struct value can also be constructed with a fieldless struct expression. For example:

 
```
#![allow(unused)]
fn main() {
struct Gamma;
let a = Gamma;  // Gamma unit value.
let b = Gamma{};  // Exact same value as `a`.
}
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/expressions/struct-expr.html>

Operator expressions
====================

 
>  **Syntax**  
>  *OperatorExpression* :  
>  [*BorrowExpression*](#borrow-operators)  
>  | [*DereferenceExpression*](#the-dereference-operator)  
>  | [*ErrorPropagationExpression*](#the-question-mark-operator)  
>  | [*NegationExpression*](#negation-operators)  
>  | [*ArithmeticOrLogicalExpression*](#arithmetic-and-logical-binary-operators)  
>  | [*ComparisonExpression*](#comparison-operators)  
>  | [*LazyBooleanExpression*](#lazy-boolean-operators)  
>  | [*TypeCastExpression*](#type-cast-expressions)  
>  | [*AssignmentExpression*](#assignment-expressions)  
>  | [*CompoundAssignmentExpression*](#compound-assignment-expressions)
> 
>  

 Operators are defined for built in types by the Rust language. Many of the following operators can also be overloaded using traits in `std::ops` or `std::cmp`.

 Overflow
--------

 Integer operators will panic when they overflow when compiled in debug mode. The `-C debug-assertions` and `-C overflow-checks` compiler flags can be used to control this more directly. The following things are considered to be overflow:

 * When `+`, `*` or binary `-` create a value greater than the maximum value, or less than the minimum value that can be stored.
* Applying unary `-` to the most negative value of any signed integer type, unless the operand is a [literal expression](literal-expr#integer-literal-expressions) (or a literal expression standing alone inside one or more [grouped expressions](grouped-expr)).
* Using `/` or `%`, where the left-hand argument is the smallest integer of a signed integer type and the right-hand argument is `-1`. These checks occur even when `-C overflow-checks` is disabled, for legacy reasons.
* Using `<<` or `>>` where the right-hand argument is greater than or equal to the number of bits in the type of the left-hand argument, or is negative.

 
>  **Note**: The exception for literal expressions behind unary `-` means that forms such as `-128_i8` or `let j: i8 = -(128)` never cause a panic and have the expected value of -128.
> 
>  In these cases, the literal expression already has the most negative value for its type (for example, `128_i8` has the value -128) because integer literals are truncated to their type per the description in [Integer literal expressions](literal-expr#integer-literal-expressions).
> 
>  Negation of these most negative values leaves the value unchanged due to two's complement overflow conventions.
> 
>  In `rustc`, these most negative expressions are also ignored by the `overflowing_literals` lint check.
> 
>  

 Borrow operators
----------------

 
>  **Syntax**  
>  *BorrowExpression* :  
>  (`&`|`&&`) [*Expression*](../expressions)  
>  | (`&`|`&&`) `mut` [*Expression*](../expressions)
> 
>  

 The `&` (shared borrow) and `&mut` (mutable borrow) operators are unary prefix operators. When applied to a [place expression](../expressions#place-expressions-and-value-expressions), this expressions produces a reference (pointer) to the location that the value refers to. The memory location is also placed into a borrowed state for the duration of the reference. For a shared borrow (`&`), this implies that the place may not be mutated, but it may be read or shared again. For a mutable borrow (`&mut`), the place may not be accessed in any way until the borrow expires. `&mut` evaluates its operand in a mutable place expression context. If the `&` or `&mut` operators are applied to a [value expression](../expressions#place-expressions-and-value-expressions), then a [temporary value](../expressions#temporaries) is created.

 These operators cannot be overloaded.

 
```
#![allow(unused)]
fn main() {
{
    // a temporary with value 7 is created that lasts for this scope.
    let shared_reference = &7;
}
let mut array = [-2, 3, 9];
{
    // Mutably borrows `array` for this scope.
    // `array` may only be used through `mutable_reference`.
    let mutable_reference = &mut array;
}
}
```
 Even though `&&` is a single token ([the lazy 'and' operator](#lazy-boolean-operators)), when used in the context of borrow expressions it works as two borrows:

 
```
#![allow(unused)]
fn main() {
// same meanings:
let a = &&  10;
let a = & & 10;

// same meanings:
let a = &&&&  mut 10;
let a = && && mut 10;
let a = & & & & mut 10;
}
```
 ### Raw address-of operators

 Related to the borrow operators are the *raw address-of operators*, which do not have first-class syntax, but are exposed via the macros [`ptr::addr_of!(expr)`](../../std/ptr/macro.addr_of) and [`ptr::addr_of_mut!(expr)`](../../std/ptr/macro.addr_of_mut). The expression `expr` is evaluated in place expression context. `ptr::addr_of!(expr)` then creates a const raw pointer of type `*const T` to the given place, and `ptr::addr_of_mut!(expr)` creates a mutable raw pointer of type `*mut T`.

 The raw address-of operators must be used instead of a borrow operator whenever the place expression could evaluate to a place that is not properly aligned or does not store a valid value as determined by its type, or whenever creating a reference would introduce incorrect aliasing assumptions. In those situations, using a borrow operator would cause [undefined behavior](../behavior-considered-undefined) by creating an invalid reference, but a raw pointer may still be constructed using an address-of operator.

 The following is an example of creating a raw pointer to an unaligned place through a `packed` struct:

 
```
#![allow(unused)]
fn main() {
use std::ptr;

#[repr(packed)]
struct Packed {
    f1: u8,
    f2: u16,
}

let packed = Packed { f1: 1, f2: 2 };
// `&packed.f2` would create an unaligned reference, and thus be Undefined Behavior!
let raw_f2 = ptr::addr_of!(packed.f2);
assert_eq!(unsafe { raw_f2.read_unaligned() }, 2);
}
```
 The following is an example of creating a raw pointer to a place that does not contain a valid value:

 
```
#![allow(unused)]
fn main() {
use std::{ptr, mem::MaybeUninit};

struct Demo {
    field: bool,
}

let mut uninit = MaybeUninit::<Demo>::uninit();
// `&uninit.as_mut().field` would create a reference to an uninitialized `bool`,
// and thus be Undefined Behavior!
let f1_ptr = unsafe { ptr::addr_of_mut!((*uninit.as_mut_ptr()).field) };
unsafe { f1_ptr.write(true); }
let init = unsafe { uninit.assume_init() };
}
```
 The dereference operator
------------------------

 
>  **Syntax**  
>  *DereferenceExpression* :  
>  `*` [*Expression*](../expressions)
> 
>  

 The `*` (dereference) operator is also a unary prefix operator. When applied to a [pointer](../types/pointer) it denotes the pointed-to location. If the expression is of type `&mut T` or `*mut T`, and is either a local variable, a (nested) field of a local variable or is a mutable [place expression](../expressions#place-expressions-and-value-expressions), then the resulting memory location can be assigned to. Dereferencing a raw pointer requires `unsafe`.

 On non-pointer types `*x` is equivalent to `*std::ops::Deref::deref(&x)` in an [immutable place expression context](../expressions#mutability) and `*std::ops::DerefMut::deref_mut(&mut x)` in a mutable place expression context.

 
```
#![allow(unused)]
fn main() {
let x = &7;
assert_eq!(*x, 7);
let y = &mut 9;
*y = 11;
assert_eq!(*y, 11);
}
```
 The question mark operator
--------------------------

 
>  **Syntax**  
>  *ErrorPropagationExpression* :  
>  [*Expression*](../expressions) `?`
> 
>  

 The question mark operator (`?`) unwraps valid values or returns erroneous values, propagating them to the calling function. It is a unary postfix operator that can only be applied to the types `Result<T, E>` and `Option<T>`.

 When applied to values of the `Result<T, E>` type, it propagates errors. If the value is `Err(e)`, then it will return `Err(From::from(e))` from the enclosing function or closure. If applied to `Ok(x)`, then it will unwrap the value to evaluate to `x`.

 
```
#![allow(unused)]
fn main() {
use std::num::ParseIntError;
fn try_to_parse() -> Result<i32, ParseIntError> {
    let x: i32 = "123".parse()?; // x = 123
    let y: i32 = "24a".parse()?; // returns an Err() immediately
    Ok(x + y)                    // Doesn't run.
}

let res = try_to_parse();
println!("{:?}", res);
assert!(res.is_err())
}
```
 When applied to values of the `Option<T>` type, it propagates `None`s. If the value is `None`, then it will return `None`. If applied to `Some(x)`, then it will unwrap the value to evaluate to `x`.

 
```
#![allow(unused)]
fn main() {
fn try_option_some() -> Option<u8> {
    let val = Some(1)?;
    Some(val)
}
assert_eq!(try_option_some(), Some(1));

fn try_option_none() -> Option<u8> {
    let val = None?;
    Some(val)
}
assert_eq!(try_option_none(), None);
}
```
 `?` cannot be overloaded.

 Negation operators
------------------

 
>  **Syntax**  
>  *NegationExpression* :  
>  `-` [*Expression*](../expressions)  
>  | `!` [*Expression*](../expressions)
> 
>  

 These are the last two unary operators. This table summarizes the behavior of them on primitive types and which traits are used to overload these operators for other types. Remember that signed integers are always represented using two's complement. The operands of all of these operators are evaluated in [value expression context](../expressions#place-expressions-and-value-expressions) so are moved or copied.

 


| Symbol | Integer | `bool` | Floating Point | Overloading Trait |
| --- | --- | --- | --- | --- |
| `-` | Negation\* |  | Negation | `std::ops::Neg` |
| `!` | Bitwise NOT | [Logical NOT](../types/boolean#logical-not) |  | `std::ops::Not` |

  \* Only for signed integer types.

 Here are some example of these operators

 
```
#![allow(unused)]
fn main() {
let x = 6;
assert_eq!(-x, -6);
assert_eq!(!x, -7);
assert_eq!(true, !false);
}
```
 Arithmetic and Logical Binary Operators
---------------------------------------

 
>  **Syntax**  
>  *ArithmeticOrLogicalExpression* :  
>  [*Expression*](../expressions) `+` [*Expression*](../expressions)  
>  | [*Expression*](../expressions) `-` [*Expression*](../expressions)  
>  | [*Expression*](../expressions) `*` [*Expression*](../expressions)  
>  | [*Expression*](../expressions) `/` [*Expression*](../expressions)  
>  | [*Expression*](../expressions) `%` [*Expression*](../expressions)  
>  | [*Expression*](../expressions) `&` [*Expression*](../expressions)  
>  | [*Expression*](../expressions) `|` [*Expression*](../expressions)  
>  | [*Expression*](../expressions) `^` [*Expression*](../expressions)  
>  | [*Expression*](../expressions) `<<` [*Expression*](../expressions)  
>  | [*Expression*](../expressions) `>>` [*Expression*](../expressions)
> 
>  

 Binary operators expressions are all written with infix notation. This table summarizes the behavior of arithmetic and logical binary operators on primitive types and which traits are used to overload these operators for other types. Remember that signed integers are always represented using two's complement. The operands of all of these operators are evaluated in [value expression context](../expressions#place-expressions-and-value-expressions) so are moved or copied.

 


| Symbol | Integer | `bool` | Floating Point | Overloading Trait | Overloading Compound Assignment Trait |
| --- | --- | --- | --- | --- | --- |
| `+` | Addition |  | Addition | `std::ops::Add` | `std::ops::AddAssign` |
| `-` | Subtraction |  | Subtraction | `std::ops::Sub` | `std::ops::SubAssign` |
| `*` | Multiplication |  | Multiplication | `std::ops::Mul` | `std::ops::MulAssign` |
| `/` | Division\* |  | Division | `std::ops::Div` | `std::ops::DivAssign` |
| `%` | Remainder\*\* |  | Remainder | `std::ops::Rem` | `std::ops::RemAssign` |
| `&` | Bitwise AND | [Logical AND](../types/boolean#logical-and) |  | `std::ops::BitAnd` | `std::ops::BitAndAssign` |
| `|` | Bitwise OR | [Logical OR](../types/boolean#logical-or) |  | `std::ops::BitOr` | `std::ops::BitOrAssign` |
| `^` | Bitwise XOR | [Logical XOR](../types/boolean#logical-xor) |  | `std::ops::BitXor` | `std::ops::BitXorAssign` |
| `<<` | Left Shift |  |  | `std::ops::Shl` | `std::ops::ShlAssign` |
| `>>` | Right Shift\*\*\* |  |  | `std::ops::Shr` | `std::ops::ShrAssign` |

  \* Integer division rounds towards zero.

 \*\* Rust uses a remainder defined with [truncating division](https://en.wikipedia.org/wiki/Modulo_operation#Variants_of_the_definition). Given `remainder = dividend % divisor`, the remainder will have the same sign as the dividend.

 \*\*\* Arithmetic right shift on signed integer types, logical right shift on unsigned integer types.

 Here are examples of these operators being used.

 
```
#![allow(unused)]
fn main() {
assert_eq!(3 + 6, 9);
assert_eq!(5.5 - 1.25, 4.25);
assert_eq!(-5 * 14, -70);
assert_eq!(14 / 3, 4);
assert_eq!(100 % 7, 2);
assert_eq!(0b1010 & 0b1100, 0b1000);
assert_eq!(0b1010 | 0b1100, 0b1110);
assert_eq!(0b1010 ^ 0b1100, 0b110);
assert_eq!(13 << 3, 104);
assert_eq!(-10 >> 2, -3);
}
```
 Comparison Operators
--------------------

 
>  **Syntax**  
>  *ComparisonExpression* :  
>  [*Expression*](../expressions) `==` [*Expression*](../expressions)  
>  | [*Expression*](../expressions) `!=` [*Expression*](../expressions)  
>  | [*Expression*](../expressions) `>` [*Expression*](../expressions)  
>  | [*Expression*](../expressions) `<` [*Expression*](../expressions)  
>  | [*Expression*](../expressions) `>=` [*Expression*](../expressions)  
>  | [*Expression*](../expressions) `<=` [*Expression*](../expressions)
> 
>  

 Comparison operators are also defined both for primitive types and many types in the standard library. Parentheses are required when chaining comparison operators. For example, the expression `a == b == c` is invalid and may be written as `(a == b) == c`.

 Unlike arithmetic and logical operators, the traits for overloading these operators are used more generally to show how a type may be compared and will likely be assumed to define actual comparisons by functions that use these traits as bounds. Many functions and macros in the standard library can then use that assumption (although not to ensure safety). Unlike the arithmetic and logical operators above, these operators implicitly take shared borrows of their operands, evaluating them in [place expression context](../expressions#place-expressions-and-value-expressions):

 
```
#![allow(unused)]
fn main() {
let a = 1;
let b = 1;
a == b;
// is equivalent to
::std::cmp::PartialEq::eq(&a, &b);
}
```
 This means that the operands don't have to be moved out of.

 


| Symbol | Meaning | Overloading method |
| --- | --- | --- |
| `==` | Equal | `std::cmp::PartialEq::eq` |
| `!=` | Not equal | `std::cmp::PartialEq::ne` |
| `>` | Greater than | `std::cmp::PartialOrd::gt` |
| `<` | Less than | `std::cmp::PartialOrd::lt` |
| `>=` | Greater than or equal to | `std::cmp::PartialOrd::ge` |
| `<=` | Less than or equal to | `std::cmp::PartialOrd::le` |

  Here are examples of the comparison operators being used.

 
```
#![allow(unused)]
fn main() {
assert!(123 == 123);
assert!(23 != -12);
assert!(12.5 > 12.2);
assert!([1, 2, 3] < [1, 3, 4]);
assert!('A' <= 'B');
assert!("World" >= "Hello");
}
```
 Lazy boolean operators
----------------------

 
>  **Syntax**  
>  *LazyBooleanExpression* :  
>  [*Expression*](../expressions) `||` [*Expression*](../expressions)  
>  | [*Expression*](../expressions) `&&` [*Expression*](../expressions)
> 
>  

 The operators `||` and `&&` may be applied to operands of boolean type. The `||` operator denotes logical 'or', and the `&&` operator denotes logical 'and'. They differ from `|` and `&` in that the right-hand operand is only evaluated when the left-hand operand does not already determine the result of the expression. That is, `||` only evaluates its right-hand operand when the left-hand operand evaluates to `false`, and `&&` only when it evaluates to `true`.

 
```
#![allow(unused)]
fn main() {
let x = false || true; // true
let y = false && panic!(); // false, doesn't evaluate `panic!()`
}
```
 Type cast expressions
---------------------

 
>  **Syntax**  
>  *TypeCastExpression* :  
>  [*Expression*](../expressions) `as` [*TypeNoBounds*](../types#type-expressions)
> 
>  

 A type cast expression is denoted with the binary operator `as`.

 Executing an `as` expression casts the value on the left-hand side to the type on the right-hand side.

 An example of an `as` expression:

 
```
#![allow(unused)]
fn main() {
fn sum(values: &[f64]) -> f64 { 0.0 }
fn len(values: &[f64]) -> i32 { 0 }
fn average(values: &[f64]) -> f64 {
    let sum: f64 = sum(values);
    let size: f64 = len(values) as f64;
    sum / size
}
}
```
 `as` can be used to explicitly perform [coercions](../type-coercions), as well as the following additional casts. Any cast that does not fit either a coercion rule or an entry in the table is a compiler error. Here `*T` means either `*const T` or `*mut T`. `m` stands for optional `mut` in reference types and `mut` or `const` in pointer types.

 


| Type of `e` | `U` | Cast performed by `e as U` |
| --- | --- | --- |
| Integer or Float type | Integer or Float type | Numeric cast |
| Enumeration | Integer type | Enum cast |
| `bool` or `char` | Integer type | Primitive to integer cast |
| `u8` | `char` | `u8` to `char` cast |
| `*T` | `*V` where `V: Sized` \* | Pointer to pointer cast |
| `*T` where `T: Sized` | Integer type | Pointer to address cast |
| Integer type | `*V` where `V: Sized` | Address to pointer cast |
| `&m₁ T` | `*m₂ T` \*\* | Reference to pointer cast |
| `&m₁ [T; n]` | `*m₂ T` \*\* | Array to pointer cast |
| [Function item](../types/function-item) | [Function pointer](../types/function-pointer) | Function item to function pointer cast |
| [Function item](../types/function-item) | `*V` where `V: Sized` | Function item to pointer cast |
| [Function item](../types/function-item) | Integer | Function item to address cast |
| [Function pointer](../types/function-pointer) | `*V` where `V: Sized` | Function pointer to pointer cast |
| [Function pointer](../types/function-pointer) | Integer | Function pointer to address cast |
| Closure \*\*\* | Function pointer | Closure to function pointer cast |

  \* or `T` and `V` are compatible unsized types, e.g., both slices, both the same trait object.

 \*\* only when `m₁` is `mut` or `m₂` is `const`. Casting `mut` reference to `const` pointer is allowed.

 \*\*\* only for closures that do not capture (close over) any local variables

 ### Semantics

 #### Numeric cast

 * Casting between two integers of the same size (e.g. i32 -> u32) is a no-op (Rust uses 2's complement for negative values of fixed integers)
* Casting from a larger integer to a smaller integer (e.g. u32 -> u8) will truncate
* Casting from a smaller integer to a larger integer (e.g. u8 -> u32) will
	+ zero-extend if the source is unsigned
	+ sign-extend if the source is signed
* Casting from a float to an integer will round the float towards zero
	+ `NaN` will return `0`
	+ Values larger than the maximum integer value, including `INFINITY`, will saturate to the maximum value of the integer type.
	+ Values smaller than the minimum integer value, including `NEG_INFINITY`, will saturate to the minimum value of the integer type.
* Casting from an integer to float will produce the closest possible float \*
	+ if necessary, rounding is according to `roundTiesToEven` mode \*\*\*
	+ on overflow, infinity (of the same sign as the input) is produced
	+ note: with the current set of numeric types, overflow can only happen on `u128 as f32` for values greater or equal to `f32::MAX + (0.5 ULP)`
* Casting from an f32 to an f64 is perfect and lossless
* Casting from an f64 to an f32 will produce the closest possible f32 \*\*
	+ if necessary, rounding is according to `roundTiesToEven` mode \*\*\*
	+ on overflow, infinity (of the same sign as the input) is produced

 \* if integer-to-float casts with this rounding mode and overflow behavior are not supported natively by the hardware, these casts will likely be slower than expected.

 \*\* if f64-to-f32 casts with this rounding mode and overflow behavior are not supported natively by the hardware, these casts will likely be slower than expected.

 \*\*\* as defined in IEEE 754-2008 §4.3.1: pick the nearest floating point number, preferring the one with an even least significant digit if exactly halfway between two floating point numbers.

 #### Enum cast

 Casts an enum to its discriminant, then uses a numeric cast if needed. Casting is limited to the following kinds of enumerations:

 * [Unit-only enums](../items/enumerations#unit-only-enum)
* [Field-less enums](../items/enumerations#field-less-enum) without [explicit discriminants](../items/enumerations#explicit-discriminants), or where only unit-variants have explicit discriminants

 #### Primitive to integer cast

 * `false` casts to `0`, `true` casts to `1`
* `char` casts to the value of the code point, then uses a numeric cast if needed.

 #### 
`u8` to `char` cast

 Casts to the `char` with the corresponding code point.

 #### Pointer to address cast

 Casting from a raw pointer to an integer produces the machine address of the referenced memory. If the integer type is smaller than the pointer type, the address may be truncated; using `usize` avoids this.

 #### Address to pointer cast

 Casting from an integer to a raw pointer interprets the integer as a memory address and produces a pointer referencing that memory.

  Warning: This interacts with the Rust memory model, which is still under development. A pointer obtained from this cast may suffer additional restrictions even if it is bitwise equal to a valid pointer. Dereferencing such a pointer may be [undefined behavior](../behavior-considered-undefined) if aliasing rules are not followed.

  A trivial example of sound address arithmetic:

 
```
#![allow(unused)]
fn main() {
let mut values: [i32; 2] = [1, 2];
let p1: *mut i32 = values.as_mut_ptr();
let first_address = p1 as usize;
let second_address = first_address + 4; // 4 == size_of::<i32>()
let p2 = second_address as *mut i32;
unsafe {
    *p2 += 1;
}
assert_eq!(values[1], 3);
}
```
 Assignment expressions
----------------------

 
>  **Syntax**  
>  *AssignmentExpression* :  
>  [*Expression*](../expressions) `=` [*Expression*](../expressions)
> 
>  

 An *assignment expression* moves a value into a specified place.

 An assignment expression consists of a [mutable](../expressions#mutability) [assignee expression](../expressions#place-expressions-and-value-expressions), the *assignee operand*, followed by an equals sign (`=`) and a [value expression](../expressions#place-expressions-and-value-expressions), the *assigned value operand*. In its most basic form, an assignee expression is a [place expression](../expressions#place-expressions-and-value-expressions), and we discuss this case first. The more general case of destructuring assignment is discussed below, but this case always decomposes into sequential assignments to place expressions, which may be considered the more fundamental case.

 ### Basic assignments

 Evaluating assignment expressions begins by evaluating its operands. The assigned value operand is evaluated first, followed by the assignee expression. For destructuring assignment, subexpressions of the assignee expression are evaluated left-to-right.

 
>  **Note**: This is different than other expressions in that the right operand is evaluated before the left one.
> 
>  

 It then has the effect of first [dropping](../destructors) the value at the assigned place, unless the place is an uninitialized local variable or an uninitialized field of a local variable. Next it either [copies or moves](../expressions#moved-and-copied-types) the assigned value to the assigned place.

 An assignment expression always produces [the unit value](../types/tuple).

 Example:

 
```
#![allow(unused)]
fn main() {
let mut x = 0;
let y = 0;
x = y;
}
```
 ### Destructuring assignments

 Destructuring assignment is a counterpart to destructuring pattern matches for variable declaration, permitting assignment to complex values, such as tuples or structs. For instance, we may swap two mutable variables:

 
```
#![allow(unused)]
fn main() {
let (mut a, mut b) = (0, 1);
// Swap `a` and `b` using destructuring assignment.
(b, a) = (a, b);
}
```
 In contrast to destructuring declarations using `let`, patterns may not appear on the left-hand side of an assignment due to syntactic ambiguities. Instead, a group of expressions that correspond to patterns are designated to be [assignee expressions](../expressions#place-expressions-and-value-expressions), and permitted on the left-hand side of an assignment. Assignee expressions are then desugared to pattern matches followed by sequential assignment. The desugared patterns must be irrefutable: in particular, this means that only slice patterns whose length is known at compile-time, and the trivial slice `[..]`, are permitted for destructuring assignment.

 The desugaring method is straightforward, and is illustrated best by example.

 
```
#![allow(unused)]
fn main() {
struct Struct { x: u32, y: u32 }
let (mut a, mut b) = (0, 0);
(a, b) = (3, 4);

[a, b] = [3, 4];

Struct { x: a, y: b } = Struct { x: 3, y: 4};

// desugars to:

{
    let (_a, _b) = (3, 4);
    a = _a;
    b = _b;
}

{
    let [_a, _b] = [3, 4];
    a = _a;
    b = _b;
}

{
    let Struct { x: _a, y: _b } = Struct { x: 3, y: 4};
    a = _a;
    b = _b;
}
}
```
 Identifiers are not forbidden from being used multiple times in a single assignee expression.

 [Underscore expressions](underscore-expr) and empty [range expressions](range-expr) may be used to ignore certain values, without binding them.

 Note that default binding modes do not apply for the desugared expression.

 Compound assignment expressions
-------------------------------

 
>  **Syntax**  
>  *CompoundAssignmentExpression* :  
>  [*Expression*](../expressions) `+=` [*Expression*](../expressions)  
>  | [*Expression*](../expressions) `-=` [*Expression*](../expressions)  
>  | [*Expression*](../expressions) `*=` [*Expression*](../expressions)  
>  | [*Expression*](../expressions) `/=` [*Expression*](../expressions)  
>  | [*Expression*](../expressions) `%=` [*Expression*](../expressions)  
>  | [*Expression*](../expressions) `&=` [*Expression*](../expressions)  
>  | [*Expression*](../expressions) `|=` [*Expression*](../expressions)  
>  | [*Expression*](../expressions) `^=` [*Expression*](../expressions)  
>  | [*Expression*](../expressions) `<<=` [*Expression*](../expressions)  
>  | [*Expression*](../expressions) `>>=` [*Expression*](../expressions)
> 
>  

 *Compound assignment expressions* combine arithmetic and logical binary operators with assignment expressions.

 For example:

 
```
#![allow(unused)]
fn main() {
let mut x = 5;
x += 1;
assert!(x == 6);
}
```
 The syntax of compound assignment is a [mutable](../expressions#mutability) [place expression](../expressions#place-expressions-and-value-expressions), the *assigned operand*, then one of the operators followed by an `=` as a single token (no whitespace), and then a [value expression](../expressions#place-expressions-and-value-expressions), the *modifying operand*.

 Unlike other place operands, the assigned place operand must be a place expression. Attempting to use a value expression is a compiler error rather than promoting it to a temporary.

 Evaluation of compound assignment expressions depends on the types of the operators.

 If both types are primitives, then the modifying operand will be evaluated first followed by the assigned operand. It will then set the value of the assigned operand's place to the value of performing the operation of the operator with the values of the assigned operand and modifying operand.

 
>  **Note**: This is different than other expressions in that the right operand is evaluated before the left one.
> 
>  

 Otherwise, this expression is syntactic sugar for calling the function of the overloading compound assignment trait of the operator (see the table earlier in this chapter). A mutable borrow of the assigned operand is automatically taken.

 For example, the following expression statements in `example` are equivalent:

 
```
#![allow(unused)]
fn main() {
struct Addable;
use std::ops::AddAssign;

impl AddAssign<Addable> for Addable {
    /* */
fn add_assign(&mut self, other: Addable) {}
}

fn example() {
let (mut a1, a2) = (Addable, Addable);
  a1 += a2;

let (mut a1, a2) = (Addable, Addable);
  AddAssign::add_assign(&mut a1, a2);
}
}
```
 Like assignment expressions, compound assignment expressions always produce [the unit value](../types/tuple).

  Warning: The evaluation order of operands swaps depending on the types of the operands: with primitive types the right-hand side will get evaluated first, while with non-primitive types the left-hand side will get evaluated first. Try not to write code that depends on the evaluation order of operands in compound assignment expressions. See [this test](https://github.com/rust-lang/rust/blob/1.58.0/src/test/ui/expr/compound-assignment/eval-order.rs) for an example of using this dependency.

 

 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/expressions/operator-expr.html>

Call expressions
================

 
>  **Syntax**  
>  *CallExpression* :  
>  [*Expression*](../expressions) `(` *CallParams*? `)`
> 
>  *CallParams* :  
>  [*Expression*](../expressions) ( `,` [*Expression*](../expressions) )\* `,`?
> 
>  

 A *call expression* calls a function. The syntax of a call expression is an expression, called the *function operand*, followed by a parenthesized comma-separated list of expression, called the *argument operands*. If the function eventually returns, then the expression completes. For [non-function types](../types/function-item), the expression `f(...)` uses the method on one of the [`std::ops::Fn`](../../std/ops/trait.fn), [`std::ops::FnMut`](../../std/ops/trait.fnmut) or [`std::ops::FnOnce`](../../std/ops/trait.fnonce) traits, which differ in whether they take the type by reference, mutable reference, or take ownership respectively. An automatic borrow will be taken if needed. The function operand will also be [automatically dereferenced](field-expr#automatic-dereferencing) as required.

 Some examples of call expressions:

 
```
#![allow(unused)]
fn main() {
fn add(x: i32, y: i32) -> i32 { 0 }
let three: i32 = add(1i32, 2i32);
let name: &'static str = (|| "Rust")();
}
```
 Disambiguating Function Calls
-----------------------------

 All function calls are sugar for a more explicit [fully-qualified syntax](../paths#qualified-paths). Function calls may need to be fully qualified, depending on the ambiguity of a call in light of in-scope items.

 
>  **Note**: In the past, the terms "Unambiguous Function Call Syntax", "Universal Function Call Syntax", or "UFCS", have been used in documentation, issues, RFCs, and other community writings. However, these terms lack descriptive power and potentially confuse the issue at hand. We mention them here for searchability's sake.
> 
>  

 Several situations often occur which result in ambiguities about the receiver or referent of method or associated function calls. These situations may include:

 * Multiple in-scope traits define methods with the same name for the same types
* Auto-`deref` is undesirable; for example, distinguishing between methods on a smart pointer itself and the pointer's referent
* Methods which take no arguments, like [`default()`](../../std/default/trait.default#tymethod.default), and return properties of a type, like [`size_of()`](../../std/mem/fn.size_of)

 To resolve the ambiguity, the programmer may refer to their desired method or function using more specific paths, types, or traits.

 For example,

 
```
trait Pretty {
    fn print(&self);
}

trait Ugly {
  fn print(&self);
}

struct Foo;
impl Pretty for Foo {
    fn print(&self) {}
}

struct Bar;
impl Pretty for Bar {
    fn print(&self) {}
}
impl Ugly for Bar {
    fn print(&self) {}
}

fn main() {
    let f = Foo;
    let b = Bar;

    // we can do this because we only have one item called `print` for `Foo`s
    f.print();
    // more explicit, and, in the case of `Foo`, not necessary
    Foo::print(&f);
    // if you're not into the whole brevity thing
    <Foo as Pretty>::print(&f);

    // b.print(); // Error: multiple 'print' found
    // Bar::print(&b); // Still an error: multiple `print` found

    // necessary because of in-scope items defining `print`
    <Bar as Pretty>::print(&b);
}
```
 Refer to [RFC 132](https://github.com/rust-lang/rfcs/blob/master/text/0132-ufcs.md) for further details and motivations.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/expressions/call-expr.html>

Method-call expressions
=======================

 
>  **Syntax**  
>  *MethodCallExpression* :  
>  [*Expression*](../expressions) `.` [*PathExprSegment*](../paths#paths-in-expressions) `(`[*CallParams*](call-expr)? `)`
> 
>  

 A *method call* consists of an expression (the *receiver*) followed by a single dot, an expression path segment, and a parenthesized expression-list. Method calls are resolved to associated [methods](../items/associated-items#methods) on specific traits, either statically dispatching to a method if the exact `self`-type of the left-hand-side is known, or dynamically dispatching if the left-hand-side expression is an indirect [trait object](../types/trait-object).

 
```
#![allow(unused)]
fn main() {
let pi: Result<f32, _> = "3.14".parse();
let log_pi = pi.unwrap_or(1.0).log(2.72);
assert!(1.14 < log_pi && log_pi < 1.15)
}
```
 When looking up a method call, the receiver may be automatically dereferenced or borrowed in order to call a method. This requires a more complex lookup process than for other functions, since there may be a number of possible methods to call. The following procedure is used:

 The first step is to build a list of candidate receiver types. Obtain these by repeatedly [dereferencing](operator-expr#the-dereference-operator) the receiver expression's type, adding each type encountered to the list, then finally attempting an [unsized coercion](../type-coercions#unsized-coercions) at the end, and adding the result type if that is successful. Then, for each candidate `T`, add `&T` and `&mut T` to the list immediately after `T`.

 For instance, if the receiver has type `Box<[i32;2]>`, then the candidate types will be `Box<[i32;2]>`, `&Box<[i32;2]>`, `&mut Box<[i32;2]>`, `[i32; 2]` (by dereferencing), `&[i32; 2]`, `&mut [i32; 2]`, `[i32]` (by unsized coercion), `&[i32]`, and finally `&mut [i32]`.

 Then, for each candidate type `T`, search for a [visible](../visibility-and-privacy) method with a receiver of that type in the following places:

 1. `T`'s inherent methods (methods implemented directly on `T`).
2. Any of the methods provided by a [visible](../visibility-and-privacy) trait implemented by `T`. If `T` is a type parameter, methods provided by trait bounds on `T` are looked up first. Then all remaining methods in scope are looked up.

 
>  Note: the lookup is done for each type in order, which can occasionally lead to surprising results. The below code will print "In trait impl!", because `&self` methods are looked up first, the trait method is found before the struct's `&mut self` method is found.
> 
>  
> ```
> struct Foo {}
> 
> trait Bar {
>   fn bar(&self);
> }
> 
> impl Foo {
>   fn bar(&mut self) {
>     println!("In struct impl!")
>   }
> }
> 
> impl Bar for Foo {
>   fn bar(&self) {
>     println!("In trait impl!")
>   }
> }
> 
> fn main() {
>   let mut f = Foo{};
>   f.bar();
> }
> ```
>  

 If this results in multiple possible candidates, then it is an error, and the receiver must be [converted](call-expr#disambiguating-function-calls) to an appropriate receiver type to make the method call.

 This process does not take into account the mutability or lifetime of the receiver, or whether a method is `unsafe`. Once a method is looked up, if it can't be called for one (or more) of those reasons, the result is a compiler error.

 If a step is reached where there is more than one possible method, such as where generic methods or traits are considered the same, then it is a compiler error. These cases require a [disambiguating function call syntax](call-expr#disambiguating-function-calls) for method and function invocation.

 
>  **Edition Differences**: Before the 2021 edition, during the search for visible methods, if the candidate receiver type is an [array type](../types/array), methods provided by the standard library [`IntoIterator`](../../std/iter/trait.intoiterator) trait are ignored.
> 
>  The edition used for this purpose is determined by the token representing the method name.
> 
>  This special case may be removed in the future.
> 
>  

  ***Warning:*** For [trait objects](../types/trait-object), if there is an inherent method of the same name as a trait method, it will give a compiler error when trying to call the method in a method call expression. Instead, you can call the method using [disambiguating function call syntax](call-expr#disambiguating-function-calls), in which case it calls the trait method, not the inherent method. There is no way to call the inherent method. Just don't define inherent methods on trait objects with the same name as a trait method and you'll be fine.

 

 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/expressions/method-call-expr.html>

Field access expressions
========================

 
>  **Syntax**  
>  *FieldExpression* :  
>  [*Expression*](../expressions) `.` [IDENTIFIER](../identifiers)
> 
>  

 A *field expression* is a [place expression](../expressions#place-expressions-and-value-expressions) that evaluates to the location of a field of a [struct](../items/structs) or [union](../items/unions). When the operand is [mutable](../expressions#mutability), the field expression is also mutable.

 The syntax for a field expression is an expression, called the *container operand*, then a `.`, and finally an [identifier](../identifiers). Field expressions cannot be followed by a parenthetical comma-separated list of expressions, as that is instead parsed as a [method call expression](method-call-expr). That is, they cannot be the function operand of a [call expression](call-expr).

 
>  **Note**: Wrap the field expression in a [parenthesized expression](grouped-expr) to use it in a call expression.
> 
>  
> ```
> #![allow(unused)]
> fn main() {
> struct HoldsCallable<F: Fn()> { callable: F }
> let holds_callable = HoldsCallable { callable: || () };
> 
> // Invalid: Parsed as calling the method "callable"
> // holds_callable.callable();
> 
> // Valid
> (holds_callable.callable)();
> }
> ```
>  

 Examples:

 
```
mystruct.myfield;
foo().x;
(Struct {a: 10, b: 20}).a;
(mystruct.function_field)() // Call expression containing a field expression
```
 Automatic dereferencing
-----------------------

 If the type of the container operand implements [`Deref`](../special-types-and-traits#deref-and-derefmut) or [`DerefMut`](../special-types-and-traits#deref-and-derefmut) depending on whether the operand is [mutable](../expressions#mutability), it is *automatically dereferenced* as many times as necessary to make the field access possible. This process is also called *autoderef* for short.

 Borrowing
---------

 The fields of a struct or a reference to a struct are treated as separate entities when borrowing. If the struct does not implement [`Drop`](../special-types-and-traits#drop) and is stored in a local variable, this also applies to moving out of each of its fields. This also does not apply if automatic dereferencing is done though user-defined types other than [`Box`](../special-types-and-traits#boxt).

 
```
#![allow(unused)]
fn main() {
struct A { f1: String, f2: String, f3: String }
let mut x: A;
x = A {
    f1: "f1".to_string(),
    f2: "f2".to_string(),
    f3: "f3".to_string()
};
let a: &mut String = &mut x.f1; // x.f1 borrowed mutably
let b: &String = &x.f2;         // x.f2 borrowed immutably
let c: &String = &x.f2;         // Can borrow again
let d: String = x.f3;           // Move out of x.f3
}
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/expressions/field-expr.html>

Closure expressions
===================

 
>  **Syntax**  
>  *ClosureExpression* :  
>  `move`?  
>  ( `||` | `|` *ClosureParameters*? `|` )  
>  ([*Expression*](../expressions) | `->` [*TypeNoBounds*](../types#type-expressions) [*BlockExpression*](block-expr))
> 
>  *ClosureParameters* :  
>  *ClosureParam* (`,` *ClosureParam*)\* `,`?
> 
>  *ClosureParam* :  
>  [*OuterAttribute*](../attributes)\* [*PatternNoTopAlt*](../patterns) ( `:` [*Type*](../types#type-expressions) )?
> 
>  

 A *closure expression*, also known as a lambda expression or a lambda, defines a [closure type](../types/closure) and evaluates to a value of that type. The syntax for a closure expression is an optional `move` keyword, then a pipe-symbol-delimited (`|`) comma-separated list of [patterns](../patterns), called the *closure parameters* each optionally followed by a `:` and a type, then an optional `->` and type, called the *return type*, and then an expression, called the *closure body operand*. The optional type after each pattern is a type annotation for the pattern. If there is a return type, the closure body must be a [block](block-expr).

 A closure expression denotes a function that maps a list of parameters onto the expression that follows the parameters. Just like a [`let` binding](../statements#let-statements), the closure parameters are irrefutable [patterns](../patterns), whose type annotation is optional and will be inferred from context if not given. Each closure expression has a unique, anonymous type.

 Significantly, closure expressions *capture their environment*, which regular [function definitions](../items/functions) do not. Without the `move` keyword, the closure expression [infers how it captures each variable from its environment](../types/closure#capture-modes), preferring to capture by shared reference, effectively borrowing all outer variables mentioned inside the closure's body. If needed the compiler will infer that instead mutable references should be taken, or that the values should be moved or copied (depending on their type) from the environment. A closure can be forced to capture its environment by copying or moving values by prefixing it with the `move` keyword. This is often used to ensure that the closure's lifetime is `'static`.

 Closure trait implementations
-----------------------------

 Which traits the closure type implement depends on how variables are captured and the types of the captured variables. See the [call traits and coercions](../types/closure#call-traits-and-coercions) chapter for how and when a closure implements `Fn`, `FnMut`, and `FnOnce`. The closure type implements [`Send`](../special-types-and-traits#send) and [`Sync`](../special-types-and-traits#sync) if the type of every captured variable also implements the trait.

 Example
-------

 In this example, we define a function `ten_times` that takes a higher-order function argument, and we then call it with a closure expression as an argument, followed by a closure expression that moves values from its environment.

 
```
#![allow(unused)]
fn main() {
fn ten_times<F>(f: F) where F: Fn(i32) {
    for index in 0..10 {
        f(index);
    }
}

ten_times(|j| println!("hello, {}", j));
// With type annotations
ten_times(|j: i32| -> () { println!("hello, {}", j) });

let word = "konnichiwa".to_owned();
ten_times(move |j| println!("{}, {}", word, j));
}
```
 Attributes on closure parameters
--------------------------------

 Attributes on closure parameters follow the same rules and restrictions as [regular function parameters](../items/functions#attributes-on-function-parameters).



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/expressions/closure-expr.html>

Loops and other breakable expressions
=====================================

 
>  **Syntax**  
>  *LoopExpression* :  
>  [*LoopLabel*](#loop-labels)? (  
>  [*InfiniteLoopExpression*](#infinite-loops)  
>  | [*PredicateLoopExpression*](#predicate-loops)  
>  | [*PredicatePatternLoopExpression*](#predicate-pattern-loops)  
>  | [*IteratorLoopExpression*](#iterator-loops)  
>  | [*LabelBlockExpression*](#labelled-block-expressions)  
>  )
> 
>  

 Rust supports five loop expressions:

 * A [`loop` expression](#infinite-loops) denotes an infinite loop.
* A [`while` expression](#predicate-loops) loops until a predicate is false.
* A [`while let` expression](#predicate-pattern-loops) tests a pattern.
* A [`for` expression](#iterator-loops) extracts values from an iterator, looping until the iterator is empty.
* A [labelled block expression](#labelled-block-expressions) runs a loop exactly once, but allows exiting the loop early with `break`.

 All five types of loop support [`break` expressions](#break-expressions), and [labels](#loop-labels). All except labelled block expressions support [`continue` expressions](#continue-expressions). Only `loop` and labelled block expressions support [evaluation to non-trivial values](#break-and-loop-values).

 Infinite loops
--------------

 
>  **Syntax**  
>  *InfiniteLoopExpression* :  
>  `loop` [*BlockExpression*](block-expr)
> 
>  

 A `loop` expression repeats execution of its body continuously: `loop { println!("I live."); }`.

 A `loop` expression without an associated `break` expression is diverging and has type [`!`](../types/never). A `loop` expression containing associated [`break` expression(s)](#break-expressions) may terminate, and must have type compatible with the value of the `break` expression(s).

 Predicate loops
---------------

 
>  **Syntax**  
>  *PredicateLoopExpression* :  
>  `while` [*Expression*](../expressions)*except struct expression* [*BlockExpression*](block-expr)
> 
>  

 A `while` loop begins by evaluating the [boolean](../types/boolean) loop conditional operand. If the loop conditional operand evaluates to `true`, the loop body block executes, then control returns to the loop conditional operand. If the loop conditional expression evaluates to `false`, the `while` expression completes.

 An example:

 
```
#![allow(unused)]
fn main() {
let mut i = 0;

while i < 10 {
    println!("hello");
    i = i + 1;
}
}
```
 Predicate pattern loops
-----------------------

 
>  **Syntax**  
>  [*PredicatePatternLoopExpression*](#predicate-pattern-loops) :  
>  `while` `let` [*Pattern*](../patterns) `=` [*Scrutinee*](match-expr)*except lazy boolean operator expression* [*BlockExpression*](block-expr)
> 
>  

 A `while let` loop is semantically similar to a `while` loop but in place of a condition expression it expects the keyword `let` followed by a pattern, an `=`, a [scrutinee](../glossary#scrutinee) expression and a block expression. If the value of the scrutinee matches the pattern, the loop body block executes then control returns to the pattern matching statement. Otherwise, the while expression completes.

 
```
#![allow(unused)]
fn main() {
let mut x = vec![1, 2, 3];

while let Some(y) = x.pop() {
    println!("y = {}", y);
}

while let _ = 5 {
    println!("Irrefutable patterns are always true");
    break;
}
}
```
 A `while let` loop is equivalent to a `loop` expression containing a [`match` expression](match-expr) as follows.

 
```
'label: while let PATS = EXPR {
    /* loop body */
}
```
 is equivalent to

 
```
'label: loop {
    match EXPR {
        PATS => { /* loop body */ },
        _ => break,
    }
}
```
 Multiple patterns may be specified with the `|` operator. This has the same semantics as with `|` in `match` expressions:

 
```
#![allow(unused)]
fn main() {
let mut vals = vec![2, 3, 1, 2, 2];
while let Some(v @ 1) | Some(v @ 2) = vals.pop() {
    // Prints 2, 2, then 1
    println!("{}", v);
}
}
```
 As is the case in [`if let` expressions](if-expr#if-let-expressions), the scrutinee cannot be a [lazy boolean operator expression](operator-expr#lazy-boolean-operators).

 Iterator loops
--------------

 
>  **Syntax**  
>  *IteratorLoopExpression* :  
>  `for` [*Pattern*](../patterns) `in` [*Expression*](../expressions)*except struct expression* [*BlockExpression*](block-expr)
> 
>  

 A `for` expression is a syntactic construct for looping over elements provided by an implementation of `std::iter::IntoIterator`. If the iterator yields a value, that value is matched against the irrefutable pattern, the body of the loop is executed, and then control returns to the head of the `for` loop. If the iterator is empty, the `for` expression completes.

 An example of a `for` loop over the contents of an array:

 
```
#![allow(unused)]
fn main() {
let v = &["apples", "cake", "coffee"];

for text in v {
    println!("I like {}.", text);
}
}
```
 An example of a for loop over a series of integers:

 
```
#![allow(unused)]
fn main() {
let mut sum = 0;
for n in 1..11 {
    sum += n;
}
assert_eq!(sum, 55);
}
```
 A `for` loop is equivalent to a `loop` expression containing a [`match` expression](match-expr) as follows:

 
```
'label: for PATTERN in iter_expr {
    /* loop body */
}
```
 is equivalent to

 
```
{
    let result = match IntoIterator::into_iter(iter_expr) {
        mut iter => 'label: loop {
            let mut next;
            match Iterator::next(&mut iter) {
                Option::Some(val) => next = val,
                Option::None => break,
            };
            let PATTERN = next;
            let () = { /* loop body */ };
        },
    };
    result
}
```
 `IntoIterator`, `Iterator`, and `Option` are always the standard library items here, not whatever those names resolve to in the current scope. The variable names `next`, `iter`, and `val` are for exposition only, they do not actually have names the user can type.

 
>  **Note**: that the outer `match` is used to ensure that any [temporary values](../expressions#temporaries) in `iter_expr` don't get dropped before the loop is finished. `next` is declared before being assigned because it results in types being inferred correctly more often.
> 
>  

 Loop labels
-----------

 
>  **Syntax**  
>  *LoopLabel* :  
>  [LIFETIME\_OR\_LABEL](../tokens#lifetimes-and-loop-labels) `:`
> 
>  

 A loop expression may optionally have a *label*. The label is written as a lifetime preceding the loop expression, as in `'foo: loop { break 'foo; }`, `'bar: while false {}`, `'humbug: for _ in 0..0 {}`. If a label is present, then labeled `break` and `continue` expressions nested within this loop may exit out of this loop or return control to its head. See [break expressions](#break-expressions) and [continue expressions](#continue-expressions).

 Labels follow the hygiene and shadowing rules of local variables. For example, this code will print "outer loop":

 
```
#![allow(unused)]
fn main() {
'a: loop {
    'a: loop {
        break 'a;
    }
    print!("outer loop");
    break 'a;
}
}
```
 
`break` expressions
--------------------

 
>  **Syntax**  
>  *BreakExpression* :  
>  `break` [LIFETIME\_OR\_LABEL](../tokens#lifetimes-and-loop-labels)? [*Expression*](../expressions)?
> 
>  

 When `break` is encountered, execution of the associated loop body is immediately terminated, for example:

 
```
#![allow(unused)]
fn main() {
let mut last = 0;
for x in 1..100 {
    if x > 12 {
        break;
    }
    last = x;
}
assert_eq!(last, 12);
}
```
 A `break` expression is normally associated with the innermost `loop`, `for` or `while` loop enclosing the `break` expression, but a [label](#loop-labels) can be used to specify which enclosing loop is affected. Example:

 
```
#![allow(unused)]
fn main() {
'outer: loop {
    while true {
        break 'outer;
    }
}
}
```
 A `break` expression is only permitted in the body of a loop, and has one of the forms `break`, `break 'label` or ([see below](#break-and-loop-values)) `break EXPR` or `break 'label EXPR`.

 Labelled block expressions
--------------------------

 
>  **Syntax**  
>  *LabelBlockExpression* :  
>  [*BlockExpression*](block-expr)
> 
>  

 Labelled block expressions are exactly like block expressions, except that they allow using `break` expressions within the block. Unlike loops, `break` expressions within a labelled block expression *must* have a label (i.e. the label is not optional). Similarly, labelled block expressions *must* begin with a label.

 
```
#![allow(unused)]
fn main() {
fn do_thing() {}
fn condition_not_met() -> bool { true }
fn do_next_thing() {}
fn do_last_thing() {}
let result = 'block: {
    do_thing();
    if condition_not_met() {
        break 'block 1;
    }
    do_next_thing();
    if condition_not_met() {
        break 'block 2;
    }
    do_last_thing();
    3
};
}
```
 
`continue` expressions
-----------------------

 
>  **Syntax**  
>  *ContinueExpression* :  
>  `continue` [LIFETIME\_OR\_LABEL](../tokens#lifetimes-and-loop-labels)?
> 
>  

 When `continue` is encountered, the current iteration of the associated loop body is immediately terminated, returning control to the loop *head*. In the case of a `while` loop, the head is the conditional expression controlling the loop. In the case of a `for` loop, the head is the call-expression controlling the loop.

 Like `break`, `continue` is normally associated with the innermost enclosing loop, but `continue 'label` may be used to specify the loop affected. A `continue` expression is only permitted in the body of a loop.

 
`break` and loop values
------------------------

 When associated with a `loop`, a break expression may be used to return a value from that loop, via one of the forms `break EXPR` or `break 'label EXPR`, where `EXPR` is an expression whose result is returned from the `loop`. For example:

 
```
#![allow(unused)]
fn main() {
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);
}
```
 In the case a `loop` has an associated `break`, it is not considered diverging, and the `loop` must have a type compatible with each `break` expression. `break` without an expression is considered identical to `break` with expression `()`.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/expressions/loop-expr.html>

Range expressions
=================

 
>  **Syntax**  
>  *RangeExpression* :  
>  *RangeExpr*  
>  | *RangeFromExpr*  
>  | *RangeToExpr*  
>  | *RangeFullExpr*  
>  | *RangeInclusiveExpr*  
>  | *RangeToInclusiveExpr*
> 
>  *RangeExpr* :  
>  [*Expression*](../expressions) `..` [*Expression*](../expressions)
> 
>  *RangeFromExpr* :  
>  [*Expression*](../expressions) `..`
> 
>  *RangeToExpr* :  
>  `..` [*Expression*](../expressions)
> 
>  *RangeFullExpr* :  
>  `..`
> 
>  *RangeInclusiveExpr* :  
>  [*Expression*](../expressions) `..=` [*Expression*](../expressions)
> 
>  *RangeToInclusiveExpr* :  
>  `..=` [*Expression*](../expressions)
> 
>  

 The `..` and `..=` operators will construct an object of one of the `std::ops::Range` (or `core::ops::Range`) variants, according to the following table:

 


| Production | Syntax | Type | Range |
| --- | --- | --- | --- |
| *RangeExpr* | start`..`end | [std::ops::Range](../../std/ops/struct.range) | start ≤ x < end |
| *RangeFromExpr* | start`..` | [std::ops::RangeFrom](../../std/ops/struct.rangefrom) | start ≤ x |
| *RangeToExpr* | `..`end | [std::ops::RangeTo](../../std/ops/struct.rangeto) | x < end |
| *RangeFullExpr* | `..` | [std::ops::RangeFull](../../std/ops/struct.rangefull) | - |
| *RangeInclusiveExpr* | start`..=`end | [std::ops::RangeInclusive](../../std/ops/struct.rangeinclusive) | start ≤ x ≤ end |
| *RangeToInclusiveExpr* | `..=`end | [std::ops::RangeToInclusive](../../std/ops/struct.rangetoinclusive) | x ≤ end |

  Examples:

 
```
#![allow(unused)]
fn main() {
1..2;   // std::ops::Range
3..;    // std::ops::RangeFrom
..4;    // std::ops::RangeTo
..;     // std::ops::RangeFull
5..=6;  // std::ops::RangeInclusive
..=7;   // std::ops::RangeToInclusive
}
```
 The following expressions are equivalent.

 
```
#![allow(unused)]
fn main() {
let x = std::ops::Range {start: 0, end: 10};
let y = 0..10;

assert_eq!(x, y);
}
```
 Ranges can be used in `for` loops:

 
```
#![allow(unused)]
fn main() {
for i in 1..11 {
    println!("{}", i);
}
}
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/expressions/range-expr.html>

`if` and `if let` expressions
==============================

 
`if` expressions
-----------------

 
>  **Syntax**  
>  *IfExpression* :  
>  `if` [*Expression*](../expressions)*except struct expression* [*BlockExpression*](block-expr)  
>  (`else` ( [*BlockExpression*](block-expr) | *IfExpression* | *IfLetExpression* ) )?
> 
>  

 An `if` expression is a conditional branch in program control. The syntax of an `if` expression is a condition operand, followed by a consequent block, any number of `else if` conditions and blocks, and an optional trailing `else` block. The condition operands must have the [boolean type](../types/boolean). If a condition operand evaluates to `true`, the consequent block is executed and any subsequent `else if` or `else` block is skipped. If a condition operand evaluates to `false`, the consequent block is skipped and any subsequent `else if` condition is evaluated. If all `if` and `else if` conditions evaluate to `false` then any `else` block is executed. An if expression evaluates to the same value as the executed block, or `()` if no block is evaluated. An `if` expression must have the same type in all situations.

 
```
#![allow(unused)]
fn main() {
let x = 3;
if x == 4 {
    println!("x is four");
} else if x == 3 {
    println!("x is three");
} else {
    println!("x is something else");
}

let y = if 12 * 15 > 150 {
    "Bigger"
} else {
    "Smaller"
};
assert_eq!(y, "Bigger");
}
```
 
`if let` expressions
---------------------

 
>  **Syntax**  
>  *IfLetExpression* :  
>  `if` `let` [*Pattern*](../patterns) `=` [*Scrutinee*](match-expr)*except lazy boolean operator expression* [*BlockExpression*](block-expr)  
>  (`else` ( [*BlockExpression*](block-expr) | *IfExpression* | *IfLetExpression* ) )?
> 
>  

 An `if let` expression is semantically similar to an `if` expression but in place of a condition operand it expects the keyword `let` followed by a pattern, an `=` and a [scrutinee](../glossary#scrutinee) operand. If the value of the scrutinee matches the pattern, the corresponding block will execute. Otherwise, flow proceeds to the following `else` block if it exists. Like `if` expressions, `if let` expressions have a value determined by the block that is evaluated.

 
```
#![allow(unused)]
fn main() {
let dish = ("Ham", "Eggs");

// this body will be skipped because the pattern is refuted
if let ("Bacon", b) = dish {
    println!("Bacon is served with {}", b);
} else {
    // This block is evaluated instead.
    println!("No bacon will be served");
}

// this body will execute
if let ("Ham", b) = dish {
    println!("Ham is served with {}", b);
}

if let _ = 5 {
    println!("Irrefutable patterns are always true");
}
}
```
 `if` and `if let` expressions can be intermixed:

 
```
#![allow(unused)]
fn main() {
let x = Some(3);
let a = if let Some(1) = x {
    1
} else if x == Some(2) {
    2
} else if let Some(y) = x {
    y
} else {
    -1
};
assert_eq!(a, 3);
}
```
 An `if let` expression is equivalent to a [`match` expression](match-expr) as follows:

 
```
if let PATS = EXPR {
    /* body */
} else {
    /*else */
}
```
 is equivalent to

 
```
match EXPR {
    PATS => { /* body */ },
    _ => { /* else */ },    // () if there is no else
}
```
 Multiple patterns may be specified with the `|` operator. This has the same semantics as with `|` in `match` expressions:

 
```
#![allow(unused)]
fn main() {
enum E {
    X(u8),
    Y(u8),
    Z(u8),
}
let v = E::Y(12);
if let E::X(n) | E::Y(n) = v {
    assert_eq!(n, 12);
}
}
```
 The expression cannot be a [lazy boolean operator expression](operator-expr#lazy-boolean-operators). Use of a lazy boolean operator is ambiguous with a planned feature change of the language (the implementation of if-let chains - see [eRFC 2947](https://github.com/rust-lang/rfcs/blob/master/text/2497-if-let-chains.md#rollout-plan-and-transitioning-to-rust-2018)). When lazy boolean operator expression is desired, this can be achieved by using parenthesis as below:

 
```
// Before...
if let PAT = EXPR && EXPR { .. }

// After...
if let PAT = ( EXPR && EXPR ) { .. }

// Before...
if let PAT = EXPR || EXPR { .. }

// After...
if let PAT = ( EXPR || EXPR ) { .. }
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/expressions/if-expr.html>

`match` expressions
====================

 
>  **Syntax**  
>  *MatchExpression* :  
>  `match` *Scrutinee* `{`  
>  [*InnerAttribute*](../attributes)\*  
>  *MatchArms*?  
>  `}`
> 
>  *Scrutinee* :  
>  [*Expression*](../expressions)*except struct expression*
> 
>  *MatchArms* :  
>  ( *MatchArm* `=>` ( [*ExpressionWithoutBlock*](../expressions) `,` | [*ExpressionWithBlock*](../expressions) `,`? ) )\*  
>  *MatchArm* `=>` [*Expression*](../expressions) `,`?
> 
>  *MatchArm* :  
>  [*OuterAttribute*](../attributes)\* [*Pattern*](../patterns) *MatchArmGuard*?
> 
>  *MatchArmGuard* :  
>  `if` [*Expression*](../expressions)
> 
>  

 A *`match` expression* branches on a pattern. The exact form of matching that occurs depends on the [pattern](../patterns). A `match` expression has a *[scrutinee](../glossary#scrutinee) expression*, which is the value to compare to the patterns. The scrutinee expression and the patterns must have the same type.

 A `match` behaves differently depending on whether or not the scrutinee expression is a [place expression or value expression](../expressions#place-expressions-and-value-expressions). If the scrutinee expression is a [value expression](../expressions#place-expressions-and-value-expressions), it is first evaluated into a temporary location, and the resulting value is sequentially compared to the patterns in the arms until a match is found. The first arm with a matching pattern is chosen as the branch target of the `match`, any variables bound by the pattern are assigned to local variables in the arm's block, and control enters the block.

 When the scrutinee expression is a [place expression](../expressions#place-expressions-and-value-expressions), the match does not allocate a temporary location; however, a by-value binding may copy or move from the memory location. When possible, it is preferable to match on place expressions, as the lifetime of these matches inherits the lifetime of the place expression rather than being restricted to the inside of the match.

 An example of a `match` expression:

 
```
#![allow(unused)]
fn main() {
let x = 1;

match x {
    1 => println!("one"),
    2 => println!("two"),
    3 => println!("three"),
    4 => println!("four"),
    5 => println!("five"),
    _ => println!("something else"),
}
}
```
 Variables bound within the pattern are scoped to the match guard and the arm's expression. The [binding mode](../patterns#binding-modes) (move, copy, or reference) depends on the pattern.

 Multiple match patterns may be joined with the `|` operator. Each pattern will be tested in left-to-right sequence until a successful match is found.

 
```
#![allow(unused)]
fn main() {
let x = 9;
let message = match x {
    0 | 1  => "not many",
    2 ..= 9 => "a few",
    _      => "lots"
};

assert_eq!(message, "a few");

// Demonstration of pattern match order.
struct S(i32, i32);

match S(1, 2) {
    S(z @ 1, _) | S(_, z @ 2) => assert_eq!(z, 1),
    _ => panic!(),
}
}
```
 
>  Note: The `2..=9` is a [Range Pattern](../patterns#range-patterns), not a [Range Expression](range-expr). Thus, only those types of ranges supported by range patterns can be used in match arms.
> 
>  

 Every binding in each `|` separated pattern must appear in all of the patterns in the arm. Every binding of the same name must have the same type, and have the same binding mode.

 Match guards
------------

 Match arms can accept *match guards* to further refine the criteria for matching a case. Pattern guards appear after the pattern and consist of a `bool`-typed expression following the `if` keyword.

 When the pattern matches successfully, the pattern guard expression is executed. If the expression evaluates to true, the pattern is successfully matched against. Otherwise, the next pattern, including other matches with the `|` operator in the same arm, is tested.

 
```
#![allow(unused)]
fn main() {
let maybe_digit = Some(0);
fn process_digit(i: i32) { }
fn process_other(i: i32) { }
let message = match maybe_digit {
    Some(x) if x < 10 => process_digit(x),
    Some(x) => process_other(x),
    None => panic!(),
};
}
```
 
>  Note: Multiple matches using the `|` operator can cause the pattern guard and the side effects it has to execute multiple times. For example:
> 
>  
> ```
> #![allow(unused)]
> fn main() {
> use std::cell::Cell;
> let i : Cell<i32> = Cell::new(0);
> match 1 {
>     1 | _ if { i.set(i.get() + 1); false } => {}
>     _ => {}
> }
> assert_eq!(i.get(), 2);
> }
> ```
>  

 A pattern guard may refer to the variables bound within the pattern they follow. Before evaluating the guard, a shared reference is taken to the part of the scrutinee the variable matches on. While evaluating the guard, this shared reference is then used when accessing the variable. Only when the guard evaluates to true is the value moved, or copied, from the scrutinee into the variable. This allows shared borrows to be used inside guards without moving out of the scrutinee in case guard fails to match. Moreover, by holding a shared reference while evaluating the guard, mutation inside guards is also prevented.

 Attributes on match arms
------------------------

 Outer attributes are allowed on match arms. The only attributes that have meaning on match arms are [`cfg`](../conditional-compilation) and the [lint check attributes](../attributes/diagnostics#lint-check-attributes).

 [Inner attributes](../attributes) are allowed directly after the opening brace of the match expression in the same expression contexts as [attributes on block expressions](block-expr#attributes-on-block-expressions).



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/expressions/match-expr.html>

`return` expressions
=====================

 
>  **Syntax**  
>  *ReturnExpression* :  
>  `return` [*Expression*](../expressions)?
> 
>  

 Return expressions are denoted with the keyword `return`. Evaluating a `return` expression moves its argument into the designated output location for the current function call, destroys the current function activation frame, and transfers control to the caller frame.

 An example of a `return` expression:

 
```
#![allow(unused)]
fn main() {
fn max(a: i32, b: i32) -> i32 {
    if a > b {
        return a;
    }
    return b;
}
}
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/expressions/return-expr.html>

Await expressions
=================

 
>  **Syntax**  
>  *AwaitExpression* :  
>  [*Expression*](../expressions) `.` `await`
> 
>  

 An `await` expression is a syntactic construct for suspending a computation provided by an implementation of `std::future::IntoFuture` until the given future is ready to produce a value. The syntax for an await expression is an expression with a type that implements the [`IntoFuture`](../../std/future/trait.intofuture) trait, called the *future operand*, then the token `.`, and then the `await` keyword. Await expressions are legal only within an [async context](block-expr#async-context), like an [`async fn`](../items/functions#async-functions) or an [`async` block](block-expr#async-blocks).

 More specifically, an await expression has the following effect.

 1. Create a future by calling [`IntoFuture::into_future`](../../std/future/trait.intofuture#tymethod.into_future) on the future operand.
2. Evaluate the future to a [future](../../std/future/trait.future) `tmp`;
3. Pin `tmp` using [`Pin::new_unchecked`](../../std/pin/struct.pin#method.new_unchecked);
4. This pinned future is then polled by calling the [`Future::poll`](../../std/future/trait.future#tymethod.poll) method and passing it the current [task context](#task-context);
5. If the call to `poll` returns [`Poll::Pending`](../../std/task/enum.poll#variant.Pending), then the future returns `Poll::Pending`, suspending its state so that, when the surrounding async context is re-polled,execution returns to step 3;
6. Otherwise the call to `poll` must have returned [`Poll::Ready`](../../std/task/enum.poll#variant.Ready), in which case the value contained in the [`Poll::Ready`](../../std/task/enum.poll#variant.Ready) variant is used as the result of the `await` expression itself.

 
>  **Edition differences**: Await expressions are only available beginning with Rust 2018.
> 
>  

 Task context
------------

 The task context refers to the [`Context`](../../std/task/struct.context) which was supplied to the current [async context](block-expr#async-context) when the async context itself was polled. Because `await` expressions are only legal in an async context, there must be some task context available.

 Approximate desugaring
----------------------

 Effectively, an await expression is roughly equivalent to the following non-normative desugaring:

 
```
match operand.into_future() {
    mut pinned => loop {
        let mut pin = unsafe { Pin::new_unchecked(&mut pinned) };
        match Pin::future::poll(Pin::borrow(&mut pin), &mut current_context) {
            Poll::Ready(r) => break r,
            Poll::Pending => yield Poll::Pending,
        }
    }
}
```
 where the `yield` pseudo-code returns `Poll::Pending` and, when re-invoked, resumes execution from that point. The variable `current_context` refers to the context taken from the async environment.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/expressions/await-expr.html>

`_` expressions
================

 
>  **Syntax**  
>  *UnderscoreExpression* :  
>  `_`
> 
>  

 Underscore expressions, denoted with the symbol `_`, are used to signify a placeholder in a destructuring assignment. They may only appear in the left-hand side of an assignment.

 An example of an `_` expression:

 
```
#![allow(unused)]
fn main() {
let p = (1, 2);
let mut a = 0;
(_, a) = p;
}
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/expressions/underscore-expr.html>

Patterns
========

 
>  **Syntax**  
>  *Pattern* :  
>  `|`? *PatternNoTopAlt* ( `|` *PatternNoTopAlt* )\*
> 
>  *PatternNoTopAlt* :  
>  *PatternWithoutRange*  
>  | [*RangePattern*](#range-patterns)
> 
>  *PatternWithoutRange* :  
>  [*LiteralPattern*](#literal-patterns)  
>  | [*IdentifierPattern*](#identifier-patterns)  
>  | [*WildcardPattern*](#wildcard-pattern)  
>  | [*RestPattern*](#rest-patterns)  
>  | [*ReferencePattern*](#reference-patterns)  
>  | [*StructPattern*](#struct-patterns)  
>  | [*TupleStructPattern*](#tuple-struct-patterns)  
>  | [*TuplePattern*](#tuple-patterns)  
>  | [*GroupedPattern*](#grouped-patterns)  
>  | [*SlicePattern*](#slice-patterns)  
>  | [*PathPattern*](#path-patterns)  
>  | [*MacroInvocation*](macros#macro-invocation)
> 
>  

 Patterns are used to match values against structures and to, optionally, bind variables to values inside these structures. They are also used in variable declarations and parameters for functions and closures.

 The pattern in the following example does four things:

 * Tests if `person` has the `car` field filled with something.
* Tests if the person's `age` field is between 13 and 19, and binds its value to the `person_age` variable.
* Binds a reference to the `name` field to the variable `person_name`.
* Ignores the rest of the fields of `person`. The remaining fields can have any value and are not bound to any variables.

 
```
#![allow(unused)]
fn main() {
struct Car;
struct Computer;
struct Person {
    name: String,
    car: Option<Car>,
    computer: Option<Computer>,
    age: u8,
}
let person = Person {
    name: String::from("John"),
    car: Some(Car),
    computer: None,
    age: 15,
};
if let
    Person {
        car: Some(_),
        age: person_age @ 13..=19,
        name: ref person_name,
        ..
    } = person
{
    println!("{} has a car and is {} years old.", person_name, person_age);
}
}
```
 Patterns are used in:

 * [`let` declarations](statements#let-statements)
* [Function](items/functions) and [closure](expressions/closure-expr) parameters
* [`match` expressions](expressions/match-expr)
* [`if let` expressions](expressions/if-expr)
* [`while let` expressions](expressions/loop-expr#predicate-pattern-loops)
* [`for` expressions](expressions/loop-expr#iterator-loops)

 Destructuring
-------------

 Patterns can be used to *destructure* [structs](items/structs), [enums](items/enumerations), and [tuples](types/tuple). Destructuring breaks up a value into its component pieces. The syntax used is almost the same as when creating such values. In a pattern whose [scrutinee](glossary#scrutinee) expression has a `struct`, `enum` or `tuple` type, a placeholder (`_`) stands in for a *single* data field, whereas a wildcard `..` stands in for *all* the remaining fields of a particular variant. When destructuring a data structure with named (but not numbered) fields, it is allowed to write `fieldname` as a shorthand for `fieldname: fieldname`.

 
```
#![allow(unused)]
fn main() {
enum Message {
    Quit,
    WriteString(String),
    Move { x: i32, y: i32 },
    ChangeColor(u8, u8, u8),
}
let message = Message::Quit;
match message {
    Message::Quit => println!("Quit"),
    Message::WriteString(write) => println!("{}", &write),
    Message::Move{ x, y: 0 } => println!("move {} horizontally", x),
    Message::Move{ .. } => println!("other move"),
    Message::ChangeColor { 0: red, 1: green, 2: _ } => {
        println!("color change, red: {}, green: {}", red, green);
    }
};
}
```
 Refutability
------------

 A pattern is said to be *refutable* when it has the possibility of not being matched by the value it is being matched against. *Irrefutable* patterns, on the other hand, always match the value they are being matched against. Examples:

 
```
#![allow(unused)]
fn main() {
let (x, y) = (1, 2);               // "(x, y)" is an irrefutable pattern

if let (a, 3) = (1, 2) {           // "(a, 3)" is refutable, and will not match
    panic!("Shouldn't reach here");
} else if let (a, 4) = (3, 4) {    // "(a, 4)" is refutable, and will match
    println!("Matched ({}, 4)", a);
}
}
```
 Literal patterns
----------------

 
>  **Syntax**  
>  *LiteralPattern* :  
>  `true` | `false`  
>  | [CHAR\_LITERAL](tokens#character-literals)  
>  | [BYTE\_LITERAL](tokens#byte-literals)  
>  | [STRING\_LITERAL](tokens#string-literals)  
>  | [RAW\_STRING\_LITERAL](tokens#raw-string-literals)  
>  | [BYTE\_STRING\_LITERAL](tokens#byte-string-literals)  
>  | [RAW\_BYTE\_STRING\_LITERAL](tokens#raw-byte-string-literals)  
>  | `-`? [INTEGER\_LITERAL](tokens#integer-literals)  
>  | `-`? [FLOAT\_LITERAL](tokens#floating-point-literals)
> 
>  

 *Literal patterns* match exactly the same value as what is created by the literal. Since negative numbers are not [literals](expressions/literal-expr), literal patterns also accept an optional minus sign before the literal, which acts like the negation operator.

  Floating-point literals are currently accepted, but due to the complexity of comparing them, they are going to be forbidden on literal patterns in a future version of Rust (see [issue #41620](https://github.com/rust-lang/rust/issues/41620)).

  Literal patterns are always refutable.

 Examples:

 
```
#![allow(unused)]
fn main() {
for i in -2..5 {
    match i {
        -1 => println!("It's minus one"),
        1 => println!("It's a one"),
        2|4 => println!("It's either a two or a four"),
        _ => println!("Matched none of the arms"),
    }
}
}
```
 Identifier patterns
-------------------

 
>  **Syntax**  
>  *IdentifierPattern* :  
>  `ref`? `mut`? [IDENTIFIER](identifiers) (`@` [*PatternNoTopAlt*](#patterns) ) ?
> 
>  

 Identifier patterns bind the value they match to a variable. The identifier must be unique within the pattern. The variable will shadow any variables of the same name in scope. The scope of the new binding depends on the context of where the pattern is used (such as a `let` binding or a `match` arm).

 Patterns that consist of only an identifier, possibly with a `mut`, match any value and bind it to that identifier. This is the most commonly used pattern in variable declarations and parameters for functions and closures.

 
```
#![allow(unused)]
fn main() {
let mut variable = 10;
fn sum(x: i32, y: i32) -> i32 {
   x + y
}
}
```
 To bind the matched value of a pattern to a variable, use the syntax `variable @ subpattern`. For example, the following binds the value 2 to `e` (not the entire range: the range here is a range subpattern).

 
```
#![allow(unused)]
fn main() {
let x = 2;

match x {
    e @ 1 ..= 5 => println!("got a range element {}", e),
    _ => println!("anything"),
}
}
```
 By default, identifier patterns bind a variable to a copy of or move from the matched value depending on whether the matched value implements [`Copy`](special-types-and-traits#copy). This can be changed to bind to a reference by using the `ref` keyword, or to a mutable reference using `ref mut`. For example:

 
```
#![allow(unused)]
fn main() {
let a = Some(10);
match a {
    None => (),
    Some(value) => (),
}

match a {
    None => (),
    Some(ref value) => (),
}
}
```
 In the first match expression, the value is copied (or moved). In the second match, a reference to the same memory location is bound to the variable value. This syntax is needed because in destructuring subpatterns the `&` operator can't be applied to the value's fields. For example, the following is not valid:

 
```
#![allow(unused)]
fn main() {
struct Person {
   name: String,
   age: u8,
}
let value = Person { name: String::from("John"), age: 23 };
if let Person { name: &person_name, age: 18..=150 } = value { }
}
```
 To make it valid, write the following:

 
```
#![allow(unused)]
fn main() {
struct Person {
   name: String,
   age: u8,
}
let value = Person { name: String::from("John"), age: 23 };
if let Person {name: ref person_name, age: 18..=150 } = value { }
}
```
 Thus, `ref` is not something that is being matched against. Its objective is exclusively to make the matched binding a reference, instead of potentially copying or moving what was matched.

 [Path patterns](#path-patterns) take precedence over identifier patterns. It is an error if `ref` or `ref mut` is specified and the identifier shadows a constant.

 Identifier patterns are irrefutable if the `@` subpattern is irrefutable or the subpattern is not specified.

 ### Binding modes

 To service better ergonomics, patterns operate in different *binding modes* in order to make it easier to bind references to values. When a reference value is matched by a non-reference pattern, it will be automatically treated as a `ref` or `ref mut` binding. Example:

 
```
#![allow(unused)]
fn main() {
let x: &Option<i32> = &Some(3);
if let Some(y) = x {
    // y was converted to `ref y` and its type is &i32
}
}
```
 *Non-reference patterns* include all patterns except bindings, [wildcard patterns](#wildcard-pattern) (`_`), [`const` patterns](#path-patterns) of reference types, and [reference patterns](#reference-patterns).

 If a binding pattern does not explicitly have `ref`, `ref mut`, or `mut`, then it uses the *default binding mode* to determine how the variable is bound. The default binding mode starts in "move" mode which uses move semantics. When matching a pattern, the compiler starts from the outside of the pattern and works inwards. Each time a reference is matched using a non-reference pattern, it will automatically dereference the value and update the default binding mode. References will set the default binding mode to `ref`. Mutable references will set the mode to `ref mut` unless the mode is already `ref` in which case it remains `ref`. If the automatically dereferenced value is still a reference, it is dereferenced and this process repeats.

 Move bindings and reference bindings can be mixed together in the same pattern. Doing so will result in partial move of the object bound to and the object cannot be used afterwards. This applies only if the type cannot be copied.

 In the example below, `name` is moved out of `person`. Trying to use `person` as a whole or `person.name` would result in an error because of *partial move*.

 Example:

 
```
#![allow(unused)]
fn main() {
struct Person {
   name: String,
   age: u8,
}
let person = Person{ name: String::from("John"), age: 23 };
// `name` is moved from person and `age` referenced
let Person { name, ref age } = person;
}
```
 Wildcard pattern
----------------

 
>  **Syntax**  
>  *WildcardPattern* :  
>  `_`
> 
>  

 The *wildcard pattern* (an underscore symbol) matches any value. It is used to ignore values when they don't matter. Inside other patterns it matches a single data field (as opposed to the `..` which matches the remaining fields). Unlike identifier patterns, it does not copy, move or borrow the value it matches.

 Examples:

 
```
#![allow(unused)]
fn main() {
let x = 20;
let (a, _) = (10, x);   // the x is always matched by _
assert_eq!(a, 10);

// ignore a function/closure param
let real_part = |a: f64, _: f64| { a };

// ignore a field from a struct
struct RGBA {
   r: f32,
   g: f32,
   b: f32,
   a: f32,
}
let color = RGBA{r: 0.4, g: 0.1, b: 0.9, a: 0.5};
let RGBA{r: red, g: green, b: blue, a: _} = color;
assert_eq!(color.r, red);
assert_eq!(color.g, green);
assert_eq!(color.b, blue);

// accept any Some, with any value
let x = Some(10);
if let Some(_) = x {}
}
```
 The wildcard pattern is always irrefutable.

 Rest patterns
-------------

 
>  **Syntax**  
>  *RestPattern* :  
>  `..`
> 
>  

 The *rest pattern* (the `..` token) acts as a variable-length pattern which matches zero or more elements that haven't been matched already before and after. It may only be used in [tuple](#tuple-patterns), [tuple struct](#tuple-struct-patterns), and [slice](#slice-patterns) patterns, and may only appear once as one of the elements in those patterns. It is also allowed in an [identifier pattern](#identifier-patterns) for [slice patterns](#slice-patterns) only.

 The rest pattern is always irrefutable.

 Examples:

 
```
#![allow(unused)]
fn main() {
let words = vec!["a", "b", "c"];
let slice = &words[..];
match slice {
    [] => println!("slice is empty"),
    [one] => println!("single element {}", one),
    [head, tail @ ..] => println!("head={} tail={:?}", head, tail),
}

match slice {
    // Ignore everything but the last element, which must be "!".
    [.., "!"] => println!("!!!"),

    // `start` is a slice of everything except the last element, which must be "z".
    [start @ .., "z"] => println!("starts with: {:?}", start),

    // `end` is a slice of everything but the first element, which must be "a".
    ["a", end @ ..] => println!("ends with: {:?}", end),

    // 'whole' is the entire slice and `last` is the final element
    whole @ [.., last] => println!("the last element of {:?} is {}", whole, last),

    rest => println!("{:?}", rest),
}

if let [.., penultimate, _] = slice {
    println!("next to last is {}", penultimate);
}

let tuple = (1, 2, 3, 4, 5);
// Rest patterns may also be used in tuple and tuple struct patterns.
match tuple {
    (1, .., y, z) => println!("y={} z={}", y, z),
    (.., 5) => println!("tail must be 5"),
    (..) => println!("matches everything else"),
}
}
```
 Range patterns
--------------

 
>  **Syntax**  
>  *RangePattern* :  
>  *RangeInclusivePattern*  
>  | *RangeFromPattern*  
>  | *RangeToInclusivePattern*  
>  | *ObsoleteRangePattern*
> 
>  *RangeInclusivePattern* :  
>  *RangePatternBound* `..=` *RangePatternBound*
> 
>  *RangeFromPattern* :  
>  *RangePatternBound* `..`
> 
>  *RangeToInclusivePattern* :  
>  `..=` *RangePatternBound*
> 
>  *ObsoleteRangePattern* :  
>  *RangePatternBound* `...` *RangePatternBound*
> 
>  *RangePatternBound* :  
>  [CHAR\_LITERAL](tokens#character-literals)  
>  | [BYTE\_LITERAL](tokens#byte-literals)  
>  | `-`? [INTEGER\_LITERAL](tokens#integer-literals)  
>  | `-`? [FLOAT\_LITERAL](tokens#floating-point-literals)  
>  | [*PathExpression*](expressions/path-expr)
> 
>  

 *Range patterns* match scalar values within the range defined by their bounds. They comprise a *sigil* (one of `..`, `..=`, or `...`) and a bound on one or both sides. A bound on the left of the sigil is a *lower bound*. A bound on the right is an *upper bound*.

 A range pattern with both a lower and upper bound will match all values between and including both of its bounds. It is written as its lower bound, followed by `..=`, followed by its upper bound. The type of the range pattern is the type unification of its upper and lower bounds.

 For example, a pattern `'m'..='p'` will match only the values `'m'`, `'n'`, `'o'`, and `'p'`.

 The lower bound cannot be greater than the upper bound. That is, in `a..=b`, a ≤ b must be the case. For example, it is an error to have a range pattern `10..=0`.

 A range pattern with only a lower bound will match any value greater than or equal to the lower bound. It is written as its lower bound followed by `..`, and has the same type as its lower bound. For example, `1..` will match 1, 9, or 9001, or 9007199254740991 (if it is of an appropriate size), but not 0, and not negative numbers for signed integers.

 A range pattern with only an upper bound matches any value less than or equal to the upper bound. It is written as `..=` followed by its upper bound, and has the same type as its upper bound. For example, `..=10` will match 10, 1, 0, and for signed integer types, all negative values.

 Range patterns with only one bound cannot be used as the top-level pattern for subpatterns in [slice patterns](#slice-patterns).

 The bounds is written as one of:

 * A character, byte, integer, or float literal.
* A `-` followed by an integer or float literal.
* A [path](expressions/path-expr)

 If the bounds is written as a path, after macro resolution, the path must resolve to a constant item of the type `char`, an integer type, or a float type.

 The type and value of the bounds is dependent upon how it is written out. If the bounds is a [path](expressions/path-expr), the pattern has the type and value of the [constant](items/constant-items) the path resolves to. If it is a literal, it has the type and value of the corresponding [literal expression](expressions/literal-expr). If is a literal preceded by a `-`, it has the same type as the corresponding [literal expression](expressions/literal-expr) and the value of [negating](expressions/operator-expr#negation-operators) the value of the corresponding literal expression.

 Examples:

 
```
#![allow(unused)]
fn main() {
let c = 'f';
let valid_variable = match c {
    'a'..='z' => true,
    'A'..='Z' => true,
    'α'..='ω' => true,
    _ => false,
};

let ph = 10;
println!("{}", match ph {
    0..=6 => "acid",
    7 => "neutral",
    8..=14 => "base",
    _ => unreachable!(),
});

let uint: u32 = 5;
match uint {
    0 => "zero!",
    1.. => "positive number!",
};

// using paths to constants:
const TROPOSPHERE_MIN : u8 = 6;
const TROPOSPHERE_MAX : u8 = 20;

const STRATOSPHERE_MIN : u8 = TROPOSPHERE_MAX + 1;
const STRATOSPHERE_MAX : u8 = 50;

const MESOSPHERE_MIN : u8 = STRATOSPHERE_MAX + 1;
const MESOSPHERE_MAX : u8 = 85;

let altitude = 70;

println!("{}", match altitude {
    TROPOSPHERE_MIN..=TROPOSPHERE_MAX => "troposphere",
    STRATOSPHERE_MIN..=STRATOSPHERE_MAX => "stratosphere",
    MESOSPHERE_MIN..=MESOSPHERE_MAX => "mesosphere",
    _ => "outer space, maybe",
});

pub mod binary {
    pub const MEGA : u64 = 1024*1024;
    pub const GIGA : u64 = 1024*1024*1024;
}
let n_items = 20_832_425;
let bytes_per_item = 12;
if let size @ binary::MEGA..=binary::GIGA = n_items * bytes_per_item {
    println!("It fits and occupies {} bytes", size);
}

trait MaxValue {
    const MAX: u64;
}
impl MaxValue for u8 {
    const MAX: u64 = (1 << 8) - 1;
}
impl MaxValue for u16 {
    const MAX: u64 = (1 << 16) - 1;
}
impl MaxValue for u32 {
    const MAX: u64 = (1 << 32) - 1;
}
// using qualified paths:
println!("{}", match 0xfacade {
    0 ..= <u8 as MaxValue>::MAX => "fits in a u8",
    0 ..= <u16 as MaxValue>::MAX => "fits in a u16",
    0 ..= <u32 as MaxValue>::MAX => "fits in a u32",
    _ => "too big",
});
}
```
 Range patterns for fix-width integer and `char` types are irrefutable when they span the entire set of possible values of a type. For example, `0u8..=255u8` is irrefutable. The range of values for an integer type is the closed range from its minimum to maximum value. The range of values for a `char` type are precisely those ranges containing all Unicode Scalar Values: `'\u{0000}'..='\u{D7FF}'` and `'\u{E000}'..='\u{10FFFF}'`.

 Floating point range patterns are deprecated and may be removed in a future Rust release. See [issue #41620](https://github.com/rust-lang/rust/issues/41620) for more information.

 
>  **Edition Differences**: Before the 2021 edition, range patterns with both a lower and upper bound may also be written using `...` in place of `..=`, with the same meaning.
> 
>  

 
>  **Note**: Although range patterns use the same syntax as [range expressions](expressions/range-expr), there are no exclusive range patterns. That is, neither `x .. y` nor `.. x` are valid range patterns.
> 
>  

 Reference patterns
------------------

 
>  **Syntax**  
>  *ReferencePattern* :  
>  (`&`|`&&`) `mut`? [*PatternWithoutRange*](#patterns)
> 
>  

 Reference patterns dereference the pointers that are being matched and, thus, borrow them.

 For example, these two matches on `x: &i32` are equivalent:

 
```
#![allow(unused)]
fn main() {
let int_reference = &3;

let a = match *int_reference { 0 => "zero", _ => "some" };
let b = match int_reference { &0 => "zero", _ => "some" };

assert_eq!(a, b);
}
```
 The grammar production for reference patterns has to match the token `&&` to match a reference to a reference because it is a token by itself, not two `&` tokens.

 Adding the `mut` keyword dereferences a mutable reference. The mutability must match the mutability of the reference.

 Reference patterns are always irrefutable.

 Struct patterns
---------------

 
>  **Syntax**  
>  *StructPattern* :  
>  [*PathInExpression*](paths#paths-in-expressions) `{`  
>  *StructPatternElements* ?  
>  `}`
> 
>  *StructPatternElements* :  
>  *StructPatternFields* (`,` | `,` *StructPatternEtCetera*)?  
>  | *StructPatternEtCetera*
> 
>  *StructPatternFields* :  
>  *StructPatternField* (`,` *StructPatternField*) \*
> 
>  *StructPatternField* :  
>  [*OuterAttribute*](attributes) \*  
>  (  
>  [TUPLE\_INDEX](tokens#tuple-index) `:` [*Pattern*](#patterns)  
>  | [IDENTIFIER](identifiers) `:` [*Pattern*](#patterns)  
>  | `ref`? `mut`? [IDENTIFIER](identifiers)  
>  )
> 
>  *StructPatternEtCetera* :  
>  [*OuterAttribute*](attributes) \*  
>  `..`
> 
>  

 Struct patterns match struct values that match all criteria defined by its subpatterns. They are also used to [destructure](#destructuring) a struct.

 On a struct pattern, the fields are referenced by name, index (in the case of tuple structs) or ignored by use of `..`:

 
```
#![allow(unused)]
fn main() {
struct Point {
    x: u32,
    y: u32,
}
let s = Point {x: 1, y: 1};

match s {
    Point {x: 10, y: 20} => (),
    Point {y: 10, x: 20} => (),    // order doesn't matter
    Point {x: 10, ..} => (),
    Point {..} => (),
}

struct PointTuple (
    u32,
    u32,
);
let t = PointTuple(1, 2);

match t {
    PointTuple {0: 10, 1: 20} => (),
    PointTuple {1: 10, 0: 20} => (),   // order doesn't matter
    PointTuple {0: 10, ..} => (),
    PointTuple {..} => (),
}
}
```
 If `..` is not used, it is required to match all fields:

 
```
#![allow(unused)]
fn main() {
struct Struct {
   a: i32,
   b: char,
   c: bool,
}
let mut struct_value = Struct{a: 10, b: 'X', c: false};

match struct_value {
    Struct{a: 10, b: 'X', c: false} => (),
    Struct{a: 10, b: 'X', ref c} => (),
    Struct{a: 10, b: 'X', ref mut c} => (),
    Struct{a: 10, b: 'X', c: _} => (),
    Struct{a: _, b: _, c: _} => (),
}
}
```
 The `ref` and/or `mut` *IDENTIFIER* syntax matches any value and binds it to a variable with the same name as the given field.

 
```
#![allow(unused)]
fn main() {
struct Struct {
   a: i32,
   b: char,
   c: bool,
}
let struct_value = Struct{a: 10, b: 'X', c: false};

let Struct{a: x, b: y, c: z} = struct_value;          // destructure all fields
}
```
 A struct pattern is refutable when one of its subpatterns is refutable.

 Tuple struct patterns
---------------------

 
>  **Syntax**  
>  *TupleStructPattern* :  
>  [*PathInExpression*](paths#paths-in-expressions) `(` *TupleStructItems*? `)`
> 
>  *TupleStructItems* :  
>  [*Pattern*](#patterns) ( `,` [*Pattern*](#patterns) )\* `,`?
> 
>  

 Tuple struct patterns match tuple struct and enum values that match all criteria defined by its subpatterns. They are also used to [destructure](#destructuring) a tuple struct or enum value.

 A tuple struct pattern is refutable when one of its subpatterns is refutable.

 Tuple patterns
--------------

 
>  **Syntax**  
>  *TuplePattern* :  
>  `(` *TuplePatternItems*? `)`
> 
>  *TuplePatternItems* :  
>  [*Pattern*](#patterns) `,`  
>  | [*RestPattern*](#rest-patterns)  
>  | [*Pattern*](#patterns) (`,` [*Pattern*](#patterns))+ `,`?
> 
>  

 Tuple patterns match tuple values that match all criteria defined by its subpatterns. They are also used to [destructure](#destructuring) a tuple.

 The form `(..)` with a single [*RestPattern*](#rest-patterns) is a special form that does not require a comma, and matches a tuple of any size.

 The tuple pattern is refutable when one of its subpatterns is refutable.

 An example of using tuple patterns:

 
```
#![allow(unused)]
fn main() {
let pair = (10, "ten");
let (a, b) = pair;

assert_eq!(a, 10);
assert_eq!(b, "ten");
}
```
 Grouped patterns
----------------

 
>  **Syntax**  
>  *GroupedPattern* :  
>  `(` [*Pattern*](#patterns) `)`
> 
>  

 Enclosing a pattern in parentheses can be used to explicitly control the precedence of compound patterns. For example, a reference pattern next to a range pattern such as `&0..=5` is ambiguous and is not allowed, but can be expressed with parentheses.

 
```
#![allow(unused)]
fn main() {
let int_reference = &3;
match int_reference {
    &(0..=5) => (),
    _ => (),
}
}
```
 Slice patterns
--------------

 
>  **Syntax**  
>  *SlicePattern* :  
>  `[` *SlicePatternItems*? `]`
> 
>  *SlicePatternItems* :  
>  [*Pattern*](#patterns) (`,` [*Pattern*](#patterns))\* `,`?
> 
>  

 Slice patterns can match both arrays of fixed size and slices of dynamic size.

 
```
#![allow(unused)]
fn main() {
// Fixed size
let arr = [1, 2, 3];
match arr {
    [1, _, _] => "starts with one",
    [a, b, c] => "starts with something else",
};
}
```
 
```
#![allow(unused)]
fn main() {
// Dynamic size
let v = vec![1, 2, 3];
match v[..] {
    [a, b] => { /* this arm will not apply because the length doesn't match */ }
    [a, b, c] => { /* this arm will apply */ }
    _ => { /* this wildcard is required, since the length is not known statically */ }
};
}
```
 Slice patterns are irrefutable when matching an array as long as each element is irrefutable. When matching a slice, it is irrefutable only in the form with a single `..` [rest pattern](#rest-patterns) or [identifier pattern](#identifier-patterns) with the `..` rest pattern as a subpattern.

 Within a slice, a range pattern without both lower and upper bound must be enclosed in parentheses, as in `(a..)`, to clarify it is intended to match against a single slice element. A range pattern with both lower and upper bound, like `a..=b`, is not required to be enclosed in parentheses.

 Path patterns
-------------

 
>  **Syntax**  
>  *PathPattern* :  
>  [*PathExpression*](expressions/path-expr)
> 
>  

 *Path patterns* are patterns that refer either to constant values or to structs or enum variants that have no fields.

 Unqualified path patterns can refer to:

 * enum variants
* structs
* constants
* associated constants

 Qualified path patterns can only refer to associated constants.

 Constants cannot be a union type. Struct and enum constants must have `#[derive(PartialEq, Eq)]` (not merely implemented).

 Path patterns are irrefutable when they refer to structs or an enum variant when the enum has only one variant or a constant whose type is irrefutable. They are refutable when they refer to refutable constants or enum variants for enums with multiple variants.

 Or-patterns
-----------

 *Or-patterns* are patterns that match on one of two or more sub-patterns (for example `A | B | C`). They can nest arbitrarily. Syntactically, or-patterns are allowed in any of the places where other patterns are allowed (represented by the *Pattern* production), with the exceptions of `let`-bindings and function and closure arguments (represented by the *PatternNoTopAlt* production).

 ### Static semantics

 1. Given a pattern `p | q` at some depth for some arbitrary patterns `p` and `q`, the pattern is considered ill-formed if:


	* the type inferred for `p` does not unify with the type inferred for `q`, or
	* the same set of bindings are not introduced in `p` and `q`, or
	* the type of any two bindings with the same name in `p` and `q` do not unify with respect to types or binding modes.Unification of types is in all instances aforementioned exact and implicit [type coercions](type-coercions) do not apply.
2. When type checking an expression `match e_s { a_1 => e_1, ... a_n => e_n }`, for each match arm `a_i` which contains a pattern of form `p_i | q_i`, the pattern `p_i | q_i` is considered ill formed if, at the depth `d` where it exists the fragment of `e_s` at depth `d`, the type of the expression fragment does not unify with `p_i | q_i`.
3. With respect to exhaustiveness checking, a pattern `p | q` is considered to cover `p` as well as `q`. For some constructor `c(x, ..)` the distributive law applies such that `c(p | q, ..rest)` covers the same set of value as `c(p, ..rest) | c(q, ..rest)` does. This can be applied recursively until there are no more nested patterns of form `p | q` other than those that exist at the top level.

 Note that by *"constructor"* we do not refer to tuple struct patterns, but rather we refer to a pattern for any product type. This includes enum variants, tuple structs, structs with named fields, arrays, tuples, and slices.

 ### Dynamic semantics

 1. The dynamic semantics of pattern matching a scrutinee expression `e_s` against a pattern `c(p | q, ..rest)` at depth `d` where `c` is some constructor, `p` and `q` are arbitrary patterns, and `rest` is optionally any remaining potential factors in `c`, is defined as being the same as that of `c(p, ..rest) | c(q, ..rest)`.

 ### Precedence with other undelimited patterns

 As shown elsewhere in this chapter, there are several types of patterns that are syntactically undelimited, including identifier patterns, reference patterns, and or-patterns. Or-patterns always have the lowest-precedence. This allows us to reserve syntactic space for a possible future type ascription feature and also to reduce ambiguity. For example, `x @ A(..) | B(..)` will result in an error that `x` is not bound in all patterns. `&A(x) | B(x)` will result in a type mismatch between `x` in the different subpatterns.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/patterns.html?highlight=range>

Type system
===========



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/type-system.html>

Types
=====

 Every variable, item, and value in a Rust program has a type. The *type* of a *value* defines the interpretation of the memory holding it and the operations that may be performed on the value.

 Built-in types are tightly integrated into the language, in nontrivial ways that are not possible to emulate in user-defined types. User-defined types have limited capabilities.

 The list of types is:

 * Primitive types:
	+ [Boolean](types/boolean) — `bool`
	+ [Numeric](types/numeric) — integer and float
	+ [Textual](types/textual) — `char` and `str`
	+ [Never](types/never) — `!` — a type with no values
* Sequence types:
	+ [Tuple](types/tuple)
	+ [Array](types/array)
	+ [Slice](types/slice)
* User-defined types:
	+ [Struct](types/struct)
	+ [Enum](types/enum)
	+ [Union](types/union)
* Function types:
	+ [Functions](types/function-item)
	+ [Closures](types/closure)
* Pointer types:
	+ [References](types/pointer#shared-references-)
	+ [Raw pointers](types/pointer#raw-pointers-const-and-mut)
	+ [Function pointers](types/function-pointer)
* Trait types:
	+ [Trait objects](types/trait-object)
	+ [Impl trait](types/impl-trait)

 Type expressions
----------------

 
>  **Syntax**  
>  *Type* :  
>  *TypeNoBounds*  
>  | [*ImplTraitType*](types/impl-trait)  
>  | [*TraitObjectType*](types/trait-object)
> 
>  *TypeNoBounds* :  
>  [*ParenthesizedType*](types#parenthesized-types)  
>  | [*ImplTraitTypeOneBound*](types/impl-trait)  
>  | [*TraitObjectTypeOneBound*](types/trait-object)  
>  | [*TypePath*](paths#paths-in-types)  
>  | [*TupleType*](types/tuple#tuple-types)  
>  | [*NeverType*](types/never)  
>  | [*RawPointerType*](types/pointer#raw-pointers-const-and-mut)  
>  | [*ReferenceType*](types/pointer#shared-references-)  
>  | [*ArrayType*](types/array)  
>  | [*SliceType*](types/slice)  
>  | [*InferredType*](types/inferred)  
>  | [*QualifiedPathInType*](paths#qualified-paths)  
>  | [*BareFunctionType*](types/function-pointer)  
>  | [*MacroInvocation*](macros#macro-invocation)
> 
>  

 A *type expression* as defined in the *Type* grammar rule above is the syntax for referring to a type. It may refer to:

 * Sequence types ([tuple](types/tuple), [array](types/array), [slice](types/slice)).
* [Type paths](paths#paths-in-types) which can reference:
	+ Primitive types ([boolean](types/boolean), [numeric](types/numeric), [textual](types/textual)).
	+ Paths to an [item](items) ([struct](types/struct), [enum](types/enum), [union](types/union), [type alias](items/type-aliases), [trait](types/trait-object)).
	+ [`Self` path](paths#self-1) where `Self` is the implementing type.
	+ Generic [type parameters](types/parameters).
* Pointer types ([reference](types/pointer#shared-references-), [raw pointer](types/pointer#raw-pointers-const-and-mut), [function pointer](types/function-pointer)).
* The [inferred type](types/inferred) which asks the compiler to determine the type.
* [Parentheses](#parenthesized-types) which are used for disambiguation.
* Trait types: [Trait objects](types/trait-object) and [impl trait](types/impl-trait).
* The [never](types/never) type.
* [Macros](macros) which expand to a type expression.

 ### Parenthesized types

 
>  *ParenthesizedType* :  
>  `(` [*Type*](types#type-expressions) `)`
> 
>  

 In some situations the combination of types may be ambiguous. Use parentheses around a type to avoid ambiguity. For example, the `+` operator for [type boundaries](trait-bounds) within a [reference type](types/pointer#shared-references-) is unclear where the boundary applies, so the use of parentheses is required. Grammar rules that require this disambiguation use the [*TypeNoBounds*](types#type-expressions) rule instead of [*Type*](types#type-expressions).

 
```
#![allow(unused)]
fn main() {
use std::any::Any;
type T<'a> = &'a (dyn Any + Send);
}
```
 Recursive types
---------------

 Nominal types — [structs](types/struct), [enumerations](types/enum), and [unions](types/union) — may be recursive. That is, each `enum` variant or `struct` or `union` field may refer, directly or indirectly, to the enclosing `enum` or `struct` type itself. Such recursion has restrictions:

 * Recursive types must include a nominal type in the recursion (not mere [type aliases](items/type-aliases), or other structural types such as [arrays](types/array) or [tuples](types/tuple)). So `type Rec = &'static [Rec]` is not allowed.
* The size of a recursive type must be finite; in other words the recursive fields of the type must be [pointer types](types/pointer).

 An example of a *recursive* type and its use:

 
```
#![allow(unused)]
fn main() {
enum List<T> {
    Nil,
    Cons(T, Box<List<T>>)
}

let a: List<i32> = List::Cons(7, Box::new(List::Cons(13, Box::new(List::Nil))));
}
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/types.html>

Boolean type
============

 
```
#![allow(unused)]
fn main() {
let b: bool = true;
}
```
 The *boolean type* or *bool* is a primitive data type that can take on one of two values, called *true* and *false*.

 Values of this type may be created using a [literal expression](../expressions/literal-expr) using the keywords `true` and `false` corresponding to the value of the same name.

 This type is a part of the [language prelude](../names/preludes#language-prelude) with the [name](../names) `bool`.

 An object with the boolean type has a [size and alignment](../type-layout#size-and-alignment) of 1 each. The value false has the bit pattern `0x00` and the value true has the bit pattern `0x01`. It is [undefined behavior](../behavior-considered-undefined) for an object with the boolean type to have any other bit pattern.

 The boolean type is the type of many operands in various [expressions](../expressions):

 * The condition operand in [if expressions](../expressions/if-expr#if-expressions) and [while expressions](../expressions/loop-expr#predicate-loops)
* The operands in [lazy boolean operator expressions](../expressions/operator-expr#lazy-boolean-operators)

 
>  **Note**: The boolean type acts similarly to but is not an [enumerated type](enum). In practice, this mostly means that constructors are not associated to the type (e.g. `bool::true`).
> 
>  

 Like all primitives, the boolean type [implements](../items/implementations) the [traits](../items/traits) [`Clone`](../special-types-and-traits#clone), [`Copy`](../special-types-and-traits#copy), [`Sized`](../special-types-and-traits#sized), [`Send`](../special-types-and-traits#send), and [`Sync`](../special-types-and-traits#sync).

 
>  **Note**: See the [standard library docs](../../std/primitive.bool) for library operations.
> 
>  

 Operations on boolean values
----------------------------

 When using certain operator expressions with a boolean type for its operands, they evaluate using the rules of [boolean logic](https://en.wikipedia.org/wiki/Boolean_algebra).

 ### Logical not

 


| `b` | [`!b`](../expressions/operator-expr#negation-operators) |
| --- | --- |
| `true` | `false` |
| `false` | `true` |

  ### Logical or

 


| `a` | `b` | [`a | b`](../expressions/operator-expr#arithmetic-and-logical-binary-operators) |
| --- | --- | --- |
| `true` | `true` | `true` |
| `true` | `false` | `true` |
| `false` | `true` | `true` |
| `false` | `false` | `false` |

  ### Logical and

 


| `a` | `b` | [`a & b`](../expressions/operator-expr#arithmetic-and-logical-binary-operators) |
| --- | --- | --- |
| `true` | `true` | `true` |
| `true` | `false` | `false` |
| `false` | `true` | `false` |
| `false` | `false` | `false` |

  ### Logical xor

 


| `a` | `b` | [`a ^ b`](../expressions/operator-expr#arithmetic-and-logical-binary-operators) |
| --- | --- | --- |
| `true` | `true` | `false` |
| `true` | `false` | `true` |
| `false` | `true` | `true` |
| `false` | `false` | `false` |

  ### Comparisons

 


| `a` | `b` | [`a == b`](../expressions/operator-expr#comparison-operators) |
| --- | --- | --- |
| `true` | `true` | `true` |
| `true` | `false` | `false` |
| `false` | `true` | `false` |
| `false` | `false` | `true` |

 



| `a` | `b` | [`a > b`](../expressions/operator-expr#comparison-operators) |
| --- | --- | --- |
| `true` | `true` | `false` |
| `true` | `false` | `true` |
| `false` | `true` | `false` |
| `false` | `false` | `false` |

  * `a != b` is the same as `!(a == b)`
* `a >= b` is the same as `a == b | a > b`
* `a < b` is the same as `!(a >= b)`
* `a <= b` is the same as `a == b | a < b`



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/types/boolean.html>

Numeric types
=============

 Integer types
-------------

 The unsigned integer types consist of:

 


| Type | Minimum | Maximum |
| --- | --- | --- |
| `u8` | 0 | 28-1 |
| `u16` | 0 | 216-1 |
| `u32` | 0 | 232-1 |
| `u64` | 0 | 264-1 |
| `u128` | 0 | 2128-1 |

  The signed two's complement integer types consist of:

 


| Type | Minimum | Maximum |
| --- | --- | --- |
| `i8` | -(27) | 27-1 |
| `i16` | -(215) | 215-1 |
| `i32` | -(231) | 231-1 |
| `i64` | -(263) | 263-1 |
| `i128` | -(2127) | 2127-1 |

  Floating-point types
--------------------

 The IEEE 754-2008 "binary32" and "binary64" floating-point types are `f32` and `f64`, respectively.

 Machine-dependent integer types
-------------------------------

 The `usize` type is an unsigned integer type with the same number of bits as the platform's pointer type. It can represent every memory address in the process.

 The `isize` type is a signed integer type with the same number of bits as the platform's pointer type. The theoretical upper bound on object and array size is the maximum `isize` value. This ensures that `isize` can be used to calculate differences between pointers into an object or array and can address every byte within an object along with one byte past the end.

 `usize` and `isize` are at least 16-bits wide.

 
>  **Note**: Many pieces of Rust code may assume that pointers, `usize`, and `isize` are either 32-bit or 64-bit. As a consequence, 16-bit pointer support is limited and may require explicit care and acknowledgment from a library to support.
> 
>  



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/types/numeric.html>

Textual types
=============

 The types `char` and `str` hold textual data.

 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. It is immediate [Undefined Behavior](../behavior-considered-undefined) to create a `char` that falls outside this range. A `[char]` is effectively a UCS-4 / UTF-32 string of length 1.

 A value of type `str` is represented the same way as `[u8]`, it is 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](../behavior-considered-undefined) now or in the future.

 Since `str` is a [dynamically sized type](../dynamically-sized-types), it can only be instantiated through a pointer type, such as `&str`.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/types/textual.html>

Never type
==========

 
>  **Syntax**  
>  *NeverType* : `!`
> 
>  

 The never type `!` is a type with no values, representing the result of computations that never complete. Expressions of type `!` can be coerced into any other type.

 
```
let x: ! = panic!();
// Can be coerced into any type.
let y: u32 = x;
```
 **NB.** The never type was expected to be stabilized in 1.41, but due to some last minute regressions detected the stabilization was temporarily reverted. The `!` type can only appear in function return types presently. See [the tracking issue](https://github.com/rust-lang/rust/issues/35121) for more details.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/types/never.html>

Tuple types
===========

 
>  **Syntax**  
>  *TupleType* :  
>  `(` `)`  
>  | `(` ( [*Type*](../types#type-expressions) `,` )+ [*Type*](../types#type-expressions)? `)`
> 
>  

 *Tuple types* are a family of structural types[1](#1) for heterogeneous lists of other types.

 The syntax for a tuple type is a parenthesized, comma-separated list of types. 1-ary tuples require a comma after their element type to be disambiguated with a [parenthesized type](../types#parenthesized-types).

 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.

 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.

 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)
* `(f64, f64)`
* `(String, i32)`
* `(i32, String)` (different type from the previous example)
* `(i32, f64, Vec<String>, Option<bool>)`

 Values of this type are constructed using a [tuple expression](../expressions/tuple-expr#tuple-expressions). Furthermore, various expressions will produce the unit value if there is no other meaningful value for it to evaluate to. Tuple fields can be accessed by either a [tuple index expression](../expressions/tuple-expr#tuple-indexing-expressions) or [pattern matching](../patterns#tuple-patterns).

 
1 Structural types are always equivalent if their internal types are equivalent. For a nominal version of tuples, see [tuple structs](struct).

 

 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/types/tuple.html>

Array types
===========

 
>  **Syntax**  
>  *ArrayType* :  
>  `[` [*Type*](../types#type-expressions) `;` [*Expression*](../expressions) `]`
> 
>  

 An array is a fixed-size sequence of `N` elements of type `T`. The array type is written as `[T; N]`. The size is a [constant expression](../const_eval#constant-expressions) that evaluates to a [`usize`](numeric#machine-dependent-integer-types).

 Examples:

 
```
#![allow(unused)]
fn main() {
// A stack-allocated array
let array: [i32; 3] = [1, 2, 3];

// A heap-allocated array, coerced to a slice
let boxed_array: Box<[i32]> = Box::new([1, 2, 3]);
}
```
 All elements of arrays are always initialized, and access to an array is always bounds-checked in safe methods and operators.

 
>  Note: The [`Vec<T>`](../../std/vec/struct.vec) standard library type provides a heap-allocated resizable array type.
> 
>  



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/types/array.html>

Slice types
===========

 
>  **Syntax**  
>  *SliceType* :  
>  `[` [*Type*](../types#type-expressions) `]`
> 
>  

 A slice is a [dynamically sized type](../dynamically-sized-types) representing a 'view' into a sequence of elements of type `T`. The slice type is written as `[T]`.

 Slice types are generally used through pointer types. For example:

 * `&[T]`: a 'shared slice', often just called a 'slice'. It doesn't own the data it points to; it borrows it.
* `&mut [T]`: a 'mutable slice'. It mutably borrows the data it points to.
* `Box<[T]>`: a 'boxed slice'

 Examples:

 
```
#![allow(unused)]
fn main() {
// A heap-allocated array, coerced to a slice
let boxed_array: Box<[i32]> = Box::new([1, 2, 3]);

// A (shared) slice into an array
let slice: &[i32] = &boxed_array[..];
}
```
 All elements of slices are always initialized, and access to a slice is always bounds-checked in safe methods and operators.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/types/slice.html>

Struct types
============

 A `struct` *type* is a heterogeneous product of other types, called the *fields* of the type.[1](#structtype)

 New instances of a `struct` can be constructed with a [struct expression](../expressions/struct-expr).

 The memory layout of a `struct` is undefined by default to allow for compiler optimizations like field reordering, but it can be fixed with the [`repr` attribute](../type-layout#representations). In either case, fields may be given in any order in a corresponding struct *expression*; the resulting `struct` value will always have the same memory layout.

 The fields of a `struct` may be qualified by [visibility modifiers](../visibility-and-privacy), to allow access to data in a struct outside a module.

 A *tuple struct* type is just like a struct type, except that the fields are anonymous.

 A *unit-like struct* type is like a struct type, except that it has no fields. The one value constructed by the associated [struct expression](../expressions/struct-expr) is the only value that inhabits such a type.

 
1 `struct` types are analogous to `struct` types in C, the *record* types of the ML family, or the *struct* types of the Lisp family.

 

 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/types/struct.html>

Enumerated types
================

 An *enumerated type* is a nominal, heterogeneous disjoint union type, denoted by the name of an [`enum` item](../items/enumerations). [1](#enumtype)

 An [`enum` item](../items/enumerations) declares both the type and a number of *variants*, each of which is independently named and has the syntax of a struct, tuple struct or unit-like struct.

 New instances of an `enum` can be constructed with a [struct expression](../expressions/struct-expr).

 Any `enum` value consumes as much memory as the largest variant for its corresponding `enum` type, as well as the size needed to store a discriminant.

 Enum types cannot be denoted *structurally* as types, but must be denoted by named reference to an [`enum` item](../items/enumerations).

 
1 The `enum` type is analogous to a `data` constructor declaration in ML, or a *pick ADT* in Limbo.

 

 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/types/enum.html>

Union types
===========

 A *union type* is a nominal, heterogeneous C-like union, denoted by the name of a [`union` item](../items/unions).

 Unions have no notion of an "active field". Instead, every union access transmutes parts of the content of the union to the type of the accessed field. Since transmutes can cause unexpected or undefined behaviour, `unsafe` is required to read from a union field. Union field types are also restricted to a subset of types which ensures that they never need dropping. See the [item](../items/unions) documentation for further details.

 The memory layout of a `union` is undefined by default (in particular, fields do *not* have to be at offset 0), but the `#[repr(...)]` attribute can be used to fix a layout.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/types/union.html>

Function item types
===================

 When referred to, a function item, or the constructor of a tuple-like struct or enum variant, yields a zero-sized value of its *function item type*. That type explicitly identifies the function - its name, its type arguments, and its early-bound lifetime arguments (but not its late-bound lifetime arguments, which are only assigned when the function is called) - so the value does not need to contain an actual function pointer, and no indirection is needed when the function is called.

 There is no syntax that directly refers to a function item type, but the compiler will display the type as something like `fn(u32) -> i32 {fn_name}` in error messages.

 Because the function item type explicitly identifies the function, the item types of different functions - different items, or the same item with different generics - are distinct, and mixing them will create a type error:

 
```
#![allow(unused)]
fn main() {
fn foo<T>() { }
let x = &mut foo::<i32>;
*x = foo::<u32>; //~ ERROR mismatched types
}
```
 However, there is a [coercion](../type-coercions) from function items to [function pointers](function-pointer) with the same signature, which is triggered not only when a function item is used when a function pointer is directly expected, but also when different function item types with the same signature meet in different arms of the same `if` or `match`:

 
```
#![allow(unused)]
fn main() {
let want_i32 = false;
fn foo<T>() { }

// `foo_ptr_1` has function pointer type `fn()` here
let foo_ptr_1: fn() = foo::<i32>;

// ... and so does `foo_ptr_2` - this type-checks.
let foo_ptr_2 = if want_i32 {
    foo::<i32>
} else {
    foo::<u32>
};
}
```
 All function items implement [`Fn`](../../std/ops/trait.fn), [`FnMut`](../../std/ops/trait.fnmut), [`FnOnce`](../../std/ops/trait.fnonce), [`Copy`](../special-types-and-traits#copy), [`Clone`](../special-types-and-traits#clone), [`Send`](../special-types-and-traits#send), and [`Sync`](../special-types-and-traits#sync).



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/types/function-item.html>

Closure types
=============

 A [closure expression](../expressions/closure-expr) produces a closure value with a unique, anonymous type that cannot be written out. A closure type is approximately equivalent to a struct which contains the captured variables. For instance, the following closure:

 
```
#![allow(unused)]
fn main() {
fn f<F : FnOnce() -> String> (g: F) {
    println!("{}", g());
}

let mut s = String::from("foo");
let t = String::from("bar");

f(|| {
    s += &t;
    s
});
// Prints "foobar".
}
```
 generates a closure type roughly like the following:

 
```
struct Closure<'a> {
    s : String,
    t : &'a String,
}

impl<'a> FnOnce<()> for Closure<'a> {
    type Output = String;
    fn call_once(self) -> String {
        self.s += &*self.t;
        self.s
    }
}
```
 so that the call to `f` works as if it were:

 
```
f(Closure{s: s, t: &t});
```
 Capture modes
-------------

 The compiler prefers to capture a closed-over variable by immutable borrow, followed by unique immutable borrow (see below), by mutable borrow, and finally by move. It will pick the first choice of these that is compatible with how the captured variable is used inside the closure body. The compiler does not take surrounding code into account, such as the lifetimes of involved variables, or of the closure itself.

 If the `move` keyword is used, then all captures are by move or, for `Copy` types, by copy, regardless of whether a borrow would work. The `move` keyword is usually used to allow the closure to outlive the captured values, such as if the closure is being returned or used to spawn a new thread.

 Composite types such as structs, tuples, and enums are always captured entirely, not by individual fields. It may be necessary to borrow into a local variable in order to capture a single field:

 
```
#![allow(unused)]
fn main() {
use std::collections::HashSet;

struct SetVec {
    set: HashSet<u32>,
    vec: Vec<u32>
}

impl SetVec {
    fn populate(&mut self) {
        let vec = &mut self.vec;
        self.set.iter().for_each(|&n| {
            vec.push(n);
        })
    }
}
}
```
 If, instead, the closure were to use `self.vec` directly, then it would attempt to capture `self` by mutable reference. But since `self.set` is already borrowed to iterate over, the code would not compile.

 Unique immutable borrows in captures
------------------------------------

 Captures can occur by a special kind of borrow called a *unique immutable borrow*, which cannot be used anywhere else in the language and cannot be written out explicitly. It occurs when modifying the referent of a mutable reference, as in the following example:

 
```
#![allow(unused)]
fn main() {
let mut b = false;
let x = &mut b;
{
    let mut c = || { *x = true; };
    // The following line is an error:
    // let y = &x;
    c();
}
let z = &x;
}
```
 In this case, borrowing `x` mutably is not possible, because `x` is not `mut`. But at the same time, borrowing `x` immutably would make the assignment illegal, because a `& &mut` reference might not be unique, so it cannot safely be used to modify a value. So a unique immutable borrow is used: it borrows `x` immutably, but like a mutable borrow, it must be unique. In the above example, uncommenting the declaration of `y` will produce an error because it would violate the uniqueness of the closure's borrow of `x`; the declaration of z is valid because the closure's lifetime has expired at the end of the block, releasing the borrow.

 Call traits and coercions
-------------------------

 Closure types all implement [`FnOnce`](../../std/ops/trait.fnonce), indicating that they can be called once by consuming ownership of the closure. Additionally, some closures implement more specific call traits:

 * A closure which does not move out of any captured variables implements [`FnMut`](../../std/ops/trait.fnmut), indicating that it can be called by mutable reference.
* A closure which does not mutate or move out of any captured variables implements [`Fn`](../../std/ops/trait.fn), indicating that it can be called by shared reference.

 
>  Note: `move` closures may still implement [`Fn`](../../std/ops/trait.fn) or [`FnMut`](../../std/ops/trait.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.
> 
>  

 *Non-capturing closures* are closures that don't capture anything from their environment. They can be coerced to function pointers (e.g., `fn()`) with the matching signature.

 
```
#![allow(unused)]
fn main() {
let add = |x, y| x + y;

let mut x = add(5,7);

type Binop = fn(i32, i32) -> i32;
let bo: Binop = add;
x = bo(5,7);
}
```
 Other traits
------------

 All closure types implement [`Sized`](../special-types-and-traits#sized). Additionally, closure types implement the following traits if allowed to do so by the types of the captures it stores:

 * [`Clone`](../special-types-and-traits#clone)
* [`Copy`](../special-types-and-traits#copy)
* [`Sync`](../special-types-and-traits#sync)
* [`Send`](../special-types-and-traits#send)

 The rules for [`Send`](../special-types-and-traits#send) and [`Sync`](../special-types-and-traits#sync) match those for normal struct types, while [`Clone`](../special-types-and-traits#clone) and [`Copy`](../special-types-and-traits#copy) behave as if [derived](../attributes/derive). For [`Clone`](../special-types-and-traits#clone), the order of cloning of the captured variables is left unspecified.

 Because captures are often by reference, the following general rules arise:

 * A closure is [`Sync`](../special-types-and-traits#sync) if all captured variables are [`Sync`](../special-types-and-traits#sync).
* A closure is [`Send`](../special-types-and-traits#send) if all variables captured by non-unique immutable reference are [`Sync`](../special-types-and-traits#sync), and all values captured by unique immutable or mutable reference, copy, or move are [`Send`](../special-types-and-traits#send).
* A closure is [`Clone`](../special-types-and-traits#clone) or [`Copy`](../special-types-and-traits#copy) if it does not capture any values by unique immutable or mutable reference, and if all values it captures by copy or move are [`Clone`](../special-types-and-traits#clone) or [`Copy`](../special-types-and-traits#copy), respectively.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/types/closure.html>

Pointer types
=============

 All pointers are explicit first-class values. They can be moved or copied, stored into data structs, and returned from functions.

 References (`&` and `&mut`)
---------------------------

 
>  **Syntax**  
>  *ReferenceType* :  
>  `&` [*Lifetime*](../trait-bounds)? `mut`? [*TypeNoBounds*](../types#type-expressions)
> 
>  

 ### Shared references (`&`)

 Shared references point to memory which is owned by some other value. When a shared reference to a value is created, it prevents direct mutation of the value. [Interior mutability](../interior-mutability) provides an exception for this in certain circumstances. As the name suggests, any number of shared references to a value may exist. A shared reference type is written `&type`, or `&'a type` when you need to specify an explicit lifetime. Copying a reference is a "shallow" operation: it involves only copying the pointer itself, that is, pointers are `Copy`. Releasing a reference has no effect on the value it points to, but referencing of a [temporary value](../expressions#temporaries) will keep it alive during the scope of the reference itself.

 ### Mutable references (`&mut`)

 Mutable references point to memory which is owned by some other value. A mutable reference type is written `&mut type` or `&'a mut type`. A mutable reference (that hasn't been borrowed) is the only way to access the value it points to, so is not `Copy`.

 Raw pointers (`*const` and `*mut`)
----------------------------------

 
>  **Syntax**  
>  *RawPointerType* :  
>  `*` ( `mut` | `const` ) [*TypeNoBounds*](../types#type-expressions)
> 
>  

 Raw pointers are pointers without safety or liveness guarantees. Raw pointers are written as `*const T` or `*mut T`. For example `*const i32` means a raw pointer to a 32-bit integer. Copying or dropping a raw pointer has no effect on the lifecycle of any other value. Dereferencing a raw pointer is an [`unsafe` operation](../unsafety). This can also be used to convert a raw pointer to a reference by reborrowing it (`&*` or `&mut *`). Raw pointers are generally discouraged; they exist to support interoperability with foreign code, and writing performance-critical or low-level functions.

 When comparing raw pointers they are compared by their address, rather than by what they point to. When comparing raw pointers to [dynamically sized types](../dynamically-sized-types) they also have their additional data compared.

 Raw pointers can be created directly using [`core::ptr::addr_of!`](https://doc.rust-lang.org/core/ptr/macro.addr_of.html) for `*const` pointers and [`core::ptr::addr_of_mut!`](https://doc.rust-lang.org/core/ptr/macro.addr_of_mut.html) for `*mut` pointers.

 Smart Pointers
--------------

 The standard library contains additional 'smart pointer' types beyond references and raw pointers.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/types/pointer.html>

Function pointer types
======================

 
>  **Syntax**  
>  *BareFunctionType* :  
>  [*ForLifetimes*](../trait-bounds#higher-ranked-trait-bounds)? *FunctionTypeQualifiers* `fn`  
>  `(` *FunctionParametersMaybeNamedVariadic*? `)` *BareFunctionReturnType*?
> 
>  *FunctionTypeQualifiers*:  
>  `unsafe`? (`extern` [*Abi*](../items/functions)?)?
> 
>  *BareFunctionReturnType*:  
>  `->` [*TypeNoBounds*](../types#type-expressions)
> 
>  *FunctionParametersMaybeNamedVariadic* :  
>  *MaybeNamedFunctionParameters* | *MaybeNamedFunctionParametersVariadic*
> 
>  *MaybeNamedFunctionParameters* :  
>  *MaybeNamedParam* ( `,` *MaybeNamedParam* )\* `,`?
> 
>  *MaybeNamedParam* :  
>  [*OuterAttribute*](../attributes)\* ( ( [IDENTIFIER](../identifiers) | `_` ) `:` )? [*Type*](../types#type-expressions)
> 
>  *MaybeNamedFunctionParametersVariadic* :  
>  ( *MaybeNamedParam* `,` )\* *MaybeNamedParam* `,` [*OuterAttribute*](../attributes)\* `...`
> 
>  

 Function pointer types, written using the `fn` keyword, refer to a function whose identity is not necessarily known at compile-time. They can be created via a coercion from both [function items](function-item) and non-capturing [closures](closure).

 The `unsafe` qualifier indicates that the type's value is an [unsafe function](../unsafe-keyword), and the `extern` qualifier indicates it is an [extern function](../items/functions#extern-function-qualifier).

 Variadic parameters can only be specified with [`extern`](../items/external-blocks) function types with the `"C"` or `"cdecl"` calling convention.

 An example where `Binop` is defined as a function pointer type:

 
```
#![allow(unused)]
fn main() {
fn add(x: i32, y: i32) -> i32 {
    x + y
}

let mut x = add(5,7);

type Binop = fn(i32, i32) -> i32;
let bo: Binop = add;
x = bo(5,7);
}
```
 Attributes on function pointer parameters
-----------------------------------------

 Attributes on function pointer parameters follow the same rules and restrictions as [regular function parameters](../items/functions#attributes-on-function-parameters).



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/types/function-pointer.html>

Trait objects
=============

 
>  **Syntax**  
>  *TraitObjectType* :  
>  `dyn`? [*TypeParamBounds*](../trait-bounds)
> 
>  *TraitObjectTypeOneBound* :  
>  `dyn`? [*TraitBound*](../trait-bounds)
> 
>  

 A *trait object* is an opaque value of another type that implements a set of traits. The set of traits is made up of an [object safe](../items/traits#object-safety) *base trait* plus any number of [auto traits](../special-types-and-traits#auto-traits).

 Trait objects implement the base trait, its auto traits, and any [supertraits](../items/traits#supertraits) of the base trait.

 Trait objects are written as the keyword `dyn` followed by a set of trait bounds, but with the following restrictions on the trait bounds. All traits except the first trait must be auto traits, there may not be more than one lifetime, and opt-out bounds (e.g. `?Sized`) are not allowed. Furthermore, paths to traits may be parenthesized.

 For example, given a trait `Trait`, the following are all trait objects:

 * `dyn Trait`
* `dyn Trait + Send`
* `dyn Trait + Send + Sync`
* `dyn Trait + 'static`
* `dyn Trait + Send + 'static`
* `dyn Trait +`
* `dyn 'static + Trait`.
* `dyn (Trait)`

 
>  **Edition Differences**: Before the 2021 edition, the `dyn` keyword may be omitted.
> 
>  Note: For clarity, it is recommended to always use the `dyn` keyword on your trait objects unless your codebase supports compiling with Rust 1.26 or lower.
> 
>  

 
>  **Edition Differences**: In the 2015 edition, if the first bound of the trait object is a path that starts with `::`, then the `dyn` will be treated as a part of the path. The first path can be put in parenthesis to get around this. As such, if you want a trait object with the trait `::your_module::Trait`, you should write it as `dyn (::your_module::Trait)`.
> 
>  Beginning in the 2018 edition, `dyn` is a true keyword and is not allowed in paths, so the parentheses are not necessary.
> 
>  

 Two trait object types alias each other if the base traits alias each other and if the sets of auto traits are the same and the lifetime bounds are the same. For example, `dyn Trait + Send + UnwindSafe` is the same as `dyn Trait + UnwindSafe + Send`.

 Due to the opaqueness of which concrete type the value is of, trait objects are [dynamically sized types](../dynamically-sized-types). Like all DSTs, trait objects are used behind some type of pointer; for example `&dyn SomeTrait` or `Box<dyn SomeTrait>`. Each instance of a pointer to a trait object includes:

 * a pointer to an instance of a type `T` that implements `SomeTrait`
* a *virtual method table*, often just called a *vtable*, which contains, for each method of `SomeTrait` and its [supertraits](../items/traits#supertraits) that `T` implements, a pointer to `T`'s implementation (i.e. a function pointer).

 The purpose of trait objects is to permit "late binding" of methods. Calling a method on a trait object results in virtual dispatch at runtime: that is, a function pointer is loaded from the trait object vtable and invoked indirectly. The actual implementation for each vtable entry can vary on an object-by-object basis.

 An example of a trait object:

 
```
trait Printable {
    fn stringify(&self) -> String;
}

impl Printable for i32 {
    fn stringify(&self) -> String { self.to_string() }
}

fn print(a: Box<dyn Printable>) {
    println!("{}", a.stringify());
}

fn main() {
    print(Box::new(10) as Box<dyn Printable>);
}
```
 In this example, the trait `Printable` occurs as a trait object in both the type signature of `print`, and the cast expression in `main`.

 Trait Object Lifetime Bounds
----------------------------

 Since a trait object can contain references, the lifetimes of those references need to be expressed as part of the trait object. This lifetime is written as `Trait + 'a`. There are [defaults](../lifetime-elision#default-trait-object-lifetimes) that allow this lifetime to usually be inferred with a sensible choice.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/types/trait-object.html>

Impl trait
==========

 
>  **Syntax**  
>  *ImplTraitType* : `impl` [*TypeParamBounds*](../trait-bounds)
> 
>  *ImplTraitTypeOneBound* : `impl` [*TraitBound*](../trait-bounds)
> 
>  

 `impl Trait` provides ways to specify unnamed but concrete types that implement a specific trait. It can appear in two sorts of places: argument position (where it can act as an anonymous type parameter to functions), and return position (where it can act as an abstract return type).

 
```
#![allow(unused)]
fn main() {
trait Trait {}
impl Trait for () {}

// argument position: anonymous type parameter
fn foo(arg: impl Trait) {
}

// return position: abstract return type
fn bar() -> impl Trait {
}
}
```
 Anonymous type parameters
-------------------------

 
>  Note: This is often called "impl Trait in argument position". (The term "parameter" is more correct here, but "impl Trait in argument position" is the phrasing used during the development of this feature, and it remains in parts of the implementation.)
> 
>  

 Functions can use `impl` followed by a set of trait bounds to declare a parameter as having an anonymous type. The caller must provide a type that satisfies the bounds declared by the anonymous type parameter, and the function can only use the methods available through the trait bounds of the anonymous type parameter.

 For example, these two forms are almost equivalent:

 
```
#![allow(unused)]
fn main() {
trait Trait {}

// generic type parameter
fn with_generic_type<T: Trait>(arg: T) {
}

// impl Trait in argument position
fn with_impl_trait(arg: impl Trait) {
}
}
```
 That is, `impl Trait` in argument position is syntactic sugar for a generic type parameter like `<T: Trait>`, except that the type is anonymous and doesn't appear in the [*GenericParams*](../items/generics) list.

 
>  **Note:** For function parameters, generic type parameters and `impl Trait` are not exactly equivalent. With a generic parameter such as `<T: Trait>`, the caller has the option to explicitly specify the generic argument for `T` at the call site using [*GenericArgs*](../paths#paths-in-expressions), for example, `foo::<usize>(1)`. If `impl Trait` is the type of *any* function parameter, then the caller can't ever provide any generic arguments when calling that function. This includes generic arguments for the return type or any const generics.
> 
>  Therefore, changing the function signature from either one to the other can constitute a breaking change for the callers of a function.
> 
>  

 Abstract return types
---------------------

 
>  Note: This is often called "impl Trait in return position".
> 
>  

 Functions can use `impl Trait` to return an abstract return type. These types stand in for another concrete type where the caller may only use the methods declared by the specified `Trait`. Each possible return value from the function must resolve to the same concrete type.

 `impl Trait` in return position allows a function to return an unboxed abstract type. This is particularly useful with [closures](closure) and iterators. For example, closures have a unique, un-writable type. Previously, the only way to return a closure from a function was to use a [trait object](trait-object):

 
```
#![allow(unused)]
fn main() {
fn returns_closure() -> Box<dyn Fn(i32) -> i32> {
    Box::new(|x| x + 1)
}
}
```
 This could incur performance penalties from heap allocation and dynamic dispatch. It wasn't possible to fully specify the type of the closure, only to use the `Fn` trait. That means that the trait object is necessary. However, with `impl Trait`, it is possible to write this more simply:

 
```
#![allow(unused)]
fn main() {
fn returns_closure() -> impl Fn(i32) -> i32 {
    |x| x + 1
}
}
```
 which also avoids the drawbacks of using a boxed trait object.

 Similarly, the concrete types of iterators could become very complex, incorporating the types of all previous iterators in a chain. Returning `impl Iterator` means that a function only exposes the `Iterator` trait as a bound on its return type, instead of explicitly specifying all of the other iterator types involved.

 ### Differences between generics and `impl Trait` in return position

 In argument position, `impl Trait` is very similar in semantics to a generic type parameter. However, there are significant differences between the two in return position. With `impl Trait`, unlike with a generic type parameter, the function chooses the return type, and the caller cannot choose the return type.

 The function:

 
```
#![allow(unused)]
fn main() {
trait Trait {}
fn foo<T: Trait>() -> T {
    // ...
panic!()
}
}
```
 allows the caller to determine the return type, `T`, and the function returns that type.

 The function:

 
```
#![allow(unused)]
fn main() {
trait Trait {}
impl Trait for () {}
fn foo() -> impl Trait {
    // ...
}
}
```
 doesn't allow the caller to determine the return type. Instead, the function chooses the return type, but only promises that it will implement `Trait`.

 Limitations
-----------

 `impl Trait` can only appear as a parameter or return type of a free or inherent function. It cannot appear inside implementations of traits, nor can it be the type of a let binding or appear inside a type alias.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/types/impl-trait.html>

Type parameters
===============

 Within the body of an item that has type parameter declarations, the names of its type parameters are types:

 
```
#![allow(unused)]
fn main() {
fn to_vec<A: Clone>(xs: &[A]) -> Vec<A> {
    if xs.is_empty() {
        return vec![];
    }
    let first: A = xs[0].clone();
    let mut rest: Vec<A> = to_vec(&xs[1..]);
    rest.insert(0, first);
    rest
}
}
```
 Here, `first` has type `A`, referring to `to_vec`'s `A` type parameter; and `rest` has type `Vec<A>`, a vector with element type `A`.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/types/parameters.html>

Inferred type
=============

 
>  **Syntax**  
>  *InferredType* : `_`
> 
>  

 The inferred type asks the compiler to infer the type if possible based on the surrounding information available. It cannot be used in item signatures. It is often used in generic arguments:

 
```
#![allow(unused)]
fn main() {
let x: Vec<_> = (0..10).collect();
}
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/types/inferred.html>

Dynamically Sized Types
=======================

 Most types have a fixed size that is known at compile time and implement the trait [`Sized`](special-types-and-traits#sized). A type with a size that is known only at run-time is called a *dynamically sized type* (*DST*) or, informally, an unsized type. [Slices](types/slice) and [trait objects](types/trait-object) are two examples of DSTs. Such types can only be used in certain cases:

 * [Pointer types](types/pointer) to DSTs are sized but have twice the size of pointers to sized types
	+ Pointers to slices also store the number of elements of the slice.
	+ Pointers to trait objects also store a pointer to a vtable.
* DSTs can be provided as type arguments to generic type parameters having the special `?Sized` bound. They can also be used for associated type definitions when the corresponding associated type declaration has a `?Sized` bound. By default, any type parameter or associated type has a `Sized` bound, unless it is relaxed using `?Sized`.
* Traits may be implemented for DSTs. Unlike with generic type parameters, `Self: ?Sized` is the default in trait definitions.
* Structs may contain a DST as the last field; this makes the struct itself a DST.

 
>  **Note**: <variables>, function parameters, [const](items/constant-items) items, and [static](items/static-items) items must be `Sized`.
> 
>  



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/dynamically-sized-types.html>

Type Layout
===========

 The layout of a type is its size, alignment, and the relative offsets of its fields. For enums, how the discriminant is laid out and interpreted is also part of type layout.

 Type layout can be changed with each compilation. Instead of trying to document exactly what is done, we only document what is guaranteed today.

 Size and Alignment
------------------

 All values have an alignment and size.

 The *alignment* of a value specifies what addresses are valid to store the value at. A value of alignment `n` must only be stored at an address that is a multiple of n. For example, a value with an alignment of 2 must be stored at an even address, while a value with an alignment of 1 can be stored at any address. Alignment is measured in bytes, and must be at least 1, and always a power of 2. The alignment of a value can be checked with the [`align_of_val`](../std/mem/fn.align_of_val) function.

 The *size* of a value is the offset in bytes between successive elements in an array with that item type including alignment padding. The size of a value is always a multiple of its alignment. Note that some types are zero-sized; 0 is considered a multiple of any alignment (for example, on some platforms, the type `[u16; 0]` has size 0 and alignment 2). The size of a value can be checked with the [`size_of_val`](../std/mem/fn.size_of_val) function.

 Types where all values have the same size and alignment, and both are known at compile time, implement the [`Sized`](../std/marker/trait.sized) trait and can be checked with the [`size_of`](../std/mem/fn.size_of) and [`align_of`](../std/mem/fn.align_of) functions. Types that are not [`Sized`](../std/marker/trait.sized) are known as [dynamically sized types](dynamically-sized-types). Since all values of a `Sized` type share the same size and alignment, we refer to those shared values as the size of the type and the alignment of the type respectively.

 Primitive Data Layout
---------------------

 The size of most primitives is given in this table.

 


| Type | `size_of::<Type>()` |
| --- | --- |
| `bool` | 1 |
| `u8` / `i8` | 1 |
| `u16` / `i16` | 2 |
| `u32` / `i32` | 4 |
| `u64` / `i64` | 8 |
| `u128` / `i128` | 16 |
| `f32` | 4 |
| `f64` | 8 |
| `char` | 4 |

  `usize` and `isize` have a size big enough to contain every address on the target platform. For example, on a 32 bit target, this is 4 bytes and on a 64 bit target, this is 8 bytes.

 Most primitives are generally aligned to their size, although this is platform-specific behavior. In particular, on x86 u64 and f64 are only aligned to 32 bits.

 Pointers and References Layout
------------------------------

 Pointers and references have the same layout. Mutability of the pointer or reference does not change the layout.

 Pointers to sized types have the same size and alignment as `usize`.

 Pointers to unsized types are sized. The size and alignment is guaranteed to be at least equal to the size and alignment of a pointer.

 
>  Note: Though you should not rely on this, all pointers to DSTs are currently twice the size of the size of `usize` and have the same alignment.
> 
>  

 Array Layout
------------

 An array of `[T; N]` has a size of `size_of::<T>() * N` and the same alignment of `T`. Arrays are laid out so that the zero-based `nth` element of the array is offset from the start of the array by `n * size_of::<T>()` bytes.

 Slice Layout
------------

 Slices have the same layout as the section of the array they slice.

 
>  Note: This is about the raw `[T]` type, not pointers (`&[T]`, `Box<[T]>`, etc.) to slices.
> 
>  

 
`str` Layout
-------------

 String slices are a UTF-8 representation of characters that have the same layout as slices of type `[u8]`.

 Tuple Layout
------------

 Tuples are laid out according to the [default representation](#the-default-representation).

 The exception to this is the unit tuple (`()`), which is guaranteed as a zero-sized type to have a size of 0 and an alignment of 1.

 Trait Object Layout
-------------------

 Trait objects have the same layout as the value the trait object is of.

 
>  Note: This is about the raw trait object types, not pointers (`&dyn Trait`, `Box<dyn Trait>`, etc.) to trait objects.
> 
>  

 Closure Layout
--------------

 Closures have no layout guarantees.

 Representations
---------------

 All user-defined composite types (`struct`s, `enum`s, and `union`s) have a *representation* that specifies what the layout is for the type. The possible representations for a type are:

 * [Default](#the-default-representation)
* [`C`](#the-c-representation)
* The [primitive representations](#primitive-representations)
* [`transparent`](#the-transparent-representation)

 The representation of a type can be changed by applying the `repr` attribute to it. The following example shows a struct with a `C` representation.

 
```
#![allow(unused)]
fn main() {
#[repr(C)]
struct ThreeInts {
    first: i16,
    second: i8,
    third: i32
}
}
```
 The alignment may be raised or lowered with the `align` and `packed` modifiers respectively. They alter the representation specified in the attribute. If no representation is specified, the default one is altered.

 
```
#![allow(unused)]
fn main() {
// Default representation, alignment lowered to 2.
#[repr(packed(2))]
struct PackedStruct {
    first: i16,
    second: i8,
    third: i32
}

// C representation, alignment raised to 8
#[repr(C, align(8))]
struct AlignedStruct {
    first: i16,
    second: i8,
    third: i32
}
}
```
 
>  Note: As a consequence of the representation being an attribute on the item, the representation does not depend on generic parameters. Any two types with the same name have the same representation. For example, `Foo<Bar>` and `Foo<Baz>` both have the same representation.
> 
>  

 The representation of a type can change the padding between fields, but does not change the layout of the fields themselves. For example, a struct with a `C` representation that contains a struct `Inner` with the default representation will not change the layout of `Inner`.

 ### The Default Representation

 Nominal types without a `repr` attribute have the default representation. Informally, this representation is also called the `rust` representation.

 The only data layout guarantees made by this representation are those required for soundness. They are:

 1. The fields are properly aligned.
2. The fields do not overlap.
3. The alignment of the type is at least the maximum alignment of its fields.

 Formally, the first guarantee means that the offset of any field is divisible by that field's alignment. The second guarantee means that the fields can be ordered such that the offset plus the size of any field is less than or equal to the offset of the next field in the ordering. The ordering does not have to be the same as the order in which the fields are specified in the declaration of the type.

 Be aware that the second guarantee does not imply that the fields have distinct addresses: zero-sized types may have the same address as other fields in the same struct.

 There are no other guarantees of data layout made by this representation.

 ### The `C` Representation

 The `C` representation is designed for dual purposes. One purpose is for creating types that are interoperable with the C Language. The second purpose is to create types that you can soundly perform operations on that rely on data layout such as reinterpreting values as a different type.

 Because of this dual purpose, it is possible to create types that are not useful for interfacing with the C programming language.

 This representation can be applied to structs, unions, and enums. The exception is [zero-variant enums](items/enumerations#zero-variant-enums) for which the `C` representation is an error.

 #### 
`#[repr(C)]` Structs

 The alignment of the struct is the alignment of the most-aligned field in it.

 The size and offset of fields is determined by the following algorithm.

 Start with a current offset of 0 bytes.

 For each field in declaration order in the struct, first determine the size and alignment of the field. If the current offset is not a multiple of the field's alignment, then add padding bytes to the current offset until it is a multiple of the field's alignment. The offset for the field is what the current offset is now. Then increase the current offset by the size of the field.

 Finally, the size of the struct is the current offset rounded up to the nearest multiple of the struct's alignment.

 Here is this algorithm described in pseudocode.

 
```
/// Returns the amount of padding needed after `offset` to ensure that the
/// following address will be aligned to `alignment`.
fn padding_needed_for(offset: usize, alignment: usize) -> usize {
    let misalignment = offset % alignment;
    if misalignment > 0 {
        // round up to next multiple of `alignment`
        alignment - misalignment
    } else {
        // already a multiple of `alignment`
        0
    }
}

struct.alignment = struct.fields().map(|field| field.alignment).max();

let current_offset = 0;

for field in struct.fields_in_declaration_order() {
    // Increase the current offset so that it's a multiple of the alignment
    // of this field. For the first field, this will always be zero.
    // The skipped bytes are called padding bytes.
    current_offset += padding_needed_for(current_offset, field.alignment);

    struct[field].offset = current_offset;

    current_offset += field.size;
}

struct.size = current_offset + padding_needed_for(current_offset, struct.alignment);
```
  Warning: This pseudocode uses a naive algorithm that ignores overflow issues for the sake of clarity. To perform memory layout computations in actual code, use [`Layout`](../std/alloc/struct.layout).

  
>  Note: This algorithm can produce zero-sized structs. In C, an empty struct declaration like `struct Foo { }` is illegal. However, both gcc and clang support options to enable such structs, and assign them size zero. C++, in contrast, gives empty structs a size of 1, unless they are inherited from or they are fields that have the `[[no_unique_address]]` attribute, in which case they do not increase the overall size of the struct.
> 
>  

 #### 
`#[repr(C)]` Unions

 A union declared with `#[repr(C)]` will have the same size and alignment as an equivalent C union declaration in the C language for the target platform. The union will have a size of the maximum size of all of its fields rounded to its alignment, and an alignment of the maximum alignment of all of its fields. These maximums may come from different fields.

 
```
#![allow(unused)]
fn main() {
#[repr(C)]
union Union {
    f1: u16,
    f2: [u8; 4],
}

assert_eq!(std::mem::size_of::<Union>(), 4);  // From f2
assert_eq!(std::mem::align_of::<Union>(), 2); // From f1

#[repr(C)]
union SizeRoundedUp {
   a: u32,
   b: [u16; 3],
}

assert_eq!(std::mem::size_of::<SizeRoundedUp>(), 8);  // Size of 6 from b,
                                                      // rounded up to 8 from
                                                      // alignment of a.
assert_eq!(std::mem::align_of::<SizeRoundedUp>(), 4); // From a
}
```
 #### 
`#[repr(C)]` Field-less Enums

 For [field-less enums](items/enumerations#field-less-enum), the `C` representation has the size and alignment of the default `enum` size and alignment for the target platform's C ABI.

 
>  Note: The enum representation in C is implementation defined, so this is really a "best guess". In particular, this may be incorrect when the C code of interest is compiled with certain flags.
> 
>  

  Warning: There are crucial differences between an `enum` in the C language and Rust's [field-less enums](items/enumerations#field-less-enum) with this representation. An `enum` in C is mostly a `typedef` plus some named constants; in other words, an object of an `enum` type can hold any integer value. For example, this is often used for bitflags in `C`. In contrast, Rust’s [field-less enums](items/enumerations#field-less-enum) can only legally hold the discriminant values, everything else is [undefined behavior](behavior-considered-undefined). Therefore, using a field-less enum in FFI to model a C `enum` is often wrong.

  #### 
`#[repr(C)]` Enums With Fields

 The representation of a `repr(C)` enum with fields is a `repr(C)` struct with two fields, also called a "tagged union" in C:

 * a `repr(C)` version of the enum with all fields removed ("the tag")
* a `repr(C)` union of `repr(C)` structs for the fields of each variant that had them ("the payload")

 
>  Note: Due to the representation of `repr(C)` structs and unions, if a variant has a single field there is no difference between putting that field directly in the union or wrapping it in a struct; any system which wishes to manipulate such an `enum`'s representation may therefore use whichever form is more convenient or consistent for them.
> 
>  

 
```
#![allow(unused)]
fn main() {
// This Enum has the same representation as ...
#[repr(C)]
enum MyEnum {
    A(u32),
    B(f32, u64),
    C { x: u32, y: u8 },
    D,
 }

// ... this struct.
#[repr(C)]
struct MyEnumRepr {
    tag: MyEnumDiscriminant,
    payload: MyEnumFields,
}

// This is the discriminant enum.
#[repr(C)]
enum MyEnumDiscriminant { A, B, C, D }

// This is the variant union.
#[repr(C)]
union MyEnumFields {
    A: MyAFields,
    B: MyBFields,
    C: MyCFields,
    D: MyDFields,
}

#[repr(C)]
#[derive(Copy, Clone)]
struct MyAFields(u32);

#[repr(C)]
#[derive(Copy, Clone)]
struct MyBFields(f32, u64);

#[repr(C)]
#[derive(Copy, Clone)]
struct MyCFields { x: u32, y: u8 }

// This struct could be omitted (it is a zero-sized type), and it must be in
// C/C++ headers.
#[repr(C)]
#[derive(Copy, Clone)]
struct MyDFields;
}
```
 
>  Note: `union`s with non-`Copy` fields are unstable, see [55149](https://github.com/rust-lang/rust/issues/55149).
> 
>  

 ### Primitive representations

 The *primitive representations* are the representations with the same names as the primitive integer types. That is: `u8`, `u16`, `u32`, `u64`, `u128`, `usize`, `i8`, `i16`, `i32`, `i64`, `i128`, and `isize`.

 Primitive representations can only be applied to enumerations and have different behavior whether the enum has fields or no fields. It is an error for [zero-variant enums](items/enumerations#zero-variant-enums) to have a primitive representation. Combining two primitive representations together is an error.

 #### Primitive Representation of Field-less Enums

 For [field-less enums](items/enumerations#field-less-enum), primitive representations set the size and alignment to be the same as the primitive type of the same name. For example, a field-less enum with a `u8` representation can only have discriminants between 0 and 255 inclusive.

 #### Primitive Representation of Enums With Fields

 The representation of a primitive representation enum is a `repr(C)` union of `repr(C)` structs for each variant with a field. The first field of each struct in the union is the primitive representation version of the enum with all fields removed ("the tag") and the remaining fields are the fields of that variant.

 
>  Note: This representation is unchanged if the tag is given its own member in the union, should that make manipulation more clear for you (although to follow the C++ standard the tag member should be wrapped in a `struct`).
> 
>  

 
```
#![allow(unused)]
fn main() {
// This enum has the same representation as ...
#[repr(u8)]
enum MyEnum {
    A(u32),
    B(f32, u64),
    C { x: u32, y: u8 },
    D,
 }

// ... this union.
#[repr(C)]
union MyEnumRepr {
    A: MyVariantA,
    B: MyVariantB,
    C: MyVariantC,
    D: MyVariantD,
}

// This is the discriminant enum.
#[repr(u8)]
#[derive(Copy, Clone)]
enum MyEnumDiscriminant { A, B, C, D }

#[repr(C)]
#[derive(Clone, Copy)]
struct MyVariantA(MyEnumDiscriminant, u32);

#[repr(C)]
#[derive(Clone, Copy)]
struct MyVariantB(MyEnumDiscriminant, f32, u64);

#[repr(C)]
#[derive(Clone, Copy)]
struct MyVariantC { tag: MyEnumDiscriminant, x: u32, y: u8 }

#[repr(C)]
#[derive(Clone, Copy)]
struct MyVariantD(MyEnumDiscriminant);
}
```
 
>  Note: `union`s with non-`Copy` fields are unstable, see [55149](https://github.com/rust-lang/rust/issues/55149).
> 
>  

 #### Combining primitive representations of enums with fields and `#[repr(C)]`

 For enums with fields, it is also possible to combine `repr(C)` and a primitive representation (e.g., `repr(C, u8)`). This modifies the [`repr(C)`](#reprc-enums-with-fields) by changing the representation of the discriminant enum to the chosen primitive instead. So, if you chose the `u8` representation, then the discriminant enum would have a size and alignment of 1 byte.

 The discriminant enum from the example [earlier](#reprc-enums-with-fields) then becomes:

 
```
#![allow(unused)]
fn main() {
#[repr(C, u8)] // `u8` was added
enum MyEnum {
    A(u32),
    B(f32, u64),
    C { x: u32, y: u8 },
    D,
 }

// ...

#[repr(u8)] // So `u8` is used here instead of `C`
enum MyEnumDiscriminant { A, B, C, D }

// ...
}
```
 For example, with a `repr(C, u8)` enum it is not possible to have 257 unique discriminants ("tags") whereas the same enum with only a `repr(C)` attribute will compile without any problems.

 Using a primitive representation in addition to `repr(C)` can change the size of an enum from the `repr(C)` form:

 
```
#![allow(unused)]
fn main() {
#[repr(C)]
enum EnumC {
    Variant0(u8),
    Variant1,
}

#[repr(C, u8)]
enum Enum8 {
    Variant0(u8),
    Variant1,
}

#[repr(C, u16)]
enum Enum16 {
    Variant0(u8),
    Variant1,
}

// The size of the C representation is platform dependant
assert_eq!(std::mem::size_of::<EnumC>(), 8);
// One byte for the discriminant and one byte for the value in Enum8::Variant0
assert_eq!(std::mem::size_of::<Enum8>(), 2);
// Two bytes for the discriminant and one byte for the value in Enum16::Variant0
// plus one byte of padding.
assert_eq!(std::mem::size_of::<Enum16>(), 4);
}
```
 ### The alignment modifiers

 The `align` and `packed` modifiers can be used to respectively raise or lower the alignment of `struct`s and `union`s. `packed` may also alter the padding between fields (although it will not alter the padding inside of any field).

 The alignment is specified as an integer parameter in the form of `#[repr(align(x))]` or `#[repr(packed(x))]`. The alignment value must be a power of two from 1 up to 229. For `packed`, if no value is given, as in `#[repr(packed)]`, then the value is 1.

 For `align`, if the specified alignment is less than the alignment of the type without the `align` modifier, then the alignment is unaffected.

 For `packed`, if the specified alignment is greater than the type's alignment without the `packed` modifier, then the alignment and layout is unaffected. The alignments of each field, for the purpose of positioning fields, is the smaller of the specified alignment and the alignment of the field's type. Inter-field padding is guaranteed to be the minimum required in order to satisfy each field's (possibly altered) alignment (although note that, on its own, `packed` does not provide any guarantee about field ordering). An important consequence of these rules is that a type with `#[repr(packed(1))]` (or `#[repr(packed)]`) will have no inter-field padding.

 The `align` and `packed` modifiers cannot be applied on the same type and a `packed` type cannot transitively contain another `align`ed type. `align` and `packed` may only be applied to the [default](#the-default-representation) and [`C`](#the-c-representation) representations.

 The `align` modifier can also be applied on an `enum`. When it is, the effect on the `enum`'s alignment is the same as if the `enum` was wrapped in a newtype `struct` with the same `align` modifier.

  ***Warning:*** Dereferencing an unaligned pointer is [undefined behavior](behavior-considered-undefined) and it is possible to [safely create unaligned pointers to `packed` fields](https://github.com/rust-lang/rust/issues/27060). Like all ways to create undefined behavior in safe Rust, this is a bug.

  ### The `transparent` Representation

 The `transparent` representation can only be used on a [`struct`](items/structs) or an [`enum`](items/enumerations) with a single variant that has:

 * a single field with non-zero size, and
* any number of fields with size 0 and alignment 1 (e.g. [`PhantomData<T>`](special-types-and-traits#phantomdatat)).

 Structs and enums with this representation have the same layout and ABI as the single non-zero sized field.

 This is different than the `C` representation because a struct with the `C` representation will always have the ABI of a `C` `struct` while, for example, a struct with the `transparent` representation with a primitive field will have the ABI of the primitive field.

 Because this representation delegates type layout to another type, it cannot be used with any other representation.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/type-layout.html>

Interior Mutability
===================

 Sometimes a type needs to be mutated while having multiple aliases. In Rust this is achieved using a pattern called *interior mutability*. A type has interior mutability if its internal state can be changed through a [shared reference](types/pointer#shared-references-) to it. This goes against the usual [requirement](behavior-considered-undefined) that the value pointed to by a shared reference is not mutated.

 [`std::cell::UnsafeCell<T>`](../std/cell/struct.unsafecell) type is the only allowed way to disable this requirement. When `UnsafeCell<T>` is immutably aliased, it is still safe to mutate, or obtain a mutable reference to, the `T` it contains. As with all other types, it is undefined behavior to have multiple `&mut UnsafeCell<T>` aliases.

 Other types with interior mutability can be created by using `UnsafeCell<T>` as a field. The standard library provides a variety of types that provide safe interior mutability APIs. For example, [`std::cell::RefCell<T>`](../std/cell/struct.refcell) uses run-time borrow checks to ensure the usual rules around multiple references. The [`std::sync::atomic`](../std/sync/atomic/index) module contains types that wrap a value that is only accessed with atomic operations, allowing the value to be shared and mutated across threads.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/interior-mutability.html>

Subtyping and Variance
======================

 Subtyping is implicit and can occur at any stage in type checking or inference. Subtyping is restricted to two cases: variance with respect to lifetimes and between types with higher ranked lifetimes. If we were to erase lifetimes from types, then the only subtyping would be due to type equality.

 Consider the following example: string literals always have `'static` lifetime. Nevertheless, we can assign `s` to `t`:

 
```
#![allow(unused)]
fn main() {
fn bar<'a>() {
    let s: &'static str = "hi";
    let t: &'a str = s;
}
}
```
 Since `'static` outlives the lifetime parameter `'a`, `&'static str` is a subtype of `&'a str`.

 [Higher-ranked](https://doc.rust-lang.org/nomicon/hrtb.html) [function pointers](types/function-pointer) and [trait objects](types/trait-object) have another subtype relation. They are subtypes of types that are given by substitutions of the higher-ranked lifetimes. Some examples:

 
```
#![allow(unused)]
fn main() {
// Here 'a is substituted for 'static
let subtype: &(for<'a> fn(&'a i32) -> &'a i32) = &((|x| x) as fn(&_) -> &_);
let supertype: &(fn(&'static i32) -> &'static i32) = subtype;

// This works similarly for trait objects
let subtype: &(dyn for<'a> Fn(&'a i32) -> &'a i32) = &|x| x;
let supertype: &(dyn Fn(&'static i32) -> &'static i32) = subtype;

// We can also substitute one higher-ranked lifetime for another
let subtype: &(for<'a, 'b> fn(&'a i32, &'b i32))= &((|x, y| {}) as fn(&_, &_));
let supertype: &for<'c> fn(&'c i32, &'c i32) = subtype;
}
```
 Variance
--------

 Variance is a property that generic types have with respect to their arguments. A generic type's *variance* in a parameter is how the subtyping of the parameter affects the subtyping of the type.

 * `F<T>` is *covariant* over `T` if `T` being a subtype of `U` implies that `F<T>` is a subtype of `F<U>` (subtyping "passes through")
* `F<T>` is *contravariant* over `T` if `T` being a subtype of `U` implies that `F<U>` is a subtype of `F<T>`
* `F<T>` is *invariant* over `T` otherwise (no subtyping relation can be derived)

 Variance of types is automatically determined as follows

 


| Type | Variance in `'a` | Variance in `T` |
| --- | --- | --- |
| `&'a T` | covariant | covariant |
| `&'a mut T` | covariant | invariant |
| `*const T` |  | covariant |
| `*mut T` |  | invariant |
| `[T]` and `[T; n]` |  | covariant |
| `fn() -> T` |  | covariant |
| `fn(T) -> ()` |  | contravariant |
| `std::cell::UnsafeCell<T>` |  | invariant |
| `std::marker::PhantomData<T>` |  | covariant |
| `dyn Trait<T> + 'a` | covariant | invariant |

  The variance of other `struct`, `enum`, and `union` types is decided by looking at the variance of the types of their fields. If the parameter is used in positions with different variances then the parameter is invariant. For example the following struct is covariant in `'a` and `T` and invariant in `'b`, `'c`, and `U`.

 
```
#![allow(unused)]
fn main() {
use std::cell::UnsafeCell;
struct Variance<'a, 'b, 'c, T, U: 'a> {
    x: &'a U,               // This makes `Variance` covariant in 'a, and would
                            // make it covariant in U, but U is used later
    y: *const T,            // Covariant in T
    z: UnsafeCell<&'b f64>, // Invariant in 'b
    w: *mut U,              // Invariant in U, makes the whole struct invariant

    f: fn(&'c ()) -> &'c () // Both co- and contravariant, makes 'c invariant
                            // in the struct.
}
}
```
 When used outside of an `struct`, `enum`, or `union`, the variance for parameters is checked at each location separately.

 
```
#![allow(unused)]
fn main() {
use std::cell::UnsafeCell;
fn generic_tuple<'short, 'long: 'short>(
    // 'long is used inside of a tuple in both a co- and invariant position.
    x: (&'long u32, UnsafeCell<&'long u32>),
) {
    // As the variance at these positions is computed separately,
    // we can freely shrink 'long in the covariant position.
    let _: (&'short u32, UnsafeCell<&'long u32>) = x;
}

fn takes_fn_ptr<'short, 'middle: 'short>(
    // 'middle is used in both a co- and contravariant position.
    f: fn(&'middle ()) -> &'middle (),
) {
    // As the variance at these positions is computed separately,
    // we can freely shrink 'middle in the covariant position
    // and extend it in the contravariant position.
    let _: fn(&'static ()) -> &'short () = f;
}
}
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/subtyping.html>

Trait and lifetime bounds
=========================

 
>  **Syntax**  
>  *TypeParamBounds* :  
>  *TypeParamBound* ( `+` *TypeParamBound* )\* `+`?
> 
>  *TypeParamBound* :  
>  *Lifetime* | *TraitBound*
> 
>  *TraitBound* :  
>  `?`? [*ForLifetimes*](#higher-ranked-trait-bounds)? [*TypePath*](paths#paths-in-types)  
>  | `(` `?`? [*ForLifetimes*](#higher-ranked-trait-bounds)? [*TypePath*](paths#paths-in-types) `)`
> 
>  *LifetimeBounds* :  
>  ( *Lifetime* `+` )\* *Lifetime*?
> 
>  *Lifetime* :  
>  [LIFETIME\_OR\_LABEL](tokens#lifetimes-and-loop-labels)  
>  | `'static`  
>  | `'_`
> 
>  

 [Trait](items/traits#trait-bounds) and lifetime bounds provide a way for [generic items](items/generics) to restrict which types and lifetimes are used as their parameters. Bounds can be provided on any type in a [where clause](items/generics#where-clauses). There are also shorter forms for certain common cases:

 * Bounds written after declaring a [generic parameter](items/generics): `fn f<A: Copy>() {}` is the same as `fn f<A>() where A: Copy {}`.
* In trait declarations as [supertraits](items/traits#supertraits): `trait Circle : Shape {}` is equivalent to `trait Circle where Self : Shape {}`.
* In trait declarations as bounds on [associated types](items/associated-items#associated-types): `trait A { type B: Copy; }` is equivalent to `trait A where Self::B: Copy { type B; }`.

 Bounds on an item must be satisfied when using the item. When type checking and borrow checking a generic item, the bounds can be used to determine that a trait is implemented for a type. For example, given `Ty: Trait`

 * In the body of a generic function, methods from `Trait` can be called on `Ty` values. Likewise associated constants on the `Trait` can be used.
* Associated types from `Trait` can be used.
* Generic functions and types with a `T: Trait` bounds can be used with `Ty` being used for `T`.

 
```
#![allow(unused)]
fn main() {
type Surface = i32;
trait Shape {
    fn draw(&self, surface: Surface);
    fn name() -> &'static str;
}

fn draw_twice<T: Shape>(surface: Surface, sh: T) {
    sh.draw(surface);           // Can call method because T: Shape
    sh.draw(surface);
}

fn copy_and_draw_twice<T: Copy>(surface: Surface, sh: T) where T: Shape {
    let shape_copy = sh;        // doesn't move sh because T: Copy
    draw_twice(surface, sh);    // Can use generic function because T: Shape
}

struct Figure<S: Shape>(S, S);

fn name_figure<U: Shape>(
    figure: Figure<U>,          // Type Figure<U> is well-formed because U: Shape
) {
    println!(
        "Figure of two {}",
        U::name(),              // Can use associated function
    );
}
}
```
 Bounds that don't use the item's parameters or [higher-ranked lifetimes](#higher-ranked-trait-bounds) are checked when the item is defined. It is an error for such a bound to be false.

 [`Copy`](special-types-and-traits#copy), [`Clone`](special-types-and-traits#clone), and [`Sized`](special-types-and-traits#sized) bounds are also checked for certain generic types when using the item, even if the use does not provide a concrete type. It is an error to have `Copy` or `Clone` as a bound on a mutable reference, [trait object](types/trait-object), or [slice](types/slice). It is an error to have `Sized` as a bound on a trait object or slice.

 
```
#![allow(unused)]
fn main() {
struct A<'a, T>
where
    i32: Default,           // Allowed, but not useful
    i32: Iterator,          // Error: `i32` is not an iterator
    &'a mut T: Copy,        // (at use) Error: the trait bound is not satisfied
    [T]: Sized,             // (at use) Error: size cannot be known at compilation
{
    f: &'a T,
}
struct UsesA<'a, T>(A<'a, T>);
}
```
 Trait and lifetime bounds are also used to name [trait objects](types/trait-object).

 `?Sized`
--------

 `?` is only used to relax the implicit [`Sized`](special-types-and-traits#sized) trait bound for [type parameters](types/parameters) or [associated types](items/associated-items#associated-types). `?Sized` may not be used as a bound for other types.

 Lifetime bounds
---------------

 Lifetime bounds can be applied to types or to other lifetimes. The bound `'a: 'b` is usually read as `'a` *outlives* `'b`. `'a: 'b` means that `'a` lasts at least as long as `'b`, so a reference `&'a ()` is valid whenever `&'b ()` is valid.

 
```
#![allow(unused)]
fn main() {
fn f<'a, 'b>(x: &'a i32, mut y: &'b i32) where 'a: 'b {
    y = x;                      // &'a i32 is a subtype of &'b i32 because 'a: 'b
    let r: &'b &'a i32 = &&0;   // &'b &'a i32 is well formed because 'a: 'b
}
}
```
 `T: 'a` means that all lifetime parameters of `T` outlive `'a`. For example, if `'a` is an unconstrained lifetime parameter, then `i32: 'static` and `&'static str: 'a` are satisfied, but `Vec<&'a ()>: 'static` is not.

 Higher-ranked trait bounds
--------------------------

 
>  *ForLifetimes* :  
>  `for` [*GenericParams*](items/generics)
> 
>  

 Trait bounds may be *higher ranked* over lifetimes. These bounds specify a bound that is true *for all* lifetimes. For example, a bound such as `for<'a> &'a T: PartialEq<i32>` would require an implementation like

 
```
#![allow(unused)]
fn main() {
struct T;
impl<'a> PartialEq<i32> for &'a T {
    // ...
   fn eq(&self, other: &i32) -> bool {true}
}
}
```
 and could then be used to compare a `&'a T` with any lifetime to an `i32`.

 Only a higher-ranked bound can be used here, because the lifetime of the reference is shorter than any possible lifetime parameter on the function:

 
```
#![allow(unused)]
fn main() {
fn call_on_ref_zero<F>(f: F) where for<'a> F: Fn(&'a i32) {
    let zero = 0;
    f(&zero);
}
}
```
 Higher-ranked lifetimes may also be specified just before the trait: the only difference is the scope of the lifetime parameter, which extends only to the end of the following trait instead of the whole bound. This function is equivalent to the last one.

 
```
#![allow(unused)]
fn main() {
fn call_on_ref_zero<F>(f: F) where F: for<'a> Fn(&'a i32) {
    let zero = 0;
    f(&zero);
}
}
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/trait-bounds.html>

Type coercions
==============

 **Type coercions** are implicit operations that change the type of a value. They happen automatically at specific locations and are highly restricted in what types actually coerce.

 Any conversions allowed by coercion can also be explicitly performed by the [type cast operator](expressions/operator-expr#type-cast-expressions), `as`.

 Coercions are originally defined in [RFC 401](https://github.com/rust-lang/rfcs/blob/master/text/0401-coercions.md) and expanded upon in [RFC 1558](https://github.com/rust-lang/rfcs/blob/master/text/1558-closure-to-fn-coercion.md).

 Coercion sites
--------------

 A coercion can only occur at certain coercion sites in a program; these are typically places where the desired type is explicit or can be derived by propagation from explicit types (without type inference). Possible coercion sites are:

 * `let` statements where an explicit type is given.

 For example, `&mut 42` is coerced to have type `&i8` in the following:

 
```
#![allow(unused)]
fn main() {
let _: &i8 = &mut 42;
}
```
* `static` and `const` item declarations (similar to `let` statements).
* Arguments for function calls

 The value being coerced is the actual parameter, and it is coerced to the type of the formal parameter.

 For example, `&mut 42` is coerced to have type `&i8` in the following:

 
```
fn bar(_: &i8) { }

fn main() {
    bar(&mut 42);
}
```
 For method calls, the receiver (`self` parameter) can only take advantage of [unsized coercions](#unsized-coercions).
* Instantiations of struct, union, or enum variant fields

 For example, `&mut 42` is coerced to have type `&i8` in the following:

 
```
struct Foo<'a> { x: &'a i8 }

fn main() {
    Foo { x: &mut 42 };
}
```
* Function results—either the final line of a block if it is not semicolon-terminated or any expression in a `return` statement

 For example, `x` is coerced to have type `&dyn Display` in the following:

 
```
#![allow(unused)]
fn main() {
use std::fmt::Display;
fn foo(x: &u32) -> &dyn Display {
    x
}
}
```

 If the expression in one of these coercion sites is a coercion-propagating expression, then the relevant sub-expressions in that expression are also coercion sites. Propagation recurses from these new coercion sites. Propagating expressions and their relevant sub-expressions are:

 * Array literals, where the array has type `[U; n]`. Each sub-expression in the array literal is a coercion site for coercion to type `U`.
* Array literals with repeating syntax, where the array has type `[U; n]`. The repeated sub-expression is a coercion site for coercion to type `U`.
* Tuples, where a tuple is a coercion site to type `(U_0, U_1, ..., U_n)`. Each sub-expression is a coercion site to the respective type, e.g. the zeroth sub-expression is a coercion site to type `U_0`.
* Parenthesized sub-expressions (`(e)`): if the expression has type `U`, then the sub-expression is a coercion site to `U`.
* Blocks: if a block has type `U`, then the last expression in the block (if it is not semicolon-terminated) is a coercion site to `U`. This includes blocks which are part of control flow statements, such as `if`/`else`, if the block has a known type.

 Coercion types
--------------

 Coercion is allowed between the following types:

 * `T` to `U` if `T` is a [subtype](subtyping) of `U` (*reflexive case*)
* `T_1` to `T_3` where `T_1` coerces to `T_2` and `T_2` coerces to `T_3` (*transitive case*)

 Note that this is not fully supported yet.
* `&mut T` to `&T`
* `*mut T` to `*const T`
* `&T` to `*const T`
* `&mut T` to `*mut T`
* `&T` or `&mut T` to `&U` if `T` implements `Deref<Target = U>`. For example:

 
```
use std::ops::Deref;

struct CharContainer {
    value: char,
}

impl Deref for CharContainer {
    type Target = char;

    fn deref<'a>(&'a self) -> &'a char {
        &self.value
    }
}

fn foo(arg: &char) {}

fn main() {
    let x = &mut CharContainer { value: 'y' };
    foo(x); //&mut CharContainer is coerced to &char.
}
```
* `&mut T` to `&mut U` if `T` implements `DerefMut<Target = U>`.
* TyCtor(`T`) to TyCtor(`U`), where TyCtor(`T`) is one of


	+ `&T`
	+ `&mut T`
	+ `*const T`
	+ `*mut T`
	+ `Box<T>`and where `U` can be obtained from `T` by [unsized coercion](#unsized-coercions).
* Function item types to `fn` pointers
* Non capturing closures to `fn` pointers
* `!` to any `T`

 ### Unsized Coercions

 The following coercions are called `unsized coercions`, since they relate to converting sized types to unsized types, and are permitted in a few cases where other coercions are not, as described above. They can still happen anywhere else a coercion can occur.

 Two traits, [`Unsize`](../std/marker/trait.unsize) and [`CoerceUnsized`](../std/ops/trait.coerceunsized), are used to assist in this process and expose it for library use. The following coercions are built-ins and, if `T` can be coerced to `U` with one of them, then an implementation of `Unsize<U>` for `T` will be provided:

 * `[T; n]` to `[T]`.
* `T` to `dyn U`, when `T` implements `U + Sized`, and `U` is [object safe](items/traits#object-safety).
* `Foo<..., T, ...>` to `Foo<..., U, ...>`, when:


	+ `Foo` is a struct.
	+ `T` implements `Unsize<U>`.
	+ The last field of `Foo` has a type involving `T`.
	+ If that field has type `Bar<T>`, then `Bar<T>` implements `Unsized<Bar<U>>`.
	+ T is not part of the type of any other fields.

 Additionally, a type `Foo<T>` can implement `CoerceUnsized<Foo<U>>` when `T` implements `Unsize<U>` or `CoerceUnsized<Foo<U>>`. This allows it to provide a unsized coercion to `Foo<U>`.

 
>  Note: While the definition of the unsized coercions and their implementation has been stabilized, the traits themselves are not yet stable and therefore can't be used directly in stable Rust.
> 
>  

 Least upper bound coercions
---------------------------

 In some contexts, the compiler must coerce together multiple types to try and find the most general type. This is called a "Least Upper Bound" coercion. LUB coercion is used and only used in the following situations:

 * To find the common type for a series of if branches.
* To find the common type for a series of match arms.
* To find the common type for array elements.
* To find the type for the return type of a closure with multiple return statements.
* To check the type for the return type of a function with multiple return statements.

 In each such case, there are a set of types `T0..Tn` to be mutually coerced to some target type `T_t`, which is unknown to start. Computing the LUB coercion is done iteratively. The target type `T_t` begins as the type `T0`. For each new type `Ti`, we consider whether

 * If `Ti` can be coerced to the current target type `T_t`, then no change is made.
* Otherwise, check whether `T_t` can be coerced to `Ti`; if so, the `T_t` is changed to `Ti`. (This check is also conditioned on whether all of the source expressions considered thus far have implicit coercions.)
* If not, try to compute a mutual supertype of `T_t` and `Ti`, which will become the new target type.

 ### Examples:

 
```
#![allow(unused)]
fn main() {
let (a, b, c) = (0, 1, 2);
// For if branches
let bar = if true {
    a
} else if false {
    b
} else {
    c
};

// For match arms
let baw = match 42 {
    0 => a,
    1 => b,
    _ => c,
};

// For array elements
let bax = [a, b, c];

// For closure with multiple return statements
let clo = || {
    if true {
        a
    } else if false {
        b
    } else {
        c
    }
};
let baz = clo();

// For type checking of function with multiple return statements
fn foo() -> i32 {
    let (a, b, c) = (0, 1, 2);
    match 42 {
        0 => a,
        1 => b,
        _ => c,
    }
}
}
```
 In these examples, types of the `ba*` are found by LUB coercion. And the compiler checks whether LUB coercion result of `a`, `b`, `c` is `i32` in the processing of the function `foo`.

 ### Caveat

 This description is obviously informal. Making it more precise is expected to proceed as part of a general effort to specify the Rust type checker more precisely.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/type-coercions.html>

Destructors
===========

 When an [initialized](glossary#initialized) [variable](variables) or [temporary](expressions#temporaries) goes out of [scope](#drop-scopes), its *destructor* is run, or it is *dropped*. [Assignment](expressions/operator-expr#assignment-expressions) also runs the destructor of its left-hand operand, if it's initialized. If a variable has been partially initialized, only its initialized fields are dropped.

 The destructor of a type `T` consists of:

 1. If `T: Drop`, calling [`<T as std::ops::Drop>::drop`](../std/ops/trait.drop#tymethod.drop)
2. Recursively running the destructor of all of its fields.
	* The fields of a [struct](types/struct) are dropped in declaration order.
	* The fields of the active [enum variant](types/enum) are dropped in declaration order.
	* The fields of a [tuple](types/tuple) are dropped in order.
	* The elements of an [array](types/array) or owned [slice](types/slice) are dropped from the first element to the last.
	* The variables that a [closure](types/closure) captures by move are dropped in an unspecified order.
	* [Trait objects](types/trait-object) run the destructor of the underlying type.
	* Other types don't result in any further drops.

 If a destructor must be run manually, such as when implementing your own smart pointer, [`std::ptr::drop_in_place`](../std/ptr/fn.drop_in_place) can be used.

 Some examples:

 
```
#![allow(unused)]
fn main() {
struct PrintOnDrop(&'static str);

impl Drop for PrintOnDrop {
    fn drop(&mut self) {
        println!("{}", self.0);
    }
}

let mut overwritten = PrintOnDrop("drops when overwritten");
overwritten = PrintOnDrop("drops when scope ends");

let tuple = (PrintOnDrop("Tuple first"), PrintOnDrop("Tuple second"));

let moved;
// No destructor run on assignment.
moved = PrintOnDrop("Drops when moved");
// Drops now, but is then uninitialized.
moved;

// Uninitialized does not drop.
let uninitialized: PrintOnDrop;

// After a partial move, only the remaining fields are dropped.
let mut partial_move = (PrintOnDrop("first"), PrintOnDrop("forgotten"));
// Perform a partial move, leaving only `partial_move.0` initialized.
core::mem::forget(partial_move.1);
// When partial_move's scope ends, only the first field is dropped.
}
```
 Drop scopes
-----------

 Each variable or temporary is associated to a *drop scope*. When control flow leaves a drop scope all variables associated to that scope are dropped in reverse order of declaration (for variables) or creation (for temporaries).

 Drop scopes are determined after replacing [`for`](expressions/loop-expr#iterator-loops), [`if let`](expressions/if-expr#if-let-expressions), and [`while let`](expressions/loop-expr#predicate-pattern-loops) expressions with the equivalent expressions using [`match`](expressions/match-expr). Overloaded operators are not distinguished from built-in operators and [binding modes](patterns#binding-modes) are not considered.

 Given a function, or closure, there are drop scopes for:

 * The entire function
* Each [statement](statements)
* Each [expression](expressions)
* Each block, including the function body
	+ In the case of a [block expression](expressions/block-expr), the scope for the block and the expression are the same scope.
* Each arm of a `match` expression

 Drop scopes are nested within one another as follows. When multiple scopes are left at once, such as when returning from a function, variables are dropped from the inside outwards.

 * The entire function scope is the outer most scope.
* The function body block is contained within the scope of the entire function.
* The parent of the expression in an expression statement is the scope of the statement.
* The parent of the initializer of a [`let` statement](statements#let-statements) is the `let` statement's scope.
* The parent of a statement scope is the scope of the block that contains the statement.
* The parent of the expression for a `match` guard is the scope of the arm that the guard is for.
* The parent of the expression after the `=>` in a `match` expression is the scope of the arm that it's in.
* The parent of the arm scope is the scope of the `match` expression that it belongs to.
* The parent of all other scopes is the scope of the immediately enclosing expression.

 ### Scopes of function parameters

 All function parameters are in the scope of the entire function body, so are dropped last when evaluating the function. Each actual function parameter is dropped after any bindings introduced in that parameter's pattern.

 
```
#![allow(unused)]
fn main() {
struct PrintOnDrop(&'static str);
impl Drop for PrintOnDrop {
    fn drop(&mut self) {
        println!("drop({})", self.0);
    }
}
// Drops `y`, then the second parameter, then `x`, then the first parameter
fn patterns_in_parameters(
    (x, _): (PrintOnDrop, PrintOnDrop),
    (_, y): (PrintOnDrop, PrintOnDrop),
) {}

// drop order is 3 2 0 1
patterns_in_parameters(
    (PrintOnDrop("0"), PrintOnDrop("1")),
    (PrintOnDrop("2"), PrintOnDrop("3")),
);
}
```
 ### Scopes of local variables

 Local variables declared in a `let` statement are associated to the scope of the block that contains the `let` statement. Local variables declared in a `match` expression are associated to the arm scope of the `match` arm that they are declared in.

 
```
#![allow(unused)]
fn main() {
struct PrintOnDrop(&'static str);
impl Drop for PrintOnDrop {
    fn drop(&mut self) {
        println!("drop({})", self.0);
    }
}
let declared_first = PrintOnDrop("Dropped last in outer scope");
{
    let declared_in_block = PrintOnDrop("Dropped in inner scope");
}
let declared_last = PrintOnDrop("Dropped first in outer scope");
}
```
 If multiple patterns are used in the same arm for a `match` expression, then an unspecified pattern will be used to determine the drop order.

 ### Temporary scopes

 The *temporary scope* of an expression is the scope that is used for the temporary variable that holds the result of that expression when used in a [place context](expressions#place-expressions-and-value-expressions), unless it is [promoted](destructors#constant-promotion).

 Apart from lifetime extension, the temporary scope of an expression is the smallest scope that contains the expression and is one of the following:

 * The entire function body.
* A statement.
* The body of an [`if`](expressions/if-expr#if-expressions), [`while`](expressions/loop-expr#predicate-loops) or [`loop`](expressions/loop-expr#infinite-loops) expression.
* The `else` block of an `if` expression.
* The condition expression of an `if` or `while` expression, or a `match` guard.
* The body expression for a match arm.
* The second operand of a [lazy boolean expression](expressions/operator-expr#lazy-boolean-operators).

 
>  **Notes**:
> 
>  Temporaries that are created in the final expression of a function body are dropped *after* any named variables bound in the function body, as there is no smaller enclosing temporary scope.
> 
>  The [scrutinee](glossary#scrutinee) of a `match` expression is not a temporary scope, so temporaries in the scrutinee can be dropped after the `match` expression. For example, the temporary for `1` in `match 1 { ref mut z => z };` lives until the end of the statement.
> 
>  

 Some examples:

 
```
#![allow(unused)]
fn main() {
struct PrintOnDrop(&'static str);
impl Drop for PrintOnDrop {
    fn drop(&mut self) {
        println!("drop({})", self.0);
    }
}
let local_var = PrintOnDrop("local var");

// Dropped once the condition has been evaluated
if PrintOnDrop("If condition").0 == "If condition" {
    // Dropped at the end of the block
    PrintOnDrop("If body").0
} else {
    unreachable!()
};

// Dropped at the end of the statement
(PrintOnDrop("first operand").0 == ""
// Dropped at the )
|| PrintOnDrop("second operand").0 == "")
// Dropped at the end of the expression
|| PrintOnDrop("third operand").0 == "";

// Dropped at the end of the function, after local variables.
// Changing this to a statement containing a return expression would make the
// temporary be dropped before the local variables. Binding to a variable
// which is then returned would also make the temporary be dropped first.
match PrintOnDrop("Matched value in final expression") {
    // Dropped once the condition has been evaluated
    _ if PrintOnDrop("guard condition").0 == "" => (),
    _ => (),
}
}
```
 ### Operands

 Temporaries are also created to hold the result of operands to an expression while the other operands are evaluated. The temporaries are associated to the scope of the expression with that operand. Since the temporaries are moved from once the expression is evaluated, dropping them has no effect unless one of the operands to an expression breaks out of the expression, returns, or panics.

 
```
#![allow(unused)]
fn main() {
struct PrintOnDrop(&'static str);
impl Drop for PrintOnDrop {
    fn drop(&mut self) {
        println!("drop({})", self.0);
    }
}
loop {
    // Tuple expression doesn't finish evaluating so operands drop in reverse order
    (
        PrintOnDrop("Outer tuple first"),
        PrintOnDrop("Outer tuple second"),
        (
            PrintOnDrop("Inner tuple first"),
            PrintOnDrop("Inner tuple second"),
            break,
        ),
        PrintOnDrop("Never created"),
    );
}
}
```
 ### Constant promotion

 Promotion of a value expression to a `'static` slot occurs when the expression could be written in a constant and borrowed, and that borrow could be dereferenced where the expression was originally written, without changing the runtime behavior. That is, the promoted expression can be evaluated at compile-time and the resulting value does not contain [interior mutability](interior-mutability) or <destructors> (these properties are determined based on the value where possible, e.g. `&None` always has the type `&'static Option<_>`, as it contains nothing disallowed).

 ### Temporary lifetime extension

 
>  **Note**: The exact rules for temporary lifetime extension are subject to change. This is describing the current behavior only.
> 
>  

 The temporary scopes for expressions in `let` statements are sometimes *extended* to the scope of the block containing the `let` statement. This is done when the usual temporary scope would be too small, based on certain syntactic rules. For example:

 
```
#![allow(unused)]
fn main() {
let x = &mut 0;
// Usually a temporary would be dropped by now, but the temporary for `0` lives
// to the end of the block.
println!("{}", x);
}
```
 If a [borrow](expressions/operator-expr#borrow-operators), [dereference](expressions/operator-expr#the-dereference-operator), [field](expressions/field-expr), or [tuple indexing expression](expressions/tuple-expr#tuple-indexing-expressions) has an extended temporary scope then so does its operand. If an [indexing expression](expressions/array-expr#array-and-slice-indexing-expressions) has an extended temporary scope then the indexed expression also has an extended temporary scope.

 #### Extending based on patterns

 An *extending pattern* is either

 * An [identifier pattern](patterns#identifier-patterns) that binds by reference or mutable reference.
* A [struct](patterns#struct-patterns), [tuple](patterns#tuple-patterns), [tuple struct](patterns#tuple-struct-patterns), or [slice](patterns#slice-patterns) pattern where at least one of the direct subpatterns is a extending pattern.

 So `ref x`, `V(ref x)` and `[ref x, y]` are all extending patterns, but `x`, `&ref x` and `&(ref x,)` are not.

 If the pattern in a `let` statement is an extending pattern then the temporary scope of the initializer expression is extended.

 #### Extending based on expressions

 For a let statement with an initializer, an *extending expression* is an expression which is one of the following:

 * The initializer expression.
* The operand of an extending [borrow expression](expressions/operator-expr#borrow-operators).
* The operand(s) of an extending [array](expressions/array-expr#array-expressions), [cast](expressions/operator-expr#type-cast-expressions), [braced struct](expressions/struct-expr), or [tuple](expressions/tuple-expr#tuple-expressions) expression.
* The final expression of any extending [block expression](expressions/block-expr).

 So the borrow expressions in `&mut 0`, `(&1, &mut 2)`, and `Some { 0: &mut 3 }` are all extending expressions. The borrows in `&0 + &1` and `Some(&mut 0)` are not: the latter is syntactically a function call expression.

 The operand of any extending borrow expression has its temporary scope extended.

 #### Examples

 Here are some examples where expressions have extended temporary scopes:

 
```
#![allow(unused)]
fn main() {
fn temp() {}
trait Use { fn use_temp(&self) -> &Self { self } }
impl Use for () {}
// The temporary that stores the result of `temp()` lives in the same scope
// as x in these cases.
let x = &temp();
let x = &temp() as &dyn Send;
let x = (&*&temp(),);
let x = { [Some { 0: &temp(), }] };
let ref x = temp();
let ref x = *&temp();
x;
}
```
 Here are some examples where expressions don't have extended temporary scopes:

 
```
#![allow(unused)]
fn main() {
fn temp() {}
trait Use { fn use_temp(&self) -> &Self { self } }
impl Use for () {}
// The temporary that stores the result of `temp()` only lives until the
// end of the let statement in these cases.

let x = Some(&temp());         // ERROR
let x = (&temp()).use_temp();  // ERROR
x;
}
```
 Not running destructors
-----------------------

 [`std::mem::forget`](../std/mem/fn.forget) can be used to prevent the destructor of a variable from being run, and [`std::mem::ManuallyDrop`](../std/mem/struct.manuallydrop) provides a wrapper to prevent a variable or field from being dropped automatically.

 
>  Note: Preventing a destructor from being run via [`std::mem::forget`](../std/mem/fn.forget) or other means is safe even if it has a type that isn't `'static`. Besides the places where destructors are guaranteed to run as defined by this document, types may *not* safely rely on a destructor being run for soundness.
> 
>  



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/destructors.html>

Lifetime elision
================

 Rust has rules that allow lifetimes to be elided in various places where the compiler can infer a sensible default choice.

 Lifetime elision in functions
-----------------------------

 In order to make common patterns more ergonomic, lifetime arguments can be *elided* in [function item](types/function-item), [function pointer](types/function-pointer), and [closure trait](types/closure) signatures. The following rules are used to infer lifetime parameters for elided lifetimes. It is an error to elide lifetime parameters that cannot be inferred. The placeholder lifetime, `'_`, can also be used to have a lifetime inferred in the same way. For lifetimes in paths, using `'_` is preferred. Trait object lifetimes follow different rules discussed [below](#default-trait-object-lifetimes).

 * Each elided lifetime in the parameters becomes a distinct lifetime parameter.
* If there is exactly one lifetime used in the parameters (elided or not), that lifetime is assigned to *all* elided output lifetimes.

 In method signatures there is another rule

 * If the receiver has type `&Self` or `&mut Self`, then the lifetime of that reference to `Self` is assigned to all elided output lifetime parameters.

 Examples:

 
```
#![allow(unused)]
fn main() {
trait T {}
trait ToCStr {}
struct Thing<'a> {f: &'a i32}
struct Command;

trait Example {
fn print1(s: &str);                                   // elided
fn print2(s: &'_ str);                                // also elided
fn print3<'a>(s: &'a str);                            // expanded

fn debug1(lvl: usize, s: &str);                       // elided
fn debug2<'a>(lvl: usize, s: &'a str);                // expanded

fn substr1(s: &str, until: usize) -> &str;            // elided
fn substr2<'a>(s: &'a str, until: usize) -> &'a str;  // expanded

fn get_mut1(&mut self) -> &mut dyn T;                 // elided
fn get_mut2<'a>(&'a mut self) -> &'a mut dyn T;       // expanded

fn args1<T: ToCStr>(&mut self, args: &[T]) -> &mut Command;                  // elided
fn args2<'a, 'b, T: ToCStr>(&'a mut self, args: &'b [T]) -> &'a mut Command; // expanded

fn new1(buf: &mut [u8]) -> Thing<'_>;                 // elided - preferred
fn new2(buf: &mut [u8]) -> Thing;                     // elided
fn new3<'a>(buf: &'a mut [u8]) -> Thing<'a>;          // expanded
}

type FunPtr1 = fn(&str) -> &str;                      // elided
type FunPtr2 = for<'a> fn(&'a str) -> &'a str;        // expanded

type FunTrait1 = dyn Fn(&str) -> &str;                // elided
type FunTrait2 = dyn for<'a> Fn(&'a str) -> &'a str;  // expanded
}
```
 
```
#![allow(unused)]
fn main() {
// The following examples show situations where it is not allowed to elide the
// lifetime parameter.

trait Example {
// Cannot infer, because there are no parameters to infer from.
fn get_str() -> &str;                                 // ILLEGAL

// Cannot infer, ambiguous if it is borrowed from the first or second parameter.
fn frob(s: &str, t: &str) -> &str;                    // ILLEGAL
}
}
```
 Default trait object lifetimes
------------------------------

 The assumed lifetime of references held by a [trait object](types/trait-object) is called its *default object lifetime bound*. These were defined in [RFC 599](https://github.com/rust-lang/rfcs/blob/master/text/0599-default-object-bound.md) and amended in [RFC 1156](https://github.com/rust-lang/rfcs/blob/master/text/1156-adjust-default-object-bounds.md).

 These default object lifetime bounds are used instead of the lifetime parameter elision rules defined above when the lifetime bound is omitted entirely. If `'_` is used as the lifetime bound then the bound follows the usual elision rules.

 If the trait object is used as a type argument of a generic type then the containing type is first used to try to infer a bound.

 * If there is a unique bound from the containing type then that is the default
* If there is more than one bound from the containing type then an explicit bound must be specified

 If neither of those rules apply, then the bounds on the trait are used:

 * If the trait is defined with a single lifetime *bound* then that bound is used.
* If `'static` is used for any lifetime bound then `'static` is used.
* If the trait has no lifetime bounds, then the lifetime is inferred in expressions and is `'static` outside of expressions.

 
```
#![allow(unused)]
fn main() {
// For the following trait...
trait Foo { }

// These two are the same because Box<T> has no lifetime bound on T
type T1 = Box<dyn Foo>;
type T2 = Box<dyn Foo + 'static>;

// ...and so are these:
impl dyn Foo {}
impl dyn Foo + 'static {}

// ...so are these, because &'a T requires T: 'a
type T3<'a> = &'a dyn Foo;
type T4<'a> = &'a (dyn Foo + 'a);

// std::cell::Ref<'a, T> also requires T: 'a, so these are the same
type T5<'a> = std::cell::Ref<'a, dyn Foo>;
type T6<'a> = std::cell::Ref<'a, dyn Foo + 'a>;
}
```
 
```
#![allow(unused)]
fn main() {
// This is an example of an error.
trait Foo { }
struct TwoBounds<'a, 'b, T: ?Sized + 'a + 'b> {
    f1: &'a i32,
    f2: &'b i32,
    f3: T,
}
type T7<'a, 'b> = TwoBounds<'a, 'b, dyn Foo>;
//                                  ^^^^^^^
// Error: the lifetime bound for this object type cannot be deduced from context
}
```
 Note that the innermost object sets the bound, so `&'a Box<dyn Foo>` is still `&'a Box<dyn Foo + 'static>`.

 
```
#![allow(unused)]
fn main() {
// For the following trait...
trait Bar<'a>: 'a { }

// ...these two are the same:
type T1<'a> = Box<dyn Bar<'a>>;
type T2<'a> = Box<dyn Bar<'a> + 'a>;

// ...and so are these:
impl<'a> dyn Bar<'a> {}
impl<'a> dyn Bar<'a> + 'a {}
}
```
 
`'static` lifetime elision
---------------------------

 Both [constant](items/constant-items) and [static](items/static-items) declarations of reference types have *implicit* `'static` lifetimes unless an explicit lifetime is specified. As such, the constant declarations involving `'static` above may be written without the lifetimes.

 
```
#![allow(unused)]
fn main() {
// STRING: &'static str
const STRING: &str = "bitstring";

struct BitsNStrings<'a> {
    mybits: [u32; 2],
    mystring: &'a str,
}

// BITS_N_STRINGS: BitsNStrings<'static>
const BITS_N_STRINGS: BitsNStrings<'_> = BitsNStrings {
    mybits: [1, 2],
    mystring: STRING,
};
}
```
 Note that if the `static` or `const` items include function or closure references, which themselves include references, the compiler will first try the standard elision rules. If it is unable to resolve the lifetimes by its usual rules, then it will error. By way of example:

 
```
#![allow(unused)]
fn main() {
struct Foo;
struct Bar;
struct Baz;
fn somefunc(a: &Foo, b: &Bar, c: &Baz) -> usize {42}
// Resolved as `fn<'a>(&'a str) -> &'a str`.
const RESOLVED_SINGLE: fn(&str) -> &str = |x| x;

// Resolved as `Fn<'a, 'b, 'c>(&'a Foo, &'b Bar, &'c Baz) -> usize`.
const RESOLVED_MULTIPLE: &dyn Fn(&Foo, &Bar, &Baz) -> usize = &somefunc;
}
```
 
```
#![allow(unused)]
fn main() {
struct Foo;
struct Bar;
struct Baz;
fn somefunc<'a,'b>(a: &'a Foo, b: &'b Bar) -> &'a Baz {unimplemented!()}
// There is insufficient information to bound the return reference lifetime
// relative to the argument lifetimes, so this is an error.
const RESOLVED_STATIC: &dyn Fn(&Foo, &Bar) -> &Baz = &somefunc;
//                                            ^
// this function's return type contains a borrowed value, but the signature
// does not say whether it is borrowed from argument 1 or argument 2
}
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/lifetime-elision.html>

Special types and traits
========================

 Certain types and traits that exist in [the standard library](../std/index) are known to the Rust compiler. This chapter documents the special features of these types and traits.

 `Box<T>`
--------

 [`Box<T>`](../std/boxed/struct.box) has a few special features that Rust doesn't currently allow for user defined types.

 * The [dereference operator](expressions/operator-expr#the-dereference-operator) for `Box<T>` produces a place which can be moved from. This means that the `*` operator and the destructor of `Box<T>` are built-in to the language.
* [Methods](items/associated-items#associated-functions-and-methods) can take `Box<Self>` as a receiver.
* A trait may be implemented for `Box<T>` in the same crate as `T`, which the [orphan rules](items/implementations#trait-implementation-coherence) prevent for other generic types.

 `Rc<T>`
-------

 [Methods](items/associated-items#associated-functions-and-methods) can take [`Rc<Self>`](../std/rc/struct.rc) as a receiver.

 `Arc<T>`
--------

 [Methods](items/associated-items#associated-functions-and-methods) can take [`Arc<Self>`](../std/sync/struct.arc) as a receiver.

 `Pin<P>`
--------

 [Methods](items/associated-items#associated-functions-and-methods) can take [`Pin<P>`](../std/pin/struct.pin) as a receiver.

 `UnsafeCell<T>`
---------------

 [`std::cell::UnsafeCell<T>`](../std/cell/struct.unsafecell) is used for [interior mutability](interior-mutability). It ensures that the compiler doesn't perform optimisations that are incorrect for such types. It also ensures that [`static` items](items/static-items) which have a type with interior mutability aren't placed in memory marked as read only.

 `PhantomData<T>`
----------------

 [`std::marker::PhantomData<T>`](../std/marker/struct.phantomdata) is a zero-sized, minimum alignment, type that is considered to own a `T` for the purposes of [variance](subtyping#variance), [drop check](https://doc.rust-lang.org/nomicon/dropck.html), and [auto traits](#auto-traits).

 Operator Traits
---------------

 The traits in [`std::ops`](../std/ops/index) and [`std::cmp`](../std/cmp/index) are used to overload [operators](expressions/operator-expr), [indexing expressions](expressions/array-expr#array-and-slice-indexing-expressions), and [call expressions](expressions/call-expr).

 
`Deref` and `DerefMut`
-----------------------

 As well as overloading the unary `*` operator, [`Deref`](../std/ops/trait.deref) and [`DerefMut`](../std/ops/trait.derefmut) are also used in [method resolution](expressions/method-call-expr) and [deref coercions](type-coercions#coercion-types).

 `Drop`
------

 The [`Drop`](../std/ops/trait.drop) trait provides a [destructor](destructors), to be run whenever a value of this type is to be destroyed.

 `Copy`
------

 The [`Copy`](../std/marker/trait.copy) trait changes the semantics of a type implementing it. Values whose type implements `Copy` are copied rather than moved upon assignment.

 `Copy` can only be implemented for types which do not implement `Drop`, and whose fields are all `Copy`. For enums, this means all fields of all variants have to be `Copy`. For unions, this means all variants have to be `Copy`.

 `Copy` is implemented by the compiler for

 * [Tuples](types/tuple) of `Copy` types
* [Function pointers](types/function-pointer)
* [Function items](types/function-item)
* [Closures](types/closure) that capture no values or that only capture values of `Copy` types

 `Clone`
-------

 The [`Clone`](../std/clone/trait.clone) trait is a supertrait of `Copy`, so it also needs compiler generated implementations. It is implemented by the compiler for the following types:

 * Types with a built-in `Copy` implementation (see above)
* [Tuples](types/tuple) of `Clone` types

 `Send`
------

 The [`Send`](../std/marker/trait.send) trait indicates that a value of this type is safe to send from one thread to another.

 `Sync`
------

 The [`Sync`](../std/marker/trait.sync) trait indicates that a value of this type is safe to share between multiple threads. This trait must be implemented for all types used in immutable [`static` items](items/static-items).

 `Termination`
-------------

 The [`Termination`](../std/process/trait.termination) trait indicates the acceptable return types for the [main function](crates-and-source-files#main-functions) and [test functions](attributes/testing#the-test-attribute).

 Auto traits
-----------

 The [`Send`](../std/marker/trait.send), [`Sync`](../std/marker/trait.sync), [`Unpin`](../std/marker/trait.unpin), [`UnwindSafe`](../std/panic/trait.unwindsafe), and [`RefUnwindSafe`](../std/panic/trait.refunwindsafe) traits are *auto traits*. Auto traits have special properties.

 If no explicit implementation or negative implementation is written out for an auto trait for a given type, then the compiler implements it automatically according to the following rules:

 * `&T`, `&mut T`, `*const T`, `*mut T`, `[T; n]`, and `[T]` implement the trait if `T` does.
* Function item types and function pointers automatically implement the trait.
* Structs, enums, unions, and tuples implement the trait if all of their fields do.
* Closures implement the trait if the types of all of their captures do. A closure that captures a `T` by shared reference and a `U` by value implements any auto traits that both `&T` and `U` do.

 For generic types (counting the built-in types above as generic over `T`), if a generic implementation is available, then the compiler does not automatically implement it for types that could use the implementation except that they do not meet the requisite trait bounds. For instance, the standard library implements `Send` for all `&T` where `T` is `Sync`; this means that the compiler will not implement `Send` for `&T` if `T` is `Send` but not `Sync`.

 Auto traits can also have negative implementations, shown as `impl !AutoTrait for T` in the standard library documentation, that override the automatic implementations. For example `*mut T` has a negative implementation of `Send`, and so `*mut T` is not `Send`, even if `T` is. There is currently no stable way to specify additional negative implementations; they exist only in the standard library.

 Auto traits may be added as an additional bound to any [trait object](types/trait-object), even though normally only one trait is allowed. For instance, `Box<dyn Debug + Send + UnwindSafe>` is a valid type.

 `Sized`
-------

 The [`Sized`](../std/marker/trait.sized) trait indicates that the size of this type is known at compile-time; that is, it's not a [dynamically sized type](dynamically-sized-types). [Type parameters](types/parameters) (except `Self` in traits) are `Sized` by default, as are [associated types](items/associated-items#associated-types). `Sized` is always implemented automatically by the compiler, not by [implementation items](items/implementations). These implicit `Sized` bounds may be relaxed by using the special `?Sized` bound.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/special-types-and-traits.html>

Names
=====

 An *entity* is a language construct that can be referred to in some way within the source program, usually via a [path](paths). Entities include <types>, <items>, [generic parameters](items/generics), [variable bindings](patterns), [loop labels](expressions/loop-expr#loop-labels), [lifetimes](tokens#lifetimes-and-loop-labels), [fields](expressions/field-expr), <attributes>, and [lints](attributes/diagnostics#lint-check-attributes).

 A *declaration* is a syntactical construct that can introduce a *name* to refer to an entity. Entity names are valid within a [*scope*](names/scopes) — a region of source text where that name may be referenced.

 Some entities are [explicitly declared](#explicitly-declared-entities) in the source code, and some are [implicitly declared](#implicitly-declared-entities) as part of the language or compiler extensions.

 [*Paths*](paths) are used to refer to an entity, possibly in another scope. Lifetimes and loop labels use a [dedicated syntax](tokens#lifetimes-and-loop-labels) using a leading quote.

 Names are segregated into different [*namespaces*](names/namespaces), allowing entities in different namespaces to share the same name without conflict.

 [*Name resolution*](names/name-resolution) is the compile-time process of tying paths, identifiers, and labels to entity declarations.

 Access to certain names may be restricted based on their [*visibility*](visibility-and-privacy).

 Explicitly declared entities
----------------------------

 Entities that explicitly introduce a name in the source code are:

 * [Items](items):
	+ [Module declarations](items/modules)
	+ [External crate declarations](items/extern-crates)
	+ [Use declarations](items/use-declarations)
	+ [Function declarations](items/functions) and [function parameters](items/functions#function-parameters)
	+ [Type aliases](items/type-aliases)
	+ [struct](items/structs), [union](items/unions), [enum](items/enumerations), enum variant declarations, and their named fields
	+ [Constant item declarations](items/constant-items)
	+ [Static item declarations](items/static-items)
	+ [Trait item declarations](items/traits) and their [associated items](items/associated-items)
	+ [External block items](items/external-blocks)
	+ [`macro_rules` declarations](macros-by-example) and [matcher metavariables](macros-by-example#metavariables)
	+ [Implementation](items/implementations) associated items
* [Expressions](expressions):
	+ [Closure](expressions/closure-expr) parameters
	+ [`while let`](expressions/loop-expr#predicate-pattern-loops) pattern bindings
	+ [`for`](expressions/loop-expr#iterator-loops) pattern bindings
	+ [`if let`](expressions/if-expr#if-let-expressions) pattern bindings
	+ [`match`](expressions/match-expr) pattern bindings
	+ [Loop labels](expressions/loop-expr#loop-labels)
* [Generic parameters](items/generics)
* [Higher ranked trait bounds](trait-bounds#higher-ranked-trait-bounds)
* [`let` statement](statements#let-statements) pattern bindings
* The [`macro_use` attribute](macros-by-example#the-macro_use-attribute) can introduce macro names from another crate
* The [`macro_export` attribute](macros-by-example#path-based-scope) can introduce an alias for the macro into the crate root

 Additionally, [macro invocations](macros#macro-invocation) and <attributes> can introduce names by expanding to one of the above items.

 Implicitly declared entities
----------------------------

 The following entities are implicitly defined by the language, or are introduced by compiler options and extensions:

 * [Language prelude](names/preludes#language-prelude):
	+ [Boolean type](types/boolean) — `bool`
	+ [Textual types](types/textual) — `char` and `str`
	+ [Integer types](types/numeric#integer-types) — `i8`, `i16`, `i32`, `i64`, `i128`, `u8`, `u16`, `u32`, `u64`, `u128`
	+ [Machine-dependent integer types](types/numeric#machine-dependent-integer-types) — `usize` and `isize`
	+ [floating-point types](types/numeric#floating-point-types) — `f32` and `f64`
* [Built-in attributes](attributes#built-in-attributes-index)
* [Standard library prelude](names/preludes#standard-library-prelude) items, attributes, and macros
* [Standard library](names/preludes#extern-prelude) crates in the root module
* [External crates](names/preludes#extern-prelude) linked by the compiler
* [Tool attributes](attributes#tool-attributes)
* [Lints](attributes/diagnostics#lint-check-attributes) and [tool lint attributes](attributes/diagnostics#tool-lint-attributes)
* [Derive helper attributes](procedural-macros#derive-macro-helper-attributes) are valid within an item without being explicitly imported
* The [`'static`](keywords#weak-keywords) lifetime

 Additionally, the crate root module does not have a name, but can be referred to with certain [path qualifiers](paths#path-qualifiers) or aliases.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/names.html>

Namespaces
==========

 A *namespace* is a logical grouping of declared [names](../names). Names are segregated into separate namespaces based on the kind of entity the name refers to. Namespaces allow the occurrence of a name in one namespace to not conflict with the same name in another namespace.

 Within a namespace, names are organized in a hierarchy, where each level of the hierarchy has its own collection of named entities.

 There are several different namespaces that each contain different kinds of entities. The usage of a name will look for the declaration of that name in different namespaces, based on the context, as described in the [name resolution](name-resolution) chapter.

 The following is a list of namespaces, with their corresponding entities:

 * Type Namespace
	+ [Module declarations](../items/modules)
	+ [External crate declarations](../items/extern-crates)
	+ [External crate prelude](preludes#extern-prelude) items
	+ [Struct](../items/structs), [union](../items/unions), [enum](../items/enumerations), enum variant declarations
	+ [Trait item declarations](../items/traits)
	+ [Type aliases](../items/type-aliases)
	+ [Associated type declarations](../items/associated-items#associated-types)
	+ Built-in types: [boolean](../types/boolean), [numeric](../types/numeric), and [textual](../types/textual)
	+ [Generic type parameters](../items/generics)
	+ [`Self` type](../paths#self-1)
	+ [Tool attribute modules](../attributes#tool-attributes)
* Value Namespace
	+ [Function declarations](../items/functions)
	+ [Constant item declarations](../items/constant-items)
	+ [Static item declarations](../items/static-items)
	+ [Struct constructors](../items/structs)
	+ [Enum variant constructors](../items/enumerations)
	+ [`Self` constructors](../paths#self-1)
	+ [Generic const parameters](../items/generics#const-generics)
	+ [Associated const declarations](../items/associated-items#associated-constants)
	+ [Associated function declarations](../items/associated-items#associated-functions-and-methods)
	+ Local bindings — [`let`](../statements#let-statements), [`if let`](../expressions/if-expr#if-let-expressions), [`while let`](../expressions/loop-expr#predicate-pattern-loops), [`for`](../expressions/loop-expr#iterator-loops), [`match`](../expressions/match-expr) arms, [function parameters](../items/functions#function-parameters), [closure parameters](../expressions/closure-expr)
	+ Captured [closure](../expressions/closure-expr) variables
* Macro Namespace
	+ [`macro_rules` declarations](../macros-by-example)
	+ [Built-in attributes](../attributes#built-in-attributes-index)
	+ [Tool attributes](../attributes#tool-attributes)
	+ [Function-like procedural macros](../procedural-macros#function-like-procedural-macros)
	+ [Derive macros](../procedural-macros#derive-macros)
	+ [Derive macro helpers](../procedural-macros#derive-macro-helper-attributes)
	+ [Attribute macros](../procedural-macros#attribute-macros)
* Lifetime Namespace
	+ [Generic lifetime parameters](../items/generics)
* Label Namespace
	+ [Loop labels](../expressions/loop-expr#loop-labels)
	+ [Block labels](../expressions/loop-expr#labelled-block-expressions)

 An example of how overlapping names in different namespaces can be used unambiguously:

 
```
#![allow(unused)]
fn main() {
// Foo introduces a type in the type namespace and a constructor in the value
// namespace.
struct Foo(u32);

// The `Foo` macro is declared in the macro namespace.
macro_rules! Foo {
    () => {};
}

// `Foo` in the `f` parameter type refers to `Foo` in the type namespace.
// `'Foo` introduces a new lifetime in the lifetime namespace.
fn example<'Foo>(f: Foo) {
    // `Foo` refers to the `Foo` constructor in the value namespace.
    let ctor = Foo;
    // `Foo` refers to the `Foo` macro in the macro namespace.
    Foo!{}
    // `'Foo` introduces a label in the label namespace.
    'Foo: loop {
        // `'Foo` refers to the `'Foo` lifetime parameter, and `Foo`
        // refers to the type namespace.
        let x: &'Foo Foo;
        // `'Foo` refers to the label.
        break 'Foo;
    }
}
}
```
 Named entities without a namespace
----------------------------------

 The following entities have explicit names, but the names are not a part of any specific namespace.

 ### Fields

 Even though struct, enum, and union fields are named, the named fields do not live in an explicit namespace. They can only be accessed via a [field expression](../expressions/field-expr), which only inspects the field names of the specific type being accessed.

 ### Use declarations

 A [use declaration](../items/use-declarations) has named aliases that it imports into scope, but the `use` item itself does not belong to a specific namespace. Instead, it can introduce aliases into multiple namespaces, depending on the item kind being imported.

 Sub-namespaces
--------------

 The macro namespace is split into two sub-namespaces: one for [bang-style macros](../macros) and one for [attributes](../attributes). When an attribute is resolved, any bang-style macros in scope will be ignored. And conversely resolving a bang-style macro will ignore attribute macros in scope. This prevents one style from shadowing another.

 For example, the [`cfg` attribute](../conditional-compilation#the-cfg-attribute) and the [`cfg` macro](../conditional-compilation#the-cfg-macro) are two different entities with the same name in the macro namespace, but they can still be used in their respective context.

 It is still an error for a [`use` import](../items/use-declarations) to shadow another macro, regardless of their sub-namespaces.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/names/namespaces.html>

Scopes
======

 
>  **Note**: This is a placeholder for future expansion.
> 
>  



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/names/scopes.html>

Preludes
========

 A *prelude* is a collection of names that are automatically brought into scope of every module in a crate.

 These prelude names are not part of the module itself: they are implicitly queried during [name resolution](name-resolution). For example, even though something like [`Box`](../../std/boxed/struct.box) is in scope in every module, you cannot refer to it as `self::Box` because it is not a member of the current module.

 There are several different preludes:

 * [Standard library prelude](#standard-library-prelude)
* [Extern prelude](#extern-prelude)
* [Language prelude](#language-prelude)
* [`macro_use` prelude](#macro_use-prelude)
* [Tool prelude](#tool-prelude)

 Standard library prelude
------------------------

 Each crate has a standard library prelude, which consists of the names from a single standard library module. The module used depends on the crate's edition, and on whether the [`no_std` attribute](#the-no_std-attribute) is applied to the crate:

 


| Edition | `no_std` not applied | `no_std` applied |
| --- | --- | --- |
| 2015 | [`std::prelude::rust_2015`](../../std/prelude/rust_2015/index) | [`core::prelude::rust_2015`](https://doc.rust-lang.org/core/prelude/rust_2015/index.html) |
| 2018 | [`std::prelude::rust_2018`](../../std/prelude/rust_2018/index) | [`core::prelude::rust_2018`](https://doc.rust-lang.org/core/prelude/rust_2018/index.html) |
| 2021 | [`std::prelude::rust_2021`](../../std/prelude/rust_2021/index) | [`core::prelude::rust_2021`](https://doc.rust-lang.org/core/prelude/rust_2021/index.html) |

  
>  **Note**:
> 
>  [`std::prelude::rust_2015`](../../std/prelude/rust_2015/index) and [`std::prelude::rust_2018`](../../std/prelude/rust_2018/index) have the same contents as [`std::prelude::v1`](../../std/prelude/v1/index).
> 
>  [`core::prelude::rust_2015`](https://doc.rust-lang.org/core/prelude/rust_2015/index.html) and [`core::prelude::rust_2018`](https://doc.rust-lang.org/core/prelude/rust_2018/index.html) have the same contents as [`core::prelude::v1`](https://doc.rust-lang.org/core/prelude/v1/index.html).
> 
>  

 Extern prelude
--------------

 External crates imported with [`extern crate`](../items/extern-crates) in the root module or provided to the compiler (as with the `--extern` flag with `rustc`) are added to the *extern prelude*. If imported with an alias such as `extern crate orig_name as new_name`, then the symbol `new_name` is instead added to the prelude.

 The [`core`](https://doc.rust-lang.org/core/index.html) crate is always added to the extern prelude. The [`std`](../../std/index) crate is added as long as the [`no_std` attribute](#the-no_std-attribute) is not specified in the crate root.

 
>  **Edition Differences**: In the 2015 edition, crates in the extern prelude cannot be referenced via [use declarations](../items/use-declarations), so it is generally standard practice to include `extern crate` declarations to bring them into scope.
> 
>  Beginning in the 2018 edition, [use declarations](../items/use-declarations) can reference crates in the extern prelude, so it is considered unidiomatic to use `extern crate`.
> 
>  

 
>  **Note**: Additional crates that ship with `rustc`, such as [`alloc`](https://doc.rust-lang.org/alloc/index.html), and [`test`](https://doc.rust-lang.org/test/index.html), are not automatically included with the `--extern` flag when using Cargo. They must be brought into scope with an `extern crate` declaration, even in the 2018 edition.
> 
>  
> ```
> #![allow(unused)]
> fn main() {
> extern crate alloc;
> use alloc::rc::Rc;
> }
> ```
>  Cargo does bring in `proc_macro` to the extern prelude for proc-macro crates only.
> 
>  

 ### The `no_std` attribute

 By default, the standard library is automatically included in the crate root module. The [`std`](../../std/index) crate is added to the root, along with an implicit [`macro_use` attribute](../macros-by-example#the-macro_use-attribute) pulling in all macros exported from `std` into the [`macro_use` prelude](#macro_use-prelude). Both [`core`](https://doc.rust-lang.org/core/index.html) and [`std`](../../std/index) are added to the [extern prelude](#extern-prelude).

 The *`no_std` [attribute](../attributes)* may be applied at the crate level to prevent the [`std`](../../std/index) crate from being automatically added into scope. It does three things:

 * Prevents `std` from being added to the [extern prelude](#extern-prelude).
* Affects which module is used to make up the [standard library prelude](#standard-library-prelude) (as described above).
* Injects the [`core`](https://doc.rust-lang.org/core/index.html) crate into the crate root instead of [`std`](../../std/index), and pulls in all macros exported from `core` in the [`macro_use` prelude](#macro_use-prelude).

 
>  **Note**: Using the core prelude over the standard prelude is useful when either the crate is targeting a platform that does not support the standard library or is purposefully not using the capabilities of the standard library. Those capabilities are mainly dynamic memory allocation (e.g. `Box` and `Vec`) and file and network capabilities (e.g. `std::fs` and `std::io`).
> 
>  

  Warning: Using `no_std` does not prevent the standard library from being linked in. It is still valid to put `extern crate std;` into the crate and dependencies can also link it in.

  Language prelude
----------------

 The language prelude includes names of types and attributes that are built-in to the language. The language prelude is always in scope. It includes the following:

 * [Type namespace](namespaces)
	+ [Boolean type](../types/boolean) — `bool`
	+ [Textual types](../types/textual) — `char` and `str`
	+ [Integer types](../types/numeric#integer-types) — `i8`, `i16`, `i32`, `i64`, `i128`, `u8`, `u16`, `u32`, `u64`, `u128`
	+ [Machine-dependent integer types](../types/numeric#machine-dependent-integer-types) — `usize` and `isize`
	+ [floating-point types](../types/numeric#floating-point-types) — `f32` and `f64`
* [Macro namespace](namespaces)
	+ [Built-in attributes](../attributes#built-in-attributes-index)

 
`macro_use` prelude
--------------------

 The `macro_use` prelude includes macros from external crates that were imported by the [`macro_use` attribute](../macros-by-example#the-macro_use-attribute) applied to an [`extern crate`](../items/extern-crates).

 Tool prelude
------------

 The tool prelude includes tool names for external tools in the [type namespace](namespaces). See the [tool attributes](../attributes#tool-attributes) section for more details.

 The `no_implicit_prelude` attribute
-----------------------------------

 The *`no_implicit_prelude` [attribute](../attributes)* may be applied at the crate level or on a module to indicate that it should not automatically bring the [standard library prelude](#standard-library-prelude), [extern prelude](#extern-prelude), or [tool prelude](#tool-prelude) into scope for that module or any of its descendants.

 This attribute does not affect the [language prelude](#language-prelude).

 
>  **Edition Differences**: In the 2015 edition, the `no_implicit_prelude` attribute does not affect the [`macro_use` prelude](#macro_use-prelude), and all macros exported from the standard library are still included in the `macro_use` prelude. Starting in the 2018 edition, it will remove the `macro_use` prelude.
> 
>  



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/names/preludes.html>

Paths
=====

 A *path* is a sequence of one or more path segments *logically* separated by a namespace qualifier (`::`). If a path consists of only one segment, it refers to either an [item](items) or a [variable](variables) in a local control scope. If a path has multiple segments, it always refers to an item.

 Two examples of simple paths consisting of only identifier segments:

 
```
x;
x::y::z;
```
 Types of paths
--------------

 ### Simple Paths

 
>  **Syntax**  
>  *SimplePath* :  
>  `::`? *SimplePathSegment* (`::` *SimplePathSegment*)\*
> 
>  *SimplePathSegment* :  
>  [IDENTIFIER](identifiers) | `super` | `self` | `crate` | `$crate`
> 
>  

 Simple paths are used in [visibility](visibility-and-privacy) markers, <attributes>, [macros](macros-by-example), and [`use`](items/use-declarations) items. Examples:

 
```
#![allow(unused)]
fn main() {
use std::io::{self, Write};
mod m {
    #[clippy::cyclomatic_complexity = "0"]
    pub (in super) fn f1() {}
}
}
```
 ### Paths in expressions

 
>  **Syntax**  
>  *PathInExpression* :  
>  `::`? *PathExprSegment* (`::` *PathExprSegment*)\*
> 
>  *PathExprSegment* :  
>  *PathIdentSegment* (`::` *GenericArgs*)?
> 
>  *PathIdentSegment* :  
>  [IDENTIFIER](identifiers) | `super` | `self` | `Self` | `crate` | `$crate`
> 
>  *GenericArgs* :  
>  `<` `>`  
>  | `<` ( *GenericArg* `,` )\* *GenericArg* `,`? `>`
> 
>  *GenericArg* :  
>  [*Lifetime*](trait-bounds) | [*Type*](types#type-expressions) | *GenericArgsConst* | *GenericArgsBinding*
> 
>  *GenericArgsConst* :  
>  [*BlockExpression*](expressions/block-expr)  
>  | [*LiteralExpression*](expressions/literal-expr)  
>  | `-` [*LiteralExpression*](expressions/literal-expr)  
>  | [*SimplePathSegment*](#simple-paths)
> 
>  *GenericArgsBinding* :  
>  [IDENTIFIER](identifiers) `=` [*Type*](types#type-expressions)
> 
>  

 Paths in expressions allow for paths with generic arguments to be specified. They are used in various places in <expressions> and <patterns>.

 The `::` token is required before the opening `<` for generic arguments to avoid ambiguity with the less-than operator. This is colloquially known as "turbofish" syntax.

 
```
#![allow(unused)]
fn main() {
(0..10).collect::<Vec<_>>();
Vec::<u8>::with_capacity(1024);
}
```
 The order of generic arguments is restricted to lifetime arguments, then type arguments, then const arguments, then equality constraints.

 Const arguments must be surrounded by braces unless they are a [literal](expressions/literal-expr) or a single segment path.

 The synthetic type parameters corresponding to `impl Trait` types are implicit, and these cannot be explicitly specified.

 Qualified paths
---------------

 
>  **Syntax**  
>  *QualifiedPathInExpression* :  
>  *QualifiedPathType* (`::` *PathExprSegment*)+
> 
>  *QualifiedPathType* :  
>  `<` [*Type*](types#type-expressions) (`as` *TypePath*)? `>`
> 
>  *QualifiedPathInType* :  
>  *QualifiedPathType* (`::` *TypePathSegment*)+
> 
>  

 Fully qualified paths allow for disambiguating the path for [trait implementations](items/implementations#trait-implementations) and for specifying [canonical paths](#canonical-paths). When used in a type specification, it supports using the type syntax specified below.

 
```
#![allow(unused)]
fn main() {
struct S;
impl S {
    fn f() { println!("S"); }
}
trait T1 {
    fn f() { println!("T1 f"); }
}
impl T1 for S {}
trait T2 {
    fn f() { println!("T2 f"); }
}
impl T2 for S {}
S::f();  // Calls the inherent impl.
<S as T1>::f();  // Calls the T1 trait function.
<S as T2>::f();  // Calls the T2 trait function.
}
```
 ### Paths in types

 
>  **Syntax**  
>  *TypePath* :  
>  `::`? *TypePathSegment* (`::` *TypePathSegment*)\*
> 
>  *TypePathSegment* :  
>  *PathIdentSegment* `::`? ([*GenericArgs*](#paths-in-expressions) | *TypePathFn*)?
> 
>  *TypePathFn* :  
>  `(` *TypePathFnInputs*? `)` (`->` [*Type*](types#type-expressions))?
> 
>  *TypePathFnInputs* :  
>  [*Type*](types#type-expressions) (`,` [*Type*](types#type-expressions))\* `,`?
> 
>  

 Type paths are used within type definitions, trait bounds, type parameter bounds, and qualified paths.

 Although the `::` token is allowed before the generics arguments, it is not required because there is no ambiguity like there is in *PathInExpression*.

 
```
#![allow(unused)]
fn main() {
mod ops {
    pub struct Range<T> {f1: T}
    pub trait Index<T> {}
    pub struct Example<'a> {f1: &'a i32}
}
struct S;
impl ops::Index<ops::Range<usize>> for S { /*...*/ }
fn i<'a>() -> impl Iterator<Item = ops::Example<'a>> {
    // ...
   const EXAMPLE: Vec<ops::Example<'static>> = Vec::new();
   EXAMPLE.into_iter()
}
type G = std::boxed::Box<dyn std::ops::FnOnce(isize) -> isize>;
}
```
 Path qualifiers
---------------

 Paths can be denoted with various leading qualifiers to change the meaning of how it is resolved.

 ### `::`

 Paths starting with `::` are considered to be *global paths* where the segments of the path start being resolved from a place which differs based on edition. Each identifier in the path must resolve to an item.

 
>  **Edition Differences**: In the 2015 Edition, identifiers resolve from the "crate root" (`crate::` in the 2018 edition), which contains a variety of different items, including external crates, default crates such as `std` or `core`, and items in the top level of the crate (including `use` imports).
> 
>  Beginning with the 2018 Edition, paths starting with `::` resolve from crates in the [extern prelude](names/preludes#extern-prelude). That is, they must be followed by the name of a crate.
> 
>  

 
```
#![allow(unused)]
fn main() {
pub fn foo() {
    // In the 2018 edition, this accesses `std` via the extern prelude.
    // In the 2015 edition, this accesses `std` via the crate root.
    let now = ::std::time::Instant::now();
    println!("{:?}", now);
}
}
```
 
```
// 2015 Edition
mod a {
    pub fn foo() {}
}
mod b {
    pub fn foo() {
        ::a::foo(); // call `a`'s foo function
        // In Rust 2018, `::a` would be interpreted as the crate `a`.
    }
}
fn main() {}
```
 ### `self`

 `self` resolves the path relative to the current module. `self` can only be used as the first segment, without a preceding `::`.

 
```
fn foo() {}
fn bar() {
    self::foo();
}
fn main() {}
```
 ### `Self`

 `Self`, with a capital "S", is used to refer to the implementing type within [traits](items/traits) and [implementations](items/implementations).

 `Self` can only be used as the first segment, without a preceding `::`.

 
```
#![allow(unused)]
fn main() {
trait T {
    type Item;
    const C: i32;
    // `Self` will be whatever type that implements `T`.
    fn new() -> Self;
    // `Self::Item` will be the type alias in the implementation.
    fn f(&self) -> Self::Item;
}
struct S;
impl T for S {
    type Item = i32;
    const C: i32 = 9;
    fn new() -> Self {           // `Self` is the type `S`.
        S
    }
    fn f(&self) -> Self::Item {  // `Self::Item` is the type `i32`.
        Self::C                  // `Self::C` is the constant value `9`.
    }
}
}
```
 ### `super`

 `super` in a path resolves to the parent module. It may only be used in leading segments of the path, possibly after an initial `self` segment.

 
```
mod a {
    pub fn foo() {}
}
mod b {
    pub fn foo() {
        super::a::foo(); // call a's foo function
    }
}
fn main() {}
```
 `super` may be repeated several times after the first `super` or `self` to refer to ancestor modules.

 
```
mod a {
    fn foo() {}

    mod b {
        mod c {
            fn foo() {
                super::super::foo(); // call a's foo function
                self::super::super::foo(); // call a's foo function
            }
        }
    }
}
fn main() {}
```
 ### `crate`

 `crate` resolves the path relative to the current crate. `crate` can only be used as the first segment, without a preceding `::`.

 
```
fn foo() {}
mod a {
    fn bar() {
        crate::foo();
    }
}
fn main() {}
```
 ### `$crate`

 `$crate` is only used within [macro transcribers](macros-by-example), and can only be used as the first segment, without a preceding `::`. `$crate` will expand to a path to access items from the top level of the crate where the macro is defined, regardless of which crate the macro is invoked.

 
```
pub fn increment(x: u32) -> u32 {
    x + 1
}

#[macro_export]
macro_rules! inc {
    ($x:expr) => ( $crate::increment($x) )
}
fn main() { }
```
 Canonical paths
---------------

 Items defined in a module or implementation have a *canonical path* that corresponds to where within its crate it is defined. All other paths to these items are aliases. The canonical path is defined as a *path prefix* appended by the path segment the item itself defines.

 [Implementations](items/implementations) and [use declarations](items/use-declarations) do not have canonical paths, although the items that implementations define do have them. Items defined in block expressions do not have canonical paths. Items defined in a module that does not have a canonical path do not have a canonical path. Associated items defined in an implementation that refers to an item without a canonical path, e.g. as the implementing type, the trait being implemented, a type parameter or bound on a type parameter, do not have canonical paths.

 The path prefix for modules is the canonical path to that module. For bare implementations, it is the canonical path of the item being implemented surrounded by angle (`<>`) brackets. For [trait implementations](items/implementations#trait-implementations), it is the canonical path of the item being implemented followed by `as` followed by the canonical path to the trait all surrounded in angle (`<>`) brackets.

 The canonical path is only meaningful within a given crate. There is no global namespace across crates; an item's canonical path merely identifies it within the crate.

 
```
// Comments show the canonical path of the item.

mod a { // crate::a
    pub struct Struct; // crate::a::Struct

    pub trait Trait { // crate::a::Trait
        fn f(&self); // crate::a::Trait::f
    }

    impl Trait for Struct {
        fn f(&self) {} // <crate::a::Struct as crate::a::Trait>::f
    }

    impl Struct {
        fn g(&self) {} // <crate::a::Struct>::g
    }
}

mod without { // crate::without
    fn canonicals() { // crate::without::canonicals
        struct OtherStruct; // None

        trait OtherTrait { // None
            fn g(&self); // None
        }

        impl OtherTrait for OtherStruct {
            fn g(&self) {} // None
        }

        impl OtherTrait for crate::a::Struct {
            fn g(&self) {} // None
        }

        impl crate::a::Trait for OtherStruct {
            fn f(&self) {} // None
        }
    }
}

fn main() {}
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/paths.html>

Name resolution
===============

 
>  **Note**: This is a placeholder for future expansion.
> 
>  



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/names/name-resolution.html>

Visibility and Privacy
======================

 
>  **Syntax**  
>  *Visibility* :  
>  `pub`  
>  | `pub` `(` `crate` `)`  
>  | `pub` `(` `self` `)`  
>  | `pub` `(` `super` `)`  
>  | `pub` `(` `in` [*SimplePath*](paths#simple-paths) `)`
> 
>  

 These two terms are often used interchangeably, and what they are attempting to convey is the answer to the question "Can this item be used at this location?"

 Rust's name resolution operates on a global hierarchy of namespaces. Each level in the hierarchy can be thought of as some item. The items are one of those mentioned above, but also include external crates. Declaring or defining a new module can be thought of as inserting a new tree into the hierarchy at the location of the definition.

 To control whether interfaces can be used across modules, Rust checks each use of an item to see whether it should be allowed or not. This is where privacy warnings are generated, or otherwise "you used a private item of another module and weren't allowed to."

 By default, everything is *private*, with two exceptions: Associated items in a `pub` Trait are public by default; Enum variants in a `pub` enum are also public by default. When an item is declared as `pub`, it can be thought of as being accessible to the outside world. For example:

 
```
fn main() {}
// Declare a private struct
struct Foo;

// Declare a public struct with a private field
pub struct Bar {
    field: i32,
}

// Declare a public enum with two public variants
pub enum State {
    PubliclyAccessibleState,
    PubliclyAccessibleState2,
}
```
 With the notion of an item being either public or private, Rust allows item accesses in two cases:

 1. If an item is public, then it can be accessed externally from some module `m` if you can access all the item's ancestor modules from `m`. You can also potentially be able to name the item through re-exports. See below.
2. If an item is private, it may be accessed by the current module and its descendants.

 These two cases are surprisingly powerful for creating module hierarchies exposing public APIs while hiding internal implementation details. To help explain, here's a few use cases and what they would entail:

 * A library developer needs to expose functionality to crates which link against their library. As a consequence of the first case, this means that anything which is usable externally must be `pub` from the root down to the destination item. Any private item in the chain will disallow external accesses.
* A crate needs a global available "helper module" to itself, but it doesn't want to expose the helper module as a public API. To accomplish this, the root of the crate's hierarchy would have a private module which then internally has a "public API". Because the entire crate is a descendant of the root, then the entire local crate can access this private module through the second case.
* When writing unit tests for a module, it's often a common idiom to have an immediate child of the module to-be-tested named `mod test`. This module could access any items of the parent module through the second case, meaning that internal implementation details could also be seamlessly tested from the child module.

 In the second case, it mentions that a private item "can be accessed" by the current module and its descendants, but the exact meaning of accessing an item depends on what the item is. Accessing a module, for example, would mean looking inside of it (to import more items). On the other hand, accessing a function would mean that it is invoked. Additionally, path expressions and import statements are considered to access an item in the sense that the import/expression is only valid if the destination is in the current visibility scope.

 Here's an example of a program which exemplifies the three cases outlined above:

 
```
// This module is private, meaning that no external crate can access this
// module. Because it is private at the root of this current crate, however, any
// module in the crate may access any publicly visible item in this module.
mod crate_helper_module {

    // This function can be used by anything in the current crate
    pub fn crate_helper() {}

    // This function *cannot* be used by anything else in the crate. It is not
    // publicly visible outside of the `crate_helper_module`, so only this
    // current module and its descendants may access it.
    fn implementation_detail() {}
}

// This function is "public to the root" meaning that it's available to external
// crates linking against this one.
pub fn public_api() {}

// Similarly to 'public_api', this module is public so external crates may look
// inside of it.
pub mod submodule {
    use crate::crate_helper_module;

    pub fn my_method() {
        // Any item in the local crate may invoke the helper module's public
        // interface through a combination of the two rules above.
        crate_helper_module::crate_helper();
    }

    // This function is hidden to any module which is not a descendant of
    // `submodule`
    fn my_implementation() {}

    #[cfg(test)]
    mod test {

        #[test]
        fn test_my_implementation() {
            // Because this module is a descendant of `submodule`, it's allowed
            // to access private items inside of `submodule` without a privacy
            // violation.
            super::my_implementation();
        }
    }
}

fn main() {}
```
 For a Rust program to pass the privacy checking pass, all paths must be valid accesses given the two rules above. This includes all use statements, expressions, types, etc.

 
`pub(in path)`, `pub(crate)`, `pub(super)`, and `pub(self)`
------------------------------------------------------------

 In addition to public and private, Rust allows users to declare an item as visible only within a given scope. The rules for `pub` restrictions are as follows:

 * `pub(in path)` makes an item visible within the provided `path`. `path` must be an ancestor module of the item whose visibility is being declared.
* `pub(crate)` makes an item visible within the current crate.
* `pub(super)` makes an item visible to the parent module. This is equivalent to `pub(in super)`.
* `pub(self)` makes an item visible to the current module. This is equivalent to `pub(in self)` or not using `pub` at all.

 
>  **Edition Differences**: 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.
> 
>  

 Here's an example:

 
```
pub mod outer_mod {
    pub mod inner_mod {
        // This function is visible within `outer_mod`
        pub(in crate::outer_mod) fn outer_mod_visible_fn() {}
        // Same as above, this is only valid in the 2015 edition.
        pub(in outer_mod) fn outer_mod_visible_fn_2015() {}

        // This function is visible to the entire crate
        pub(crate) fn crate_visible_fn() {}

        // This function is visible within `outer_mod`
        pub(super) fn super_mod_visible_fn() {
            // This function is visible since we're in the same `mod`
            inner_mod_visible_fn();
        }

        // This function is visible only within `inner_mod`,
        // which is the same as leaving it private.
        pub(self) fn inner_mod_visible_fn() {}
    }
    pub fn foo() {
        inner_mod::outer_mod_visible_fn();
        inner_mod::crate_visible_fn();
        inner_mod::super_mod_visible_fn();

        // This function is no longer visible since we're outside of `inner_mod`
        // Error! `inner_mod_visible_fn` is private
        //inner_mod::inner_mod_visible_fn();
    }
}

fn bar() {
    // This function is still visible since we're in the same crate
    outer_mod::inner_mod::crate_visible_fn();

    // This function is no longer visible since we're outside of `outer_mod`
    // Error! `super_mod_visible_fn` is private
    //outer_mod::inner_mod::super_mod_visible_fn();

    // This function is no longer visible since we're outside of `outer_mod`
    // Error! `outer_mod_visible_fn` is private
    //outer_mod::inner_mod::outer_mod_visible_fn();

    outer_mod::foo();
}

fn main() { bar() }
```
 
>  **Note:** This syntax only adds another restriction to the visibility of an item. It does not guarantee that the item is visible within all parts of the specified scope. To access an item, all of its parent items up to the current scope must still be visible as well.
> 
>  

 Re-exporting and Visibility
---------------------------

 Rust allows publicly re-exporting items through a `pub use` directive. Because this is a public directive, this allows the item to be used in the current module through the rules above. It essentially allows public access into the re-exported item. For example, this program is valid:

 
```
pub use self::implementation::api;

mod implementation {
    pub mod api {
        pub fn f() {}
    }
}

fn main() {}
```
 This means that any external crate referencing `implementation::api::f` would receive a privacy violation, while the path `api::f` would be allowed.

 When re-exporting a private item, it can be thought of as allowing the "privacy chain" being short-circuited through the reexport instead of passing through the namespace hierarchy as it normally would.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/visibility-and-privacy.html?highlight=pub>

Memory model
============

 Rust does not yet have a defined memory model. Various academics and industry professionals are working on various proposals, but for now, this is an under-defined place in the language.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/memory-model.html>

Memory allocation and lifetime
==============================

 The *items* of a program are those functions, modules, and types that have their value calculated at compile-time and stored uniquely in the memory image of the rust process. Items are neither dynamically allocated nor freed.

 The *heap* is a general term that describes boxes. The lifetime of an allocation in the heap depends on the lifetime of the box values pointing to it. Since box values may themselves be passed in and out of frames, or stored in the heap, heap allocations may outlive the frame they are allocated within. An allocation in the heap is guaranteed to reside at a single location in the heap for the whole lifetime of the allocation - it will never be relocated as a result of moving a box value.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/memory-allocation-and-lifetime.html>

Variables
=========

 A *variable* is a component of a stack frame, either a named function parameter, an anonymous [temporary](expressions#temporaries), or a named local variable.

 A *local variable* (or *stack-local* allocation) holds a value directly, allocated within the stack's memory. The value is a part of the stack frame.

 Local variables are immutable unless declared otherwise. For example: `let mut x = ...`.

 Function parameters are immutable unless declared with `mut`. The `mut` keyword applies only to the following parameter. For example: `|mut x, y|` and `fn f(mut x: Box<i32>, y: Box<i32>)` declare one mutable variable `x` and one immutable variable `y`.

 Local variables are not initialized when allocated. Instead, the entire frame worth of local variables are allocated, on frame-entry, in an uninitialized state. Subsequent statements within a function may or may not initialize the local variables. Local variables can be used only after they have been initialized through all reachable control flow paths.

 In this next example, `init_after_if` is initialized after the [`if` expression](expressions/if-expr#if-expressions) while `uninit_after_if` is not because it is not initialized in the `else` case.

 
```
#![allow(unused)]
fn main() {
fn random_bool() -> bool { true }
fn initialization_example() {
    let init_after_if: ();
    let uninit_after_if: ();

    if random_bool() {
        init_after_if = ();
        uninit_after_if = ();
    } else {
        init_after_if = ();
    }

    init_after_if; // ok
    // uninit_after_if; // err: use of possibly uninitialized `uninit_after_if`
}
}
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/variables.html>

Linkage
=======

 
>  Note: This section is described more in terms of the compiler than of the language.
> 
>  

 The compiler supports various methods to link crates together both statically and dynamically. This section will explore the various methods to link crates together, and more information about native libraries can be found in the [FFI section of the book](../book/ch19-01-unsafe-rust#using-extern-functions-to-call-external-code).

 In one session of compilation, the compiler can generate multiple artifacts through the usage of either command line flags or the `crate_type` attribute. If one or more command line flags are specified, all `crate_type` attributes will be ignored in favor of only building the artifacts specified by command line.

 * `--crate-type=bin`, `#![crate_type = "bin"]` - A runnable executable will be produced. This requires that there is a `main` function in the crate which will be run when the program begins executing. This will link in all Rust and native dependencies, producing a single distributable binary. This is the default crate type.
* `--crate-type=lib`, `#![crate_type = "lib"]` - A Rust library will be produced. This is an ambiguous concept as to what exactly is produced because a library can manifest itself in several forms. The purpose of this generic `lib` option is to generate the "compiler recommended" style of library. The output library will always be usable by rustc, but the actual type of library may change from time-to-time. The remaining output types are all different flavors of libraries, and the `lib` type can be seen as an alias for one of them (but the actual one is compiler-defined).
* `--crate-type=dylib`, `#![crate_type = "dylib"]` - A dynamic Rust library will be produced. This is different from the `lib` output type in that this forces dynamic library generation. The resulting dynamic library can be used as a dependency for other libraries and/or executables. This output type will create `*.so` files on Linux, `*.dylib` files on macOS, and `*.dll` files on Windows.
* `--crate-type=staticlib`, `#![crate_type = "staticlib"]` - A static system library will be produced. This is different from other library outputs in that the compiler will never attempt to link to `staticlib` outputs. The purpose of this output type is to create a static library containing all of the local crate's code along with all upstream dependencies. This output type will create `*.a` files on Linux, macOS and Windows (MinGW), and `*.lib` files on Windows (MSVC). This format is recommended for use in situations such as linking Rust code into an existing non-Rust application because it will not have dynamic dependencies on other Rust code.
* `--crate-type=cdylib`, `#![crate_type = "cdylib"]` - A dynamic system library will be produced. This is used when compiling a dynamic library to be loaded from another language. This output type will create `*.so` files on Linux, `*.dylib` files on macOS, and `*.dll` files on Windows.
* `--crate-type=rlib`, `#![crate_type = "rlib"]` - A "Rust library" file will be produced. This is used as an intermediate artifact and can be thought of as a "static Rust library". These `rlib` files, unlike `staticlib` files, are interpreted by the compiler in future linkage. This essentially means that `rustc` will look for metadata in `rlib` files like it looks for metadata in dynamic libraries. This form of output is used to produce statically linked executables as well as `staticlib` outputs.
* `--crate-type=proc-macro`, `#![crate_type = "proc-macro"]` - The output produced is not specified, but if a `-L` path is provided to it then the compiler will recognize the output artifacts as a macro and it can be loaded for a program. Crates compiled with this crate type must only export [procedural macros](procedural-macros). The compiler will automatically set the `proc_macro` [configuration option](conditional-compilation). The crates are always compiled with the same target that the compiler itself was built with. For example, if you are executing the compiler from Linux with an `x86_64` CPU, the target will be `x86_64-unknown-linux-gnu` even if the crate is a dependency of another crate being built for a different target.

 Note that these outputs are stackable in the sense that if multiple are specified, then the compiler will produce each form of output without having to recompile. However, this only applies for outputs specified by the same method. If only `crate_type` attributes are specified, then they will all be built, but if one or more `--crate-type` command line flags are specified, then only those outputs will be built.

 With all these different kinds of outputs, if crate A depends on crate B, then the compiler could find B in various different forms throughout the system. The only forms looked for by the compiler, however, are the `rlib` format and the dynamic library format. With these two options for a dependent library, the compiler must at some point make a choice between these two formats. With this in mind, the compiler follows these rules when determining what format of dependencies will be used:

 1. If a static library is being produced, all upstream dependencies are required to be available in `rlib` formats. This requirement stems from the reason that a dynamic library cannot be converted into a static format.

 Note that it is impossible to link in native dynamic dependencies to a static library, and in this case warnings will be printed about all unlinked native dynamic dependencies.
2. If an `rlib` file is being produced, then there are no restrictions on what format the upstream dependencies are available in. It is simply required that all upstream dependencies be available for reading metadata from.

 The reason for this is that `rlib` files do not contain any of their upstream dependencies. It wouldn't be very efficient for all `rlib` files to contain a copy of `libstd.rlib`!
3. If an executable is being produced and the `-C prefer-dynamic` flag is not specified, then dependencies are first attempted to be found in the `rlib` format. If some dependencies are not available in an rlib format, then dynamic linking is attempted (see below).
4. If a dynamic library or an executable that is being dynamically linked is being produced, then the compiler will attempt to reconcile the available dependencies in either the rlib or dylib format to create a final product.

 A major goal of the compiler is to ensure that a library never appears more than once in any artifact. For example, if dynamic libraries B and C were each statically linked to library A, then a crate could not link to B and C together because there would be two copies of A. The compiler allows mixing the rlib and dylib formats, but this restriction must be satisfied.

 The compiler currently implements no method of hinting what format a library should be linked with. When dynamically linking, the compiler will attempt to maximize dynamic dependencies while still allowing some dependencies to be linked in via an rlib.

 For most situations, having all libraries available as a dylib is recommended if dynamically linking. For other situations, the compiler will emit a warning if it is unable to determine which formats to link each library with.

 In general, `--crate-type=bin` or `--crate-type=lib` should be sufficient for all compilation needs, and the other options are just available if more fine-grained control is desired over the output format of a crate.

 Static and dynamic C runtimes
-----------------------------

 The standard library in general strives to support both statically linked and dynamically linked C runtimes for targets as appropriate. For example the `x86_64-pc-windows-msvc` and `x86_64-unknown-linux-musl` targets typically come with both runtimes and the user selects which one they'd like. All targets in the compiler have a default mode of linking to the C runtime. Typically targets are linked dynamically by default, but there are exceptions which are static by default such as:

 * `arm-unknown-linux-musleabi`
* `arm-unknown-linux-musleabihf`
* `armv7-unknown-linux-musleabihf`
* `i686-unknown-linux-musl`
* `x86_64-unknown-linux-musl`

 The linkage of the C runtime is configured to respect the `crt-static` target feature. These target features are typically configured from the command line via flags to the compiler itself. For example to enable a static runtime you would execute:

 
```
rustc -C target-feature=+crt-static foo.rs

```
 whereas to link dynamically to the C runtime you would execute:

 
```
rustc -C target-feature=-crt-static foo.rs

```
 Targets which do not support switching between linkage of the C runtime will ignore this flag. It's recommended to inspect the resulting binary to ensure that it's linked as you would expect after the compiler succeeds.

 Crates may also learn about how the C runtime is being linked. Code on MSVC, for example, needs to be compiled differently (e.g. with `/MT` or `/MD`) depending on the runtime being linked. This is exported currently through the [`cfg` attribute `target_feature` option](conditional-compilation#target_feature):

 
```
#![allow(unused)]
fn main() {
#[cfg(target_feature = "crt-static")]
fn foo() {
    println!("the C runtime should be statically linked");
}

#[cfg(not(target_feature = "crt-static"))]
fn foo() {
    println!("the C runtime should be dynamically linked");
}
}
```
 Also note that Cargo build scripts can learn about this feature through [environment variables](https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts). In a build script you can detect the linkage via:

 
```
use std::env;

fn main() {
    let linkage = env::var("CARGO_CFG_TARGET_FEATURE").unwrap_or(String::new());

    if linkage.contains("crt-static") {
        println!("the C runtime will be statically linked");
    } else {
        println!("the C runtime will be dynamically linked");
    }
}
```
 To use this feature locally, you typically will use the `RUSTFLAGS` environment variable to specify flags to the compiler through Cargo. For example to compile a statically linked binary on MSVC you would execute:

 
```
RUSTFLAGS='-C target-feature=+crt-static' cargo build --target x86_64-pc-windows-msvc

```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/linkage.html>

Inline assembly
===============

 Support for inline assembly is provided via the [`asm!`](https://doc.rust-lang.org/core/arch/macro.asm.html) and [`global_asm!`](https://doc.rust-lang.org/core/arch/macro.global_asm.html) macros. It can be used to embed handwritten assembly in the assembly output generated by the compiler.

 Support for inline assembly is stable on the following architectures:

 * x86 and x86-64
* ARM
* AArch64
* RISC-V

 The compiler will emit an error if `asm!` is used on an unsupported target.

 Example
-------

 
```
#![allow(unused)]
fn main() {
#[cfg(target_arch = "x86_64")] {
use std::arch::asm;

// Multiply x by 6 using shifts and adds
let mut x: u64 = 4;
unsafe {
    asm!(
        "mov {tmp}, {x}",
        "shl {tmp}, 1",
        "shl {x}, 2",
        "add {x}, {tmp}",
        x = inout(reg) x,
        tmp = out(reg) _,
    );
}
assert_eq!(x, 4 * 6);
}
}
```
 Syntax
------

 The following ABNF specifies the general syntax:

 
```
format_string := STRING_LITERAL / RAW_STRING_LITERAL
dir_spec := "in" / "out" / "lateout" / "inout" / "inlateout"
reg_spec := <register class> / "\"" <explicit register> "\""
operand_expr := expr / "_" / expr "=>" expr / expr "=>" "_"
reg_operand := [ident "="] dir_spec "(" reg_spec ")" operand_expr
clobber_abi := "clobber_abi(" <abi> *("," <abi>) [","] ")"
option := "pure" / "nomem" / "readonly" / "preserves_flags" / "noreturn" / "nostack" / "att_syntax" / "raw"
options := "options(" option *("," option) [","] ")"
operand := reg_operand / clobber_abi / options
asm := "asm!(" format_string *("," format_string) *("," operand) [","] ")"
global_asm := "global_asm!(" format_string *("," format_string) *("," operand) [","] ")"

```
 Scope
-----

 Inline assembly can be used in one of two ways.

 With the `asm!` macro, the assembly code is emitted in a function scope and integrated into the compiler-generated assembly code of a function. This assembly code must obey [strict rules](#rules-for-inline-assembly) to avoid undefined behavior. Note that in some cases the compiler may choose to emit the assembly code as a separate function and generate a call to it.

 With the `global_asm!` macro, the assembly code is emitted in a global scope, outside a function. This can be used to hand-write entire functions using assembly code, and generally provides much more freedom to use arbitrary registers and assembler directives.

 Template string arguments
-------------------------

 The assembler template uses the same syntax as [format strings](../std/fmt/index#syntax) (i.e. placeholders are specified by curly braces). The corresponding arguments are accessed in order, by index, or by name. However, implicit named arguments (introduced by [RFC #2795](https://github.com/rust-lang/rfcs/pull/2795)) are not supported.

 An `asm!` invocation may have one or more template string arguments; an `asm!` with multiple template string arguments is treated as if all the strings were concatenated with a `\n` between them. The expected usage is for each template string argument to correspond to a line of assembly code. All template string arguments must appear before any other arguments.

 As with format strings, positional arguments must appear before named arguments and explicit [register operands](#register-operands).

 Explicit register operands cannot be used by placeholders in the template string. All other named and positional operands must appear at least once in the template string, otherwise a compiler error is generated.

 The exact assembly code syntax is target-specific and opaque to the compiler except for the way operands are substituted into the template string to form the code passed to the assembler.

 Currently, all supported targets follow the assembly code syntax used by LLVM's internal assembler which usually corresponds to that of the GNU assembler (GAS). On x86, the `.intel_syntax noprefix` mode of GAS is used by default. On ARM, the `.syntax unified` mode is used. These targets impose an additional restriction on the assembly code: any assembler state (e.g. the current section which can be changed with `.section`) must be restored to its original value at the end of the asm string. Assembly code that does not conform to the GAS syntax will result in assembler-specific behavior. Further constraints on the directives used by inline assembly are indicated by [Directives Support](#directives-support).

 Operand type
------------

 Several types of operands are supported:

 * `in(<reg>) <expr>`
	+ `<reg>` can refer to a register class or an explicit register. The allocated register name is substituted into the asm template string.
	+ The allocated register will contain the value of `<expr>` at the start of the asm code.
	+ The allocated register must contain the same value at the end of the asm code (except if a `lateout` is allocated to the same register).
* `out(<reg>) <expr>`
	+ `<reg>` can refer to a register class or an explicit register. The allocated register name is substituted into the asm template string.
	+ The allocated register will contain an undefined value at the start of the asm code.
	+ `<expr>` must be a (possibly uninitialized) place expression, to which the contents of the allocated register are written at the end of the asm code.
	+ An underscore (`_`) may be specified instead of an expression, which will cause the contents of the register to be discarded at the end of the asm code (effectively acting as a clobber).
* `lateout(<reg>) <expr>`
	+ Identical to `out` except that the register allocator can reuse a register allocated to an `in`.
	+ You should only write to the register after all inputs are read, otherwise you may clobber an input.
* `inout(<reg>) <expr>`
	+ `<reg>` can refer to a register class or an explicit register. The allocated register name is substituted into the asm template string.
	+ The allocated register will contain the value of `<expr>` at the start of the asm code.
	+ `<expr>` must be a mutable initialized place expression, to which the contents of the allocated register are written at the end of the asm code.
* `inout(<reg>) <in expr> => <out expr>`
	+ Same as `inout` except that the initial value of the register is taken from the value of `<in expr>`.
	+ `<out expr>` must be a (possibly uninitialized) place expression, to which the contents of the allocated register are written at the end of the asm code.
	+ An underscore (`_`) may be specified instead of an expression for `<out expr>`, which will cause the contents of the register to be discarded at the end of the asm code (effectively acting as a clobber).
	+ `<in expr>` and `<out expr>` may have different types.
* `inlateout(<reg>) <expr>` / `inlateout(<reg>) <in expr> => <out expr>`
	+ Identical to `inout` except that the register allocator can reuse a register allocated to an `in` (this can happen if the compiler knows the `in` has the same initial value as the `inlateout`).
	+ You should only write to the register after all inputs are read, otherwise you may clobber an input.
* `sym <path>`
	+ `<path>` must refer to a `fn` or `static`.
	+ A mangled symbol name referring to the item is substituted into the asm template string.
	+ The substituted string does not include any modifiers (e.g. GOT, PLT, relocations, etc).
	+ `<path>` is allowed to point to a `#[thread_local]` static, in which case the asm code can combine the symbol with relocations (e.g. `@plt`, `@TPOFF`) to read from thread-local data.

 Operand expressions are evaluated from left to right, just like function call arguments. After the `asm!` has executed, outputs are written to in left to right order. This is significant if two outputs point to the same place: that place will contain the value of the rightmost output.

 Since `global_asm!` exists outside a function, it can only use `sym` operands.

 Register operands
-----------------

 Input and output operands can be specified either as an explicit register or as a register class from which the register allocator can select a register. Explicit registers are specified as string literals (e.g. `"eax"`) while register classes are specified as identifiers (e.g. `reg`).

 Note that explicit registers treat register aliases (e.g. `r14` vs `lr` on ARM) and smaller views of a register (e.g. `eax` vs `rax`) as equivalent to the base register. It is a compile-time error to use the same explicit register for two input operands or two output operands. Additionally, it is also a compile-time error to use overlapping registers (e.g. ARM VFP) in input operands or in output operands.

 Only the following types are allowed as operands for inline assembly:

 * Integers (signed and unsigned)
* Floating-point numbers
* Pointers (thin only)
* Function pointers
* SIMD vectors (structs defined with `#[repr(simd)]` and which implement `Copy`). This includes architecture-specific vector types defined in `std::arch` such as `__m128` (x86) or `int8x16_t` (ARM).

 Here is the list of currently supported register classes:

 


| Architecture | Register class | Registers | LLVM constraint code |
| --- | --- | --- | --- |
| x86 | `reg` | `ax`, `bx`, `cx`, `dx`, `si`, `di`, `bp`, `r[8-15]` (x86-64 only) | `r` |
| x86 | `reg_abcd` | `ax`, `bx`, `cx`, `dx` | `Q` |
| x86-32 | `reg_byte` | `al`, `bl`, `cl`, `dl`, `ah`, `bh`, `ch`, `dh` | `q` |
| x86-64 | `reg_byte`\* | `al`, `bl`, `cl`, `dl`, `sil`, `dil`, `bpl`, `r[8-15]b` | `q` |
| x86 | `xmm_reg` | `xmm[0-7]` (x86) `xmm[0-15]` (x86-64) | `x` |
| x86 | `ymm_reg` | `ymm[0-7]` (x86) `ymm[0-15]` (x86-64) | `x` |
| x86 | `zmm_reg` | `zmm[0-7]` (x86) `zmm[0-31]` (x86-64) | `v` |
| x86 | `kreg` | `k[1-7]` | `Yk` |
| x86 | `kreg0` | `k0` | Only clobbers |
| x86 | `x87_reg` | `st([0-7])` | Only clobbers |
| x86 | `mmx_reg` | `mm[0-7]` | Only clobbers |
| x86-64 | `tmm_reg` | `tmm[0-7]` | Only clobbers |
| AArch64 | `reg` | `x[0-30]` | `r` |
| AArch64 | `vreg` | `v[0-31]` | `w` |
| AArch64 | `vreg_low16` | `v[0-15]` | `x` |
| AArch64 | `preg` | `p[0-15]`, `ffr` | Only clobbers |
| ARM (ARM/Thumb2) | `reg` | `r[0-12]`, `r14` | `r` |
| ARM (Thumb1) | `reg` | `r[0-7]` | `r` |
| ARM | `sreg` | `s[0-31]` | `t` |
| ARM | `sreg_low16` | `s[0-15]` | `x` |
| ARM | `dreg` | `d[0-31]` | `w` |
| ARM | `dreg_low16` | `d[0-15]` | `t` |
| ARM | `dreg_low8` | `d[0-8]` | `x` |
| ARM | `qreg` | `q[0-15]` | `w` |
| ARM | `qreg_low8` | `q[0-7]` | `t` |
| ARM | `qreg_low4` | `q[0-3]` | `x` |
| RISC-V | `reg` | `x1`, `x[5-7]`, `x[9-15]`, `x[16-31]` (non-RV32E) | `r` |
| RISC-V | `freg` | `f[0-31]` | `f` |
| RISC-V | `vreg` | `v[0-31]` | Only clobbers |

  
>  **Notes**:
> 
>  * On x86 we treat `reg_byte` differently from `reg` because the compiler can allocate `al` and `ah` separately whereas `reg` reserves the whole register.
> * On x86-64 the high byte registers (e.g. `ah`) are not available in the `reg_byte` register class.
> * Some register classes are marked as "Only clobbers" which means that registers in these classes cannot be used for inputs or outputs, only clobbers of the form `out(<explicit register>) _` or `lateout(<explicit register>) _`.
> 
>  

 Each register class has constraints on which value types they can be used with. This is necessary because the way a value is loaded into a register depends on its type. For example, on big-endian systems, loading a `i32x4` and a `i8x16` into a SIMD register may result in different register contents even if the byte-wise memory representation of both values is identical. The availability of supported types for a particular register class may depend on what target features are currently enabled.

 


| Architecture | Register class | Target feature | Allowed types |
| --- | --- | --- | --- |
| x86-32 | `reg` | None | `i16`, `i32`, `f32` |
| x86-64 | `reg` | None | `i16`, `i32`, `f32`, `i64`, `f64` |
| x86 | `reg_byte` | None | `i8` |
| x86 | `xmm_reg` | `sse` | `i32`, `f32`, `i64`, `f64`,  `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2` |
| x86 | `ymm_reg` | `avx` | `i32`, `f32`, `i64`, `f64`,  `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2`  `i8x32`, `i16x16`, `i32x8`, `i64x4`, `f32x8`, `f64x4` |
| x86 | `zmm_reg` | `avx512f` | `i32`, `f32`, `i64`, `f64`,  `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2`  `i8x32`, `i16x16`, `i32x8`, `i64x4`, `f32x8`, `f64x4`  `i8x64`, `i16x32`, `i32x16`, `i64x8`, `f32x16`, `f64x8` |
| x86 | `kreg` | `avx512f` | `i8`, `i16` |
| x86 | `kreg` | `avx512bw` | `i32`, `i64` |
| x86 | `mmx_reg` | N/A | Only clobbers |
| x86 | `x87_reg` | N/A | Only clobbers |
| x86 | `tmm_reg` | N/A | Only clobbers |
| AArch64 | `reg` | None | `i8`, `i16`, `i32`, `f32`, `i64`, `f64` |
| AArch64 | `vreg` | `neon` | `i8`, `i16`, `i32`, `f32`, `i64`, `f64`,  `i8x8`, `i16x4`, `i32x2`, `i64x1`, `f32x2`, `f64x1`,  `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2` |
| AArch64 | `preg` | N/A | Only clobbers |
| ARM | `reg` | None | `i8`, `i16`, `i32`, `f32` |
| ARM | `sreg` | `vfp2` | `i32`, `f32` |
| ARM | `dreg` | `vfp2` | `i64`, `f64`, `i8x8`, `i16x4`, `i32x2`, `i64x1`, `f32x2` |
| ARM | `qreg` | `neon` | `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4` |
| RISC-V32 | `reg` | None | `i8`, `i16`, `i32`, `f32` |
| RISC-V64 | `reg` | None | `i8`, `i16`, `i32`, `f32`, `i64`, `f64` |
| RISC-V | `freg` | `f` | `f32` |
| RISC-V | `freg` | `d` | `f64` |
| RISC-V | `vreg` | N/A | Only clobbers |

  
>  **Note**: For the purposes of the above table pointers, function pointers and `isize`/`usize` are treated as the equivalent integer type (`i16`/`i32`/`i64` depending on the target).
> 
>  

 If a value is of a smaller size than the register it is allocated in then the upper bits of that register will have an undefined value for inputs and will be ignored for outputs. The only exception is the `freg` register class on RISC-V where `f32` values are NaN-boxed in a `f64` as required by the RISC-V architecture.

 When separate input and output expressions are specified for an `inout` operand, both expressions must have the same type. The only exception is if both operands are pointers or integers, in which case they are only required to have the same size. This restriction exists because the register allocators in LLVM and GCC sometimes cannot handle tied operands with different types.

 Register names
--------------

 Some registers have multiple names. These are all treated by the compiler as identical to the base register name. Here is the list of all supported register aliases:

 


| Architecture | Base register | Aliases |
| --- | --- | --- |
| x86 | `ax` | `eax`, `rax` |
| x86 | `bx` | `ebx`, `rbx` |
| x86 | `cx` | `ecx`, `rcx` |
| x86 | `dx` | `edx`, `rdx` |
| x86 | `si` | `esi`, `rsi` |
| x86 | `di` | `edi`, `rdi` |
| x86 | `bp` | `bpl`, `ebp`, `rbp` |
| x86 | `sp` | `spl`, `esp`, `rsp` |
| x86 | `ip` | `eip`, `rip` |
| x86 | `st(0)` | `st` |
| x86 | `r[8-15]` | `r[8-15]b`, `r[8-15]w`, `r[8-15]d` |
| x86 | `xmm[0-31]` | `ymm[0-31]`, `zmm[0-31]` |
| AArch64 | `x[0-30]` | `w[0-30]` |
| AArch64 | `x29` | `fp` |
| AArch64 | `x30` | `lr` |
| AArch64 | `sp` | `wsp` |
| AArch64 | `xzr` | `wzr` |
| AArch64 | `v[0-31]` | `b[0-31]`, `h[0-31]`, `s[0-31]`, `d[0-31]`, `q[0-31]` |
| ARM | `r[0-3]` | `a[1-4]` |
| ARM | `r[4-9]` | `v[1-6]` |
| ARM | `r9` | `rfp` |
| ARM | `r10` | `sl` |
| ARM | `r11` | `fp` |
| ARM | `r12` | `ip` |
| ARM | `r13` | `sp` |
| ARM | `r14` | `lr` |
| ARM | `r15` | `pc` |
| RISC-V | `x0` | `zero` |
| RISC-V | `x1` | `ra` |
| RISC-V | `x2` | `sp` |
| RISC-V | `x3` | `gp` |
| RISC-V | `x4` | `tp` |
| RISC-V | `x[5-7]` | `t[0-2]` |
| RISC-V | `x8` | `fp`, `s0` |
| RISC-V | `x9` | `s1` |
| RISC-V | `x[10-17]` | `a[0-7]` |
| RISC-V | `x[18-27]` | `s[2-11]` |
| RISC-V | `x[28-31]` | `t[3-6]` |
| RISC-V | `f[0-7]` | `ft[0-7]` |
| RISC-V | `f[8-9]` | `fs[0-1]` |
| RISC-V | `f[10-17]` | `fa[0-7]` |
| RISC-V | `f[18-27]` | `fs[2-11]` |
| RISC-V | `f[28-31]` | `ft[8-11]` |

  Some registers cannot be used for input or output operands:

 


| Architecture | Unsupported register | Reason |
| --- | --- | --- |
| All | `sp` | The stack pointer must be restored to its original value at the end of an asm code block. |
| All | `bp` (x86), `x29` (AArch64), `x8` (RISC-V) | The frame pointer cannot be used as an input or output. |
| ARM | `r7` or `r11` | On ARM the frame pointer can be either `r7` or `r11` depending on the target. The frame pointer cannot be used as an input or output. |
| All | `si` (x86-32), `bx` (x86-64), `r6` (ARM), `x19` (AArch64), `x9` (RISC-V) | This is used internally by LLVM as a "base pointer" for functions with complex stack frames. |
| x86 | `ip` | This is the program counter, not a real register. |
| AArch64 | `xzr` | This is a constant zero register which can't be modified. |
| AArch64 | `x18` | This is an OS-reserved register on some AArch64 targets. |
| ARM | `pc` | This is the program counter, not a real register. |
| ARM | `r9` | This is an OS-reserved register on some ARM targets. |
| RISC-V | `x0` | This is a constant zero register which can't be modified. |
| RISC-V | `gp`, `tp` | These registers are reserved and cannot be used as inputs or outputs. |

  The frame pointer and base pointer registers are reserved for internal use by LLVM. While `asm!` statements cannot explicitly specify the use of reserved registers, in some cases LLVM will allocate one of these reserved registers for `reg` operands. Assembly code making use of reserved registers should be careful since `reg` operands may use the same registers.

 Template modifiers
------------------

 The placeholders can be augmented by modifiers which are specified after the `:` in the curly braces. These modifiers do not affect register allocation, but change the way operands are formatted when inserted into the template string. Only one modifier is allowed per template placeholder.

 The supported modifiers are a subset of LLVM's (and GCC's) [asm template argument modifiers](http://llvm.org/docs/LangRef.html#asm-template-argument-modifiers), but do not use the same letter codes.

 


| Architecture | Register class | Modifier | Example output | LLVM modifier |
| --- | --- | --- | --- | --- |
| x86-32 | `reg` | None | `eax` | `k` |
| x86-64 | `reg` | None | `rax` | `q` |
| x86-32 | `reg_abcd` | `l` | `al` | `b` |
| x86-64 | `reg` | `l` | `al` | `b` |
| x86 | `reg_abcd` | `h` | `ah` | `h` |
| x86 | `reg` | `x` | `ax` | `w` |
| x86 | `reg` | `e` | `eax` | `k` |
| x86-64 | `reg` | `r` | `rax` | `q` |
| x86 | `reg_byte` | None | `al` / `ah` | None |
| x86 | `xmm_reg` | None | `xmm0` | `x` |
| x86 | `ymm_reg` | None | `ymm0` | `t` |
| x86 | `zmm_reg` | None | `zmm0` | `g` |
| x86 | `*mm_reg` | `x` | `xmm0` | `x` |
| x86 | `*mm_reg` | `y` | `ymm0` | `t` |
| x86 | `*mm_reg` | `z` | `zmm0` | `g` |
| x86 | `kreg` | None | `k1` | None |
| AArch64 | `reg` | None | `x0` | `x` |
| AArch64 | `reg` | `w` | `w0` | `w` |
| AArch64 | `reg` | `x` | `x0` | `x` |
| AArch64 | `vreg` | None | `v0` | None |
| AArch64 | `vreg` | `v` | `v0` | None |
| AArch64 | `vreg` | `b` | `b0` | `b` |
| AArch64 | `vreg` | `h` | `h0` | `h` |
| AArch64 | `vreg` | `s` | `s0` | `s` |
| AArch64 | `vreg` | `d` | `d0` | `d` |
| AArch64 | `vreg` | `q` | `q0` | `q` |
| ARM | `reg` | None | `r0` | None |
| ARM | `sreg` | None | `s0` | None |
| ARM | `dreg` | None | `d0` | `P` |
| ARM | `qreg` | None | `q0` | `q` |
| ARM | `qreg` | `e` / `f` | `d0` / `d1` | `e` / `f` |
| RISC-V | `reg` | None | `x1` | None |
| RISC-V | `freg` | None | `f0` | None |

  
>  **Notes**:
> 
>  * on ARM `e` / `f`: this prints the low or high doubleword register name of a NEON quad (128-bit) register.
> * on x86: our behavior for `reg` with no modifiers differs from what GCC does. GCC will infer the modifier based on the operand value type, while we default to the full register size.
> * on x86 `xmm_reg`: the `x`, `t` and `g` LLVM modifiers are not yet implemented in LLVM (they are supported by GCC only), but this should be a simple change.
> 
>  

 As stated in the previous section, passing an input value smaller than the register width will result in the upper bits of the register containing undefined values. This is not a problem if the inline asm only accesses the lower bits of the register, which can be done by using a template modifier to use a subregister name in the asm code (e.g. `ax` instead of `rax`). Since this an easy pitfall, the compiler will suggest a template modifier to use where appropriate given the input type. If all references to an operand already have modifiers then the warning is suppressed for that operand.

 ABI clobbers
------------

 The `clobber_abi` keyword can be used to apply a default set of clobbers to an `asm!` block. This will automatically insert the necessary clobber constraints as needed for calling a function with a particular calling convention: if the calling convention does not fully preserve the value of a register across a call then `lateout("...") _` is implicitly added to the operands list (where the `...` is replaced by the register's name).

 `clobber_abi` may be specified any number of times. It will insert a clobber for all unique registers in the union of all specified calling conventions.

 Generic register class outputs are disallowed by the compiler when `clobber_abi` is used: all outputs must specify an explicit register. Explicit register outputs have precedence over the implicit clobbers inserted by `clobber_abi`: a clobber will only be inserted for a register if that register is not used as an output. The following ABIs can be used with `clobber_abi`:

 


| Architecture | ABI name | Clobbered registers |
| --- | --- | --- |
| x86-32 | `"C"`, `"system"`, `"efiapi"`, `"cdecl"`, `"stdcall"`, `"fastcall"` | `ax`, `cx`, `dx`, `xmm[0-7]`, `mm[0-7]`, `k[0-7]`, `st([0-7])` |
| x86-64 | `"C"`, `"system"` (on Windows), `"efiapi"`, `"win64"` | `ax`, `cx`, `dx`, `r[8-11]`, `xmm[0-31]`, `mm[0-7]`, `k[0-7]`, `st([0-7])`, `tmm[0-7]` |
| x86-64 | `"C"`, `"system"` (on non-Windows), `"sysv64"` | `ax`, `cx`, `dx`, `si`, `di`, `r[8-11]`, `xmm[0-31]`, `mm[0-7]`, `k[0-7]`, `st([0-7])`, `tmm[0-7]` |
| AArch64 | `"C"`, `"system"`, `"efiapi"` | `x[0-17]`, `x18`\*, `x30`, `v[0-31]`, `p[0-15]`, `ffr` |
| ARM | `"C"`, `"system"`, `"efiapi"`, `"aapcs"` | `r[0-3]`, `r12`, `r14`, `s[0-15]`, `d[0-7]`, `d[16-31]` |
| RISC-V | `"C"`, `"system"`, `"efiapi"` | `x1`, `x[5-7]`, `x[10-17]`, `x[28-31]`, `f[0-7]`, `f[10-17]`, `f[28-31]`, `v[0-31]` |

  
>  Notes:
> 
>  * On AArch64 `x18` only included in the clobber list if it is not considered as a reserved register on the target.
> 
>  

 The list of clobbered registers for each ABI is updated in rustc as architectures gain new registers: this ensures that `asm!` clobbers will continue to be correct when LLVM starts using these new registers in its generated code.

 Options
-------

 Flags are used to further influence the behavior of the inline assembly block. Currently the following options are defined:

 * `pure`: The `asm!` block has no side effects, and its outputs depend only on its direct inputs (i.e. the values themselves, not what they point to) or values read from memory (unless the `nomem` options is also set). This allows the compiler to execute the `asm!` block fewer times than specified in the program (e.g. by hoisting it out of a loop) or even eliminate it entirely if the outputs are not used.
* `nomem`: The `asm!` blocks does not read or write to any memory. This allows the compiler to cache the values of modified global variables in registers across the `asm!` block since it knows that they are not read or written to by the `asm!`.
* `readonly`: The `asm!` block does not write to any memory. This allows the compiler to cache the values of unmodified global variables in registers across the `asm!` block since it knows that they are not written to by the `asm!`.
* `preserves_flags`: The `asm!` block does not modify the flags register (defined in the rules below). This allows the compiler to avoid recomputing the condition flags after the `asm!` block.
* `noreturn`: The `asm!` block never returns, and its return type is defined as `!` (never). Behavior is undefined if execution falls through past the end of the asm code. A `noreturn` asm block behaves just like a function which doesn't return; notably, local variables in scope are not dropped before it is invoked.
* `nostack`: The `asm!` block does not push data to the stack, or write to the stack red-zone (if supported by the target). If this option is *not* used then the stack pointer is guaranteed to be suitably aligned (according to the target ABI) for a function call.
* `att_syntax`: This option is only valid on x86, and causes the assembler to use the `.att_syntax prefix` mode of the GNU assembler. Register operands are substituted in with a leading `%`.
* `raw`: This causes the template string to be parsed as a raw assembly string, with no special handling for `{` and `}`. This is primarily useful when including raw assembly code from an external file using `include_str!`.

 The compiler performs some additional checks on options:

 * The `nomem` and `readonly` options are mutually exclusive: it is a compile-time error to specify both.
* The `pure` option must be combined with either the `nomem` or `readonly` options, otherwise a compile-time error is emitted.
* It is a compile-time error to specify `pure` on an asm block with no outputs or only discarded outputs (`_`).
* It is a compile-time error to specify `noreturn` on an asm block with outputs.

 `global_asm!` only supports the `att_syntax` and `raw` options. The remaining options are not meaningful for global-scope inline assembly

 Rules for inline assembly
-------------------------

 To avoid undefined behavior, these rules must be followed when using function-scope inline assembly (`asm!`):

 * Any registers not specified as inputs will contain an undefined value on entry to the asm block.
	+ An "undefined value" in the context of inline assembly means that the register can (non-deterministically) have any one of the possible values allowed by the architecture. Notably it is not the same as an LLVM `undef` which can have a different value every time you read it (since such a concept does not exist in assembly code).
* Any registers not specified as outputs must have the same value upon exiting the asm block as they had on entry, otherwise behavior is undefined.
	+ This only applies to registers which can be specified as an input or output. Other registers follow target-specific rules.
	+ Note that a `lateout` may be allocated to the same register as an `in`, in which case this rule does not apply. Code should not rely on this however since it depends on the results of register allocation.
* Behavior is undefined if execution unwinds out of an asm block.
	+ This also applies if the assembly code calls a function which then unwinds.
* The set of memory locations that assembly code is allowed to read and write are the same as those allowed for an FFI function.
	+ Refer to the unsafe code guidelines for the exact rules.
	+ If the `readonly` option is set, then only memory reads are allowed.
	+ If the `nomem` option is set then no reads or writes to memory are allowed.
	+ These rules do not apply to memory which is private to the asm code, such as stack space allocated within the asm block.
* The compiler cannot assume that the instructions in the asm are the ones that will actually end up executed.
	+ This effectively means that the compiler must treat the `asm!` as a black box and only take the interface specification into account, not the instructions themselves.
	+ Runtime code patching is allowed, via target-specific mechanisms.
* Unless the `nostack` option is set, asm code is allowed to use stack space below the stack pointer.
	+ On entry to the asm block the stack pointer is guaranteed to be suitably aligned (according to the target ABI) for a function call.
	+ You are responsible for making sure you don't overflow the stack (e.g. use stack probing to ensure you hit a guard page).
	+ You should adjust the stack pointer when allocating stack memory as required by the target ABI.
	+ The stack pointer must be restored to its original value before leaving the asm block.
* If the `noreturn` option is set then behavior is undefined if execution falls through to the end of the asm block.
* If the `pure` option is set then behavior is undefined if the `asm!` has side-effects other than its direct outputs. Behavior is also undefined if two executions of the `asm!` code with the same inputs result in different outputs.
	+ When used with the `nomem` option, "inputs" are just the direct inputs of the `asm!`.
	+ When used with the `readonly` option, "inputs" comprise the direct inputs of the `asm!` and any memory that the `asm!` block is allowed to read.
* These flags registers must be restored upon exiting the asm block if the `preserves_flags` option is set:
	+ x86
		- Status flags in `EFLAGS` (CF, PF, AF, ZF, SF, OF).
		- Floating-point status word (all).
		- Floating-point exception flags in `MXCSR` (PE, UE, OE, ZE, DE, IE).
	+ ARM
		- Condition flags in `CPSR` (N, Z, C, V)
		- Saturation flag in `CPSR` (Q)
		- Greater than or equal flags in `CPSR` (GE).
		- Condition flags in `FPSCR` (N, Z, C, V)
		- Saturation flag in `FPSCR` (QC)
		- Floating-point exception flags in `FPSCR` (IDC, IXC, UFC, OFC, DZC, IOC).
	+ AArch64
		- Condition flags (`NZCV` register).
		- Floating-point status (`FPSR` register).
	+ RISC-V
		- Floating-point exception flags in `fcsr` (`fflags`).
		- Vector extension state (`vtype`, `vl`, `vcsr`).
* On x86, the direction flag (DF in `EFLAGS`) is clear on entry to an asm block and must be clear on exit.
	+ Behavior is undefined if the direction flag is set on exiting an asm block.
* On x86, the x87 floating-point register stack must remain unchanged unless all of the `st([0-7])` registers have been marked as clobbered with `out("st(0)") _, out("st(1)") _, ...`.
	+ If all x87 registers are clobbered then the x87 register stack is guaranteed to be empty upon entering an `asm` block. Assembly code must ensure that the x87 register stack is also empty when exiting the asm block.
* The requirement of restoring the stack pointer and non-output registers to their original value only applies when exiting an `asm!` block.
	+ This means that `asm!` blocks that never return (even if not marked `noreturn`) don't need to preserve these registers.
	+ When returning to a different `asm!` block than you entered (e.g. for context switching), these registers must contain the value they had upon entering the `asm!` block that you are *exiting*.
		- You cannot exit an `asm!` block that has not been entered. Neither can you exit an `asm!` block that has already been exited (without first entering it again).
		- You are responsible for switching any target-specific state (e.g. thread-local storage, stack bounds).
		- You cannot jump from an address in one `asm!` block to an address in another, even within the same function or block, without treating their contexts as potentially different and requiring context switching. You cannot assume that any particular value in those contexts (e.g. current stack pointer or temporary values below the stack pointer) will remain unchanged between the two `asm!` blocks.
		- The set of memory locations that you may access is the intersection of those allowed by the `asm!` blocks you entered and exited.
* You cannot assume that two `asm!` blocks adjacent in source code, even without any other code between them, will end up in successive addresses in the binary without any other instructions between them.
* You cannot assume that an `asm!` block will appear exactly once in the output binary. The compiler is allowed to instantiate multiple copies of the `asm!` block, for example when the function containing it is inlined in multiple places.
* On x86, inline assembly must not end with an instruction prefix (such as `LOCK`) that would apply to instructions generated by the compiler.
	+ The compiler is currently unable to detect this due to the way inline assembly is compiled, but may catch and reject this in the future.

 
>  **Note**: As a general rule, the flags covered by `preserves_flags` are those which are *not* preserved when performing a function call.
> 
>  

 ### Correctness and Validity

 In addition to all of the previous rules, the string argument to `asm!` must ultimately become— after all other arguments are evaluated, formatting is performed, and operands are translated— assembly that is both syntactically correct and semantically valid for the target architecture. The formatting rules allow the compiler to generate assembly with correct syntax. Rules concerning operands permit valid translation of Rust operands into and out of `asm!`. Adherence to these rules is necessary, but not sufficient, for the final expanded assembly to be both correct and valid. For instance:

 * arguments may be placed in positions which are syntactically incorrect after formatting
* an instruction may be correctly written, but given architecturally invalid operands
* an architecturally unspecified instruction may be assembled into unspecified code
* a set of instructions, each correct and valid, may cause undefined behavior if placed in immediate succession

 As a result, these rules are *non-exhaustive*. The compiler is not required to check the correctness and validity of the initial string nor the final assembly that is generated. The assembler may check for correctness and validity but is not required to do so. When using `asm!`, a typographical error may be sufficient to make a program unsound, and the rules for assembly may include thousands of pages of architectural reference manuals. Programmers should exercise appropriate care, as invoking this `unsafe` capability comes with assuming the responsibility of not violating rules of both the compiler or the architecture.

 ### Directives Support

 Inline assembly supports a subset of the directives supported by both GNU AS and LLVM's internal assembler, given as follows. The result of using other directives is assembler-specific (and may cause an error, or may be accepted as-is).

 If inline assembly includes any "stateful" directive that modifies how subsequent assembly is processed, the block must undo the effects of any such directives before the inline assembly ends.

 The following directives are guaranteed to be supported by the assembler:

 * `.2byte`
* `.4byte`
* `.8byte`
* `.align`
* `.alt_entry`
* `.ascii`
* `.asciz`
* `.balign`
* `.balignl`
* `.balignw`
* `.bss`
* `.byte`
* `.comm`
* `.data`
* `.def`
* `.double`
* `.endef`
* `.equ`
* `.equiv`
* `.eqv`
* `.fill`
* `.float`
* `.global`
* `.globl`
* `.inst`
* `.lcomm`
* `.long`
* `.octa`
* `.option`
* `.p2align`
* `.popsection`
* `.private_extern`
* `.pushsection`
* `.quad`
* `.scl`
* `.section`
* `.set`
* `.short`
* `.size`
* `.skip`
* `.sleb128`
* `.space`
* `.string`
* `.text`
* `.type`
* `.uleb128`
* `.word`

 #### Target Specific Directive Support

 ##### Dwarf Unwinding

 The following directives are supported on ELF targets that support DWARF unwind info:

 * `.cfi_adjust_cfa_offset`
* `.cfi_def_cfa`
* `.cfi_def_cfa_offset`
* `.cfi_def_cfa_register`
* `.cfi_endproc`
* `.cfi_escape`
* `.cfi_lsda`
* `.cfi_offset`
* `.cfi_personality`
* `.cfi_register`
* `.cfi_rel_offset`
* `.cfi_remember_state`
* `.cfi_restore`
* `.cfi_restore_state`
* `.cfi_return_column`
* `.cfi_same_value`
* `.cfi_sections`
* `.cfi_signal_frame`
* `.cfi_startproc`
* `.cfi_undefined`
* `.cfi_window_save`

 ##### Structured Exception Handling

 On targets with structured exception Handling, the following additional directives are guaranteed to be supported:

 * `.seh_endproc`
* `.seh_endprologue`
* `.seh_proc`
* `.seh_pushreg`
* `.seh_savereg`
* `.seh_setframe`
* `.seh_stackalloc`

 ##### x86 (32-bit and 64-bit)

 On x86 targets, both 32-bit and 64-bit, the following additional directives are guaranteed to be supported:

 * `.nops`
* `.code16`
* `.code32`
* `.code64`

 Use of `.code16`, `.code32`, and `.code64` directives are only supported if the state is reset to the default before exiting the assembly block. 32-bit x86 uses `.code32` by default, and x86\_64 uses `.code64` by default.

 ##### ARM (32-bit)

 On ARM, the following additional directives are guaranteed to be supported:

 * `.even`
* `.fnstart`
* `.fnend`
* `.save`
* `.movsp`
* `.code`
* `.thumb`
* `.thumb_func`



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/inline-assembly.html>

Unsafety
========

 Unsafe operations are those that can potentially violate the memory-safety guarantees of Rust's static semantics.

 The following language level features cannot be used in the safe subset of Rust:

 * Dereferencing a [raw pointer](types/pointer).
* Reading or writing a [mutable](items/static-items#mutable-statics) or [external](items/external-blocks) static variable.
* Accessing a field of a [`union`](items/unions), other than to assign to it.
* Calling an unsafe function (including an intrinsic or foreign function).
* Implementing an [unsafe trait](items/traits#unsafe-traits).



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/unsafety.html>

The `unsafe` keyword
====================

 The `unsafe` keyword can occur in several different contexts: unsafe functions (`unsafe fn`), unsafe blocks (`unsafe {}`), unsafe traits (`unsafe trait`), and unsafe trait implementations (`unsafe impl`). It plays several different roles, depending on where it is used and whether the `unsafe_op_in_unsafe_fn` lint is enabled:

 * it is used to mark code that *defines* extra safety conditions (`unsafe fn`, `unsafe trait`)
* it is used to mark code that needs to *satisfy* extra safety conditions (`unsafe {}`, `unsafe impl`, `unsafe fn` without [`unsafe_op_in_unsafe_fn`](https://doc.rust-lang.org/rustc/lints/listing/allowed-by-default.html#unsafe-op-in-unsafe-fn))

 The following discusses each of these cases. See the [keyword documentation](../std/keyword.unsafe) for some illustrative examples.

 Unsafe functions (`unsafe fn`)
------------------------------

 Unsafe functions are functions that are not safe in all contexts and/or for all possible inputs. We say they have *extra safety conditions*, which are requirements that must be upheld by all callers and that the compiler does not check. For example, [`get_unchecked`](../std/primitive.slice#method.get_unchecked) has the extra safety condition that the index must be in-bounds. The unsafe function should come with documentation explaining what those extra safety conditions are.

 Such a function must be prefixed with the keyword `unsafe` and can only be called from inside an `unsafe` block, or inside `unsafe fn` without the [`unsafe_op_in_unsafe_fn`](https://doc.rust-lang.org/rustc/lints/listing/allowed-by-default.html#unsafe-op-in-unsafe-fn) lint.

 Unsafe blocks (`unsafe {}`)
---------------------------

 A block of code can be prefixed with the `unsafe` keyword, to permit calling `unsafe` functions or dereferencing raw pointers. By default, the body of an unsafe function is also considered to be an unsafe block; this can be changed by enabling the [`unsafe_op_in_unsafe_fn`](https://doc.rust-lang.org/rustc/lints/listing/allowed-by-default.html#unsafe-op-in-unsafe-fn) lint.

 By putting operations into an unsafe block, the programmer states that they have taken care of satisfying the extra safety conditions of all operations inside that block.

 Unsafe blocks are the logical dual to unsafe functions: where unsafe functions define a proof obligation that callers must uphold, unsafe blocks state that all relevant proof obligations have been discharged. There are many ways to discharge proof obligations; for example, there could be run-time checks or data structure invariants that guarantee that certain properties are definitely true, or the unsafe block could be inside an `unsafe fn` and use its own proof obligations to discharge the proof obligations of its callees.

 Unsafe blocks are used to wrap foreign libraries, make direct use of hardware or implement features not directly present in the language. For example, Rust provides the language features necessary to implement memory-safe concurrency in the language but the implementation of threads and message passing in the standard library uses unsafe blocks.

 Rust's type system is a conservative approximation of the dynamic safety requirements, so in some cases there is a performance cost to using safe code. For example, a doubly-linked list is not a tree structure and can only be represented with reference-counted pointers in safe code. By using `unsafe` blocks to represent the reverse links as raw pointers, it can be implemented without reference counting. (See ["Learn Rust With Entirely Too Many Linked Lists"](https://rust-unofficial.github.io/too-many-lists/) for a more in-depth exploration of this particular example.)

 Unsafe traits (`unsafe trait`)
------------------------------

 An unsafe trait is a trait that comes with extra safety conditions that must be upheld by *implementations* of the trait. The unsafe trait should come with documentation explaining what those extra safety conditions are.

 Such a trait must be prefixed with the keyword `unsafe` and can only be implemented by `unsafe impl` blocks.

 Unsafe trait implementations (`unsafe impl`)
--------------------------------------------

 When implementing an unsafe trait, the implementation needs to be prefixed with the `unsafe` keyword. By writing `unsafe impl`, the programmer states that they have taken care of satisfying the extra safety conditions required by the trait.

 Unsafe trait implementations are the logical dual to unsafe traits: where unsafe traits define a proof obligation that implementations must uphold, unsafe implementations state that all relevant proof obligations have been discharged.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/unsafe-keyword.html>

Behavior considered undefined
=============================

 Rust code is incorrect if it exhibits any of the behaviors in the following list. This includes code within `unsafe` blocks and `unsafe` functions. `unsafe` only means that avoiding undefined behavior is on the programmer; it does not change anything about the fact that Rust programs must never cause undefined behavior.

 It is the programmer's responsibility when writing `unsafe` code to ensure that any safe code interacting with the `unsafe` code cannot trigger these behaviors. `unsafe` code that satisfies this property for any safe client is called *sound*; if `unsafe` code can be misused by safe code to exhibit undefined behavior, it is *unsound*.

  ***Warning:*** The following list is not exhaustive. There is no formal model of Rust's semantics for what is and is not allowed in unsafe code, so there may be more behavior considered unsafe. The following list is just what we know for sure is undefined behavior. Please read the [Rustonomicon](https://doc.rust-lang.org/nomicon/index.html) before writing unsafe code.

  * Data races.
* Evaluating a [dereference expression](expressions/operator-expr#the-dereference-operator) (`*expr`) on a raw pointer that is [dangling](#dangling-pointers) or unaligned, even in [place expression context](expressions#place-expressions-and-value-expressions) (e.g. `addr_of!(*expr)`).
* Breaking the [pointer aliasing rules](http://llvm.org/docs/LangRef.html#pointer-aliasing-rules). `Box<T>`, `&mut T` and `&T` follow LLVM’s scoped [noalias](http://llvm.org/docs/LangRef.html#noalias) model, except if the `&T` contains an [`UnsafeCell<U>`](../std/cell/struct.unsafecell). References and boxes must not be [dangling](#dangling-pointers) while they are live. The exact liveness duration is not specified, but some bounds exist:


	+ For references, the liveness duration is upper-bounded by the syntactic lifetime assigned by the borrow checker; it cannot be live any *longer* than that lifetime.
	+ Each time a reference or box is passed to or returned from a function, it is considered live.
	+ When a reference (but not a `Box`!) is passed to a function, it is live at least as long as that function call, again except if the `&T` contains an [`UnsafeCell<U>`](../std/cell/struct.unsafecell).All this also applies when values of these types are passed in a (nested) field of a compound type, but not behind pointer indirections.
* Mutating immutable data. All data inside a [`const`](items/constant-items) item is immutable. Moreover, all data reached through a shared reference or data owned by an immutable binding is immutable, unless that data is contained within an [`UnsafeCell<U>`](../std/cell/struct.unsafecell).
* Invoking undefined behavior via compiler intrinsics.
* Executing code compiled with platform features that the current platform does not support (see [`target_feature`](attributes/codegen#the-target_feature-attribute)), *except* if the platform explicitly documents this to be safe.
* Calling a function with the wrong call ABI or unwinding from a function with the wrong unwind ABI.
* Producing an invalid value, even in private fields and locals. "Producing" a value happens any time a value is assigned to or read from a place, passed to a function/primitive operation or returned from a function/primitive operation. The following values are invalid (at their respective type):


	+ A value other than `false` (`0`) or `true` (`1`) in a [`bool`](types/boolean).
	+ A discriminant in an `enum` not included in the type definition.
	+ A null `fn` pointer.
	+ A value in a `char` which is a surrogate or above `char::MAX`.
	+ A `!` (all values are invalid for this type).
	+ An integer (`i*`/`u*`), floating point value (`f*`), or raw pointer obtained from [uninitialized memory](http://llvm.org/docs/LangRef.html#undefined-values), or uninitialized memory in a `str`.
	+ A reference or `Box<T>` that is [dangling](#dangling-pointers), unaligned, or points to an invalid value.
	+ Invalid metadata in a wide reference, `Box<T>`, or raw pointer:
	
	
		- `dyn Trait` metadata is invalid if it is not a pointer to a vtable for `Trait` that matches the actual dynamic trait the pointer or reference points to.
		- Slice metadata is invalid if the length is not a valid `usize` (i.e., it must not be read from uninitialized memory).
	+ Invalid values for a type with a custom definition of invalid values. In the standard library, this affects [`NonNull<T>`](https://doc.rust-lang.org/core/ptr/struct.NonNull.html) and [`NonZero*`](https://doc.rust-lang.org/core/num/index.html).
	
	 
	>  **Note**: `rustc` achieves this with the unstable `rustc_layout_scalar_valid_range_*` attributes.
	> 
	>
* Incorrect use of inline assembly. For more details, refer to the [rules](inline-assembly#rules-for-inline-assembly) to follow when writing code that uses inline assembly.

 **Note:** Uninitialized memory is also implicitly invalid for any type that has a restricted set of valid values. In other words, the only cases in which reading uninitialized memory is permitted are inside `union`s and in "padding" (the gaps between the fields/elements of a type).

 
>  **Note**: Undefined behavior affects the entire program. For example, calling a function in C that exhibits undefined behavior of C means your entire program contains undefined behaviour that can also affect the Rust code. And vice versa, undefined behavior in Rust can cause adverse affects on code executed by any FFI calls to other languages.
> 
>  

 ### Dangling pointers

 A reference/pointer is "dangling" if it is null or not all of the bytes it points to are part of the same live allocation (so in particular they all have to be part of *some* allocation). The span of bytes it points to is determined by the pointer value and the size of the pointee type (using `size_of_val`).

 If the size is 0, then the pointer must either point inside of a live allocation (including pointing just after the last byte of the allocation), or it must be directly constructed from a non-zero integer literal.

 Note that dynamically sized types (such as slices and strings) point to their entire range, so it is important that the length metadata is never too large. In particular, the dynamic size of a Rust value (as determined by `size_of_val`) must never exceed `isize::MAX`.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/behavior-considered-undefined.html>

Behavior not considered `unsafe`
================================

 The Rust compiler does not consider the following behaviors *unsafe*, though a programmer may (should) find them undesirable, unexpected, or erroneous.

 ##### Deadlocks

 ##### Leaks of memory and other resources

 ##### Exiting without calling destructors

 ##### Exposing randomized base addresses through pointer leaks

 ##### Integer overflow

 If a program contains arithmetic overflow, the programmer has made an error. In the following discussion, we maintain a distinction between arithmetic overflow and wrapping arithmetic. The first is erroneous, while the second is intentional.

 When the programmer has enabled `debug_assert!` assertions (for example, by enabling a non-optimized build), implementations must insert dynamic checks that `panic` on overflow. Other kinds of builds may result in `panics` or silently wrapped values on overflow, at the implementation's discretion.

 In the case of implicitly-wrapped overflow, implementations must provide well-defined (even if still considered erroneous) results by using two's complement overflow conventions.

 The integral types provide inherent methods to allow programmers explicitly to perform wrapping arithmetic. For example, `i32::wrapping_add` provides two's complement, wrapping addition.

 The standard library also provides a `Wrapping<T>` newtype which ensures all standard arithmetic operations for `T` have wrapping semantics.

 See [RFC 560](https://github.com/rust-lang/rfcs/blob/master/text/0560-integer-overflow.md) for error conditions, rationale, and more details about integer overflow.

 ##### Logic errors

 Safe code may impose extra logical constraints that can be checked at neither compile-time nor runtime. If a program breaks such a constraint, the behavior may be unspecified but will not result in undefined behavior. This could include panics, incorrect results, aborts, and non-termination. The behavior may also differ between runs, builds, or kinds of build.

 For example, implementing both `Hash` and `Eq` requires that values considered equal have equal hashes. Another example are data structures like `BinaryHeap`, `BTreeMap`, `BTreeSet`, `HashMap` and `HashSet` which describe constraints on the modification of their keys while they are in the data structure. Violating such constraints is not considered unsafe, yet the program is considered erroneous and its behavior unpredictable.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/behavior-not-considered-unsafe.html>

Application Binary Interface (ABI)
==================================

 This section documents features that affect the ABI of the compiled output of a crate.

 See *[extern functions](items/functions#extern-function-qualifier)* for information on specifying the ABI for exporting functions. See *[external blocks](items/external-blocks)* for information on specifying the ABI for linking external libraries.

 The `used` attribute
--------------------

 The *`used` attribute* can only be applied to [`static` items](items/static-items). This [attribute](attributes) forces the compiler to keep the variable in the output object file (.o, .rlib, etc. excluding final binaries) even if the variable is not used, or referenced, by any other item in the crate. However, the linker is still free to remove such an item.

 Below is an example that shows under what conditions the compiler keeps a `static` item in the output object file.

 
```
#![allow(unused)]
fn main() {
// foo.rs

// This is kept because of `#[used]`:
#[used]
static FOO: u32 = 0;

// This is removable because it is unused:
#[allow(dead_code)]
static BAR: u32 = 0;

// This is kept because it is publicly reachable:
pub static BAZ: u32 = 0;

// This is kept because it is referenced by a public, reachable function:
static QUUX: u32 = 0;

pub fn quux() -> &'static u32 {
    &QUUX
}

// This is removable because it is referenced by a private, unused (dead) function:
static CORGE: u32 = 0;

#[allow(dead_code)]
fn corge() -> &'static u32 {
    &CORGE
}
}
```
 
```
$ rustc -O --emit=obj --crate-type=rlib foo.rs

$ nm -C foo.o
0000000000000000 R foo::BAZ
0000000000000000 r foo::FOO
0000000000000000 R foo::QUUX
0000000000000000 T foo::quux

```
 The `no_mangle` attribute
-------------------------

 The *`no_mangle` attribute* may be used on any [item](items) to disable standard symbol name mangling. The symbol for the item will be the identifier of the item's name.

 Additionally, the item will be publicly exported from the produced library or object file, similar to the [`used` attribute](#the-used-attribute).

 The `link_section` attribute
----------------------------

 The *`link_section` attribute* specifies the section of the object file that a [function](items/functions) or [static](items/static-items)'s content will be placed into. It uses the [*MetaNameValueStr*](attributes#meta-item-attribute-syntax) syntax to specify the section name.

 
```
#![allow(unused)]
fn main() {
#[no_mangle]
#[link_section = ".example_section"]
pub static VAR1: u32 = 1;
}
```
 The `export_name` attribute
---------------------------

 The *`export_name` attribute* specifies the name of the symbol that will be exported on a [function](items/functions) or [static](items/static-items). It uses the [*MetaNameValueStr*](attributes#meta-item-attribute-syntax) syntax to specify the symbol name.

 
```
#![allow(unused)]
fn main() {
#[export_name = "exported_symbol_name"]
pub fn name_in_rust() { }
}
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/abi.html>

The Rust runtime
================

 This section documents features that define some aspects of the Rust runtime.

 The `panic_handler` attribute
-----------------------------

 The *`panic_handler` attribute* can only be applied to a function with signature `fn(&PanicInfo) -> !`. The function marked with this [attribute](attributes) defines the behavior of panics. The [`PanicInfo`](https://doc.rust-lang.org/core/panic/struct.PanicInfo.html) struct contains information about the location of the panic. There must be a single `panic_handler` function in the dependency graph of a binary, dylib or cdylib crate.

 Below is shown a `panic_handler` function that logs the panic message and then halts the thread.

 
```
#![no_std]

use core::fmt::{self, Write};
use core::panic::PanicInfo;

struct Sink {
    // ..
   _0: (),
}

impl Sink {
    fn new() -> Sink { Sink { _0: () }}
}

impl fmt::Write for Sink {
    fn write_str(&mut self, _: &str) -> fmt::Result { Ok(()) }
}

#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
    let mut sink = Sink::new();

    // logs "panicked at '$reason', src/main.rs:27:4" to some `sink`
    let _ = writeln!(sink, "{}", info);

    loop {}
}
```
 ### Standard behavior

 The standard library provides an implementation of `panic_handler` that defaults to unwinding the stack but that can be [changed to abort the process](../book/ch09-01-unrecoverable-errors-with-panic). The standard library's panic behavior can be modified at runtime with the [set\_hook](../std/panic/fn.set_hook) function.

 The `global_allocator` attribute
--------------------------------

 The *`global_allocator` attribute* is used on a [static item](items/static-items) implementing the [`GlobalAlloc`](https://doc.rust-lang.org/alloc/alloc/trait.GlobalAlloc.html) trait to set the global allocator.

 The `windows_subsystem` attribute
---------------------------------

 The *`windows_subsystem` attribute* may be applied at the crate level to set the [subsystem](https://msdn.microsoft.com/en-us/library/fcc1zstk.aspx) when linking on a Windows target. It uses the [*MetaNameValueStr*](attributes#meta-item-attribute-syntax) syntax to specify the subsystem with a value of either `console` or `windows`. This attribute is ignored on non-Windows targets, and for non-`bin` [crate types](linkage).

 The "console" subsystem is the default. If a console process is run from an existing console then it will be attached to that console, otherwise a new console window will be created.

 The "windows" subsystem is commonly used by GUI applications that do not want to display a console window on startup. It will run detached from any existing console.

 
```
#![allow(unused)]
#![windows_subsystem = "windows"]
fn main() {
}
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/runtime.html>

Appendices
==========



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/appendices.html>

Appendix: Macro Follow-Set Ambiguity Formal Specification
=========================================================

 This page documents the formal specification of the follow rules for [Macros By Example](macros-by-example). They were originally specified in [RFC 550](https://github.com/rust-lang/rfcs/blob/master/text/0550-macro-future-proofing.md), from which the bulk of this text is copied, and expanded upon in subsequent RFCs.

 Definitions & Conventions
-------------------------

 * `macro`: anything invokable as `foo!(...)` in source code.
* `MBE`: macro-by-example, a macro defined by `macro_rules`.
* `matcher`: the left-hand-side of a rule in a `macro_rules` invocation, or a subportion thereof.
* `macro parser`: the bit of code in the Rust parser that will parse the input using a grammar derived from all of the matchers.
* `fragment`: The class of Rust syntax that a given matcher will accept (or "match").
* `repetition` : a fragment that follows a regular repeating pattern
* `NT`: non-terminal, the various "meta-variables" or repetition matchers that can appear in a matcher, specified in MBE syntax with a leading `$` character.
* `simple NT`: a "meta-variable" non-terminal (further discussion below).
* `complex NT`: a repetition matching non-terminal, specified via repetition operators (`*`, `+`, `?`).
* `token`: an atomic element of a matcher; i.e. identifiers, operators, open/close delimiters, *and* simple NT's.
* `token tree`: a tree structure formed from tokens (the leaves), complex NT's, and finite sequences of token trees.
* `delimiter token`: a token that is meant to divide the end of one fragment and the start of the next fragment.
* `separator token`: an optional delimiter token in an complex NT that separates each pair of elements in the matched repetition.
* `separated complex NT`: a complex NT that has its own separator token.
* `delimited sequence`: a sequence of token trees with appropriate open- and close-delimiters at the start and end of the sequence.
* `empty fragment`: The class of invisible Rust syntax that separates tokens, i.e. whitespace, or (in some lexical contexts), the empty token sequence.
* `fragment specifier`: The identifier in a simple NT that specifies which fragment the NT accepts.
* `language`: a context-free language.

 Example:

 
```
#![allow(unused)]
fn main() {
macro_rules! i_am_an_mbe {
    (start $foo:expr $($i:ident),* end) => ($foo)
}
}
```
 `(start $foo:expr $($i:ident),* end)` is a matcher. The whole matcher is a delimited sequence (with open- and close-delimiters `(` and `)`), and `$foo` and `$i` are simple NT's with `expr` and `ident` as their respective fragment specifiers.

 `$(i:ident),*` is *also* an NT; it is a complex NT that matches a comma-separated repetition of identifiers. The `,` is the separator token for the complex NT; it occurs in between each pair of elements (if any) of the matched fragment.

 Another example of a complex NT is `$(hi $e:expr ;)+`, which matches any fragment of the form `hi <expr>; hi <expr>; ...` where `hi <expr>;` occurs at least once. Note that this complex NT does not have a dedicated separator token.

 (Note that Rust's parser ensures that delimited sequences always occur with proper nesting of token tree structure and correct matching of open- and close-delimiters.)

 We will tend to use the variable "M" to stand for a matcher, variables "t" and "u" for arbitrary individual tokens, and the variables "tt" and "uu" for arbitrary token trees. (The use of "tt" does present potential ambiguity with its additional role as a fragment specifier; but it will be clear from context which interpretation is meant.)

 "SEP" will range over separator tokens, "OP" over the repetition operators `*`, `+`, and `?`, "OPEN"/"CLOSE" over matching token pairs surrounding a delimited sequence (e.g. `[` and `]`).

 Greek letters "α" "β" "γ" "δ" stand for potentially empty token-tree sequences. (However, the Greek letter "ε" (epsilon) has a special role in the presentation and does not stand for a token-tree sequence.)

 * This Greek letter convention is usually just employed when the presence of a sequence is a technical detail; in particular, when we wish to *emphasize* that we are operating on a sequence of token-trees, we will use the notation "tt ..." for the sequence, not a Greek letter.

 Note that a matcher is merely a token tree. A "simple NT", as mentioned above, is an meta-variable NT; thus it is a non-repetition. For example, `$foo:ty` is a simple NT but `$($foo:ty)+` is a complex NT.

 Note also that in the context of this formalism, the term "token" generally *includes* simple NTs.

 Finally, it is useful for the reader to keep in mind that according to the definitions of this formalism, no simple NT matches the empty fragment, and likewise no token matches the empty fragment of Rust syntax. (Thus, the *only* NT that can match the empty fragment is a complex NT.) This is not actually true, because the `vis` matcher can match an empty fragment. Thus, for the purposes of the formalism, we will treat `$v:vis` as actually being `$($v:vis)?`, with a requirement that the matcher match an empty fragment.

 ### The Matcher Invariants

 To be valid, a matcher must meet the following three invariants. The definitions of FIRST and FOLLOW are described later.

 1. For any two successive token tree sequences in a matcher `M` (i.e. `M = ... tt uu ...`) with `uu ...` nonempty, we must have FOLLOW(`... tt`) ∪ {ε} ⊇ FIRST(`uu ...`).
2. For any separated complex NT in a matcher, `M = ... $(tt ...) SEP OP ...`, we must have `SEP` ∈ FOLLOW(`tt ...`).
3. For an unseparated complex NT in a matcher, `M = ... $(tt ...) OP ...`, if OP = `*` or `+`, we must have FOLLOW(`tt ...`) ⊇ FIRST(`tt ...`).

 The first invariant says that whatever actual token that comes after a matcher, if any, must be somewhere in the predetermined follow set. This ensures that a legal macro definition will continue to assign the same determination as to where `... tt` ends and `uu ...` begins, even as new syntactic forms are added to the language.

 The second invariant says that a separated complex NT must use a separator token that is part of the predetermined follow set for the internal contents of the NT. This ensures that a legal macro definition will continue to parse an input fragment into the same delimited sequence of `tt ...`'s, even as new syntactic forms are added to the language.

 The third invariant says that when we have a complex NT that can match two or more copies of the same thing with no separation in between, it must be permissible for them to be placed next to each other as per the first invariant. This invariant also requires they be nonempty, which eliminates a possible ambiguity.

 **NOTE: The third invariant is currently unenforced due to historical oversight and significant reliance on the behaviour. It is currently undecided what to do about this going forward. Macros that do not respect the behaviour may become invalid in a future edition of Rust. See the [tracking issue](https://github.com/rust-lang/rust/issues/56575).**

 ### FIRST and FOLLOW, informally

 A given matcher M maps to three sets: FIRST(M), LAST(M) and FOLLOW(M).

 Each of the three sets is made up of tokens. FIRST(M) and LAST(M) may also contain a distinguished non-token element ε ("epsilon"), which indicates that M can match the empty fragment. (But FOLLOW(M) is always just a set of tokens.)

 Informally:

 * FIRST(M): collects the tokens potentially used first when matching a fragment to M.
* LAST(M): collects the tokens potentially used last when matching a fragment to M.
* FOLLOW(M): the set of tokens allowed to follow immediately after some fragment matched by M.

 In other words: t ∈ FOLLOW(M) if and only if there exists (potentially empty) token sequences α, β, γ, δ where:


	+ M matches β,
	+ t matches γ, and
	+ The concatenation α β γ δ is a parseable Rust program.

 We use the shorthand ANYTOKEN to denote the set of all tokens (including simple NTs). For example, if any token is legal after a matcher M, then FOLLOW(M) = ANYTOKEN.

 (To review one's understanding of the above informal descriptions, the reader at this point may want to jump ahead to the [examples of FIRST/LAST](#examples-of-first-and-last) before reading their formal definitions.)

 ### FIRST, LAST

 Below are formal inductive definitions for FIRST and LAST.

 "A ∪ B" denotes set union, "A ∩ B" denotes set intersection, and "A \ B" denotes set difference (i.e. all elements of A that are not present in B).

 #### FIRST

 FIRST(M) is defined by case analysis on the sequence M and the structure of its first token-tree (if any):

 * if M is the empty sequence, then FIRST(M) = { ε },
* if M starts with a token t, then FIRST(M) = { t },

 (Note: this covers the case where M starts with a delimited token-tree sequence, `M = OPEN tt ... CLOSE ...`, in which case `t = OPEN` and thus FIRST(M) = { `OPEN` }.)

 (Note: this critically relies on the property that no simple NT matches the empty fragment.)
* Otherwise, M is a token-tree sequence starting with a complex NT: `M = $( tt ... ) OP α`, or `M = $( tt ... ) SEP OP α`, (where `α` is the (potentially empty) sequence of token trees for the rest of the matcher).


	+ Let SEP\_SET(M) = { SEP } if SEP is present and ε ∈ FIRST(`tt ...`); otherwise SEP\_SET(M) = {}.
* Let ALPHA\_SET(M) = FIRST(`α`) if OP = `*` or `?` and ALPHA\_SET(M) = {} if OP = `+`.
* FIRST(M) = (FIRST(`tt ...`) \ {ε}) ∪ SEP\_SET(M) ∪ ALPHA\_SET(M).

 The definition for complex NTs deserves some justification. SEP\_SET(M) defines the possibility that the separator could be a valid first token for M, which happens when there is a separator defined and the repeated fragment could be empty. ALPHA\_SET(M) defines the possibility that the complex NT could be empty, meaning that M's valid first tokens are those of the following token-tree sequences `α`. This occurs when either `*` or `?` is used, in which case there could be zero repetitions. In theory, this could also occur if `+` was used with a potentially-empty repeating fragment, but this is forbidden by the third invariant.

 From there, clearly FIRST(M) can include any token from SEP\_SET(M) or ALPHA\_SET(M), and if the complex NT match is nonempty, then any token starting FIRST(`tt ...`) could work too. The last piece to consider is ε. SEP\_SET(M) and FIRST(`tt ...`) \ {ε} cannot contain ε, but ALPHA\_SET(M) could. Hence, this definition allows M to accept ε if and only if ε ∈ ALPHA\_SET(M) does. This is correct because for M to accept ε in the complex NT case, both the complex NT and α must accept it. If OP = `+`, meaning that the complex NT cannot be empty, then by definition ε ∉ ALPHA\_SET(M). Otherwise, the complex NT can accept zero repetitions, and then ALPHA\_SET(M) = FOLLOW(`α`). So this definition is correct with respect to \varepsilon as well.

 #### LAST

 LAST(M), defined by case analysis on M itself (a sequence of token-trees):

 * if M is the empty sequence, then LAST(M) = { ε }
* if M is a singleton token t, then LAST(M) = { t }
* if M is the singleton complex NT repeating zero or more times, `M = $( tt ... ) *`, or `M = $( tt ... ) SEP *`


	+ Let sep\_set = { SEP } if SEP present; otherwise sep\_set = {}.
	+ if ε ∈ LAST(`tt ...`) then LAST(M) = LAST(`tt ...`) ∪ sep\_set
	+ otherwise, the sequence `tt ...` must be non-empty; LAST(M) = LAST(`tt ...`) ∪ {ε}.
* if M is the singleton complex NT repeating one or more times, `M = $( tt ... ) +`, or `M = $( tt ... ) SEP +`


	+ Let sep\_set = { SEP } if SEP present; otherwise sep\_set = {}.
	+ if ε ∈ LAST(`tt ...`) then LAST(M) = LAST(`tt ...`) ∪ sep\_set
	+ otherwise, the sequence `tt ...` must be non-empty; LAST(M) = LAST(`tt ...`)
* if M is the singleton complex NT repeating zero or one time, `M = $( tt ...) ?`, then LAST(M) = LAST(`tt ...`) ∪ {ε}.
* if M is a delimited token-tree sequence `OPEN tt ... CLOSE`, then LAST(M) = { `CLOSE` }.
* if M is a non-empty sequence of token-trees `tt uu ...`,


	+ If ε ∈ LAST(`uu ...`), then LAST(M) = LAST(`tt`) ∪ (LAST(`uu ...`) \ { ε }).
	+ Otherwise, the sequence `uu ...` must be non-empty; then LAST(M) = LAST(`uu ...`).

 ### Examples of FIRST and LAST

 Below are some examples of FIRST and LAST. (Note in particular how the special ε element is introduced and eliminated based on the interaction between the pieces of the input.)

 Our first example is presented in a tree structure to elaborate on how the analysis of the matcher composes. (Some of the simpler subtrees have been elided.)

 
```
INPUT:  $(  $d:ident   $e:expr   );*    $( $( h )* );*    $( f ; )+   g
            ~~~~~~~~   ~~~~~~~                ~
                |         |                   |
FIRST:   { $d:ident }  { $e:expr }          { h }


INPUT:  $(  $d:ident   $e:expr   );*    $( $( h )* );*    $( f ; )+
            ~~~~~~~~~~~~~~~~~~             ~~~~~~~           ~~~
                        |                      |               |
FIRST:          { $d:ident }               { h, ε }         { f }

INPUT:  $(  $d:ident   $e:expr   );*    $( $( h )* );*    $( f ; )+   g
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~    ~~~~~~~~~~~~~~    ~~~~~~~~~   ~
                        |                       |              |       |
FIRST:        { $d:ident, ε }            {  h, ε, ;  }      { f }   { g }


INPUT:  $(  $d:ident   $e:expr   );*    $( $( h )* );*    $( f ; )+   g
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                                        |
FIRST:                       { $d:ident, h, ;,  f }

```
 Thus:

 * FIRST(`$($d:ident $e:expr );* $( $(h)* );* $( f ;)+ g`) = { `$d:ident`, `h`, `;`, `f` }

 Note however that:

 * FIRST(`$($d:ident $e:expr );* $( $(h)* );* $($( f ;)+ g)*`) = { `$d:ident`, `h`, `;`, `f`, ε }

 Here are similar examples but now for LAST.

 * LAST(`$d:ident $e:expr`) = { `$e:expr` }
* LAST(`$( $d:ident $e:expr );*`) = { `$e:expr`, ε }
* LAST(`$( $d:ident $e:expr );* $(h)*`) = { `$e:expr`, ε, `h` }
* LAST(`$( $d:ident $e:expr );* $(h)* $( f ;)+`) = { `;` }
* LAST(`$( $d:ident $e:expr );* $(h)* $( f ;)+ g`) = { `g` }

 ### FOLLOW(M)

 Finally, the definition for FOLLOW(M) is built up as follows. pat, expr, etc. represent simple nonterminals with the given fragment specifier.

 * FOLLOW(pat) = {`=>`, `,`, `=`, `|`, `if`, `in`}`.
* FOLLOW(expr) = FOLLOW(stmt) = {`=>`, `,`, `;`}`.
* FOLLOW(ty) = FOLLOW(path) = {`{`, `[`, `,`, `=>`, `:`, `=`, `>`, `>>`, `;`, `|`, `as`, `where`, block nonterminals}.
* FOLLOW(vis) = {`,`l any keyword or identifier except a non-raw `priv`; any token that can begin a type; ident, ty, and path nonterminals}.
* FOLLOW(t) = ANYTOKEN for any other simple token, including block, ident, tt, item, lifetime, literal and meta simple nonterminals, and all terminals.
* FOLLOW(M), for any other M, is defined as the intersection, as t ranges over (LAST(M) \ {ε}), of FOLLOW(t).

 The tokens that can begin a type are, as of this writing, {`(`, `[`, `!`, `*`, `&`, `&&`, `?`, lifetimes, `>`, `>>`, `::`, any non-keyword identifier, `super`, `self`, `Self`, `extern`, `crate`, `$crate`, `_`, `for`, `impl`, `fn`, `unsafe`, `typeof`, `dyn`}, although this list may not be complete because people won't always remember to update the appendix when new ones are added.

 Examples of FOLLOW for complex M:

 * FOLLOW(`$( $d:ident $e:expr )*`) = FOLLOW(`$e:expr`)
* FOLLOW(`$( $d:ident $e:expr )* $(;)*`) = FOLLOW(`$e:expr`) ∩ ANYTOKEN = FOLLOW(`$e:expr`)
* FOLLOW(`$( $d:ident $e:expr )* $(;)* $( f |)+`) = ANYTOKEN

 ### Examples of valid and invalid matchers

 With the above specification in hand, we can present arguments for why particular matchers are legal and others are not.

 * `($ty:ty < foo ,)` : illegal, because FIRST(`< foo ,`) = { `<` } ⊈ FOLLOW(`ty`)
* `($ty:ty , foo <)` : legal, because FIRST(`, foo <`) = { `,` } is ⊆ FOLLOW(`ty`).
* `($pa:pat $pb:pat $ty:ty ,)` : illegal, because FIRST(`$pb:pat $ty:ty ,`) = { `$pb:pat` } ⊈ FOLLOW(`pat`), and also FIRST(`$ty:ty ,`) = { `$ty:ty` } ⊈ FOLLOW(`pat`).
* `( $($a:tt $b:tt)* ; )` : legal, because FIRST(`$b:tt`) = { `$b:tt` } is ⊆ FOLLOW(`tt`) = ANYTOKEN, as is FIRST(`;`) = { `;` }.
* `( $($t:tt),* , $(t:tt),* )` : legal, (though any attempt to actually use this macro will signal a local ambiguity error during expansion).
* `($ty:ty $(; not sep)* -)` : illegal, because FIRST(`$(; not sep)* -`) = { `;`, `-` } is not in FOLLOW(`ty`).
* `($($ty:ty)-+)` : illegal, because separator `-` is not in FOLLOW(`ty`).
* `($($e:expr)*)` : illegal, because expr NTs are not in FOLLOW(expr NT).



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/macro-ambiguity.html>

Influences
==========

 Rust is not a particularly original language, with design elements coming from a wide range of sources. Some of these are listed below (including elements that have since been removed):

 * SML, OCaml: algebraic data types, pattern matching, type inference, semicolon statement separation
* C++: references, RAII, smart pointers, move semantics, monomorphization, memory model
* ML Kit, Cyclone: region based memory management
* Haskell (GHC): typeclasses, type families
* Newsqueak, Alef, Limbo: channels, concurrency
* Erlang: message passing, thread failure, linked thread failure, lightweight concurrency
* Swift: optional bindings
* Scheme: hygienic macros
* C#: attributes
* Ruby: closure syntax, block syntax
* NIL, Hermes: typestate
* [Unicode Annex #31](http://www.unicode.org/reports/tr31/): identifier and pattern syntax



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/influences.html>

Glossary
========

 ### Abstract syntax tree

 An ‘abstract syntax tree’, or ‘AST’, is an intermediate representation of the structure of the program when the compiler is compiling it.

 ### Alignment

 The alignment of a value specifies what addresses values are preferred to start at. Always a power of two. References to a value must be aligned. [More](type-layout#size-and-alignment).

 ### Arity

 Arity refers to the number of arguments a function or operator takes. For some examples, `f(2, 3)` and `g(4, 6)` have arity 2, while `h(8, 2, 6)` has arity 3. The `!` operator has arity 1.

 ### Array

 An array, sometimes also called a fixed-size array or an inline array, is a value describing a collection of elements, each selected by an index that can be computed at run time by the program. It occupies a contiguous region of memory.

 ### Associated item

 An associated item is an item that is associated with another item. Associated items are defined in [implementations](items/implementations) and declared in [traits](items/traits). Only functions, constants, and type aliases can be associated. Contrast to a [free item](#free-item).

 ### Blanket implementation

 Any implementation where a type appears [uncovered](#uncovered-type). `impl<T> Foo for T`, `impl<T> Bar<T> for T`, `impl<T> Bar<Vec<T>> for T`, and `impl<T> Bar<T> for Vec<T>` are considered blanket impls. However, `impl<T> Bar<Vec<T>> for Vec<T>` is not a blanket impl, as all instances of `T` which appear in this `impl` are covered by `Vec`.

 ### Bound

 Bounds are constraints on a type or trait. For example, if a bound is placed on the argument a function takes, types passed to that function must abide by that constraint.

 ### Combinator

 Combinators are higher-order functions that apply only functions and earlier defined combinators to provide a result from its arguments. They can be used to manage control flow in a modular fashion.

 ### Crate

 A crate is the unit of compilation and linking. There are different [types of crates](linkage), such as libraries or executables. Crates may link and refer to other library crates, called external crates. A crate has a self-contained tree of [modules](items/modules), starting from an unnamed root module called the crate root. [Items](items) may be made visible to other crates by marking them as public in the crate root, including through <paths> of public modules. [More](crates-and-source-files).

 ### Dispatch

 Dispatch is the mechanism to determine which specific version of code is actually run when it involves polymorphism. Two major forms of dispatch are static dispatch and dynamic dispatch. While Rust favors static dispatch, it also supports dynamic dispatch through a mechanism called ‘trait objects’.

 ### Dynamically sized type

 A dynamically sized type (DST) is a type without a statically known size or alignment.

 ### Entity

 An [*entity*](names) is a language construct that can be referred to in some way within the source program, usually via a [path](paths). Entities include <types>, <items>, [generic parameters](items/generics), [variable bindings](patterns), [loop labels](tokens#lifetimes-and-loop-labels), [lifetimes](tokens#lifetimes-and-loop-labels), [fields](expressions/field-expr), <attributes>, and [lints](attributes/diagnostics#lint-check-attributes).

 ### Expression

 An expression is a combination of values, constants, variables, operators and functions that evaluate to a single value, with or without side-effects.

 For example, `2 + (3 * 4)` is an expression that returns the value 14.

 ### Free item

 An [item](items) that is not a member of an [implementation](items/implementations), such as a *free function* or a *free const*. Contrast to an [associated item](#associated-item).

 ### Fundamental traits

 A fundamental trait is one where adding an impl of it for an existing type is a breaking change. The `Fn` traits and `Sized` are fundamental.

 ### Fundamental type constructors

 A fundamental type constructor is a type where implementing a [blanket implementation](#blanket-implementation) over it is a breaking change. `&`, `&mut`, `Box`, and `Pin` are fundamental.

 Any time a type `T` is considered [local](#local-type), `&T`, `&mut T`, `Box<T>`, and `Pin<T>` are also considered local. Fundamental type constructors cannot [cover](#uncovered-type) other types. Any time the term "covered type" is used, the `T` in `&T`, `&mut T`, `Box<T>`, and `Pin<T>` is not considered covered.

 ### Inhabited

 A type is inhabited if it has constructors and therefore can be instantiated. An inhabited type is not "empty" in the sense that there can be values of the type. Opposite of [Uninhabited](#uninhabited).

 ### Inherent implementation

 An [implementation](items/implementations) that applies to a nominal type, not to a trait-type pair. [More](items/implementations#inherent-implementations).

 ### Inherent method

 A [method](items/associated-items#methods) defined in an [inherent implementation](items/implementations#inherent-implementations), not in a trait implementation.

 ### Initialized

 A variable is initialized if it has been assigned a value and hasn't since been moved from. All other memory locations are assumed to be uninitialized. Only unsafe Rust can create a memory location without initializing it.

 ### Local trait

 A `trait` which was defined in the current crate. A trait definition is local or not independent of applied type arguments. Given `trait Foo<T, U>`, `Foo` is always local, regardless of the types substituted for `T` and `U`.

 ### Local type

 A `struct`, `enum`, or `union` which was defined in the current crate. This is not affected by applied type arguments. `struct Foo` is considered local, but `Vec<Foo>` is not. `LocalType<ForeignType>` is local. Type aliases do not affect locality.

 ### Module

 A module is a container for zero or more <items>. Modules are organized in a tree, starting from an unnamed module at the root called the crate root or the root module. [Paths](paths) may be used to refer to items from other modules, which may be restricted by [visibility rules](visibility-and-privacy). [More](items/modules)

 ### Name

 A [*name*](names) is an [identifier](identifiers) or [lifetime or loop label](tokens#lifetimes-and-loop-labels) that refers to an [entity](#entity). A *name binding* is when an entity declaration introduces an identifier or label associated with that entity. [Paths](paths), identifiers, and labels are used to refer to an entity.

 ### Name resolution

 [*Name resolution*](names/name-resolution) is the compile-time process of tying <paths>, <identifiers>, and [labels](tokens#lifetimes-and-loop-labels) to [entity](#entity) declarations.

 ### Namespace

 A *namespace* is a logical grouping of declared [names](#name) based on the kind of [entity](#entity) the name refers to. Namespaces allow the occurrence of a name in one namespace to not conflict with the same name in another namespace.

 Within a namespace, names are organized in a hierarchy, where each level of the hierarchy has its own collection of named entities.

 ### Nominal types

 Types that can be referred to by a path directly. Specifically [enums](items/enumerations), [structs](items/structs), [unions](items/unions), and [trait objects](types/trait-object).

 ### Object safe traits

 [Traits](items/traits) that can be used as [trait objects](types/trait-object). Only traits that follow specific [rules](items/traits#object-safety) are object safe.

 ### Path

 A [*path*](paths) is a sequence of one or more path segments used to refer to an [entity](#entity) in the current scope or other levels of a [namespace](#namespace) hierarchy.

 ### Prelude

 Prelude, or The Rust Prelude, is a small collection of items - mostly traits - that are imported into every module of every crate. The traits in the prelude are pervasive.

 ### Scope

 A [*scope*](names/scopes) is the region of source text where a named [entity](#entity) may be referenced with that name.

 ### Scrutinee

 A scrutinee is the expression that is matched on in `match` expressions and similar pattern matching constructs. For example, in `match x { A => 1, B => 2 }`, the expression `x` is the scrutinee.

 ### Size

 The size of a value has two definitions.

 The first is that it is how much memory must be allocated to store that value.

 The second is that it is the offset in bytes between successive elements in an array with that item type.

 It is a multiple of the alignment, including zero. The size can change depending on compiler version (as new optimizations are made) and target platform (similar to how `usize` varies per-platform).

 [More](type-layout#size-and-alignment).

 ### Slice

 A slice is dynamically-sized view into a contiguous sequence, written as `[T]`.

 It is often seen in its borrowed forms, either mutable or shared. The shared slice type is `&[T]`, while the mutable slice type is `&mut [T]`, where `T` represents the element type.

 ### Statement

 A statement is the smallest standalone element of a programming language that commands a computer to perform an action.

 ### String literal

 A string literal is a string stored directly in the final binary, and so will be valid for the `'static` duration.

 Its type is `'static` duration borrowed string slice, `&'static str`.

 ### String slice

 A string slice is the most primitive string type in Rust, written as `str`. It is often seen in its borrowed forms, either mutable or shared. The shared string slice type is `&str`, while the mutable string slice type is `&mut str`.

 Strings slices are always valid UTF-8.

 ### Trait

 A trait is a language item that is used for describing the functionalities a type must provide. It allows a type to make certain promises about its behavior.

 Generic functions and generic structs can use traits to constrain, or bound, the types they accept.

 ### Turbofish

 Paths with generic parameters in expressions must prefix the opening brackets with a `::`. Combined with the angular brackets for generics, this looks like a fish `::<>`. As such, this syntax is colloquially referred to as turbofish syntax.

 Examples:

 
```
#![allow(unused)]
fn main() {
let ok_num = Ok::<_, ()>(5);
let vec = [1, 2, 3].iter().map(|n| n * 2).collect::<Vec<_>>();
}
```
 This `::` prefix is required to disambiguate generic paths with multiple comparisons in a comma-separate list. See [the bastion of the turbofish](https://github.com/rust-lang/rust/blob/1.58.0/src/test/ui/parser/bastion-of-the-turbofish.rs) for an example where not having the prefix would be ambiguous.

 ### Uncovered type

 A type which does not appear as an argument to another type. For example, `T` is uncovered, but the `T` in `Vec<T>` is covered. This is only relevant for type arguments.

 ### Undefined behavior

 Compile-time or run-time behavior that is not specified. This may result in, but is not limited to: process termination or corruption; improper, incorrect, or unintended computation; or platform-specific results. [More](behavior-considered-undefined).

 ### Uninhabited

 A type is uninhabited if it has no constructors and therefore can never be instantiated. An uninhabited type is "empty" in the sense that there are no values of the type. The canonical example of an uninhabited type is the [never type](types/never) `!`, or an enum with no variants `enum Never { }`. Opposite of [Inhabited](#inhabited).



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/reference/glossary.html>

List of all items
=================


### Structs


* [alloc::AllocError](alloc/struct.allocerror)
* [alloc::Global](alloc/struct.global)
* [alloc::Layout](alloc/struct.layout)
* [alloc::LayoutError](alloc/struct.layouterror)
* [alloc::System](alloc/struct.system)
* [any::Demand](any/struct.demand)
* [any::TypeId](any/struct.typeid)
* [array::IntoIter](array/struct.intoiter)
* [array::TryFromSliceError](array/struct.tryfromsliceerror)
* [ascii::EscapeDefault](ascii/struct.escapedefault)
* [async\_iter::FromIter](async_iter/struct.fromiter)
* [backtrace::Backtrace](backtrace/struct.backtrace)
* [backtrace::BacktraceFrame](backtrace/struct.backtraceframe)
* [boxed::Box](boxed/struct.box)
* [boxed::ThinBox](boxed/struct.thinbox)
* [cell::BorrowError](cell/struct.borrowerror)
* [cell::BorrowMutError](cell/struct.borrowmuterror)
* [cell::Cell](cell/struct.cell)
* [cell::LazyCell](cell/struct.lazycell)
* [cell::OnceCell](cell/struct.oncecell)
* [cell::Ref](cell/struct.ref)
* [cell::RefCell](cell/struct.refcell)
* [cell::RefMut](cell/struct.refmut)
* [cell::SyncUnsafeCell](cell/struct.syncunsafecell)
* [cell::UnsafeCell](cell/struct.unsafecell)
* [char::CharTryFromError](char/struct.chartryfromerror)
* [char::DecodeUtf16](char/struct.decodeutf16)
* [char::DecodeUtf16Error](char/struct.decodeutf16error)
* [char::EscapeDebug](char/struct.escapedebug)
* [char::EscapeDefault](char/struct.escapedefault)
* [char::EscapeUnicode](char/struct.escapeunicode)
* [char::ParseCharError](char/struct.parsecharerror)
* [char::ToLowercase](char/struct.tolowercase)
* [char::ToUppercase](char/struct.touppercase)
* [char::TryFromCharError](char/struct.tryfromcharerror)
* [cmp::Reverse](cmp/struct.reverse)
* [collections::BTreeMap](collections/struct.btreemap)
* [collections::BTreeSet](collections/struct.btreeset)
* [collections::BinaryHeap](collections/struct.binaryheap)
* [collections::HashMap](collections/struct.hashmap)
* [collections::HashSet](collections/struct.hashset)
* [collections::LinkedList](collections/struct.linkedlist)
* [collections::TryReserveError](collections/struct.tryreserveerror)
* [collections::VecDeque](collections/struct.vecdeque)
* [collections::binary\_heap::BinaryHeap](collections/binary_heap/struct.binaryheap)
* [collections::binary\_heap::Drain](collections/binary_heap/struct.drain)
* [collections::binary\_heap::DrainSorted](collections/binary_heap/struct.drainsorted)
* [collections::binary\_heap::IntoIter](collections/binary_heap/struct.intoiter)
* [collections::binary\_heap::IntoIterSorted](collections/binary_heap/struct.intoitersorted)
* [collections::binary\_heap::Iter](collections/binary_heap/struct.iter)
* [collections::binary\_heap::PeekMut](collections/binary_heap/struct.peekmut)
* [collections::btree\_map::BTreeMap](collections/btree_map/struct.btreemap)
* [collections::btree\_map::Cursor](collections/btree_map/struct.cursor)
* [collections::btree\_map::CursorMut](collections/btree_map/struct.cursormut)
* [collections::btree\_map::DrainFilter](collections/btree_map/struct.drainfilter)
* [collections::btree\_map::IntoIter](collections/btree_map/struct.intoiter)
* [collections::btree\_map::IntoKeys](collections/btree_map/struct.intokeys)
* [collections::btree\_map::IntoValues](collections/btree_map/struct.intovalues)
* [collections::btree\_map::Iter](collections/btree_map/struct.iter)
* [collections::btree\_map::IterMut](collections/btree_map/struct.itermut)
* [collections::btree\_map::Keys](collections/btree_map/struct.keys)
* [collections::btree\_map::OccupiedEntry](collections/btree_map/struct.occupiedentry)
* [collections::btree\_map::OccupiedError](collections/btree_map/struct.occupiederror)
* [collections::btree\_map::Range](collections/btree_map/struct.range)
* [collections::btree\_map::RangeMut](collections/btree_map/struct.rangemut)
* [collections::btree\_map::VacantEntry](collections/btree_map/struct.vacantentry)
* [collections::btree\_map::Values](collections/btree_map/struct.values)
* [collections::btree\_map::ValuesMut](collections/btree_map/struct.valuesmut)
* [collections::btree\_set::BTreeSet](collections/btree_set/struct.btreeset)
* [collections::btree\_set::Difference](collections/btree_set/struct.difference)
* [collections::btree\_set::DrainFilter](collections/btree_set/struct.drainfilter)
* [collections::btree\_set::Intersection](collections/btree_set/struct.intersection)
* [collections::btree\_set::IntoIter](collections/btree_set/struct.intoiter)
* [collections::btree\_set::Iter](collections/btree_set/struct.iter)
* [collections::btree\_set::Range](collections/btree_set/struct.range)
* [collections::btree\_set::SymmetricDifference](collections/btree_set/struct.symmetricdifference)
* [collections::btree\_set::Union](collections/btree_set/struct.union)
* [collections::hash\_map::DefaultHasher](collections/hash_map/struct.defaulthasher)
* [collections::hash\_map::Drain](collections/hash_map/struct.drain)
* [collections::hash\_map::DrainFilter](collections/hash_map/struct.drainfilter)
* [collections::hash\_map::HashMap](collections/hash_map/struct.hashmap)
* [collections::hash\_map::IntoIter](collections/hash_map/struct.intoiter)
* [collections::hash\_map::IntoKeys](collections/hash_map/struct.intokeys)
* [collections::hash\_map::IntoValues](collections/hash_map/struct.intovalues)
* [collections::hash\_map::Iter](collections/hash_map/struct.iter)
* [collections::hash\_map::IterMut](collections/hash_map/struct.itermut)
* [collections::hash\_map::Keys](collections/hash_map/struct.keys)
* [collections::hash\_map::OccupiedEntry](collections/hash_map/struct.occupiedentry)
* [collections::hash\_map::OccupiedError](collections/hash_map/struct.occupiederror)
* [collections::hash\_map::RandomState](collections/hash_map/struct.randomstate)
* [collections::hash\_map::RawEntryBuilder](collections/hash_map/struct.rawentrybuilder)
* [collections::hash\_map::RawEntryBuilderMut](collections/hash_map/struct.rawentrybuildermut)
* [collections::hash\_map::RawOccupiedEntryMut](collections/hash_map/struct.rawoccupiedentrymut)
* [collections::hash\_map::RawVacantEntryMut](collections/hash_map/struct.rawvacantentrymut)
* [collections::hash\_map::VacantEntry](collections/hash_map/struct.vacantentry)
* [collections::hash\_map::Values](collections/hash_map/struct.values)
* [collections::hash\_map::ValuesMut](collections/hash_map/struct.valuesmut)
* [collections::hash\_set::Difference](collections/hash_set/struct.difference)
* [collections::hash\_set::Drain](collections/hash_set/struct.drain)
* [collections::hash\_set::DrainFilter](collections/hash_set/struct.drainfilter)
* [collections::hash\_set::HashSet](collections/hash_set/struct.hashset)
* [collections::hash\_set::Intersection](collections/hash_set/struct.intersection)
* [collections::hash\_set::IntoIter](collections/hash_set/struct.intoiter)
* [collections::hash\_set::Iter](collections/hash_set/struct.iter)
* [collections::hash\_set::SymmetricDifference](collections/hash_set/struct.symmetricdifference)
* [collections::hash\_set::Union](collections/hash_set/struct.union)
* [collections::linked\_list::Cursor](collections/linked_list/struct.cursor)
* [collections::linked\_list::CursorMut](collections/linked_list/struct.cursormut)
* [collections::linked\_list::DrainFilter](collections/linked_list/struct.drainfilter)
* [collections::linked\_list::IntoIter](collections/linked_list/struct.intoiter)
* [collections::linked\_list::Iter](collections/linked_list/struct.iter)
* [collections::linked\_list::IterMut](collections/linked_list/struct.itermut)
* [collections::linked\_list::LinkedList](collections/linked_list/struct.linkedlist)
* [collections::vec\_deque::Drain](collections/vec_deque/struct.drain)
* [collections::vec\_deque::IntoIter](collections/vec_deque/struct.intoiter)
* [collections::vec\_deque::Iter](collections/vec_deque/struct.iter)
* [collections::vec\_deque::IterMut](collections/vec_deque/struct.itermut)
* [collections::vec\_deque::VecDeque](collections/vec_deque/struct.vecdeque)
* [env::Args](env/struct.args)
* [env::ArgsOs](env/struct.argsos)
* [env::JoinPathsError](env/struct.joinpathserror)
* [env::SplitPaths](env/struct.splitpaths)
* [env::Vars](env/struct.vars)
* [env::VarsOs](env/struct.varsos)
* [error::Report](error/struct.report)
* [ffi::CStr](ffi/struct.cstr)
* [ffi::CString](ffi/struct.cstring)
* [ffi::FromBytesWithNulError](ffi/struct.frombyteswithnulerror)
* [ffi::FromVecWithNulError](ffi/struct.fromvecwithnulerror)
* [ffi::IntoStringError](ffi/struct.intostringerror)
* [ffi::NulError](ffi/struct.nulerror)
* [ffi::OsStr](ffi/struct.osstr)
* [ffi::OsString](ffi/struct.osstring)
* [ffi::VaList](ffi/struct.valist)
* [ffi::VaListImpl](ffi/struct.valistimpl)
* [fmt::Arguments](fmt/struct.arguments)
* [fmt::DebugList](fmt/struct.debuglist)
* [fmt::DebugMap](fmt/struct.debugmap)
* [fmt::DebugSet](fmt/struct.debugset)
* [fmt::DebugStruct](fmt/struct.debugstruct)
* [fmt::DebugTuple](fmt/struct.debugtuple)
* [fmt::Error](fmt/struct.error)
* [fmt::Formatter](fmt/struct.formatter)
* [fs::DirBuilder](fs/struct.dirbuilder)
* [fs::DirEntry](fs/struct.direntry)
* [fs::File](fs/struct.file)
* [fs::FileTimes](fs/struct.filetimes)
* [fs::FileType](fs/struct.filetype)
* [fs::Metadata](fs/struct.metadata)
* [fs::OpenOptions](fs/struct.openoptions)
* [fs::Permissions](fs/struct.permissions)
* [fs::ReadDir](fs/struct.readdir)
* [future::Pending](future/struct.pending)
* [future::PollFn](future/struct.pollfn)
* [future::Ready](future/struct.ready)
* [hash::BuildHasherDefault](hash/struct.buildhasherdefault)
* [hash::SipHasher](hash/struct.siphasher)
* [intrinsics::mir::BasicBlock](intrinsics/mir/struct.basicblock)
* [io::BorrowedBuf](io/struct.borrowedbuf)
* [io::BorrowedCursor](io/struct.borrowedcursor)
* [io::BufReader](io/struct.bufreader)
* [io::BufWriter](io/struct.bufwriter)
* [io::Bytes](io/struct.bytes)
* [io::Chain](io/struct.chain)
* [io::Cursor](io/struct.cursor)
* [io::Empty](io/struct.empty)
* [io::Error](io/struct.error)
* [io::IntoInnerError](io/struct.intoinnererror)
* [io::IoSlice](io/struct.ioslice)
* [io::IoSliceMut](io/struct.ioslicemut)
* [io::LineWriter](io/struct.linewriter)
* [io::Lines](io/struct.lines)
* [io::Repeat](io/struct.repeat)
* [io::Sink](io/struct.sink)
* [io::Split](io/struct.split)
* [io::Stderr](io/struct.stderr)
* [io::StderrLock](io/struct.stderrlock)
* [io::Stdin](io/struct.stdin)
* [io::StdinLock](io/struct.stdinlock)
* [io::Stdout](io/struct.stdout)
* [io::StdoutLock](io/struct.stdoutlock)
* [io::Take](io/struct.take)
* [io::WriterPanicked](io/struct.writerpanicked)
* [iter::ArrayChunks](iter/struct.arraychunks)
* [iter::ByRefSized](iter/struct.byrefsized)
* [iter::Chain](iter/struct.chain)
* [iter::Cloned](iter/struct.cloned)
* [iter::Copied](iter/struct.copied)
* [iter::Cycle](iter/struct.cycle)
* [iter::Empty](iter/struct.empty)
* [iter::Enumerate](iter/struct.enumerate)
* [iter::Filter](iter/struct.filter)
* [iter::FilterMap](iter/struct.filtermap)
* [iter::FlatMap](iter/struct.flatmap)
* [iter::Flatten](iter/struct.flatten)
* [iter::FromFn](iter/struct.fromfn)
* [iter::Fuse](iter/struct.fuse)
* [iter::Inspect](iter/struct.inspect)
* [iter::Intersperse](iter/struct.intersperse)
* [iter::IntersperseWith](iter/struct.interspersewith)
* [iter::Map](iter/struct.map)
* [iter::MapWhile](iter/struct.mapwhile)
* [iter::Once](iter/struct.once)
* [iter::OnceWith](iter/struct.oncewith)
* [iter::Peekable](iter/struct.peekable)
* [iter::Repeat](iter/struct.repeat)
* [iter::RepeatWith](iter/struct.repeatwith)
* [iter::Rev](iter/struct.rev)
* [iter::Scan](iter/struct.scan)
* [iter::Skip](iter/struct.skip)
* [iter::SkipWhile](iter/struct.skipwhile)
* [iter::StepBy](iter/struct.stepby)
* [iter::Successors](iter/struct.successors)
* [iter::Take](iter/struct.take)
* [iter::TakeWhile](iter/struct.takewhile)
* [iter::Zip](iter/struct.zip)
* [marker::PhantomData](marker/struct.phantomdata)
* [marker::PhantomPinned](marker/struct.phantompinned)
* [mem::Assume](mem/struct.assume)
* [mem::Discriminant](mem/struct.discriminant)
* [mem::ManuallyDrop](mem/struct.manuallydrop)
* [net::AddrParseError](net/struct.addrparseerror)
* [net::Incoming](net/struct.incoming)
* [net::IntoIncoming](net/struct.intoincoming)
* [net::Ipv4Addr](net/struct.ipv4addr)
* [net::Ipv6Addr](net/struct.ipv6addr)
* [net::SocketAddrV4](net/struct.socketaddrv4)
* [net::SocketAddrV6](net/struct.socketaddrv6)
* [net::TcpListener](net/struct.tcplistener)
* [net::TcpStream](net/struct.tcpstream)
* [net::UdpSocket](net/struct.udpsocket)
* [num::NonZeroI128](num/struct.nonzeroi128)
* [num::NonZeroI16](num/struct.nonzeroi16)
* [num::NonZeroI32](num/struct.nonzeroi32)
* [num::NonZeroI64](num/struct.nonzeroi64)
* [num::NonZeroI8](num/struct.nonzeroi8)
* [num::NonZeroIsize](num/struct.nonzeroisize)
* [num::NonZeroU128](num/struct.nonzerou128)
* [num::NonZeroU16](num/struct.nonzerou16)
* [num::NonZeroU32](num/struct.nonzerou32)
* [num::NonZeroU64](num/struct.nonzerou64)
* [num::NonZeroU8](num/struct.nonzerou8)
* [num::NonZeroUsize](num/struct.nonzerousize)
* [num::ParseFloatError](num/struct.parsefloaterror)
* [num::ParseIntError](num/struct.parseinterror)
* [num::Saturating](num/struct.saturating)
* [num::TryFromIntError](num/struct.tryfrominterror)
* [num::Wrapping](num/struct.wrapping)
* [ops::Range](ops/struct.range)
* [ops::RangeFrom](ops/struct.rangefrom)
* [ops::RangeFull](ops/struct.rangefull)
* [ops::RangeInclusive](ops/struct.rangeinclusive)
* [ops::RangeTo](ops/struct.rangeto)
* [ops::RangeToInclusive](ops/struct.rangetoinclusive)
* [ops::Yeet](ops/struct.yeet)
* [option::IntoIter](option/struct.intoiter)
* [option::Iter](option/struct.iter)
* [option::IterMut](option/struct.itermut)
* [os::fd::BorrowedFd](os/fd/struct.borrowedfd)
* [os::fd::OwnedFd](os/fd/struct.ownedfd)
* [os::linux::process::PidFd](os/linux/process/struct.pidfd)
* [os::linux::raw::stat](os/linux/raw/struct.stat)
* [os::unix::net::Incoming](os/unix/net/struct.incoming)
* [os::unix::net::Messages](os/unix/net/struct.messages)
* [os::unix::net::ScmCredentials](os/unix/net/struct.scmcredentials)
* [os::unix::net::ScmRights](os/unix/net/struct.scmrights)
* [os::unix::net::SocketAddr](os/unix/net/struct.socketaddr)
* [os::unix::net::SocketAncillary](os/unix/net/struct.socketancillary)
* [os::unix::net::SocketCred](os/unix/net/struct.socketcred)
* [os::unix::net::UnixDatagram](os/unix/net/struct.unixdatagram)
* [os::unix::net::UnixListener](os/unix/net/struct.unixlistener)
* [os::unix::net::UnixStream](os/unix/net/struct.unixstream)
* [os::unix::ucred::UCred](os/unix/ucred/struct.ucred)
* [os::windows::ffi::EncodeWide](os/windows/ffi/struct.encodewide)
* [os::windows::io::BorrowedHandle](os/windows/io/struct.borrowedhandle)
* [os::windows::io::BorrowedSocket](os/windows/io/struct.borrowedsocket)
* [os::windows::io::HandleOrInvalid](os/windows/io/struct.handleorinvalid)
* [os::windows::io::HandleOrNull](os/windows/io/struct.handleornull)
* [os::windows::io::InvalidHandleError](os/windows/io/struct.invalidhandleerror)
* [os::windows::io::NullHandleError](os/windows/io/struct.nullhandleerror)
* [os::windows::io::OwnedHandle](os/windows/io/struct.ownedhandle)
* [os::windows::io::OwnedSocket](os/windows/io/struct.ownedsocket)
* [panic::AssertUnwindSafe](panic/struct.assertunwindsafe)
* [panic::Location](panic/struct.location)
* [panic::PanicInfo](panic/struct.panicinfo)
* [path::Ancestors](path/struct.ancestors)
* [path::Components](path/struct.components)
* [path::Display](path/struct.display)
* [path::Iter](path/struct.iter)
* [path::Path](path/struct.path)
* [path::PathBuf](path/struct.pathbuf)
* [path::PrefixComponent](path/struct.prefixcomponent)
* [path::StripPrefixError](path/struct.stripprefixerror)
* [pin::Pin](pin/struct.pin)
* [process::Child](process/struct.child)
* [process::ChildStderr](process/struct.childstderr)
* [process::ChildStdin](process/struct.childstdin)
* [process::ChildStdout](process/struct.childstdout)
* [process::Command](process/struct.command)
* [process::CommandArgs](process/struct.commandargs)
* [process::CommandEnvs](process/struct.commandenvs)
* [process::ExitCode](process/struct.exitcode)
* [process::ExitStatus](process/struct.exitstatus)
* [process::ExitStatusError](process/struct.exitstatuserror)
* [process::Output](process/struct.output)
* [process::Stdio](process/struct.stdio)
* [ptr::Alignment](ptr/struct.alignment)
* [ptr::DynMetadata](ptr/struct.dynmetadata)
* [ptr::NonNull](ptr/struct.nonnull)
* [rc::Rc](rc/struct.rc)
* [rc::Weak](rc/struct.weak)
* [result::IntoIter](result/struct.intoiter)
* [result::Iter](result/struct.iter)
* [result::IterMut](result/struct.itermut)
* [simd::LaneCount](simd/struct.lanecount)
* [simd::Mask](simd/struct.mask)
* [simd::Simd](simd/struct.simd)
* [slice::ArrayChunks](slice/struct.arraychunks)
* [slice::ArrayChunksMut](slice/struct.arraychunksmut)
* [slice::ArrayWindows](slice/struct.arraywindows)
* [slice::Chunks](slice/struct.chunks)
* [slice::ChunksExact](slice/struct.chunksexact)
* [slice::ChunksExactMut](slice/struct.chunksexactmut)
* [slice::ChunksMut](slice/struct.chunksmut)
* [slice::EscapeAscii](slice/struct.escapeascii)
* [slice::GroupBy](slice/struct.groupby)
* [slice::GroupByMut](slice/struct.groupbymut)
* [slice::Iter](slice/struct.iter)
* [slice::IterMut](slice/struct.itermut)
* [slice::RChunks](slice/struct.rchunks)
* [slice::RChunksExact](slice/struct.rchunksexact)
* [slice::RChunksExactMut](slice/struct.rchunksexactmut)
* [slice::RChunksMut](slice/struct.rchunksmut)
* [slice::RSplit](slice/struct.rsplit)
* [slice::RSplitMut](slice/struct.rsplitmut)
* [slice::RSplitN](slice/struct.rsplitn)
* [slice::RSplitNMut](slice/struct.rsplitnmut)
* [slice::Split](slice/struct.split)
* [slice::SplitInclusive](slice/struct.splitinclusive)
* [slice::SplitInclusiveMut](slice/struct.splitinclusivemut)
* [slice::SplitMut](slice/struct.splitmut)
* [slice::SplitN](slice/struct.splitn)
* [slice::SplitNMut](slice/struct.splitnmut)
* [slice::Windows](slice/struct.windows)
* [str::Bytes](str/struct.bytes)
* [str::CharIndices](str/struct.charindices)
* [str::Chars](str/struct.chars)
* [str::EncodeUtf16](str/struct.encodeutf16)
* [str::EscapeDebug](str/struct.escapedebug)
* [str::EscapeDefault](str/struct.escapedefault)
* [str::EscapeUnicode](str/struct.escapeunicode)
* [str::Lines](str/struct.lines)
* [str::LinesAny](str/struct.linesany)
* [str::MatchIndices](str/struct.matchindices)
* [str::Matches](str/struct.matches)
* [str::ParseBoolError](str/struct.parseboolerror)
* [str::RMatchIndices](str/struct.rmatchindices)
* [str::RMatches](str/struct.rmatches)
* [str::RSplit](str/struct.rsplit)
* [str::RSplitN](str/struct.rsplitn)
* [str::RSplitTerminator](str/struct.rsplitterminator)
* [str::Split](str/struct.split)
* [str::SplitAsciiWhitespace](str/struct.splitasciiwhitespace)
* [str::SplitInclusive](str/struct.splitinclusive)
* [str::SplitN](str/struct.splitn)
* [str::SplitTerminator](str/struct.splitterminator)
* [str::SplitWhitespace](str/struct.splitwhitespace)
* [str::Utf8Chunk](str/struct.utf8chunk)
* [str::Utf8Chunks](str/struct.utf8chunks)
* [str::Utf8Error](str/struct.utf8error)
* [str::pattern::CharArrayRefSearcher](str/pattern/struct.chararrayrefsearcher)
* [str::pattern::CharArraySearcher](str/pattern/struct.chararraysearcher)
* [str::pattern::CharPredicateSearcher](str/pattern/struct.charpredicatesearcher)
* [str::pattern::CharSearcher](str/pattern/struct.charsearcher)
* [str::pattern::CharSliceSearcher](str/pattern/struct.charslicesearcher)
* [str::pattern::StrSearcher](str/pattern/struct.strsearcher)
* [string::Drain](string/struct.drain)
* [string::FromUtf16Error](string/struct.fromutf16error)
* [string::FromUtf8Error](string/struct.fromutf8error)
* [string::String](string/struct.string)
* [sync::Arc](sync/struct.arc)
* [sync::Barrier](sync/struct.barrier)
* [sync::BarrierWaitResult](sync/struct.barrierwaitresult)
* [sync::Condvar](sync/struct.condvar)
* [sync::Exclusive](sync/struct.exclusive)
* [sync::LazyLock](sync/struct.lazylock)
* [sync::Mutex](sync/struct.mutex)
* [sync::MutexGuard](sync/struct.mutexguard)
* [sync::Once](sync/struct.once)
* [sync::OnceLock](sync/struct.oncelock)
* [sync::OnceState](sync/struct.oncestate)
* [sync::PoisonError](sync/struct.poisonerror)
* [sync::RwLock](sync/struct.rwlock)
* [sync::RwLockReadGuard](sync/struct.rwlockreadguard)
* [sync::RwLockWriteGuard](sync/struct.rwlockwriteguard)
* [sync::WaitTimeoutResult](sync/struct.waittimeoutresult)
* [sync::Weak](sync/struct.weak)
* [sync::atomic::AtomicBool](sync/atomic/struct.atomicbool)
* [sync::atomic::AtomicI16](sync/atomic/struct.atomici16)
* [sync::atomic::AtomicI32](sync/atomic/struct.atomici32)
* [sync::atomic::AtomicI64](sync/atomic/struct.atomici64)
* [sync::atomic::AtomicI8](sync/atomic/struct.atomici8)
* [sync::atomic::AtomicIsize](sync/atomic/struct.atomicisize)
* [sync::atomic::AtomicPtr](sync/atomic/struct.atomicptr)
* [sync::atomic::AtomicU16](sync/atomic/struct.atomicu16)
* [sync::atomic::AtomicU32](sync/atomic/struct.atomicu32)
* [sync::atomic::AtomicU64](sync/atomic/struct.atomicu64)
* [sync::atomic::AtomicU8](sync/atomic/struct.atomicu8)
* [sync::atomic::AtomicUsize](sync/atomic/struct.atomicusize)
* [sync::mpsc::IntoIter](sync/mpsc/struct.intoiter)
* [sync::mpsc::Iter](sync/mpsc/struct.iter)
* [sync::mpsc::Receiver](sync/mpsc/struct.receiver)
* [sync::mpsc::RecvError](sync/mpsc/struct.recverror)
* [sync::mpsc::SendError](sync/mpsc/struct.senderror)
* [sync::mpsc::Sender](sync/mpsc/struct.sender)
* [sync::mpsc::SyncSender](sync/mpsc/struct.syncsender)
* [sync::mpsc::TryIter](sync/mpsc/struct.tryiter)
* [task::Context](task/struct.context)
* [task::RawWaker](task/struct.rawwaker)
* [task::RawWakerVTable](task/struct.rawwakervtable)
* [task::Waker](task/struct.waker)
* [thread::AccessError](thread/struct.accesserror)
* [thread::Builder](thread/struct.builder)
* [thread::JoinHandle](thread/struct.joinhandle)
* [thread::LocalKey](thread/struct.localkey)
* [thread::Scope](thread/struct.scope)
* [thread::ScopedJoinHandle](thread/struct.scopedjoinhandle)
* [thread::Thread](thread/struct.thread)
* [thread::ThreadId](thread/struct.threadid)
* [time::Duration](time/struct.duration)
* [time::Instant](time/struct.instant)
* [time::SystemTime](time/struct.systemtime)
* [time::SystemTimeError](time/struct.systemtimeerror)
* [time::TryFromFloatSecsError](time/struct.tryfromfloatsecserror)
* [vec::Drain](vec/struct.drain)
* [vec::DrainFilter](vec/struct.drainfilter)
* [vec::IntoIter](vec/struct.intoiter)
* [vec::Splice](vec/struct.splice)
* [vec::Vec](vec/struct.vec)


### Enums


* [ascii::Char](ascii/enum.char)
* [backtrace::BacktraceStatus](backtrace/enum.backtracestatus)
* [borrow::Cow](borrow/enum.cow)
* [cmp::Ordering](cmp/enum.ordering)
* [collections::TryReserveErrorKind](collections/enum.tryreserveerrorkind)
* [collections::btree\_map::Entry](collections/btree_map/enum.entry)
* [collections::hash\_map::Entry](collections/hash_map/enum.entry)
* [collections::hash\_map::RawEntryMut](collections/hash_map/enum.rawentrymut)
* [convert::Infallible](convert/enum.infallible)
* [env::VarError](env/enum.varerror)
* [ffi::c\_void](ffi/enum.c_void)
* [fmt::Alignment](fmt/enum.alignment)
* [io::ErrorKind](io/enum.errorkind)
* [io::SeekFrom](io/enum.seekfrom)
* [net::IpAddr](net/enum.ipaddr)
* [net::Ipv6MulticastScope](net/enum.ipv6multicastscope)
* [net::Shutdown](net/enum.shutdown)
* [net::SocketAddr](net/enum.socketaddr)
* [num::FpCategory](num/enum.fpcategory)
* [num::IntErrorKind](num/enum.interrorkind)
* [ops::Bound](ops/enum.bound)
* [ops::ControlFlow](ops/enum.controlflow)
* [ops::GeneratorState](ops/enum.generatorstate)
* [option::Option](option/enum.option)
* [os::unix::net::AncillaryData](os/unix/net/enum.ancillarydata)
* [os::unix::net::AncillaryError](os/unix/net/enum.ancillaryerror)
* [panic::BacktraceStyle](panic/enum.backtracestyle)
* [path::Component](path/enum.component)
* [path::Prefix](path/enum.prefix)
* [result::Result](result/enum.result)
* [simd::Which](simd/enum.which)
* [str::pattern::SearchStep](str/pattern/enum.searchstep)
* [sync::TryLockError](sync/enum.trylockerror)
* [sync::atomic::Ordering](sync/atomic/enum.ordering)
* [sync::mpsc::RecvTimeoutError](sync/mpsc/enum.recvtimeouterror)
* [sync::mpsc::TryRecvError](sync/mpsc/enum.tryrecverror)
* [sync::mpsc::TrySendError](sync/mpsc/enum.trysenderror)
* [task::Poll](task/enum.poll)


### Unions


* [mem::MaybeUninit](mem/union.maybeuninit)


### Primitive Types


* [array](primitive.array)
* [bool](primitive.bool)
* [char](primitive.char)
* [f32](primitive.f32)
* [f64](primitive.f64)
* [fn](primitive.fn)
* [i128](primitive.i128)
* [i16](primitive.i16)
* [i32](primitive.i32)
* [i64](primitive.i64)
* [i8](primitive.i8)
* [isize](primitive.isize)
* [never](primitive.never)
* [pointer](primitive.pointer)
* [reference](primitive.reference)
* [slice](primitive.slice)
* [str](primitive.str)
* [tuple](primitive.tuple)
* [u128](primitive.u128)
* [u16](primitive.u16)
* [u32](primitive.u32)
* [u64](primitive.u64)
* [u8](primitive.u8)
* [unit](primitive.unit)
* [usize](primitive.usize)


### Traits


* [alloc::Allocator](alloc/trait.allocator)
* [alloc::GlobalAlloc](alloc/trait.globalalloc)
* [any::Any](any/trait.any)
* [any::Provider](any/trait.provider)
* [ascii::AsciiExt](ascii/trait.asciiext)
* [async\_iter::AsyncIterator](async_iter/trait.asynciterator)
* [borrow::Borrow](borrow/trait.borrow)
* [borrow::BorrowMut](borrow/trait.borrowmut)
* [borrow::ToOwned](borrow/trait.toowned)
* [clone::Clone](clone/trait.clone)
* [cmp::Eq](cmp/trait.eq)
* [cmp::Ord](cmp/trait.ord)
* [cmp::PartialEq](cmp/trait.partialeq)
* [cmp::PartialOrd](cmp/trait.partialord)
* [convert::AsMut](convert/trait.asmut)
* [convert::AsRef](convert/trait.asref)
* [convert::FloatToInt](convert/trait.floattoint)
* [convert::From](convert/trait.from)
* [convert::Into](convert/trait.into)
* [convert::TryFrom](convert/trait.tryfrom)
* [convert::TryInto](convert/trait.tryinto)
* [default::Default](default/trait.default)
* [error::Error](error/trait.error)
* [fmt::Binary](fmt/trait.binary)
* [fmt::Debug](fmt/trait.debug)
* [fmt::Display](fmt/trait.display)
* [fmt::LowerExp](fmt/trait.lowerexp)
* [fmt::LowerHex](fmt/trait.lowerhex)
* [fmt::Octal](fmt/trait.octal)
* [fmt::Pointer](fmt/trait.pointer)
* [fmt::UpperExp](fmt/trait.upperexp)
* [fmt::UpperHex](fmt/trait.upperhex)
* [fmt::Write](fmt/trait.write)
* [future::Future](future/trait.future)
* [future::IntoFuture](future/trait.intofuture)
* [hash::BuildHasher](hash/trait.buildhasher)
* [hash::Hash](hash/trait.hash)
* [hash::Hasher](hash/trait.hasher)
* [io::BufRead](io/trait.bufread)
* [io::IsTerminal](io/trait.isterminal)
* [io::Read](io/trait.read)
* [io::Seek](io/trait.seek)
* [io::Write](io/trait.write)
* [iter::DoubleEndedIterator](iter/trait.doubleendediterator)
* [iter::ExactSizeIterator](iter/trait.exactsizeiterator)
* [iter::Extend](iter/trait.extend)
* [iter::FromIterator](iter/trait.fromiterator)
* [iter::FusedIterator](iter/trait.fusediterator)
* [iter::IntoIterator](iter/trait.intoiterator)
* [iter::Iterator](iter/trait.iterator)
* [iter::Product](iter/trait.product)
* [iter::Step](iter/trait.step)
* [iter::Sum](iter/trait.sum)
* [iter::TrustedLen](iter/trait.trustedlen)
* [iter::TrustedStep](iter/trait.trustedstep)
* [marker::ConstParamTy](marker/trait.constparamty)
* [marker::Copy](marker/trait.copy)
* [marker::Destruct](marker/trait.destruct)
* [marker::DiscriminantKind](marker/trait.discriminantkind)
* [marker::FnPtr](marker/trait.fnptr)
* [marker::PointerLike](marker/trait.pointerlike)
* [marker::Send](marker/trait.send)
* [marker::Sized](marker/trait.sized)
* [marker::StructuralEq](marker/trait.structuraleq)
* [marker::StructuralPartialEq](marker/trait.structuralpartialeq)
* [marker::Sync](marker/trait.sync)
* [marker::Tuple](marker/trait.tuple)
* [marker::Unpin](marker/trait.unpin)
* [marker::Unsize](marker/trait.unsize)
* [mem::BikeshedIntrinsicFrom](mem/trait.bikeshedintrinsicfrom)
* [net::ToSocketAddrs](net/trait.tosocketaddrs)
* [ops::Add](ops/trait.add)
* [ops::AddAssign](ops/trait.addassign)
* [ops::BitAnd](ops/trait.bitand)
* [ops::BitAndAssign](ops/trait.bitandassign)
* [ops::BitOr](ops/trait.bitor)
* [ops::BitOrAssign](ops/trait.bitorassign)
* [ops::BitXor](ops/trait.bitxor)
* [ops::BitXorAssign](ops/trait.bitxorassign)
* [ops::CoerceUnsized](ops/trait.coerceunsized)
* [ops::Deref](ops/trait.deref)
* [ops::DerefMut](ops/trait.derefmut)
* [ops::DispatchFromDyn](ops/trait.dispatchfromdyn)
* [ops::Div](ops/trait.div)
* [ops::DivAssign](ops/trait.divassign)
* [ops::Drop](ops/trait.drop)
* [ops::Fn](ops/trait.fn)
* [ops::FnMut](ops/trait.fnmut)
* [ops::FnOnce](ops/trait.fnonce)
* [ops::FromResidual](ops/trait.fromresidual)
* [ops::Generator](ops/trait.generator)
* [ops::Index](ops/trait.index)
* [ops::IndexMut](ops/trait.indexmut)
* [ops::Mul](ops/trait.mul)
* [ops::MulAssign](ops/trait.mulassign)
* [ops::Neg](ops/trait.neg)
* [ops::Not](ops/trait.not)
* [ops::OneSidedRange](ops/trait.onesidedrange)
* [ops::RangeBounds](ops/trait.rangebounds)
* [ops::Rem](ops/trait.rem)
* [ops::RemAssign](ops/trait.remassign)
* [ops::Residual](ops/trait.residual)
* [ops::Shl](ops/trait.shl)
* [ops::ShlAssign](ops/trait.shlassign)
* [ops::Shr](ops/trait.shr)
* [ops::ShrAssign](ops/trait.shrassign)
* [ops::Sub](ops/trait.sub)
* [ops::SubAssign](ops/trait.subassign)
* [ops::Try](ops/trait.try)
* [os::fd::AsFd](os/fd/trait.asfd)
* [os::fd::AsRawFd](os/fd/trait.asrawfd)
* [os::fd::FromRawFd](os/fd/trait.fromrawfd)
* [os::fd::IntoRawFd](os/fd/trait.intorawfd)
* [os::linux::fs::MetadataExt](os/linux/fs/trait.metadataext)
* [os::linux::net::SocketAddrExt](os/linux/net/trait.socketaddrext)
* [os::linux::net::TcpStreamExt](os/linux/net/trait.tcpstreamext)
* [os::linux::process::ChildExt](os/linux/process/trait.childext)
* [os::linux::process::CommandExt](os/linux/process/trait.commandext)
* [os::unix::ffi::OsStrExt](os/unix/ffi/trait.osstrext)
* [os::unix::ffi::OsStringExt](os/unix/ffi/trait.osstringext)
* [os::unix::fs::DirBuilderExt](os/unix/fs/trait.dirbuilderext)
* [os::unix::fs::DirEntryExt](os/unix/fs/trait.direntryext)
* [os::unix::fs::DirEntryExt2](os/unix/fs/trait.direntryext2)
* [os::unix::fs::FileExt](os/unix/fs/trait.fileext)
* [os::unix::fs::FileTypeExt](os/unix/fs/trait.filetypeext)
* [os::unix::fs::MetadataExt](os/unix/fs/trait.metadataext)
* [os::unix::fs::OpenOptionsExt](os/unix/fs/trait.openoptionsext)
* [os::unix::fs::PermissionsExt](os/unix/fs/trait.permissionsext)
* [os::unix::process::CommandExt](os/unix/process/trait.commandext)
* [os::unix::process::ExitStatusExt](os/unix/process/trait.exitstatusext)
* [os::unix::thread::JoinHandleExt](os/unix/thread/trait.joinhandleext)
* [os::wasi::ffi::OsStrExt](os/wasi/ffi/trait.osstrext)
* [os::wasi::ffi::OsStringExt](os/wasi/ffi/trait.osstringext)
* [os::wasi::fs::DirEntryExt](os/wasi/fs/trait.direntryext)
* [os::wasi::fs::FileExt](os/wasi/fs/trait.fileext)
* [os::wasi::fs::FileTypeExt](os/wasi/fs/trait.filetypeext)
* [os::wasi::fs::MetadataExt](os/wasi/fs/trait.metadataext)
* [os::wasi::fs::OpenOptionsExt](os/wasi/fs/trait.openoptionsext)
* [os::wasi::net::TcpListenerExt](os/wasi/net/trait.tcplistenerext)
* [os::windows::ffi::OsStrExt](os/windows/ffi/trait.osstrext)
* [os::windows::ffi::OsStringExt](os/windows/ffi/trait.osstringext)
* [os::windows::fs::FileExt](os/windows/fs/trait.fileext)
* [os::windows::fs::FileTimesExt](os/windows/fs/trait.filetimesext)
* [os::windows::fs::FileTypeExt](os/windows/fs/trait.filetypeext)
* [os::windows::fs::MetadataExt](os/windows/fs/trait.metadataext)
* [os::windows::fs::OpenOptionsExt](os/windows/fs/trait.openoptionsext)
* [os::windows::io::AsHandle](os/windows/io/trait.ashandle)
* [os::windows::io::AsRawHandle](os/windows/io/trait.asrawhandle)
* [os::windows::io::AsRawSocket](os/windows/io/trait.asrawsocket)
* [os::windows::io::AsSocket](os/windows/io/trait.assocket)
* [os::windows::io::FromRawHandle](os/windows/io/trait.fromrawhandle)
* [os::windows::io::FromRawSocket](os/windows/io/trait.fromrawsocket)
* [os::windows::io::IntoRawHandle](os/windows/io/trait.intorawhandle)
* [os::windows::io::IntoRawSocket](os/windows/io/trait.intorawsocket)
* [os::windows::process::ChildExt](os/windows/process/trait.childext)
* [os::windows::process::CommandExt](os/windows/process/trait.commandext)
* [os::windows::process::ExitCodeExt](os/windows/process/trait.exitcodeext)
* [os::windows::process::ExitStatusExt](os/windows/process/trait.exitstatusext)
* [panic::RefUnwindSafe](panic/trait.refunwindsafe)
* [panic::UnwindSafe](panic/trait.unwindsafe)
* [process::Termination](process/trait.termination)
* [ptr::Pointee](ptr/trait.pointee)
* [simd::MaskElement](simd/trait.maskelement)
* [simd::SimdCast](simd/trait.simdcast)
* [simd::SimdCastPtr](simd/trait.simdcastptr)
* [simd::SimdConstPtr](simd/trait.simdconstptr)
* [simd::SimdElement](simd/trait.simdelement)
* [simd::SimdFloat](simd/trait.simdfloat)
* [simd::SimdInt](simd/trait.simdint)
* [simd::SimdMutPtr](simd/trait.simdmutptr)
* [simd::SimdOrd](simd/trait.simdord)
* [simd::SimdPartialEq](simd/trait.simdpartialeq)
* [simd::SimdPartialOrd](simd/trait.simdpartialord)
* [simd::SimdUint](simd/trait.simduint)
* [simd::StdFloat](simd/trait.stdfloat)
* [simd::SupportedLaneCount](simd/trait.supportedlanecount)
* [simd::Swizzle](simd/trait.swizzle)
* [simd::Swizzle2](simd/trait.swizzle2)
* [simd::ToBitMask](simd/trait.tobitmask)
* [slice::Concat](slice/trait.concat)
* [slice::Join](slice/trait.join)
* [slice::SliceIndex](slice/trait.sliceindex)
* [str::FromStr](str/trait.fromstr)
* [str::pattern::DoubleEndedSearcher](str/pattern/trait.doubleendedsearcher)
* [str::pattern::Pattern](str/pattern/trait.pattern)
* [str::pattern::ReverseSearcher](str/pattern/trait.reversesearcher)
* [str::pattern::Searcher](str/pattern/trait.searcher)
* [string::ToString](string/trait.tostring)
* [task::Wake](task/trait.wake)


### Macros


* [arch::is\_aarch64\_feature\_detected](arch/macro.is_aarch64_feature_detected)
* [arch::is\_arm\_feature\_detected](arch/macro.is_arm_feature_detected)
* [arch::is\_mips64\_feature\_detected](arch/macro.is_mips64_feature_detected)
* [arch::is\_mips\_feature\_detected](arch/macro.is_mips_feature_detected)
* [arch::is\_powerpc64\_feature\_detected](arch/macro.is_powerpc64_feature_detected)
* [arch::is\_powerpc\_feature\_detected](arch/macro.is_powerpc_feature_detected)
* [arch::is\_riscv\_feature\_detected](arch/macro.is_riscv_feature_detected)
* [arch::is\_x86\_feature\_detected](arch/macro.is_x86_feature_detected)
* [assert](macro.assert)
* [assert\_eq](macro.assert_eq)
* [assert\_matches::assert\_matches](assert_matches/macro.assert_matches)
* [assert\_matches::debug\_assert\_matches](assert_matches/macro.debug_assert_matches)
* [assert\_ne](macro.assert_ne)
* [cfg](macro.cfg)
* [column](macro.column)
* [compile\_error](macro.compile_error)
* [concat](macro.concat)
* [concat\_bytes](macro.concat_bytes)
* [concat\_idents](macro.concat_idents)
* [const\_format\_args](macro.const_format_args)
* [dbg](macro.dbg)
* [debug\_assert](macro.debug_assert)
* [debug\_assert\_eq](macro.debug_assert_eq)
* [debug\_assert\_ne](macro.debug_assert_ne)
* [env](macro.env)
* [eprint](macro.eprint)
* [eprintln](macro.eprintln)
* [file](macro.file)
* [format](macro.format)
* [format\_args](macro.format_args)
* [format\_args\_nl](macro.format_args_nl)
* [future::join](future/macro.join)
* [include](macro.include)
* [include\_bytes](macro.include_bytes)
* [include\_str](macro.include_str)
* [intrinsics::mir::mir](intrinsics/mir/macro.mir)
* [intrinsics::mir::place](intrinsics/mir/macro.place)
* [is\_x86\_feature\_detected](macro.is_x86_feature_detected)
* [line](macro.line)
* [log\_syntax](macro.log_syntax)
* [matches](macro.matches)
* [mem::offset\_of](mem/macro.offset_of)
* [module\_path](macro.module_path)
* [option\_env](macro.option_env)
* [panic](macro.panic)
* [pin::pin](pin/macro.pin)
* [prelude::v1::type\_ascribe](prelude/v1/macro.type_ascribe)
* [print](macro.print)
* [println](macro.println)
* [ptr::addr\_of](ptr/macro.addr_of)
* [ptr::addr\_of\_mut](ptr/macro.addr_of_mut)
* [simd::simd\_swizzle](simd/macro.simd_swizzle)
* [stringify](macro.stringify)
* [task::ready](task/macro.ready)
* [thread\_local](macro.thread_local)
* [todo](macro.todo)
* [trace\_macros](macro.trace_macros)
* [try](macro.try)
* [unimplemented](macro.unimplemented)
* [unreachable](macro.unreachable)
* [vec](macro.vec)
* [write](macro.write)
* [writeln](macro.writeln)


### Attribute Macros


* [prelude::v1::alloc\_error\_handler](prelude/v1/attr.alloc_error_handler)
* [prelude::v1::bench](prelude/v1/attr.bench)
* [prelude::v1::cfg\_accessible](prelude/v1/attr.cfg_accessible)
* [prelude::v1::cfg\_eval](prelude/v1/attr.cfg_eval)
* [prelude::v1::derive](prelude/v1/attr.derive)
* [prelude::v1::derive\_const](prelude/v1/attr.derive_const)
* [prelude::v1::global\_allocator](prelude/v1/attr.global_allocator)
* [prelude::v1::test](prelude/v1/attr.test)
* [prelude::v1::test\_case](prelude/v1/attr.test_case)


### Derive Macros


* [clone::Clone](clone/derive.clone)
* [cmp::Eq](cmp/derive.eq)
* [cmp::Ord](cmp/derive.ord)
* [cmp::PartialEq](cmp/derive.partialeq)
* [cmp::PartialOrd](cmp/derive.partialord)
* [default::Default](default/derive.default)
* [fmt::Debug](fmt/derive.debug)
* [hash::Hash](hash/derive.hash)
* [marker::ConstParamTy](marker/derive.constparamty)
* [marker::Copy](marker/derive.copy)


### Functions


* [alloc::alloc](alloc/fn.alloc)
* [alloc::alloc\_zeroed](alloc/fn.alloc_zeroed)
* [alloc::dealloc](alloc/fn.dealloc)
* [alloc::handle\_alloc\_error](alloc/fn.handle_alloc_error)
* [alloc::realloc](alloc/fn.realloc)
* [alloc::set\_alloc\_error\_hook](alloc/fn.set_alloc_error_hook)
* [alloc::take\_alloc\_error\_hook](alloc/fn.take_alloc_error_hook)
* [any::request\_ref](any/fn.request_ref)
* [any::request\_value](any/fn.request_value)
* [any::type\_name](any/fn.type_name)
* [any::type\_name\_of\_val](any/fn.type_name_of_val)
* [array::from\_fn](array/fn.from_fn)
* [array::from\_mut](array/fn.from_mut)
* [array::from\_ref](array/fn.from_ref)
* [array::try\_from\_fn](array/fn.try_from_fn)
* [ascii::escape\_default](ascii/fn.escape_default)
* [async\_iter::from\_iter](async_iter/fn.from_iter)
* [char::decode\_utf16](char/fn.decode_utf16)
* [char::from\_digit](char/fn.from_digit)
* [char::from\_u32](char/fn.from_u32)
* [char::from\_u32\_unchecked](char/fn.from_u32_unchecked)
* [cmp::max](cmp/fn.max)
* [cmp::max\_by](cmp/fn.max_by)
* [cmp::max\_by\_key](cmp/fn.max_by_key)
* [cmp::min](cmp/fn.min)
* [cmp::min\_by](cmp/fn.min_by)
* [cmp::min\_by\_key](cmp/fn.min_by_key)
* [convert::identity](convert/fn.identity)
* [default::default](default/fn.default)
* [env::args](env/fn.args)
* [env::args\_os](env/fn.args_os)
* [env::current\_dir](env/fn.current_dir)
* [env::current\_exe](env/fn.current_exe)
* [env::home\_dir](env/fn.home_dir)
* [env::join\_paths](env/fn.join_paths)
* [env::remove\_var](env/fn.remove_var)
* [env::set\_current\_dir](env/fn.set_current_dir)
* [env::set\_var](env/fn.set_var)
* [env::split\_paths](env/fn.split_paths)
* [env::temp\_dir](env/fn.temp_dir)
* [env::var](env/fn.var)
* [env::var\_os](env/fn.var_os)
* [env::vars](env/fn.vars)
* [env::vars\_os](env/fn.vars_os)
* [fmt::format](fmt/fn.format)
* [fmt::write](fmt/fn.write)
* [fs::canonicalize](fs/fn.canonicalize)
* [fs::copy](fs/fn.copy)
* [fs::create\_dir](fs/fn.create_dir)
* [fs::create\_dir\_all](fs/fn.create_dir_all)
* [fs::hard\_link](fs/fn.hard_link)
* [fs::metadata](fs/fn.metadata)
* [fs::read](fs/fn.read)
* [fs::read\_dir](fs/fn.read_dir)
* [fs::read\_link](fs/fn.read_link)
* [fs::read\_to\_string](fs/fn.read_to_string)
* [fs::remove\_dir](fs/fn.remove_dir)
* [fs::remove\_dir\_all](fs/fn.remove_dir_all)
* [fs::remove\_file](fs/fn.remove_file)
* [fs::rename](fs/fn.rename)
* [fs::set\_permissions](fs/fn.set_permissions)
* [fs::soft\_link](fs/fn.soft_link)
* [fs::symlink\_metadata](fs/fn.symlink_metadata)
* [fs::try\_exists](fs/fn.try_exists)
* [fs::write](fs/fn.write)
* [future::pending](future/fn.pending)
* [future::poll\_fn](future/fn.poll_fn)
* [future::ready](future/fn.ready)
* [hint::black\_box](hint/fn.black_box)
* [hint::must\_use](hint/fn.must_use)
* [hint::spin\_loop](hint/fn.spin_loop)
* [hint::unreachable\_unchecked](hint/fn.unreachable_unchecked)
* [intrinsics::abort](intrinsics/fn.abort)
* [intrinsics::add\_with\_overflow](intrinsics/fn.add_with_overflow)
* [intrinsics::arith\_offset](intrinsics/fn.arith_offset)
* [intrinsics::assert\_inhabited](intrinsics/fn.assert_inhabited)
* [intrinsics::assert\_mem\_uninitialized\_valid](intrinsics/fn.assert_mem_uninitialized_valid)
* [intrinsics::assert\_zero\_valid](intrinsics/fn.assert_zero_valid)
* [intrinsics::assume](intrinsics/fn.assume)
* [intrinsics::atomic\_and\_acqrel](intrinsics/fn.atomic_and_acqrel)
* [intrinsics::atomic\_and\_acquire](intrinsics/fn.atomic_and_acquire)
* [intrinsics::atomic\_and\_relaxed](intrinsics/fn.atomic_and_relaxed)
* [intrinsics::atomic\_and\_release](intrinsics/fn.atomic_and_release)
* [intrinsics::atomic\_and\_seqcst](intrinsics/fn.atomic_and_seqcst)
* [intrinsics::atomic\_cxchg\_acqrel\_acquire](intrinsics/fn.atomic_cxchg_acqrel_acquire)
* [intrinsics::atomic\_cxchg\_acqrel\_relaxed](intrinsics/fn.atomic_cxchg_acqrel_relaxed)
* [intrinsics::atomic\_cxchg\_acqrel\_seqcst](intrinsics/fn.atomic_cxchg_acqrel_seqcst)
* [intrinsics::atomic\_cxchg\_acquire\_acquire](intrinsics/fn.atomic_cxchg_acquire_acquire)
* [intrinsics::atomic\_cxchg\_acquire\_relaxed](intrinsics/fn.atomic_cxchg_acquire_relaxed)
* [intrinsics::atomic\_cxchg\_acquire\_seqcst](intrinsics/fn.atomic_cxchg_acquire_seqcst)
* [intrinsics::atomic\_cxchg\_relaxed\_acquire](intrinsics/fn.atomic_cxchg_relaxed_acquire)
* [intrinsics::atomic\_cxchg\_relaxed\_relaxed](intrinsics/fn.atomic_cxchg_relaxed_relaxed)
* [intrinsics::atomic\_cxchg\_relaxed\_seqcst](intrinsics/fn.atomic_cxchg_relaxed_seqcst)
* [intrinsics::atomic\_cxchg\_release\_acquire](intrinsics/fn.atomic_cxchg_release_acquire)
* [intrinsics::atomic\_cxchg\_release\_relaxed](intrinsics/fn.atomic_cxchg_release_relaxed)
* [intrinsics::atomic\_cxchg\_release\_seqcst](intrinsics/fn.atomic_cxchg_release_seqcst)
* [intrinsics::atomic\_cxchg\_seqcst\_acquire](intrinsics/fn.atomic_cxchg_seqcst_acquire)
* [intrinsics::atomic\_cxchg\_seqcst\_relaxed](intrinsics/fn.atomic_cxchg_seqcst_relaxed)
* [intrinsics::atomic\_cxchg\_seqcst\_seqcst](intrinsics/fn.atomic_cxchg_seqcst_seqcst)
* [intrinsics::atomic\_cxchgweak\_acqrel\_acquire](intrinsics/fn.atomic_cxchgweak_acqrel_acquire)
* [intrinsics::atomic\_cxchgweak\_acqrel\_relaxed](intrinsics/fn.atomic_cxchgweak_acqrel_relaxed)
* [intrinsics::atomic\_cxchgweak\_acqrel\_seqcst](intrinsics/fn.atomic_cxchgweak_acqrel_seqcst)
* [intrinsics::atomic\_cxchgweak\_acquire\_acquire](intrinsics/fn.atomic_cxchgweak_acquire_acquire)
* [intrinsics::atomic\_cxchgweak\_acquire\_relaxed](intrinsics/fn.atomic_cxchgweak_acquire_relaxed)
* [intrinsics::atomic\_cxchgweak\_acquire\_seqcst](intrinsics/fn.atomic_cxchgweak_acquire_seqcst)
* [intrinsics::atomic\_cxchgweak\_relaxed\_acquire](intrinsics/fn.atomic_cxchgweak_relaxed_acquire)
* [intrinsics::atomic\_cxchgweak\_relaxed\_relaxed](intrinsics/fn.atomic_cxchgweak_relaxed_relaxed)
* [intrinsics::atomic\_cxchgweak\_relaxed\_seqcst](intrinsics/fn.atomic_cxchgweak_relaxed_seqcst)
* [intrinsics::atomic\_cxchgweak\_release\_acquire](intrinsics/fn.atomic_cxchgweak_release_acquire)
* [intrinsics::atomic\_cxchgweak\_release\_relaxed](intrinsics/fn.atomic_cxchgweak_release_relaxed)
* [intrinsics::atomic\_cxchgweak\_release\_seqcst](intrinsics/fn.atomic_cxchgweak_release_seqcst)
* [intrinsics::atomic\_cxchgweak\_seqcst\_acquire](intrinsics/fn.atomic_cxchgweak_seqcst_acquire)
* [intrinsics::atomic\_cxchgweak\_seqcst\_relaxed](intrinsics/fn.atomic_cxchgweak_seqcst_relaxed)
* [intrinsics::atomic\_cxchgweak\_seqcst\_seqcst](intrinsics/fn.atomic_cxchgweak_seqcst_seqcst)
* [intrinsics::atomic\_fence\_acqrel](intrinsics/fn.atomic_fence_acqrel)
* [intrinsics::atomic\_fence\_acquire](intrinsics/fn.atomic_fence_acquire)
* [intrinsics::atomic\_fence\_release](intrinsics/fn.atomic_fence_release)
* [intrinsics::atomic\_fence\_seqcst](intrinsics/fn.atomic_fence_seqcst)
* [intrinsics::atomic\_load\_acquire](intrinsics/fn.atomic_load_acquire)
* [intrinsics::atomic\_load\_relaxed](intrinsics/fn.atomic_load_relaxed)
* [intrinsics::atomic\_load\_seqcst](intrinsics/fn.atomic_load_seqcst)
* [intrinsics::atomic\_load\_unordered](intrinsics/fn.atomic_load_unordered)
* [intrinsics::atomic\_max\_acqrel](intrinsics/fn.atomic_max_acqrel)
* [intrinsics::atomic\_max\_acquire](intrinsics/fn.atomic_max_acquire)
* [intrinsics::atomic\_max\_relaxed](intrinsics/fn.atomic_max_relaxed)
* [intrinsics::atomic\_max\_release](intrinsics/fn.atomic_max_release)
* [intrinsics::atomic\_max\_seqcst](intrinsics/fn.atomic_max_seqcst)
* [intrinsics::atomic\_min\_acqrel](intrinsics/fn.atomic_min_acqrel)
* [intrinsics::atomic\_min\_acquire](intrinsics/fn.atomic_min_acquire)
* [intrinsics::atomic\_min\_relaxed](intrinsics/fn.atomic_min_relaxed)
* [intrinsics::atomic\_min\_release](intrinsics/fn.atomic_min_release)
* [intrinsics::atomic\_min\_seqcst](intrinsics/fn.atomic_min_seqcst)
* [intrinsics::atomic\_nand\_acqrel](intrinsics/fn.atomic_nand_acqrel)
* [intrinsics::atomic\_nand\_acquire](intrinsics/fn.atomic_nand_acquire)
* [intrinsics::atomic\_nand\_relaxed](intrinsics/fn.atomic_nand_relaxed)
* [intrinsics::atomic\_nand\_release](intrinsics/fn.atomic_nand_release)
* [intrinsics::atomic\_nand\_seqcst](intrinsics/fn.atomic_nand_seqcst)
* [intrinsics::atomic\_or\_acqrel](intrinsics/fn.atomic_or_acqrel)
* [intrinsics::atomic\_or\_acquire](intrinsics/fn.atomic_or_acquire)
* [intrinsics::atomic\_or\_relaxed](intrinsics/fn.atomic_or_relaxed)
* [intrinsics::atomic\_or\_release](intrinsics/fn.atomic_or_release)
* [intrinsics::atomic\_or\_seqcst](intrinsics/fn.atomic_or_seqcst)
* [intrinsics::atomic\_singlethreadfence\_acqrel](intrinsics/fn.atomic_singlethreadfence_acqrel)
* [intrinsics::atomic\_singlethreadfence\_acquire](intrinsics/fn.atomic_singlethreadfence_acquire)
* [intrinsics::atomic\_singlethreadfence\_release](intrinsics/fn.atomic_singlethreadfence_release)
* [intrinsics::atomic\_singlethreadfence\_seqcst](intrinsics/fn.atomic_singlethreadfence_seqcst)
* [intrinsics::atomic\_store\_relaxed](intrinsics/fn.atomic_store_relaxed)
* [intrinsics::atomic\_store\_release](intrinsics/fn.atomic_store_release)
* [intrinsics::atomic\_store\_seqcst](intrinsics/fn.atomic_store_seqcst)
* [intrinsics::atomic\_store\_unordered](intrinsics/fn.atomic_store_unordered)
* [intrinsics::atomic\_umax\_acqrel](intrinsics/fn.atomic_umax_acqrel)
* [intrinsics::atomic\_umax\_acquire](intrinsics/fn.atomic_umax_acquire)
* [intrinsics::atomic\_umax\_relaxed](intrinsics/fn.atomic_umax_relaxed)
* [intrinsics::atomic\_umax\_release](intrinsics/fn.atomic_umax_release)
* [intrinsics::atomic\_umax\_seqcst](intrinsics/fn.atomic_umax_seqcst)
* [intrinsics::atomic\_umin\_acqrel](intrinsics/fn.atomic_umin_acqrel)
* [intrinsics::atomic\_umin\_acquire](intrinsics/fn.atomic_umin_acquire)
* [intrinsics::atomic\_umin\_relaxed](intrinsics/fn.atomic_umin_relaxed)
* [intrinsics::atomic\_umin\_release](intrinsics/fn.atomic_umin_release)
* [intrinsics::atomic\_umin\_seqcst](intrinsics/fn.atomic_umin_seqcst)
* [intrinsics::atomic\_xadd\_acqrel](intrinsics/fn.atomic_xadd_acqrel)
* [intrinsics::atomic\_xadd\_acquire](intrinsics/fn.atomic_xadd_acquire)
* [intrinsics::atomic\_xadd\_relaxed](intrinsics/fn.atomic_xadd_relaxed)
* [intrinsics::atomic\_xadd\_release](intrinsics/fn.atomic_xadd_release)
* [intrinsics::atomic\_xadd\_seqcst](intrinsics/fn.atomic_xadd_seqcst)
* [intrinsics::atomic\_xchg\_acqrel](intrinsics/fn.atomic_xchg_acqrel)
* [intrinsics::atomic\_xchg\_acquire](intrinsics/fn.atomic_xchg_acquire)
* [intrinsics::atomic\_xchg\_relaxed](intrinsics/fn.atomic_xchg_relaxed)
* [intrinsics::atomic\_xchg\_release](intrinsics/fn.atomic_xchg_release)
* [intrinsics::atomic\_xchg\_seqcst](intrinsics/fn.atomic_xchg_seqcst)
* [intrinsics::atomic\_xor\_acqrel](intrinsics/fn.atomic_xor_acqrel)
* [intrinsics::atomic\_xor\_acquire](intrinsics/fn.atomic_xor_acquire)
* [intrinsics::atomic\_xor\_relaxed](intrinsics/fn.atomic_xor_relaxed)
* [intrinsics::atomic\_xor\_release](intrinsics/fn.atomic_xor_release)
* [intrinsics::atomic\_xor\_seqcst](intrinsics/fn.atomic_xor_seqcst)
* [intrinsics::atomic\_xsub\_acqrel](intrinsics/fn.atomic_xsub_acqrel)
* [intrinsics::atomic\_xsub\_acquire](intrinsics/fn.atomic_xsub_acquire)
* [intrinsics::atomic\_xsub\_relaxed](intrinsics/fn.atomic_xsub_relaxed)
* [intrinsics::atomic\_xsub\_release](intrinsics/fn.atomic_xsub_release)
* [intrinsics::atomic\_xsub\_seqcst](intrinsics/fn.atomic_xsub_seqcst)
* [intrinsics::bitreverse](intrinsics/fn.bitreverse)
* [intrinsics::black\_box](intrinsics/fn.black_box)
* [intrinsics::breakpoint](intrinsics/fn.breakpoint)
* [intrinsics::bswap](intrinsics/fn.bswap)
* [intrinsics::caller\_location](intrinsics/fn.caller_location)
* [intrinsics::ceilf32](intrinsics/fn.ceilf32)
* [intrinsics::ceilf64](intrinsics/fn.ceilf64)
* [intrinsics::const\_allocate](intrinsics/fn.const_allocate)
* [intrinsics::const\_deallocate](intrinsics/fn.const_deallocate)
* [intrinsics::const\_eval\_select](intrinsics/fn.const_eval_select)
* [intrinsics::copy](intrinsics/fn.copy)
* [intrinsics::copy\_nonoverlapping](intrinsics/fn.copy_nonoverlapping)
* [intrinsics::copysignf32](intrinsics/fn.copysignf32)
* [intrinsics::copysignf64](intrinsics/fn.copysignf64)
* [intrinsics::cosf32](intrinsics/fn.cosf32)
* [intrinsics::cosf64](intrinsics/fn.cosf64)
* [intrinsics::ctlz](intrinsics/fn.ctlz)
* [intrinsics::ctlz\_nonzero](intrinsics/fn.ctlz_nonzero)
* [intrinsics::ctpop](intrinsics/fn.ctpop)
* [intrinsics::cttz](intrinsics/fn.cttz)
* [intrinsics::cttz\_nonzero](intrinsics/fn.cttz_nonzero)
* [intrinsics::discriminant\_value](intrinsics/fn.discriminant_value)
* [intrinsics::drop\_in\_place](intrinsics/fn.drop_in_place)
* [intrinsics::exact\_div](intrinsics/fn.exact_div)
* [intrinsics::exp2f32](intrinsics/fn.exp2f32)
* [intrinsics::exp2f64](intrinsics/fn.exp2f64)
* [intrinsics::expf32](intrinsics/fn.expf32)
* [intrinsics::expf64](intrinsics/fn.expf64)
* [intrinsics::fabsf32](intrinsics/fn.fabsf32)
* [intrinsics::fabsf64](intrinsics/fn.fabsf64)
* [intrinsics::fadd\_fast](intrinsics/fn.fadd_fast)
* [intrinsics::fdiv\_fast](intrinsics/fn.fdiv_fast)
* [intrinsics::float\_to\_int\_unchecked](intrinsics/fn.float_to_int_unchecked)
* [intrinsics::floorf32](intrinsics/fn.floorf32)
* [intrinsics::floorf64](intrinsics/fn.floorf64)
* [intrinsics::fmaf32](intrinsics/fn.fmaf32)
* [intrinsics::fmaf64](intrinsics/fn.fmaf64)
* [intrinsics::fmul\_fast](intrinsics/fn.fmul_fast)
* [intrinsics::forget](intrinsics/fn.forget)
* [intrinsics::frem\_fast](intrinsics/fn.frem_fast)
* [intrinsics::fsub\_fast](intrinsics/fn.fsub_fast)
* [intrinsics::likely](intrinsics/fn.likely)
* [intrinsics::log10f32](intrinsics/fn.log10f32)
* [intrinsics::log10f64](intrinsics/fn.log10f64)
* [intrinsics::log2f32](intrinsics/fn.log2f32)
* [intrinsics::log2f64](intrinsics/fn.log2f64)
* [intrinsics::logf32](intrinsics/fn.logf32)
* [intrinsics::logf64](intrinsics/fn.logf64)
* [intrinsics::maxnumf32](intrinsics/fn.maxnumf32)
* [intrinsics::maxnumf64](intrinsics/fn.maxnumf64)
* [intrinsics::min\_align\_of](intrinsics/fn.min_align_of)
* [intrinsics::min\_align\_of\_val](intrinsics/fn.min_align_of_val)
* [intrinsics::minnumf32](intrinsics/fn.minnumf32)
* [intrinsics::minnumf64](intrinsics/fn.minnumf64)
* [intrinsics::mir::Call](intrinsics/mir/fn.call)
* [intrinsics::mir::CastTransmute](intrinsics/mir/fn.casttransmute)
* [intrinsics::mir::Checked](intrinsics/mir/fn.checked)
* [intrinsics::mir::CopyForDeref](intrinsics/mir/fn.copyforderef)
* [intrinsics::mir::Deinit](intrinsics/mir/fn.deinit)
* [intrinsics::mir::Discriminant](intrinsics/mir/fn.discriminant)
* [intrinsics::mir::Drop](intrinsics/mir/fn.drop)
* [intrinsics::mir::Field](intrinsics/mir/fn.field)
* [intrinsics::mir::Goto](intrinsics/mir/fn.goto)
* [intrinsics::mir::Len](intrinsics/mir/fn.len)
* [intrinsics::mir::Move](intrinsics/mir/fn.move)
* [intrinsics::mir::Offset](intrinsics/mir/fn.offset)
* [intrinsics::mir::Retag](intrinsics/mir/fn.retag)
* [intrinsics::mir::Return](intrinsics/mir/fn.return)
* [intrinsics::mir::SetDiscriminant](intrinsics/mir/fn.setdiscriminant)
* [intrinsics::mir::Static](intrinsics/mir/fn.static)
* [intrinsics::mir::StaticMut](intrinsics/mir/fn.staticmut)
* [intrinsics::mir::StorageDead](intrinsics/mir/fn.storagedead)
* [intrinsics::mir::StorageLive](intrinsics/mir/fn.storagelive)
* [intrinsics::mir::Unreachable](intrinsics/mir/fn.unreachable)
* [intrinsics::mir::Variant](intrinsics/mir/fn.variant)
* [intrinsics::mul\_with\_overflow](intrinsics/fn.mul_with_overflow)
* [intrinsics::nearbyintf32](intrinsics/fn.nearbyintf32)
* [intrinsics::nearbyintf64](intrinsics/fn.nearbyintf64)
* [intrinsics::needs\_drop](intrinsics/fn.needs_drop)
* [intrinsics::nontemporal\_store](intrinsics/fn.nontemporal_store)
* [intrinsics::offset](intrinsics/fn.offset)
* [intrinsics::option\_payload\_ptr](intrinsics/fn.option_payload_ptr)
* [intrinsics::powf32](intrinsics/fn.powf32)
* [intrinsics::powf64](intrinsics/fn.powf64)
* [intrinsics::powif32](intrinsics/fn.powif32)
* [intrinsics::powif64](intrinsics/fn.powif64)
* [intrinsics::pref\_align\_of](intrinsics/fn.pref_align_of)
* [intrinsics::prefetch\_read\_data](intrinsics/fn.prefetch_read_data)
* [intrinsics::prefetch\_read\_instruction](intrinsics/fn.prefetch_read_instruction)
* [intrinsics::prefetch\_write\_data](intrinsics/fn.prefetch_write_data)
* [intrinsics::prefetch\_write\_instruction](intrinsics/fn.prefetch_write_instruction)
* [intrinsics::ptr\_guaranteed\_cmp](intrinsics/fn.ptr_guaranteed_cmp)
* [intrinsics::ptr\_mask](intrinsics/fn.ptr_mask)
* [intrinsics::ptr\_offset\_from](intrinsics/fn.ptr_offset_from)
* [intrinsics::ptr\_offset\_from\_unsigned](intrinsics/fn.ptr_offset_from_unsigned)
* [intrinsics::raw\_eq](intrinsics/fn.raw_eq)
* [intrinsics::read\_via\_copy](intrinsics/fn.read_via_copy)
* [intrinsics::rintf32](intrinsics/fn.rintf32)
* [intrinsics::rintf64](intrinsics/fn.rintf64)
* [intrinsics::rotate\_left](intrinsics/fn.rotate_left)
* [intrinsics::rotate\_right](intrinsics/fn.rotate_right)
* [intrinsics::roundevenf32](intrinsics/fn.roundevenf32)
* [intrinsics::roundevenf64](intrinsics/fn.roundevenf64)
* [intrinsics::roundf32](intrinsics/fn.roundf32)
* [intrinsics::roundf64](intrinsics/fn.roundf64)
* [intrinsics::rustc\_peek](intrinsics/fn.rustc_peek)
* [intrinsics::saturating\_add](intrinsics/fn.saturating_add)
* [intrinsics::saturating\_sub](intrinsics/fn.saturating_sub)
* [intrinsics::sinf32](intrinsics/fn.sinf32)
* [intrinsics::sinf64](intrinsics/fn.sinf64)
* [intrinsics::size\_of](intrinsics/fn.size_of)
* [intrinsics::size\_of\_val](intrinsics/fn.size_of_val)
* [intrinsics::sqrtf32](intrinsics/fn.sqrtf32)
* [intrinsics::sqrtf64](intrinsics/fn.sqrtf64)
* [intrinsics::sub\_with\_overflow](intrinsics/fn.sub_with_overflow)
* [intrinsics::transmute](intrinsics/fn.transmute)
* [intrinsics::transmute\_unchecked](intrinsics/fn.transmute_unchecked)
* [intrinsics::truncf32](intrinsics/fn.truncf32)
* [intrinsics::truncf64](intrinsics/fn.truncf64)
* [intrinsics::try](intrinsics/fn.try)
* [intrinsics::type\_id](intrinsics/fn.type_id)
* [intrinsics::type\_name](intrinsics/fn.type_name)
* [intrinsics::unaligned\_volatile\_load](intrinsics/fn.unaligned_volatile_load)
* [intrinsics::unaligned\_volatile\_store](intrinsics/fn.unaligned_volatile_store)
* [intrinsics::unchecked\_add](intrinsics/fn.unchecked_add)
* [intrinsics::unchecked\_div](intrinsics/fn.unchecked_div)
* [intrinsics::unchecked\_mul](intrinsics/fn.unchecked_mul)
* [intrinsics::unchecked\_rem](intrinsics/fn.unchecked_rem)
* [intrinsics::unchecked\_shl](intrinsics/fn.unchecked_shl)
* [intrinsics::unchecked\_shr](intrinsics/fn.unchecked_shr)
* [intrinsics::unchecked\_sub](intrinsics/fn.unchecked_sub)
* [intrinsics::unlikely](intrinsics/fn.unlikely)
* [intrinsics::unreachable](intrinsics/fn.unreachable)
* [intrinsics::variant\_count](intrinsics/fn.variant_count)
* [intrinsics::volatile\_copy\_memory](intrinsics/fn.volatile_copy_memory)
* [intrinsics::volatile\_copy\_nonoverlapping\_memory](intrinsics/fn.volatile_copy_nonoverlapping_memory)
* [intrinsics::volatile\_load](intrinsics/fn.volatile_load)
* [intrinsics::volatile\_set\_memory](intrinsics/fn.volatile_set_memory)
* [intrinsics::volatile\_store](intrinsics/fn.volatile_store)
* [intrinsics::vtable\_align](intrinsics/fn.vtable_align)
* [intrinsics::vtable\_size](intrinsics/fn.vtable_size)
* [intrinsics::wrapping\_add](intrinsics/fn.wrapping_add)
* [intrinsics::wrapping\_mul](intrinsics/fn.wrapping_mul)
* [intrinsics::wrapping\_sub](intrinsics/fn.wrapping_sub)
* [intrinsics::write\_bytes](intrinsics/fn.write_bytes)
* [intrinsics::write\_via\_move](intrinsics/fn.write_via_move)
* [io::copy](io/fn.copy)
* [io::empty](io/fn.empty)
* [io::read\_to\_string](io/fn.read_to_string)
* [io::repeat](io/fn.repeat)
* [io::sink](io/fn.sink)
* [io::stderr](io/fn.stderr)
* [io::stdin](io/fn.stdin)
* [io::stdout](io/fn.stdout)
* [iter::empty](iter/fn.empty)
* [iter::from\_fn](iter/fn.from_fn)
* [iter::from\_generator](iter/fn.from_generator)
* [iter::once](iter/fn.once)
* [iter::once\_with](iter/fn.once_with)
* [iter::repeat](iter/fn.repeat)
* [iter::repeat\_with](iter/fn.repeat_with)
* [iter::successors](iter/fn.successors)
* [iter::zip](iter/fn.zip)
* [mem::align\_of](mem/fn.align_of)
* [mem::align\_of\_val](mem/fn.align_of_val)
* [mem::align\_of\_val\_raw](mem/fn.align_of_val_raw)
* [mem::copy](mem/fn.copy)
* [mem::discriminant](mem/fn.discriminant)
* [mem::drop](mem/fn.drop)
* [mem::forget](mem/fn.forget)
* [mem::forget\_unsized](mem/fn.forget_unsized)
* [mem::min\_align\_of](mem/fn.min_align_of)
* [mem::min\_align\_of\_val](mem/fn.min_align_of_val)
* [mem::needs\_drop](mem/fn.needs_drop)
* [mem::replace](mem/fn.replace)
* [mem::size\_of](mem/fn.size_of)
* [mem::size\_of\_val](mem/fn.size_of_val)
* [mem::size\_of\_val\_raw](mem/fn.size_of_val_raw)
* [mem::swap](mem/fn.swap)
* [mem::take](mem/fn.take)
* [mem::transmute](mem/fn.transmute)
* [mem::transmute\_copy](mem/fn.transmute_copy)
* [mem::uninitialized](mem/fn.uninitialized)
* [mem::variant\_count](mem/fn.variant_count)
* [mem::zeroed](mem/fn.zeroed)
* [os::unix::fs::chown](os/unix/fs/fn.chown)
* [os::unix::fs::chroot](os/unix/fs/fn.chroot)
* [os::unix::fs::fchown](os/unix/fs/fn.fchown)
* [os::unix::fs::lchown](os/unix/fs/fn.lchown)
* [os::unix::fs::symlink](os/unix/fs/fn.symlink)
* [os::unix::process::parent\_id](os/unix/process/fn.parent_id)
* [os::unix::ucred::impl\_linux::peer\_cred](os/unix/ucred/impl_linux/fn.peer_cred)
* [os::wasi::fs::link](os/wasi/fs/fn.link)
* [os::wasi::fs::rename](os/wasi/fs/fn.rename)
* [os::wasi::fs::symlink](os/wasi/fs/fn.symlink)
* [os::wasi::fs::symlink\_path](os/wasi/fs/fn.symlink_path)
* [os::windows::fs::symlink\_dir](os/windows/fs/fn.symlink_dir)
* [os::windows::fs::symlink\_file](os/windows/fs/fn.symlink_file)
* [panic::always\_abort](panic/fn.always_abort)
* [panic::catch\_unwind](panic/fn.catch_unwind)
* [panic::get\_backtrace\_style](panic/fn.get_backtrace_style)
* [panic::panic\_any](panic/fn.panic_any)
* [panic::resume\_unwind](panic/fn.resume_unwind)
* [panic::set\_backtrace\_style](panic/fn.set_backtrace_style)
* [panic::set\_hook](panic/fn.set_hook)
* [panic::take\_hook](panic/fn.take_hook)
* [panic::update\_hook](panic/fn.update_hook)
* [path::absolute](path/fn.absolute)
* [path::is\_separator](path/fn.is_separator)
* [process::abort](process/fn.abort)
* [process::exit](process/fn.exit)
* [process::id](process/fn.id)
* [ptr::copy](ptr/fn.copy)
* [ptr::copy\_nonoverlapping](ptr/fn.copy_nonoverlapping)
* [ptr::drop\_in\_place](ptr/fn.drop_in_place)
* [ptr::eq](ptr/fn.eq)
* [ptr::from\_exposed\_addr](ptr/fn.from_exposed_addr)
* [ptr::from\_exposed\_addr\_mut](ptr/fn.from_exposed_addr_mut)
* [ptr::from\_mut](ptr/fn.from_mut)
* [ptr::from\_raw\_parts](ptr/fn.from_raw_parts)
* [ptr::from\_raw\_parts\_mut](ptr/fn.from_raw_parts_mut)
* [ptr::from\_ref](ptr/fn.from_ref)
* [ptr::hash](ptr/fn.hash)
* [ptr::invalid](ptr/fn.invalid)
* [ptr::invalid\_mut](ptr/fn.invalid_mut)
* [ptr::metadata](ptr/fn.metadata)
* [ptr::null](ptr/fn.null)
* [ptr::null\_mut](ptr/fn.null_mut)
* [ptr::read](ptr/fn.read)
* [ptr::read\_unaligned](ptr/fn.read_unaligned)
* [ptr::read\_volatile](ptr/fn.read_volatile)
* [ptr::replace](ptr/fn.replace)
* [ptr::slice\_from\_raw\_parts](ptr/fn.slice_from_raw_parts)
* [ptr::slice\_from\_raw\_parts\_mut](ptr/fn.slice_from_raw_parts_mut)
* [ptr::swap](ptr/fn.swap)
* [ptr::swap\_nonoverlapping](ptr/fn.swap_nonoverlapping)
* [ptr::write](ptr/fn.write)
* [ptr::write\_bytes](ptr/fn.write_bytes)
* [ptr::write\_unaligned](ptr/fn.write_unaligned)
* [ptr::write\_volatile](ptr/fn.write_volatile)
* [slice::from\_mut](slice/fn.from_mut)
* [slice::from\_mut\_ptr\_range](slice/fn.from_mut_ptr_range)
* [slice::from\_ptr\_range](slice/fn.from_ptr_range)
* [slice::from\_raw\_parts](slice/fn.from_raw_parts)
* [slice::from\_raw\_parts\_mut](slice/fn.from_raw_parts_mut)
* [slice::from\_ref](slice/fn.from_ref)
* [slice::range](slice/fn.range)
* [str::from\_boxed\_utf8\_unchecked](str/fn.from_boxed_utf8_unchecked)
* [str::from\_utf8](str/fn.from_utf8)
* [str::from\_utf8\_mut](str/fn.from_utf8_mut)
* [str::from\_utf8\_unchecked](str/fn.from_utf8_unchecked)
* [str::from\_utf8\_unchecked\_mut](str/fn.from_utf8_unchecked_mut)
* [sync::atomic::compiler\_fence](sync/atomic/fn.compiler_fence)
* [sync::atomic::fence](sync/atomic/fn.fence)
* [sync::atomic::spin\_loop\_hint](sync/atomic/fn.spin_loop_hint)
* [sync::mpsc::channel](sync/mpsc/fn.channel)
* [sync::mpsc::sync\_channel](sync/mpsc/fn.sync_channel)
* [thread::available\_parallelism](thread/fn.available_parallelism)
* [thread::current](thread/fn.current)
* [thread::panicking](thread/fn.panicking)
* [thread::park](thread/fn.park)
* [thread::park\_timeout](thread/fn.park_timeout)
* [thread::park\_timeout\_ms](thread/fn.park_timeout_ms)
* [thread::scope](thread/fn.scope)
* [thread::sleep](thread/fn.sleep)
* [thread::sleep\_ms](thread/fn.sleep_ms)
* [thread::spawn](thread/fn.spawn)
* [thread::yield\_now](thread/fn.yield_now)


### Type Definitions


* [alloc::LayoutErr](alloc/type.layouterr)
* [ffi::c\_char](ffi/type.c_char)
* [ffi::c\_double](ffi/type.c_double)
* [ffi::c\_float](ffi/type.c_float)
* [ffi::c\_int](ffi/type.c_int)
* [ffi::c\_long](ffi/type.c_long)
* [ffi::c\_longlong](ffi/type.c_longlong)
* [ffi::c\_schar](ffi/type.c_schar)
* [ffi::c\_short](ffi/type.c_short)
* [ffi::c\_uchar](ffi/type.c_uchar)
* [ffi::c\_uint](ffi/type.c_uint)
* [ffi::c\_ulong](ffi/type.c_ulong)
* [ffi::c\_ulonglong](ffi/type.c_ulonglong)
* [ffi::c\_ushort](ffi/type.c_ushort)
* [fmt::Result](fmt/type.result)
* [io::RawOsError](io/type.rawoserror)
* [io::Result](io/type.result)
* [os::fd::RawFd](os/fd/type.rawfd)
* [os::linux::raw::blkcnt\_t](os/linux/raw/type.blkcnt_t)
* [os::linux::raw::blksize\_t](os/linux/raw/type.blksize_t)
* [os::linux::raw::dev\_t](os/linux/raw/type.dev_t)
* [os::linux::raw::ino\_t](os/linux/raw/type.ino_t)
* [os::linux::raw::mode\_t](os/linux/raw/type.mode_t)
* [os::linux::raw::nlink\_t](os/linux/raw/type.nlink_t)
* [os::linux::raw::off\_t](os/linux/raw/type.off_t)
* [os::linux::raw::pthread\_t](os/linux/raw/type.pthread_t)
* [os::linux::raw::time\_t](os/linux/raw/type.time_t)
* [os::raw::c\_char](os/raw/type.c_char)
* [os::raw::c\_double](os/raw/type.c_double)
* [os::raw::c\_float](os/raw/type.c_float)
* [os::raw::c\_int](os/raw/type.c_int)
* [os::raw::c\_long](os/raw/type.c_long)
* [os::raw::c\_longlong](os/raw/type.c_longlong)
* [os::raw::c\_schar](os/raw/type.c_schar)
* [os::raw::c\_short](os/raw/type.c_short)
* [os::raw::c\_uchar](os/raw/type.c_uchar)
* [os::raw::c\_uint](os/raw/type.c_uint)
* [os::raw::c\_ulong](os/raw/type.c_ulong)
* [os::raw::c\_ulonglong](os/raw/type.c_ulonglong)
* [os::raw::c\_ushort](os/raw/type.c_ushort)
* [os::raw::c\_void](os/raw/type.c_void)
* [os::unix::raw::blkcnt\_t](os/unix/raw/type.blkcnt_t)
* [os::unix::raw::blksize\_t](os/unix/raw/type.blksize_t)
* [os::unix::raw::dev\_t](os/unix/raw/type.dev_t)
* [os::unix::raw::gid\_t](os/unix/raw/type.gid_t)
* [os::unix::raw::ino\_t](os/unix/raw/type.ino_t)
* [os::unix::raw::mode\_t](os/unix/raw/type.mode_t)
* [os::unix::raw::nlink\_t](os/unix/raw/type.nlink_t)
* [os::unix::raw::off\_t](os/unix/raw/type.off_t)
* [os::unix::raw::pid\_t](os/unix/raw/type.pid_t)
* [os::unix::raw::pthread\_t](os/unix/raw/type.pthread_t)
* [os::unix::raw::time\_t](os/unix/raw/type.time_t)
* [os::unix::raw::uid\_t](os/unix/raw/type.uid_t)
* [os::unix::thread::RawPthread](os/unix/thread/type.rawpthread)
* [os::windows::io::RawHandle](os/windows/io/type.rawhandle)
* [os::windows::io::RawSocket](os/windows/io/type.rawsocket)
* [os::windows::raw::HANDLE](os/windows/raw/type.handle)
* [os::windows::raw::SOCKET](os/windows/raw/type.socket)
* [simd::f32x1](simd/type.f32x1)
* [simd::f32x16](simd/type.f32x16)
* [simd::f32x2](simd/type.f32x2)
* [simd::f32x32](simd/type.f32x32)
* [simd::f32x4](simd/type.f32x4)
* [simd::f32x64](simd/type.f32x64)
* [simd::f32x8](simd/type.f32x8)
* [simd::f64x1](simd/type.f64x1)
* [simd::f64x16](simd/type.f64x16)
* [simd::f64x2](simd/type.f64x2)
* [simd::f64x32](simd/type.f64x32)
* [simd::f64x4](simd/type.f64x4)
* [simd::f64x64](simd/type.f64x64)
* [simd::f64x8](simd/type.f64x8)
* [simd::i16x1](simd/type.i16x1)
* [simd::i16x16](simd/type.i16x16)
* [simd::i16x2](simd/type.i16x2)
* [simd::i16x32](simd/type.i16x32)
* [simd::i16x4](simd/type.i16x4)
* [simd::i16x64](simd/type.i16x64)
* [simd::i16x8](simd/type.i16x8)
* [simd::i32x1](simd/type.i32x1)
* [simd::i32x16](simd/type.i32x16)
* [simd::i32x2](simd/type.i32x2)
* [simd::i32x32](simd/type.i32x32)
* [simd::i32x4](simd/type.i32x4)
* [simd::i32x64](simd/type.i32x64)
* [simd::i32x8](simd/type.i32x8)
* [simd::i64x1](simd/type.i64x1)
* [simd::i64x16](simd/type.i64x16)
* [simd::i64x2](simd/type.i64x2)
* [simd::i64x32](simd/type.i64x32)
* [simd::i64x4](simd/type.i64x4)
* [simd::i64x64](simd/type.i64x64)
* [simd::i64x8](simd/type.i64x8)
* [simd::i8x1](simd/type.i8x1)
* [simd::i8x16](simd/type.i8x16)
* [simd::i8x2](simd/type.i8x2)
* [simd::i8x32](simd/type.i8x32)
* [simd::i8x4](simd/type.i8x4)
* [simd::i8x64](simd/type.i8x64)
* [simd::i8x8](simd/type.i8x8)
* [simd::isizex1](simd/type.isizex1)
* [simd::isizex16](simd/type.isizex16)
* [simd::isizex2](simd/type.isizex2)
* [simd::isizex32](simd/type.isizex32)
* [simd::isizex4](simd/type.isizex4)
* [simd::isizex64](simd/type.isizex64)
* [simd::isizex8](simd/type.isizex8)
* [simd::mask16x1](simd/type.mask16x1)
* [simd::mask16x16](simd/type.mask16x16)
* [simd::mask16x2](simd/type.mask16x2)
* [simd::mask16x32](simd/type.mask16x32)
* [simd::mask16x4](simd/type.mask16x4)
* [simd::mask16x64](simd/type.mask16x64)
* [simd::mask16x8](simd/type.mask16x8)
* [simd::mask32x1](simd/type.mask32x1)
* [simd::mask32x16](simd/type.mask32x16)
* [simd::mask32x2](simd/type.mask32x2)
* [simd::mask32x32](simd/type.mask32x32)
* [simd::mask32x4](simd/type.mask32x4)
* [simd::mask32x64](simd/type.mask32x64)
* [simd::mask32x8](simd/type.mask32x8)
* [simd::mask64x1](simd/type.mask64x1)
* [simd::mask64x16](simd/type.mask64x16)
* [simd::mask64x2](simd/type.mask64x2)
* [simd::mask64x32](simd/type.mask64x32)
* [simd::mask64x4](simd/type.mask64x4)
* [simd::mask64x64](simd/type.mask64x64)
* [simd::mask64x8](simd/type.mask64x8)
* [simd::mask8x1](simd/type.mask8x1)
* [simd::mask8x16](simd/type.mask8x16)
* [simd::mask8x2](simd/type.mask8x2)
* [simd::mask8x32](simd/type.mask8x32)
* [simd::mask8x4](simd/type.mask8x4)
* [simd::mask8x64](simd/type.mask8x64)
* [simd::mask8x8](simd/type.mask8x8)
* [simd::masksizex1](simd/type.masksizex1)
* [simd::masksizex16](simd/type.masksizex16)
* [simd::masksizex2](simd/type.masksizex2)
* [simd::masksizex32](simd/type.masksizex32)
* [simd::masksizex4](simd/type.masksizex4)
* [simd::masksizex64](simd/type.masksizex64)
* [simd::masksizex8](simd/type.masksizex8)
* [simd::u16x1](simd/type.u16x1)
* [simd::u16x16](simd/type.u16x16)
* [simd::u16x2](simd/type.u16x2)
* [simd::u16x32](simd/type.u16x32)
* [simd::u16x4](simd/type.u16x4)
* [simd::u16x64](simd/type.u16x64)
* [simd::u16x8](simd/type.u16x8)
* [simd::u32x1](simd/type.u32x1)
* [simd::u32x16](simd/type.u32x16)
* [simd::u32x2](simd/type.u32x2)
* [simd::u32x32](simd/type.u32x32)
* [simd::u32x4](simd/type.u32x4)
* [simd::u32x64](simd/type.u32x64)
* [simd::u32x8](simd/type.u32x8)
* [simd::u64x1](simd/type.u64x1)
* [simd::u64x16](simd/type.u64x16)
* [simd::u64x2](simd/type.u64x2)
* [simd::u64x32](simd/type.u64x32)
* [simd::u64x4](simd/type.u64x4)
* [simd::u64x64](simd/type.u64x64)
* [simd::u64x8](simd/type.u64x8)
* [simd::u8x1](simd/type.u8x1)
* [simd::u8x16](simd/type.u8x16)
* [simd::u8x2](simd/type.u8x2)
* [simd::u8x32](simd/type.u8x32)
* [simd::u8x4](simd/type.u8x4)
* [simd::u8x64](simd/type.u8x64)
* [simd::u8x8](simd/type.u8x8)
* [simd::usizex1](simd/type.usizex1)
* [simd::usizex16](simd/type.usizex16)
* [simd::usizex2](simd/type.usizex2)
* [simd::usizex32](simd/type.usizex32)
* [simd::usizex4](simd/type.usizex4)
* [simd::usizex64](simd/type.usizex64)
* [simd::usizex8](simd/type.usizex8)
* [string::ParseError](string/type.parseerror)
* [sync::LockResult](sync/type.lockresult)
* [sync::TryLockResult](sync/type.trylockresult)
* [thread::Result](thread/type.result)


### Constants


* [char::MAX](char/constant.max)
* [char::REPLACEMENT\_CHARACTER](char/constant.replacement_character)
* [char::UNICODE\_VERSION](char/constant.unicode_version)
* [env::consts::ARCH](env/consts/constant.arch)
* [env::consts::DLL\_EXTENSION](env/consts/constant.dll_extension)
* [env::consts::DLL\_PREFIX](env/consts/constant.dll_prefix)
* [env::consts::DLL\_SUFFIX](env/consts/constant.dll_suffix)
* [env::consts::EXE\_EXTENSION](env/consts/constant.exe_extension)
* [env::consts::EXE\_SUFFIX](env/consts/constant.exe_suffix)
* [env::consts::FAMILY](env/consts/constant.family)
* [env::consts::OS](env/consts/constant.os)
* [f32::DIGITS](f32/constant.digits)
* [f32::EPSILON](f32/constant.epsilon)
* [f32::INFINITY](f32/constant.infinity)
* [f32::MANTISSA\_DIGITS](f32/constant.mantissa_digits)
* [f32::MAX](f32/constant.max)
* [f32::MAX\_10\_EXP](f32/constant.max_10_exp)
* [f32::MAX\_EXP](f32/constant.max_exp)
* [f32::MIN](f32/constant.min)
* [f32::MIN\_10\_EXP](f32/constant.min_10_exp)
* [f32::MIN\_EXP](f32/constant.min_exp)
* [f32::MIN\_POSITIVE](f32/constant.min_positive)
* [f32::NAN](f32/constant.nan)
* [f32::NEG\_INFINITY](f32/constant.neg_infinity)
* [f32::RADIX](f32/constant.radix)
* [f32::consts::E](f32/consts/constant.e)
* [f32::consts::FRAC\_1\_PI](f32/consts/constant.frac_1_pi)
* [f32::consts::FRAC\_1\_SQRT\_2](f32/consts/constant.frac_1_sqrt_2)
* [f32::consts::FRAC\_2\_PI](f32/consts/constant.frac_2_pi)
* [f32::consts::FRAC\_2\_SQRT\_PI](f32/consts/constant.frac_2_sqrt_pi)
* [f32::consts::FRAC\_PI\_2](f32/consts/constant.frac_pi_2)
* [f32::consts::FRAC\_PI\_3](f32/consts/constant.frac_pi_3)
* [f32::consts::FRAC\_PI\_4](f32/consts/constant.frac_pi_4)
* [f32::consts::FRAC\_PI\_6](f32/consts/constant.frac_pi_6)
* [f32::consts::FRAC\_PI\_8](f32/consts/constant.frac_pi_8)
* [f32::consts::LN\_10](f32/consts/constant.ln_10)
* [f32::consts::LN\_2](f32/consts/constant.ln_2)
* [f32::consts::LOG10\_2](f32/consts/constant.log10_2)
* [f32::consts::LOG10\_E](f32/consts/constant.log10_e)
* [f32::consts::LOG2\_10](f32/consts/constant.log2_10)
* [f32::consts::LOG2\_E](f32/consts/constant.log2_e)
* [f32::consts::PI](f32/consts/constant.pi)
* [f32::consts::SQRT\_2](f32/consts/constant.sqrt_2)
* [f32::consts::TAU](f32/consts/constant.tau)
* [f64::DIGITS](f64/constant.digits)
* [f64::EPSILON](f64/constant.epsilon)
* [f64::INFINITY](f64/constant.infinity)
* [f64::MANTISSA\_DIGITS](f64/constant.mantissa_digits)
* [f64::MAX](f64/constant.max)
* [f64::MAX\_10\_EXP](f64/constant.max_10_exp)
* [f64::MAX\_EXP](f64/constant.max_exp)
* [f64::MIN](f64/constant.min)
* [f64::MIN\_10\_EXP](f64/constant.min_10_exp)
* [f64::MIN\_EXP](f64/constant.min_exp)
* [f64::MIN\_POSITIVE](f64/constant.min_positive)
* [f64::NAN](f64/constant.nan)
* [f64::NEG\_INFINITY](f64/constant.neg_infinity)
* [f64::RADIX](f64/constant.radix)
* [f64::consts::E](f64/consts/constant.e)
* [f64::consts::FRAC\_1\_PI](f64/consts/constant.frac_1_pi)
* [f64::consts::FRAC\_1\_SQRT\_2](f64/consts/constant.frac_1_sqrt_2)
* [f64::consts::FRAC\_2\_PI](f64/consts/constant.frac_2_pi)
* [f64::consts::FRAC\_2\_SQRT\_PI](f64/consts/constant.frac_2_sqrt_pi)
* [f64::consts::FRAC\_PI\_2](f64/consts/constant.frac_pi_2)
* [f64::consts::FRAC\_PI\_3](f64/consts/constant.frac_pi_3)
* [f64::consts::FRAC\_PI\_4](f64/consts/constant.frac_pi_4)
* [f64::consts::FRAC\_PI\_6](f64/consts/constant.frac_pi_6)
* [f64::consts::FRAC\_PI\_8](f64/consts/constant.frac_pi_8)
* [f64::consts::LN\_10](f64/consts/constant.ln_10)
* [f64::consts::LN\_2](f64/consts/constant.ln_2)
* [f64::consts::LOG10\_2](f64/consts/constant.log10_2)
* [f64::consts::LOG10\_E](f64/consts/constant.log10_e)
* [f64::consts::LOG2\_10](f64/consts/constant.log2_10)
* [f64::consts::LOG2\_E](f64/consts/constant.log2_e)
* [f64::consts::PI](f64/consts/constant.pi)
* [f64::consts::SQRT\_2](f64/consts/constant.sqrt_2)
* [f64::consts::TAU](f64/consts/constant.tau)
* [i128::MAX](i128/constant.max)
* [i128::MIN](i128/constant.min)
* [i16::MAX](i16/constant.max)
* [i16::MIN](i16/constant.min)
* [i32::MAX](i32/constant.max)
* [i32::MIN](i32/constant.min)
* [i64::MAX](i64/constant.max)
* [i64::MIN](i64/constant.min)
* [i8::MAX](i8/constant.max)
* [i8::MIN](i8/constant.min)
* [isize::MAX](isize/constant.max)
* [isize::MIN](isize/constant.min)
* [path::MAIN\_SEPARATOR](path/constant.main_separator)
* [path::MAIN\_SEPARATOR\_STR](path/constant.main_separator_str)
* [sync::ONCE\_INIT](sync/constant.once_init)
* [sync::atomic::ATOMIC\_BOOL\_INIT](sync/atomic/constant.atomic_bool_init)
* [sync::atomic::ATOMIC\_I16\_INIT](sync/atomic/constant.atomic_i16_init)
* [sync::atomic::ATOMIC\_I32\_INIT](sync/atomic/constant.atomic_i32_init)
* [sync::atomic::ATOMIC\_I64\_INIT](sync/atomic/constant.atomic_i64_init)
* [sync::atomic::ATOMIC\_I8\_INIT](sync/atomic/constant.atomic_i8_init)
* [sync::atomic::ATOMIC\_ISIZE\_INIT](sync/atomic/constant.atomic_isize_init)
* [sync::atomic::ATOMIC\_U16\_INIT](sync/atomic/constant.atomic_u16_init)
* [sync::atomic::ATOMIC\_U32\_INIT](sync/atomic/constant.atomic_u32_init)
* [sync::atomic::ATOMIC\_U64\_INIT](sync/atomic/constant.atomic_u64_init)
* [sync::atomic::ATOMIC\_U8\_INIT](sync/atomic/constant.atomic_u8_init)
* [sync::atomic::ATOMIC\_USIZE\_INIT](sync/atomic/constant.atomic_usize_init)
* [time::UNIX\_EPOCH](time/constant.unix_epoch)
* [u128::MAX](u128/constant.max)
* [u128::MIN](u128/constant.min)
* [u16::MAX](u16/constant.max)
* [u16::MIN](u16/constant.min)
* [u32::MAX](u32/constant.max)
* [u32::MIN](u32/constant.min)
* [u64::MAX](u64/constant.max)
* [u64::MIN](u64/constant.min)
* [u8::MAX](u8/constant.max)
* [u8::MIN](u8/constant.min)
* [usize::MAX](usize/constant.max)
* [usize::MIN](usize/constant.min)



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/all.html>

Module std::io
==============


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

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

 Read and Write
--------------

 Because they are traits, [`Read`](trait.read "trait std::io::Read") and [`Write`](trait.write "trait std::io::Write") are implemented by a number of other types, and you can implement them for your types too. As such, you’ll see a few different types of I/O throughout the documentation in this module: [`File`](../fs/struct.file "struct std::fs::File")s, [`TcpStream`](../net/struct.tcpstream "struct std::net::TcpStream")s, and sometimes even [`Vec<T>`](../vec/struct.vec "struct std::vec::Vec")s. For example, [`Read`](trait.read "trait std::io::Read") adds a [`read`](trait.read#tymethod.read "method std::io::Read::read") method, which we can use on [`File`](../fs/struct.file "struct std::fs::File")s:

 
```
use std::io;
use std::io::prelude::*;
use std::fs::File;

fn main() -> io::Result<()> {
    let mut f = File::open("foo.txt")?;
    let mut buffer = [0; 10];

    // read up to 10 bytes
    let n = f.read(&mut buffer)?;

    println!("The bytes: {:?}", &buffer[..n]);
    Ok(())
}
```
 [`Read`](trait.read "trait std::io::Read") and [`Write`](trait.write "trait std::io::Write") are so important, implementors of the two traits have a nickname: readers and writers. So you’ll sometimes see ‘a reader’ instead of ‘a type that implements the [`Read`](trait.read "trait std::io::Read") trait’. Much easier!

 ### Seek and BufRead

 Beyond that, there are two important traits that are provided: [`Seek`](trait.seek "trait std::io::Seek") and [`BufRead`](trait.bufread "trait std::io::BufRead"). Both of these build on top of a reader to control how the reading happens. [`Seek`](trait.seek "trait std::io::Seek") lets you control where the next byte is coming from:

 
```
use std::io;
use std::io::prelude::*;
use std::io::SeekFrom;
use std::fs::File;

fn main() -> io::Result<()> {
    let mut f = File::open("foo.txt")?;
    let mut buffer = [0; 10];

    // skip to the last 10 bytes of the file
    f.seek(SeekFrom::End(-10))?;

    // read up to 10 bytes
    let n = f.read(&mut buffer)?;

    println!("The bytes: {:?}", &buffer[..n]);
    Ok(())
}
```
 [`BufRead`](trait.bufread "trait std::io::BufRead") uses an internal buffer to provide a number of other ways to read, but to show it off, we’ll need to talk about buffers in general. Keep reading!

 ### BufReader and BufWriter

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

 For example, [`BufReader`](struct.bufreader "struct std::io::BufReader") works with the [`BufRead`](trait.bufread "trait std::io::BufRead") trait to add extra methods to any reader:

 
```
use std::io;
use std::io::prelude::*;
use std::io::BufReader;
use std::fs::File;

fn main() -> io::Result<()> {
    let f = File::open("foo.txt")?;
    let mut reader = BufReader::new(f);
    let mut buffer = String::new();

    // read a line into buffer
    reader.read_line(&mut buffer)?;

    println!("{buffer}");
    Ok(())
}
```
 [`BufWriter`](struct.bufwriter "struct std::io::BufWriter") doesn’t add any new ways of writing; it just buffers every call to [`write`](trait.write#tymethod.write "method std::io::Write::write"):

 
```
use std::io;
use std::io::prelude::*;
use std::io::BufWriter;
use std::fs::File;

fn main() -> io::Result<()> {
    let f = File::create("foo.txt")?;
    {
        let mut writer = BufWriter::new(f);

        // write a byte to the buffer
        writer.write(&[42])?;

    } // the buffer is flushed once writer goes out of scope

    Ok(())
}
```
 ### Standard input and output

 A very common source of input is standard input:

 
```
use std::io;

fn main() -> io::Result<()> {
    let mut input = String::new();

    io::stdin().read_line(&mut input)?;

    println!("You typed: {}", input.trim());
    Ok(())
}
```
 Note that you cannot use the [`?` operator](../../book/appendix-02-operators) in functions that do not return a [`Result<T, E>`](../result/enum.result "enum std::result::Result"). Instead, you can call [`.unwrap()`](../result/enum.result#method.unwrap "method std::result::Result::unwrap") or `match` on the return value to catch any possible errors:

 
```
use std::io;

let mut input = String::new();

io::stdin().read_line(&mut input).unwrap();
```
 And a very common source of output is standard output:

 
```
use std::io;
use std::io::prelude::*;

fn main() -> io::Result<()> {
    io::stdout().write(&[42])?;
    Ok(())
}
```
 Of course, using [`io::stdout`](fn.stdout "fn std::io::stdout") directly is less common than something like [`println!`](../macro.println "macro std::println").

 ### Iterator types

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

 
```
use std::io;
use std::io::prelude::*;
use std::io::BufReader;
use std::fs::File;

fn main() -> io::Result<()> {
    let f = File::open("foo.txt")?;
    let reader = BufReader::new(f);

    for line in reader.lines() {
        println!("{}", line?);
    }
    Ok(())
}
```
 ### Functions

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

 
```
use std::io;

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

 Last, but certainly not least, is [`io::Result`](type.result "type std::io::Result"). This type is used as the return type of many `std::io` functions that can cause an error, and can be returned from your own functions as well. Many of the examples in this module use the [`?` operator](../../book/appendix-02-operators):

 
```
use std::io;

fn read_input() -> io::Result<()> {
    let mut input = String::new();

    io::stdin().read_line(&mut input)?;

    println!("You typed: {}", input.trim());

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

 ### Platform-specific behavior

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

 Modules
-------


* [prelude](prelude/index "mod std::io::prelude")
The I/O Prelude.


Structs
-------


* [BorrowedBuf](struct.borrowedbuf "struct std::io::BorrowedBuf")Experimental

A borrowed byte buffer which is incrementally filled and initialized.
* [BorrowedCursor](struct.borrowedcursor "struct std::io::BorrowedCursor")Experimental

A writeable view of the unfilled portion of a [`BorrowedBuf`](struct.borrowedbuf "struct std::io::BorrowedBuf").
* [BufReader](struct.bufreader "struct std::io::BufReader")
The `BufReader<R>` struct adds buffering to any reader.
* [BufWriter](struct.bufwriter "struct std::io::BufWriter")
Wraps a writer and buffers its output.
* [Bytes](struct.bytes "struct std::io::Bytes")
An iterator over `u8` values of a reader.
* [Chain](struct.chain "struct std::io::Chain")
Adapter to chain together two readers.
* [Cursor](struct.cursor "struct std::io::Cursor")
A `Cursor` wraps an in-memory buffer and provides it with a [`Seek`](trait.seek "trait std::io::Seek") implementation.
* [Empty](struct.empty "struct std::io::Empty")
A reader which is always at EOF.
* [Error](struct.error "struct std::io::Error")
The error type for I/O operations of the [`Read`](trait.read "trait std::io::Read"), [`Write`](trait.write "trait std::io::Write"), [`Seek`](trait.seek "trait std::io::Seek"), and associated traits.
* [IntoInnerError](struct.intoinnererror "struct std::io::IntoInnerError")
An error returned by [`BufWriter::into_inner`](struct.bufwriter#method.into_inner "method std::io::BufWriter::into_inner") which combines an error that happened while writing out the buffer, and the buffered writer object which may be used to recover from the condition.
* [IoSlice](struct.ioslice "struct std::io::IoSlice")
A buffer type used with `Write::write_vectored`.
* [IoSliceMut](struct.ioslicemut "struct std::io::IoSliceMut")
A buffer type used with `Read::read_vectored`.
* [LineWriter](struct.linewriter "struct std::io::LineWriter")
Wraps a writer and buffers output to it, flushing whenever a newline (`0x0a`, `'\n'`) is detected.
* [Lines](struct.lines "struct std::io::Lines")
An iterator over the lines of an instance of `BufRead`.
* [Repeat](struct.repeat "struct std::io::Repeat")
A reader which yields one byte over and over and over and over and over and…
* [Sink](struct.sink "struct std::io::Sink")
A writer which will move data into the void.
* [Split](struct.split "struct std::io::Split")
An iterator over the contents of an instance of `BufRead` split on a particular byte.
* [Stderr](struct.stderr "struct std::io::Stderr")
A handle to the standard error stream of a process.
* [StderrLock](struct.stderrlock "struct std::io::StderrLock")
A locked reference to the [`Stderr`](struct.stderr "struct std::io::Stderr") handle.
* [Stdin](struct.stdin "struct std::io::Stdin")
A handle to the standard input stream of a process.
* [StdinLock](struct.stdinlock "struct std::io::StdinLock")
A locked reference to the [`Stdin`](struct.stdin "struct std::io::Stdin") handle.
* [Stdout](struct.stdout "struct std::io::Stdout")
A handle to the global standard output stream of the current process.
* [StdoutLock](struct.stdoutlock "struct std::io::StdoutLock")
A locked reference to the [`Stdout`](struct.stdout "struct std::io::Stdout") handle.
* [Take](struct.take "struct std::io::Take")
Reader adapter which limits the bytes read from an underlying reader.
* [WriterPanicked](struct.writerpanicked "struct std::io::WriterPanicked")
Error returned for the buffered data from `BufWriter::into_parts`, when the underlying writer has previously panicked. Contains the (possibly partly written) buffered data.


Enums
-----


* [ErrorKind](enum.errorkind "enum std::io::ErrorKind")
A list specifying general categories of I/O error.
* [SeekFrom](enum.seekfrom "enum std::io::SeekFrom")
Enumeration of possible methods to seek within an I/O object.


Traits
------


* [BufRead](trait.bufread "trait std::io::BufRead")
A `BufRead` is a type of `Read`er which has an internal buffer, allowing it to perform extra ways of reading.
* [IsTerminal](trait.isterminal "trait std::io::IsTerminal")
Trait to determine if a descriptor/handle refers to a terminal/tty.
* [Read](trait.read "trait std::io::Read")
The `Read` trait allows for reading bytes from a source.
* [Seek](trait.seek "trait std::io::Seek")
The `Seek` trait provides a cursor which can be moved within a stream of bytes.
* [Write](trait.write "trait std::io::Write")
A trait for objects which are byte-oriented sinks.


Functions
---------


* [copy](fn.copy "fn std::io::copy")
Copies the entire contents of a reader into a writer.
* [empty](fn.empty "fn std::io::empty")
Constructs a new handle to an empty reader.
* [read\_to\_string](fn.read_to_string "fn std::io::read_to_string")
Read all bytes from a [reader](trait.read "trait std::io::Read") into a new [`String`](../string/struct.string "struct std::string::String").
* [repeat](fn.repeat "fn std::io::repeat")
Creates an instance of a reader that infinitely repeats one byte.
* [sink](fn.sink "fn std::io::sink")
Creates an instance of a writer which will successfully consume all data.
* [stderr](fn.stderr "fn std::io::stderr")
Constructs a new handle to the standard error of the current process.
* [stdin](fn.stdin "fn std::io::stdin")
Constructs a new handle to the standard input of the current process.
* [stdout](fn.stdout "fn std::io::stdout")
Constructs a new handle to the standard output of the current process.


Type Definitions
----------------


* [RawOsError](type.rawoserror "type std::io::RawOsError")Experimental

The type of raw OS error codes returned by [`Error::raw_os_error`](struct.error#method.raw_os_error "method std::io::Error::raw_os_error").
* [Result](type.result "type std::io::Result")
A specialized [`Result`](../result/enum.result "enum std::result::Result") type for I/O operations.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/io/index.html>

Module std::thread
==================


Native threads.

 ### 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](../sync/mpsc/index "mod std::sync::mpsc"), Rust’s message-passing types, along with [other forms of thread synchronization](../sync/index) 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`](../sync/struct.arc "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`](../panic/fn.catch_unwind) and recovered from, or alternatively be resumed with [`resume_unwind`](../panic/fn.resume_unwind). If the panic is not caught the thread will exit, but the panic may optionally be detected from a different thread with [`join`](struct.joinhandle#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).

 ### Spawning a thread

 A new thread can be spawned using the [`thread::spawn`](fn.spawn "fn std::thread::spawn") function:

 
```
use std::thread;

thread::spawn(move || {
    // some work here
});
```
 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`](struct.joinhandle "struct std::thread::JoinHandle") object that is returned by the call to [`spawn`](fn.spawn "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();
```
 The [`join`](struct.joinhandle#method.join "method std::thread::JoinHandle::join") method returns a [`thread::Result`](type.result "type std::thread::Result") containing [`Ok`](../result/enum.result#variant.Ok "variant std::result::Result::Ok") of the final value produced by the spawned thread, or [`Err`](../result/enum.result#variant.Err "variant std::result::Result::Err") of the value given to a call to [`panic!`](../macro.panic "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.

 ### Configuring threads

 A new thread can be configured before it is spawned via the [`Builder`](struct.builder "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!");
});
```
 ### The `Thread` type

 Threads are represented via the [`Thread`](struct.thread "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`](fn.spawn "fn std::thread::spawn") function, and calling [`thread`](struct.joinhandle#method.thread "method std::thread::JoinHandle::thread") on the [`JoinHandle`](struct.joinhandle "struct std::thread::JoinHandle").
* By requesting the current thread, using the [`thread::current`](fn.current "fn std::thread::current") function.

 The [`thread::current`](fn.current "fn std::thread::current") function is available even for threads not spawned by the APIs of this module.

 ### 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!`](../macro.thread_local "macro std::thread_local") macro and can contain any value that is `'static` (no borrowed pointers). It provides an accessor function, [`with`](struct.localkey#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`](../cell/struct.cell "struct std::cell::Cell") or [`RefCell`](../cell/struct.refcell "struct std::cell::RefCell") types.

 ### 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`](struct.builder "struct std::thread::Builder") and pass the desired thread name to [`Builder::name`](struct.builder#method.name "method std::thread::Builder::name"). To retrieve the thread name from within the thread, use [`Thread::name`](struct.thread#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).

 ### 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`](struct.builder "struct std::thread::Builder") and pass the desired stack size to [`Builder::stack_size`](struct.builder#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`](struct.builder#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
-------


* [AccessError](struct.accesserror "struct std::thread::AccessError")
An error returned by [`LocalKey::try_with`](struct.localkey#method.try_with).
* [Builder](struct.builder "struct std::thread::Builder")
Thread factory, which can be used in order to configure the properties of a new thread.
* [JoinHandle](struct.joinhandle "struct std::thread::JoinHandle")
An owned permission to join on a thread (block on its termination).
* [LocalKey](struct.localkey "struct std::thread::LocalKey")
A thread local storage key which owns its contents.
* [Scope](struct.scope "struct std::thread::Scope")
A scope to spawn scoped threads in.
* [ScopedJoinHandle](struct.scopedjoinhandle "struct std::thread::ScopedJoinHandle")
An owned permission to join on a scoped thread (block on its termination).
* [Thread](struct.thread "struct std::thread::Thread")
A handle to a thread.
* [ThreadId](struct.threadid "struct std::thread::ThreadId")
A unique identifier for a running thread.


Functions
---------


* [available\_parallelism](fn.available_parallelism "fn std::thread::available_parallelism")
Returns an estimate of the default amount of parallelism a program should use.
* [current](fn.current "fn std::thread::current")
Gets a handle to the thread that invokes it.
* [panicking](fn.panicking "fn std::thread::panicking")
Determines whether the current thread is unwinding because of panic.
* [park](fn.park "fn std::thread::park")
Blocks unless or until the current thread’s token is made available.
* [park\_timeout](fn.park_timeout "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](fn.park_timeout_ms "fn std::thread::park_timeout_ms")Deprecated

Use [`park_timeout`](fn.park_timeout "fn std::thread::park_timeout").
* [scope](fn.scope "fn std::thread::scope")
Create a scope for spawning scoped threads.
* [sleep](fn.sleep "fn std::thread::sleep")
Puts the current thread to sleep for at least the specified amount of time.
* [sleep\_ms](fn.sleep_ms "fn std::thread::sleep_ms")Deprecated

Use [`sleep`](fn.sleep "fn std::thread::sleep").
* [spawn](fn.spawn "fn std::thread::spawn")
Spawns a new thread, returning a [`JoinHandle`](struct.joinhandle "struct std::thread::JoinHandle") for it.
* [yield\_now](fn.yield_now "fn std::thread::yield_now")
Cooperatively gives up a timeslice to the OS scheduler.


Type Definitions
----------------


* [Result](type.result "type std::thread::Result")
A specialized [`Result`](../result/enum.result "enum std::result::Result") type for threads.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/thread/index.html>

Module std::env
===============


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`](../ffi/struct.osstring "struct std::ffi::OsString") and those without will return a [`String`](../string/struct.string "struct std::string::String").

 Modules
-------


* [consts](consts/index "mod std::env::consts")
Constants associated with the current target


Structs
-------


* [Args](struct.args "struct std::env::Args")
An iterator over the arguments of a process, yielding a [`String`](../string/struct.string "struct std::string::String") value for each argument.
* [ArgsOs](struct.argsos "struct std::env::ArgsOs")
An iterator over the arguments of a process, yielding an [`OsString`](../ffi/struct.osstring "struct std::ffi::OsString") value for each argument.
* [JoinPathsError](struct.joinpathserror "struct std::env::JoinPathsError")
The error type for operations on the `PATH` variable. Possibly returned from [`env::join_paths()`](fn.join_paths "fn std::env::join_paths").
* [SplitPaths](struct.splitpaths "struct std::env::SplitPaths")
An iterator that splits an environment variable into paths according to platform-specific conventions.
* [Vars](struct.vars "struct std::env::Vars")
An iterator over a snapshot of the environment variables of this process.
* [VarsOs](struct.varsos "struct std::env::VarsOs")
An iterator over a snapshot of the environment variables of this process.


Enums
-----


* [VarError](enum.varerror "enum std::env::VarError")
The error type for operations interacting with environment variables. Possibly returned from [`env::var()`](fn.var "fn std::env::var").


Functions
---------


* [args](fn.args "fn std::env::args")
Returns the arguments that this program was started with (normally passed via the command line).
* [args\_os](fn.args_os "fn std::env::args_os")
Returns the arguments that this program was started with (normally passed via the command line).
* [current\_dir](fn.current_dir "fn std::env::current_dir")
Returns the current working directory as a [`PathBuf`](../path/struct.pathbuf "struct std::path::PathBuf").
* [current\_exe](fn.current_exe "fn std::env::current_exe")
Returns the full filesystem path of the current running executable.
* [home\_dir](fn.home_dir "fn std::env::home_dir")Deprecated

Returns the path of the current user’s home directory if known.
* [join\_paths](fn.join_paths "fn std::env::join_paths")
Joins a collection of [`Path`](../path/struct.path "struct std::path::Path")s appropriately for the `PATH` environment variable.
* [remove\_var](fn.remove_var "fn std::env::remove_var")
Removes an environment variable from the environment of the currently running process.
* [set\_current\_dir](fn.set_current_dir "fn std::env::set_current_dir")
Changes the current working directory to the specified path.
* [set\_var](fn.set_var "fn std::env::set_var")
Sets the environment variable `key` to the value `value` for the currently running process.
* [split\_paths](fn.split_paths "fn std::env::split_paths")
Parses input according to platform conventions for the `PATH` environment variable.
* [temp\_dir](fn.temp_dir "fn std::env::temp_dir")
Returns the path of a temporary directory.
* [var](fn.var "fn std::env::var")
Fetches the environment variable `key` from the current process.
* [var\_os](fn.var_os "fn std::env::var_os")
Fetches the environment variable `key` from the current process, returning [`None`](../option/enum.option#variant.None "variant std::option::Option::None") if the variable isn’t set or if there is another error.
* [vars](fn.vars "fn std::env::vars")
Returns an iterator of (variable, value) pairs of strings, for all the environment variables of the current process.
* [vars\_os](fn.vars_os "fn std::env::vars_os")
Returns an iterator of (variable, value) pairs of OS strings, for all the environment variables of the current process.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/env/index.html>

Module std::slice
=================


Utilities for the slice primitive type.

 *[See also the slice primitive type](../primitive.slice "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`](struct.iter "struct std::slice::Iter").

 A few functions are provided to create a slice from a value reference or from a raw pointer.

 Structs
-------


* [ArrayChunks](struct.arraychunks "struct std::slice::ArrayChunks")Experimental

An iterator over a slice in (non-overlapping) chunks (`N` elements at a time), starting at the beginning of the slice.
* [ArrayChunksMut](struct.arraychunksmut "struct std::slice::ArrayChunksMut")Experimental

An iterator over a slice in (non-overlapping) mutable chunks (`N` elements at a time), starting at the beginning of the slice.
* [ArrayWindows](struct.arraywindows "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
* [GroupBy](struct.groupby "struct std::slice::GroupBy")Experimental

An iterator over slice in (non-overlapping) chunks separated by a predicate.
* [GroupByMut](struct.groupbymut "struct std::slice::GroupByMut")Experimental

An iterator over slice in (non-overlapping) mutable chunks separated by a predicate.
* [Chunks](struct.chunks "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](struct.chunksexact "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](struct.chunksexactmut "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](struct.chunksmut "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](struct.escapeascii "struct std::slice::EscapeAscii")
An iterator over the escaped version of a byte slice.
* [Iter](struct.iter "struct std::slice::Iter")
Immutable slice iterator
* [IterMut](struct.itermut "struct std::slice::IterMut")
Mutable slice iterator.
* [RChunks](struct.rchunks "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](struct.rchunksexact "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](struct.rchunksexactmut "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](struct.rchunksmut "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](struct.rsplit "struct std::slice::RSplit")
An iterator over subslices separated by elements that match a predicate function, starting from the end of the slice.
* [RSplitMut](struct.rsplitmut "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](struct.rsplitn "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](struct.rsplitnmut "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](struct.split "struct std::slice::Split")
An iterator over subslices separated by elements that match a predicate function.
* [SplitInclusive](struct.splitinclusive "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](struct.splitinclusivemut "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](struct.splitmut "struct std::slice::SplitMut")
An iterator over the mutable subslices of the vector which are separated by elements that match `pred`.
* [SplitN](struct.splitn "struct std::slice::SplitN")
An iterator over subslices separated by elements that match a predicate function, limited to a given number of splits.
* [SplitNMut](struct.splitnmut "struct std::slice::SplitNMut")
An iterator over subslices separated by elements that match a predicate function, limited to a given number of splits.
* [Windows](struct.windows "struct std::slice::Windows")
An iterator over overlapping subslices of length `size`.


Traits
------


* [Concat](trait.concat "trait std::slice::Concat")Experimental

Helper trait for [`[T]::concat`](../primitive.slice#method.concat "method slice::concat").
* [Join](trait.join "trait std::slice::Join")Experimental

Helper trait for [`[T]::join`](../primitive.slice#method.join "method slice::join")
* [SliceIndex](trait.sliceindex "trait std::slice::SliceIndex")
A helper trait used for indexing operations.


Functions
---------


* [from\_mut\_ptr\_range](fn.from_mut_ptr_range "fn std::slice::from_mut_ptr_range")⚠Experimental

Forms a mutable slice from a pointer range.
* [from\_ptr\_range](fn.from_ptr_range "fn std::slice::from_ptr_range")⚠Experimental

Forms a slice from a pointer range.
* [range](fn.range "fn std::slice::range")Experimental

Performs bounds-checking of a range.
* [from\_mut](fn.from_mut "fn std::slice::from_mut")
Converts a reference to T into a slice of length 1 (without copying).
* [from\_raw\_parts](fn.from_raw_parts "fn std::slice::from_raw_parts")⚠

Forms a slice from a pointer and a length.
* [from\_raw\_parts\_mut](fn.from_raw_parts_mut "fn std::slice::from_raw_parts_mut")⚠

Performs the same functionality as [`from_raw_parts`](fn.from_raw_parts "fn std::slice::from_raw_parts"), except that a mutable slice is returned.
* [from\_ref](fn.from_ref "fn std::slice::from_ref")
Converts a reference to T into a slice of length 1 (without copying).



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/slice/index.html>

Module std::cmp
===============


Utilities for comparing and ordering values.

 This module contains various tools for comparing and ordering values. In summary:

 * [`Eq`](trait.eq "trait std::cmp::Eq") and [`PartialEq`](trait.partialeq "trait std::cmp::PartialEq") are traits that allow you to define total and partial equality between values, respectively. Implementing them overloads the `==` and `!=` operators.
* [`Ord`](trait.ord "trait std::cmp::Ord") and [`PartialOrd`](trait.partialord "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`](enum.ordering "enum std::cmp::Ordering") is an enum returned by the main functions of [`Ord`](trait.ord "trait std::cmp::Ord") and [`PartialOrd`](trait.partialord "trait std::cmp::PartialOrd"), and describes an ordering.
* [`Reverse`](struct.reverse "struct std::cmp::Reverse") is a struct that allows you to easily reverse an ordering.
* [`max`](trait.ord#method.max "method std::cmp::Ord::max") and [`min`](trait.ord#method.min "method std::cmp::Ord::min") are functions that build off of [`Ord`](trait.ord "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
-------


* [Reverse](struct.reverse "struct std::cmp::Reverse")
A helper struct for reverse ordering.


Enums
-----


* [Ordering](enum.ordering "enum std::cmp::Ordering")
An `Ordering` is the result of a comparison between two values.


Traits
------


* [Eq](trait.eq "trait std::cmp::Eq")
Trait for equality comparisons which are [equivalence relations](https://en.wikipedia.org/wiki/Equivalence_relation).
* [Ord](trait.ord "trait std::cmp::Ord")
Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).
* [PartialEq](trait.partialeq "trait std::cmp::PartialEq")
Trait for equality comparisons.
* [PartialOrd](trait.partialord "trait std::cmp::PartialOrd")
Trait for types that form a [partial order](https://en.wikipedia.org/wiki/Partial_order).


Functions
---------


* [max](fn.max "fn std::cmp::max")
Compares and returns the maximum of two values.
* [max\_by](fn.max_by "fn std::cmp::max_by")
Returns the maximum of two values with respect to the specified comparison function.
* [max\_by\_key](fn.max_by_key "fn std::cmp::max_by_key")
Returns the element that gives the maximum value from the specified function.
* [min](fn.min "fn std::cmp::min")
Compares and returns the minimum of two values.
* [min\_by](fn.min_by "fn std::cmp::min_by")
Returns the minimum of two values with respect to the specified comparison function.
* [min\_by\_key](fn.min_by_key "fn std::cmp::min_by_key")
Returns the element that gives the minimum value from the specified function.


Derive Macros
-------------


* [Eq](derive.eq "derive std::cmp::Eq")
Derive macro generating an impl of the trait [`Eq`](trait.eq "trait std::cmp::Eq").
* [Ord](derive.ord "derive std::cmp::Ord")
Derive macro generating an impl of the trait [`Ord`](trait.ord "trait std::cmp::Ord"). The behavior of this macro is described in detail [here](trait.ord#derivable "trait std::cmp::Ord").
* [PartialEq](derive.partialeq "derive std::cmp::PartialEq")
Derive macro generating an impl of the trait [`PartialEq`](trait.partialeq "trait std::cmp::PartialEq"). The behavior of this macro is described in detail [here](trait.partialeq#derivable "trait std::cmp::PartialEq").
* [PartialOrd](derive.partialord "derive std::cmp::PartialOrd")
Derive macro generating an impl of the trait [`PartialOrd`](trait.partialord "trait std::cmp::PartialOrd"). The behavior of this macro is described in detail [here](trait.partialord#derivable "trait std::cmp::PartialOrd").



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/cmp/index.html>

Primitive Type i32
==================


The 32-bit signed integer type.

 Implementations
---------------



[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#342)
```
impl i32
```

[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.43.0
```
pub const MIN: i32 = -2_147_483_648i32
```

The smallest value that can be represented by this integer type (−231).

 ##### Examples

 Basic usage:

 
```
assert_eq!(i32::MIN, -2147483648);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.43.0
```
pub const MAX: i32 = 2_147_483_647i32
```

The largest value that can be represented by this integer type (231 − 1).

 ##### Examples

 Basic usage:

 
```
assert_eq!(i32::MAX, 2147483647);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.53.0
```
pub const BITS: u32 = 32u32
```

The size of this integer type in bits.

 ##### Examples

 
```
assert_eq!(i32::BITS, 32);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)
```
pub fn from_str_radix(src: &str, radix: u32) -> Result<i32, ParseIntError>
```

Converts a string slice in a given base to an integer.

 The string is expected to be an optional `+` or `-` sign followed by digits. Leading and trailing whitespace represent an error. Digits are a subset of these characters, depending on `radix`:

 * `0-9`
* `a-z`
* `A-Z`

 ##### Panics

 This function panics if `radix` is not in the range from 2 to 36.

 ##### Examples

 Basic usage:

 
```
assert_eq!(i32::from_str_radix("A", 16), Ok(10));
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: 1.32.0
```
pub const fn count_ones(self) -> u32
```

Returns the number of ones in the binary representation of `self`.

 ##### Examples

 Basic usage:

 
```
let n = 0b100_0000i32;

assert_eq!(n.count_ones(), 1);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: 1.32.0
```
pub const fn count_zeros(self) -> u32
```

Returns the number of zeros in the binary representation of `self`.

 ##### Examples

 Basic usage:

 
```
assert_eq!(i32::MAX.count_zeros(), 1);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: 1.32.0
```
pub const fn leading_zeros(self) -> u32
```

Returns the number of leading zeros in the binary representation of `self`.

 Depending on what you’re doing with the value, you might also be interested in the [`ilog2`](primitive.i32#method.ilog2 "method i32::ilog2") function which returns a consistent number, even if the type widens.

 ##### Examples

 Basic usage:

 
```
let n = -1i32;

assert_eq!(n.leading_zeros(), 0);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: 1.32.0
```
pub const fn trailing_zeros(self) -> u32
```

Returns the number of trailing zeros in the binary representation of `self`.

 ##### Examples

 Basic usage:

 
```
let n = -4i32;

assert_eq!(n.trailing_zeros(), 2);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.46.0 (const: 1.46.0)
```
pub const fn leading_ones(self) -> u32
```

Returns the number of leading ones in the binary representation of `self`.

 ##### Examples

 Basic usage:

 
```
let n = -1i32;

assert_eq!(n.leading_ones(), 32);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.46.0 (const: 1.46.0)
```
pub const fn trailing_ones(self) -> u32
```

Returns the number of trailing ones in the binary representation of `self`.

 ##### Examples

 Basic usage:

 
```
let n = 3i32;

assert_eq!(n.trailing_ones(), 2);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: 1.32.0
```
pub const fn rotate_left(self, n: u32) -> i32
```

Shifts the bits to the left by a specified amount, `n`, wrapping the truncated bits to the end of the resulting integer.

 Please note this isn’t the same operation as the `<<` shifting operator!

 ##### Examples

 Basic usage:

 
```
let n = 0x10000b3i32;
let m = 0xb301;

assert_eq!(n.rotate_left(8), m);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: 1.32.0
```
pub const fn rotate_right(self, n: u32) -> i32
```

Shifts the bits to the right by a specified amount, `n`, wrapping the truncated bits to the beginning of the resulting integer.

 Please note this isn’t the same operation as the `>>` shifting operator!

 ##### Examples

 Basic usage:

 
```
let n = 0xb301i32;
let m = 0x10000b3;

assert_eq!(n.rotate_right(8), m);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: 1.32.0
```
pub const fn swap_bytes(self) -> i32
```

Reverses the byte order of the integer.

 ##### Examples

 Basic usage:

 
```
let n = 0x12345678i32;

let m = n.swap_bytes();

assert_eq!(m, 0x78563412);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.37.0 (const: 1.37.0)
```
pub const fn reverse_bits(self) -> i32
```

Reverses the order of bits in the integer. The least significant bit becomes the most significant bit, second least-significant bit becomes second most-significant bit, etc.

 ##### Examples

 Basic usage:

 
```
let n = 0x12345678i32;
let m = n.reverse_bits();

assert_eq!(m, 0x1e6a2c48);
assert_eq!(0, 0i32.reverse_bits());
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: 1.32.0
```
pub const fn from_be(x: i32) -> i32
```

Converts an integer from big endian to the target’s endianness.

 On big endian this is a no-op. On little endian the bytes are swapped.

 ##### Examples

 Basic usage:

 
```
let n = 0x1Ai32;

if cfg!(target_endian = "big") {
    assert_eq!(i32::from_be(n), n)
} else {
    assert_eq!(i32::from_be(n), n.swap_bytes())
}
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: 1.32.0
```
pub const fn from_le(x: i32) -> i32
```

Converts an integer from little endian to the target’s endianness.

 On little endian this is a no-op. On big endian the bytes are swapped.

 ##### Examples

 Basic usage:

 
```
let n = 0x1Ai32;

if cfg!(target_endian = "little") {
    assert_eq!(i32::from_le(n), n)
} else {
    assert_eq!(i32::from_le(n), n.swap_bytes())
}
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: 1.32.0
```
pub const fn to_be(self) -> i32
```

Converts `self` to big endian from the target’s endianness.

 On big endian this is a no-op. On little endian the bytes are swapped.

 ##### Examples

 Basic usage:

 
```
let n = 0x1Ai32;

if cfg!(target_endian = "big") {
    assert_eq!(n.to_be(), n)
} else {
    assert_eq!(n.to_be(), n.swap_bytes())
}
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: 1.32.0
```
pub const fn to_le(self) -> i32
```

Converts `self` to little endian from the target’s endianness.

 On little endian this is a no-op. On big endian the bytes are swapped.

 ##### Examples

 Basic usage:

 
```
let n = 0x1Ai32;

if cfg!(target_endian = "little") {
    assert_eq!(n.to_le(), n)
} else {
    assert_eq!(n.to_le(), n.swap_bytes())
}
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: 1.47.0
```
pub const fn checked_add(self, rhs: i32) -> Option<i32>
```

Checked integer addition. Computes `self + rhs`, returning `None` if overflow occurred.

 ##### Examples

 Basic usage:

 
```
assert_eq!((i32::MAX - 2).checked_add(1), Some(i32::MAX - 1));
assert_eq!((i32::MAX - 2).checked_add(3), None);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: [unstable](https://github.com/rust-lang/rust/issues/85122 "Tracking issue for const_inherent_unchecked_arith")
```
pub unsafe fn unchecked_add(self, rhs: i32) -> i32
```

🔬This is a nightly-only experimental API. (`unchecked_math` [#85122](https://github.com/rust-lang/rust/issues/85122))

Unchecked integer addition. Computes `self + rhs`, assuming overflow cannot occur.

 ##### Safety

 This results in undefined behavior when `self + rhs > i32::MAX` or `self + rhs < i32::MIN`, i.e. when [`checked_add`](primitive.i32#method.checked_add "method i32::checked_add") would return `None`.

 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.66.0 (const: 1.66.0)
```
pub const fn checked_add_unsigned(self, rhs: u32) -> Option<i32>
```

Checked addition with an unsigned integer. Computes `self + rhs`, returning `None` if overflow occurred.

 ##### Examples

 Basic usage:

 
```
assert_eq!(1i32.checked_add_unsigned(2), Some(3));
assert_eq!((i32::MAX - 2).checked_add_unsigned(3), None);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: 1.47.0
```
pub const fn checked_sub(self, rhs: i32) -> Option<i32>
```

Checked integer subtraction. Computes `self - rhs`, returning `None` if overflow occurred.

 ##### Examples

 Basic usage:

 
```
assert_eq!((i32::MIN + 2).checked_sub(1), Some(i32::MIN + 1));
assert_eq!((i32::MIN + 2).checked_sub(3), None);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: [unstable](https://github.com/rust-lang/rust/issues/85122 "Tracking issue for const_inherent_unchecked_arith")
```
pub unsafe fn unchecked_sub(self, rhs: i32) -> i32
```

🔬This is a nightly-only experimental API. (`unchecked_math` [#85122](https://github.com/rust-lang/rust/issues/85122))

Unchecked integer subtraction. Computes `self - rhs`, assuming overflow cannot occur.

 ##### Safety

 This results in undefined behavior when `self - rhs > i32::MAX` or `self - rhs < i32::MIN`, i.e. when [`checked_sub`](primitive.i32#method.checked_sub "method i32::checked_sub") would return `None`.

 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.66.0 (const: 1.66.0)
```
pub const fn checked_sub_unsigned(self, rhs: u32) -> Option<i32>
```

Checked subtraction with an unsigned integer. Computes `self - rhs`, returning `None` if overflow occurred.

 ##### Examples

 Basic usage:

 
```
assert_eq!(1i32.checked_sub_unsigned(2), Some(-1));
assert_eq!((i32::MIN + 2).checked_sub_unsigned(3), None);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: 1.47.0
```
pub const fn checked_mul(self, rhs: i32) -> Option<i32>
```

Checked integer multiplication. Computes `self * rhs`, returning `None` if overflow occurred.

 ##### Examples

 Basic usage:

 
```
assert_eq!(i32::MAX.checked_mul(1), Some(i32::MAX));
assert_eq!(i32::MAX.checked_mul(2), None);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: [unstable](https://github.com/rust-lang/rust/issues/85122 "Tracking issue for const_inherent_unchecked_arith")
```
pub unsafe fn unchecked_mul(self, rhs: i32) -> i32
```

🔬This is a nightly-only experimental API. (`unchecked_math` [#85122](https://github.com/rust-lang/rust/issues/85122))

Unchecked integer multiplication. Computes `self * rhs`, assuming overflow cannot occur.

 ##### Safety

 This results in undefined behavior when `self * rhs > i32::MAX` or `self * rhs < i32::MIN`, i.e. when [`checked_mul`](primitive.i32#method.checked_mul "method i32::checked_mul") would return `None`.

 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: 1.52.0
```
pub const fn checked_div(self, rhs: i32) -> Option<i32>
```

Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0` or the division results in overflow.

 ##### Examples

 Basic usage:

 
```
assert_eq!((i32::MIN + 1).checked_div(-1), Some(2147483647));
assert_eq!(i32::MIN.checked_div(-1), None);
assert_eq!((1i32).checked_div(0), None);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.38.0 (const: 1.52.0)
```
pub const fn checked_div_euclid(self, rhs: i32) -> Option<i32>
```

Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None` if `rhs == 0` or the division results in overflow.

 ##### Examples

 Basic usage:

 
```
assert_eq!((i32::MIN + 1).checked_div_euclid(-1), Some(2147483647));
assert_eq!(i32::MIN.checked_div_euclid(-1), None);
assert_eq!((1i32).checked_div_euclid(0), None);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.7.0 (const: 1.52.0)
```
pub const fn checked_rem(self, rhs: i32) -> Option<i32>
```

Checked integer remainder. Computes `self % rhs`, returning `None` if `rhs == 0` or the division results in overflow.

 ##### Examples

 Basic usage:

 
```
assert_eq!(5i32.checked_rem(2), Some(1));
assert_eq!(5i32.checked_rem(0), None);
assert_eq!(i32::MIN.checked_rem(-1), None);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.38.0 (const: 1.52.0)
```
pub const fn checked_rem_euclid(self, rhs: i32) -> Option<i32>
```

Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None` if `rhs == 0` or the division results in overflow.

 ##### Examples

 Basic usage:

 
```
assert_eq!(5i32.checked_rem_euclid(2), Some(1));
assert_eq!(5i32.checked_rem_euclid(0), None);
assert_eq!(i32::MIN.checked_rem_euclid(-1), None);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.7.0 (const: 1.47.0)
```
pub const fn checked_neg(self) -> Option<i32>
```

Checked negation. Computes `-self`, returning `None` if `self == MIN`.

 ##### Examples

 Basic usage:

 
```
assert_eq!(5i32.checked_neg(), Some(-5));
assert_eq!(i32::MIN.checked_neg(), None);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.7.0 (const: 1.47.0)
```
pub const fn checked_shl(self, rhs: u32) -> Option<i32>
```

Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger than or equal to the number of bits in `self`.

 ##### Examples

 Basic usage:

 
```
assert_eq!(0x1i32.checked_shl(4), Some(0x10));
assert_eq!(0x1i32.checked_shl(129), None);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: [unstable](https://github.com/rust-lang/rust/issues/85122 "Tracking issue for const_inherent_unchecked_arith")
```
pub unsafe fn unchecked_shl(self, rhs: u32) -> i32
```

🔬This is a nightly-only experimental API. (`unchecked_math` [#85122](https://github.com/rust-lang/rust/issues/85122))

Unchecked shift left. Computes `self << rhs`, assuming that `rhs` is less than the number of bits in `self`.

 ##### Safety

 This results in undefined behavior if `rhs` is larger than or equal to the number of bits in `self`, i.e. when [`checked_shl`](primitive.i32#method.checked_shl "method i32::checked_shl") would return `None`.

 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.7.0 (const: 1.47.0)
```
pub const fn checked_shr(self, rhs: u32) -> Option<i32>
```

Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is larger than or equal to the number of bits in `self`.

 ##### Examples

 Basic usage:

 
```
assert_eq!(0x10i32.checked_shr(4), Some(0x1));
assert_eq!(0x10i32.checked_shr(128), None);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: [unstable](https://github.com/rust-lang/rust/issues/85122 "Tracking issue for const_inherent_unchecked_arith")
```
pub unsafe fn unchecked_shr(self, rhs: u32) -> i32
```

🔬This is a nightly-only experimental API. (`unchecked_math` [#85122](https://github.com/rust-lang/rust/issues/85122))

Unchecked shift right. Computes `self >> rhs`, assuming that `rhs` is less than the number of bits in `self`.

 ##### Safety

 This results in undefined behavior if `rhs` is larger than or equal to the number of bits in `self`, i.e. when [`checked_shr`](primitive.i32#method.checked_shr "method i32::checked_shr") would return `None`.

 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.13.0 (const: 1.47.0)
```
pub const fn checked_abs(self) -> Option<i32>
```

Checked absolute value. Computes `self.abs()`, returning `None` if `self == MIN`.

 ##### Examples

 Basic usage:

 
```
assert_eq!((-5i32).checked_abs(), Some(5));
assert_eq!(i32::MIN.checked_abs(), None);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.34.0 (const: 1.50.0)
```
pub const fn checked_pow(self, exp: u32) -> Option<i32>
```

Checked exponentiation. Computes `self.pow(exp)`, returning `None` if overflow occurred.

 ##### Examples

 Basic usage:

 
```
assert_eq!(8i32.checked_pow(2), Some(64));
assert_eq!(i32::MAX.checked_pow(2), None);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: 1.47.0
```
pub const fn saturating_add(self, rhs: i32) -> i32
```

Saturating integer addition. Computes `self + rhs`, saturating at the numeric bounds instead of overflowing.

 ##### Examples

 Basic usage:

 
```
assert_eq!(100i32.saturating_add(1), 101);
assert_eq!(i32::MAX.saturating_add(100), i32::MAX);
assert_eq!(i32::MIN.saturating_add(-1), i32::MIN);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.66.0 (const: 1.66.0)
```
pub const fn saturating_add_unsigned(self, rhs: u32) -> i32
```

Saturating addition with an unsigned integer. Computes `self + rhs`, saturating at the numeric bounds instead of overflowing.

 ##### Examples

 Basic usage:

 
```
assert_eq!(1i32.saturating_add_unsigned(2), 3);
assert_eq!(i32::MAX.saturating_add_unsigned(100), i32::MAX);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: 1.47.0
```
pub const fn saturating_sub(self, rhs: i32) -> i32
```

Saturating integer subtraction. Computes `self - rhs`, saturating at the numeric bounds instead of overflowing.

 ##### Examples

 Basic usage:

 
```
assert_eq!(100i32.saturating_sub(127), -27);
assert_eq!(i32::MIN.saturating_sub(100), i32::MIN);
assert_eq!(i32::MAX.saturating_sub(-1), i32::MAX);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.66.0 (const: 1.66.0)
```
pub const fn saturating_sub_unsigned(self, rhs: u32) -> i32
```

Saturating subtraction with an unsigned integer. Computes `self - rhs`, saturating at the numeric bounds instead of overflowing.

 ##### Examples

 Basic usage:

 
```
assert_eq!(100i32.saturating_sub_unsigned(127), -27);
assert_eq!(i32::MIN.saturating_sub_unsigned(100), i32::MIN);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.45.0 (const: 1.47.0)
```
pub const fn saturating_neg(self) -> i32
```

Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN` instead of overflowing.

 ##### Examples

 Basic usage:

 
```
assert_eq!(100i32.saturating_neg(), -100);
assert_eq!((-100i32).saturating_neg(), 100);
assert_eq!(i32::MIN.saturating_neg(), i32::MAX);
assert_eq!(i32::MAX.saturating_neg(), i32::MIN + 1);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.45.0 (const: 1.47.0)
```
pub const fn saturating_abs(self) -> i32
```

Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self == MIN` instead of overflowing.

 ##### Examples

 Basic usage:

 
```
assert_eq!(100i32.saturating_abs(), 100);
assert_eq!((-100i32).saturating_abs(), 100);
assert_eq!(i32::MIN.saturating_abs(), i32::MAX);
assert_eq!((i32::MIN + 1).saturating_abs(), i32::MAX);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.7.0 (const: 1.47.0)
```
pub const fn saturating_mul(self, rhs: i32) -> i32
```

Saturating integer multiplication. Computes `self * rhs`, saturating at the numeric bounds instead of overflowing.

 ##### Examples

 Basic usage:

 
```
assert_eq!(10i32.saturating_mul(12), 120);
assert_eq!(i32::MAX.saturating_mul(10), i32::MAX);
assert_eq!(i32::MIN.saturating_mul(10), i32::MIN);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.58.0 (const: 1.58.0)
```
pub const fn saturating_div(self, rhs: i32) -> i32
```

Saturating integer division. Computes `self / rhs`, saturating at the numeric bounds instead of overflowing.

 ##### Examples

 Basic usage:

 
```
assert_eq!(5i32.saturating_div(2), 2);
assert_eq!(i32::MAX.saturating_div(-1), i32::MIN + 1);
assert_eq!(i32::MIN.saturating_div(-1), i32::MAX);

```
 ⓘ
```
let _ = 1i32.saturating_div(0);

```

 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.34.0 (const: 1.50.0)
```
pub const fn saturating_pow(self, exp: u32) -> i32
```

Saturating integer exponentiation. Computes `self.pow(exp)`, saturating at the numeric bounds instead of overflowing.

 ##### Examples

 Basic usage:

 
```
assert_eq!((-4i32).saturating_pow(3), -64);
assert_eq!(i32::MIN.saturating_pow(2), i32::MAX);
assert_eq!(i32::MIN.saturating_pow(3), i32::MIN);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: 1.32.0
```
pub const fn wrapping_add(self, rhs: i32) -> i32
```

Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the boundary of the type.

 ##### Examples

 Basic usage:

 
```
assert_eq!(100i32.wrapping_add(27), 127);
assert_eq!(i32::MAX.wrapping_add(2), i32::MIN + 1);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.66.0 (const: 1.66.0)
```
pub const fn wrapping_add_unsigned(self, rhs: u32) -> i32
```

Wrapping (modular) addition with an unsigned integer. Computes `self + rhs`, wrapping around at the boundary of the type.

 ##### Examples

 Basic usage:

 
```
assert_eq!(100i32.wrapping_add_unsigned(27), 127);
assert_eq!(i32::MAX.wrapping_add_unsigned(2), i32::MIN + 1);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: 1.32.0
```
pub const fn wrapping_sub(self, rhs: i32) -> i32
```

Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the boundary of the type.

 ##### Examples

 Basic usage:

 
```
assert_eq!(0i32.wrapping_sub(127), -127);
assert_eq!((-2i32).wrapping_sub(i32::MAX), i32::MAX);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.66.0 (const: 1.66.0)
```
pub const fn wrapping_sub_unsigned(self, rhs: u32) -> i32
```

Wrapping (modular) subtraction with an unsigned integer. Computes `self - rhs`, wrapping around at the boundary of the type.

 ##### Examples

 Basic usage:

 
```
assert_eq!(0i32.wrapping_sub_unsigned(127), -127);
assert_eq!((-2i32).wrapping_sub_unsigned(u32::MAX), -1);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: 1.32.0
```
pub const fn wrapping_mul(self, rhs: i32) -> i32
```

Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at the boundary of the type.

 ##### Examples

 Basic usage:

 
```
assert_eq!(10i32.wrapping_mul(12), 120);
assert_eq!(11i8.wrapping_mul(12), -124);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.2.0 (const: 1.52.0)
```
pub const fn wrapping_div(self, rhs: i32) -> i32
```

Wrapping (modular) division. Computes `self / rhs`, wrapping around at the boundary of the type.

 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value that is too large to represent in the type. In such a case, this function returns `MIN` itself.

 ##### Panics

 This function will panic if `rhs` is 0.

 ##### Examples

 Basic usage:

 
```
assert_eq!(100i32.wrapping_div(10), 10);
assert_eq!((-128i8).wrapping_div(-1), -128);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.38.0 (const: 1.52.0)
```
pub const fn wrapping_div_euclid(self, rhs: i32) -> i32
```

Wrapping Euclidean division. Computes `self.div_euclid(rhs)`, wrapping around at the boundary of the type.

 Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the type. In this case, this method returns `MIN` itself.

 ##### Panics

 This function will panic if `rhs` is 0.

 ##### Examples

 Basic usage:

 
```
assert_eq!(100i32.wrapping_div_euclid(10), 10);
assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.2.0 (const: 1.52.0)
```
pub const fn wrapping_rem(self, rhs: i32) -> i32
```

Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the boundary of the type.

 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y` invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case, this function returns `0`.

 ##### Panics

 This function will panic if `rhs` is 0.

 ##### Examples

 Basic usage:

 
```
assert_eq!(100i32.wrapping_rem(10), 0);
assert_eq!((-128i8).wrapping_rem(-1), 0);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.38.0 (const: 1.52.0)
```
pub const fn wrapping_rem_euclid(self, rhs: i32) -> i32
```

Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around at the boundary of the type.

 Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value for the type). In this case, this method returns 0.

 ##### Panics

 This function will panic if `rhs` is 0.

 ##### Examples

 Basic usage:

 
```
assert_eq!(100i32.wrapping_rem_euclid(10), 0);
assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.2.0 (const: 1.32.0)
```
pub const fn wrapping_neg(self) -> i32
```

Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary of the type.

 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN` is the negative minimal value for the type); this is a positive value that is too large to represent in the type. In such a case, this function returns `MIN` itself.

 ##### Examples

 Basic usage:

 
```
assert_eq!(100i32.wrapping_neg(), -100);
assert_eq!(i32::MIN.wrapping_neg(), i32::MIN);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.2.0 (const: 1.32.0)
```
pub const fn wrapping_shl(self, rhs: u32) -> i32
```

Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.

 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to the range of the type, rather than the bits shifted out of the LHS being returned to the other end. The primitive integer types all implement a [`rotate_left`](primitive.i32#method.rotate_left "method i32::rotate_left") function, which may be what you want instead.

 ##### Examples

 Basic usage:

 
```
assert_eq!((-1i32).wrapping_shl(7), -128);
assert_eq!((-1i32).wrapping_shl(128), -1);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.2.0 (const: 1.32.0)
```
pub const fn wrapping_shr(self, rhs: u32) -> i32
```

Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask` removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.

 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted to the range of the type, rather than the bits shifted out of the LHS being returned to the other end. The primitive integer types all implement a [`rotate_right`](primitive.i32#method.rotate_right "method i32::rotate_right") function, which may be what you want instead.

 ##### Examples

 Basic usage:

 
```
assert_eq!((-128i32).wrapping_shr(7), -1);
assert_eq!((-128i16).wrapping_shr(64), -128);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.13.0 (const: 1.32.0)
```
pub const fn wrapping_abs(self) -> i32
```

Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at the boundary of the type.

 The only case where such wrapping can occur is when one takes the absolute value of the negative minimal value for the type; this is a positive value that is too large to represent in the type. In such a case, this function returns `MIN` itself.

 ##### Examples

 Basic usage:

 
```
assert_eq!(100i32.wrapping_abs(), 100);
assert_eq!((-100i32).wrapping_abs(), 100);
assert_eq!(i32::MIN.wrapping_abs(), i32::MIN);
assert_eq!((-128i8).wrapping_abs() as u8, 128);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.51.0 (const: 1.51.0)
```
pub const fn unsigned_abs(self) -> u32
```

Computes the absolute value of `self` without any wrapping or panicking.

 ##### Examples

 Basic usage:

 
```
assert_eq!(100i32.unsigned_abs(), 100u32);
assert_eq!((-100i32).unsigned_abs(), 100u32);
assert_eq!((-128i8).unsigned_abs(), 128u8);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.34.0 (const: 1.50.0)
```
pub const fn wrapping_pow(self, exp: u32) -> i32
```

Wrapping (modular) exponentiation. Computes `self.pow(exp)`, wrapping around at the boundary of the type.

 ##### Examples

 Basic usage:

 
```
assert_eq!(3i32.wrapping_pow(4), 81);
assert_eq!(3i8.wrapping_pow(5), -13);
assert_eq!(3i8.wrapping_pow(6), -39);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.7.0 (const: 1.32.0)
```
pub const fn overflowing_add(self, rhs: i32) -> (i32, bool)
```

Calculates `self` + `rhs`

 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would occur. If an overflow would have occurred then the wrapped value is returned.

 ##### Examples

 Basic usage:

 
```
assert_eq!(5i32.overflowing_add(2), (7, false));
assert_eq!(i32::MAX.overflowing_add(1), (i32::MIN, true));
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: [unstable](https://github.com/rust-lang/rust/issues/85532 "Tracking issue for const_bigint_helper_methods")
```
pub fn carrying_add(self, rhs: i32, carry: bool) -> (i32, bool)
```

🔬This is a nightly-only experimental API. (`bigint_helper_methods` [#85532](https://github.com/rust-lang/rust/issues/85532))

Calculates `self` + `rhs` + `carry` and checks for overflow.

 Performs “ternary addition” of two integer operands and a carry-in bit, and returns a tuple of the sum along with a boolean indicating whether an arithmetic overflow would occur. On overflow, the wrapped value is returned.

 This allows chaining together multiple additions to create a wider addition, and can be useful for bignum addition. This method should only be used for the most significant word; for the less significant words the unsigned method [`u32::carrying_add`](primitive.u32#method.carrying_add "method u32::carrying_add") should be used.

 The output boolean returned by this method is *not* a carry flag, and should *not* be added to a more significant word.

 If the input carry is false, this method is equivalent to [`overflowing_add`](primitive.i32#method.overflowing_add "method i32::overflowing_add").

 ##### Examples

 
```
#![feature(bigint_helper_methods)]
// Only the most significant word is signed.
//
//   10  MAX    (a = 10 × 2^32 + 2^32 - 1)
// + -5    9    (b = -5 × 2^32 + 9)
// ---------
//    6    8    (sum = 6 × 2^32 + 8)

let (a1, a0): (i32, u32) = (10, u32::MAX);
let (b1, b0): (i32, u32) = (-5, 9);
let carry0 = false;

// u32::carrying_add for the less significant words
let (sum0, carry1) = a0.carrying_add(b0, carry0);
assert_eq!(carry1, true);

// i32::carrying_add for the most significant word
let (sum1, overflow) = a1.carrying_add(b1, carry1);
assert_eq!(overflow, false);

assert_eq!((sum1, sum0), (6, 8));
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.66.0 (const: 1.66.0)
```
pub const fn overflowing_add_unsigned(self, rhs: u32) -> (i32, bool)
```

Calculates `self` + `rhs` with an unsigned `rhs`

 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would occur. If an overflow would have occurred then the wrapped value is returned.

 ##### Examples

 Basic usage:

 
```
assert_eq!(1i32.overflowing_add_unsigned(2), (3, false));
assert_eq!((i32::MIN).overflowing_add_unsigned(u32::MAX), (i32::MAX, false));
assert_eq!((i32::MAX - 2).overflowing_add_unsigned(3), (i32::MIN, true));
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.7.0 (const: 1.32.0)
```
pub const fn overflowing_sub(self, rhs: i32) -> (i32, bool)
```

Calculates `self` - `rhs`

 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow would occur. If an overflow would have occurred then the wrapped value is returned.

 ##### Examples

 Basic usage:

 
```
assert_eq!(5i32.overflowing_sub(2), (3, false));
assert_eq!(i32::MIN.overflowing_sub(1), (i32::MAX, true));
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: [unstable](https://github.com/rust-lang/rust/issues/85532 "Tracking issue for const_bigint_helper_methods")
```
pub fn borrowing_sub(self, rhs: i32, borrow: bool) -> (i32, bool)
```

🔬This is a nightly-only experimental API. (`bigint_helper_methods` [#85532](https://github.com/rust-lang/rust/issues/85532))

Calculates `self` − `rhs` − `borrow` and checks for overflow.

 Performs “ternary subtraction” by subtracting both an integer operand and a borrow-in bit from `self`, and returns a tuple of the difference along with a boolean indicating whether an arithmetic overflow would occur. On overflow, the wrapped value is returned.

 This allows chaining together multiple subtractions to create a wider subtraction, and can be useful for bignum subtraction. This method should only be used for the most significant word; for the less significant words the unsigned method [`u32::borrowing_sub`](primitive.u32#method.borrowing_sub "method u32::borrowing_sub") should be used.

 The output boolean returned by this method is *not* a borrow flag, and should *not* be subtracted from a more significant word.

 If the input borrow is false, this method is equivalent to [`overflowing_sub`](primitive.i32#method.overflowing_sub "method i32::overflowing_sub").

 ##### Examples

 
```
#![feature(bigint_helper_methods)]
// Only the most significant word is signed.
//
//    6    8    (a = 6 × 2^32 + 8)
// - -5    9    (b = -5 × 2^32 + 9)
// ---------
//   10  MAX    (diff = 10 × 2^32 + 2^32 - 1)

let (a1, a0): (i32, u32) = (6, 8);
let (b1, b0): (i32, u32) = (-5, 9);
let borrow0 = false;

// u32::borrowing_sub for the less significant words
let (diff0, borrow1) = a0.borrowing_sub(b0, borrow0);
assert_eq!(borrow1, true);

// i32::borrowing_sub for the most significant word
let (diff1, overflow) = a1.borrowing_sub(b1, borrow1);
assert_eq!(overflow, false);

assert_eq!((diff1, diff0), (10, u32::MAX));
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.66.0 (const: 1.66.0)
```
pub const fn overflowing_sub_unsigned(self, rhs: u32) -> (i32, bool)
```

Calculates `self` - `rhs` with an unsigned `rhs`

 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow would occur. If an overflow would have occurred then the wrapped value is returned.

 ##### Examples

 Basic usage:

 
```
assert_eq!(1i32.overflowing_sub_unsigned(2), (-1, false));
assert_eq!((i32::MAX).overflowing_sub_unsigned(u32::MAX), (i32::MIN, false));
assert_eq!((i32::MIN + 2).overflowing_sub_unsigned(3), (i32::MAX, true));
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.7.0 (const: 1.32.0)
```
pub const fn overflowing_mul(self, rhs: i32) -> (i32, bool)
```

Calculates the multiplication of `self` and `rhs`.

 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow would occur. If an overflow would have occurred then the wrapped value is returned.

 ##### Examples

 Basic usage:

 
```
assert_eq!(5i32.overflowing_mul(2), (10, false));
assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.7.0 (const: 1.52.0)
```
pub const fn overflowing_div(self, rhs: i32) -> (i32, bool)
```

Calculates the divisor when `self` is divided by `rhs`.

 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would occur. If an overflow would occur then self is returned.

 ##### Panics

 This function will panic if `rhs` is 0.

 ##### Examples

 Basic usage:

 
```
assert_eq!(5i32.overflowing_div(2), (2, false));
assert_eq!(i32::MIN.overflowing_div(-1), (i32::MIN, true));
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.38.0 (const: 1.52.0)
```
pub const fn overflowing_div_euclid(self, rhs: i32) -> (i32, bool)
```

Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.

 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would occur. If an overflow would occur then `self` is returned.

 ##### Panics

 This function will panic if `rhs` is 0.

 ##### Examples

 Basic usage:

 
```
assert_eq!(5i32.overflowing_div_euclid(2), (2, false));
assert_eq!(i32::MIN.overflowing_div_euclid(-1), (i32::MIN, true));
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.7.0 (const: 1.52.0)
```
pub const fn overflowing_rem(self, rhs: i32) -> (i32, bool)
```

Calculates the remainder when `self` is divided by `rhs`.

 Returns a tuple of the remainder after dividing along with a boolean indicating whether an arithmetic overflow would occur. If an overflow would occur then 0 is returned.

 ##### Panics

 This function will panic if `rhs` is 0.

 ##### Examples

 Basic usage:

 
```
assert_eq!(5i32.overflowing_rem(2), (1, false));
assert_eq!(i32::MIN.overflowing_rem(-1), (0, true));
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.38.0 (const: 1.52.0)
```
pub const fn overflowing_rem_euclid(self, rhs: i32) -> (i32, bool)
```

Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.

 Returns a tuple of the remainder after dividing along with a boolean indicating whether an arithmetic overflow would occur. If an overflow would occur then 0 is returned.

 ##### Panics

 This function will panic if `rhs` is 0.

 ##### Examples

 Basic usage:

 
```
assert_eq!(5i32.overflowing_rem_euclid(2), (1, false));
assert_eq!(i32::MIN.overflowing_rem_euclid(-1), (0, true));
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.7.0 (const: 1.32.0)
```
pub const fn overflowing_neg(self) -> (i32, bool)
```

Negates self, overflowing if this is equal to the minimum value.

 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow happened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the minimum value will be returned again and `true` will be returned for an overflow happening.

 ##### Examples

 Basic usage:

 
```
assert_eq!(2i32.overflowing_neg(), (-2, false));
assert_eq!(i32::MIN.overflowing_neg(), (i32::MIN, true));
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.7.0 (const: 1.32.0)
```
pub const fn overflowing_shl(self, rhs: u32) -> (i32, bool)
```

Shifts self left by `rhs` bits.

 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift value was larger than or equal to the number of bits. If the shift value is too large, then value is masked (N-1) where N is the number of bits, and this value is then used to perform the shift.

 ##### Examples

 Basic usage:

 
```
assert_eq!(0x1i32.overflowing_shl(4), (0x10, false));
assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.7.0 (const: 1.32.0)
```
pub const fn overflowing_shr(self, rhs: u32) -> (i32, bool)
```

Shifts self right by `rhs` bits.

 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift value was larger than or equal to the number of bits. If the shift value is too large, then value is masked (N-1) where N is the number of bits, and this value is then used to perform the shift.

 ##### Examples

 Basic usage:

 
```
assert_eq!(0x10i32.overflowing_shr(4), (0x1, false));
assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.13.0 (const: 1.32.0)
```
pub const fn overflowing_abs(self) -> (i32, bool)
```

Computes the absolute value of `self`.

 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow happened. If self is the minimum value (e.g., i32::MIN for values of type i32), then the minimum value will be returned again and true will be returned for an overflow happening.

 ##### Examples

 Basic usage:

 
```
assert_eq!(10i32.overflowing_abs(), (10, false));
assert_eq!((-10i32).overflowing_abs(), (10, false));
assert_eq!((i32::MIN).overflowing_abs(), (i32::MIN, true));
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.34.0 (const: 1.50.0)
```
pub const fn overflowing_pow(self, exp: u32) -> (i32, bool)
```

Raises self to the power of `exp`, using exponentiation by squaring.

 Returns a tuple of the exponentiation along with a bool indicating whether an overflow happened.

 ##### Examples

 Basic usage:

 
```
assert_eq!(3i32.overflowing_pow(4), (81, false));
assert_eq!(3i8.overflowing_pow(5), (-13, true));
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: 1.50.0
```
pub const fn pow(self, exp: u32) -> i32
```

Raises self to the power of `exp`, using exponentiation by squaring.

 ##### Examples

 Basic usage:

 
```
let x: i32 = 2; // or any other integer type

assert_eq!(x.pow(5), 32);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.38.0 (const: 1.52.0)
```
pub const fn div_euclid(self, rhs: i32) -> i32
```

Calculates the quotient of Euclidean division of `self` by `rhs`.

 This computes the integer `q` such that `self = q * rhs + r`, with `r = self.rem_euclid(rhs)` and `0 <= r < abs(rhs)`.

 In other words, the result is `self / rhs` rounded to the integer `q` such that `self >= q * rhs`. If `self > 0`, this is equal to round towards zero (the default in Rust); if `self < 0`, this is equal to round towards +/- infinity.

 ##### Panics

 This function will panic if `rhs` is 0 or the division results in overflow.

 ##### Examples

 Basic usage:

 
```
let a: i32 = 7; // or any other integer type
let b = 4;

assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.38.0 (const: 1.52.0)
```
pub const fn rem_euclid(self, rhs: i32) -> i32
```

Calculates the least nonnegative remainder of `self (mod rhs)`.

 This is done as if by the Euclidean division algorithm – given `r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) + r`, and `0 <= r < abs(rhs)`.

 ##### Panics

 This function will panic if `rhs` is 0 or the division results in overflow.

 ##### Examples

 Basic usage:

 
```
let a: i32 = 7; // or any other integer type
let b = 4;

assert_eq!(a.rem_euclid(b), 3);
assert_eq!((-a).rem_euclid(b), 1);
assert_eq!(a.rem_euclid(-b), 3);
assert_eq!((-a).rem_euclid(-b), 1);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)
```
pub const fn div_floor(self, rhs: i32) -> i32
```

🔬This is a nightly-only experimental API. (`int_roundings` [#88581](https://github.com/rust-lang/rust/issues/88581))

Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.

 ##### Panics

 This function will panic if `rhs` is zero.

 ###### [Overflow behavior](#overflow-behavior)

 On overflow, this function will panic if overflow checks are enabled (default in debug mode) and wrap if overflow checks are disabled (default in release mode).

 ##### Examples

 Basic usage:

 
```
#![feature(int_roundings)]
let a: i32 = 8;
let b = 3;

assert_eq!(a.div_floor(b), 2);
assert_eq!(a.div_floor(-b), -3);
assert_eq!((-a).div_floor(b), -3);
assert_eq!((-a).div_floor(-b), 2);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)
```
pub const fn div_ceil(self, rhs: i32) -> i32
```

🔬This is a nightly-only experimental API. (`int_roundings` [#88581](https://github.com/rust-lang/rust/issues/88581))

Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.

 ##### Panics

 This function will panic if `rhs` is zero.

 ###### [Overflow behavior](#overflow-behavior-1)

 On overflow, this function will panic if overflow checks are enabled (default in debug mode) and wrap if overflow checks are disabled (default in release mode).

 ##### Examples

 Basic usage:

 
```
#![feature(int_roundings)]
let a: i32 = 8;
let b = 3;

assert_eq!(a.div_ceil(b), 3);
assert_eq!(a.div_ceil(-b), -2);
assert_eq!((-a).div_ceil(b), -2);
assert_eq!((-a).div_ceil(-b), 3);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)
```
pub const fn next_multiple_of(self, rhs: i32) -> i32
```

🔬This is a nightly-only experimental API. (`int_roundings` [#88581](https://github.com/rust-lang/rust/issues/88581))

If `rhs` is positive, calculates the smallest value greater than or equal to `self` that is a multiple of `rhs`. If `rhs` is negative, calculates the largest value less than or equal to `self` that is a multiple of `rhs`.

 ##### Panics

 This function will panic if `rhs` is zero.

 ###### [Overflow behavior](#overflow-behavior-2)

 On overflow, this function will panic if overflow checks are enabled (default in debug mode) and wrap if overflow checks are disabled (default in release mode).

 ##### Examples

 Basic usage:

 
```
#![feature(int_roundings)]
assert_eq!(16_i32.next_multiple_of(8), 16);
assert_eq!(23_i32.next_multiple_of(8), 24);
assert_eq!(16_i32.next_multiple_of(-8), 16);
assert_eq!(23_i32.next_multiple_of(-8), 16);
assert_eq!((-16_i32).next_multiple_of(8), -16);
assert_eq!((-23_i32).next_multiple_of(8), -16);
assert_eq!((-16_i32).next_multiple_of(-8), -16);
assert_eq!((-23_i32).next_multiple_of(-8), -24);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)
```
pub const fn checked_next_multiple_of(self, rhs: i32) -> Option<i32>
```

🔬This is a nightly-only experimental API. (`int_roundings` [#88581](https://github.com/rust-lang/rust/issues/88581))

If `rhs` is positive, calculates the smallest value greater than or equal to `self` that is a multiple of `rhs`. If `rhs` is negative, calculates the largest value less than or equal to `self` that is a multiple of `rhs`. Returns `None` if `rhs` is zero or the operation would result in overflow.

 ##### Examples

 Basic usage:

 
```
#![feature(int_roundings)]
assert_eq!(16_i32.checked_next_multiple_of(8), Some(16));
assert_eq!(23_i32.checked_next_multiple_of(8), Some(24));
assert_eq!(16_i32.checked_next_multiple_of(-8), Some(16));
assert_eq!(23_i32.checked_next_multiple_of(-8), Some(16));
assert_eq!((-16_i32).checked_next_multiple_of(8), Some(-16));
assert_eq!((-23_i32).checked_next_multiple_of(8), Some(-16));
assert_eq!((-16_i32).checked_next_multiple_of(-8), Some(-16));
assert_eq!((-23_i32).checked_next_multiple_of(-8), Some(-24));
assert_eq!(1_i32.checked_next_multiple_of(0), None);
assert_eq!(i32::MAX.checked_next_multiple_of(2), None);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: [unstable](https://github.com/rust-lang/rust/issues/110840 "Tracking issue for const_num_midpoint")
```
pub fn midpoint(self, rhs: i32) -> i32
```

🔬This is a nightly-only experimental API. (`num_midpoint` [#110840](https://github.com/rust-lang/rust/issues/110840))

Calculates the middle point of `self` and `rhs`.

 `midpoint(a, b)` is `(a + b) >> 1` as if it were performed in a sufficiently-large signed integral type. This implies that the result is always rounded towards negative infinity and that no overflow will ever occur.

 ##### Examples

 
```
#![feature(num_midpoint)]
assert_eq!(0i32.midpoint(4), 2);
assert_eq!(0i32.midpoint(-1), -1);
assert_eq!((-1i32).midpoint(0), -1);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.67.0 (const: 1.67.0)
```
pub const fn ilog(self, base: i32) -> u32
```

Returns the logarithm of the number with respect to an arbitrary base, rounded down.

 This method might not be optimized owing to implementation details; `ilog2` can produce results more efficiently for base 2, and `ilog10` can produce results more efficiently for base 10.

 ##### Panics

 This function will panic if `self` is less than or equal to zero, or if `base` is less than 2.

 ##### Examples

 
```
assert_eq!(5i32.ilog(5), 1);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.67.0 (const: 1.67.0)
```
pub const fn ilog2(self) -> u32
```

Returns the base 2 logarithm of the number, rounded down.

 ##### Panics

 This function will panic if `self` is less than or equal to zero.

 ##### Examples

 
```
assert_eq!(2i32.ilog2(), 1);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.67.0 (const: 1.67.0)
```
pub const fn ilog10(self) -> u32
```

Returns the base 10 logarithm of the number, rounded down.

 ##### Panics

 This function will panic if `self` is less than or equal to zero.

 ##### Example

 
```
assert_eq!(10i32.ilog10(), 1);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.67.0 (const: 1.67.0)
```
pub const fn checked_ilog(self, base: i32) -> Option<u32>
```

Returns the logarithm of the number with respect to an arbitrary base, rounded down.

 Returns `None` if the number is negative or zero, or if the base is not at least 2.

 This method might not be optimized owing to implementation details; `checked_ilog2` can produce results more efficiently for base 2, and `checked_ilog10` can produce results more efficiently for base 10.

 ##### Examples

 
```
assert_eq!(5i32.checked_ilog(5), Some(1));
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.67.0 (const: 1.67.0)
```
pub const fn checked_ilog2(self) -> Option<u32>
```

Returns the base 2 logarithm of the number, rounded down.

 Returns `None` if the number is negative or zero.

 ##### Examples

 
```
assert_eq!(2i32.checked_ilog2(), Some(1));
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.67.0 (const: 1.67.0)
```
pub const fn checked_ilog10(self) -> Option<u32>
```

Returns the base 10 logarithm of the number, rounded down.

 Returns `None` if the number is negative or zero.

 ##### Example

 
```
assert_eq!(10i32.checked_ilog10(), Some(1));
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: 1.32.0
```
pub const fn abs(self) -> i32
```

Computes the absolute value of `self`.

 ##### Overflow behavior

 The absolute value of `i32::MIN` cannot be represented as an `i32`, and attempting to calculate it will cause an overflow. This means that code in debug mode will trigger a panic on this case and optimized code will return `i32::MIN` without a panic.

 ##### Examples

 Basic usage:

 
```
assert_eq!(10i32.abs(), 10);
assert_eq!((-10i32).abs(), 10);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.60.0 (const: 1.60.0)
```
pub const fn abs_diff(self, other: i32) -> u32
```

Computes the absolute difference between `self` and `other`.

 This function always returns the correct answer without overflow or panics by returning an unsigned integer.

 ##### Examples

 Basic usage:

 
```
assert_eq!(100i32.abs_diff(80), 20u32);
assert_eq!(100i32.abs_diff(110), 10u32);
assert_eq!((-100i32).abs_diff(80), 180u32);
assert_eq!((-100i32).abs_diff(-120), 20u32);
assert_eq!(i32::MIN.abs_diff(i32::MAX), u32::MAX);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: 1.47.0
```
pub const fn signum(self) -> i32
```

Returns a number representing sign of `self`.

 * `0` if the number is zero
* `1` if the number is positive
* `-1` if the number is negative

 ##### Examples

 Basic usage:

 
```
assert_eq!(10i32.signum(), 1);
assert_eq!(0i32.signum(), 0);
assert_eq!((-10i32).signum(), -1);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: 1.32.0
```
pub const fn is_positive(self) -> bool
```

Returns `true` if `self` is positive and `false` if the number is zero or negative.

 ##### Examples

 Basic usage:

 
```
assert!(10i32.is_positive());
assert!(!(-10i32).is_positive());
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: 1.32.0
```
pub const fn is_negative(self) -> bool
```

Returns `true` if `self` is negative and `false` if the number is zero or positive.

 ##### Examples

 Basic usage:

 
```
assert!((-10i32).is_negative());
assert!(!10i32.is_negative());
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.32.0 (const: 1.44.0)
```
pub const fn to_be_bytes(self) -> [u8; 4]
```

Return the memory representation of this integer as a byte array in big-endian (network) byte order.

 ##### Examples

 
```
let bytes = 0x12345678i32.to_be_bytes();
assert_eq!(bytes, [0x12, 0x34, 0x56, 0x78]);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.32.0 (const: 1.44.0)
```
pub const fn to_le_bytes(self) -> [u8; 4]
```

Return the memory representation of this integer as a byte array in little-endian byte order.

 ##### Examples

 
```
let bytes = 0x12345678i32.to_le_bytes();
assert_eq!(bytes, [0x78, 0x56, 0x34, 0x12]);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.32.0 (const: 1.44.0)
```
pub const fn to_ne_bytes(self) -> [u8; 4]
```

Return the memory representation of this integer as a byte array in native byte order.

 As the target platform’s native endianness is used, portable code should use [`to_be_bytes`](primitive.i32#method.to_be_bytes "method i32::to_be_bytes") or [`to_le_bytes`](primitive.i32#method.to_le_bytes "method i32::to_le_bytes"), as appropriate, instead.

 ##### Examples

 
```
let bytes = 0x12345678i32.to_ne_bytes();
assert_eq!(
    bytes,
    if cfg!(target_endian = "big") {
        [0x12, 0x34, 0x56, 0x78]
    } else {
        [0x78, 0x56, 0x34, 0x12]
    }
);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.32.0 (const: 1.44.0)
```
pub const fn from_be_bytes(bytes: [u8; 4]) -> i32
```

Create an integer value from its representation as a byte array in big endian.

 ##### Examples

 
```
let value = i32::from_be_bytes([0x12, 0x34, 0x56, 0x78]);
assert_eq!(value, 0x12345678);
```
 When starting from a slice rather than an array, fallible conversion APIs can be used:

 
```
fn read_be_i32(input: &mut &[u8]) -> i32 {
    let (int_bytes, rest) = input.split_at(std::mem::size_of::<i32>());
    *input = rest;
    i32::from_be_bytes(int_bytes.try_into().unwrap())
}
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.32.0 (const: 1.44.0)
```
pub const fn from_le_bytes(bytes: [u8; 4]) -> i32
```

Create an integer value from its representation as a byte array in little endian.

 ##### Examples

 
```
let value = i32::from_le_bytes([0x78, 0x56, 0x34, 0x12]);
assert_eq!(value, 0x12345678);
```
 When starting from a slice rather than an array, fallible conversion APIs can be used:

 
```
fn read_le_i32(input: &mut &[u8]) -> i32 {
    let (int_bytes, rest) = input.split_at(std::mem::size_of::<i32>());
    *input = rest;
    i32::from_le_bytes(int_bytes.try_into().unwrap())
}
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)1.32.0 (const: 1.44.0)
```
pub const fn from_ne_bytes(bytes: [u8; 4]) -> i32
```

Create an integer value from its memory representation as a byte array in native endianness.

 As the target platform’s native endianness is used, portable code likely wants to use [`from_be_bytes`](primitive.i32#method.from_be_bytes "associated function i32::from_be_bytes") or [`from_le_bytes`](primitive.i32#method.from_le_bytes "associated function i32::from_le_bytes"), as appropriate instead.

 ##### Examples

 
```
let value = i32::from_ne_bytes(if cfg!(target_endian = "big") {
    [0x12, 0x34, 0x56, 0x78]
} else {
    [0x78, 0x56, 0x34, 0x12]
});
assert_eq!(value, 0x12345678);
```
 When starting from a slice rather than an array, fallible conversion APIs can be used:

 
```
fn read_ne_i32(input: &mut &[u8]) -> i32 {
    let (int_bytes, rest) = input.split_at(std::mem::size_of::<i32>());
    *input = rest;
    i32::from_ne_bytes(int_bytes.try_into().unwrap())
}
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: 1.32.0
```
pub const fn min_value() -> i32
```

👎Deprecating in a future Rust version: replaced by the `MIN` associated constant on this type

New code should prefer to use [`i32::MIN`](primitive.i32#associatedconstant.MIN "associated constant i32::MIN") instead.

 Returns the smallest value that can be represented by this integer type.

 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#343-362)const: 1.32.0
```
pub const fn max_value() -> i32
```

👎Deprecating in a future Rust version: replaced by the `MAX` associated constant on this type

New code should prefer to use [`i32::MAX`](primitive.i32#associatedconstant.MAX "associated constant i32::MAX") instead.

 Returns the largest value that can be represented by this integer type.

 


Trait Implementations
---------------------



[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#109)
```
impl Add<&i32> for &i32
```


```
type Output = <i32 as Add<i32>>::Output
```
The resulting type after applying the `+` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#109)
```
fn add(self, other: &i32) -> <i32 as Add<i32>>::Output
```
Performs the `+` operation. [Read more](ops/trait.add#tymethod.add)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#109)
```
impl Add<&i32> for i32
```


```
type Output = <i32 as Add<i32>>::Output
```
The resulting type after applying the `+` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#109)
```
fn add(self, other: &i32) -> <i32 as Add<i32>>::Output
```
Performs the `+` operation. [Read more](ops/trait.add#tymethod.add)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#109)
```
impl<'a> Add<i32> for &'a i32
```


```
type Output = <i32 as Add<i32>>::Output
```
The resulting type after applying the `+` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#109)
```
fn add(self, other: i32) -> <i32 as Add<i32>>::Output
```
Performs the `+` operation. [Read more](ops/trait.add#tymethod.add)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#109)
```
impl Add<i32> for i32
```


```
type Output = i32
```
The resulting type after applying the `+` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#109)
```
fn add(self, other: i32) -> i32
```
Performs the `+` operation. [Read more](ops/trait.add#tymethod.add)


[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)1.22.0
```
impl AddAssign<&i32> for Saturating<i32>
```

[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)
```
fn add_assign(&mut self, other: &i32)
```
Performs the `+=` operation. [Read more](ops/trait.addassign#tymethod.add_assign)


[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)1.22.0
```
impl AddAssign<&i32> for Wrapping<i32>
```

[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)
```
fn add_assign(&mut self, other: &i32)
```
Performs the `+=` operation. [Read more](ops/trait.addassign#tymethod.add_assign)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#760)1.22.0
```
impl AddAssign<&i32> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#760)
```
fn add_assign(&mut self, other: &i32)
```
Performs the `+=` operation. [Read more](ops/trait.addassign#tymethod.add_assign)


[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)
```
impl AddAssign<i32> for Saturating<i32>
```

[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)
```
fn add_assign(&mut self, other: i32)
```
Performs the `+=` operation. [Read more](ops/trait.addassign#tymethod.add_assign)


[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)1.60.0
```
impl AddAssign<i32> for Wrapping<i32>
```

[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)
```
fn add_assign(&mut self, other: i32)
```
Performs the `+=` operation. [Read more](ops/trait.addassign#tymethod.add_assign)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#760)1.8.0
```
impl AddAssign<i32> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#760)
```
fn add_assign(&mut self, other: i32)
```
Performs the `+=` operation. [Read more](ops/trait.addassign#tymethod.add_assign)


[source](https://doc.rust-lang.org/src/core/fmt/num.rs.html#181)
```
impl Binary for i32
```

[source](https://doc.rust-lang.org/src/core/fmt/num.rs.html#181)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter.

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#178)
```
impl BitAnd<&i32> for &i32
```


```
type Output = <i32 as BitAnd<i32>>::Output
```
The resulting type after applying the `&` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#178)
```
fn bitand(self, other: &i32) -> <i32 as BitAnd<i32>>::Output
```
Performs the `&` operation. [Read more](ops/trait.bitand#tymethod.bitand)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#178)
```
impl BitAnd<&i32> for i32
```


```
type Output = <i32 as BitAnd<i32>>::Output
```
The resulting type after applying the `&` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#178)
```
fn bitand(self, other: &i32) -> <i32 as BitAnd<i32>>::Output
```
Performs the `&` operation. [Read more](ops/trait.bitand#tymethod.bitand)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#178)
```
impl<'a> BitAnd<i32> for &'a i32
```


```
type Output = <i32 as BitAnd<i32>>::Output
```
The resulting type after applying the `&` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#178)
```
fn bitand(self, other: i32) -> <i32 as BitAnd<i32>>::Output
```
Performs the `&` operation. [Read more](ops/trait.bitand#tymethod.bitand)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#178)
```
impl BitAnd<i32> for i32
```


```
type Output = i32
```
The resulting type after applying the `&` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#178)
```
fn bitand(self, rhs: i32) -> i32
```
Performs the `&` operation. [Read more](ops/trait.bitand#tymethod.bitand)


[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)1.22.0
```
impl BitAndAssign<&i32> for Saturating<i32>
```

[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)
```
fn bitand_assign(&mut self, other: &i32)
```
Performs the `&=` operation. [Read more](ops/trait.bitandassign#tymethod.bitand_assign)


[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)1.22.0
```
impl BitAndAssign<&i32> for Wrapping<i32>
```

[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)
```
fn bitand_assign(&mut self, other: &i32)
```
Performs the `&=` operation. [Read more](ops/trait.bitandassign#tymethod.bitand_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#726)1.22.0
```
impl BitAndAssign<&i32> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#726)
```
fn bitand_assign(&mut self, other: &i32)
```
Performs the `&=` operation. [Read more](ops/trait.bitandassign#tymethod.bitand_assign)


[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)
```
impl BitAndAssign<i32> for Saturating<i32>
```

[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)
```
fn bitand_assign(&mut self, other: i32)
```
Performs the `&=` operation. [Read more](ops/trait.bitandassign#tymethod.bitand_assign)


[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)1.60.0
```
impl BitAndAssign<i32> for Wrapping<i32>
```

[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)
```
fn bitand_assign(&mut self, other: i32)
```
Performs the `&=` operation. [Read more](ops/trait.bitandassign#tymethod.bitand_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#726)1.8.0
```
impl BitAndAssign<i32> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#726)
```
fn bitand_assign(&mut self, other: i32)
```
Performs the `&=` operation. [Read more](ops/trait.bitandassign#tymethod.bitand_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#278)
```
impl BitOr<&i32> for &i32
```


```
type Output = <i32 as BitOr<i32>>::Output
```
The resulting type after applying the `|` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#278)
```
fn bitor(self, other: &i32) -> <i32 as BitOr<i32>>::Output
```
Performs the `|` operation. [Read more](ops/trait.bitor#tymethod.bitor)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#278)
```
impl BitOr<&i32> for i32
```


```
type Output = <i32 as BitOr<i32>>::Output
```
The resulting type after applying the `|` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#278)
```
fn bitor(self, other: &i32) -> <i32 as BitOr<i32>>::Output
```
Performs the `|` operation. [Read more](ops/trait.bitor#tymethod.bitor)


[source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#165-178)1.45.0
```
impl BitOr<NonZeroI32> for i32
```


```
type Output = NonZeroI32
```
The resulting type after applying the `|` operator.
[source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#165-178)
```
fn bitor(self, rhs: NonZeroI32) -> <i32 as BitOr<NonZeroI32>>::Output
```
Performs the `|` operation. [Read more](ops/trait.bitor#tymethod.bitor)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#278)
```
impl<'a> BitOr<i32> for &'a i32
```


```
type Output = <i32 as BitOr<i32>>::Output
```
The resulting type after applying the `|` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#278)
```
fn bitor(self, other: i32) -> <i32 as BitOr<i32>>::Output
```
Performs the `|` operation. [Read more](ops/trait.bitor#tymethod.bitor)


[source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#165-178)1.45.0
```
impl BitOr<i32> for NonZeroI32
```


```
type Output = NonZeroI32
```
The resulting type after applying the `|` operator.
[source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#165-178)
```
fn bitor(self, rhs: i32) -> <NonZeroI32 as BitOr<i32>>::Output
```
Performs the `|` operation. [Read more](ops/trait.bitor#tymethod.bitor)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#278)
```
impl BitOr<i32> for i32
```


```
type Output = i32
```
The resulting type after applying the `|` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#278)
```
fn bitor(self, rhs: i32) -> i32
```
Performs the `|` operation. [Read more](ops/trait.bitor#tymethod.bitor)


[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)1.22.0
```
impl BitOrAssign<&i32> for Saturating<i32>
```

[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)
```
fn bitor_assign(&mut self, other: &i32)
```
Performs the `|=` operation. [Read more](ops/trait.bitorassign#tymethod.bitor_assign)


[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)1.22.0
```
impl BitOrAssign<&i32> for Wrapping<i32>
```

[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)
```
fn bitor_assign(&mut self, other: &i32)
```
Performs the `|=` operation. [Read more](ops/trait.bitorassign#tymethod.bitor_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#797)1.22.0
```
impl BitOrAssign<&i32> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#797)
```
fn bitor_assign(&mut self, other: &i32)
```
Performs the `|=` operation. [Read more](ops/trait.bitorassign#tymethod.bitor_assign)


[source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#165-178)1.45.0
```
impl BitOrAssign<i32> for NonZeroI32
```

[source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#165-178)
```
fn bitor_assign(&mut self, rhs: i32)
```
Performs the `|=` operation. [Read more](ops/trait.bitorassign#tymethod.bitor_assign)


[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)
```
impl BitOrAssign<i32> for Saturating<i32>
```

[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)
```
fn bitor_assign(&mut self, other: i32)
```
Performs the `|=` operation. [Read more](ops/trait.bitorassign#tymethod.bitor_assign)


[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)1.60.0
```
impl BitOrAssign<i32> for Wrapping<i32>
```

[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)
```
fn bitor_assign(&mut self, other: i32)
```
Performs the `|=` operation. [Read more](ops/trait.bitorassign#tymethod.bitor_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#797)1.8.0
```
impl BitOrAssign<i32> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#797)
```
fn bitor_assign(&mut self, other: i32)
```
Performs the `|=` operation. [Read more](ops/trait.bitorassign#tymethod.bitor_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#378)
```
impl BitXor<&i32> for &i32
```


```
type Output = <i32 as BitXor<i32>>::Output
```
The resulting type after applying the `^` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#378)
```
fn bitxor(self, other: &i32) -> <i32 as BitXor<i32>>::Output
```
Performs the `^` operation. [Read more](ops/trait.bitxor#tymethod.bitxor)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#378)
```
impl BitXor<&i32> for i32
```


```
type Output = <i32 as BitXor<i32>>::Output
```
The resulting type after applying the `^` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#378)
```
fn bitxor(self, other: &i32) -> <i32 as BitXor<i32>>::Output
```
Performs the `^` operation. [Read more](ops/trait.bitxor#tymethod.bitxor)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#378)
```
impl<'a> BitXor<i32> for &'a i32
```


```
type Output = <i32 as BitXor<i32>>::Output
```
The resulting type after applying the `^` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#378)
```
fn bitxor(self, other: i32) -> <i32 as BitXor<i32>>::Output
```
Performs the `^` operation. [Read more](ops/trait.bitxor#tymethod.bitxor)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#378)
```
impl BitXor<i32> for i32
```


```
type Output = i32
```
The resulting type after applying the `^` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#378)
```
fn bitxor(self, other: i32) -> i32
```
Performs the `^` operation. [Read more](ops/trait.bitxor#tymethod.bitxor)


[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)1.22.0
```
impl BitXorAssign<&i32> for Saturating<i32>
```

[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)
```
fn bitxor_assign(&mut self, other: &i32)
```
Performs the `^=` operation. [Read more](ops/trait.bitxorassign#tymethod.bitxor_assign)


[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)1.22.0
```
impl BitXorAssign<&i32> for Wrapping<i32>
```

[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)
```
fn bitxor_assign(&mut self, other: &i32)
```
Performs the `^=` operation. [Read more](ops/trait.bitxorassign#tymethod.bitxor_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#868)1.22.0
```
impl BitXorAssign<&i32> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#868)
```
fn bitxor_assign(&mut self, other: &i32)
```
Performs the `^=` operation. [Read more](ops/trait.bitxorassign#tymethod.bitxor_assign)


[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)
```
impl BitXorAssign<i32> for Saturating<i32>
```

[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)
```
fn bitxor_assign(&mut self, other: i32)
```
Performs the `^=` operation. [Read more](ops/trait.bitxorassign#tymethod.bitxor_assign)


[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)1.60.0
```
impl BitXorAssign<i32> for Wrapping<i32>
```

[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)
```
fn bitxor_assign(&mut self, other: i32)
```
Performs the `^=` operation. [Read more](ops/trait.bitxorassign#tymethod.bitxor_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#868)1.8.0
```
impl BitXorAssign<i32> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#868)
```
fn bitxor_assign(&mut self, other: i32)
```
Performs the `^=` operation. [Read more](ops/trait.bitxorassign#tymethod.bitxor_assign)


[source](https://doc.rust-lang.org/src/core/clone.rs.html#189-194)
```
impl Clone for i32
```

[source](https://doc.rust-lang.org/src/core/clone.rs.html#189-194)
```
fn clone(&self) -> i32
```
Returns a copy of the value. [Read more](clone/trait.clone#tymethod.clone)

[source](https://doc.rust-lang.org/src/core/clone.rs.html#129)
```
fn clone_from(&mut self, source: &Self)
```
Performs copy-assignment from `source`. [Read more](clone/trait.clone#method.clone_from)


[source](https://doc.rust-lang.org/src/core/fmt/num.rs.html#201-204)
```
impl Debug for i32
```

[source](https://doc.rust-lang.org/src/core/fmt/num.rs.html#201-204)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter. [Read more](fmt/trait.debug#tymethod.fmt)


[source](https://doc.rust-lang.org/src/core/default.rs.html#216)
```
impl Default for i32
```

[source](https://doc.rust-lang.org/src/core/default.rs.html#216)
```
fn default() -> i32
```

Returns the default value of `0`

 

[source](https://doc.rust-lang.org/src/core/fmt/num.rs.html#466-469)
```
impl Display for i32
```

[source](https://doc.rust-lang.org/src/core/fmt/num.rs.html#466-469)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter. [Read more](fmt/trait.display#tymethod.fmt)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#484-487)
```
impl Div<&i32> for &i32
```


```
type Output = <i32 as Div<i32>>::Output
```
The resulting type after applying the `/` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#484-487)
```
fn div(self, other: &i32) -> <i32 as Div<i32>>::Output
```
Performs the `/` operation. [Read more](ops/trait.div#tymethod.div)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#484-487)
```
impl Div<&i32> for i32
```


```
type Output = <i32 as Div<i32>>::Output
```
The resulting type after applying the `/` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#484-487)
```
fn div(self, other: &i32) -> <i32 as Div<i32>>::Output
```
Performs the `/` operation. [Read more](ops/trait.div#tymethod.div)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#484-487)
```
impl<'a> Div<i32> for &'a i32
```


```
type Output = <i32 as Div<i32>>::Output
```
The resulting type after applying the `/` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#484-487)
```
fn div(self, other: i32) -> <i32 as Div<i32>>::Output
```
Performs the `/` operation. [Read more](ops/trait.div#tymethod.div)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#484-487)
```
impl Div<i32> for i32
```

This operation rounds towards zero, truncating any fractional part of the exact result.

 #### Panics

 This operation will panic if `other == 0` or the division results in overflow.

 


```
type Output = i32
```
The resulting type after applying the `/` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#484-487)
```
fn div(self, other: i32) -> i32
```
Performs the `/` operation. [Read more](ops/trait.div#tymethod.div)


[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)1.22.0
```
impl DivAssign<&i32> for Saturating<i32>
```

[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)
```
fn div_assign(&mut self, other: &i32)
```
Performs the `/=` operation. [Read more](ops/trait.divassign#tymethod.div_assign)


[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)1.22.0
```
impl DivAssign<&i32> for Wrapping<i32>
```

[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)
```
fn div_assign(&mut self, other: &i32)
```
Performs the `/=` operation. [Read more](ops/trait.divassign#tymethod.div_assign)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#939)1.22.0
```
impl DivAssign<&i32> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#939)
```
fn div_assign(&mut self, other: &i32)
```
Performs the `/=` operation. [Read more](ops/trait.divassign#tymethod.div_assign)


[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)
```
impl DivAssign<i32> for Saturating<i32>
```

[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)
```
fn div_assign(&mut self, other: i32)
```
Performs the `/=` operation. [Read more](ops/trait.divassign#tymethod.div_assign)


[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)1.60.0
```
impl DivAssign<i32> for Wrapping<i32>
```

[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)
```
fn div_assign(&mut self, other: i32)
```
Performs the `/=` operation. [Read more](ops/trait.divassign#tymethod.div_assign)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#939)1.8.0
```
impl DivAssign<i32> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#939)
```
fn div_assign(&mut self, other: i32)
```
Performs the `/=` operation. [Read more](ops/trait.divassign#tymethod.div_assign)


[source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#165-178)1.31.0
```
impl From<NonZeroI32> for i32
```

[source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#165-178)
```
fn from(nonzero: NonZeroI32) -> i32
```

Converts a `NonZeroI32` into an `i32`

 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#93)1.28.0
```
impl From<bool> for i32
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#93)
```
fn from(small: bool) -> i32
```

Converts a `bool` to a `i32`. The resulting value is `0` for `false` and `1` for `true` values.

 ##### Examples

 
```
assert_eq!(i32::from(true), 1);
assert_eq!(i32::from(false), 0);
```
 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#117)1.5.0
```
impl From<i16> for i32
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#117)
```
fn from(small: i16) -> i32
```

Converts `i16` to `i32` losslessly.

 

[source](https://doc.rust-lang.org/src/core/sync/atomic.rs.html#2947-2965)1.34.0
```
impl From<i32> for AtomicI32
```

[source](https://doc.rust-lang.org/src/core/sync/atomic.rs.html#2947-2965)
```
fn from(v: i32) -> AtomicI32
```

Converts an `i32` into an `AtomicI32`.

 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#158)1.6.0
```
impl From<i32> for f64
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#158)
```
fn from(small: i32) -> f64
```

Converts `i32` to `f64` losslessly.

 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#121)1.26.0
```
impl From<i32> for i128
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#121)
```
fn from(small: i32) -> i128
```

Converts `i32` to `i128` losslessly.

 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#120)1.5.0
```
impl From<i32> for i64
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#120)
```
fn from(small: i32) -> i64
```

Converts `i32` to `i64` losslessly.

 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#113)1.5.0
```
impl From<i8> for i32
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#113)
```
fn from(small: i8) -> i32
```

Converts `i8` to `i32` losslessly.

 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#129)1.5.0
```
impl From<u16> for i32
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#129)
```
fn from(small: u16) -> i32
```

Converts `u16` to `i32` losslessly.

 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#126)1.5.0
```
impl From<u8> for i32
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#126)
```
fn from(small: u8) -> i32
```

Converts `u8` to `i32` losslessly.

 

[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#1404)
```
impl FromStr for i32
```


```
type Err = ParseIntError
```
The associated error which can be returned from parsing.
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#1404)
```
fn from_str(src: &str) -> Result<i32, ParseIntError>
```
Parses a string `s` to return a value of this type. [Read more](str/trait.fromstr#tymethod.from_str)


[source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#827-840)
```
impl Hash for i32
```

[source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#827-840)
```
fn hash<H>(&self, state: &mut H)
where
    H: Hasher,
```
Feeds this value into the given [`Hasher`](hash/trait.hasher "trait std::hash::Hasher"). [Read more](hash/trait.hash#tymethod.hash)

[source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#827-840)
```
fn hash_slice<H>(data: &[i32], state: &mut H)
where
    H: Hasher,
```
Feeds a slice of this type into the given [`Hasher`](hash/trait.hasher "trait std::hash::Hasher"). [Read more](hash/trait.hash#method.hash_slice)


[source](https://doc.rust-lang.org/src/core/fmt/num.rs.html#470-473)1.42.0
```
impl LowerExp for i32
```

[source](https://doc.rust-lang.org/src/core/fmt/num.rs.html#470-473)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter.

[source](https://doc.rust-lang.org/src/core/fmt/num.rs.html#181)
```
impl LowerHex for i32
```

[source](https://doc.rust-lang.org/src/core/fmt/num.rs.html#181)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter.

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#346)
```
impl Mul<&i32> for &i32
```


```
type Output = <i32 as Mul<i32>>::Output
```
The resulting type after applying the `*` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#346)
```
fn mul(self, other: &i32) -> <i32 as Mul<i32>>::Output
```
Performs the `*` operation. [Read more](ops/trait.mul#tymethod.mul)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#346)
```
impl Mul<&i32> for i32
```


```
type Output = <i32 as Mul<i32>>::Output
```
The resulting type after applying the `*` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#346)
```
fn mul(self, other: &i32) -> <i32 as Mul<i32>>::Output
```
Performs the `*` operation. [Read more](ops/trait.mul#tymethod.mul)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#346)
```
impl<'a> Mul<i32> for &'a i32
```


```
type Output = <i32 as Mul<i32>>::Output
```
The resulting type after applying the `*` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#346)
```
fn mul(self, other: i32) -> <i32 as Mul<i32>>::Output
```
Performs the `*` operation. [Read more](ops/trait.mul#tymethod.mul)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#346)
```
impl Mul<i32> for i32
```


```
type Output = i32
```
The resulting type after applying the `*` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#346)
```
fn mul(self, other: i32) -> i32
```
Performs the `*` operation. [Read more](ops/trait.mul#tymethod.mul)


[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)1.22.0
```
impl MulAssign<&i32> for Saturating<i32>
```

[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)
```
fn mul_assign(&mut self, other: &i32)
```
Performs the `*=` operation. [Read more](ops/trait.mulassign#tymethod.mul_assign)


[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)1.22.0
```
impl MulAssign<&i32> for Wrapping<i32>
```

[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)
```
fn mul_assign(&mut self, other: &i32)
```
Performs the `*=` operation. [Read more](ops/trait.mulassign#tymethod.mul_assign)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#883)1.22.0
```
impl MulAssign<&i32> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#883)
```
fn mul_assign(&mut self, other: &i32)
```
Performs the `*=` operation. [Read more](ops/trait.mulassign#tymethod.mul_assign)


[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)
```
impl MulAssign<i32> for Saturating<i32>
```

[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)
```
fn mul_assign(&mut self, other: i32)
```
Performs the `*=` operation. [Read more](ops/trait.mulassign#tymethod.mul_assign)


[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)1.60.0
```
impl MulAssign<i32> for Wrapping<i32>
```

[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)
```
fn mul_assign(&mut self, other: i32)
```
Performs the `*=` operation. [Read more](ops/trait.mulassign#tymethod.mul_assign)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#883)1.8.0
```
impl MulAssign<i32> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#883)
```
fn mul_assign(&mut self, other: i32)
```
Performs the `*=` operation. [Read more](ops/trait.mulassign#tymethod.mul_assign)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#694)
```
impl Neg for &i32
```


```
type Output = <i32 as Neg>::Output
```
The resulting type after applying the `-` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#694)
```
fn neg(self) -> <i32 as Neg>::Output
```
Performs the unary `-` operation. [Read more](ops/trait.neg#tymethod.neg)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#694)
```
impl Neg for i32
```


```
type Output = i32
```
The resulting type after applying the `-` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#694)
```
fn neg(self) -> i32
```
Performs the unary `-` operation. [Read more](ops/trait.neg#tymethod.neg)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#68)
```
impl Not for &i32
```


```
type Output = <i32 as Not>::Output
```
The resulting type after applying the `!` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#68)
```
fn not(self) -> <i32 as Not>::Output
```
Performs the unary `!` operation. [Read more](ops/trait.not#tymethod.not)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#68)
```
impl Not for i32
```


```
type Output = i32
```
The resulting type after applying the `!` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#68)
```
fn not(self) -> i32
```
Performs the unary `!` operation. [Read more](ops/trait.not#tymethod.not)


[source](https://doc.rust-lang.org/src/core/fmt/num.rs.html#181)
```
impl Octal for i32
```

[source](https://doc.rust-lang.org/src/core/fmt/num.rs.html#181)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter.

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1411)
```
impl Ord for i32
```

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1411)
```
fn cmp(&self, other: &i32) -> Ordering
```
This method returns an [`Ordering`](cmp/enum.ordering "enum std::cmp::Ordering") between `self` and `other`. [Read more](cmp/trait.ord#tymethod.cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#790-792)1.21.0
```
fn max(self, other: Self) -> Self
where
    Self: Sized,
```
Compares and returns the maximum of two values. [Read more](cmp/trait.ord#method.max)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#810-812)1.21.0
```
fn min(self, other: Self) -> Self
where
    Self: Sized,
```
Compares and returns the minimum of two values. [Read more](cmp/trait.ord#method.min)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#835-838)1.50.0
```
fn clamp(self, min: Self, max: Self) -> Self
where
    Self: Sized + PartialOrd<Self>,
```
Restrict a value to a certain interval. [Read more](cmp/trait.ord#method.clamp)


[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1298-1300)
```
impl PartialEq<i32> for i32
```

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1298-1300)
```
fn eq(&self, other: &i32) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1298-1300)
```
fn ne(&self, other: &i32) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1411)
```
impl PartialOrd<i32> for i32
```

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1411)
```
fn partial_cmp(&self, other: &i32) -> Option<Ordering>
```
This method returns an ordering between `self` and `other` values if one exists. [Read more](cmp/trait.partialord#tymethod.partial_cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1411)
```
fn lt(&self, other: &i32) -> bool
```
This method tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](cmp/trait.partialord#method.lt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1411)
```
fn le(&self, other: &i32) -> bool
```
This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](cmp/trait.partialord#method.le)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1411)
```
fn ge(&self, other: &i32) -> bool
```
This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](cmp/trait.partialord#method.ge)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1411)
```
fn gt(&self, other: &i32) -> bool
```
This method tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](cmp/trait.partialord#method.gt)


[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#149)1.12.0
```
impl<'a> Product<&'a i32> for i32
```

[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#149)
```
fn product<I>(iter: I) -> i32
where
    I: Iterator<Item = &'a i32>,
```
Method which takes an iterator and generates `Self` from the elements by multiplying the items.

[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#149)1.12.0
```
impl Product<i32> for i32
```

[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#149)
```
fn product<I>(iter: I) -> i32
where
    I: Iterator<Item = i32>,
```
Method which takes an iterator and generates `Self` from the elements by multiplying the items.

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#585-588)
```
impl Rem<&i32> for &i32
```


```
type Output = <i32 as Rem<i32>>::Output
```
The resulting type after applying the `%` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#585-588)
```
fn rem(self, other: &i32) -> <i32 as Rem<i32>>::Output
```
Performs the `%` operation. [Read more](ops/trait.rem#tymethod.rem)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#585-588)
```
impl Rem<&i32> for i32
```


```
type Output = <i32 as Rem<i32>>::Output
```
The resulting type after applying the `%` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#585-588)
```
fn rem(self, other: &i32) -> <i32 as Rem<i32>>::Output
```
Performs the `%` operation. [Read more](ops/trait.rem#tymethod.rem)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#585-588)
```
impl<'a> Rem<i32> for &'a i32
```


```
type Output = <i32 as Rem<i32>>::Output
```
The resulting type after applying the `%` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#585-588)
```
fn rem(self, other: i32) -> <i32 as Rem<i32>>::Output
```
Performs the `%` operation. [Read more](ops/trait.rem#tymethod.rem)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#585-588)
```
impl Rem<i32> for i32
```

This operation satisfies `n % d == n - (n / d) * d`. The result has the same sign as the left operand.

 #### Panics

 This operation will panic if `other == 0` or if `self / other` results in overflow.

 


```
type Output = i32
```
The resulting type after applying the `%` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#585-588)
```
fn rem(self, other: i32) -> i32
```
Performs the `%` operation. [Read more](ops/trait.rem#tymethod.rem)


[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)1.22.0
```
impl RemAssign<&i32> for Saturating<i32>
```

[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)
```
fn rem_assign(&mut self, other: &i32)
```
Performs the `%=` operation. [Read more](ops/trait.remassign#tymethod.rem_assign)


[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)1.22.0
```
impl RemAssign<&i32> for Wrapping<i32>
```

[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)
```
fn rem_assign(&mut self, other: &i32)
```
Performs the `%=` operation. [Read more](ops/trait.remassign#tymethod.rem_assign)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#999)1.22.0
```
impl RemAssign<&i32> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#999)
```
fn rem_assign(&mut self, other: &i32)
```
Performs the `%=` operation. [Read more](ops/trait.remassign#tymethod.rem_assign)


[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)
```
impl RemAssign<i32> for Saturating<i32>
```

[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)
```
fn rem_assign(&mut self, other: i32)
```
Performs the `%=` operation. [Read more](ops/trait.remassign#tymethod.rem_assign)


[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)1.60.0
```
impl RemAssign<i32> for Wrapping<i32>
```

[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)
```
fn rem_assign(&mut self, other: i32)
```
Performs the `%=` operation. [Read more](ops/trait.remassign#tymethod.rem_assign)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#999)1.8.0
```
impl RemAssign<i32> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#999)
```
fn rem_assign(&mut self, other: i32)
```
Performs the `%=` operation. [Read more](ops/trait.remassign#tymethod.rem_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i128> for &i32
```


```
type Output = <i32 as Shl<i128>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i128) -> <i32 as Shl<i128>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i128> for i32
```


```
type Output = <i32 as Shl<i128>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i128) -> <i32 as Shl<i128>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i16> for &i32
```


```
type Output = <i32 as Shl<i16>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i16) -> <i32 as Shl<i16>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i16> for i32
```


```
type Output = <i32 as Shl<i16>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i16) -> <i32 as Shl<i16>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i32> for &i128
```


```
type Output = <i128 as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i32) -> <i128 as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i32> for &i16
```


```
type Output = <i16 as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i32) -> <i16 as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i32> for &i32
```


```
type Output = <i32 as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i32) -> <i32 as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i32> for &i64
```


```
type Output = <i64 as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i32) -> <i64 as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i32> for &i8
```


```
type Output = <i8 as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i32) -> <i8 as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i32> for &isize
```


```
type Output = <isize as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i32) -> <isize as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i32> for &u128
```


```
type Output = <u128 as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i32) -> <u128 as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i32> for &u16
```


```
type Output = <u16 as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i32) -> <u16 as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i32> for &u32
```


```
type Output = <u32 as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i32) -> <u32 as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i32> for &u64
```


```
type Output = <u64 as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i32) -> <u64 as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i32> for &u8
```


```
type Output = <u8 as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i32) -> <u8 as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i32> for &usize
```


```
type Output = <usize as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i32) -> <usize as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i32> for i128
```


```
type Output = <i128 as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i32) -> <i128 as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i32> for i16
```


```
type Output = <i16 as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i32) -> <i16 as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i32> for i32
```


```
type Output = <i32 as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i32) -> <i32 as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i32> for i64
```


```
type Output = <i64 as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i32) -> <i64 as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i32> for i8
```


```
type Output = <i8 as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i32) -> <i8 as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i32> for isize
```


```
type Output = <isize as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i32) -> <isize as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i32> for u128
```


```
type Output = <u128 as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i32) -> <u128 as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i32> for u16
```


```
type Output = <u16 as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i32) -> <u16 as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i32> for u32
```


```
type Output = <u32 as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i32) -> <u32 as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i32> for u64
```


```
type Output = <u64 as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i32) -> <u64 as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i32> for u8
```


```
type Output = <u8 as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i32) -> <u8 as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i32> for usize
```


```
type Output = <usize as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i32) -> <usize as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i64> for &i32
```


```
type Output = <i32 as Shl<i64>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i64) -> <i32 as Shl<i64>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i64> for i32
```


```
type Output = <i32 as Shl<i64>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i64) -> <i32 as Shl<i64>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i8> for &i32
```


```
type Output = <i32 as Shl<i8>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i8) -> <i32 as Shl<i8>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&i8> for i32
```


```
type Output = <i32 as Shl<i8>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &i8) -> <i32 as Shl<i8>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&isize> for &i32
```


```
type Output = <i32 as Shl<isize>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &isize) -> <i32 as Shl<isize>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&isize> for i32
```


```
type Output = <i32 as Shl<isize>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &isize) -> <i32 as Shl<isize>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&u128> for &i32
```


```
type Output = <i32 as Shl<u128>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &u128) -> <i32 as Shl<u128>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&u128> for i32
```


```
type Output = <i32 as Shl<u128>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &u128) -> <i32 as Shl<u128>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&u16> for &i32
```


```
type Output = <i32 as Shl<u16>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &u16) -> <i32 as Shl<u16>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&u16> for i32
```


```
type Output = <i32 as Shl<u16>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &u16) -> <i32 as Shl<u16>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&u32> for &i32
```


```
type Output = <i32 as Shl<u32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &u32) -> <i32 as Shl<u32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&u32> for i32
```


```
type Output = <i32 as Shl<u32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &u32) -> <i32 as Shl<u32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&u64> for &i32
```


```
type Output = <i32 as Shl<u64>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &u64) -> <i32 as Shl<u64>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&u64> for i32
```


```
type Output = <i32 as Shl<u64>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &u64) -> <i32 as Shl<u64>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&u8> for &i32
```


```
type Output = <i32 as Shl<u8>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &u8) -> <i32 as Shl<u8>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&u8> for i32
```


```
type Output = <i32 as Shl<u8>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &u8) -> <i32 as Shl<u8>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&usize> for &i32
```


```
type Output = <i32 as Shl<usize>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &usize) -> <i32 as Shl<usize>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<&usize> for i32
```


```
type Output = <i32 as Shl<usize>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: &usize) -> <i32 as Shl<usize>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl<'a> Shl<i128> for &'a i32
```


```
type Output = <i32 as Shl<i128>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i128) -> <i32 as Shl<i128>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<i128> for i32
```


```
type Output = i32
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i128) -> i32
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl<'a> Shl<i16> for &'a i32
```


```
type Output = <i32 as Shl<i16>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i16) -> <i32 as Shl<i16>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<i16> for i32
```


```
type Output = i32
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i16) -> i32
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl<'a> Shl<i32> for &'a i128
```


```
type Output = <i128 as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i32) -> <i128 as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl<'a> Shl<i32> for &'a i16
```


```
type Output = <i16 as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i32) -> <i16 as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl<'a> Shl<i32> for &'a i32
```


```
type Output = <i32 as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i32) -> <i32 as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl<'a> Shl<i32> for &'a i64
```


```
type Output = <i64 as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i32) -> <i64 as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl<'a> Shl<i32> for &'a i8
```


```
type Output = <i8 as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i32) -> <i8 as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl<'a> Shl<i32> for &'a isize
```


```
type Output = <isize as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i32) -> <isize as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl<'a> Shl<i32> for &'a u128
```


```
type Output = <u128 as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i32) -> <u128 as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl<'a> Shl<i32> for &'a u16
```


```
type Output = <u16 as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i32) -> <u16 as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl<'a> Shl<i32> for &'a u32
```


```
type Output = <u32 as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i32) -> <u32 as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl<'a> Shl<i32> for &'a u64
```


```
type Output = <u64 as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i32) -> <u64 as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl<'a> Shl<i32> for &'a u8
```


```
type Output = <u8 as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i32) -> <u8 as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl<'a> Shl<i32> for &'a usize
```


```
type Output = <usize as Shl<i32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i32) -> <usize as Shl<i32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<i32> for i128
```


```
type Output = i128
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i32) -> i128
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<i32> for i16
```


```
type Output = i16
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i32) -> i16
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<i32> for i32
```


```
type Output = i32
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i32) -> i32
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<i32> for i64
```


```
type Output = i64
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i32) -> i64
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<i32> for i8
```


```
type Output = i8
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i32) -> i8
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<i32> for isize
```


```
type Output = isize
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i32) -> isize
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<i32> for u128
```


```
type Output = u128
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i32) -> u128
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<i32> for u16
```


```
type Output = u16
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i32) -> u16
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<i32> for u32
```


```
type Output = u32
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i32) -> u32
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<i32> for u64
```


```
type Output = u64
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i32) -> u64
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<i32> for u8
```


```
type Output = u8
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i32) -> u8
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<i32> for usize
```


```
type Output = usize
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i32) -> usize
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl<'a> Shl<i64> for &'a i32
```


```
type Output = <i32 as Shl<i64>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i64) -> <i32 as Shl<i64>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<i64> for i32
```


```
type Output = i32
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i64) -> i32
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl<'a> Shl<i8> for &'a i32
```


```
type Output = <i32 as Shl<i8>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i8) -> <i32 as Shl<i8>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<i8> for i32
```


```
type Output = i32
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: i8) -> i32
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl<'a> Shl<isize> for &'a i32
```


```
type Output = <i32 as Shl<isize>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: isize) -> <i32 as Shl<isize>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<isize> for i32
```


```
type Output = i32
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: isize) -> i32
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl<'a> Shl<u128> for &'a i32
```


```
type Output = <i32 as Shl<u128>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: u128) -> <i32 as Shl<u128>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<u128> for i32
```


```
type Output = i32
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: u128) -> i32
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl<'a> Shl<u16> for &'a i32
```


```
type Output = <i32 as Shl<u16>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: u16) -> <i32 as Shl<u16>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<u16> for i32
```


```
type Output = i32
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: u16) -> i32
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl<'a> Shl<u32> for &'a i32
```


```
type Output = <i32 as Shl<u32>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: u32) -> <i32 as Shl<u32>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<u32> for i32
```


```
type Output = i32
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: u32) -> i32
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl<'a> Shl<u64> for &'a i32
```


```
type Output = <i32 as Shl<u64>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: u64) -> <i32 as Shl<u64>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<u64> for i32
```


```
type Output = i32
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: u64) -> i32
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl<'a> Shl<u8> for &'a i32
```


```
type Output = <i32 as Shl<u8>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: u8) -> <i32 as Shl<u8>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<u8> for i32
```


```
type Output = i32
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: u8) -> i32
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl<'a> Shl<usize> for &'a i32
```


```
type Output = <i32 as Shl<usize>>::Output
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: usize) -> <i32 as Shl<usize>>::Output
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
impl Shl<usize> for i32
```


```
type Output = i32
```
The resulting type after applying the `<<` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#496)
```
fn shl(self, other: usize) -> i32
```
Performs the `<<` operation. [Read more](ops/trait.shl#tymethod.shl)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.22.0
```
impl ShlAssign<&i128> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: &i128)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.22.0
```
impl ShlAssign<&i16> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: &i16)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.22.0
```
impl ShlAssign<&i32> for i128
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: &i32)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.22.0
```
impl ShlAssign<&i32> for i16
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: &i32)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.22.0
```
impl ShlAssign<&i32> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: &i32)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.22.0
```
impl ShlAssign<&i32> for i64
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: &i32)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.22.0
```
impl ShlAssign<&i32> for i8
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: &i32)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.22.0
```
impl ShlAssign<&i32> for isize
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: &i32)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.22.0
```
impl ShlAssign<&i32> for u128
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: &i32)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.22.0
```
impl ShlAssign<&i32> for u16
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: &i32)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.22.0
```
impl ShlAssign<&i32> for u32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: &i32)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.22.0
```
impl ShlAssign<&i32> for u64
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: &i32)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.22.0
```
impl ShlAssign<&i32> for u8
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: &i32)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.22.0
```
impl ShlAssign<&i32> for usize
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: &i32)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.22.0
```
impl ShlAssign<&i64> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: &i64)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.22.0
```
impl ShlAssign<&i8> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: &i8)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.22.0
```
impl ShlAssign<&isize> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: &isize)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.22.0
```
impl ShlAssign<&u128> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: &u128)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.22.0
```
impl ShlAssign<&u16> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: &u16)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.22.0
```
impl ShlAssign<&u32> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: &u32)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.22.0
```
impl ShlAssign<&u64> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: &u64)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.22.0
```
impl ShlAssign<&u8> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: &u8)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.22.0
```
impl ShlAssign<&usize> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: &usize)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.8.0
```
impl ShlAssign<i128> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: i128)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.8.0
```
impl ShlAssign<i16> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: i16)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.8.0
```
impl ShlAssign<i32> for i128
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: i32)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.8.0
```
impl ShlAssign<i32> for i16
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: i32)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.8.0
```
impl ShlAssign<i32> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: i32)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.8.0
```
impl ShlAssign<i32> for i64
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: i32)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.8.0
```
impl ShlAssign<i32> for i8
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: i32)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.8.0
```
impl ShlAssign<i32> for isize
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: i32)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.8.0
```
impl ShlAssign<i32> for u128
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: i32)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.8.0
```
impl ShlAssign<i32> for u16
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: i32)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.8.0
```
impl ShlAssign<i32> for u32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: i32)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.8.0
```
impl ShlAssign<i32> for u64
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: i32)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.8.0
```
impl ShlAssign<i32> for u8
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: i32)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.8.0
```
impl ShlAssign<i32> for usize
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: i32)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.8.0
```
impl ShlAssign<i64> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: i64)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.8.0
```
impl ShlAssign<i8> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: i8)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.8.0
```
impl ShlAssign<isize> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: isize)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.8.0
```
impl ShlAssign<u128> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: u128)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.8.0
```
impl ShlAssign<u16> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: u16)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.8.0
```
impl ShlAssign<u32> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: u32)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.8.0
```
impl ShlAssign<u64> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: u64)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.8.0
```
impl ShlAssign<u8> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: u8)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)1.8.0
```
impl ShlAssign<usize> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#950)
```
fn shl_assign(&mut self, other: usize)
```
Performs the `<<=` operation. [Read more](ops/trait.shlassign#tymethod.shl_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i128> for &i32
```


```
type Output = <i32 as Shr<i128>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i128) -> <i32 as Shr<i128>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i128> for i32
```


```
type Output = <i32 as Shr<i128>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i128) -> <i32 as Shr<i128>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i16> for &i32
```


```
type Output = <i32 as Shr<i16>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i16) -> <i32 as Shr<i16>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i16> for i32
```


```
type Output = <i32 as Shr<i16>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i16) -> <i32 as Shr<i16>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i32> for &i128
```


```
type Output = <i128 as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i32) -> <i128 as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i32> for &i16
```


```
type Output = <i16 as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i32) -> <i16 as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i32> for &i32
```


```
type Output = <i32 as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i32) -> <i32 as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i32> for &i64
```


```
type Output = <i64 as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i32) -> <i64 as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i32> for &i8
```


```
type Output = <i8 as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i32) -> <i8 as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i32> for &isize
```


```
type Output = <isize as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i32) -> <isize as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i32> for &u128
```


```
type Output = <u128 as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i32) -> <u128 as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i32> for &u16
```


```
type Output = <u16 as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i32) -> <u16 as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i32> for &u32
```


```
type Output = <u32 as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i32) -> <u32 as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i32> for &u64
```


```
type Output = <u64 as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i32) -> <u64 as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i32> for &u8
```


```
type Output = <u8 as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i32) -> <u8 as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i32> for &usize
```


```
type Output = <usize as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i32) -> <usize as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i32> for i128
```


```
type Output = <i128 as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i32) -> <i128 as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i32> for i16
```


```
type Output = <i16 as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i32) -> <i16 as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i32> for i32
```


```
type Output = <i32 as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i32) -> <i32 as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i32> for i64
```


```
type Output = <i64 as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i32) -> <i64 as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i32> for i8
```


```
type Output = <i8 as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i32) -> <i8 as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i32> for isize
```


```
type Output = <isize as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i32) -> <isize as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i32> for u128
```


```
type Output = <u128 as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i32) -> <u128 as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i32> for u16
```


```
type Output = <u16 as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i32) -> <u16 as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i32> for u32
```


```
type Output = <u32 as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i32) -> <u32 as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i32> for u64
```


```
type Output = <u64 as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i32) -> <u64 as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i32> for u8
```


```
type Output = <u8 as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i32) -> <u8 as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i32> for usize
```


```
type Output = <usize as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i32) -> <usize as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i64> for &i32
```


```
type Output = <i32 as Shr<i64>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i64) -> <i32 as Shr<i64>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i64> for i32
```


```
type Output = <i32 as Shr<i64>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i64) -> <i32 as Shr<i64>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i8> for &i32
```


```
type Output = <i32 as Shr<i8>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i8) -> <i32 as Shr<i8>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&i8> for i32
```


```
type Output = <i32 as Shr<i8>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &i8) -> <i32 as Shr<i8>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&isize> for &i32
```


```
type Output = <i32 as Shr<isize>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &isize) -> <i32 as Shr<isize>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&isize> for i32
```


```
type Output = <i32 as Shr<isize>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &isize) -> <i32 as Shr<isize>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&u128> for &i32
```


```
type Output = <i32 as Shr<u128>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &u128) -> <i32 as Shr<u128>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&u128> for i32
```


```
type Output = <i32 as Shr<u128>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &u128) -> <i32 as Shr<u128>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&u16> for &i32
```


```
type Output = <i32 as Shr<u16>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &u16) -> <i32 as Shr<u16>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&u16> for i32
```


```
type Output = <i32 as Shr<u16>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &u16) -> <i32 as Shr<u16>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&u32> for &i32
```


```
type Output = <i32 as Shr<u32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &u32) -> <i32 as Shr<u32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&u32> for i32
```


```
type Output = <i32 as Shr<u32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &u32) -> <i32 as Shr<u32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&u64> for &i32
```


```
type Output = <i32 as Shr<u64>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &u64) -> <i32 as Shr<u64>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&u64> for i32
```


```
type Output = <i32 as Shr<u64>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &u64) -> <i32 as Shr<u64>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&u8> for &i32
```


```
type Output = <i32 as Shr<u8>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &u8) -> <i32 as Shr<u8>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&u8> for i32
```


```
type Output = <i32 as Shr<u8>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &u8) -> <i32 as Shr<u8>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&usize> for &i32
```


```
type Output = <i32 as Shr<usize>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &usize) -> <i32 as Shr<usize>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<&usize> for i32
```


```
type Output = <i32 as Shr<usize>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: &usize) -> <i32 as Shr<usize>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl<'a> Shr<i128> for &'a i32
```


```
type Output = <i32 as Shr<i128>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i128) -> <i32 as Shr<i128>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<i128> for i32
```


```
type Output = i32
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i128) -> i32
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl<'a> Shr<i16> for &'a i32
```


```
type Output = <i32 as Shr<i16>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i16) -> <i32 as Shr<i16>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<i16> for i32
```


```
type Output = i32
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i16) -> i32
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl<'a> Shr<i32> for &'a i128
```


```
type Output = <i128 as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i32) -> <i128 as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl<'a> Shr<i32> for &'a i16
```


```
type Output = <i16 as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i32) -> <i16 as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl<'a> Shr<i32> for &'a i32
```


```
type Output = <i32 as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i32) -> <i32 as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl<'a> Shr<i32> for &'a i64
```


```
type Output = <i64 as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i32) -> <i64 as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl<'a> Shr<i32> for &'a i8
```


```
type Output = <i8 as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i32) -> <i8 as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl<'a> Shr<i32> for &'a isize
```


```
type Output = <isize as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i32) -> <isize as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl<'a> Shr<i32> for &'a u128
```


```
type Output = <u128 as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i32) -> <u128 as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl<'a> Shr<i32> for &'a u16
```


```
type Output = <u16 as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i32) -> <u16 as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl<'a> Shr<i32> for &'a u32
```


```
type Output = <u32 as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i32) -> <u32 as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl<'a> Shr<i32> for &'a u64
```


```
type Output = <u64 as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i32) -> <u64 as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl<'a> Shr<i32> for &'a u8
```


```
type Output = <u8 as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i32) -> <u8 as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl<'a> Shr<i32> for &'a usize
```


```
type Output = <usize as Shr<i32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i32) -> <usize as Shr<i32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<i32> for i128
```


```
type Output = i128
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i32) -> i128
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<i32> for i16
```


```
type Output = i16
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i32) -> i16
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<i32> for i32
```


```
type Output = i32
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i32) -> i32
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<i32> for i64
```


```
type Output = i64
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i32) -> i64
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<i32> for i8
```


```
type Output = i8
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i32) -> i8
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<i32> for isize
```


```
type Output = isize
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i32) -> isize
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<i32> for u128
```


```
type Output = u128
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i32) -> u128
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<i32> for u16
```


```
type Output = u16
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i32) -> u16
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<i32> for u32
```


```
type Output = u32
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i32) -> u32
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<i32> for u64
```


```
type Output = u64
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i32) -> u64
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<i32> for u8
```


```
type Output = u8
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i32) -> u8
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<i32> for usize
```


```
type Output = usize
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i32) -> usize
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl<'a> Shr<i64> for &'a i32
```


```
type Output = <i32 as Shr<i64>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i64) -> <i32 as Shr<i64>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<i64> for i32
```


```
type Output = i32
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i64) -> i32
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl<'a> Shr<i8> for &'a i32
```


```
type Output = <i32 as Shr<i8>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i8) -> <i32 as Shr<i8>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<i8> for i32
```


```
type Output = i32
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: i8) -> i32
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl<'a> Shr<isize> for &'a i32
```


```
type Output = <i32 as Shr<isize>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: isize) -> <i32 as Shr<isize>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<isize> for i32
```


```
type Output = i32
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: isize) -> i32
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl<'a> Shr<u128> for &'a i32
```


```
type Output = <i32 as Shr<u128>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: u128) -> <i32 as Shr<u128>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<u128> for i32
```


```
type Output = i32
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: u128) -> i32
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl<'a> Shr<u16> for &'a i32
```


```
type Output = <i32 as Shr<u16>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: u16) -> <i32 as Shr<u16>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<u16> for i32
```


```
type Output = i32
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: u16) -> i32
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl<'a> Shr<u32> for &'a i32
```


```
type Output = <i32 as Shr<u32>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: u32) -> <i32 as Shr<u32>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<u32> for i32
```


```
type Output = i32
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: u32) -> i32
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl<'a> Shr<u64> for &'a i32
```


```
type Output = <i32 as Shr<u64>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: u64) -> <i32 as Shr<u64>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<u64> for i32
```


```
type Output = i32
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: u64) -> i32
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl<'a> Shr<u8> for &'a i32
```


```
type Output = <i32 as Shr<u8>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: u8) -> <i32 as Shr<u8>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<u8> for i32
```


```
type Output = i32
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: u8) -> i32
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl<'a> Shr<usize> for &'a i32
```


```
type Output = <i32 as Shr<usize>>::Output
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: usize) -> <i32 as Shr<usize>>::Output
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
impl Shr<usize> for i32
```


```
type Output = i32
```
The resulting type after applying the `>>` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#614)
```
fn shr(self, other: usize) -> i32
```
Performs the `>>` operation. [Read more](ops/trait.shr#tymethod.shr)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.22.0
```
impl ShrAssign<&i128> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: &i128)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.22.0
```
impl ShrAssign<&i16> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: &i16)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.22.0
```
impl ShrAssign<&i32> for i128
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: &i32)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.22.0
```
impl ShrAssign<&i32> for i16
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: &i32)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.22.0
```
impl ShrAssign<&i32> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: &i32)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.22.0
```
impl ShrAssign<&i32> for i64
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: &i32)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.22.0
```
impl ShrAssign<&i32> for i8
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: &i32)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.22.0
```
impl ShrAssign<&i32> for isize
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: &i32)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.22.0
```
impl ShrAssign<&i32> for u128
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: &i32)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.22.0
```
impl ShrAssign<&i32> for u16
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: &i32)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.22.0
```
impl ShrAssign<&i32> for u32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: &i32)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.22.0
```
impl ShrAssign<&i32> for u64
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: &i32)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.22.0
```
impl ShrAssign<&i32> for u8
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: &i32)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.22.0
```
impl ShrAssign<&i32> for usize
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: &i32)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.22.0
```
impl ShrAssign<&i64> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: &i64)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.22.0
```
impl ShrAssign<&i8> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: &i8)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.22.0
```
impl ShrAssign<&isize> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: &isize)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.22.0
```
impl ShrAssign<&u128> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: &u128)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.22.0
```
impl ShrAssign<&u16> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: &u16)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.22.0
```
impl ShrAssign<&u32> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: &u32)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.22.0
```
impl ShrAssign<&u64> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: &u64)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.22.0
```
impl ShrAssign<&u8> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: &u8)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.22.0
```
impl ShrAssign<&usize> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: &usize)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.8.0
```
impl ShrAssign<i128> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: i128)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.8.0
```
impl ShrAssign<i16> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: i16)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.8.0
```
impl ShrAssign<i32> for i128
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: i32)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.8.0
```
impl ShrAssign<i32> for i16
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: i32)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.8.0
```
impl ShrAssign<i32> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: i32)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.8.0
```
impl ShrAssign<i32> for i64
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: i32)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.8.0
```
impl ShrAssign<i32> for i8
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: i32)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.8.0
```
impl ShrAssign<i32> for isize
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: i32)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.8.0
```
impl ShrAssign<i32> for u128
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: i32)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.8.0
```
impl ShrAssign<i32> for u16
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: i32)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.8.0
```
impl ShrAssign<i32> for u32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: i32)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.8.0
```
impl ShrAssign<i32> for u64
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: i32)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.8.0
```
impl ShrAssign<i32> for u8
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: i32)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.8.0
```
impl ShrAssign<i32> for usize
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: i32)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.8.0
```
impl ShrAssign<i64> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: i64)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.8.0
```
impl ShrAssign<i8> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: i8)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.8.0
```
impl ShrAssign<isize> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: isize)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.8.0
```
impl ShrAssign<u128> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: u128)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.8.0
```
impl ShrAssign<u16> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: u16)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.8.0
```
impl ShrAssign<u32> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: u32)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.8.0
```
impl ShrAssign<u64> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: u64)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.8.0
```
impl ShrAssign<u8> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: u8)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)1.8.0
```
impl ShrAssign<usize> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#1032)
```
fn shr_assign(&mut self, other: usize)
```
Performs the `>>=` operation. [Read more](ops/trait.shrassign#tymethod.shr_assign)


[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/vector.rs.html#973)
```
impl SimdElement for i32
```


```
type Mask = i32
```

🔬This is a nightly-only experimental API. (`portable_simd` [#86656](https://github.com/rust-lang/rust/issues/86656))
The mask element type corresponding to this element type.

[source](https://doc.rust-lang.org/src/core/iter/range.rs.html#391-394)
```
impl Step for i32
```

[source](https://doc.rust-lang.org/src/core/iter/range.rs.html#391-394)
```
unsafe fn forward_unchecked(start: i32, n: usize) -> i32
```

🔬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](iter/trait.step#method.forward_unchecked)

[source](https://doc.rust-lang.org/src/core/iter/range.rs.html#391-394)
```
unsafe fn backward_unchecked(start: i32, n: usize) -> i32
```

🔬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](iter/trait.step#method.backward_unchecked)

[source](https://doc.rust-lang.org/src/core/iter/range.rs.html#391-394)
```
fn forward(start: i32, n: usize) -> i32
```

🔬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](iter/trait.step#method.forward)

[source](https://doc.rust-lang.org/src/core/iter/range.rs.html#391-394)
```
fn backward(start: i32, n: usize) -> i32
```

🔬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](iter/trait.step#method.backward)

[source](https://doc.rust-lang.org/src/core/iter/range.rs.html#391-394)
```
fn steps_between(start: &i32, end: &i32) -> Option<usize>
```

🔬This is a nightly-only experimental API. (`step_trait` [#42168](https://github.com/rust-lang/rust/issues/42168))
Returns the number of *successor* steps required to get from `start` to `end`. [Read more](iter/trait.step#tymethod.steps_between)

[source](https://doc.rust-lang.org/src/core/iter/range.rs.html#391-394)
```
fn forward_checked(start: i32, n: usize) -> Option<i32>
```

🔬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](iter/trait.step#tymethod.forward_checked)

[source](https://doc.rust-lang.org/src/core/iter/range.rs.html#391-394)
```
fn backward_checked(start: i32, n: usize) -> Option<i32>
```

🔬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](iter/trait.step#tymethod.backward_checked)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#217)
```
impl Sub<&i32> for &i32
```


```
type Output = <i32 as Sub<i32>>::Output
```
The resulting type after applying the `-` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#217)
```
fn sub(self, other: &i32) -> <i32 as Sub<i32>>::Output
```
Performs the `-` operation. [Read more](ops/trait.sub#tymethod.sub)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#217)
```
impl Sub<&i32> for i32
```


```
type Output = <i32 as Sub<i32>>::Output
```
The resulting type after applying the `-` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#217)
```
fn sub(self, other: &i32) -> <i32 as Sub<i32>>::Output
```
Performs the `-` operation. [Read more](ops/trait.sub#tymethod.sub)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#217)
```
impl<'a> Sub<i32> for &'a i32
```


```
type Output = <i32 as Sub<i32>>::Output
```
The resulting type after applying the `-` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#217)
```
fn sub(self, other: i32) -> <i32 as Sub<i32>>::Output
```
Performs the `-` operation. [Read more](ops/trait.sub#tymethod.sub)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#217)
```
impl Sub<i32> for i32
```


```
type Output = i32
```
The resulting type after applying the `-` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#217)
```
fn sub(self, other: i32) -> i32
```
Performs the `-` operation. [Read more](ops/trait.sub#tymethod.sub)


[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)1.22.0
```
impl SubAssign<&i32> for Saturating<i32>
```

[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)
```
fn sub_assign(&mut self, other: &i32)
```
Performs the `-=` operation. [Read more](ops/trait.subassign#tymethod.sub_assign)


[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)1.22.0
```
impl SubAssign<&i32> for Wrapping<i32>
```

[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)
```
fn sub_assign(&mut self, other: &i32)
```
Performs the `-=` operation. [Read more](ops/trait.subassign#tymethod.sub_assign)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#826)1.22.0
```
impl SubAssign<&i32> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#826)
```
fn sub_assign(&mut self, other: &i32)
```
Performs the `-=` operation. [Read more](ops/trait.subassign#tymethod.sub_assign)


[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)
```
impl SubAssign<i32> for Saturating<i32>
```

[source](https://doc.rust-lang.org/src/core/num/saturating.rs.html#483)
```
fn sub_assign(&mut self, other: i32)
```
Performs the `-=` operation. [Read more](ops/trait.subassign#tymethod.sub_assign)


[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)1.60.0
```
impl SubAssign<i32> for Wrapping<i32>
```

[source](https://doc.rust-lang.org/src/core/num/wrapping.rs.html#477)
```
fn sub_assign(&mut self, other: i32)
```
Performs the `-=` operation. [Read more](ops/trait.subassign#tymethod.sub_assign)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#826)1.8.0
```
impl SubAssign<i32> for i32
```

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#826)
```
fn sub_assign(&mut self, other: i32)
```
Performs the `-=` operation. [Read more](ops/trait.subassign#tymethod.sub_assign)


[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#149)1.12.0
```
impl<'a> Sum<&'a i32> for i32
```

[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#149)
```
fn sum<I>(iter: I) -> i32
where
    I: Iterator<Item = &'a i32>,
```
Method which takes an iterator and generates `Self` from the elements by “summing up” the items.

[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#149)1.12.0
```
impl Sum<i32> for i32
```

[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#149)
```
fn sum<I>(iter: I) -> i32
where
    I: Iterator<Item = i32>,
```
Method which takes an iterator and generates `Self` from the elements by “summing up” the items.

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#311)1.34.0
```
impl TryFrom<i128> for i32
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#311)
```
fn try_from(u: i128) -> Result<i32, <i32 as TryFrom<i128>>::Error>
```

Try to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type.

 

```
type Error = TryFromIntError
```
The type returned in the event of a conversion error.

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#529)1.46.0
```
impl TryFrom<i32> for NonZeroI32
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#529)
```
fn try_from(
    value: i32
) -> Result<NonZeroI32, <NonZeroI32 as TryFrom<i32>>::Error>
```

Attempts to convert `i32` to `NonZeroI32`.

 

```
type Error = TryFromIntError
```
The type returned in the event of a conversion error.

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#309)1.34.0
```
impl TryFrom<i32> for i16
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#309)
```
fn try_from(u: i32) -> Result<i16, <i16 as TryFrom<i32>>::Error>
```

Try to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type.

 

```
type Error = TryFromIntError
```
The type returned in the event of a conversion error.

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#309)1.34.0
```
impl TryFrom<i32> for i8
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#309)
```
fn try_from(u: i32) -> Result<i8, <i8 as TryFrom<i32>>::Error>
```

Try to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type.

 

```
type Error = TryFromIntError
```
The type returned in the event of a conversion error.

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#406)1.34.0
```
impl TryFrom<i32> for isize
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#406)
```
fn try_from(value: i32) -> Result<isize, <isize as TryFrom<i32>>::Error>
```

Try to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type.

 

```
type Error = TryFromIntError
```
The type returned in the event of a conversion error.

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#323)1.34.0
```
impl TryFrom<i32> for u128
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#323)
```
fn try_from(u: i32) -> Result<u128, <u128 as TryFrom<i32>>::Error>
```

Try to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type.

 

```
type Error = TryFromIntError
```
The type returned in the event of a conversion error.

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#327)1.34.0
```
impl TryFrom<i32> for u16
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#327)
```
fn try_from(u: i32) -> Result<u16, <u16 as TryFrom<i32>>::Error>
```

Try to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type.

 

```
type Error = TryFromIntError
```
The type returned in the event of a conversion error.

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#323)1.34.0
```
impl TryFrom<i32> for u32
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#323)
```
fn try_from(u: i32) -> Result<u32, <u32 as TryFrom<i32>>::Error>
```

Try to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type.

 

```
type Error = TryFromIntError
```
The type returned in the event of a conversion error.

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#323)1.34.0
```
impl TryFrom<i32> for u64
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#323)
```
fn try_from(u: i32) -> Result<u64, <u64 as TryFrom<i32>>::Error>
```

Try to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type.

 

```
type Error = TryFromIntError
```
The type returned in the event of a conversion error.

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#327)1.34.0
```
impl TryFrom<i32> for u8
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#327)
```
fn try_from(u: i32) -> Result<u8, <u8 as TryFrom<i32>>::Error>
```

Try to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type.

 

```
type Error = TryFromIntError
```
The type returned in the event of a conversion error.

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#401)1.34.0
```
impl TryFrom<i32> for usize
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#401)
```
fn try_from(u: i32) -> Result<usize, <usize as TryFrom<i32>>::Error>
```

Try to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type.

 

```
type Error = TryFromIntError
```
The type returned in the event of a conversion error.

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#310)1.34.0
```
impl TryFrom<i64> for i32
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#310)
```
fn try_from(u: i64) -> Result<i32, <i32 as TryFrom<i64>>::Error>
```

Try to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type.

 

```
type Error = TryFromIntError
```
The type returned in the event of a conversion error.

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#396)1.34.0
```
impl TryFrom<isize> for i32
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#396)
```
fn try_from(u: isize) -> Result<i32, <i32 as TryFrom<isize>>::Error>
```

Try to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type.

 

```
type Error = TryFromIntError
```
The type returned in the event of a conversion error.

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#318)1.34.0
```
impl TryFrom<u128> for i32
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#318)
```
fn try_from(u: u128) -> Result<i32, <i32 as TryFrom<u128>>::Error>
```

Try to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type.

 

```
type Error = TryFromIntError
```
The type returned in the event of a conversion error.

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#316)1.34.0
```
impl TryFrom<u32> for i32
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#316)
```
fn try_from(u: u32) -> Result<i32, <i32 as TryFrom<u32>>::Error>
```

Try to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type.

 

```
type Error = TryFromIntError
```
The type returned in the event of a conversion error.

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#317)1.34.0
```
impl TryFrom<u64> for i32
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#317)
```
fn try_from(u: u64) -> Result<i32, <i32 as TryFrom<u64>>::Error>
```

Try to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type.

 

```
type Error = TryFromIntError
```
The type returned in the event of a conversion error.

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#391)1.34.0
```
impl TryFrom<usize> for i32
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#391)
```
fn try_from(u: usize) -> Result<i32, <i32 as TryFrom<usize>>::Error>
```

Try to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type.

 

```
type Error = TryFromIntError
```
The type returned in the event of a conversion error.

[source](https://doc.rust-lang.org/src/core/fmt/num.rs.html#470-473)1.42.0
```
impl UpperExp for i32
```

[source](https://doc.rust-lang.org/src/core/fmt/num.rs.html#470-473)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter.

[source](https://doc.rust-lang.org/src/core/fmt/num.rs.html#181)
```
impl UpperHex for i32
```

[source](https://doc.rust-lang.org/src/core/fmt/num.rs.html#181)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter.

[source](https://doc.rust-lang.org/src/core/marker.rs.html#989-1000)
```
impl ConstParamTy for i32
```
[source](https://doc.rust-lang.org/src/core/marker.rs.html#467-477)
```
impl Copy for i32
```
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1309)
```
impl Eq for i32
```
[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#38)
```
impl FloatToInt<i32> for f32
```
[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#39)
```
impl FloatToInt<i32> for f64
```
[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/masks.rs.html#80)
```
impl MaskElement for i32
```
[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/cast.rs.html#15)
```
impl SimdCast for i32
```
[source](https://doc.rust-lang.org/src/core/marker.rs.html#262-273)
```
impl StructuralEq for i32
```
[source](https://doc.rust-lang.org/src/core/iter/range.rs.html#17)
```
impl TrustedStep for i32
```


Auto Trait Implementations
--------------------------




```
impl RefUnwindSafe for i32
```

```
impl Send for i32
```

```
impl Sync for i32
```

```
impl Unpin for i32
```

```
impl UnwindSafe for i32
```


Blanket Implementations
-----------------------



[source](https://doc.rust-lang.org/src/core/any.rs.html#200)
```
impl<T> Any for T
where
    T: 'static + ?Sized,
```

[source](https://doc.rust-lang.org/src/core/any.rs.html#201)
```
fn type_id(&self) -> TypeId
```
Gets the `TypeId` of `self`. [Read more](any/trait.any#tymethod.type_id)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#208)
```
impl<T> Borrow<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#210)
```
fn borrow(&self) -> &T
```
Immutably borrows from an owned value. [Read more](borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#216)
```
impl<T> BorrowMut<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#217)
```
fn borrow_mut(&mut self) -> &mut T
```
Mutably borrows from an owned value. [Read more](borrow/trait.borrowmut#tymethod.borrow_mut)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#723)
```
impl<T> From<T> for T
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#726)
```
fn from(t: T) -> T
```

Returns the argument unchanged.

 

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#707)
```
impl<T, U> Into<U> for T
where
    U: From<T>,
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#716)
```
fn into(self) -> U
```

Calls `U::from(self)`.

 That is, this conversion is whatever the implementation of `[From](convert/trait.from "trait std::convert::From")<T> for U` chooses to do.

 

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#82)
```
impl<T> ToOwned for T
where
    T: Clone,
```


```
type Owned = T
```
The resulting type after obtaining ownership.
[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#87)
```
fn to_owned(&self) -> T
```
Creates owned data from borrowed data, usually by cloning. [Read more](borrow/trait.toowned#tymethod.to_owned)

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#91)
```
fn clone_into(&self, target: &mut T)
```
Uses borrowed data to replace owned data, usually by cloning. [Read more](borrow/trait.toowned#method.clone_into)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2513)
```
impl<T> ToString for T
where
    T: Display + ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2519)
```
default fn to_string(&self) -> String
```
Converts the given value to a `String`. [Read more](string/trait.tostring#tymethod.to_string)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#763)
```
impl<T, U> TryFrom<U> for T
where
    U: Into<T>,
```


```
type Error = Infallible
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#770)
```
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#748)
```
impl<T, U> TryInto<U> for T
where
    U: TryFrom<T>,
```


```
type Error = <U as TryFrom<T>>::Error
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#755)
```
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
```
Performs the conversion.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/primitive.i32.html>

Module std::i32
===============



👎Deprecating in a future Rust version: all constants in this module replaced by associated constants on `i32`
Redundant constants module for the [`i32` primitive type](../primitive.i32 "primitive i32").

 New code should use the associated constants directly on the primitive type.

 Constants
---------


* [MAX](constant.max "constant std::i32::MAX")Deprecation planned

The largest value that can be represented by this integer type. Use [`i32::MAX`](../primitive.i32#associatedconstant.MAX "associated constant i32::MAX") instead.
* [MIN](constant.min "constant std::i32::MIN")Deprecation planned

The smallest value that can be represented by this integer type. Use [`i32::MIN`](../primitive.i32#associatedconstant.MIN "associated constant i32::MIN") instead.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/i32/index.html>

Constant std::i32::MIN
======================



```
pub const MIN: i32 = i32::MIN; // -2_147_483_648i32
```


👎Deprecating in a future Rust version: replaced by the `MIN` associated constant on this type
The smallest value that can be represented by this integer type. Use [`i32::MIN`](../primitive.i32#associatedconstant.MIN "associated constant i32::MIN") instead.

 Examples
--------

 
```
// deprecated way
let min = std::i32::MIN;

// intended way
let min = i32::MIN;
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/i32/constant.MIN.html>

Constant std::i32::MAX
======================



```
pub const MAX: i32 = i32::MAX; // 2_147_483_647i32
```


👎Deprecating in a future Rust version: replaced by the `MAX` associated constant on this type
The largest value that can be represented by this integer type. Use [`i32::MAX`](../primitive.i32#associatedconstant.MAX "associated constant i32::MAX") instead.

 Examples
--------

 
```
// deprecated way
let max = std::i32::MAX;

// intended way
let max = i32::MAX;
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/i32/constant.MAX.html>

Primitive Type slice
====================


A dynamically-sized view into a contiguous sequence, `[T]`. Contiguous here means that elements are laid out so that every element is the same distance from its neighbors.

 *[See also the `std::slice` module](slice/index "mod std::slice").*

 Slices are a view into a block of memory represented as a pointer and a length.

 
```
// slicing a Vec
let vec = vec![1, 2, 3];
let int_slice = &vec[..];
// coercing an array to a slice
let str_slice: &[&str] = &["one", "two", "three"];
```
 Slices are either mutable or shared. The shared slice type is `&[T]`, while the mutable slice type is `&mut [T]`, where `T` represents the element type. For example, you can mutate the block of memory that a mutable slice points to:

 
```
let mut x = [1, 2, 3];
let x = &mut x[..]; // Take a full slice of `x`.
x[1] = 7;
assert_eq!(x, &[1, 7, 3]);
```
 As slices store the length of the sequence they refer to, they have twice the size of pointers to [`Sized`](marker/trait.sized) types. Also see the reference on [dynamically sized types](../reference/dynamically-sized-types).

 
```
let pointer_size = std::mem::size_of::<&u8>();
assert_eq!(2 * pointer_size, std::mem::size_of::<&[u8]>());
assert_eq!(2 * pointer_size, std::mem::size_of::<*const [u8]>());
assert_eq!(2 * pointer_size, std::mem::size_of::<Box<[u8]>>());
assert_eq!(2 * pointer_size, std::mem::size_of::<Rc<[u8]>>());
```
 ### Trait Implementations

 Some traits are implemented for slices if the element type implements that trait. This includes [`Eq`](cmp/trait.eq "trait std::cmp::Eq"), [`Hash`](hash/trait.hash "trait std::hash::Hash") and [`Ord`](cmp/trait.ord "trait std::cmp::Ord").

 ### Iteration

 The slices implement `IntoIterator`. The iterator yields references to the slice elements.

 
```
let numbers: &[i32] = &[0, 1, 2];
for n in numbers {
    println!("{n} is a number!");
}
```
 The mutable slice yields mutable references to the elements:

 
```
let mut scores: &mut [i32] = &mut [7, 8, 9];
for score in scores {
    *score += 1;
}
```
 This iterator yields mutable references to the slice’s elements, so while the element type of the slice is `i32`, the element type of the iterator is `&mut i32`.

 * [`.iter`](primitive.slice#method.iter "method slice::iter") and [`.iter_mut`](primitive.slice#method.iter_mut "method slice::iter_mut") are the explicit methods to return the default iterators.
* Further methods that return iterators are [`.split`](primitive.slice#method.split "method slice::split"), [`.splitn`](primitive.slice#method.splitn "method slice::splitn"), [`.chunks`](primitive.slice#method.chunks "method slice::chunks"), [`.windows`](primitive.slice#method.windows "method slice::windows") and more.

 Implementations
---------------



[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#602)
```
impl<T> Box<[T], Global>
```

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#626)
```
pub fn new_uninit_slice(len: usize) -> Box<[MaybeUninit<T>], Global>
```

🔬This is a nightly-only experimental API. (`new_uninit` [#63291](https://github.com/rust-lang/rust/issues/63291))

Constructs a new boxed slice with uninitialized contents.

 ##### Examples

 
```
#![feature(new_uninit)]

let mut values = Box::<[u32]>::new_uninit_slice(3);

let values = unsafe {
    // Deferred initialization:
    values[0].as_mut_ptr().write(1);
    values[1].as_mut_ptr().write(2);
    values[2].as_mut_ptr().write(3);

    values.assume_init()
};

assert_eq!(*values, [1, 2, 3])
```
 
[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#651)
```
pub fn new_zeroed_slice(len: usize) -> Box<[MaybeUninit<T>], Global>
```

🔬This is a nightly-only experimental API. (`new_uninit` [#63291](https://github.com/rust-lang/rust/issues/63291))

Constructs a new boxed slice with uninitialized contents, with the memory being filled with `0` bytes.

 See [`MaybeUninit::zeroed`](mem/union.maybeuninit#method.zeroed "associated function std::mem::MaybeUninit::zeroed") for examples of correct and incorrect usage of this method.

 ##### Examples

 
```
#![feature(new_uninit)]

let values = Box::<[u32]>::new_zeroed_slice(3);
let values = unsafe { values.assume_init() };

assert_eq!(*values, [0, 0, 0])
```
 
[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#677)
```
pub fn try_new_uninit_slice(
    len: usize
) -> Result<Box<[MaybeUninit<T>], Global>, AllocError>
```

🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838))

Constructs a new boxed slice with uninitialized contents. Returns an error if the allocation fails

 ##### Examples

 
```
#![feature(allocator_api, new_uninit)]

let mut values = Box::<[u32]>::try_new_uninit_slice(3)?;
let values = unsafe {
    // Deferred initialization:
    values[0].as_mut_ptr().write(1);
    values[1].as_mut_ptr().write(2);
    values[2].as_mut_ptr().write(3);
    values.assume_init()
};

assert_eq!(*values, [1, 2, 3]);
```
 
[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#709)
```
pub fn try_new_zeroed_slice(
    len: usize
) -> Result<Box<[MaybeUninit<T>], Global>, AllocError>
```

🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838))

Constructs a new boxed slice with uninitialized contents, with the memory being filled with `0` bytes. Returns an error if the allocation fails

 See [`MaybeUninit::zeroed`](mem/union.maybeuninit#method.zeroed "associated function std::mem::MaybeUninit::zeroed") for examples of correct and incorrect usage of this method.

 ##### Examples

 
```
#![feature(allocator_api, new_uninit)]

let values = Box::<[u32]>::try_new_zeroed_slice(3)?;
let values = unsafe { values.assume_init() };

assert_eq!(*values, [0, 0, 0]);
```
 

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#721)
```
impl<T, A> Box<[T], A>
where
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#748)
```
pub fn new_uninit_slice_in(len: usize, alloc: A) -> Box<[MaybeUninit<T>], A>
```

🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838))

Constructs a new boxed slice with uninitialized contents in the provided allocator.

 ##### Examples

 
```
#![feature(allocator_api, new_uninit)]

use std::alloc::System;

let mut values = Box::<[u32], _>::new_uninit_slice_in(3, System);

let values = unsafe {
    // Deferred initialization:
    values[0].as_mut_ptr().write(1);
    values[1].as_mut_ptr().write(2);
    values[2].as_mut_ptr().write(3);

    values.assume_init()
};

assert_eq!(*values, [1, 2, 3])
```
 
[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#776)
```
pub fn new_zeroed_slice_in(len: usize, alloc: A) -> Box<[MaybeUninit<T>], A>
```

🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838))

Constructs a new boxed slice with uninitialized contents in the provided allocator, with the memory being filled with `0` bytes.

 See [`MaybeUninit::zeroed`](mem/union.maybeuninit#method.zeroed "associated function std::mem::MaybeUninit::zeroed") for examples of correct and incorrect usage of this method.

 ##### Examples

 
```
#![feature(allocator_api, new_uninit)]

use std::alloc::System;

let values = Box::<[u32], _>::new_zeroed_slice_in(3, System);
let values = unsafe { values.assume_init() };

assert_eq!(*values, [0, 0, 0])
```
 

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#854)
```
impl<T, A> Box<[MaybeUninit<T>], A>
where
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#887)
```
pub unsafe fn assume_init(self) -> Box<[T], A>
```

🔬This is a nightly-only experimental API. (`new_uninit` [#63291](https://github.com/rust-lang/rust/issues/63291))

Converts to `Box<[T], A>`.

 ##### Safety

 As with [`MaybeUninit::assume_init`](mem/union.maybeuninit#method.assume_init "method std::mem::MaybeUninit::assume_init"), it is up to the caller to guarantee that the values really are in an initialized state. Calling this when the content is not yet fully initialized causes immediate undefined behavior.

 ##### Examples

 
```
#![feature(new_uninit)]

let mut values = Box::<[u32]>::new_uninit_slice(3);

let values = unsafe {
    // Deferred initialization:
    values[0].as_mut_ptr().write(1);
    values[1].as_mut_ptr().write(2);
    values[2].as_mut_ptr().write(3);

    values.assume_init()
};

assert_eq!(*values, [1, 2, 3])
```
 

[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4547)
```
impl [f32]
```

[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4570)
```
pub fn sort_floats(&mut self)
```

🔬This is a nightly-only experimental API. (`sort_floats` [#93396](https://github.com/rust-lang/rust/issues/93396))

Sorts the slice of floats.

 This sort is in-place (i.e. does not allocate), *O*(*n* \* log(*n*)) worst-case, and uses the ordering defined by [`f32::total_cmp`](primitive.f32#method.total_cmp "method f32::total_cmp").

 ##### Current implementation

 This uses the same sorting algorithm as [`sort_unstable_by`](primitive.slice#method.sort_unstable_by "method slice::sort_unstable_by").

 ##### Examples

 
```
#![feature(sort_floats)]
let mut v = [2.6, -5e-8, f32::NAN, 8.29, f32::INFINITY, -1.0, 0.0, -f32::INFINITY, -0.0];

v.sort_floats();
let sorted = [-f32::INFINITY, -1.0, -5e-8, -0.0, 0.0, 2.6, 8.29, f32::INFINITY, f32::NAN];
assert_eq!(&v[..8], &sorted[..8]);
assert!(v[8].is_nan());
```
 

[source](https://doc.rust-lang.org/src/core/ascii/ascii_char.rs.html#540)
```
impl [AsciiChar]
```

[source](https://doc.rust-lang.org/src/core/ascii/ascii_char.rs.html#544)
```
pub const fn as_str(&self) -> &str
```

🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998))

Views this slice of ASCII characters as a UTF-8 `str`.

 
[source](https://doc.rust-lang.org/src/core/ascii/ascii_char.rs.html#555)
```
pub const fn as_bytes(&self) -> &[u8] ⓘ
```

🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998))

Views this slice of ASCII characters as a slice of `u8` bytes.

 

[source](https://doc.rust-lang.org/src/core/slice/ascii.rs.html#10)
```
impl [u8]
```

[source](https://doc.rust-lang.org/src/core/slice/ascii.rs.html#16)1.23.0 (const: [unstable](https://github.com/rust-lang/rust/issues/111090 "Tracking issue for const_slice_is_ascii"))
```
pub fn is_ascii(&self) -> bool
```

Checks if all bytes in this slice are within the ASCII range.

 
[source](https://doc.rust-lang.org/src/core/slice/ascii.rs.html#25)
```
pub const fn as_ascii(&self) -> Option<&[AsciiChar]>
```

🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998))

If this slice [`is_ascii`](primitive.slice#method.is_ascii "method slice::is_ascii"), returns it as a slice of [ASCII characters](ascii/enum.char "enum std::ascii::Char"), otherwise returns `None`.

 
[source](https://doc.rust-lang.org/src/core/slice/ascii.rs.html#43)
```
pub const unsafe fn as_ascii_unchecked(&self) -> &[AsciiChar]
```

🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998))

Converts this slice of bytes into a slice of ASCII characters, without checking whether they’re valid.

 ##### Safety

 Every byte in the slice must be in `0..=127`, or else this is UB.

 
[source](https://doc.rust-lang.org/src/core/slice/ascii.rs.html#57)1.23.0
```
pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool
```

Checks that two slices are an ASCII case-insensitive match.

 Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`, but without allocating and copying temporaries.

 
[source](https://doc.rust-lang.org/src/core/slice/ascii.rs.html#72)1.23.0
```
pub fn make_ascii_uppercase(&mut self)
```

Converts this slice to its ASCII upper case equivalent in-place.

 ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, but non-ASCII letters are unchanged.

 To return a new uppercased value without modifying the existing one, use [`to_ascii_uppercase`](#method.to_ascii_uppercase).

 
[source](https://doc.rust-lang.org/src/core/slice/ascii.rs.html#89)1.23.0
```
pub fn make_ascii_lowercase(&mut self)
```

Converts this slice to its ASCII lower case equivalent in-place.

 ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’, but non-ASCII letters are unchanged.

 To return a new lowercased value without modifying the existing one, use [`to_ascii_lowercase`](#method.to_ascii_lowercase).

 
[source](https://doc.rust-lang.org/src/core/slice/ascii.rs.html#109)1.60.0
```
pub fn escape_ascii(&self) -> EscapeAscii<'_> ⓘ
```

Returns an iterator that produces an escaped version of this slice, treating it as an ASCII string.

 ##### Examples

 
```

let s = b"0\t\r\n'\"\\\x9d";
let escaped = s.escape_ascii().to_string();
assert_eq!(escaped, "0\\t\\r\\n\\'\\\"\\\\\\x9d");
```
 
[source](https://doc.rust-lang.org/src/core/slice/ascii.rs.html#128)
```
pub const fn trim_ascii_start(&self) -> &[u8] ⓘ
```

🔬This is a nightly-only experimental API. (`byte_slice_trim_ascii` [#94035](https://github.com/rust-lang/rust/issues/94035))

Returns a byte slice with leading ASCII whitespace bytes removed.

 ‘Whitespace’ refers to the definition used by `u8::is_ascii_whitespace`.

 ##### Examples

 
```
#![feature(byte_slice_trim_ascii)]

assert_eq!(b" \t hello world\n".trim_ascii_start(), b"hello world\n");
assert_eq!(b"  ".trim_ascii_start(), b"");
assert_eq!(b"".trim_ascii_start(), b"");
```
 
[source](https://doc.rust-lang.org/src/core/slice/ascii.rs.html#157)
```
pub const fn trim_ascii_end(&self) -> &[u8] ⓘ
```

🔬This is a nightly-only experimental API. (`byte_slice_trim_ascii` [#94035](https://github.com/rust-lang/rust/issues/94035))

Returns a byte slice with trailing ASCII whitespace bytes removed.

 ‘Whitespace’ refers to the definition used by `u8::is_ascii_whitespace`.

 ##### Examples

 
```
#![feature(byte_slice_trim_ascii)]

assert_eq!(b"\r hello world\n ".trim_ascii_end(), b"\r hello world");
assert_eq!(b"  ".trim_ascii_end(), b"");
assert_eq!(b"".trim_ascii_end(), b"");
```
 
[source](https://doc.rust-lang.org/src/core/slice/ascii.rs.html#187)
```
pub const fn trim_ascii(&self) -> &[u8] ⓘ
```

🔬This is a nightly-only experimental API. (`byte_slice_trim_ascii` [#94035](https://github.com/rust-lang/rust/issues/94035))

Returns a byte slice with leading and trailing ASCII whitespace bytes removed.

 ‘Whitespace’ refers to the definition used by `u8::is_ascii_whitespace`.

 ##### Examples

 
```
#![feature(byte_slice_trim_ascii)]

assert_eq!(b"\r hello world\n ".trim_ascii(), b"hello world");
assert_eq!(b"  ".trim_ascii(), b"");
assert_eq!(b"".trim_ascii(), b"");
```
 

[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4576)
```
impl [f64]
```

[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4599)
```
pub fn sort_floats(&mut self)
```

🔬This is a nightly-only experimental API. (`sort_floats` [#93396](https://github.com/rust-lang/rust/issues/93396))

Sorts the slice of floats.

 This sort is in-place (i.e. does not allocate), *O*(*n* \* log(*n*)) worst-case, and uses the ordering defined by [`f64::total_cmp`](primitive.f64#method.total_cmp "method f64::total_cmp").

 ##### Current implementation

 This uses the same sorting algorithm as [`sort_unstable_by`](primitive.slice#method.sort_unstable_by "method slice::sort_unstable_by").

 ##### Examples

 
```
#![feature(sort_floats)]
let mut v = [2.6, -5e-8, f64::NAN, 8.29, f64::INFINITY, -1.0, 0.0, -f64::INFINITY, -0.0];

v.sort_floats();
let sorted = [-f64::INFINITY, -1.0, -5e-8, -0.0, 0.0, 2.6, 8.29, f64::INFINITY, f64::NAN];
assert_eq!(&v[..8], &sorted[..8]);
assert!(v[8].is_nan());
```
 

[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4465)
```
impl<T, const N: usize> [[T; N]]
```

[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4495)
```
pub const fn flatten(&self) -> &[T]
```

🔬This is a nightly-only experimental API. (`slice_flatten` [#95629](https://github.com/rust-lang/rust/issues/95629))

Takes a `&[[T; N]]`, and flattens it to a `&[T]`.

 ##### Panics

 This panics if the length of the resulting slice would overflow a `usize`.

 This is only possible when flattening a slice of arrays of zero-sized types, and thus tends to be irrelevant in practice. If `size_of::<T>() > 0`, this will never panic.

 ##### Examples

 
```
#![feature(slice_flatten)]

assert_eq!([[1, 2, 3], [4, 5, 6]].flatten(), &[1, 2, 3, 4, 5, 6]);

assert_eq!(
    [[1, 2, 3], [4, 5, 6]].flatten(),
    [[1, 2], [3, 4], [5, 6]].flatten(),
);

let slice_of_empty_arrays: &[[i32; 0]] = &[[], [], [], [], []];
assert!(slice_of_empty_arrays.flatten().is_empty());

let empty_slice_of_arrays: &[[u32; 10]] = &[];
assert!(empty_slice_of_arrays.flatten().is_empty());
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4533)
```
pub fn flatten_mut(&mut self) -> &mut [T]
```

🔬This is a nightly-only experimental API. (`slice_flatten` [#95629](https://github.com/rust-lang/rust/issues/95629))

Takes a `&mut [[T; N]]`, and flattens it to a `&mut [T]`.

 ##### Panics

 This panics if the length of the resulting slice would overflow a `usize`.

 This is only possible when flattening a slice of arrays of zero-sized types, and thus tends to be irrelevant in practice. If `size_of::<T>() > 0`, this will never panic.

 ##### Examples

 
```
#![feature(slice_flatten)]

fn add_5_to_all(slice: &mut [i32]) {
    for i in slice {
        *i += 5;
    }
}

let mut array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
add_5_to_all(array.flatten_mut());
assert_eq!(array, [[6, 7, 8], [9, 10, 11], [12, 13, 14]]);
```
 

[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#126)
```
impl<T> [T]
```

[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#141)const: 1.39.0
```
pub const fn len(&self) -> usize
```

Returns the number of elements in the slice.

 ##### Examples

 
```
let a = [1, 2, 3];
assert_eq!(a.len(), 3);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#157)const: 1.39.0
```
pub const fn is_empty(&self) -> bool
```

Returns `true` if the slice has a length of 0.

 ##### Examples

 
```
let a = [1, 2, 3];
assert!(!a.is_empty());
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#176)const: 1.56.0
```
pub const fn first(&self) -> Option<&T>
```

Returns the first element of the slice, or `None` if it is empty.

 ##### Examples

 
```
let v = [10, 40, 30];
assert_eq!(Some(&10), v.first());

let w: &[i32] = &[];
assert_eq!(None, w.first());
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#196)const: [unstable](https://github.com/rust-lang/rust/issues/83570 "Tracking issue for const_slice_first_last")
```
pub fn first_mut(&mut self) -> Option<&mut T>
```

Returns a mutable pointer to the first element of the slice, or `None` if it is empty.

 ##### Examples

 
```
let x = &mut [0, 1, 2];

if let Some(first) = x.first_mut() {
    *first = 5;
}
assert_eq!(x, &[5, 1, 2]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#216)1.5.0 (const: 1.56.0)
```
pub const fn split_first(&self) -> Option<(&T, &[T])>
```

Returns the first and all the rest of the elements of the slice, or `None` if it is empty.

 ##### Examples

 
```
let x = &[0, 1, 2];

if let Some((first, elements)) = x.split_first() {
    assert_eq!(first, &0);
    assert_eq!(elements, &[1, 2]);
}
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#238)1.5.0 (const: [unstable](https://github.com/rust-lang/rust/issues/83570 "Tracking issue for const_slice_first_last"))
```
pub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])>
```

Returns the first and all the rest of the elements of the slice, or `None` if it is empty.

 ##### Examples

 
```
let x = &mut [0, 1, 2];

if let Some((first, elements)) = x.split_first_mut() {
    *first = 3;
    elements[0] = 4;
    elements[1] = 5;
}
assert_eq!(x, &[3, 4, 5]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#258)1.5.0 (const: 1.56.0)
```
pub const fn split_last(&self) -> Option<(&T, &[T])>
```

Returns the last and all the rest of the elements of the slice, or `None` if it is empty.

 ##### Examples

 
```
let x = &[0, 1, 2];

if let Some((last, elements)) = x.split_last() {
    assert_eq!(last, &2);
    assert_eq!(elements, &[0, 1]);
}
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#280)1.5.0 (const: [unstable](https://github.com/rust-lang/rust/issues/83570 "Tracking issue for const_slice_first_last"))
```
pub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])>
```

Returns the last and all the rest of the elements of the slice, or `None` if it is empty.

 ##### Examples

 
```
let x = &mut [0, 1, 2];

if let Some((last, elements)) = x.split_last_mut() {
    *last = 3;
    elements[0] = 4;
    elements[1] = 5;
}
assert_eq!(x, &[4, 5, 3]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#299)const: 1.56.0
```
pub const fn last(&self) -> Option<&T>
```

Returns the last element of the slice, or `None` if it is empty.

 ##### Examples

 
```
let v = [10, 40, 30];
assert_eq!(Some(&30), v.last());

let w: &[i32] = &[];
assert_eq!(None, w.last());
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#319)const: [unstable](https://github.com/rust-lang/rust/issues/83570 "Tracking issue for const_slice_first_last")
```
pub fn last_mut(&mut self) -> Option<&mut T>
```

Returns a mutable pointer to the last item in the slice.

 ##### Examples

 
```
let x = &mut [0, 1, 2];

if let Some(last) = x.last_mut() {
    *last = 10;
}
assert_eq!(x, &[0, 1, 10]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#342)const: [unstable](https://github.com/rust-lang/rust/issues/111774 "Tracking issue for slice_first_last_chunk")
```
pub fn first_chunk<const N: usize>(&self) -> Option<&[T; N]>
```

🔬This is a nightly-only experimental API. (`slice_first_last_chunk` [#111774](https://github.com/rust-lang/rust/issues/111774))

Returns the first `N` elements of the slice, or `None` if it has fewer than `N` elements.

 ##### Examples

 
```
#![feature(slice_first_last_chunk)]

let u = [10, 40, 30];
assert_eq!(Some(&[10, 40]), u.first_chunk::<2>());

let v: &[i32] = &[10];
assert_eq!(None, v.first_chunk::<2>());

let w: &[i32] = &[];
assert_eq!(Some(&[]), w.first_chunk::<0>());
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#371)const: [unstable](https://github.com/rust-lang/rust/issues/111774 "Tracking issue for slice_first_last_chunk")
```
pub fn first_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>
```

🔬This is a nightly-only experimental API. (`slice_first_last_chunk` [#111774](https://github.com/rust-lang/rust/issues/111774))

Returns a mutable reference to the first `N` elements of the slice, or `None` if it has fewer than `N` elements.

 ##### Examples

 
```
#![feature(slice_first_last_chunk)]

let x = &mut [0, 1, 2];

if let Some(first) = x.first_chunk_mut::<2>() {
    first[0] = 5;
    first[1] = 4;
}
assert_eq!(x, &[5, 4, 2]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#400)const: [unstable](https://github.com/rust-lang/rust/issues/111774 "Tracking issue for slice_first_last_chunk")
```
pub fn split_first_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])>
```

🔬This is a nightly-only experimental API. (`slice_first_last_chunk` [#111774](https://github.com/rust-lang/rust/issues/111774))

Returns the first `N` elements of the slice and the remainder, or `None` if it has fewer than `N` elements.

 ##### Examples

 
```
#![feature(slice_first_last_chunk)]

let x = &[0, 1, 2];

if let Some((first, elements)) = x.split_first_chunk::<2>() {
    assert_eq!(first, &[0, 1]);
    assert_eq!(elements, &[2]);
}
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#433-435)const: [unstable](https://github.com/rust-lang/rust/issues/111774 "Tracking issue for slice_first_last_chunk")
```
pub fn split_first_chunk_mut<const N: usize>(
    &mut self
) -> Option<(&mut [T; N], &mut [T])>
```

🔬This is a nightly-only experimental API. (`slice_first_last_chunk` [#111774](https://github.com/rust-lang/rust/issues/111774))

Returns a mutable reference to the first `N` elements of the slice and the remainder, or `None` if it has fewer than `N` elements.

 ##### Examples

 
```
#![feature(slice_first_last_chunk)]

let x = &mut [0, 1, 2];

if let Some((first, elements)) = x.split_first_chunk_mut::<2>() {
    first[0] = 3;
    first[1] = 4;
    elements[0] = 5;
}
assert_eq!(x, &[3, 4, 5]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#467)const: [unstable](https://github.com/rust-lang/rust/issues/111774 "Tracking issue for slice_first_last_chunk")
```
pub fn split_last_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])>
```

🔬This is a nightly-only experimental API. (`slice_first_last_chunk` [#111774](https://github.com/rust-lang/rust/issues/111774))

Returns the last `N` elements of the slice and the remainder, or `None` if it has fewer than `N` elements.

 ##### Examples

 
```
#![feature(slice_first_last_chunk)]

let x = &[0, 1, 2];

if let Some((last, elements)) = x.split_last_chunk::<2>() {
    assert_eq!(last, &[1, 2]);
    assert_eq!(elements, &[0]);
}
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#499-501)const: [unstable](https://github.com/rust-lang/rust/issues/111774 "Tracking issue for slice_first_last_chunk")
```
pub fn split_last_chunk_mut<const N: usize>(
    &mut self
) -> Option<(&mut [T; N], &mut [T])>
```

🔬This is a nightly-only experimental API. (`slice_first_last_chunk` [#111774](https://github.com/rust-lang/rust/issues/111774))

Returns the last and all the rest of the elements of the slice, or `None` if it is empty.

 ##### Examples

 
```
#![feature(slice_first_last_chunk)]

let x = &mut [0, 1, 2];

if let Some((last, elements)) = x.split_last_chunk_mut::<2>() {
    last[0] = 3;
    last[1] = 4;
    elements[0] = 5;
}
assert_eq!(x, &[5, 3, 4]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#534)const: [unstable](https://github.com/rust-lang/rust/issues/111774 "Tracking issue for slice_first_last_chunk")
```
pub fn last_chunk<const N: usize>(&self) -> Option<&[T; N]>
```

🔬This is a nightly-only experimental API. (`slice_first_last_chunk` [#111774](https://github.com/rust-lang/rust/issues/111774))

Returns the last element of the slice, or `None` if it is empty.

 ##### Examples

 
```
#![feature(slice_first_last_chunk)]

let u = [10, 40, 30];
assert_eq!(Some(&[40, 30]), u.last_chunk::<2>());

let v: &[i32] = &[10];
assert_eq!(None, v.last_chunk::<2>());

let w: &[i32] = &[];
assert_eq!(Some(&[]), w.last_chunk::<0>());
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#566)const: [unstable](https://github.com/rust-lang/rust/issues/111774 "Tracking issue for slice_first_last_chunk")
```
pub fn last_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>
```

🔬This is a nightly-only experimental API. (`slice_first_last_chunk` [#111774](https://github.com/rust-lang/rust/issues/111774))

Returns a mutable pointer to the last item in the slice.

 ##### Examples

 
```
#![feature(slice_first_last_chunk)]

let x = &mut [0, 1, 2];

if let Some(last) = x.last_chunk_mut::<2>() {
    last[0] = 10;
    last[1] = 20;
}
assert_eq!(x, &[0, 10, 20]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#601-603)
```
pub fn get<I>(&self, index: I) -> Option<&<I as SliceIndex<[T]>>::Output>
where
    I: SliceIndex<[T]>,
```

Returns a reference to an element or subslice depending on the type of index.

 * If given a position, returns a reference to the element at that position or `None` if out of bounds.
* If given a range, returns the subslice corresponding to that range, or `None` if out of bounds.

 ##### Examples

 
```
let v = [10, 40, 30];
assert_eq!(Some(&40), v.get(1));
assert_eq!(Some(&[10, 40][..]), v.get(0..2));
assert_eq!(None, v.get(3));
assert_eq!(None, v.get(0..4));
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#626-628)
```
pub fn get_mut<I>(
    &mut self,
    index: I
) -> Option<&mut <I as SliceIndex<[T]>>::Output>
where
    I: SliceIndex<[T]>,
```

Returns a mutable reference to an element or subslice depending on the type of index (see [`get`](primitive.slice#method.get "method slice::get")) or `None` if the index is out of bounds.

 ##### Examples

 
```
let x = &mut [0, 1, 2];

if let Some(elem) = x.get_mut(1) {
    *elem = 42;
}
assert_eq!(x, &[0, 42, 2]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#658-660)
```
pub unsafe fn get_unchecked<I>(
    &self,
    index: I
) -> &<I as SliceIndex<[T]>>::Output
where
    I: SliceIndex<[T]>,
```

Returns a reference to an element or subslice, without doing bounds checking.

 For a safe alternative see [`get`](primitive.slice#method.get "method slice::get").

 ##### Safety

 Calling this method with an out-of-bounds index is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used.

 ##### Examples

 
```
let x = &[1, 2, 4];

unsafe {
    assert_eq!(x.get_unchecked(1), &2);
}
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#695-697)
```
pub unsafe fn get_unchecked_mut<I>(
    &mut self,
    index: I
) -> &mut <I as SliceIndex<[T]>>::Output
where
    I: SliceIndex<[T]>,
```

Returns a mutable reference to an element or subslice, without doing bounds checking.

 For a safe alternative see [`get_mut`](primitive.slice#method.get_mut "method slice::get_mut").

 ##### Safety

 Calling this method with an out-of-bounds index is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used.

 ##### Examples

 
```
let x = &mut [1, 2, 4];

unsafe {
    let elem = x.get_unchecked_mut(1);
    *elem = 13;
}
assert_eq!(x, &[1, 13, 4]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#735)const: 1.32.0
```
pub const fn as_ptr(&self) -> *const T
```

Returns a raw pointer to the slice’s buffer.

 The caller must ensure that the slice outlives the pointer this function returns, or else it will end up pointing to garbage.

 The caller must also ensure that the memory the pointer (non-transitively) points to is never written to (except inside an `UnsafeCell`) using this pointer or any pointer derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`](primitive.slice#method.as_mut_ptr "method slice::as_mut_ptr").

 Modifying the container referenced by this slice may cause its buffer to be reallocated, which would also make any pointers to it invalid.

 ##### Examples

 
```
let x = &[1, 2, 4];
let x_ptr = x.as_ptr();

unsafe {
    for i in 0..x.len() {
        assert_eq!(x.get_unchecked(i), &*x_ptr.add(i));
    }
}
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#765)const: 1.61.0
```
pub const fn as_mut_ptr(&mut self) -> *mut T
```

Returns an unsafe mutable pointer to the slice’s buffer.

 The caller must ensure that the slice outlives the pointer this function returns, or else it will end up pointing to garbage.

 Modifying the container referenced by this slice may cause its buffer to be reallocated, which would also make any pointers to it invalid.

 ##### Examples

 
```
let x = &mut [1, 2, 4];
let x_ptr = x.as_mut_ptr();

unsafe {
    for i in 0..x.len() {
        *x_ptr.add(i) += 2;
    }
}
assert_eq!(x, &[3, 4, 6]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#801)1.48.0 (const: 1.61.0)
```
pub const fn as_ptr_range(&self) -> Range<*const T> ⓘ
```

Returns the two raw pointers spanning the slice.

 The returned range is half-open, which means that the end pointer points *one past* the last element of the slice. This way, an empty slice is represented by two equal pointers, and the difference between the two pointers represents the size of the slice.

 See [`as_ptr`](primitive.slice#method.as_ptr "method slice::as_ptr") for warnings on using these pointers. The end pointer requires extra caution, as it does not point to a valid element in the slice.

 This function is useful for interacting with foreign interfaces which use two pointers to refer to a range of elements in memory, as is common in C++.

 It can also be useful to check if a pointer to an element refers to an element of this slice:

 
```
let a = [1, 2, 3];
let x = &a[1] as *const _;
let y = &5 as *const _;

assert!(a.as_ptr_range().contains(&x));
assert!(!a.as_ptr_range().contains(&y));
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#845)1.48.0 (const: 1.61.0)
```
pub const fn as_mut_ptr_range(&mut self) -> Range<*mut T> ⓘ
```

Returns the two unsafe mutable pointers spanning the slice.

 The returned range is half-open, which means that the end pointer points *one past* the last element of the slice. This way, an empty slice is represented by two equal pointers, and the difference between the two pointers represents the size of the slice.

 See [`as_mut_ptr`](primitive.slice#method.as_mut_ptr "method slice::as_mut_ptr") for warnings on using these pointers. The end pointer requires extra caution, as it does not point to a valid element in the slice.

 This function is useful for interacting with foreign interfaces which use two pointers to refer to a range of elements in memory, as is common in C++.

 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#874)const: [unstable](https://github.com/rust-lang/rust/issues/83163 "Tracking issue for const_swap")
```
pub fn swap(&mut self, a: usize, b: usize)
```

Swaps two elements in the slice.

 ##### Arguments

 * a - The index of the first element
* b - The index of the second element

 ##### Panics

 Panics if `a` or `b` are out of bounds.

 ##### Examples

 
```
let mut v = ["a", "b", "c", "d", "e"];
v.swap(2, 4);
assert!(v == ["a", "b", "e", "d", "c"]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#917)const: [unstable](https://github.com/rust-lang/rust/issues/83163 "Tracking issue for const_swap")
```
pub unsafe fn swap_unchecked(&mut self, a: usize, b: usize)
```

🔬This is a nightly-only experimental API. (`slice_swap_unchecked` [#88539](https://github.com/rust-lang/rust/issues/88539))

Swaps two elements in the slice, without doing bounds checking.

 For a safe alternative see [`swap`](primitive.slice#method.swap "method slice::swap").

 ##### Arguments

 * a - The index of the first element
* b - The index of the second element

 ##### Safety

 Calling this method with an out-of-bounds index is *[undefined behavior](../reference/behavior-considered-undefined)*. The caller has to ensure that `a < self.len()` and `b < self.len()`.

 ##### Examples

 
```
#![feature(slice_swap_unchecked)]

let mut v = ["a", "b", "c", "d"];
// SAFETY: we know that 1 and 3 are both indices of the slice
unsafe { v.swap_unchecked(1, 3) };
assert!(v == ["a", "d", "c", "b"]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#941)
```
pub fn reverse(&mut self)
```

Reverses the order of elements in the slice, in place.

 ##### Examples

 
```
let mut v = [1, 2, 3];
v.reverse();
assert!(v == [3, 2, 1]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#999)
```
pub fn iter(&self) -> Iter<'_, T> ⓘ
```

Returns an iterator over the slice.

 The iterator yields all items from start to end.

 ##### Examples

 
```
let x = &[1, 2, 4];
let mut iterator = x.iter();

assert_eq!(iterator.next(), Some(&1));
assert_eq!(iterator.next(), Some(&2));
assert_eq!(iterator.next(), Some(&4));
assert_eq!(iterator.next(), None);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1018)
```
pub fn iter_mut(&mut self) -> IterMut<'_, T> ⓘ
```

Returns an iterator that allows modifying each value.

 The iterator yields all items from start to end.

 ##### Examples

 
```
let x = &mut [1, 2, 4];
for elem in x.iter_mut() {
    *elem += 2;
}
assert_eq!(x, &[3, 4, 6]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1067)
```
pub fn windows(&self, size: usize) -> Windows<'_, T> ⓘ
```

Returns an iterator over all contiguous windows of length `size`. The windows overlap. If the slice is shorter than `size`, the iterator returns no values.

 ##### Panics

 Panics if `size` is 0.

 ##### Examples

 
```
let slice = ['r', 'u', 's', 't'];
let mut iter = slice.windows(2);
assert_eq!(iter.next().unwrap(), &['r', 'u']);
assert_eq!(iter.next().unwrap(), &['u', 's']);
assert_eq!(iter.next().unwrap(), &['s', 't']);
assert!(iter.next().is_none());
```
 If the slice is shorter than `size`:

 
```
let slice = ['f', 'o', 'o'];
let mut iter = slice.windows(4);
assert!(iter.next().is_none());
```
 There’s no `windows_mut`, as that existing would let safe code violate the “only one `&mut` at a time to the same thing” rule. However, you can sometimes use [`Cell::as_slice_of_cells`](cell/struct.cell#method.as_slice_of_cells "method std::cell::Cell::as_slice_of_cells") in conjunction with `windows` to accomplish something similar:

 
```
use std::cell::Cell;

let mut array = ['R', 'u', 's', 't', ' ', '2', '0', '1', '5'];
let slice = &mut array[..];
let slice_of_cells: &[Cell<char>] = Cell::from_mut(slice).as_slice_of_cells();
for w in slice_of_cells.windows(3) {
    Cell::swap(&w[0], &w[2]);
}
assert_eq!(array, ['s', 't', ' ', '2', '0', '1', '5', 'u', 'R']);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1102)
```
pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T> ⓘ
```

Returns an iterator over `chunk_size` elements of the slice at a time, starting at the beginning of the slice.

 The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the slice, then the last chunk will not have length `chunk_size`.

 See [`chunks_exact`](primitive.slice#method.chunks_exact "method slice::chunks_exact") for a variant of this iterator that returns chunks of always exactly `chunk_size` elements, and [`rchunks`](primitive.slice#method.rchunks "method slice::rchunks") for the same iterator but starting at the end of the slice.

 ##### Panics

 Panics if `chunk_size` is 0.

 ##### Examples

 
```
let slice = ['l', 'o', 'r', 'e', 'm'];
let mut iter = slice.chunks(2);
assert_eq!(iter.next().unwrap(), &['l', 'o']);
assert_eq!(iter.next().unwrap(), &['r', 'e']);
assert_eq!(iter.next().unwrap(), &['m']);
assert!(iter.next().is_none());
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1141)
```
pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, T> ⓘ
```

Returns an iterator over `chunk_size` elements of the slice at a time, starting at the beginning of the slice.

 The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the length of the slice, then the last chunk will not have length `chunk_size`.

 See [`chunks_exact_mut`](primitive.slice#method.chunks_exact_mut "method slice::chunks_exact_mut") for a variant of this iterator that returns chunks of always exactly `chunk_size` elements, and [`rchunks_mut`](primitive.slice#method.rchunks_mut "method slice::rchunks_mut") for the same iterator but starting at the end of the slice.

 ##### Panics

 Panics if `chunk_size` is 0.

 ##### Examples

 
```
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;

for chunk in v.chunks_mut(2) {
    for elem in chunk.iter_mut() {
        *elem += count;
    }
    count += 1;
}
assert_eq!(v, &[1, 1, 2, 2, 3]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1179)1.31.0
```
pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T> ⓘ
```

Returns an iterator over `chunk_size` elements of the slice at a time, starting at the beginning of the slice.

 The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved from the `remainder` function of the iterator.

 Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the resulting code better than in the case of [`chunks`](primitive.slice#method.chunks "method slice::chunks").

 See [`chunks`](primitive.slice#method.chunks "method slice::chunks") for a variant of this iterator that also returns the remainder as a smaller chunk, and [`rchunks_exact`](primitive.slice#method.rchunks_exact "method slice::rchunks_exact") for the same iterator but starting at the end of the slice.

 ##### Panics

 Panics if `chunk_size` is 0.

 ##### Examples

 
```
let slice = ['l', 'o', 'r', 'e', 'm'];
let mut iter = slice.chunks_exact(2);
assert_eq!(iter.next().unwrap(), &['l', 'o']);
assert_eq!(iter.next().unwrap(), &['r', 'e']);
assert!(iter.next().is_none());
assert_eq!(iter.remainder(), &['m']);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1222)1.31.0
```
pub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, T> ⓘ
```

Returns an iterator over `chunk_size` elements of the slice at a time, starting at the beginning of the slice.

 The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved from the `into_remainder` function of the iterator.

 Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the resulting code better than in the case of [`chunks_mut`](primitive.slice#method.chunks_mut "method slice::chunks_mut").

 See [`chunks_mut`](primitive.slice#method.chunks_mut "method slice::chunks_mut") for a variant of this iterator that also returns the remainder as a smaller chunk, and [`rchunks_exact_mut`](primitive.slice#method.rchunks_exact_mut "method slice::rchunks_exact_mut") for the same iterator but starting at the end of the slice.

 ##### Panics

 Panics if `chunk_size` is 0.

 ##### Examples

 
```
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;

for chunk in v.chunks_exact_mut(2) {
    for elem in chunk.iter_mut() {
        *elem += count;
    }
    count += 1;
}
assert_eq!(v, &[1, 1, 2, 2, 0]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1257)
```
pub const unsafe fn as_chunks_unchecked<const N: usize>(&self) -> &[[T; N]]
```

🔬This is a nightly-only experimental API. (`slice_as_chunks` [#74985](https://github.com/rust-lang/rust/issues/74985))

Splits the slice into a slice of `N`-element arrays, assuming that there’s no remainder.

 ##### Safety

 This may only be called when

 * The slice splits exactly into `N`-element chunks (aka `self.len() % N == 0`).
* `N != 0`.

 ##### Examples

 
```
#![feature(slice_as_chunks)]
let slice: &[char] = &['l', 'o', 'r', 'e', 'm', '!'];
let chunks: &[[char; 1]] =
    // SAFETY: 1-element chunks never have remainder
    unsafe { slice.as_chunks_unchecked() };
assert_eq!(chunks, &[['l'], ['o'], ['r'], ['e'], ['m'], ['!']]);
let chunks: &[[char; 3]] =
    // SAFETY: The slice length (6) is a multiple of 3
    unsafe { slice.as_chunks_unchecked() };
assert_eq!(chunks, &[['l', 'o', 'r'], ['e', 'm', '!']]);

// These would be unsound:
// let chunks: &[[_; 5]] = slice.as_chunks_unchecked() // The slice length is not a multiple of 5
// let chunks: &[[_; 0]] = slice.as_chunks_unchecked() // Zero-length chunks are never allowed
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1305)
```
pub const fn as_chunks<const N: usize>(&self) -> (&[[T; N]], &[T])
```

🔬This is a nightly-only experimental API. (`slice_as_chunks` [#74985](https://github.com/rust-lang/rust/issues/74985))

Splits the slice into a slice of `N`-element arrays, starting at the beginning of the slice, and a remainder slice with length strictly less than `N`.

 ##### Panics

 Panics if `N` is 0. This check will most probably get changed to a compile time error before this method gets stabilized.

 ##### Examples

 
```
#![feature(slice_as_chunks)]
let slice = ['l', 'o', 'r', 'e', 'm'];
let (chunks, remainder) = slice.as_chunks();
assert_eq!(chunks, &[['l', 'o'], ['r', 'e']]);
assert_eq!(remainder, &['m']);
```
 If you expect the slice to be an exact multiple, you can combine `let`-`else` with an empty slice pattern:

 
```
#![feature(slice_as_chunks)]
let slice = ['R', 'u', 's', 't'];
let (chunks, []) = slice.as_chunks::<2>() else {
    panic!("slice didn't have even length")
};
assert_eq!(chunks, &[['R', 'u'], ['s', 't']]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1337)
```
pub const fn as_rchunks<const N: usize>(&self) -> (&[T], &[[T; N]])
```

🔬This is a nightly-only experimental API. (`slice_as_chunks` [#74985](https://github.com/rust-lang/rust/issues/74985))

Splits the slice into a slice of `N`-element arrays, starting at the end of the slice, and a remainder slice with length strictly less than `N`.

 ##### Panics

 Panics if `N` is 0. This check will most probably get changed to a compile time error before this method gets stabilized.

 ##### Examples

 
```
#![feature(slice_as_chunks)]
let slice = ['l', 'o', 'r', 'e', 'm'];
let (remainder, chunks) = slice.as_rchunks();
assert_eq!(remainder, &['l']);
assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1377)
```
pub fn array_chunks<const N: usize>(&self) -> ArrayChunks<'_, T, N> ⓘ
```

🔬This is a nightly-only experimental API. (`array_chunks` [#74985](https://github.com/rust-lang/rust/issues/74985))

Returns an iterator over `N` elements of the slice at a time, starting at the beginning of the slice.

 The chunks are array references and do not overlap. If `N` does not divide the length of the slice, then the last up to `N-1` elements will be omitted and can be retrieved from the `remainder` function of the iterator.

 This method is the const generic equivalent of [`chunks_exact`](primitive.slice#method.chunks_exact "method slice::chunks_exact").

 ##### Panics

 Panics if `N` is 0. This check will most probably get changed to a compile time error before this method gets stabilized.

 ##### Examples

 
```
#![feature(array_chunks)]
let slice = ['l', 'o', 'r', 'e', 'm'];
let mut iter = slice.array_chunks();
assert_eq!(iter.next().unwrap(), &['l', 'o']);
assert_eq!(iter.next().unwrap(), &['r', 'e']);
assert!(iter.next().is_none());
assert_eq!(iter.remainder(), &['m']);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1414)
```
pub const unsafe fn as_chunks_unchecked_mut<const N: usize>(
    &mut self
) -> &mut [[T; N]]
```

🔬This is a nightly-only experimental API. (`slice_as_chunks` [#74985](https://github.com/rust-lang/rust/issues/74985))

Splits the slice into a slice of `N`-element arrays, assuming that there’s no remainder.

 ##### Safety

 This may only be called when

 * The slice splits exactly into `N`-element chunks (aka `self.len() % N == 0`).
* `N != 0`.

 ##### Examples

 
```
#![feature(slice_as_chunks)]
let slice: &mut [char] = &mut ['l', 'o', 'r', 'e', 'm', '!'];
let chunks: &mut [[char; 1]] =
    // SAFETY: 1-element chunks never have remainder
    unsafe { slice.as_chunks_unchecked_mut() };
chunks[0] = ['L'];
assert_eq!(chunks, &[['L'], ['o'], ['r'], ['e'], ['m'], ['!']]);
let chunks: &mut [[char; 3]] =
    // SAFETY: The slice length (6) is a multiple of 3
    unsafe { slice.as_chunks_unchecked_mut() };
chunks[1] = ['a', 'x', '?'];
assert_eq!(slice, &['L', 'o', 'r', 'a', 'x', '?']);

// These would be unsound:
// let chunks: &[[_; 5]] = slice.as_chunks_unchecked_mut() // The slice length is not a multiple of 5
// let chunks: &[[_; 0]] = slice.as_chunks_unchecked_mut() // Zero-length chunks are never allowed
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1457)
```
pub const fn as_chunks_mut<const N: usize>(
    &mut self
) -> (&mut [[T; N]], &mut [T])
```

🔬This is a nightly-only experimental API. (`slice_as_chunks` [#74985](https://github.com/rust-lang/rust/issues/74985))

Splits the slice into a slice of `N`-element arrays, starting at the beginning of the slice, and a remainder slice with length strictly less than `N`.

 ##### Panics

 Panics if `N` is 0. This check will most probably get changed to a compile time error before this method gets stabilized.

 ##### Examples

 
```
#![feature(slice_as_chunks)]
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;

let (chunks, remainder) = v.as_chunks_mut();
remainder[0] = 9;
for chunk in chunks {
    *chunk = [count; 2];
    count += 1;
}
assert_eq!(v, &[1, 1, 2, 2, 9]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1495)
```
pub const fn as_rchunks_mut<const N: usize>(
    &mut self
) -> (&mut [T], &mut [[T; N]])
```

🔬This is a nightly-only experimental API. (`slice_as_chunks` [#74985](https://github.com/rust-lang/rust/issues/74985))

Splits the slice into a slice of `N`-element arrays, starting at the end of the slice, and a remainder slice with length strictly less than `N`.

 ##### Panics

 Panics if `N` is 0. This check will most probably get changed to a compile time error before this method gets stabilized.

 ##### Examples

 
```
#![feature(slice_as_chunks)]
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;

let (remainder, chunks) = v.as_rchunks_mut();
remainder[0] = 9;
for chunk in chunks {
    *chunk = [count; 2];
    count += 1;
}
assert_eq!(v, &[9, 1, 1, 2, 2]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1537)
```
pub fn array_chunks_mut<const N: usize>(&mut self) -> ArrayChunksMut<'_, T, N> ⓘ
```

🔬This is a nightly-only experimental API. (`array_chunks` [#74985](https://github.com/rust-lang/rust/issues/74985))

Returns an iterator over `N` elements of the slice at a time, starting at the beginning of the slice.

 The chunks are mutable array references and do not overlap. If `N` does not divide the length of the slice, then the last up to `N-1` elements will be omitted and can be retrieved from the `into_remainder` function of the iterator.

 This method is the const generic equivalent of [`chunks_exact_mut`](primitive.slice#method.chunks_exact_mut "method slice::chunks_exact_mut").

 ##### Panics

 Panics if `N` is 0. This check will most probably get changed to a compile time error before this method gets stabilized.

 ##### Examples

 
```
#![feature(array_chunks)]
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;

for chunk in v.array_chunks_mut() {
    *chunk = [count; 2];
    count += 1;
}
assert_eq!(v, &[1, 1, 2, 2, 0]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1570)
```
pub fn array_windows<const N: usize>(&self) -> ArrayWindows<'_, T, N> ⓘ
```

🔬This is a nightly-only experimental API. (`array_windows` [#75027](https://github.com/rust-lang/rust/issues/75027))

Returns an iterator over overlapping windows of `N` elements of a slice, starting at the beginning of the slice.

 This is the const generic equivalent of [`windows`](primitive.slice#method.windows "method slice::windows").

 If `N` is greater than the size of the slice, it will return no windows.

 ##### Panics

 Panics if `N` is 0. This check will most probably get changed to a compile time error before this method gets stabilized.

 ##### Examples

 
```
#![feature(array_windows)]
let slice = [0, 1, 2, 3];
let mut iter = slice.array_windows();
assert_eq!(iter.next().unwrap(), &[0, 1]);
assert_eq!(iter.next().unwrap(), &[1, 2]);
assert_eq!(iter.next().unwrap(), &[2, 3]);
assert!(iter.next().is_none());
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1605)1.31.0
```
pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T> ⓘ
```

Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end of the slice.

 The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the slice, then the last chunk will not have length `chunk_size`.

 See [`rchunks_exact`](primitive.slice#method.rchunks_exact "method slice::rchunks_exact") for a variant of this iterator that returns chunks of always exactly `chunk_size` elements, and [`chunks`](primitive.slice#method.chunks "method slice::chunks") for the same iterator but starting at the beginning of the slice.

 ##### Panics

 Panics if `chunk_size` is 0.

 ##### Examples

 
```
let slice = ['l', 'o', 'r', 'e', 'm'];
let mut iter = slice.rchunks(2);
assert_eq!(iter.next().unwrap(), &['e', 'm']);
assert_eq!(iter.next().unwrap(), &['o', 'r']);
assert_eq!(iter.next().unwrap(), &['l']);
assert!(iter.next().is_none());
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1644)1.31.0
```
pub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, T> ⓘ
```

Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end of the slice.

 The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the length of the slice, then the last chunk will not have length `chunk_size`.

 See [`rchunks_exact_mut`](primitive.slice#method.rchunks_exact_mut "method slice::rchunks_exact_mut") for a variant of this iterator that returns chunks of always exactly `chunk_size` elements, and [`chunks_mut`](primitive.slice#method.chunks_mut "method slice::chunks_mut") for the same iterator but starting at the beginning of the slice.

 ##### Panics

 Panics if `chunk_size` is 0.

 ##### Examples

 
```
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;

for chunk in v.rchunks_mut(2) {
    for elem in chunk.iter_mut() {
        *elem += count;
    }
    count += 1;
}
assert_eq!(v, &[3, 2, 2, 1, 1]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1684)1.31.0
```
pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T> ⓘ
```

Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end of the slice.

 The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved from the `remainder` function of the iterator.

 Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the resulting code better than in the case of [`rchunks`](primitive.slice#method.rchunks "method slice::rchunks").

 See [`rchunks`](primitive.slice#method.rchunks "method slice::rchunks") for a variant of this iterator that also returns the remainder as a smaller chunk, and [`chunks_exact`](primitive.slice#method.chunks_exact "method slice::chunks_exact") for the same iterator but starting at the beginning of the slice.

 ##### Panics

 Panics if `chunk_size` is 0.

 ##### Examples

 
```
let slice = ['l', 'o', 'r', 'e', 'm'];
let mut iter = slice.rchunks_exact(2);
assert_eq!(iter.next().unwrap(), &['e', 'm']);
assert_eq!(iter.next().unwrap(), &['o', 'r']);
assert!(iter.next().is_none());
assert_eq!(iter.remainder(), &['l']);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1728)1.31.0
```
pub fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, T> ⓘ
```

Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end of the slice.

 The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved from the `into_remainder` function of the iterator.

 Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the resulting code better than in the case of [`chunks_mut`](primitive.slice#method.chunks_mut "method slice::chunks_mut").

 See [`rchunks_mut`](primitive.slice#method.rchunks_mut "method slice::rchunks_mut") for a variant of this iterator that also returns the remainder as a smaller chunk, and [`chunks_exact_mut`](primitive.slice#method.chunks_exact_mut "method slice::chunks_exact_mut") for the same iterator but starting at the beginning of the slice.

 ##### Panics

 Panics if `chunk_size` is 0.

 ##### Examples

 
```
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;

for chunk in v.rchunks_exact_mut(2) {
    for elem in chunk.iter_mut() {
        *elem += count;
    }
    count += 1;
}
assert_eq!(v, &[0, 2, 2, 1, 1]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1771-1773)
```
pub fn group_by<F>(&self, pred: F) -> GroupBy<'_, T, F> ⓘ
where
    F: FnMut(&T, &T) -> bool,
```

🔬This is a nightly-only experimental API. (`slice_group_by` [#80552](https://github.com/rust-lang/rust/issues/80552))

Returns an iterator over the slice producing non-overlapping runs of elements using the predicate to separate them.

 The predicate is called on two elements following themselves, it means the predicate is called on `slice[0]` and `slice[1]` then on `slice[1]` and `slice[2]` and so on.

 ##### Examples

 
```
#![feature(slice_group_by)]

let slice = &[1, 1, 1, 3, 3, 2, 2, 2];

let mut iter = slice.group_by(|a, b| a == b);

assert_eq!(iter.next(), Some(&[1, 1, 1][..]));
assert_eq!(iter.next(), Some(&[3, 3][..]));
assert_eq!(iter.next(), Some(&[2, 2, 2][..]));
assert_eq!(iter.next(), None);
```
 This method can be used to extract the sorted subslices:

 
```
#![feature(slice_group_by)]

let slice = &[1, 1, 2, 3, 2, 3, 2, 3, 4];

let mut iter = slice.group_by(|a, b| a <= b);

assert_eq!(iter.next(), Some(&[1, 1, 2, 3][..]));
assert_eq!(iter.next(), Some(&[2, 3][..]));
assert_eq!(iter.next(), Some(&[2, 3, 4][..]));
assert_eq!(iter.next(), None);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1816-1818)
```
pub fn group_by_mut<F>(&mut self, pred: F) -> GroupByMut<'_, T, F> ⓘ
where
    F: FnMut(&T, &T) -> bool,
```

🔬This is a nightly-only experimental API. (`slice_group_by` [#80552](https://github.com/rust-lang/rust/issues/80552))

Returns an iterator over the slice producing non-overlapping mutable runs of elements using the predicate to separate them.

 The predicate is called on two elements following themselves, it means the predicate is called on `slice[0]` and `slice[1]` then on `slice[1]` and `slice[2]` and so on.

 ##### Examples

 
```
#![feature(slice_group_by)]

let slice = &mut [1, 1, 1, 3, 3, 2, 2, 2];

let mut iter = slice.group_by_mut(|a, b| a == b);

assert_eq!(iter.next(), Some(&mut [1, 1, 1][..]));
assert_eq!(iter.next(), Some(&mut [3, 3][..]));
assert_eq!(iter.next(), Some(&mut [2, 2, 2][..]));
assert_eq!(iter.next(), None);
```
 This method can be used to extract the sorted subslices:

 
```
#![feature(slice_group_by)]

let slice = &mut [1, 1, 2, 3, 2, 3, 2, 3, 4];

let mut iter = slice.group_by_mut(|a, b| a <= b);

assert_eq!(iter.next(), Some(&mut [1, 1, 2, 3][..]));
assert_eq!(iter.next(), Some(&mut [2, 3][..]));
assert_eq!(iter.next(), Some(&mut [2, 3, 4][..]));
assert_eq!(iter.next(), None);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1862)const: 1.71.0
```
pub const fn split_at(&self, mid: usize) -> (&[T], &[T])
```

Divides one slice into two at an index.

 The first will contain all indices from `[0, mid)` (excluding the index `mid` itself) and the second will contain all indices from `[mid, len)` (excluding the index `len` itself).

 ##### Panics

 Panics if `mid > len`.

 ##### Examples

 
```
let v = [1, 2, 3, 4, 5, 6];

{
   let (left, right) = v.split_at(0);
   assert_eq!(left, []);
   assert_eq!(right, [1, 2, 3, 4, 5, 6]);
}

{
    let (left, right) = v.split_at(2);
    assert_eq!(left, [1, 2]);
    assert_eq!(right, [3, 4, 5, 6]);
}

{
    let (left, right) = v.split_at(6);
    assert_eq!(left, [1, 2, 3, 4, 5, 6]);
    assert_eq!(right, []);
}
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1895)const: [unstable](https://github.com/rust-lang/rust/issues/101804 "Tracking issue for const_slice_split_at_mut")
```
pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T])
```

Divides one mutable slice into two at an index.

 The first will contain all indices from `[0, mid)` (excluding the index `mid` itself) and the second will contain all indices from `[mid, len)` (excluding the index `len` itself).

 ##### Panics

 Panics if `mid > len`.

 ##### Examples

 
```
let mut v = [1, 0, 3, 0, 5, 6];
let (left, right) = v.split_at_mut(2);
assert_eq!(left, [1, 0]);
assert_eq!(right, [3, 0, 5, 6]);
left[1] = 2;
right[1] = 4;
assert_eq!(v, [1, 2, 3, 4, 5, 6]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#1948)const: [unstable](https://github.com/rust-lang/rust/issues/76014 "Tracking issue for slice_split_at_unchecked")
```
pub unsafe fn split_at_unchecked(&self, mid: usize) -> (&[T], &[T])
```

🔬This is a nightly-only experimental API. (`slice_split_at_unchecked` [#76014](https://github.com/rust-lang/rust/issues/76014))

Divides one slice into two at an index, without doing bounds checking.

 The first will contain all indices from `[0, mid)` (excluding the index `mid` itself) and the second will contain all indices from `[mid, len)` (excluding the index `len` itself).

 For a safe alternative see [`split_at`](primitive.slice#method.split_at "method slice::split_at").

 ##### Safety

 Calling this method with an out-of-bounds index is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used. The caller has to ensure that `0 <= mid <= self.len()`.

 ##### Examples

 
```
#![feature(slice_split_at_unchecked)]

let v = [1, 2, 3, 4, 5, 6];

unsafe {
   let (left, right) = v.split_at_unchecked(0);
   assert_eq!(left, []);
   assert_eq!(right, [1, 2, 3, 4, 5, 6]);
}

unsafe {
    let (left, right) = v.split_at_unchecked(2);
    assert_eq!(left, [1, 2]);
    assert_eq!(right, [3, 4, 5, 6]);
}

unsafe {
    let (left, right) = v.split_at_unchecked(6);
    assert_eq!(left, [1, 2, 3, 4, 5, 6]);
    assert_eq!(right, []);
}
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2003)const: [unstable](https://github.com/rust-lang/rust/issues/101804 "Tracking issue for const_slice_split_at_mut")
```
pub unsafe fn split_at_mut_unchecked(
    &mut self,
    mid: usize
) -> (&mut [T], &mut [T])
```

🔬This is a nightly-only experimental API. (`slice_split_at_unchecked` [#76014](https://github.com/rust-lang/rust/issues/76014))

Divides one mutable slice into two at an index, without doing bounds checking.

 The first will contain all indices from `[0, mid)` (excluding the index `mid` itself) and the second will contain all indices from `[mid, len)` (excluding the index `len` itself).

 For a safe alternative see [`split_at_mut`](primitive.slice#method.split_at_mut "method slice::split_at_mut").

 ##### Safety

 Calling this method with an out-of-bounds index is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used. The caller has to ensure that `0 <= mid <= self.len()`.

 ##### Examples

 
```
#![feature(slice_split_at_unchecked)]

let mut v = [1, 0, 3, 0, 5, 6];
// scoped to restrict the lifetime of the borrows
unsafe {
    let (left, right) = v.split_at_mut_unchecked(2);
    assert_eq!(left, [1, 0]);
    assert_eq!(right, [3, 0, 5, 6]);
    left[1] = 2;
    right[1] = 4;
}
assert_eq!(v, [1, 2, 3, 4, 5, 6]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2059)
```
pub fn split_array_ref<const N: usize>(&self) -> (&[T; N], &[T])
```

🔬This is a nightly-only experimental API. (`split_array` [#90091](https://github.com/rust-lang/rust/issues/90091))

Divides one slice into an array and a remainder slice at an index.

 The array will contain all indices from `[0, N)` (excluding the index `N` itself) and the slice will contain all indices from `[N, len)` (excluding the index `len` itself).

 ##### Panics

 Panics if `N > len`.

 ##### Examples

 
```
#![feature(split_array)]

let v = &[1, 2, 3, 4, 5, 6][..];

{
   let (left, right) = v.split_array_ref::<0>();
   assert_eq!(left, &[]);
   assert_eq!(right, [1, 2, 3, 4, 5, 6]);
}

{
    let (left, right) = v.split_array_ref::<2>();
    assert_eq!(left, &[1, 2]);
    assert_eq!(right, [3, 4, 5, 6]);
}

{
    let (left, right) = v.split_array_ref::<6>();
    assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
    assert_eq!(right, []);
}
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2092)
```
pub fn split_array_mut<const N: usize>(&mut self) -> (&mut [T; N], &mut [T])
```

🔬This is a nightly-only experimental API. (`split_array` [#90091](https://github.com/rust-lang/rust/issues/90091))

Divides one mutable slice into an array and a remainder slice at an index.

 The array will contain all indices from `[0, N)` (excluding the index `N` itself) and the slice will contain all indices from `[N, len)` (excluding the index `len` itself).

 ##### Panics

 Panics if `N > len`.

 ##### Examples

 
```
#![feature(split_array)]

let mut v = &mut [1, 0, 3, 0, 5, 6][..];
let (left, right) = v.split_array_mut::<2>();
assert_eq!(left, &mut [1, 0]);
assert_eq!(right, [3, 0, 5, 6]);
left[1] = 2;
right[1] = 4;
assert_eq!(v, [1, 2, 3, 4, 5, 6]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2137)
```
pub fn rsplit_array_ref<const N: usize>(&self) -> (&[T], &[T; N])
```

🔬This is a nightly-only experimental API. (`split_array` [#90091](https://github.com/rust-lang/rust/issues/90091))

Divides one slice into an array and a remainder slice at an index from the end.

 The slice will contain all indices from `[0, len - N)` (excluding the index `len - N` itself) and the array will contain all indices from `[len - N, len)` (excluding the index `len` itself).

 ##### Panics

 Panics if `N > len`.

 ##### Examples

 
```
#![feature(split_array)]

let v = &[1, 2, 3, 4, 5, 6][..];

{
   let (left, right) = v.rsplit_array_ref::<0>();
   assert_eq!(left, [1, 2, 3, 4, 5, 6]);
   assert_eq!(right, &[]);
}

{
    let (left, right) = v.rsplit_array_ref::<2>();
    assert_eq!(left, [1, 2, 3, 4]);
    assert_eq!(right, &[5, 6]);
}

{
    let (left, right) = v.rsplit_array_ref::<6>();
    assert_eq!(left, []);
    assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
}
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2171)
```
pub fn rsplit_array_mut<const N: usize>(&mut self) -> (&mut [T], &mut [T; N])
```

🔬This is a nightly-only experimental API. (`split_array` [#90091](https://github.com/rust-lang/rust/issues/90091))

Divides one mutable slice into an array and a remainder slice at an index from the end.

 The slice will contain all indices from `[0, len - N)` (excluding the index `N` itself) and the array will contain all indices from `[len - N, len)` (excluding the index `len` itself).

 ##### Panics

 Panics if `N > len`.

 ##### Examples

 
```
#![feature(split_array)]

let mut v = &mut [1, 0, 3, 0, 5, 6][..];
let (left, right) = v.rsplit_array_mut::<4>();
assert_eq!(left, [1, 0]);
assert_eq!(right, &mut [3, 0, 5, 6]);
left[1] = 2;
right[1] = 4;
assert_eq!(v, [1, 2, 3, 4, 5, 6]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2220-2222)
```
pub fn split<F>(&self, pred: F) -> Split<'_, T, F> ⓘ
where
    F: FnMut(&T) -> bool,
```

Returns an iterator over subslices separated by elements that match `pred`. The matched element is not contained in the subslices.

 ##### Examples

 
```
let slice = [10, 40, 33, 20];
let mut iter = slice.split(|num| num % 3 == 0);

assert_eq!(iter.next().unwrap(), &[10, 40]);
assert_eq!(iter.next().unwrap(), &[20]);
assert!(iter.next().is_none());
```
 If the first element is matched, an empty slice will be the first item returned by the iterator. Similarly, if the last element in the slice is matched, an empty slice will be the last item returned by the iterator:

 
```
let slice = [10, 40, 33];
let mut iter = slice.split(|num| num % 3 == 0);

assert_eq!(iter.next().unwrap(), &[10, 40]);
assert_eq!(iter.next().unwrap(), &[]);
assert!(iter.next().is_none());
```
 If two matched elements are directly adjacent, an empty slice will be present between them:

 
```
let slice = [10, 6, 33, 20];
let mut iter = slice.split(|num| num % 3 == 0);

assert_eq!(iter.next().unwrap(), &[10]);
assert_eq!(iter.next().unwrap(), &[]);
assert_eq!(iter.next().unwrap(), &[20]);
assert!(iter.next().is_none());
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2242-2244)
```
pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, T, F> ⓘ
where
    F: FnMut(&T) -> bool,
```

Returns an iterator over mutable subslices separated by elements that match `pred`. The matched element is not contained in the subslices.

 ##### Examples

 
```
let mut v = [10, 40, 30, 20, 60, 50];

for group in v.split_mut(|num| *num % 3 == 0) {
    group[0] = 1;
}
assert_eq!(v, [1, 40, 30, 1, 60, 1]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2278-2280)1.51.0
```
pub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<'_, T, F> ⓘ
where
    F: FnMut(&T) -> bool,
```

Returns an iterator over subslices separated by elements that match `pred`. The matched element is contained in the end of the previous subslice as a terminator.

 ##### Examples

 
```
let slice = [10, 40, 33, 20];
let mut iter = slice.split_inclusive(|num| num % 3 == 0);

assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
assert_eq!(iter.next().unwrap(), &[20]);
assert!(iter.next().is_none());
```
 If the last element of the slice is matched, that element will be considered the terminator of the preceding slice. That slice will be the last item returned by the iterator.

 
```
let slice = [3, 10, 40, 33];
let mut iter = slice.split_inclusive(|num| num % 3 == 0);

assert_eq!(iter.next().unwrap(), &[3]);
assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
assert!(iter.next().is_none());
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2302-2304)1.51.0
```
pub fn split_inclusive_mut<F>(&mut self, pred: F) -> SplitInclusiveMut<'_, T, F> ⓘ
where
    F: FnMut(&T) -> bool,
```

Returns an iterator over mutable subslices separated by elements that match `pred`. The matched element is contained in the previous subslice as a terminator.

 ##### Examples

 
```
let mut v = [10, 40, 30, 20, 60, 50];

for group in v.split_inclusive_mut(|num| *num % 3 == 0) {
    let terminator_idx = group.len()-1;
    group[terminator_idx] = 1;
}
assert_eq!(v, [10, 40, 1, 20, 1, 1]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2338-2340)1.27.0
```
pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F> ⓘ
where
    F: FnMut(&T) -> bool,
```

Returns an iterator over subslices separated by elements that match `pred`, starting at the end of the slice and working backwards. The matched element is not contained in the subslices.

 ##### Examples

 
```
let slice = [11, 22, 33, 0, 44, 55];
let mut iter = slice.rsplit(|num| *num == 0);

assert_eq!(iter.next().unwrap(), &[44, 55]);
assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
assert_eq!(iter.next(), None);
```
 As with `split()`, if the first or last element is matched, an empty slice will be the first (or last) item returned by the iterator.

 
```
let v = &[0, 1, 1, 2, 3, 5, 8];
let mut it = v.rsplit(|n| *n % 2 == 0);
assert_eq!(it.next().unwrap(), &[]);
assert_eq!(it.next().unwrap(), &[3, 5]);
assert_eq!(it.next().unwrap(), &[1, 1]);
assert_eq!(it.next().unwrap(), &[]);
assert_eq!(it.next(), None);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2364-2366)1.27.0
```
pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, T, F> ⓘ
where
    F: FnMut(&T) -> bool,
```

Returns an iterator over mutable subslices separated by elements that match `pred`, starting at the end of the slice and working backwards. The matched element is not contained in the subslices.

 ##### Examples

 
```
let mut v = [100, 400, 300, 200, 600, 500];

let mut count = 0;
for group in v.rsplit_mut(|num| *num % 3 == 0) {
    count += 1;
    group[0] = count;
}
assert_eq!(v, [3, 400, 300, 2, 600, 1]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2392-2394)
```
pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F> ⓘ
where
    F: FnMut(&T) -> bool,
```

Returns an iterator over subslices separated by elements that match `pred`, limited to returning at most `n` items. The matched element is not contained in the subslices.

 The last element returned, if any, will contain the remainder of the slice.

 ##### Examples

 Print the slice split once by numbers divisible by 3 (i.e., `[10, 40]`, `[20, 60, 50]`):

 
```
let v = [10, 40, 30, 20, 60, 50];

for group in v.splitn(2, |num| *num % 3 == 0) {
    println!("{group:?}");
}
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2418-2420)
```
pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, T, F> ⓘ
where
    F: FnMut(&T) -> bool,
```

Returns an iterator over mutable subslices separated by elements that match `pred`, limited to returning at most `n` items. The matched element is not contained in the subslices.

 The last element returned, if any, will contain the remainder of the slice.

 ##### Examples

 
```
let mut v = [10, 40, 30, 20, 60, 50];

for group in v.splitn_mut(2, |num| *num % 3 == 0) {
    group[0] = 1;
}
assert_eq!(v, [1, 40, 30, 1, 60, 50]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2447-2449)
```
pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F> ⓘ
where
    F: FnMut(&T) -> bool,
```

Returns an iterator over subslices separated by elements that match `pred` limited to returning at most `n` items. This starts at the end of the slice and works backwards. The matched element is not contained in the subslices.

 The last element returned, if any, will contain the remainder of the slice.

 ##### Examples

 Print the slice split once, starting from the end, by numbers divisible by 3 (i.e., `[50]`, `[10, 40, 30, 20]`):

 
```
let v = [10, 40, 30, 20, 60, 50];

for group in v.rsplitn(2, |num| *num % 3 == 0) {
    println!("{group:?}");
}
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2474-2476)
```
pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, T, F> ⓘ
where
    F: FnMut(&T) -> bool,
```

Returns an iterator over subslices separated by elements that match `pred` limited to returning at most `n` items. This starts at the end of the slice and works backwards. The matched element is not contained in the subslices.

 The last element returned, if any, will contain the remainder of the slice.

 ##### Examples

 
```
let mut s = [10, 40, 30, 20, 60, 50];

for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
    group[0] = 1;
}
assert_eq!(s, [1, 40, 30, 20, 60, 1]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2509-2511)
```
pub fn contains(&self, x: &T) -> bool
where
    T: PartialEq<T>,
```

Returns `true` if the slice contains an element with the given value.

 This operation is *O*(*n*).

 Note that if you have a sorted slice, [`binary_search`](primitive.slice#method.binary_search "method slice::binary_search") may be faster.

 ##### Examples

 
```
let v = [10, 40, 30];
assert!(v.contains(&30));
assert!(!v.contains(&50));
```
 If you do not have a `&T`, but some other value that you can compare with one (for example, `String` implements `PartialEq<str>`), you can use `iter().any`:

 
```
let v = [String::from("hello"), String::from("world")]; // slice of `String`
assert!(v.iter().any(|e| e == "hello")); // search with `&str`
assert!(!v.iter().any(|e| e == "hi"));
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2538-2540)
```
pub fn starts_with(&self, needle: &[T]) -> bool
where
    T: PartialEq<T>,
```

Returns `true` if `needle` is a prefix of the slice.

 ##### Examples

 
```
let v = [10, 40, 30];
assert!(v.starts_with(&[10]));
assert!(v.starts_with(&[10, 40]));
assert!(!v.starts_with(&[50]));
assert!(!v.starts_with(&[10, 50]));
```
 Always returns `true` if `needle` is an empty slice:

 
```
let v = &[10, 40, 30];
assert!(v.starts_with(&[]));
let v: &[u8] = &[];
assert!(v.starts_with(&[]));
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2568-2570)
```
pub fn ends_with(&self, needle: &[T]) -> bool
where
    T: PartialEq<T>,
```

Returns `true` if `needle` is a suffix of the slice.

 ##### Examples

 
```
let v = [10, 40, 30];
assert!(v.ends_with(&[30]));
assert!(v.ends_with(&[40, 30]));
assert!(!v.ends_with(&[50]));
assert!(!v.ends_with(&[50, 30]));
```
 Always returns `true` if `needle` is an empty slice:

 
```
let v = &[10, 40, 30];
assert!(v.ends_with(&[]));
let v: &[u8] = &[];
assert!(v.ends_with(&[]));
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2598-2600)1.51.0
```
pub fn strip_prefix<P>(&self, prefix: &P) -> Option<&[T]>
where
    P: SlicePattern<Item = T> + ?Sized,
    T: PartialEq<T>,
```

Returns a subslice with the prefix removed.

 If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`. If `prefix` is empty, simply returns the original slice.

 If the slice does not start with `prefix`, returns `None`.

 ##### Examples

 
```
let v = &[10, 40, 30];
assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..]));
assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..]));
assert_eq!(v.strip_prefix(&[50]), None);
assert_eq!(v.strip_prefix(&[10, 50]), None);

let prefix : &str = "he";
assert_eq!(b"hello".strip_prefix(prefix.as_bytes()),
           Some(b"llo".as_ref()));
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2632-2634)1.51.0
```
pub fn strip_suffix<P>(&self, suffix: &P) -> Option<&[T]>
where
    P: SlicePattern<Item = T> + ?Sized,
    T: PartialEq<T>,
```

Returns a subslice with the suffix removed.

 If the slice ends with `suffix`, returns the subslice before the suffix, wrapped in `Some`. If `suffix` is empty, simply returns the original slice.

 If the slice does not end with `suffix`, returns `None`.

 ##### Examples

 
```
let v = &[10, 40, 30];
assert_eq!(v.strip_suffix(&[30]), Some(&[10, 40][..]));
assert_eq!(v.strip_suffix(&[40, 30]), Some(&[10][..]));
assert_eq!(v.strip_suffix(&[50]), None);
assert_eq!(v.strip_suffix(&[50, 30]), None);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2716-2718)
```
pub fn binary_search(&self, x: &T) -> Result<usize, usize>
where
    T: Ord,
```

Binary searches this slice for a given element. If the slice is not sorted, the returned result is unspecified and meaningless.

 If the value is found then [`Result::Ok`](result/enum.result#variant.Ok "variant std::result::Result::Ok") is returned, containing the index of the matching element. If there are multiple matches, then any one of the matches could be returned. The index is chosen deterministically, but is subject to change in future versions of Rust. If the value is not found then [`Result::Err`](result/enum.result#variant.Err "variant std::result::Result::Err") is returned, containing the index where a matching element could be inserted while maintaining sorted order.

 See also [`binary_search_by`](primitive.slice#method.binary_search_by "method slice::binary_search_by"), [`binary_search_by_key`](primitive.slice#method.binary_search_by_key "method slice::binary_search_by_key"), and [`partition_point`](primitive.slice#method.partition_point "method slice::partition_point").

 ##### Examples

 Looks up a series of four elements. The first is found, with a uniquely determined position; the second and third are not found; the fourth could match any position in `[1, 4]`.

 
```
let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];

assert_eq!(s.binary_search(&13),  Ok(9));
assert_eq!(s.binary_search(&4),   Err(7));
assert_eq!(s.binary_search(&100), Err(13));
let r = s.binary_search(&1);
assert!(match r { Ok(1..=4) => true, _ => false, });
```
 If you want to find that whole *range* of matching items, rather than an arbitrary matching one, that can be done using [`partition_point`](primitive.slice#method.partition_point "method slice::partition_point"):

 
```
let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];

let low = s.partition_point(|x| x < &1);
assert_eq!(low, 1);
let high = s.partition_point(|x| x <= &1);
assert_eq!(high, 5);
let r = s.binary_search(&1);
assert!((low..high).contains(&r.unwrap()));

assert!(s[..low].iter().all(|&x| x < 1));
assert!(s[low..high].iter().all(|&x| x == 1));
assert!(s[high..].iter().all(|&x| x > 1));

// For something not found, the "range" of equal items is empty
assert_eq!(s.partition_point(|x| x < &11), 9);
assert_eq!(s.partition_point(|x| x <= &11), 9);
assert_eq!(s.binary_search(&11), Err(9));
```
 If you want to insert an item to a sorted vector, while maintaining sort order, consider using [`partition_point`](primitive.slice#method.partition_point "method slice::partition_point"):

 
```
let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
let num = 42;
let idx = s.partition_point(|&x| x < num);
// The above is equivalent to `let idx = s.binary_search(&num).unwrap_or_else(|x| x);`
s.insert(idx, num);
assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2767-2769)
```
pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
where
    F: FnMut(&'a T) -> Ordering,
```

Binary searches this slice with a comparator function.

 The comparator function should return an order code that indicates whether its argument is `Less`, `Equal` or `Greater` the desired target. If the slice is not sorted or if the comparator function does not implement an order consistent with the sort order of the underlying slice, the returned result is unspecified and meaningless.

 If the value is found then [`Result::Ok`](result/enum.result#variant.Ok "variant std::result::Result::Ok") is returned, containing the index of the matching element. If there are multiple matches, then any one of the matches could be returned. The index is chosen deterministically, but is subject to change in future versions of Rust. If the value is not found then [`Result::Err`](result/enum.result#variant.Err "variant std::result::Result::Err") is returned, containing the index where a matching element could be inserted while maintaining sorted order.

 See also [`binary_search`](primitive.slice#method.binary_search "method slice::binary_search"), [`binary_search_by_key`](primitive.slice#method.binary_search_by_key "method slice::binary_search_by_key"), and [`partition_point`](primitive.slice#method.partition_point "method slice::partition_point").

 ##### Examples

 Looks up a series of four elements. The first is found, with a uniquely determined position; the second and third are not found; the fourth could match any position in `[1, 4]`.

 
```
let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];

let seek = 13;
assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
let seek = 4;
assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
let seek = 100;
assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
let seek = 1;
let r = s.binary_search_by(|probe| probe.cmp(&seek));
assert!(match r { Ok(1..=4) => true, _ => false, });
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2856-2859)1.10.0
```
pub fn binary_search_by_key<'a, B, F>(
    &'a self,
    b: &B,
    f: F
) -> Result<usize, usize>
where
    F: FnMut(&'a T) -> B,
    B: Ord,
```

Binary searches this slice with a key extraction function.

 Assumes that the slice is sorted by the key, for instance with [`sort_by_key`](primitive.slice#method.sort_by_key "method slice::sort_by_key") using the same key extraction function. If the slice is not sorted by the key, the returned result is unspecified and meaningless.

 If the value is found then [`Result::Ok`](result/enum.result#variant.Ok "variant std::result::Result::Ok") is returned, containing the index of the matching element. If there are multiple matches, then any one of the matches could be returned. The index is chosen deterministically, but is subject to change in future versions of Rust. If the value is not found then [`Result::Err`](result/enum.result#variant.Err "variant std::result::Result::Err") is returned, containing the index where a matching element could be inserted while maintaining sorted order.

 See also [`binary_search`](primitive.slice#method.binary_search "method slice::binary_search"), [`binary_search_by`](primitive.slice#method.binary_search_by "method slice::binary_search_by"), and [`partition_point`](primitive.slice#method.partition_point "method slice::partition_point").

 ##### Examples

 Looks up a series of four elements in a slice of pairs sorted by their second elements. The first is found, with a uniquely determined position; the second and third are not found; the fourth could match any position in `[1, 4]`.

 
```
let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
         (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
         (1, 21), (2, 34), (4, 55)];

assert_eq!(s.binary_search_by_key(&13, |&(a, b)| b),  Ok(9));
assert_eq!(s.binary_search_by_key(&4, |&(a, b)| b),   Err(7));
assert_eq!(s.binary_search_by_key(&100, |&(a, b)| b), Err(13));
let r = s.binary_search_by_key(&1, |&(a, b)| b);
assert!(match r { Ok(1..=4) => true, _ => false, });
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2892-2894)1.20.0
```
pub fn sort_unstable(&mut self)
where
    T: Ord,
```

Sorts the slice, but might not preserve the order of equal elements.

 This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not allocate), and *O*(*n* \* log(*n*)) worst-case.

 ##### Current implementation

 The current algorithm is based on [pattern-defeating quicksort](https://github.com/orlp/pdqsort) by Orson Peters, which combines the fast average case of randomized quicksort with the fast worst case of heapsort, while achieving linear time on slices with certain patterns. It uses some randomization to avoid degenerate cases, but with a fixed seed to always provide deterministic behavior.

 It is typically faster than stable sorting, except in a few special cases, e.g., when the slice consists of several concatenated sorted sequences.

 ##### Examples

 
```
let mut v = [-5, 4, 1, -3, 2];

v.sort_unstable();
assert!(v == [-5, -3, 1, 2, 4]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2947-2949)1.20.0
```
pub fn sort_unstable_by<F>(&mut self, compare: F)
where
    F: FnMut(&T, &T) -> Ordering,
```

Sorts the slice with a comparator function, but might not preserve the order of equal elements.

 This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not allocate), and *O*(*n* \* log(*n*)) worst-case.

 The comparator function must define a total ordering for the elements in the slice. If the ordering is not total, the order of the elements is unspecified. An order is a total order if it is (for all `a`, `b` and `c`):

 * total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b` is true, and
* transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.

 For example, while [`f64`](primitive.f64 "primitive f64") doesn’t implement [`Ord`](cmp/trait.ord "trait std::cmp::Ord") because `NaN != NaN`, we can use `partial_cmp` as our sort function when we know the slice doesn’t contain a `NaN`.

 
```
let mut floats = [5f64, 4.0, 1.0, 3.0, 2.0];
floats.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap());
assert_eq!(floats, [1.0, 2.0, 3.0, 4.0, 5.0]);
```
 ##### Current implementation

 The current algorithm is based on [pattern-defeating quicksort](https://github.com/orlp/pdqsort) by Orson Peters, which combines the fast average case of randomized quicksort with the fast worst case of heapsort, while achieving linear time on slices with certain patterns. It uses some randomization to avoid degenerate cases, but with a fixed seed to always provide deterministic behavior.

 It is typically faster than stable sorting, except in a few special cases, e.g., when the slice consists of several concatenated sorted sequences.

 ##### Examples

 
```
let mut v = [5, 4, 1, 3, 2];
v.sort_unstable_by(|a, b| a.cmp(b));
assert!(v == [1, 2, 3, 4, 5]);

// reverse sorting
v.sort_unstable_by(|a, b| b.cmp(a));
assert!(v == [5, 4, 3, 2, 1]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#2985-2988)1.20.0
```
pub fn sort_unstable_by_key<K, F>(&mut self, f: F)
where
    F: FnMut(&T) -> K,
    K: Ord,
```

Sorts the slice with a key extraction function, but might not preserve the order of equal elements.

 This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not allocate), and *O*(m \* *n* \* log(*n*)) worst-case, where the key function is *O*(*m*).

 ##### Current implementation

 The current algorithm is based on [pattern-defeating quicksort](https://github.com/orlp/pdqsort) by Orson Peters, which combines the fast average case of randomized quicksort with the fast worst case of heapsort, while achieving linear time on slices with certain patterns. It uses some randomization to avoid degenerate cases, but with a fixed seed to always provide deterministic behavior.

 Due to its key calling strategy, [`sort_unstable_by_key`](#method.sort_unstable_by_key) is likely to be slower than [`sort_by_cached_key`](#method.sort_by_cached_key) in cases where the key function is expensive.

 ##### Examples

 
```
let mut v = [-5i32, 4, 1, -3, 2];

v.sort_unstable_by_key(|k| k.abs());
assert!(v == [1, 2, -3, 4, -5]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3035-3037)1.49.0
```
pub fn select_nth_unstable(
    &mut self,
    index: usize
) -> (&mut [T], &mut T, &mut [T])
where
    T: Ord,
```

Reorder the slice such that the element at `index` is at its final sorted position.

 This reordering has the additional property that any value at position `i < index` will be less than or equal to any value at a position `j > index`. Additionally, this reordering is unstable (i.e. any number of equal elements may end up at position `index`), in-place (i.e. does not allocate), and *O*(*n*) on average. The worst-case performance is *O*(*n* log *n*). This function is also known as “kth element” in other libraries.

 It returns a triplet of the following from the reordered slice: the subslice prior to `index`, the element at `index`, and the subslice after `index`; accordingly, the values in those two subslices will respectively all be less-than-or-equal-to and greater-than-or-equal-to the value of the element at `index`.

 ##### Current implementation

 The current algorithm is an introselect implementation based on Pattern Defeating Quicksort, which is also the basis for [`sort_unstable`](primitive.slice#method.sort_unstable "method slice::sort_unstable"). The fallback algorithm is Median of Medians using Tukey’s Ninther for pivot selection, which guarantees linear runtime for all inputs.

 ##### Panics

 Panics when `index >= len()`, meaning it always panics on empty slices.

 ##### Examples

 
```
let mut v = [-5i32, 4, 1, -3, 2];

// Find the median
v.select_nth_unstable(2);

// We are only guaranteed the slice will be one of the following, based on the way we sort
// about the specified index.
assert!(v == [-3, -5, 1, 2, 4] ||
        v == [-5, -3, 1, 2, 4] ||
        v == [-3, -5, 1, 4, 2] ||
        v == [-5, -3, 1, 4, 2]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3087-3093)1.49.0
```
pub fn select_nth_unstable_by<F>(
    &mut self,
    index: usize,
    compare: F
) -> (&mut [T], &mut T, &mut [T])
where
    F: FnMut(&T, &T) -> Ordering,
```

Reorder the slice with a comparator function such that the element at `index` is at its final sorted position.

 This reordering has the additional property that any value at position `i < index` will be less than or equal to any value at a position `j > index` using the comparator function. Additionally, this reordering is unstable (i.e. any number of equal elements may end up at position `index`), in-place (i.e. does not allocate), and *O*(*n*) on average. The worst-case performance is *O*(*n* log *n*). This function is also known as “kth element” in other libraries.

 It returns a triplet of the following from the slice reordered according to the provided comparator function: the subslice prior to `index`, the element at `index`, and the subslice after `index`; accordingly, the values in those two subslices will respectively all be less-than-or-equal-to and greater-than-or-equal-to the value of the element at `index`.

 ##### Current implementation

 The current algorithm is an introselect implementation based on Pattern Defeating Quicksort, which is also the basis for [`sort_unstable`](primitive.slice#method.sort_unstable "method slice::sort_unstable"). The fallback algorithm is Median of Medians using Tukey’s Ninther for pivot selection, which guarantees linear runtime for all inputs.

 ##### Panics

 Panics when `index >= len()`, meaning it always panics on empty slices.

 ##### Examples

 
```
let mut v = [-5i32, 4, 1, -3, 2];

// Find the median as if the slice were sorted in descending order.
v.select_nth_unstable_by(2, |a, b| b.cmp(a));

// We are only guaranteed the slice will be one of the following, based on the way we sort
// about the specified index.
assert!(v == [2, 4, 1, -5, -3] ||
        v == [2, 4, 1, -3, -5] ||
        v == [4, 2, 1, -5, -3] ||
        v == [4, 2, 1, -3, -5]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3142-3149)1.49.0
```
pub fn select_nth_unstable_by_key<K, F>(
    &mut self,
    index: usize,
    f: F
) -> (&mut [T], &mut T, &mut [T])
where
    F: FnMut(&T) -> K,
    K: Ord,
```

Reorder the slice with a key extraction function such that the element at `index` is at its final sorted position.

 This reordering has the additional property that any value at position `i < index` will be less than or equal to any value at a position `j > index` using the key extraction function. Additionally, this reordering is unstable (i.e. any number of equal elements may end up at position `index`), in-place (i.e. does not allocate), and *O*(*n*) on average. The worst-case performance is *O*(*n* log *n*). This function is also known as “kth element” in other libraries.

 It returns a triplet of the following from the slice reordered according to the provided key extraction function: the subslice prior to `index`, the element at `index`, and the subslice after `index`; accordingly, the values in those two subslices will respectively all be less-than-or-equal-to and greater-than-or-equal-to the value of the element at `index`.

 ##### Current implementation

 The current algorithm is based on the quickselect portion of the same quicksort algorithm used for [`sort_unstable`](primitive.slice#method.sort_unstable "method slice::sort_unstable").

 ##### Panics

 Panics when `index >= len()`, meaning it always panics on empty slices.

 ##### Examples

 
```
let mut v = [-5i32, 4, 1, -3, 2];

// Return the median as if the array were sorted according to absolute value.
v.select_nth_unstable_by_key(2, |a| a.abs());

// We are only guaranteed the slice will be one of the following, based on the way we sort
// about the specified index.
assert!(v == [1, 2, -3, 4, -5] ||
        v == [1, 2, -3, -5, 4] ||
        v == [2, 1, -3, 4, -5] ||
        v == [2, 1, -3, -5, 4]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3176-3178)
```
pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])
where
    T: PartialEq<T>,
```

🔬This is a nightly-only experimental API. (`slice_partition_dedup` [#54279](https://github.com/rust-lang/rust/issues/54279))

Moves all consecutive repeated elements to the end of the slice according to the [`PartialEq`](cmp/trait.partialeq "trait std::cmp::PartialEq") trait implementation.

 Returns two slices. The first contains no consecutive repeated elements. The second contains all the duplicates in no specified order.

 If the slice is sorted, the first returned slice contains no duplicates.

 ##### Examples

 
```
#![feature(slice_partition_dedup)]

let mut slice = [1, 2, 2, 3, 3, 2, 1, 1];

let (dedup, duplicates) = slice.partition_dedup();

assert_eq!(dedup, [1, 2, 3, 2, 1]);
assert_eq!(duplicates, [2, 3, 1]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3210-3212)
```
pub fn partition_dedup_by<F>(&mut self, same_bucket: F) -> (&mut [T], &mut [T])
where
    F: FnMut(&mut T, &mut T) -> bool,
```

🔬This is a nightly-only experimental API. (`slice_partition_dedup` [#54279](https://github.com/rust-lang/rust/issues/54279))

Moves all but the first of consecutive elements to the end of the slice satisfying a given equality relation.

 Returns two slices. The first contains no consecutive repeated elements. The second contains all the duplicates in no specified order.

 The `same_bucket` function is passed references to two elements from the slice and must determine if the elements compare equal. The elements are passed in opposite order from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is moved at the end of the slice.

 If the slice is sorted, the first returned slice contains no duplicates.

 ##### Examples

 
```
#![feature(slice_partition_dedup)]

let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"];

let (dedup, duplicates) = slice.partition_dedup_by(|a, b| a.eq_ignore_ascii_case(b));

assert_eq!(dedup, ["foo", "BAZ", "Bar", "baz"]);
assert_eq!(duplicates, ["bar", "Foo", "BAZ"]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3336-3339)
```
pub fn partition_dedup_by_key<K, F>(&mut self, key: F) -> (&mut [T], &mut [T])
where
    F: FnMut(&mut T) -> K,
    K: PartialEq<K>,
```

🔬This is a nightly-only experimental API. (`slice_partition_dedup` [#54279](https://github.com/rust-lang/rust/issues/54279))

Moves all but the first of consecutive elements to the end of the slice that resolve to the same key.

 Returns two slices. The first contains no consecutive repeated elements. The second contains all the duplicates in no specified order.

 If the slice is sorted, the first returned slice contains no duplicates.

 ##### Examples

 
```
#![feature(slice_partition_dedup)]

let mut slice = [10, 20, 21, 30, 30, 20, 11, 13];

let (dedup, duplicates) = slice.partition_dedup_by_key(|i| *i / 10);

assert_eq!(dedup, [10, 20, 30, 20, 11]);
assert_eq!(duplicates, [21, 30, 13]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3375)1.26.0
```
pub fn rotate_left(&mut self, mid: usize)
```

Rotates the slice in-place such that the first `mid` elements of the slice move to the end while the last `self.len() - mid` elements move to the front. After calling `rotate_left`, the element previously at index `mid` will become the first element in the slice.

 ##### Panics

 This function will panic if `mid` is greater than the length of the slice. Note that `mid == self.len()` does *not* panic and is a no-op rotation.

 ##### Complexity

 Takes linear (in `self.len()`) time.

 ##### Examples

 
```
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
a.rotate_left(2);
assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
```
 Rotating a subslice:

 
```
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
a[1..5].rotate_left(1);
assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3418)1.26.0
```
pub fn rotate_right(&mut self, k: usize)
```

Rotates the slice in-place such that the first `self.len() - k` elements of the slice move to the end while the last `k` elements move to the front. After calling `rotate_right`, the element previously at index `self.len() - k` will become the first element in the slice.

 ##### Panics

 This function will panic if `k` is greater than the length of the slice. Note that `k == self.len()` does *not* panic and is a no-op rotation.

 ##### Complexity

 Takes linear (in `self.len()`) time.

 ##### Examples

 
```
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
a.rotate_right(2);
assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
```
 Rotate a subslice:

 
```
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
a[1..5].rotate_right(1);
assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3441-3443)1.50.0
```
pub fn fill(&mut self, value: T)
where
    T: Clone,
```

Fills `self` with elements by cloning `value`.

 ##### Examples

 
```
let mut buf = vec![0; 10];
buf.fill(1);
assert_eq!(buf, vec![1; 10]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3465-3467)1.51.0
```
pub fn fill_with<F>(&mut self, f: F)
where
    F: FnMut() -> T,
```

Fills `self` with elements returned by calling a closure repeatedly.

 This method uses a closure to create new values. If you’d rather [`Clone`](clone/trait.clone "trait std::clone::Clone") a given value, use [`fill`](primitive.slice#method.fill "method slice::fill"). If you want to use the [`Default`](default/trait.default "trait std::default::Default") trait to generate values, you can pass [`Default::default`](default/trait.default#tymethod.default "associated function std::default::Default::default") as the argument.

 ##### Examples

 
```
let mut buf = vec![1; 10];
buf.fill_with(Default::default);
assert_eq!(buf, vec![0; 10]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3528-3530)1.7.0
```
pub fn clone_from_slice(&mut self, src: &[T])
where
    T: Clone,
```

Copies the elements from `src` into `self`.

 The length of `src` must be the same as `self`.

 ##### Panics

 This function will panic if the two slices have different lengths.

 ##### Examples

 Cloning two elements from a slice into another:

 
```
let src = [1, 2, 3, 4];
let mut dst = [0, 0];

// Because the slices have to be the same length,
// we slice the source slice from four elements
// to two. It will panic if we don't do this.
dst.clone_from_slice(&src[2..]);

assert_eq!(src, [1, 2, 3, 4]);
assert_eq!(dst, [3, 4]);
```
 Rust enforces that there can only be one mutable reference with no immutable references to a particular piece of data in a particular scope. Because of this, attempting to use `clone_from_slice` on a single slice will result in a compile failure:

 ⓘ
```
let mut slice = [1, 2, 3, 4, 5];

slice[..2].clone_from_slice(&slice[3..]); // compile fail!
```

 To work around this, we can use [`split_at_mut`](primitive.slice#method.split_at_mut "method slice::split_at_mut") to create two distinct sub-slices from a slice:

 
```
let mut slice = [1, 2, 3, 4, 5];

{
    let (left, right) = slice.split_at_mut(2);
    left.clone_from_slice(&right[1..]);
}

assert_eq!(slice, [4, 5, 3, 4, 5]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3592-3594)1.9.0
```
pub fn copy_from_slice(&mut self, src: &[T])
where
    T: Copy,
```

Copies all elements from `src` into `self`, using a memcpy.

 The length of `src` must be the same as `self`.

 If `T` does not implement `Copy`, use [`clone_from_slice`](primitive.slice#method.clone_from_slice "method slice::clone_from_slice").

 ##### Panics

 This function will panic if the two slices have different lengths.

 ##### Examples

 Copying two elements from a slice into another:

 
```
let src = [1, 2, 3, 4];
let mut dst = [0, 0];

// Because the slices have to be the same length,
// we slice the source slice from four elements
// to two. It will panic if we don't do this.
dst.copy_from_slice(&src[2..]);

assert_eq!(src, [1, 2, 3, 4]);
assert_eq!(dst, [3, 4]);
```
 Rust enforces that there can only be one mutable reference with no immutable references to a particular piece of data in a particular scope. Because of this, attempting to use `copy_from_slice` on a single slice will result in a compile failure:

 ⓘ
```
let mut slice = [1, 2, 3, 4, 5];

slice[..2].copy_from_slice(&slice[3..]); // compile fail!
```

 To work around this, we can use [`split_at_mut`](primitive.slice#method.split_at_mut "method slice::split_at_mut") to create two distinct sub-slices from a slice:

 
```
let mut slice = [1, 2, 3, 4, 5];

{
    let (left, right) = slice.split_at_mut(2);
    left.copy_from_slice(&right[1..]);
}

assert_eq!(slice, [4, 5, 3, 4, 5]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3646-3648)1.37.0
```
pub fn copy_within<R>(&mut self, src: R, dest: usize)
where
    R: RangeBounds<usize>,
    T: Copy,
```

Copies elements from one part of the slice to another part of itself, using a memmove.

 `src` is the range within `self` to copy from. `dest` is the starting index of the range within `self` to copy to, which will have the same length as `src`. The two ranges may overlap. The ends of the two ranges must be less than or equal to `self.len()`.

 ##### Panics

 This function will panic if either range exceeds the end of the slice, or if the end of `src` is before the start.

 ##### Examples

 Copying four bytes within a slice:

 
```
let mut bytes = *b"Hello, World!";

bytes.copy_within(1..5, 8);

assert_eq!(&bytes, b"Hello, Wello!");
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3713)1.27.0
```
pub fn swap_with_slice(&mut self, other: &mut [T])
```

Swaps all elements in `self` with those in `other`.

 The length of `other` must be the same as `self`.

 ##### Panics

 This function will panic if the two slices have different lengths.

 ##### Example

 Swapping two elements across slices:

 
```
let mut slice1 = [0, 0];
let mut slice2 = [1, 2, 3, 4];

slice1.swap_with_slice(&mut slice2[2..]);

assert_eq!(slice1, [3, 4]);
assert_eq!(slice2, [1, 2, 0, 0]);
```
 Rust enforces that there can only be one mutable reference to a particular piece of data in a particular scope. Because of this, attempting to use `swap_with_slice` on a single slice will result in a compile failure:

 ⓘ
```
let mut slice = [1, 2, 3, 4, 5];
slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
```

 To work around this, we can use [`split_at_mut`](primitive.slice#method.split_at_mut "method slice::split_at_mut") to create two distinct mutable sub-slices from a slice:

 
```
let mut slice = [1, 2, 3, 4, 5];

{
    let (left, right) = slice.split_at_mut(2);
    left.swap_with_slice(&mut right[1..]);
}

assert_eq!(slice, [4, 5, 3, 1, 2]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3793)1.30.0
```
pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T])
```

Transmute the slice to a slice of another type, ensuring alignment of the types is maintained.

 This method splits the slice into three distinct slices: prefix, correctly aligned middle slice of a new type, and the suffix slice. How exactly the slice is split up is not specified; the middle part may be smaller than necessary. However, if this fails to return a maximal middle part, that is because code is running in a context where performance does not matter, such as a sanitizer attempting to find alignment bugs. Regular code running in a default (debug or release) execution *will* return a maximal middle part.

 This method has no purpose when either input element `T` or output element `U` are zero-sized and will return the original slice without splitting anything.

 ##### Safety

 This method is essentially a `transmute` with respect to the elements in the returned middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.

 ##### Examples

 Basic usage:

 
```
unsafe {
    let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
    let (prefix, shorts, suffix) = bytes.align_to::<u16>();
    // less_efficient_algorithm_for_bytes(prefix);
    // more_efficient_algorithm_for_aligned_shorts(shorts);
    // less_efficient_algorithm_for_bytes(suffix);
}
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3855)1.30.0
```
pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T])
```

Transmute the mutable slice to a mutable slice of another type, ensuring alignment of the types is maintained.

 This method splits the slice into three distinct slices: prefix, correctly aligned middle slice of a new type, and the suffix slice. How exactly the slice is split up is not specified; the middle part may be smaller than necessary. However, if this fails to return a maximal middle part, that is because code is running in a context where performance does not matter, such as a sanitizer attempting to find alignment bugs. Regular code running in a default (debug or release) execution *will* return a maximal middle part.

 This method has no purpose when either input element `T` or output element `U` are zero-sized and will return the original slice without splitting anything.

 ##### Safety

 This method is essentially a `transmute` with respect to the elements in the returned middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.

 ##### Examples

 Basic usage:

 
```
unsafe {
    let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
    let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
    // less_efficient_algorithm_for_bytes(prefix);
    // more_efficient_algorithm_for_aligned_shorts(shorts);
    // less_efficient_algorithm_for_bytes(suffix);
}
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3950-3954)
```
pub fn as_simd<const LANES: usize>(&self) -> (&[T], &[Simd<T, LANES>], &[T])
where
    Simd<T, LANES>: AsRef<[T; LANES]>,
    T: SimdElement,
    LaneCount<LANES>: SupportedLaneCount,
```

🔬This is a nightly-only experimental API. (`portable_simd` [#86656](https://github.com/rust-lang/rust/issues/86656))

Split a slice into a prefix, a middle of aligned SIMD types, and a suffix.

 This is a safe wrapper around [`slice::align_to`](primitive.slice#method.align_to "method slice::align_to"), so has the same weak postconditions as that method. You’re only assured that `self.len() == prefix.len() + middle.len() * LANES + suffix.len()`.

 Notably, all of the following are possible:

 * `prefix.len() >= LANES`.
* `middle.is_empty()` despite `self.len() >= 3 * LANES`.
* `suffix.len() >= LANES`.

 That said, this is a safe method, so if you’re only writing safe code, then this can at most cause incorrect logic, not unsoundness.

 ##### Panics

 This will panic if the size of the SIMD type is different from `LANES` times that of the scalar.

 At the time of writing, the trait restrictions on `Simd<T, LANES>` keeps that from ever happening, as only power-of-two numbers of lanes are supported. It’s possible that, in the future, those restrictions might be lifted in a way that would make it possible to see panics from this method for something like `LANES == 3`.

 ##### Examples

 
```
#![feature(portable_simd)]
use core::simd::SimdFloat;

let short = &[1, 2, 3];
let (prefix, middle, suffix) = short.as_simd::<4>();
assert_eq!(middle, []); // Not enough elements for anything in the middle

// They might be split in any possible way between prefix and suffix
let it = prefix.iter().chain(suffix).copied();
assert_eq!(it.collect::<Vec<_>>(), vec![1, 2, 3]);

fn basic_simd_sum(x: &[f32]) -> f32 {
    use std::ops::Add;
    use std::simd::f32x4;
    let (prefix, middle, suffix) = x.as_simd();
    let sums = f32x4::from_array([
        prefix.iter().copied().sum(),
        0.0,
        0.0,
        suffix.iter().copied().sum(),
    ]);
    let sums = middle.iter().copied().fold(sums, f32x4::add);
    sums.reduce_sum()
}

let numbers: Vec<f32> = (1..101).map(|x| x as _).collect();
assert_eq!(basic_simd_sum(&numbers[1..99]), 4949.0);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#3995-3999)
```
pub fn as_simd_mut<const LANES: usize>(
    &mut self
) -> (&mut [T], &mut [Simd<T, LANES>], &mut [T])
where
    Simd<T, LANES>: AsMut<[T; LANES]>,
    T: SimdElement,
    LaneCount<LANES>: SupportedLaneCount,
```

🔬This is a nightly-only experimental API. (`portable_simd` [#86656](https://github.com/rust-lang/rust/issues/86656))

Split a mutable slice into a mutable prefix, a middle of aligned SIMD types, and a mutable suffix.

 This is a safe wrapper around [`slice::align_to_mut`](primitive.slice#method.align_to_mut "method slice::align_to_mut"), so has the same weak postconditions as that method. You’re only assured that `self.len() == prefix.len() + middle.len() * LANES + suffix.len()`.

 Notably, all of the following are possible:

 * `prefix.len() >= LANES`.
* `middle.is_empty()` despite `self.len() >= 3 * LANES`.
* `suffix.len() >= LANES`.

 That said, this is a safe method, so if you’re only writing safe code, then this can at most cause incorrect logic, not unsoundness.

 This is the mutable version of [`slice::as_simd`](primitive.slice#method.as_simd "method slice::as_simd"); see that for examples.

 ##### Panics

 This will panic if the size of the SIMD type is different from `LANES` times that of the scalar.

 At the time of writing, the trait restrictions on `Simd<T, LANES>` keeps that from ever happening, as only power-of-two numbers of lanes are supported. It’s possible that, in the future, those restrictions might be lifted in a way that would make it possible to see panics from this method for something like `LANES == 3`.

 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4035-4037)
```
pub fn is_sorted(&self) -> bool
where
    T: PartialOrd<T>,
```

🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485))

Checks if the elements of this slice are sorted.

 That is, for each element `a` and its following element `b`, `a <= b` must hold. If the slice yields exactly zero or one element, `true` is returned.

 Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition implies that this function returns `false` if any two consecutive items are not comparable.

 ##### Examples

 
```
#![feature(is_sorted)]
let empty: [i32; 0] = [];

assert!([1, 2, 2, 9].is_sorted());
assert!(![1, 3, 2, 4].is_sorted());
assert!([0].is_sorted());
assert!(empty.is_sorted());
assert!(![0.0, 1.0, f32::NAN].is_sorted());
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4051-4053)
```
pub fn is_sorted_by<'a, F>(&'a self, compare: F) -> bool
where
    F: FnMut(&'a T, &'a T) -> Option<Ordering>,
```

🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485))

Checks if the elements of this slice are sorted using the given comparator function.

 Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare` function to determine the ordering of two elements. Apart from that, it’s equivalent to [`is_sorted`](primitive.slice#method.is_sorted "method slice::is_sorted"); see its documentation for more information.

 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4077-4080)
```
pub fn is_sorted_by_key<'a, F, K>(&'a self, f: F) -> bool
where
    F: FnMut(&'a T) -> K,
    K: PartialOrd<K>,
```

🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485))

Checks if the elements of this slice are sorted using the given key extraction function.

 Instead of comparing the slice’s elements directly, this function compares the keys of the elements, as determined by `f`. Apart from that, it’s equivalent to [`is_sorted`](primitive.slice#method.is_sorted "method slice::is_sorted"); see its documentation for more information.

 ##### Examples

 
```
#![feature(is_sorted)]

assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));
assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4136-4138)1.52.0
```
pub fn partition_point<P>(&self, pred: P) -> usize
where
    P: FnMut(&T) -> bool,
```

Returns the index of the partition point according to the given predicate (the index of the first element of the second partition).

 The slice is assumed to be partitioned according to the given predicate. This means that all elements for which the predicate returns true are at the start of the slice and all elements for which the predicate returns false are at the end. For example, `[7, 15, 3, 5, 4, 12, 6]` is partitioned under the predicate `x % 2 != 0` (all odd numbers are at the start, all even at the end).

 If this slice is not partitioned, the returned result is unspecified and meaningless, as this method performs a kind of binary search.

 See also [`binary_search`](primitive.slice#method.binary_search "method slice::binary_search"), [`binary_search_by`](primitive.slice#method.binary_search_by "method slice::binary_search_by"), and [`binary_search_by_key`](primitive.slice#method.binary_search_by_key "method slice::binary_search_by_key").

 ##### Examples

 
```
let v = [1, 2, 3, 3, 5, 6, 7];
let i = v.partition_point(|&x| x < 5);

assert_eq!(i, 4);
assert!(v[..i].iter().all(|&x| x < 5));
assert!(v[i..].iter().all(|&x| !(x < 5)));
```
 If all elements of the slice match the predicate, including if the slice is empty, then the length of the slice will be returned:

 
```
let a = [2, 4, 8];
assert_eq!(a.partition_point(|x| x < &100), a.len());
let a: [i32; 0] = [];
assert_eq!(a.partition_point(|x| x < &100), 0);
```
 If you want to insert an item to a sorted vector, while maintaining sort order:

 
```
let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
let num = 42;
let idx = s.partition_point(|&x| x < num);
s.insert(idx, num);
assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4194)
```
pub fn take<R, 'a>(self: &mut &'a [T], range: R) -> Option<&'a [T]>
where
    R: OneSidedRange<usize>,
```

🔬This is a nightly-only experimental API. (`slice_take` [#62280](https://github.com/rust-lang/rust/issues/62280))

Removes the subslice corresponding to the given range and returns a reference to it.

 Returns `None` and does not modify the slice if the given range is out of bounds.

 Note that this method only accepts one-sided ranges such as `2..` or `..6`, but not `2..6`.

 ##### Examples

 Taking the first three elements of a slice:

 
```
#![feature(slice_take)]

let mut slice: &[_] = &['a', 'b', 'c', 'd'];
let mut first_three = slice.take(..3).unwrap();

assert_eq!(slice, &['d']);
assert_eq!(first_three, &['a', 'b', 'c']);
```
 Taking the last two elements of a slice:

 
```
#![feature(slice_take)]

let mut slice: &[_] = &['a', 'b', 'c', 'd'];
let mut tail = slice.take(2..).unwrap();

assert_eq!(slice, &['a', 'b']);
assert_eq!(tail, &['c', 'd']);
```
 Getting `None` when `range` is out of bounds:

 
```
#![feature(slice_take)]

let mut slice: &[_] = &['a', 'b', 'c', 'd'];

assert_eq!(None, slice.take(5..));
assert_eq!(None, slice.take(..5));
assert_eq!(None, slice.take(..=4));
let expected: &[char] = &['a', 'b', 'c', 'd'];
assert_eq!(Some(expected), slice.take(..4));
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4263-4266)
```
pub fn take_mut<R, 'a>(self: &mut &'a mut [T], range: R) -> Option<&'a mut [T]>
where
    R: OneSidedRange<usize>,
```

🔬This is a nightly-only experimental API. (`slice_take` [#62280](https://github.com/rust-lang/rust/issues/62280))

Removes the subslice corresponding to the given range and returns a mutable reference to it.

 Returns `None` and does not modify the slice if the given range is out of bounds.

 Note that this method only accepts one-sided ranges such as `2..` or `..6`, but not `2..6`.

 ##### Examples

 Taking the first three elements of a slice:

 
```
#![feature(slice_take)]

let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
let mut first_three = slice.take_mut(..3).unwrap();

assert_eq!(slice, &mut ['d']);
assert_eq!(first_three, &mut ['a', 'b', 'c']);
```
 Taking the last two elements of a slice:

 
```
#![feature(slice_take)]

let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
let mut tail = slice.take_mut(2..).unwrap();

assert_eq!(slice, &mut ['a', 'b']);
assert_eq!(tail, &mut ['c', 'd']);
```
 Getting `None` when `range` is out of bounds:

 
```
#![feature(slice_take)]

let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];

assert_eq!(None, slice.take_mut(5..));
assert_eq!(None, slice.take_mut(..5));
assert_eq!(None, slice.take_mut(..=4));
let expected: &mut [_] = &mut ['a', 'b', 'c', 'd'];
assert_eq!(Some(expected), slice.take_mut(..4));
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4302)
```
pub fn take_first<'a>(self: &mut &'a [T]) -> Option<&'a T>
```

🔬This is a nightly-only experimental API. (`slice_take` [#62280](https://github.com/rust-lang/rust/issues/62280))

Removes the first element of the slice and returns a reference to it.

 Returns `None` if the slice is empty.

 ##### Examples

 
```
#![feature(slice_take)]

let mut slice: &[_] = &['a', 'b', 'c'];
let first = slice.take_first().unwrap();

assert_eq!(slice, &['b', 'c']);
assert_eq!(first, &'a');
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4327)
```
pub fn take_first_mut<'a>(self: &mut &'a mut [T]) -> Option<&'a mut T>
```

🔬This is a nightly-only experimental API. (`slice_take` [#62280](https://github.com/rust-lang/rust/issues/62280))

Removes the first element of the slice and returns a mutable reference to it.

 Returns `None` if the slice is empty.

 ##### Examples

 
```
#![feature(slice_take)]

let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
let first = slice.take_first_mut().unwrap();
*first = 'd';

assert_eq!(slice, &['b', 'c']);
assert_eq!(first, &'d');
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4351)
```
pub fn take_last<'a>(self: &mut &'a [T]) -> Option<&'a T>
```

🔬This is a nightly-only experimental API. (`slice_take` [#62280](https://github.com/rust-lang/rust/issues/62280))

Removes the last element of the slice and returns a reference to it.

 Returns `None` if the slice is empty.

 ##### Examples

 
```
#![feature(slice_take)]

let mut slice: &[_] = &['a', 'b', 'c'];
let last = slice.take_last().unwrap();

assert_eq!(slice, &['a', 'b']);
assert_eq!(last, &'c');
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4376)
```
pub fn take_last_mut<'a>(self: &mut &'a mut [T]) -> Option<&'a mut T>
```

🔬This is a nightly-only experimental API. (`slice_take` [#62280](https://github.com/rust-lang/rust/issues/62280))

Removes the last element of the slice and returns a mutable reference to it.

 Returns `None` if the slice is empty.

 ##### Examples

 
```
#![feature(slice_take)]

let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
let last = slice.take_last_mut().unwrap();
*last = 'd';

assert_eq!(slice, &['a', 'b']);
assert_eq!(last, &'d');
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4410-4413)
```
pub unsafe fn get_many_unchecked_mut<const N: usize>(
    &mut self,
    indices: [usize; N]
) -> [&mut T; N]
```

🔬This is a nightly-only experimental API. (`get_many_mut` [#104642](https://github.com/rust-lang/rust/issues/104642))

Returns mutable references to many indices at once, without doing any checks.

 For a safe alternative see [`get_many_mut`](primitive.slice#method.get_many_mut "method slice::get_many_mut").

 ##### Safety

 Calling this method with overlapping or out-of-bounds indices is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting references are not used.

 ##### Examples

 
```
#![feature(get_many_mut)]

let x = &mut [1, 2, 4];

unsafe {
    let [a, b] = x.get_many_unchecked_mut([0, 2]);
    *a *= 10;
    *b *= 100;
}
assert_eq!(x, &[10, 2, 400]);
```
 
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4452-4455)
```
pub fn get_many_mut<const N: usize>(
    &mut self,
    indices: [usize; N]
) -> Result<[&mut T; N], GetManyMutError<N>>
```

🔬This is a nightly-only experimental API. (`get_many_mut` [#104642](https://github.com/rust-lang/rust/issues/104642))

Returns mutable references to many indices at once.

 Returns an error if any index is out-of-bounds, or if the same index was passed more than once.

 ##### Examples

 
```
#![feature(get_many_mut)]

let v = &mut [1, 2, 3];
if let Ok([a, b]) = v.get_many_mut([0, 2]) {
    *a = 413;
    *b = 612;
}
assert_eq!(v, &[413, 2, 612]);
```
 

[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#176)
```
impl<T> [T]
```

[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#207-209)
```
pub fn sort(&mut self)
where
    T: Ord,
```

Sorts the slice.

 This sort is stable (i.e., does not reorder equal elements) and *O*(*n* \* log(*n*)) worst-case.

 When applicable, unstable sorting is preferred because it is generally faster than stable sorting and it doesn’t allocate auxiliary memory. See [`sort_unstable`](primitive.slice#method.sort_unstable "method slice::sort_unstable").

 ##### Current implementation

 The current algorithm is an adaptive, iterative merge sort inspired by [timsort](https://en.wikipedia.org/wiki/Timsort). It is designed to be very fast in cases where the slice is nearly sorted, or consists of two or more sorted sequences concatenated one after another.

 Also, it allocates temporary storage half the size of `self`, but for short slices a non-allocating insertion sort is used instead.

 ##### Examples

 
```
let mut v = [-5, 4, 1, -3, 2];

v.sort();
assert!(v == [-5, -3, 1, 2, 4]);
```
 
[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#263-265)
```
pub fn sort_by<F>(&mut self, compare: F)
where
    F: FnMut(&T, &T) -> Ordering,
```

Sorts the slice with a comparator function.

 This sort is stable (i.e., does not reorder equal elements) and *O*(*n* \* log(*n*)) worst-case.

 The comparator function must define a total ordering for the elements in the slice. If the ordering is not total, the order of the elements is unspecified. An order is a total order if it is (for all `a`, `b` and `c`):

 * total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b` is true, and
* transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.

 For example, while [`f64`](primitive.f64 "primitive f64") doesn’t implement [`Ord`](cmp/trait.ord "trait std::cmp::Ord") because `NaN != NaN`, we can use `partial_cmp` as our sort function when we know the slice doesn’t contain a `NaN`.

 
```
let mut floats = [5f64, 4.0, 1.0, 3.0, 2.0];
floats.sort_by(|a, b| a.partial_cmp(b).unwrap());
assert_eq!(floats, [1.0, 2.0, 3.0, 4.0, 5.0]);
```
 When applicable, unstable sorting is preferred because it is generally faster than stable sorting and it doesn’t allocate auxiliary memory. See [`sort_unstable_by`](primitive.slice#method.sort_unstable_by "method slice::sort_unstable_by").

 ##### Current implementation

 The current algorithm is an adaptive, iterative merge sort inspired by [timsort](https://en.wikipedia.org/wiki/Timsort). It is designed to be very fast in cases where the slice is nearly sorted, or consists of two or more sorted sequences concatenated one after another.

 Also, it allocates temporary storage half the size of `self`, but for short slices a non-allocating insertion sort is used instead.

 ##### Examples

 
```
let mut v = [5, 4, 1, 3, 2];
v.sort_by(|a, b| a.cmp(b));
assert!(v == [1, 2, 3, 4, 5]);

// reverse sorting
v.sort_by(|a, b| b.cmp(a));
assert!(v == [5, 4, 3, 2, 1]);
```
 
[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#305-308)1.7.0
```
pub fn sort_by_key<K, F>(&mut self, f: F)
where
    F: FnMut(&T) -> K,
    K: Ord,
```

Sorts the slice with a key extraction function.

 This sort is stable (i.e., does not reorder equal elements) and *O*(*m* \* *n* \* log(*n*)) worst-case, where the key function is *O*(*m*).

 For expensive key functions (e.g. functions that are not simple property accesses or basic operations), [`sort_by_cached_key`](primitive.slice#method.sort_by_cached_key "method slice::sort_by_cached_key") is likely to be significantly faster, as it does not recompute element keys.

 When applicable, unstable sorting is preferred because it is generally faster than stable sorting and it doesn’t allocate auxiliary memory. See [`sort_unstable_by_key`](primitive.slice#method.sort_unstable_by_key "method slice::sort_unstable_by_key").

 ##### Current implementation

 The current algorithm is an adaptive, iterative merge sort inspired by [timsort](https://en.wikipedia.org/wiki/Timsort). It is designed to be very fast in cases where the slice is nearly sorted, or consists of two or more sorted sequences concatenated one after another.

 Also, it allocates temporary storage half the size of `self`, but for short slices a non-allocating insertion sort is used instead.

 ##### Examples

 
```
let mut v = [-5i32, 4, 1, -3, 2];

v.sort_by_key(|k| k.abs());
assert!(v == [1, 2, -3, 4, -5]);
```
 
[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#352-355)1.34.0
```
pub fn sort_by_cached_key<K, F>(&mut self, f: F)
where
    F: FnMut(&T) -> K,
    K: Ord,
```

Sorts the slice with a key extraction function.

 During sorting, the key function is called at most once per element, by using temporary storage to remember the results of key evaluation. The order of calls to the key function is unspecified and may change in future versions of the standard library.

 This sort is stable (i.e., does not reorder equal elements) and *O*(*m* \* *n* + *n* \* log(*n*)) worst-case, where the key function is *O*(*m*).

 For simple key functions (e.g., functions that are property accesses or basic operations), [`sort_by_key`](primitive.slice#method.sort_by_key "method slice::sort_by_key") is likely to be faster.

 ##### Current implementation

 The current algorithm is based on [pattern-defeating quicksort](https://github.com/orlp/pdqsort) by Orson Peters, which combines the fast average case of randomized quicksort with the fast worst case of heapsort, while achieving linear time on slices with certain patterns. It uses some randomization to avoid degenerate cases, but with a fixed seed to always provide deterministic behavior.

 In the worst case, the algorithm allocates temporary storage in a `Vec<(K, usize)>` the length of the slice.

 ##### Examples

 
```
let mut v = [-5i32, 4, 32, -3, 2];

v.sort_by_cached_key(|k| k.to_string());
assert!(v == [-3, -5, 2, 32, 4]);
```
 
[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#412-414)
```
pub fn to_vec(&self) -> Vec<T, Global>
where
    T: Clone,
```

Copies `self` into a new `Vec`.

 ##### Examples

 
```
let s = [10, 40, 30];
let x = s.to_vec();
// Here, `s` and `x` can be modified independently.
```
 
[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#436-438)
```
pub fn to_vec_in<A>(&self, alloc: A) -> Vec<T, A>
where
    A: Allocator,
    T: Clone,
```

🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838))

Copies `self` into a new `Vec` with an allocator.

 ##### Examples

 
```
#![feature(allocator_api)]

use std::alloc::System;

let s = [10, 40, 30];
let x = s.to_vec_in(System);
// Here, `s` and `x` can be modified independently.
```
 
[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#461)
```
pub fn into_vec<A>(self: Box<[T], A>) -> Vec<T, A>
where
    A: Allocator,
```

Converts `self` into a vector without clones or allocation.

 The resulting vector can be converted back into a box via `Vec<T>`’s `into_boxed_slice` method.

 ##### Examples

 
```
let s: Box<[i32]> = Box::new([10, 40, 30]);
let x = s.into_vec();
// `s` cannot be used anymore because it has been converted into `x`.

assert_eq!(x, vec![10, 40, 30]);
```
 
[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#489-491)1.40.0
```
pub fn repeat(&self, n: usize) -> Vec<T, Global>
where
    T: Copy,
```

Creates a vector by copying a slice `n` times.

 ##### Panics

 This function will panic if the capacity would overflow.

 ##### Examples

 Basic usage:

 
```
assert_eq!([1, 2].repeat(3), vec![1, 2, 1, 2, 1, 2]);
```
 A panic upon overflow:

 ⓘ
```
// this will panic at runtime
b"0123456789abcdef".repeat(usize::MAX);
```

 
[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#557-559)
```
pub fn concat<Item>(&self) -> <[T] as Concat<Item>>::Output ⓘ
where
    [T]: Concat<Item>,
    Item: ?Sized,
```

Flattens a slice of `T` into a single value `Self::Output`.

 ##### Examples

 
```
assert_eq!(["hello", "world"].concat(), "helloworld");
assert_eq!([[1, 2], [3, 4]].concat(), [1, 2, 3, 4]);
```
 
[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#576-578)1.3.0
```
pub fn join<Separator>(
    &self,
    sep: Separator
) -> <[T] as Join<Separator>>::Output ⓘ
where
    [T]: Join<Separator>,
```

Flattens a slice of `T` into a single value `Self::Output`, placing a given separator between each.

 ##### Examples

 
```
assert_eq!(["hello", "world"].join(" "), "hello world");
assert_eq!([[1, 2], [3, 4]].join(&0), [1, 2, 0, 3, 4]);
assert_eq!([[1, 2], [3, 4]].join(&[0, 0][..]), [1, 2, 0, 0, 3, 4]);
```
 
[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#596-598)
```
pub fn connect<Separator>(
    &self,
    sep: Separator
) -> <[T] as Join<Separator>>::Output ⓘ
where
    [T]: Join<Separator>,
```

👎Deprecated since 1.3.0: renamed to join

Flattens a slice of `T` into a single value `Self::Output`, placing a given separator between each.

 ##### Examples

 
```
assert_eq!(["hello", "world"].connect(" "), "hello world");
assert_eq!([[1, 2], [3, 4]].connect(&0), [1, 2, 0, 3, 4]);
```
 

[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#605)
```
impl [u8]
```

[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#621)1.23.0
```
pub fn to_ascii_uppercase(&self) -> Vec<u8, Global> ⓘ
```

Returns a vector containing a copy of this slice where each byte is mapped to its ASCII upper case equivalent.

 ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, but non-ASCII letters are unchanged.

 To uppercase the value in-place, use [`make_ascii_uppercase`](primitive.slice#method.make_ascii_uppercase "method slice::make_ascii_uppercase").

 
[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#642)1.23.0
```
pub fn to_ascii_lowercase(&self) -> Vec<u8, Global> ⓘ
```

Returns a vector containing a copy of this slice where each byte is mapped to its ASCII lower case equivalent.

 ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’, but non-ASCII letters are unchanged.

 To lowercase the value in-place, use [`make_ascii_lowercase`](primitive.slice#method.make_ascii_lowercase "method slice::make_ascii_lowercase").

 


Trait Implementations
---------------------



[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#788)
```
impl<T> AsMut<[T]> for [T]
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#790)
```
fn as_mut(&mut self) -> &mut [T]
```
Converts this type into a mutable reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#167)
```
impl<T, const N: usize> AsMut<[T]> for [T; N]
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#169)
```
fn as_mut(&mut self) -> &mut [T]
```
Converts this type into a mutable reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/vector.rs.html#847)
```
impl<T, const N: usize> AsMut<[T]> for Simd<T, N>
where
    LaneCount<N>: SupportedLaneCount,
    T: SimdElement,
```

[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/vector.rs.html#853)
```
fn as_mut(&mut self) -> &mut [T]
```
Converts this type into a mutable reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3062)1.5.0
```
impl<T, A> AsMut<[T]> for Vec<T, A>
where
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3063)
```
fn as_mut(&mut self) -> &mut [T]
```
Converts this type into a mutable reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#780)
```
impl<T> AsRef<[T]> for [T]
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#782)
```
fn as_ref(&self) -> &[T]
```
Converts this type into a shared reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#159)
```
impl<T, const N: usize> AsRef<[T]> for [T; N]
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#161)
```
fn as_ref(&self) -> &[T]
```
Converts this type into a shared reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/alloc/vec/drain.rs.html#140)1.46.0
```
impl<'a, T, A> AsRef<[T]> for Drain<'a, T, A>
where
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/vec/drain.rs.html#141)
```
fn as_ref(&self) -> &[T]
```
Converts this type into a shared reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/alloc/vec/into_iter.rs.html#172)1.46.0
```
impl<T, A> AsRef<[T]> for IntoIter<T, A>
where
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/vec/into_iter.rs.html#173)
```
fn as_ref(&self) -> &[T]
```
Converts this type into a shared reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#150)1.13.0
```
impl<T> AsRef<[T]> for Iter<'_, T>
```

[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#152)
```
fn as_ref(&self) -> &[T]
```
Converts this type into a shared reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#349)1.53.0
```
impl<T> AsRef<[T]> for IterMut<'_, T>
```

[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#351)
```
fn as_ref(&self) -> &[T]
```
Converts this type into a shared reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/vector.rs.html#836)
```
impl<T, const N: usize> AsRef<[T]> for Simd<T, N>
where
    LaneCount<N>: SupportedLaneCount,
    T: SimdElement,
```

[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/vector.rs.html#842)
```
fn as_ref(&self) -> &[T]
```
Converts this type into a shared reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3055)
```
impl<T, A> AsRef<[T]> for Vec<T, A>
where
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3056)
```
fn as_ref(&self) -> &[T]
```
Converts this type into a shared reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2961)1.55.0
```
impl<'a> AsRef<[u8]> for Drain<'a>
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2962)
```
fn as_ref(&self) -> &[u8] ⓘ
```
Converts this type into a shared reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2652)
```
impl AsRef<[u8]> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2654)
```
fn as_ref(&self) -> &[u8] ⓘ
```
Converts this type into a shared reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2581)
```
impl AsRef<[u8]> for str
```

[source](https://doc.rust-lang.org/src/core/str/mod.rs.html#2583)
```
fn as_ref(&self) -> &[u8] ⓘ
```
Converts this type into a shared reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/std/ascii.rs.html#199-203)
```
impl AsciiExt for [u8]
```


```
type Owned = Vec<u8, Global>
```

👎Deprecated since 1.26.0: use inherent methods instead
Container type for copied ASCII characters.
[source](https://doc.rust-lang.org/src/std/ascii.rs.html#202)
```
fn is_ascii(&self) -> bool
```

👎Deprecated since 1.26.0: use inherent methods instead
Checks if the value is within the ASCII range. [Read more](ascii/trait.asciiext#tymethod.is_ascii)

[source](https://doc.rust-lang.org/src/std/ascii.rs.html#202)
```
fn to_ascii_uppercase(&self) -> Self::Owned
```

👎Deprecated since 1.26.0: use inherent methods instead
Makes a copy of the value in its ASCII upper case equivalent. [Read more](ascii/trait.asciiext#tymethod.to_ascii_uppercase)

[source](https://doc.rust-lang.org/src/std/ascii.rs.html#202)
```
fn to_ascii_lowercase(&self) -> Self::Owned
```

👎Deprecated since 1.26.0: use inherent methods instead
Makes a copy of the value in its ASCII lower case equivalent. [Read more](ascii/trait.asciiext#tymethod.to_ascii_lowercase)

[source](https://doc.rust-lang.org/src/std/ascii.rs.html#202)
```
fn eq_ignore_ascii_case(&self, o: &Self) -> bool
```

👎Deprecated since 1.26.0: use inherent methods instead
Checks that two values are an ASCII case-insensitive match. [Read more](ascii/trait.asciiext#tymethod.eq_ignore_ascii_case)

[source](https://doc.rust-lang.org/src/std/ascii.rs.html#202)
```
fn make_ascii_uppercase(&mut self)
```

👎Deprecated since 1.26.0: use inherent methods instead
Converts this type to its ASCII upper case equivalent in-place. [Read more](ascii/trait.asciiext#tymethod.make_ascii_uppercase)

[source](https://doc.rust-lang.org/src/std/ascii.rs.html#202)
```
fn make_ascii_lowercase(&mut self)
```

👎Deprecated since 1.26.0: use inherent methods instead
Converts this type to its ASCII lower case equivalent in-place. [Read more](ascii/trait.asciiext#tymethod.make_ascii_lowercase)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#175)1.4.0
```
impl<T, const N: usize> Borrow<[T]> for [T; N]
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#176)
```
fn borrow(&self) -> &[T]
```
Immutably borrows from an owned value. [Read more](borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#772)
```
impl<T, A> Borrow<[T]> for Vec<T, A>
where
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#773)
```
fn borrow(&self) -> &[T]
```
Immutably borrows from an owned value. [Read more](borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#182)1.4.0
```
impl<T, const N: usize> BorrowMut<[T]> for [T; N]
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#183)
```
fn borrow_mut(&mut self) -> &mut [T]
```
Mutably borrows from an owned value. [Read more](borrow/trait.borrowmut#tymethod.borrow_mut)


[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#779)
```
impl<T, A> BorrowMut<[T]> for Vec<T, A>
where
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#780)
```
fn borrow_mut(&mut self) -> &mut [T]
```
Mutably borrows from an owned value. [Read more](borrow/trait.borrowmut#tymethod.borrow_mut)


[source](https://doc.rust-lang.org/src/std/io/impls.rs.html#325-335)
```
impl BufRead for &[u8]
```

[source](https://doc.rust-lang.org/src/std/io/impls.rs.html#327-329)
```
fn fill_buf(&mut self) -> Result<&[u8]>
```
Returns the contents of the internal buffer, filling it with more data from the inner reader if it is empty. [Read more](io/trait.bufread#tymethod.fill_buf)

[source](https://doc.rust-lang.org/src/std/io/impls.rs.html#332-334)
```
fn consume(&mut self, amt: usize)
```
Tells this buffer that `amt` bytes have been consumed from the buffer, so they should no longer be returned in calls to `read`. [Read more](io/trait.bufread#tymethod.consume)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#2107-2109)
```
fn has_data_left(&mut self) -> Result<bool>
```

🔬This is a nightly-only experimental API. (`buf_read_has_data_left` [#86423](https://github.com/rust-lang/rust/issues/86423))
Check if the underlying `Read` has any data left to be read. [Read more](io/trait.bufread#method.has_data_left)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#2166-2168)
```
fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize>
```
Read all bytes into `buf` until the delimiter `byte` or EOF is reached. [Read more](io/trait.bufread#method.read_until)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#2234-2239)
```
fn read_line(&mut self, buf: &mut String) -> Result<usize>
```
Read all bytes until a newline (the `0xA` byte) is reached, and append them to the provided `String` buffer. [Read more](io/trait.bufread#method.read_line)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#2272-2277)
```
fn split(self, byte: u8) -> Split<Self> ⓘ
where
    Self: Sized,
```
Returns an iterator over the contents of this reader split on the byte `byte`. [Read more](io/trait.bufread#method.split)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#2309-2314)
```
fn lines(self) -> Lines<Self> ⓘ
where
    Self: Sized,
```
Returns an iterator over the lines of this reader. [Read more](io/trait.bufread#method.lines)


[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2019)1.3.0
```
impl<T, A> Clone for Box<[T], A>
where
    T: Clone,
    A: Allocator + Clone,
```

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2020)
```
fn clone(&self) -> Box<[T], A>
```
Returns a copy of the value. [Read more](clone/trait.clone#tymethod.clone)

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2025)
```
fn clone_from(&mut self, other: &Box<[T], A>)
```
Performs copy-assignment from `source`. [Read more](clone/trait.clone#method.clone_from)


[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#707)
```
impl<T, V> Concat<T> for [V]
where
    T: Clone,
    V: Borrow<[T]>,
```


```
type Output = Vec<T, Global>
```

🔬This is a nightly-only experimental API. (`slice_concat_trait` [#27747](https://github.com/rust-lang/rust/issues/27747))
The resulting type after concatenation
[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#710)
```
fn concat(slice: &[V]) -> Vec<T, Global>
```

🔬This is a nightly-only experimental API. (`slice_concat_trait` [#27747](https://github.com/rust-lang/rust/issues/27747))
Implementation of [`[T]::concat`](primitive.slice#method.concat "method slice::concat")


[source](https://doc.rust-lang.org/src/alloc/str.rs.html#61)
```
impl<S> Concat<str> for [S]
where
    S: Borrow<str>,
```

Note: `str` in `Concat<str>` is not meaningful here. This type parameter of the trait only exists to enable another impl.

 


```
type Output = String
```

🔬This is a nightly-only experimental API. (`slice_concat_trait` [#27747](https://github.com/rust-lang/rust/issues/27747))
The resulting type after concatenation
[source](https://doc.rust-lang.org/src/alloc/str.rs.html#64)
```
fn concat(slice: &[S]) -> String
```

🔬This is a nightly-only experimental API. (`slice_concat_trait` [#27747](https://github.com/rust-lang/rust/issues/27747))
Implementation of [`[T]::concat`](primitive.slice#method.concat "method slice::concat")


[source](https://doc.rust-lang.org/src/core/fmt/mod.rs.html#2494)
```
impl<T> Debug for [T]
where
    T: Debug,
```

[source](https://doc.rust-lang.org/src/core/fmt/mod.rs.html#2495)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter. [Read more](fmt/trait.debug#tymethod.fmt)


[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4637)
```
impl<T> Default for &[T]
```

[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4639)
```
fn default() -> &[T]
```

Creates an empty slice.

 

[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4645)1.5.0
```
impl<T> Default for &mut [T]
```

[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4647)
```
fn default() -> &mut [T]
```

Creates a mutable empty slice.

 

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1231)
```
impl<T> Default for Box<[T], Global>
```

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1233)
```
fn default() -> Box<[T], Global>
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2672)1.21.0
```
impl<T> From<&[T]> for Arc<[T]>
where
    T: Clone,
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2684)
```
fn from(v: &[T]) -> Arc<[T]>
```

Allocate a reference-counted slice and fill it by cloning `v`’s items.

 ##### Example

 
```
let original: &[i32] = &[1, 2, 3];
let shared: Arc<[i32]> = Arc::from(original);
assert_eq!(&[1, 2, 3], &shared[..]);
```
 

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1487)1.17.0
```
impl<T> From<&[T]> for Box<[T], Global>
where
    T: Clone,
```

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1502)
```
fn from(slice: &[T]) -> Box<[T], Global>
```

Converts a `&[T]` into a `Box<[T]>`

 This conversion allocates on the heap and performs a copy of `slice` and its contents.

 ##### Examples

 
```
// create a &[u8] which will be used to create a Box<[u8]>
let slice: &[u8] = &[104, 101, 108, 108, 111];
let boxed_slice: Box<[u8]> = Box::from(slice);

println!("{boxed_slice:?}");
```
 

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1930)1.21.0
```
impl<T> From<&[T]> for Rc<[T]>
where
    T: Clone,
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1942)
```
fn from(v: &[T]) -> Rc<[T]>
```

Allocate a reference-counted slice and fill it by cloning `v`’s items.

 ##### Example

 
```
let original: &[i32] = &[1, 2, 3];
let shared: Rc<[i32]> = Rc::from(original);
assert_eq!(&[1, 2, 3], &shared[..]);
```
 

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3070)
```
impl<T> From<&[T]> for Vec<T, Global>
where
    T: Clone,
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3079)
```
fn from(s: &[T]) -> Vec<T, Global>
```

Allocate a `Vec<T>` and fill it by cloning `s`’s items.

 ##### Examples

 
```
assert_eq!(Vec::from(&[1, 2, 3][..]), vec![1, 2, 3]);
```
 

[source](https://doc.rust-lang.org/src/alloc/vec/cow.rs.html#6)1.8.0
```
impl<'a, T> From<&'a [T]> for Cow<'a, [T]>
where
    T: Clone,
```

[source](https://doc.rust-lang.org/src/alloc/vec/cow.rs.html#13)
```
fn from(s: &'a [T]) -> Cow<'a, [T]>
```

Creates a [`Borrowed`](borrow/enum.cow#variant.Borrowed "variant std::borrow::Cow::Borrowed") variant of [`Cow`](borrow/enum.cow "enum std::borrow::Cow") from a slice.

 This conversion does not allocate or clone the data.

 

[source](https://doc.rust-lang.org/src/std/io/readbuf.rs.html#69-74)
```
impl<'data> From<&'data mut [MaybeUninit<u8>]> for BorrowedBuf<'data>
```

Create a new `BorrowedBuf` from an uninitialized buffer.

 Use `set_init` if part of the buffer is known to be already initialized.

 

[source](https://doc.rust-lang.org/src/std/io/readbuf.rs.html#71-73)
```
fn from(buf: &'data mut [MaybeUninit<u8>]) -> BorrowedBuf<'data>
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/std/io/readbuf.rs.html#52-64)
```
impl<'data> From<&'data mut [u8]> for BorrowedBuf<'data>
```

Create a new `BorrowedBuf` from a fully initialized slice.

 

[source](https://doc.rust-lang.org/src/std/io/readbuf.rs.html#54-63)
```
fn from(slice: &'data mut [u8]) -> BorrowedBuf<'data>
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3090)1.19.0
```
impl<T> From<&mut [T]> for Vec<T, Global>
where
    T: Clone,
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3099)
```
fn from(s: &mut [T]) -> Vec<T, Global>
```

Allocate a `Vec<T>` and fill it by cloning `s`’s items.

 ##### Examples

 
```
assert_eq!(Vec::from(&mut [1, 2, 3][..]), vec![1, 2, 3]);
```
 

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1607)1.45.0
```
impl<T, const N: usize> From<[T; N]> for Box<[T], Global>
```

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1618)
```
fn from(array: [T; N]) -> Box<[T], Global>
```

Converts a `[T; N]` into a `Box<[T]>`

 This conversion moves the array to newly heap-allocated memory.

 ##### Examples

 
```
let boxed: Box<[u8]> = Box::from([4, 2]);
println!("{boxed:?}");
```
 

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1581)1.19.0
```
impl<A> From<Box<str, A>> for Box<[u8], A>
where
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1599)
```
fn from(s: Box<str, A>) -> Box<[u8], A>
```

Converts a `Box<str>` into a `Box<[u8]>`

 This conversion does not allocate on the heap and happens in place.

 ##### Examples

 
```
// create a Box<str> which will be used to create a Box<[u8]>
let boxed: Box<str> = Box::from("hello");
let boxed_str: Box<[u8]> = Box::from(boxed);

// create a &[u8] which will be used to create a Box<[u8]>
let slice: &[u8] = &[104, 101, 108, 108, 111];
let boxed_slice = Box::from(slice);

assert_eq!(boxed_slice, boxed_str);
```
 

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1509)1.45.0
```
impl<T> From<Cow<'_, [T]>> for Box<[T], Global>
where
    T: Clone,
```

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1517)
```
fn from(cow: Cow<'_, [T]>) -> Box<[T], Global>
```

Converts a `Cow<'_, [T]>` into a `Box<[T]>`

 When `cow` is the `Cow::Borrowed` variant, this conversion allocates on the heap and copies the underlying slice. Otherwise, it will try to reuse the owned `Vec`’s allocation.

 

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3175)1.20.0
```
impl<T, A> From<Vec<T, A>> for Box<[T], A>
where
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3194)
```
fn from(v: Vec<T, A>) -> Box<[T], A>
```

Convert a vector into a boxed slice.

 If `v` has excess capacity, its items will be moved into a newly-allocated buffer with exactly the right capacity.

 ##### Examples

 
```
assert_eq!(Box::from(vec![1, 2, 3]), vec![1, 2, 3].into_boxed_slice());
```
 Any excess capacity is removed:

 
```
let mut vec = Vec::with_capacity(10);
vec.extend([1, 2, 3]);

assert_eq!(Box::from(vec), vec![1, 2, 3].into_boxed_slice());
```
 

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2011)1.32.0
```
impl<I> FromIterator<I> for Box<[I], Global>
```

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#2012)
```
fn from_iter<T>(iter: T) -> Box<[I], Global>
where
    T: IntoIterator<Item = I>,
```
Creates a value from an iterator. [Read more](iter/trait.fromiterator#tymethod.from_iter)


[source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#933)
```
impl<T> Hash for [T]
where
    T: Hash,
```

[source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#935)
```
fn hash<H>(&self, state: &mut H)
where
    H: Hasher,
```
Feeds this value into the given [`Hasher`](hash/trait.hasher "trait std::hash::Hasher"). [Read more](hash/trait.hash#tymethod.hash)


[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#10)
```
impl<T, I> Index<I> for [T]
where
    I: SliceIndex<[T]>,
```


```
type Output = <I as SliceIndex<[T]>>::Output
```
The returned type after indexing.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#17)
```
fn index(&self, index: I) -> &<I as SliceIndex<[T]>>::Output
```
Performs the indexing (`container[index]`) operation. [Read more](ops/trait.index#tymethod.index)


[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#23)
```
impl<T, I> IndexMut<I> for [T]
where
    I: SliceIndex<[T]>,
```

[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#28)
```
fn index_mut(&mut self, index: I) -> &mut <I as SliceIndex<[T]>>::Output
```
Performs the mutable indexing (`container[index]`) operation. [Read more](ops/trait.indexmut#tymethod.index_mut)


[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#21)
```
impl<'a, T> IntoIterator for &'a [T]
```


```
type Item = &'a T
```
The type of the elements being iterated over.

```
type IntoIter = Iter<'a, T>
```
Which kind of iterator are we turning this into?
[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#25)
```
fn into_iter(self) -> Iter<'a, T> ⓘ
```
Creates an iterator from a value. [Read more](iter/trait.intoiterator#tymethod.into_iter)


[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#31)
```
impl<'a, T> IntoIterator for &'a mut [T]
```


```
type Item = &'a mut T
```
The type of the elements being iterated over.

```
type IntoIter = IterMut<'a, T>
```
Which kind of iterator are we turning this into?
[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#35)
```
fn into_iter(self) -> IterMut<'a, T> ⓘ
```
Creates an iterator from a value. [Read more](iter/trait.intoiterator#tymethod.into_iter)


[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#745)
```
impl<T, V> Join<&[T]> for [V]
where
    T: Clone,
    V: Borrow<[T]>,
```


```
type Output = Vec<T, Global>
```

🔬This is a nightly-only experimental API. (`slice_concat_trait` [#27747](https://github.com/rust-lang/rust/issues/27747))
The resulting type after concatenation
[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#748)
```
fn join(slice: &[V], sep: &[T]) -> Vec<T, Global>
```

🔬This is a nightly-only experimental API. (`slice_concat_trait` [#27747](https://github.com/rust-lang/rust/issues/27747))
Implementation of [`[T]::join`](primitive.slice#method.join "method slice::join")


[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1264-1278)
```
impl<S: Borrow<OsStr>> Join<&OsStr> for [S]
```


```
type Output = OsString
```

🔬This is a nightly-only experimental API. (`slice_concat_trait` [#27747](https://github.com/rust-lang/rust/issues/27747))
The resulting type after concatenation
[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1267-1277)
```
fn join(slice: &Self, sep: &OsStr) -> OsString
```

🔬This is a nightly-only experimental API. (`slice_concat_trait` [#27747](https://github.com/rust-lang/rust/issues/27747))
Implementation of [`[T]::join`](primitive.slice#method.join "method slice::join")


[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#722)
```
impl<T, V> Join<&T> for [V]
where
    T: Clone,
    V: Borrow<[T]>,
```


```
type Output = Vec<T, Global>
```

🔬This is a nightly-only experimental API. (`slice_concat_trait` [#27747](https://github.com/rust-lang/rust/issues/27747))
The resulting type after concatenation
[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#725)
```
fn join(slice: &[V], sep: &T) -> Vec<T, Global>
```

🔬This is a nightly-only experimental API. (`slice_concat_trait` [#27747](https://github.com/rust-lang/rust/issues/27747))
Implementation of [`[T]::join`](primitive.slice#method.join "method slice::join")


[source](https://doc.rust-lang.org/src/alloc/str.rs.html#71)
```
impl<S> Join<&str> for [S]
where
    S: Borrow<str>,
```


```
type Output = String
```

🔬This is a nightly-only experimental API. (`slice_concat_trait` [#27747](https://github.com/rust-lang/rust/issues/27747))
The resulting type after concatenation
[source](https://doc.rust-lang.org/src/alloc/str.rs.html#74)
```
fn join(slice: &[S], sep: &str) -> String
```

🔬This is a nightly-only experimental API. (`slice_concat_trait` [#27747](https://github.com/rust-lang/rust/issues/27747))
Implementation of [`[T]::join`](primitive.slice#method.join "method slice::join")


[source](https://doc.rust-lang.org/src/core/slice/cmp.rs.html#39)
```
impl<T> Ord for [T]
where
    T: Ord,
```

Implements comparison of vectors [lexicographically](cmp/trait.ord#lexicographical-comparison "trait std::cmp::Ord").

 

[source](https://doc.rust-lang.org/src/core/slice/cmp.rs.html#40)
```
fn cmp(&self, other: &[T]) -> Ordering
```
This method returns an [`Ordering`](cmp/enum.ordering "enum std::cmp::Ordering") between `self` and `other`. [Read more](cmp/trait.ord#tymethod.cmp)


[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#66)
```
impl<A, B, const N: usize> PartialEq<&[B]> for [A; N]
where
    A: PartialEq<B>,
```

[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#71)
```
fn eq(&self, other: &&[B]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#75)
```
fn ne(&self, other: &&[B]) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#33)
```
impl<T, U> PartialEq<&[U]> for Cow<'_, [T]>
where
    T: PartialEq<U> + Clone,
```

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#33)
```
fn eq(&self, other: &&[U]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#33)
```
fn ne(&self, other: &&[U]) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#24)
```
impl<T, U, A> PartialEq<&[U]> for Vec<T, A>
where
    A: Allocator,
    T: PartialEq<U>,
```

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#24)
```
fn eq(&self, other: &&[U]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#24)
```
fn ne(&self, other: &&[U]) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2702)1.17.0
```
impl<T, U, A> PartialEq<&[U]> for VecDeque<T, A>
where
    A: Allocator,
    T: PartialEq<U>,
```

[source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2702)
```
fn eq(&self, other: &&[U]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#226)
```
fn ne(&self, other: &Rhs) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#96)
```
impl<A, B, const N: usize> PartialEq<&mut [B]> for [A; N]
where
    A: PartialEq<B>,
```

[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#101)
```
fn eq(&self, other: &&mut [B]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#105)
```
fn ne(&self, other: &&mut [B]) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#35)
```
impl<T, U> PartialEq<&mut [U]> for Cow<'_, [T]>
where
    T: PartialEq<U> + Clone,
```

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#35)
```
fn eq(&self, other: &&mut [U]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#35)
```
fn ne(&self, other: &&mut [U]) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#25)
```
impl<T, U, A> PartialEq<&mut [U]> for Vec<T, A>
where
    A: Allocator,
    T: PartialEq<U>,
```

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#25)
```
fn eq(&self, other: &&mut [U]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#25)
```
fn ne(&self, other: &&mut [U]) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2703)1.17.0
```
impl<T, U, A> PartialEq<&mut [U]> for VecDeque<T, A>
where
    A: Allocator,
    T: PartialEq<U>,
```

[source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2703)
```
fn eq(&self, other: &&mut [U]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#226)
```
fn ne(&self, other: &Rhs) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#81)
```
impl<A, B, const N: usize> PartialEq<[A; N]> for &[B]
where
    B: PartialEq<A>,
```

[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#86)
```
fn eq(&self, other: &[A; N]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#90)
```
fn ne(&self, other: &[A; N]) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#111)
```
impl<A, B, const N: usize> PartialEq<[A; N]> for &mut [B]
where
    B: PartialEq<A>,
```

[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#116)
```
fn eq(&self, other: &[A; N]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#120)
```
fn ne(&self, other: &[A; N]) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#43)
```
impl<A, B, const N: usize> PartialEq<[A; N]> for [B]
where
    B: PartialEq<A>,
```

[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#48)
```
fn eq(&self, other: &[A; N]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#56)
```
fn ne(&self, other: &[A; N]) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/slice/cmp.rs.html#21)
```
impl<A, B> PartialEq<[B]> for [A]
where
    A: PartialEq<B>,
```

[source](https://doc.rust-lang.org/src/core/slice/cmp.rs.html#25)
```
fn eq(&self, other: &[B]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/slice/cmp.rs.html#29)
```
fn ne(&self, other: &[B]) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#20)
```
impl<A, B, const N: usize> PartialEq<[B]> for [A; N]
where
    A: PartialEq<B>,
```

[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#25)
```
fn eq(&self, other: &[B]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#33)
```
fn ne(&self, other: &[B]) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#28)1.48.0
```
impl<T, U, A> PartialEq<[U]> for Vec<T, A>
where
    A: Allocator,
    T: PartialEq<U>,
```

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#28)
```
fn eq(&self, other: &[U]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#28)
```
fn ne(&self, other: &[U]) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#26)1.46.0
```
impl<T, U, A> PartialEq<Vec<U, A>> for &[T]
where
    A: Allocator,
    T: PartialEq<U>,
```

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#26)
```
fn eq(&self, other: &Vec<U, A>) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#26)
```
fn ne(&self, other: &Vec<U, A>) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#27)1.46.0
```
impl<T, U, A> PartialEq<Vec<U, A>> for &mut [T]
where
    A: Allocator,
    T: PartialEq<U>,
```

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#27)
```
fn eq(&self, other: &Vec<U, A>) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#27)
```
fn ne(&self, other: &Vec<U, A>) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#29)1.48.0
```
impl<T, U, A> PartialEq<Vec<U, A>> for [T]
where
    A: Allocator,
    T: PartialEq<U>,
```

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#29)
```
fn eq(&self, other: &Vec<U, A>) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#29)
```
fn ne(&self, other: &Vec<U, A>) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/slice/cmp.rs.html#47)
```
impl<T> PartialOrd<[T]> for [T]
where
    T: PartialOrd<T>,
```

Implements comparison of vectors [lexicographically](cmp/trait.ord#lexicographical-comparison "trait std::cmp::Ord").

 

[source](https://doc.rust-lang.org/src/core/slice/cmp.rs.html#48)
```
fn partial_cmp(&self, other: &[T]) -> Option<Ordering>
```
This method returns an ordering between `self` and `other` values if one exists. [Read more](cmp/trait.partialord#tymethod.partial_cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1067)
```
fn lt(&self, other: &Rhs) -> bool
```
This method tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](cmp/trait.partialord#method.lt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1084)
```
fn le(&self, other: &Rhs) -> bool
```
This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](cmp/trait.partialord#method.le)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1100)
```
fn gt(&self, other: &Rhs) -> bool
```
This method tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](cmp/trait.partialord#method.gt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1117)
```
fn ge(&self, other: &Rhs) -> bool
```
This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](cmp/trait.partialord#method.ge)


[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#857)
```
impl<'a, 'b> Pattern<'a> for &'b [char]
```

Searches for chars that are equal to any of the [`char`](primitive.char "primitive char")s in the slice.

 #### Examples

 
```
assert_eq!("Hello world".find(&['l', 'l'] as &[_]), Some(2));
assert_eq!("Hello world".find(&['l', 'l'][..]), Some(2));
```
 


```
type Searcher = CharSliceSearcher<'a, 'b>
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Associated searcher for this pattern
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#858)
```
fn into_searcher(self, haystack: &'a str) -> CharSliceSearcher<'a, 'b>
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Constructs the associated searcher from `self` and the `haystack` to search in.
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#858)
```
fn is_contained_in(self, haystack: &'a str) -> bool
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Checks whether the pattern matches anywhere in the haystack
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#858)
```
fn is_prefix_of(self, haystack: &'a str) -> bool
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Checks whether the pattern matches at the front of the haystack
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#858)
```
fn strip_prefix_of(self, haystack: &'a str) -> Option<&'a str>
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Removes the pattern from the front of haystack, if it matches.
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#858)
```
fn is_suffix_of(self, haystack: &'a str) -> bool
where
    CharSliceSearcher<'a, 'b>: ReverseSearcher<'a>,
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Checks whether the pattern matches at the back of the haystack
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#858)
```
fn strip_suffix_of(self, haystack: &'a str) -> Option<&'a str>
where
    CharSliceSearcher<'a, 'b>: ReverseSearcher<'a>,
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Removes the pattern from the back of haystack, if it matches.

[source](https://doc.rust-lang.org/src/std/io/impls.rs.html#233-322)
```
impl Read for &[u8]
```

Read is implemented for `&[u8]` by copying from the slice.

 Note that reading updates the slice to point to the yet unread part. The slice will be empty when EOF is reached.

 

[source](https://doc.rust-lang.org/src/std/io/impls.rs.html#235-250)
```
fn read(&mut self, buf: &mut [u8]) -> Result<usize>
```
Pull some bytes from this source into the specified buffer, returning how many bytes were read. [Read more](io/trait.read#tymethod.read)

[source](https://doc.rust-lang.org/src/std/io/impls.rs.html#253-261)
```
fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> Result<()>
```

🔬This is a nightly-only experimental API. (`read_buf` [#78485](https://github.com/rust-lang/rust/issues/78485))
Pull some bytes from this source into the specified buffer. [Read more](io/trait.read#method.read_buf)

[source](https://doc.rust-lang.org/src/std/io/impls.rs.html#264-274)
```
fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
```
Like `read`, except that it reads into a slice of buffers. [Read more](io/trait.read#method.read_vectored)

[source](https://doc.rust-lang.org/src/std/io/impls.rs.html#277-279)
```
fn is_read_vectored(&self) -> bool
```

🔬This is a nightly-only experimental API. (`can_vector` [#69941](https://github.com/rust-lang/rust/issues/69941))
Determines if this `Read`er has an efficient `read_vectored` implementation. [Read more](io/trait.read#method.is_read_vectored)

[source](https://doc.rust-lang.org/src/std/io/impls.rs.html#282-302)
```
fn read_exact(&mut self, buf: &mut [u8]) -> Result<()>
```
Read the exact number of bytes required to fill `buf`. [Read more](io/trait.read#method.read_exact)

[source](https://doc.rust-lang.org/src/std/io/impls.rs.html#305-310)
```
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize>
```
Read all bytes until EOF in this source, placing them into `buf`. [Read more](io/trait.read#method.read_to_end)

[source](https://doc.rust-lang.org/src/std/io/impls.rs.html#313-321)
```
fn read_to_string(&mut self, buf: &mut String) -> Result<usize>
```
Read all bytes until EOF in this source, appending them to `buf`. [Read more](io/trait.read#method.read_to_string)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#858-873)
```
fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<()>
```

🔬This is a nightly-only experimental API. (`read_buf` [#78485](https://github.com/rust-lang/rust/issues/78485))
Read the exact number of bytes required to fill `cursor`. [Read more](io/trait.read#method.read_buf_exact)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#910-915)
```
fn by_ref(&mut self) -> &mut Self
where
    Self: Sized,
```
Creates a “by reference” adaptor for this instance of `Read`. [Read more](io/trait.read#method.by_ref)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#953-958)
```
fn bytes(self) -> Bytes<Self> ⓘ
where
    Self: Sized,
```
Transforms this `Read` instance to an [`Iterator`](iter/trait.iterator "trait std::iter::Iterator") over its bytes. [Read more](io/trait.read#method.bytes)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#991-996)
```
fn chain<R: Read>(self, next: R) -> Chain<Self, R> ⓘ
where
    Self: Sized,
```
Creates an adapter which will chain this stream with another. [Read more](io/trait.read#method.chain)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1030-1035)
```
fn take(self, limit: u64) -> Take<Self> ⓘ
where
    Self: Sized,
```
Creates an adapter which will read at most `limit` bytes from it. [Read more](io/trait.read#method.take)


[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#800)1.53.0
```
impl<T> SliceIndex<[T]> for (Bound<usize>, Bound<usize>)
```


```
type Output = [T]
```
The output type returned by methods.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#804)
```
fn get(
    self,
    slice: &[T]
) -> Option<&<(Bound<usize>, Bound<usize>) as SliceIndex<[T]>>::Output>
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, if in bounds.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#809)
```
fn get_mut(
    self,
    slice: &mut [T]
) -> Option<&mut <(Bound<usize>, Bound<usize>) as SliceIndex<[T]>>::Output>
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, if in bounds.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#814)
```
unsafe fn get_unchecked(
    self,
    slice: *const [T]
) -> *const <(Bound<usize>, Bound<usize>) as SliceIndex<[T]>>::Output
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, without performing any bounds checking. Calling this method with an out-of-bounds index or a dangling `slice` pointer is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#820)
```
unsafe fn get_unchecked_mut(
    self,
    slice: *mut [T]
) -> *mut <(Bound<usize>, Bound<usize>) as SliceIndex<[T]>>::Output
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, without performing any bounds checking. Calling this method with an out-of-bounds index or a dangling `slice` pointer is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#826)
```
fn index(
    self,
    slice: &[T]
) -> &<(Bound<usize>, Bound<usize>) as SliceIndex<[T]>>::Output
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, panicking if out of bounds.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#831)
```
fn index_mut(
    self,
    slice: &mut [T]
) -> &mut <(Bound<usize>, Bound<usize>) as SliceIndex<[T]>>::Output
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, panicking if out of bounds.

[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#347)1.15.0 (const: unstable)
```
impl<T> SliceIndex<[T]> for Range<usize>
```


```
type Output = [T]
```
The output type returned by methods.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#351)const: unstable
```
fn get(self, slice: &[T]) -> Option<&[T]>
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, if in bounds.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#361)const: unstable
```
fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]>
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, if in bounds.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#371)const: unstable
```
unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T]
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, without performing any bounds checking. Calling this method with an out-of-bounds index or a dangling `slice` pointer is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#389)const: unstable
```
unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T]
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, without performing any bounds checking. Calling this method with an out-of-bounds index or a dangling `slice` pointer is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#404)const: unstable
```
fn index(self, slice: &[T]) -> &[T]
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, panicking if out of bounds.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#415)const: unstable
```
fn index_mut(self, slice: &mut [T]) -> &mut [T]
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, panicking if out of bounds.

[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#466)1.15.0 (const: unstable)
```
impl<T> SliceIndex<[T]> for RangeFrom<usize>
```


```
type Output = [T]
```
The output type returned by methods.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#470)const: unstable
```
fn get(self, slice: &[T]) -> Option<&[T]>
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, if in bounds.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#475)const: unstable
```
fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]>
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, if in bounds.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#480)const: unstable
```
unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T]
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, without performing any bounds checking. Calling this method with an out-of-bounds index or a dangling `slice` pointer is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#486)const: unstable
```
unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T]
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, without performing any bounds checking. Calling this method with an out-of-bounds index or a dangling `slice` pointer is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#492)const: unstable
```
fn index(self, slice: &[T]) -> &[T]
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, panicking if out of bounds.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#501)const: unstable
```
fn index_mut(self, slice: &mut [T]) -> &mut [T]
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, panicking if out of bounds.

[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#512)1.15.0 (const: unstable)
```
impl<T> SliceIndex<[T]> for RangeFull
```


```
type Output = [T]
```
The output type returned by methods.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#516)const: unstable
```
fn get(self, slice: &[T]) -> Option<&[T]>
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, if in bounds.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#521)const: unstable
```
fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]>
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, if in bounds.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#526)const: unstable
```
unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T]
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, without performing any bounds checking. Calling this method with an out-of-bounds index or a dangling `slice` pointer is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#531)const: unstable
```
unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T]
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, without performing any bounds checking. Calling this method with an out-of-bounds index or a dangling `slice` pointer is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#536)const: unstable
```
fn index(self, slice: &[T]) -> &[T]
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, panicking if out of bounds.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#541)const: unstable
```
fn index_mut(self, slice: &mut [T]) -> &mut [T]
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, panicking if out of bounds.

[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#548)1.26.0 (const: unstable)
```
impl<T> SliceIndex<[T]> for RangeInclusive<usize>
```


```
type Output = [T]
```
The output type returned by methods.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#552)const: unstable
```
fn get(self, slice: &[T]) -> Option<&[T]>
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, if in bounds.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#557)const: unstable
```
fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]>
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, if in bounds.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#562)const: unstable
```
unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T]
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, without performing any bounds checking. Calling this method with an out-of-bounds index or a dangling `slice` pointer is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#568)const: unstable
```
unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T]
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, without performing any bounds checking. Calling this method with an out-of-bounds index or a dangling `slice` pointer is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#574)const: unstable
```
fn index(self, slice: &[T]) -> &[T]
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, panicking if out of bounds.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#582)const: unstable
```
fn index_mut(self, slice: &mut [T]) -> &mut [T]
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, panicking if out of bounds.

[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#428)1.15.0 (const: unstable)
```
impl<T> SliceIndex<[T]> for RangeTo<usize>
```


```
type Output = [T]
```
The output type returned by methods.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#432)const: unstable
```
fn get(self, slice: &[T]) -> Option<&[T]>
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, if in bounds.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#437)const: unstable
```
fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]>
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, if in bounds.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#442)const: unstable
```
unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T]
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, without performing any bounds checking. Calling this method with an out-of-bounds index or a dangling `slice` pointer is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#448)const: unstable
```
unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T]
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, without performing any bounds checking. Calling this method with an out-of-bounds index or a dangling `slice` pointer is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#454)const: unstable
```
fn index(self, slice: &[T]) -> &[T]
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, panicking if out of bounds.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#459)const: unstable
```
fn index_mut(self, slice: &mut [T]) -> &mut [T]
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, panicking if out of bounds.

[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#592)1.26.0 (const: unstable)
```
impl<T> SliceIndex<[T]> for RangeToInclusive<usize>
```


```
type Output = [T]
```
The output type returned by methods.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#596)const: unstable
```
fn get(self, slice: &[T]) -> Option<&[T]>
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, if in bounds.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#601)const: unstable
```
fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]>
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, if in bounds.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#606)const: unstable
```
unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T]
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, without performing any bounds checking. Calling this method with an out-of-bounds index or a dangling `slice` pointer is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#612)const: unstable
```
unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T]
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, without performing any bounds checking. Calling this method with an out-of-bounds index or a dangling `slice` pointer is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#618)const: unstable
```
fn index(self, slice: &[T]) -> &[T]
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, panicking if out of bounds.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#623)const: unstable
```
fn index_mut(self, slice: &mut [T]) -> &mut [T]
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, panicking if out of bounds.

[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#211)1.15.0 (const: unstable)
```
impl<T> SliceIndex<[T]> for usize
```


```
type Output = T
```
The output type returned by methods.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#215)const: unstable
```
fn get(self, slice: &[T]) -> Option<&T>
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, if in bounds.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#221)const: unstable
```
fn get_mut(self, slice: &mut [T]) -> Option<&mut T>
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, if in bounds.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#227)const: unstable
```
unsafe fn get_unchecked(self, slice: *const [T]) -> *const T
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, without performing any bounds checking. Calling this method with an out-of-bounds index or a dangling `slice` pointer is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#243)const: unstable
```
unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut T
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, without performing any bounds checking. Calling this method with an out-of-bounds index or a dangling `slice` pointer is *[undefined behavior](../reference/behavior-considered-undefined)* even if the resulting reference is not used.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#256)const: unstable
```
fn index(self, slice: &[T]) -> &T
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a shared reference to the output at this location, panicking if out of bounds.
[source](https://doc.rust-lang.org/src/core/slice/index.rs.html#262)const: unstable
```
fn index_mut(self, slice: &mut [T]) -> &mut T
```

🔬This is a nightly-only experimental API. (`slice_index_methods`)
Returns a mutable reference to the output at this location, panicking if out of bounds.

[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4665)1.51.0
```
impl<T> SlicePattern for [T]
```


```
type Item = T
```

🔬This is a nightly-only experimental API. (`slice_pattern` [#56345](https://github.com/rust-lang/rust/issues/56345))
The element type of the slice being matched on.
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4669)
```
fn as_slice(&self) -> &[<[T] as SlicePattern>::Item]
```

🔬This is a nightly-only experimental API. (`slice_pattern` [#56345](https://github.com/rust-lang/rust/issues/56345))
Currently, the consumers of `SlicePattern` need a slice.

[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#819)
```
impl<T> ToOwned for [T]
where
    T: Clone,
```


```
type Owned = Vec<T, Global>
```
The resulting type after obtaining ownership.
[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#822)
```
fn to_owned(&self) -> Vec<T, Global>
```
Creates owned data from borrowed data, usually by cloning. [Read more](borrow/trait.toowned#tymethod.to_owned)

[source](https://doc.rust-lang.org/src/alloc/slice.rs.html#831)
```
fn clone_into(&self, target: &mut Vec<T, Global>)
```
Uses borrowed data to replace owned data, usually by cloning. [Read more](borrow/trait.toowned#method.clone_into)


[source](https://doc.rust-lang.org/src/std/net/socket_addr.rs.html#293-299)1.8.0
```
impl<'a> ToSocketAddrs for &'a [SocketAddr]
```


```
type Iter = Cloned<Iter<'a, SocketAddr>>
```
Returned iterator over socket addresses which this type may correspond to.
[source](https://doc.rust-lang.org/src/std/net/socket_addr.rs.html#296-298)
```
fn to_socket_addrs(&self) -> Result<Self::Iter>
```
Converts this object to an iterator of resolved [`SocketAddr`](net/enum.socketaddr "enum std::net::SocketAddr")s. [Read more](net/trait.tosocketaddrs#tymethod.to_socket_addrs)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#201)1.34.0
```
impl<T, const N: usize> TryFrom<&[T]> for [T; N]
where
    T: Copy,
```

Tries to create an array `[T; N]` by copying from a slice `&[T]`. Succeeds if `slice.len() == N`.

 
```
let bytes: [u8; 3] = [1, 0, 2];

let bytes_head: [u8; 2] = <[u8; 2]>::try_from(&bytes[0..2]).unwrap();
assert_eq!(1, u16::from_le_bytes(bytes_head));

let bytes_tail: [u8; 2] = bytes[1..3].try_into().unwrap();
assert_eq!(512, u16::from_le_bytes(bytes_tail));
```
 


```
type Error = TryFromSliceError
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#208)
```
fn try_from(slice: &[T]) -> Result<[T; N], TryFromSliceError>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/vector.rs.html#879)
```
impl<T, const N: usize> TryFrom<&[T]> for Simd<T, N>
where
    LaneCount<N>: SupportedLaneCount,
    T: SimdElement,
```


```
type Error = TryFromSliceError
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/vector.rs.html#886)
```
fn try_from(slice: &[T]) -> Result<Simd<T, N>, TryFromSliceError>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#251)1.34.0
```
impl<'a, T, const N: usize> TryFrom<&'a [T]> for &'a [T; N]
```

Tries to create an array ref `&[T; N]` from a slice ref `&[T]`. Succeeds if `slice.len() == N`.

 
```
let bytes: [u8; 3] = [1, 0, 2];

let bytes_head: &[u8; 2] = <&[u8; 2]>::try_from(&bytes[0..2]).unwrap();
assert_eq!(1, u16::from_le_bytes(*bytes_head));

let bytes_tail: &[u8; 2] = bytes[1..3].try_into().unwrap();
assert_eq!(512, u16::from_le_bytes(*bytes_tail));
```
 


```
type Error = TryFromSliceError
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#255)
```
fn try_from(slice: &'a [T]) -> Result<&'a [T; N], TryFromSliceError>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#279)1.34.0
```
impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut [T; N]
```

Tries to create a mutable array ref `&mut [T; N]` from a mutable slice ref `&mut [T]`. Succeeds if `slice.len() == N`.

 
```
let mut bytes: [u8; 3] = [1, 0, 2];

let bytes_head: &mut [u8; 2] = <&mut [u8; 2]>::try_from(&mut bytes[0..2]).unwrap();
assert_eq!(1, u16::from_le_bytes(*bytes_head));

let bytes_tail: &mut [u8; 2] = (&mut bytes[1..3]).try_into().unwrap();
assert_eq!(512, u16::from_le_bytes(*bytes_tail));
```
 


```
type Error = TryFromSliceError
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#283)
```
fn try_from(slice: &'a mut [T]) -> Result<&'a mut [T; N], TryFromSliceError>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#226)1.59.0
```
impl<T, const N: usize> TryFrom<&mut [T]> for [T; N]
where
    T: Copy,
```

Tries to create an array `[T; N]` by copying from a mutable slice `&mut [T]`. Succeeds if `slice.len() == N`.

 
```
let mut bytes: [u8; 3] = [1, 0, 2];

let bytes_head: [u8; 2] = <[u8; 2]>::try_from(&mut bytes[0..2]).unwrap();
assert_eq!(1, u16::from_le_bytes(bytes_head));

let bytes_tail: [u8; 2] = (&mut bytes[1..3]).try_into().unwrap();
assert_eq!(512, u16::from_le_bytes(bytes_tail));
```
 


```
type Error = TryFromSliceError
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#233)
```
fn try_from(slice: &mut [T]) -> Result<[T; N], TryFromSliceError>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/vector.rs.html#891)
```
impl<T, const N: usize> TryFrom<&mut [T]> for Simd<T, N>
where
    LaneCount<N>: SupportedLaneCount,
    T: SimdElement,
```


```
type Error = TryFromSliceError
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/vector.rs.html#898)
```
fn try_from(slice: &mut [T]) -> Result<Simd<T, N>, TryFromSliceError>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/std/io/impls.rs.html#347-388)
```
impl Write for &mut [u8]
```

Write is implemented for `&mut [u8]` by copying into the slice, overwriting its data.

 Note that writing updates the slice to point to the yet unwritten part. The slice will be empty when it has been completely overwritten.

 If the number of bytes to be written exceeds the size of the slice, write operations will return short writes: ultimately, `Ok(0)`; in this situation, `write_all` returns an error of kind `ErrorKind::WriteZero`.

 

[source](https://doc.rust-lang.org/src/std/io/impls.rs.html#349-355)
```
fn write(&mut self, data: &[u8]) -> Result<usize>
```
Write a buffer into this writer, returning how many bytes were written. [Read more](io/trait.write#tymethod.write)

[source](https://doc.rust-lang.org/src/std/io/impls.rs.html#358-368)
```
fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize>
```
Like [`write`](io/trait.write#tymethod.write "method std::io::Write::write"), except that it writes from a slice of buffers. [Read more](io/trait.write#method.write_vectored)

[source](https://doc.rust-lang.org/src/std/io/impls.rs.html#371-373)
```
fn is_write_vectored(&self) -> bool
```

🔬This is a nightly-only experimental API. (`can_vector` [#69941](https://github.com/rust-lang/rust/issues/69941))
Determines if this `Write`r has an efficient [`write_vectored`](io/trait.write#method.write_vectored "method std::io::Write::write_vectored") implementation. [Read more](io/trait.write#method.is_write_vectored)

[source](https://doc.rust-lang.org/src/std/io/impls.rs.html#376-382)
```
fn write_all(&mut self, data: &[u8]) -> Result<()>
```
Attempts to write an entire buffer into this writer. [Read more](io/trait.write#method.write_all)

[source](https://doc.rust-lang.org/src/std/io/impls.rs.html#385-387)
```
fn flush(&mut self) -> Result<()>
```
Flush this output stream, ensuring that all intermediately buffered contents reach their destination. [Read more](io/trait.write#tymethod.flush)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1636-1654)
```
fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<()>
```

🔬This is a nightly-only experimental API. (`write_all_vectored` [#70436](https://github.com/rust-lang/rust/issues/70436))
Attempts to write multiple buffers into this writer. [Read more](io/trait.write#method.write_all_vectored)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1692-1724)
```
fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result<()>
```
Writes a formatted string into this writer, returning any error encountered. [Read more](io/trait.write#method.write_fmt)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1748-1753)
```
fn by_ref(&mut self) -> &mut Self
where
    Self: Sized,
```
Creates a “by reference” adapter for this instance of `Write`. [Read more](io/trait.write#method.by_ref)


[source](https://doc.rust-lang.org/src/core/marker.rs.html#989-1000)
```
impl<T> ConstParamTy for [T]
where
    T: ConstParamTy,
```
[source](https://doc.rust-lang.org/src/core/slice/cmp.rs.html#35)
```
impl<T> Eq for [T]
where
    T: Eq,
```
[source](https://doc.rust-lang.org/src/core/marker.rs.html#262-273)
```
impl<T> StructuralEq for [T]
```


Auto Trait Implementations
--------------------------




```
impl<T> RefUnwindSafe for [T]
where
    T: RefUnwindSafe,
```

```
impl<T> Send for [T]
where
    T: Send,
```

```
impl<T> !Sized for [T]
```

```
impl<T> Sync for [T]
where
    T: Sync,
```

```
impl<T> Unpin for [T]
where
    T: Unpin,
```

```
impl<T> UnwindSafe for [T]
where
    T: UnwindSafe,
```


Blanket Implementations
-----------------------



[source](https://doc.rust-lang.org/src/core/any.rs.html#200)
```
impl<T> Any for T
where
    T: 'static + ?Sized,
```

[source](https://doc.rust-lang.org/src/core/any.rs.html#201)
```
fn type_id(&self) -> TypeId
```
Gets the `TypeId` of `self`. [Read more](any/trait.any#tymethod.type_id)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#208)
```
impl<T> Borrow<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#210)
```
fn borrow(&self) -> &T
```
Immutably borrows from an owned value. [Read more](borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#216)
```
impl<T> BorrowMut<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#217)
```
fn borrow_mut(&mut self) -> &mut T
```
Mutably borrows from an owned value. [Read more](borrow/trait.borrowmut#tymethod.borrow_mut)




 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/primitive.slice.html>

Module std::option
==================


Optional values.

 Type [`Option`](enum.option "enum std::option::Option") represents an optional value: every [`Option`](enum.option "enum std::option::Option") is either [`Some`](enum.option#variant.Some "variant std::option::Option::Some") and contains a value, or [`None`](enum.option#variant.None "variant std::option::Option::None"), and does not. [`Option`](enum.option "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`](enum.option#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`](enum.option "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`](enum.option#variant.None "variant std::option::Option::None") case.

 
```
fn divide(numerator: f64, denominator: f64) -> Option<f64> {
    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"),
}
```
 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](enum.option "enum std::option::Option")<[Box<T>](../boxed/struct.box)>`.

 The following example uses [`Option`](enum.option "enum std::option::Option") to create an optional box of [`i32`](../primitive.i32 "primitive i32"). Notice that in order to use the inner [`i32`](../primitive.i32 "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(...)`](enum.option#variant.Some "variant std::option::Option::Some")) or not ([`None`](enum.option#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<Box<i32>>) {
    match optional {
        Some(p) => println!("has value {p}"),
        None => println!("has no value"),
    }
}
```
 The question mark operator, `?`
-------------------------------

 Similar to the [`Result`](../result/enum.result "enum std::result::Result") type, when writing code that calls many functions that return the [`Option`](enum.option "enum std::option::Option") type, handling `Some`/`None` can be tedious. The question mark operator, [`?`](../ops/trait.try "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<i32>) -> Option<i32> {
    let a = stack.pop();
    let b = stack.pop();

    match (a, b) {
        (Some(x), Some(y)) => Some(x + y),
        _ => None,
    }
}

```
 With this:

 
```
fn add_last_numbers(stack: &mut Vec<i32>) -> Option<i32> {
    Some(stack.pop()? + stack.pop()?)
}
```
 *It’s much nicer!*

 Ending the expression with [`?`](../ops/trait.try "trait std::ops::Try") will result in the [`Some`](enum.option#variant.Some "variant std::option::Option::Some")’s unwrapped value, unless the result is [`None`](enum.option#variant.None "variant std::option::Option::None"), in which case [`None`](enum.option#variant.None "variant std::option::Option::None") is returned early from the enclosing function.

 [`?`](../ops/trait.try "trait std::ops::Try") can be used in functions that return [`Option`](enum.option "enum std::option::Option") because of the early return of [`None`](enum.option#variant.None "variant std::option::Option::None") that it provides.

 Representation
--------------

 Rust guarantees to optimize the following types `T` such that [`Option<T>`](enum.option "enum std::option::Option") has the same size as `T`:

 * [`Box<U>`](../boxed/struct.box)
* `&U`
* `&mut U`
* `fn`, `extern "C" fn`[1](#fn1)
* [`num::NonZero*`](https://doc.rust-lang.org/core/num/index.html "mod core::num")
* [`ptr::NonNull<U>`](../ptr/struct.nonnull "struct std::ptr::NonNull")
* `#[repr(transparent)]` struct around one of the types in this list.

 This is called the “null pointer optimization” or NPO.

 It is further guaranteed that, for the cases above, one can [`mem::transmute`](../mem/fn.transmute "fn std::mem::transmute") from all valid values of `T` to `Option<T>` and from `Some::<T>(_)` to `T` (but transmuting `None::<T>` to `T` is undefined behaviour).

 Method overview
---------------

 In addition to working with pattern matching, [`Option`](enum.option "enum std::option::Option") provides a wide variety of different methods.

 ### Querying the variant

 The [`is_some`](enum.option#method.is_some "method std::option::Option::is_some") and [`is_none`](enum.option#method.is_none "method std::option::Option::is_none") methods return [`true`](../primitive.bool "primitive bool") if the [`Option`](enum.option "enum std::option::Option") is [`Some`](enum.option#variant.Some "variant std::option::Option::Some") or [`None`](enum.option#variant.None "variant std::option::Option::None"), respectively.

 ### Adapters for working with references

 * [`as_ref`](enum.option#method.as_ref "method std::option::Option::as_ref") converts from `[&](../primitive.reference "shared reference")[Option](enum.option "enum std::option::Option")<T>` to `[Option](enum.option "enum std::option::Option")<[&](../primitive.reference "shared reference")T>`
* [`as_mut`](enum.option#method.as_mut "method std::option::Option::as_mut") converts from `[&mut](../primitive.reference "mutable reference") [Option](enum.option "enum std::option::Option")<T>` to `[Option](enum.option "enum std::option::Option")<[&mut](../primitive.reference "mutable reference") T>`
* [`as_deref`](enum.option#method.as_deref "method std::option::Option::as_deref") converts from `[&](../primitive.reference "shared reference")[Option](enum.option "enum std::option::Option")<T>` to `[Option](enum.option "enum std::option::Option")<[&](../primitive.reference "shared reference")T::[Target](../ops/trait.deref#associatedtype.Target "ops::Deref::Target")>`
* [`as_deref_mut`](enum.option#method.as_deref_mut "method std::option::Option::as_deref_mut") converts from `[&mut](../primitive.reference "mutable reference") [Option](enum.option "enum std::option::Option")<T>` to `[Option](enum.option "enum std::option::Option")<[&mut](../primitive.reference "mutable reference") T::[Target](../ops/trait.deref#associatedtype.Target "ops::Deref::Target")>`
* [`as_pin_ref`](enum.option#method.as_pin_ref "method std::option::Option::as_pin_ref") converts from `[Pin](../pin/struct.pin "struct std::pin::Pin")<[&](../primitive.reference "shared reference")[Option](enum.option "enum std::option::Option")<T>>` to `[Option](enum.option "enum std::option::Option")<[Pin](../pin/struct.pin "struct std::pin::Pin")<[&](../primitive.reference "shared reference")T>>`
* [`as_pin_mut`](enum.option#method.as_pin_mut "method std::option::Option::as_pin_mut") converts from `[Pin](../pin/struct.pin "struct std::pin::Pin")<[&mut](../primitive.reference "mutable reference") [Option](enum.option "enum std::option::Option")<T>>` to `[Option](enum.option "enum std::option::Option")<[Pin](../pin/struct.pin "struct std::pin::Pin")<[&mut](../primitive.reference "mutable reference") T>>`

 ### Extracting the contained value

 These methods extract the contained value in an [`Option<T>`](enum.option "enum std::option::Option") when it is the [`Some`](enum.option#variant.Some "variant std::option::Option::Some") variant. If the [`Option`](enum.option "enum std::option::Option") is [`None`](enum.option#variant.None "variant std::option::Option::None"):

 * [`expect`](enum.option#method.expect "method std::option::Option::expect") panics with a provided custom message
* [`unwrap`](enum.option#method.unwrap "method std::option::Option::unwrap") panics with a generic message
* [`unwrap_or`](enum.option#method.unwrap_or "method std::option::Option::unwrap_or") returns the provided default value
* [`unwrap_or_default`](enum.option#method.unwrap_or_default "method std::option::Option::unwrap_or_default") returns the default value of the type `T` (which must implement the [`Default`](../default/trait.default "trait std::default::Default") trait)
* [`unwrap_or_else`](enum.option#method.unwrap_or_else "method std::option::Option::unwrap_or_else") returns the result of evaluating the provided function

 ### Transforming contained values

 These methods transform [`Option`](enum.option "enum std::option::Option") to [`Result`](../result/enum.result "enum std::result::Result"):

 * [`ok_or`](enum.option#method.ok_or "method std::option::Option::ok_or") transforms [`Some(v)`](enum.option#variant.Some "variant std::option::Option::Some") to [`Ok(v)`](../result/enum.result#variant.Ok "variant std::result::Result::Ok"), and [`None`](enum.option#variant.None "variant std::option::Option::None") to [`Err(err)`](../result/enum.result#variant.Err "variant std::result::Result::Err") using the provided default `err` value
* [`ok_or_else`](enum.option#method.ok_or_else "method std::option::Option::ok_or_else") transforms [`Some(v)`](enum.option#variant.Some "variant std::option::Option::Some") to [`Ok(v)`](../result/enum.result#variant.Ok "variant std::result::Result::Ok"), and [`None`](enum.option#variant.None "variant std::option::Option::None") to a value of [`Err`](../result/enum.result#variant.Err "variant std::result::Result::Err") using the provided function
* [`transpose`](enum.option#method.transpose "method std::option::Option::transpose") transposes an [`Option`](enum.option "enum std::option::Option") of a [`Result`](../result/enum.result "enum std::result::Result") into a [`Result`](../result/enum.result "enum std::result::Result") of an [`Option`](enum.option "enum std::option::Option")

 These methods transform the [`Some`](enum.option#variant.Some "variant std::option::Option::Some") variant:

 * [`filter`](enum.option#method.filter "method std::option::Option::filter") calls the provided predicate function on the contained value `t` if the [`Option`](enum.option "enum std::option::Option") is [`Some(t)`](enum.option#variant.Some "variant std::option::Option::Some"), and returns [`Some(t)`](enum.option#variant.Some "variant std::option::Option::Some") if the function returns `true`; otherwise, returns [`None`](enum.option#variant.None "variant std::option::Option::None")
* [`flatten`](enum.option#method.flatten "method std::option::Option::flatten") removes one level of nesting from an [`Option<Option<T>>`](enum.option "enum std::option::Option")
* [`map`](enum.option#method.map "method std::option::Option::map") transforms [`Option<T>`](enum.option "enum std::option::Option") to [`Option<U>`](enum.option "enum std::option::Option") by applying the provided function to the contained value of [`Some`](enum.option#variant.Some "variant std::option::Option::Some") and leaving [`None`](enum.option#variant.None "variant std::option::Option::None") values unchanged

 These methods transform [`Option<T>`](enum.option "enum std::option::Option") to a value of a possibly different type `U`:

 * [`map_or`](enum.option#method.map_or "method std::option::Option::map_or") applies the provided function to the contained value of [`Some`](enum.option#variant.Some "variant std::option::Option::Some"), or returns the provided default value if the [`Option`](enum.option "enum std::option::Option") is [`None`](enum.option#variant.None "variant std::option::Option::None")
* [`map_or_else`](enum.option#method.map_or_else "method std::option::Option::map_or_else") applies the provided function to the contained value of [`Some`](enum.option#variant.Some "variant std::option::Option::Some"), or returns the result of evaluating the provided fallback function if the [`Option`](enum.option "enum std::option::Option") is [`None`](enum.option#variant.None "variant std::option::Option::None")

 These methods combine the [`Some`](enum.option#variant.Some "variant std::option::Option::Some") variants of two [`Option`](enum.option "enum std::option::Option") values:

 * [`zip`](enum.option#method.zip "method std::option::Option::zip") returns [`Some((s, o))`](enum.option#variant.Some "variant std::option::Option::Some") if `self` is [`Some(s)`](enum.option#variant.Some "variant std::option::Option::Some") and the provided [`Option`](enum.option "enum std::option::Option") value is [`Some(o)`](enum.option#variant.Some "variant std::option::Option::Some"); otherwise, returns [`None`](enum.option#variant.None "variant std::option::Option::None")
* [`zip_with`](enum.option#method.zip_with "method std::option::Option::zip_with") calls the provided function `f` and returns [`Some(f(s, o))`](enum.option#variant.Some "variant std::option::Option::Some") if `self` is [`Some(s)`](enum.option#variant.Some "variant std::option::Option::Some") and the provided [`Option`](enum.option "enum std::option::Option") value is [`Some(o)`](enum.option#variant.Some "variant std::option::Option::Some"); otherwise, returns [`None`](enum.option#variant.None "variant std::option::Option::None")

 ### Boolean operators

 These methods treat the [`Option`](enum.option "enum std::option::Option") as a boolean value, where [`Some`](enum.option#variant.Some "variant std::option::Option::Some") acts like [`true`](../primitive.bool "primitive bool") and [`None`](enum.option#variant.None "variant std::option::Option::None") acts like [`false`](../primitive.bool "primitive bool"). There are two categories of these methods: ones that take an [`Option`](enum.option "enum std::option::Option") as input, and ones that take a function as input (to be lazily evaluated).

 The [`and`](enum.option#method.and "method std::option::Option::and"), [`or`](enum.option#method.or "method std::option::Option::or"), and [`xor`](enum.option#method.xor "method std::option::Option::xor") methods take another [`Option`](enum.option "enum std::option::Option") as input, and produce an [`Option`](enum.option "enum std::option::Option") as output. Only the [`and`](enum.option#method.and "method std::option::Option::and") method can produce an [`Option<U>`](enum.option "enum std::option::Option") value having a different inner type `U` than [`Option<T>`](enum.option "enum std::option::Option").

 


| method | self | input | output |
| --- | --- | --- | --- |
| [`and`](enum.option#method.and "method std::option::Option::and") | `None` | (ignored) | `None` |
| [`and`](enum.option#method.and "method std::option::Option::and") | `Some(x)` | `None` | `None` |
| [`and`](enum.option#method.and "method std::option::Option::and") | `Some(x)` | `Some(y)` | `Some(y)` |
| [`or`](enum.option#method.or "method std::option::Option::or") | `None` | `None` | `None` |
| [`or`](enum.option#method.or "method std::option::Option::or") | `None` | `Some(y)` | `Some(y)` |
| [`or`](enum.option#method.or "method std::option::Option::or") | `Some(x)` | (ignored) | `Some(x)` |
| [`xor`](enum.option#method.xor "method std::option::Option::xor") | `None` | `None` | `None` |
| [`xor`](enum.option#method.xor "method std::option::Option::xor") | `None` | `Some(y)` | `Some(y)` |
| [`xor`](enum.option#method.xor "method std::option::Option::xor") | `Some(x)` | `None` | `Some(x)` |
| [`xor`](enum.option#method.xor "method std::option::Option::xor") | `Some(x)` | `Some(y)` | `None` |

  The [`and_then`](enum.option#method.and_then "method std::option::Option::and_then") and [`or_else`](enum.option#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`](enum.option#method.and_then "method std::option::Option::and_then") method can produce an [`Option<U>`](enum.option "enum std::option::Option") value having a different inner type `U` than [`Option<T>`](enum.option "enum std::option::Option").

 


| method | self | function input | function result | output |
| --- | --- | --- | --- | --- |
| [`and_then`](enum.option#method.and_then "method std::option::Option::and_then") | `None` | (not provided) | (not evaluated) | `None` |
| [`and_then`](enum.option#method.and_then "method std::option::Option::and_then") | `Some(x)` | `x` | `None` | `None` |
| [`and_then`](enum.option#method.and_then "method std::option::Option::and_then") | `Some(x)` | `x` | `Some(y)` | `Some(y)` |
| [`or_else`](enum.option#method.or_else "method std::option::Option::or_else") | `None` | (not provided) | `None` | `None` |
| [`or_else`](enum.option#method.or_else "method std::option::Option::or_else") | `None` | (not provided) | `Some(y)` | `Some(y)` |
| [`or_else`](enum.option#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`](enum.option#method.and_then "method std::option::Option::and_then") and [`or`](enum.option#method.or "method std::option::Option::or") in a pipeline of method calls. Early stages of the pipeline pass failure values ([`None`](enum.option#variant.None "variant std::option::Option::None")) through unchanged, and continue processing on success values ([`Some`](enum.option#variant.Some "variant std::option::Option::Some")). Toward the end, [`or`](enum.option#method.or "method std::option::Option::or") substitutes an error message if it receives [`None`](enum.option#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::<Vec<_>>();
assert_eq!(res, ["error!", "error!", "foo", "error!", "bar"]);
```
 ### Comparison operators

 If `T` implements [`PartialOrd`](../cmp/trait.partialord "trait std::cmp::PartialOrd") then [`Option<T>`](enum.option "enum std::option::Option") will derive its [`PartialOrd`](../cmp/trait.partialord "trait std::cmp::PartialOrd") implementation. With this order, [`None`](enum.option#variant.None "variant std::option::Option::None") compares as less than any [`Some`](enum.option#variant.Some "variant std::option::Option::Some"), and two [`Some`](enum.option#variant.Some "variant std::option::Option::Some") compare the same way as their contained values would in `T`. If `T` also implements [`Ord`](../cmp/trait.ord "trait std::cmp::Ord"), then so does [`Option<T>`](enum.option "enum std::option::Option").

 
```
assert!(None < Some(0));
assert!(Some(0) < Some(1));
```
 ### Iterating over `Option`

 An [`Option`](enum.option "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`](enum.option "enum std::option::Option") is [`Some`](enum.option#variant.Some "variant std::option::Option::Some")), or produce no values (when the [`Option`](enum.option "enum std::option::Option") is [`None`](enum.option#variant.None "variant std::option::Option::None")). For example, [`into_iter`](enum.option#method.into_iter "method std::option::Option::into_iter") acts like [`once(v)`](../iter/fn.once "fn std::iter::once") if the [`Option`](enum.option "enum std::option::Option") is [`Some(v)`](enum.option#variant.Some "variant std::option::Option::Some"), and like [`empty()`](../iter/fn.empty "fn std::iter::empty") if the [`Option`](enum.option "enum std::option::Option") is [`None`](enum.option#variant.None "variant std::option::Option::None").

 Iterators over [`Option<T>`](enum.option "enum std::option::Option") come in three types:

 * [`into_iter`](enum.option#method.into_iter "method std::option::Option::into_iter") consumes the [`Option`](enum.option "enum std::option::Option") and produces the contained value
* [`iter`](enum.option#method.iter "method std::option::Option::iter") produces an immutable reference of type `&T` to the contained value
* [`iter_mut`](enum.option#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`](enum.option "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`](../iter/trait.iterator "trait std::iter::Iterator") methods that accept other iterators will also accept iterable types that implement [`IntoIterator`](../iter/trait.intoiterator "trait std::iter::IntoIterator"), which includes [`Option`](enum.option "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<i32> = (0..4).chain(yep).chain(4..8).collect();
assert_eq!(nums, [0, 1, 2, 3, 42, 4, 5, 6, 7]);
let nums: Vec<i32> = (0..4).chain(nope).chain(4..8).collect();
assert_eq!(nums, [0, 1, 2, 3, 4, 5, 6, 7]);
```
 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`](enum.option "enum std::option::Option") can help with that.

 
```
fn make_iter(do_insert: bool) -> impl Iterator<Item = i32> {
    // 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::<Vec<_>>());
println!("{:?}", make_iter(false).collect::<Vec<_>>());
```
 If we try to do the same thing, but using [`once()`](../iter/fn.once "fn std::iter::once") and [`empty()`](../iter/fn.empty "fn std::iter::empty"), we can’t return `impl Iterator` anymore because the concrete types of the return values differ.

 ⓘ
```
// 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<Item = i32> {
    // 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),
    }
}
```

 ### Collecting into `Option`

 [`Option`](enum.option "enum std::option::Option") implements the [`FromIterator`](enum.option#impl-FromIterator%3COption%3CA%3E%3E-for-Option%3CV%3E "enum std::option::Option") trait, which allows an iterator over [`Option`](enum.option "enum std::option::Option") values to be collected into an [`Option`](enum.option "enum std::option::Option") of a collection of each contained value of the original [`Option`](enum.option "enum std::option::Option") values, or [`None`](enum.option#variant.None "variant std::option::Option::None") if any of the elements was [`None`](enum.option#variant.None "variant std::option::Option::None").

 
```
let v = [Some(2), Some(4), None, Some(8)];
let res: Option<Vec<_>> = v.into_iter().collect();
assert_eq!(res, None);
let v = [Some(2), Some(4), Some(8)];
let res: Option<Vec<_>> = v.into_iter().collect();
assert_eq!(res, Some(vec![2, 4, 8]));
```
 [`Option`](enum.option "enum std::option::Option") also implements the [`Product`](enum.option#impl-Product%3COption%3CU%3E%3E-for-Option%3CT%3E "enum std::option::Option") and [`Sum`](enum.option#impl-Sum%3COption%3CU%3E%3E-for-Option%3CT%3E "enum std::option::Option") traits, allowing an iterator over [`Option`](enum.option "enum std::option::Option") values to provide the [`product`](../iter/trait.iterator#method.product "method std::iter::Iterator::product") and [`sum`](../iter/trait.iterator#method.sum "method std::iter::Iterator::sum") methods.

 
```
let v = [None, Some(1), Some(2), Some(3)];
let res: Option<i32> = v.into_iter().sum();
assert_eq!(res, None);
let v = [Some(1), Some(2), Some(21)];
let res: Option<i32> = v.into_iter().product();
assert_eq!(res, Some(42));
```
 ### Modifying an `Option` in-place

 These methods return a mutable reference to the contained value of an [`Option<T>`](enum.option "enum std::option::Option"):

 * [`insert`](enum.option#method.insert "method std::option::Option::insert") inserts a value, dropping any old contents
* [`get_or_insert`](enum.option#method.get_or_insert "method std::option::Option::get_or_insert") gets the current value, inserting a provided default value if it is [`None`](enum.option#variant.None "variant std::option::Option::None")
* [`get_or_insert_default`](enum.option#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`](../default/trait.default "trait std::default::Default")) if it is [`None`](enum.option#variant.None "variant std::option::Option::None")
* [`get_or_insert_with`](enum.option#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`](enum.option#variant.None "variant std::option::Option::None")

 These methods transfer ownership of the contained value of an [`Option`](enum.option "enum std::option::Option"):

 * [`take`](enum.option#method.take "method std::option::Option::take") takes ownership of the contained value of an [`Option`](enum.option "enum std::option::Option"), if any, replacing the [`Option`](enum.option "enum std::option::Option") with [`None`](enum.option#variant.None "variant std::option::Option::None")
* [`replace`](enum.option#method.replace "method std::option::Option::replace") takes ownership of the contained value of an [`Option`](enum.option "enum std::option::Option"), if any, replacing the [`Option`](enum.option "enum std::option::Option") with a [`Some`](enum.option#variant.Some "variant std::option::Option::Some") containing the provided value

 Examples
--------

 Basic pattern matching on [`Option`](enum.option "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");
```
 Initialize a result to [`None`](enum.option#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 :("),
}
```
 1. this remains true for any other ABI: `extern "abi" fn` (*e.g.*, `extern "system" fn`) [↩](#fnref1)

Structs
-------


* [IntoIter](struct.intoiter "struct std::option::IntoIter")
An iterator over the value in [`Some`](enum.option#variant.Some "variant std::option::Option::Some") variant of an [`Option`](enum.option "enum std::option::Option").
* [Iter](struct.iter "struct std::option::Iter")
An iterator over a reference to the [`Some`](enum.option#variant.Some "variant std::option::Option::Some") variant of an [`Option`](enum.option "enum std::option::Option").
* [IterMut](struct.itermut "struct std::option::IterMut")
An iterator over a mutable reference to the [`Some`](enum.option#variant.Some "variant std::option::Option::Some") variant of an [`Option`](enum.option "enum std::option::Option").


Enums
-----


* [Option](enum.option "enum std::option::Option")
The `Option` type. See [the module level documentation](index "mod std::option") for more.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/option/index.html>

Module std::result
==================


Error handling with the `Result` type.

 [`Result<T, E>`](enum.result "enum std::result::Result") is the type used for returning and propagating errors. It is an enum with the variants, [`Ok(T)`](enum.result#variant.Ok "variant std::result::Result::Ok"), representing success and containing a value, and [`Err(E)`](enum.result#variant.Err "variant std::result::Result::Err"), representing error and containing an error value.

 
```
enum Result<T, E> {
   Ok(T),
   Err(E),
}
```
 Functions return [`Result`](enum.result "enum std::result::Result") whenever errors are expected and recoverable. In the `std` crate, [`Result`](enum.result "enum std::result::Result") is most prominently used for [I/O](../io/index).

 A simple function returning [`Result`](enum.result "enum std::result::Result") might be defined and used like so:

 
```
#[derive(Debug)]
enum Version { Version1, Version2 }

fn parse_version(header: &[u8]) -> Result<Version, &'static str> {
    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:?}"),
}
```
 Pattern matching on [`Result`](enum.result "enum std::result::Result")s is clear and straightforward for simple cases, but [`Result`](enum.result "enum std::result::Result") comes with some convenience methods that make working with it more succinct.

 
```
let good_result: Result<i32, i32> = Ok(10);
let bad_result: Result<i32, i32> = Err(10);

// The `is_ok` and `is_err` methods do what they say.
assert!(good_result.is_ok() && !good_result.is_err());
assert!(bad_result.is_err() && !bad_result.is_ok());

// `map` consumes the `Result` and produces another.
let good_result: Result<i32, i32> = good_result.map(|i| i + 1);
let bad_result: Result<i32, i32> = bad_result.map(|i| i - 1);

// Use `and_then` to continue the computation.
let good_result: Result<bool, i32> = good_result.and_then(|i| Ok(i == 11));

// Use `or_else` to handle the error.
let bad_result: Result<i32, i32> = bad_result.or_else(|i| Ok(i + 20));

// Consume the result and return the contents with `unwrap`.
let final_awesome_result = good_result.unwrap();
```
 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`](enum.result "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`](enum.result "enum std::result::Result") especially useful with functions that may encounter errors but don’t otherwise return a useful value.

 Consider the [`write_all`](../io/trait.write#method.write_all "io::Write::write_all") method defined for I/O types by the [`Write`](../io/trait.write "io::Write") trait:

 
```
use std::io;

trait Write {
    fn write_all(&mut self, bytes: &[u8]) -> Result<(), io::Error>;
}
```
 *Note: The actual definition of [`Write`](../io/trait.write "io::Write") uses [`io::Result`](../io/type.result "io::Result"), which is just a synonym for `[Result](enum.result "enum std::result::Result")<T, [io::Error](../io/struct.error "io::Error")>`.*

 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");
```
 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`](enum.result#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");
```
 You might also simply assert success:

 
```
assert!(file.write_all(b"important message").is_ok());
```
 Or propagate the error up the call stack with [`?`](../ops/trait.try "trait std::ops::Try"):

 
```
fn write_message() -> io::Result<()> {
    let mut file = File::create("valuable_data.txt")?;
    file.write_all(b"important message")?;
    Ok(())
}
```
 The question mark operator, `?`
-------------------------------

 When writing code that calls many functions that return the [`Result`](enum.result "enum std::result::Result") type, the error handling can be tedious. The question mark operator, [`?`](../ops/trait.try "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(())
}
```
 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(())
}
```
 *It’s much nicer!*

 Ending the expression with [`?`](../ops/trait.try "trait std::ops::Try") will result in the [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok")’s unwrapped value, unless the result is [`Err`](enum.result#variant.Err "variant std::result::Result::Err"), in which case [`Err`](enum.result#variant.Err "variant std::result::Result::Err") is returned early from the enclosing function.

 [`?`](../ops/trait.try "trait std::ops::Try") can be used in functions that return [`Result`](enum.result "enum std::result::Result") because of the early return of [`Err`](enum.result#variant.Err "variant std::result::Result::Err") that it provides.

 Method overview
---------------

 In addition to working with pattern matching, [`Result`](enum.result "enum std::result::Result") provides a wide variety of different methods.

 ### Querying the variant

 The [`is_ok`](enum.result#method.is_ok "method std::result::Result::is_ok") and [`is_err`](enum.result#method.is_err "method std::result::Result::is_err") methods return [`true`](../primitive.bool "primitive bool") if the [`Result`](enum.result "enum std::result::Result") is [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok") or [`Err`](enum.result#variant.Err "variant std::result::Result::Err"), respectively.

 ### Adapters for working with references

 * [`as_ref`](enum.result#method.as_ref "method std::result::Result::as_ref") converts from `&Result<T, E>` to `Result<&T, &E>`
* [`as_mut`](enum.result#method.as_mut "method std::result::Result::as_mut") converts from `&mut Result<T, E>` to `Result<&mut T, &mut E>`
* [`as_deref`](enum.result#method.as_deref "method std::result::Result::as_deref") converts from `&Result<T, E>` to `Result<&T::Target, &E>`
* [`as_deref_mut`](enum.result#method.as_deref_mut "method std::result::Result::as_deref_mut") converts from `&mut Result<T, E>` to `Result<&mut T::Target, &mut E>`

 ### Extracting contained values

 These methods extract the contained value in a [`Result<T, E>`](enum.result "enum std::result::Result") when it is the [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok") variant. If the [`Result`](enum.result "enum std::result::Result") is [`Err`](enum.result#variant.Err "variant std::result::Result::Err"):

 * [`expect`](enum.result#method.expect "method std::result::Result::expect") panics with a provided custom message
* [`unwrap`](enum.result#method.unwrap "method std::result::Result::unwrap") panics with a generic message
* [`unwrap_or`](enum.result#method.unwrap_or "method std::result::Result::unwrap_or") returns the provided default value
* [`unwrap_or_default`](enum.result#method.unwrap_or_default "method std::result::Result::unwrap_or_default") returns the default value of the type `T` (which must implement the [`Default`](../default/trait.default "trait std::default::Default") trait)
* [`unwrap_or_else`](enum.result#method.unwrap_or_else "method std::result::Result::unwrap_or_else") returns the result of evaluating the provided function

 The panicking methods [`expect`](enum.result#method.expect "method std::result::Result::expect") and [`unwrap`](enum.result#method.unwrap "method std::result::Result::unwrap") require `E` to implement the [`Debug`](../fmt/trait.debug "trait std::fmt::Debug") trait.

 These methods extract the contained value in a [`Result<T, E>`](enum.result "enum std::result::Result") when it is the [`Err`](enum.result#variant.Err "variant std::result::Result::Err") variant. They require `T` to implement the [`Debug`](../fmt/trait.debug "trait std::fmt::Debug") trait. If the [`Result`](enum.result "enum std::result::Result") is [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok"):

 * [`expect_err`](enum.result#method.expect_err "method std::result::Result::expect_err") panics with a provided custom message
* [`unwrap_err`](enum.result#method.unwrap_err "method std::result::Result::unwrap_err") panics with a generic message

 ### Transforming contained values

 These methods transform [`Result`](enum.result "enum std::result::Result") to [`Option`](../option/enum.option "enum std::option::Option"):

 * [`err`](enum.result#method.err "method std::result::Result::err") transforms [`Result<T, E>`](enum.result "enum std::result::Result") into [`Option<E>`](../option/enum.option "enum std::option::Option"), mapping [`Err(e)`](enum.result#variant.Err "variant std::result::Result::Err") to [`Some(e)`](../option/enum.option#variant.Some "variant std::option::Option::Some") and [`Ok(v)`](enum.result#variant.Ok "variant std::result::Result::Ok") to [`None`](../option/enum.option#variant.None "variant std::option::Option::None")
* [`ok`](enum.result#method.ok "method std::result::Result::ok") transforms [`Result<T, E>`](enum.result "enum std::result::Result") into [`Option<T>`](../option/enum.option "enum std::option::Option"), mapping [`Ok(v)`](enum.result#variant.Ok "variant std::result::Result::Ok") to [`Some(v)`](../option/enum.option#variant.Some "variant std::option::Option::Some") and [`Err(e)`](enum.result#variant.Err "variant std::result::Result::Err") to [`None`](../option/enum.option#variant.None "variant std::option::Option::None")
* [`transpose`](enum.result#method.transpose "method std::result::Result::transpose") transposes a [`Result`](enum.result "enum std::result::Result") of an [`Option`](../option/enum.option "enum std::option::Option") into an [`Option`](../option/enum.option "enum std::option::Option") of a [`Result`](enum.result "enum std::result::Result")

 This method transforms the contained value of the [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok") variant:

 * [`map`](enum.result#method.map "method std::result::Result::map") transforms [`Result<T, E>`](enum.result "enum std::result::Result") into [`Result<U, E>`](enum.result "enum std::result::Result") by applying the provided function to the contained value of [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok") and leaving [`Err`](enum.result#variant.Err "variant std::result::Result::Err") values unchanged

 This method transforms the contained value of the [`Err`](enum.result#variant.Err "variant std::result::Result::Err") variant:

 * [`map_err`](enum.result#method.map_err "method std::result::Result::map_err") transforms [`Result<T, E>`](enum.result "enum std::result::Result") into [`Result<T, F>`](enum.result "enum std::result::Result") by applying the provided function to the contained value of [`Err`](enum.result#variant.Err "variant std::result::Result::Err") and leaving [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok") values unchanged

 These methods transform a [`Result<T, E>`](enum.result "enum std::result::Result") into a value of a possibly different type `U`:

 * [`map_or`](enum.result#method.map_or "method std::result::Result::map_or") applies the provided function to the contained value of [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok"), or returns the provided default value if the [`Result`](enum.result "enum std::result::Result") is [`Err`](enum.result#variant.Err "variant std::result::Result::Err")
* [`map_or_else`](enum.result#method.map_or_else "method std::result::Result::map_or_else") applies the provided function to the contained value of [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok"), or applies the provided default fallback function to the contained value of [`Err`](enum.result#variant.Err "variant std::result::Result::Err")

 ### Boolean operators

 These methods treat the [`Result`](enum.result "enum std::result::Result") as a boolean value, where [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok") acts like [`true`](../primitive.bool "primitive bool") and [`Err`](enum.result#variant.Err "variant std::result::Result::Err") acts like [`false`](../primitive.bool "primitive bool"). There are two categories of these methods: ones that take a [`Result`](enum.result "enum std::result::Result") as input, and ones that take a function as input (to be lazily evaluated).

 The [`and`](enum.result#method.and "method std::result::Result::and") and [`or`](enum.result#method.or "method std::result::Result::or") methods take another [`Result`](enum.result "enum std::result::Result") as input, and produce a [`Result`](enum.result "enum std::result::Result") as output. The [`and`](enum.result#method.and "method std::result::Result::and") method can produce a [`Result<U, E>`](enum.result "enum std::result::Result") value having a different inner type `U` than [`Result<T, E>`](enum.result "enum std::result::Result"). The [`or`](enum.result#method.or "method std::result::Result::or") method can produce a [`Result<T, F>`](enum.result "enum std::result::Result") value having a different error type `F` than [`Result<T, E>`](enum.result "enum std::result::Result").

 


| method | self | input | output |
| --- | --- | --- | --- |
| [`and`](enum.result#method.and "method std::result::Result::and") | `Err(e)` | (ignored) | `Err(e)` |
| [`and`](enum.result#method.and "method std::result::Result::and") | `Ok(x)` | `Err(d)` | `Err(d)` |
| [`and`](enum.result#method.and "method std::result::Result::and") | `Ok(x)` | `Ok(y)` | `Ok(y)` |
| [`or`](enum.result#method.or "method std::result::Result::or") | `Err(e)` | `Err(d)` | `Err(d)` |
| [`or`](enum.result#method.or "method std::result::Result::or") | `Err(e)` | `Ok(y)` | `Ok(y)` |
| [`or`](enum.result#method.or "method std::result::Result::or") | `Ok(x)` | (ignored) | `Ok(x)` |

  The [`and_then`](enum.result#method.and_then "method std::result::Result::and_then") and [`or_else`](enum.result#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`](enum.result#method.and_then "method std::result::Result::and_then") method can produce a [`Result<U, E>`](enum.result "enum std::result::Result") value having a different inner type `U` than [`Result<T, E>`](enum.result "enum std::result::Result"). The [`or_else`](enum.result#method.or_else "method std::result::Result::or_else") method can produce a [`Result<T, F>`](enum.result "enum std::result::Result") value having a different error type `F` than [`Result<T, E>`](enum.result "enum std::result::Result").

 


| method | self | function input | function result | output |
| --- | --- | --- | --- | --- |
| [`and_then`](enum.result#method.and_then "method std::result::Result::and_then") | `Err(e)` | (not provided) | (not evaluated) | `Err(e)` |
| [`and_then`](enum.result#method.and_then "method std::result::Result::and_then") | `Ok(x)` | `x` | `Err(d)` | `Err(d)` |
| [`and_then`](enum.result#method.and_then "method std::result::Result::and_then") | `Ok(x)` | `x` | `Ok(y)` | `Ok(y)` |
| [`or_else`](enum.result#method.or_else "method std::result::Result::or_else") | `Err(e)` | `e` | `Err(d)` | `Err(d)` |
| [`or_else`](enum.result#method.or_else "method std::result::Result::or_else") | `Err(e)` | `e` | `Ok(y)` | `Ok(y)` |
| [`or_else`](enum.result#method.or_else "method std::result::Result::or_else") | `Ok(x)` | (not provided) | (not evaluated) | `Ok(x)` |

 
### Comparison operators

 If `T` and `E` both implement [`PartialOrd`](../cmp/trait.partialord "trait std::cmp::PartialOrd") then [`Result<T, E>`](enum.result "enum std::result::Result") will derive its [`PartialOrd`](../cmp/trait.partialord "trait std::cmp::PartialOrd") implementation. With this order, an [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok") compares as less than any [`Err`](enum.result#variant.Err "variant std::result::Result::Err"), while two [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok") or two [`Err`](enum.result#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`](../cmp/trait.ord "trait std::cmp::Ord"), then so does [`Result<T, E>`](enum.result "enum std::result::Result").

 
```
assert!(Ok(1) < Err(0));
let x: Result<i32, ()> = Ok(0);
let y = Ok(1);
assert!(x < y);
let x: Result<(), i32> = Err(0);
let y = Err(1);
assert!(x < y);
```
 ### Iterating over `Result`

 A [`Result`](enum.result "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`](enum.result "enum std::result::Result") is [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok")), or produce no values (when the [`Result`](enum.result "enum std::result::Result") is [`Err`](enum.result#variant.Err "variant std::result::Result::Err")). For example, [`into_iter`](enum.result#method.into_iter "method std::result::Result::into_iter") acts like [`once(v)`](../iter/fn.once "fn std::iter::once") if the [`Result`](enum.result "enum std::result::Result") is [`Ok(v)`](enum.result#variant.Ok "variant std::result::Result::Ok"), and like [`empty()`](../iter/fn.empty "fn std::iter::empty") if the [`Result`](enum.result "enum std::result::Result") is [`Err`](enum.result#variant.Err "variant std::result::Result::Err").

 Iterators over [`Result<T, E>`](enum.result "enum std::result::Result") come in three types:

 * [`into_iter`](enum.result#method.into_iter "method std::result::Result::into_iter") consumes the [`Result`](enum.result "enum std::result::Result") and produces the contained value
* [`iter`](enum.result#method.iter "method std::result::Result::iter") produces an immutable reference of type `&T` to the contained value
* [`iter_mut`](enum.result#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`](../option/index#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`](enum.result "enum std::result::Result") to select only the [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok") values using [`flatten`](../iter/trait.iterator#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:?}");
```
 ### Collecting into `Result`

 [`Result`](enum.result "enum std::result::Result") implements the [`FromIterator`](enum.result#impl-FromIterator%3CResult%3CA,+E%3E%3E-for-Result%3CV,+E%3E "enum std::result::Result") trait, which allows an iterator over [`Result`](enum.result "enum std::result::Result") values to be collected into a [`Result`](enum.result "enum std::result::Result") of a collection of each contained value of the original [`Result`](enum.result "enum std::result::Result") values, or [`Err`](enum.result#variant.Err "variant std::result::Result::Err") if any of the elements was [`Err`](enum.result#variant.Err "variant std::result::Result::Err").

 
```
let v = [Ok(2), Ok(4), Err("err!"), Ok(8)];
let res: Result<Vec<_>, &str> = v.into_iter().collect();
assert_eq!(res, Err("err!"));
let v = [Ok(2), Ok(4), Ok(8)];
let res: Result<Vec<_>, &str> = v.into_iter().collect();
assert_eq!(res, Ok(vec![2, 4, 8]));
```
 [`Result`](enum.result "enum std::result::Result") also implements the [`Product`](enum.result#impl-Product%3CResult%3CU,+E%3E%3E-for-Result%3CT,+E%3E "enum std::result::Result") and [`Sum`](enum.result#impl-Sum%3CResult%3CU,+E%3E%3E-for-Result%3CT,+E%3E "enum std::result::Result") traits, allowing an iterator over [`Result`](enum.result "enum std::result::Result") values to provide the [`product`](../iter/trait.iterator#method.product "method std::iter::Iterator::product") and [`sum`](../iter/trait.iterator#method.sum "method std::iter::Iterator::sum") methods.

 
```
let v = [Err("error!"), Ok(1), Ok(2), Ok(3), Err("foo")];
let res: Result<i32, &str> = v.into_iter().sum();
assert_eq!(res, Err("error!"));
let v = [Ok(1), Ok(2), Ok(21)];
let res: Result<i32, &str> = v.into_iter().product();
assert_eq!(res, Ok(42));
```
 Structs
-------


* [IntoIter](struct.intoiter "struct std::result::IntoIter")
An iterator over the value in a [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok") variant of a [`Result`](enum.result "enum std::result::Result").
* [Iter](struct.iter "struct std::result::Iter")
An iterator over a reference to the [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok") variant of a [`Result`](enum.result "enum std::result::Result").
* [IterMut](struct.itermut "struct std::result::IterMut")
An iterator over a mutable reference to the [`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok") variant of a [`Result`](enum.result "enum std::result::Result").


Enums
-----


* [Result](enum.result "enum std::result::Result")

`Result` is a type that represents either success ([`Ok`](enum.result#variant.Ok "variant std::result::Result::Ok")) or failure ([`Err`](enum.result#variant.Err "variant std::result::Result::Err")).



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/result/index.html>

Module std::iter
================


Composable external iteration.

 If you’ve found yourself with a collection of some kind, and needed to perform an operation on the elements of said collection, you’ll quickly run into ‘iterators’. Iterators are heavily used in idiomatic Rust code, so it’s worth becoming familiar with them.

 Before explaining more, let’s talk about how this module is structured:

 Organization
------------

 This module is largely organized by type:

 * [Traits](#traits) are the core portion: these traits define what kind of iterators exist and what you can do with them. The methods of these traits are worth putting some extra study time into.
* [Functions](#functions) provide some helpful ways to create some basic iterators.
* [Structs](#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 Iterator](#implementing-iterator)’.

 That’s it! Let’s dig into iterators.

 Iterator
--------

 The heart and soul of this module is the [`Iterator`](trait.iterator "trait std::iter::Iterator") trait. The core of [`Iterator`](trait.iterator "trait std::iter::Iterator") looks like this:

 
```
trait Iterator {
    type Item;
    fn next(&mut self) -> Option<Self::Item>;
}
```
 An iterator has a method, [`next`](trait.iterator#tymethod.next "method std::iter::Iterator::next"), which when called, returns an `[Option](../option/enum.option "enum std::option::Option")<Item>`. Calling [`next`](trait.iterator#tymethod.next "method std::iter::Iterator::next") will return [`Some(Item)`](../option/enum.option#variant.Some "variant std::option::Option::Some") as long as there are elements, and once they’ve all been exhausted, will return `None` to indicate that iteration is finished. Individual iterators may choose to resume iteration, and so calling [`next`](trait.iterator#tymethod.next "method std::iter::Iterator::next") again may or may not eventually start returning [`Some(Item)`](../option/enum.option#variant.Some "variant std::option::Option::Some") again at some point (for example, see [`TryIter`](../sync/mpsc/struct.tryiter)).

 [`Iterator`](trait.iterator "trait std::iter::Iterator")’s full definition includes a number of other methods as well, but they are default methods, built on top of [`next`](trait.iterator#tymethod.next "method std::iter::Iterator::next"), and so you get them for free.

 Iterators are also composable, and it’s common to chain them together to do more complex forms of processing. See the [Adapters](#adapters) section below for more details.

 The three forms of iteration
----------------------------

 There are three common methods which can create iterators from a collection:

 * `iter()`, which iterates over `&T`.
* `iter_mut()`, which iterates over `&mut T`.
* `into_iter()`, which iterates over `T`.

 Various things in the standard library may implement one or more of the three, where appropriate.

 Implementing Iterator
---------------------

 Creating an iterator of your own involves two steps: creating a `struct` to hold the iterator’s state, and then implementing [`Iterator`](trait.iterator "trait std::iter::Iterator") for that `struct`. This is why there are so many `struct`s in this module: there is one for each iterator and iterator adapter.

 Let’s make an iterator named `Counter` which counts from `1` to `5`:

 
```
// First, the struct:

/// An 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 `next()`'s implementation below.
impl Counter {
    fn new() -> Counter {
        Counter { count: 0 }
    }
}

// Then, we implement `Iterator` for our `Counter`:

impl Iterator for Counter {
    // we will be counting with usize
    type Item = usize;

    // next() is the only required method
    fn next(&mut self) -> Option<Self::Item> {
        // 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 {
            Some(self.count)
        } else {
            None
        }
    }
}

// And now we can use it!

let mut counter = Counter::new();

assert_eq!(counter.next(), Some(1));
assert_eq!(counter.next(), Some(2));
assert_eq!(counter.next(), Some(3));
assert_eq!(counter.next(), Some(4));
assert_eq!(counter.next(), Some(5));
assert_eq!(counter.next(), None);
```
 Calling [`next`](trait.iterator#tymethod.next "method std::iter::Iterator::next") this way gets repetitive. Rust has a construct which can call [`next`](trait.iterator#tymethod.next "method std::iter::Iterator::next") on your iterator, until it reaches `None`. Let’s go over that next.

 Also note that `Iterator` provides a default implementation of methods such as `nth` and `fold` which call `next` internally. However, it is also possible to write a custom implementation of methods like `nth` and `fold` if an iterator can compute them more efficiently without calling `next`.

 
`for` loops and `IntoIterator`
-------------------------------

 Rust’s `for` loop syntax is actually sugar for iterators. Here’s a basic example of `for`:

 
```
let values = vec![1, 2, 3, 4, 5];

for x in values {
    println!("{x}");
}
```
 This will print the numbers one through five, each on their own line. But you’ll notice something here: we never called anything on our vector to produce an iterator. What gives?

 There’s a trait in the standard library for converting something into an iterator: [`IntoIterator`](trait.intoiterator "trait std::iter::IntoIterator"). This trait has one method, [`into_iter`](trait.intoiterator#tymethod.into_iter "method std::iter::IntoIterator::into_iter"), which converts the thing implementing [`IntoIterator`](trait.intoiterator "trait std::iter::IntoIterator") into an iterator. Let’s take a look at that `for` loop again, and what the compiler converts it into:

 
```
let values = vec![1, 2, 3, 4, 5];

for x in values {
    println!("{x}");
}
```
 Rust de-sugars this into:

 
```
let values = vec![1, 2, 3, 4, 5];
{
    let result = match IntoIterator::into_iter(values) {
        mut iter => loop {
            let next;
            match iter.next() {
                Some(val) => next = val,
                None => break,
            };
            let x = next;
            let () = { println!("{x}"); };
        },
    };
    result
}
```
 First, we call `into_iter()` on the value. Then, we match on the iterator that returns, calling [`next`](trait.iterator#tymethod.next "method std::iter::Iterator::next") over and over until we see a `None`. At that point, we `break` out of the loop, and we’re done iterating.

 There’s one more subtle bit here: the standard library contains an interesting implementation of [`IntoIterator`](trait.intoiterator "trait std::iter::IntoIterator"):

 ⓘ
```
impl<I: Iterator> IntoIterator for I
```

 In other words, all [`Iterator`](trait.iterator "trait std::iter::Iterator")s implement [`IntoIterator`](trait.intoiterator "trait std::iter::IntoIterator"), by just returning themselves. This means two things:

 1. If you’re writing an [`Iterator`](trait.iterator "trait std::iter::Iterator"), you can use it with a `for` loop.
2. If you’re creating a collection, implementing [`IntoIterator`](trait.intoiterator "trait std::iter::IntoIterator") for it will allow your collection to be used with the `for` loop.

 Iterating by reference
----------------------

 Since [`into_iter()`](trait.intoiterator#tymethod.into_iter "method std::iter::IntoIterator::into_iter") takes `self` by value, using a `for` loop to iterate over a collection consumes that collection. Often, you may want to iterate over a collection without consuming it. Many collections offer methods that provide iterators over references, conventionally called `iter()` and `iter_mut()` respectively:

 
```
let mut values = vec![41];
for x in values.iter_mut() {
    *x += 1;
}
for x in values.iter() {
    assert_eq!(*x, 42);
}
assert_eq!(values.len(), 1); // `values` is still owned by this function.
```
 If a collection type `C` provides `iter()`, it usually also implements `IntoIterator` for `&C`, with an implementation that just calls `iter()`. Likewise, a collection `C` that provides `iter_mut()` generally implements `IntoIterator` for `&mut C` by delegating to `iter_mut()`. This enables a convenient shorthand:

 
```
let mut values = vec![41];
for x in &mut values { // same as `values.iter_mut()`
    *x += 1;
}
for x in &values { // same as `values.iter()`
    assert_eq!(*x, 42);
}
assert_eq!(values.len(), 1);
```
 While many collections offer `iter()`, not all offer `iter_mut()`. For example, mutating the keys of a [`HashSet<T>`](../collections/struct.hashset) could put the collection into an inconsistent state if the key hashes change, so this collection only offers `iter()`.

 Adapters
--------

 Functions which take an [`Iterator`](trait.iterator "trait std::iter::Iterator") and return another [`Iterator`](trait.iterator "trait std::iter::Iterator") are often called ‘iterator adapters’, as they’re a form of the ‘adapter pattern’.

 Common iterator adapters include [`map`](trait.iterator#method.map "method std::iter::Iterator::map"), [`take`](trait.iterator#method.take "method std::iter::Iterator::take"), and [`filter`](trait.iterator#method.filter "method std::iter::Iterator::filter"). For more, see their documentation.

 If an iterator adapter panics, the iterator will be in an unspecified (but memory safe) state. This state is also not guaranteed to stay the same across versions of Rust, so you should avoid relying on the exact values returned by an iterator which panicked.

 Laziness
--------

 Iterators (and iterator [adapters](#adapters)) are *lazy*. This means that just creating an iterator doesn’t *do* a whole lot. Nothing really happens until you call [`next`](trait.iterator#tymethod.next "method std::iter::Iterator::next"). This is sometimes a source of confusion when creating an iterator solely for its side effects. For example, the [`map`](trait.iterator#method.map "method std::iter::Iterator::map") method calls a closure on each element it iterates over:

 
```
let v = vec![1, 2, 3, 4, 5];
v.iter().map(|x| println!("{x}"));
```
 This will not print any values, as we only created an iterator, rather than using it. The compiler will warn us about this kind of behavior:

 
```
warning: unused result that must be used: iterators are lazy and
do nothing unless consumed

```
 The idiomatic way to write a [`map`](trait.iterator#method.map "method std::iter::Iterator::map") for its side effects is to use a `for` loop or call the [`for_each`](trait.iterator#method.for_each "method std::iter::Iterator::for_each") method:

 
```
let v = vec![1, 2, 3, 4, 5];

v.iter().for_each(|x| println!("{x}"));
// or
for x in &v {
    println!("{x}");
}
```
 Another common way to evaluate an iterator is to use the [`collect`](trait.iterator#method.collect "method std::iter::Iterator::collect") method to produce a new collection.

 Infinity
--------

 Iterators do not have to be finite. As an example, an open-ended range is an infinite iterator:

 
```
let numbers = 0..;
```
 It is common to use the [`take`](trait.iterator#method.take "method std::iter::Iterator::take") iterator adapter to turn an infinite iterator into a finite one:

 
```
let numbers = 0..;
let five_numbers = numbers.take(5);

for number in five_numbers {
    println!("{number}");
}
```
 This will print the numbers `0` through `4`, each on their own line.

 Bear in mind that methods on infinite iterators, even those for which a result can be determined mathematically in finite time, might not terminate. Specifically, methods such as [`min`](trait.iterator#method.min "method std::iter::Iterator::min"), which in the general case require traversing every element in the iterator, are likely not to return successfully for any infinite iterators.

 
```
let ones = std::iter::repeat(1);
let least = ones.min().unwrap(); // Oh no! An infinite loop!
// `ones.min()` causes an infinite loop, so we won't reach this point!
println!("The smallest number one is {least}.");
```
 Structs
-------


* [ArrayChunks](struct.arraychunks "struct std::iter::ArrayChunks")Experimental

An iterator over `N` elements of the iterator at a time.
* [ByRefSized](struct.byrefsized "struct std::iter::ByRefSized")Experimental

Like `Iterator::by_ref`, but requiring `Sized` so it can forward generics.
* [Intersperse](struct.intersperse "struct std::iter::Intersperse")Experimental

An iterator adapter that places a separator between all elements.
* [IntersperseWith](struct.interspersewith "struct std::iter::IntersperseWith")Experimental

An iterator adapter that places a separator between all elements.
* [Chain](struct.chain "struct std::iter::Chain")
An iterator that links two iterators together, in a chain.
* [Cloned](struct.cloned "struct std::iter::Cloned")
An iterator that clones the elements of an underlying iterator.
* [Copied](struct.copied "struct std::iter::Copied")
An iterator that copies the elements of an underlying iterator.
* [Cycle](struct.cycle "struct std::iter::Cycle")
An iterator that repeats endlessly.
* [Empty](struct.empty "struct std::iter::Empty")
An iterator that yields nothing.
* [Enumerate](struct.enumerate "struct std::iter::Enumerate")
An iterator that yields the current count and the element during iteration.
* [Filter](struct.filter "struct std::iter::Filter")
An iterator that filters the elements of `iter` with `predicate`.
* [FilterMap](struct.filtermap "struct std::iter::FilterMap")
An iterator that uses `f` to both filter and map elements from `iter`.
* [FlatMap](struct.flatmap "struct std::iter::FlatMap")
An iterator that maps each element to an iterator, and yields the elements of the produced iterators.
* [Flatten](struct.flatten "struct std::iter::Flatten")
An iterator that flattens one level of nesting in an iterator of things that can be turned into iterators.
* [FromFn](struct.fromfn "struct std::iter::FromFn")
An iterator where each iteration calls the provided closure `F: FnMut() -> Option<T>`.
* [Fuse](struct.fuse "struct std::iter::Fuse")
An iterator that yields `None` forever after the underlying iterator yields `None` once.
* [Inspect](struct.inspect "struct std::iter::Inspect")
An iterator that calls a function with a reference to each element before yielding it.
* [Map](struct.map "struct std::iter::Map")
An iterator that maps the values of `iter` with `f`.
* [MapWhile](struct.mapwhile "struct std::iter::MapWhile")
An iterator that only accepts elements while `predicate` returns `Some(_)`.
* [Once](struct.once "struct std::iter::Once")
An iterator that yields an element exactly once.
* [OnceWith](struct.oncewith "struct std::iter::OnceWith")
An iterator that yields a single element of type `A` by applying the provided closure `F: FnOnce() -> A`.
* [Peekable](struct.peekable "struct std::iter::Peekable")
An iterator with a `peek()` that returns an optional reference to the next element.
* [Repeat](struct.repeat "struct std::iter::Repeat")
An iterator that repeats an element endlessly.
* [RepeatWith](struct.repeatwith "struct std::iter::RepeatWith")
An iterator that repeats elements of type `A` endlessly by applying the provided closure `F: FnMut() -> A`.
* [Rev](struct.rev "struct std::iter::Rev")
A double-ended iterator with the direction inverted.
* [Scan](struct.scan "struct std::iter::Scan")
An iterator to maintain state while iterating another iterator.
* [Skip](struct.skip "struct std::iter::Skip")
An iterator that skips over `n` elements of `iter`.
* [SkipWhile](struct.skipwhile "struct std::iter::SkipWhile")
An iterator that rejects elements while `predicate` returns `true`.
* [StepBy](struct.stepby "struct std::iter::StepBy")
An iterator for stepping iterators by a custom amount.
* [Successors](struct.successors "struct std::iter::Successors")
An new iterator where each successive item is computed based on the preceding one.
* [Take](struct.take "struct std::iter::Take")
An iterator that only iterates over the first `n` iterations of `iter`.
* [TakeWhile](struct.takewhile "struct std::iter::TakeWhile")
An iterator that only accepts elements while `predicate` returns `true`.
* [Zip](struct.zip "struct std::iter::Zip")
An iterator that iterates two other iterators simultaneously.


Traits
------


* [Step](trait.step "trait std::iter::Step")Experimental

Objects that have a notion of *successor* and *predecessor* operations.
* [TrustedLen](trait.trustedlen "trait std::iter::TrustedLen")Experimental

An iterator that reports an accurate length using size\_hint.
* [TrustedStep](trait.trustedstep "trait std::iter::TrustedStep")Experimental

A type that upholds all invariants of [`Step`](trait.step "trait std::iter::Step").
* [DoubleEndedIterator](trait.doubleendediterator "trait std::iter::DoubleEndedIterator")
An iterator able to yield elements from both ends.
* [ExactSizeIterator](trait.exactsizeiterator "trait std::iter::ExactSizeIterator")
An iterator that knows its exact length.
* [Extend](trait.extend "trait std::iter::Extend")
Extend a collection with the contents of an iterator.
* [FromIterator](trait.fromiterator "trait std::iter::FromIterator")
Conversion from an [`Iterator`](trait.iterator "trait std::iter::Iterator").
* [FusedIterator](trait.fusediterator "trait std::iter::FusedIterator")
An iterator that always continues to yield `None` when exhausted.
* [IntoIterator](trait.intoiterator "trait std::iter::IntoIterator")
Conversion into an [`Iterator`](trait.iterator "trait std::iter::Iterator").
* [Iterator](trait.iterator "trait std::iter::Iterator")
A trait for dealing with iterators.
* [Product](trait.product "trait std::iter::Product")
Trait to represent types that can be created by multiplying elements of an iterator.
* [Sum](trait.sum "trait std::iter::Sum")
Trait to represent types that can be created by summing up an iterator.


Functions
---------


* [from\_generator](fn.from_generator "fn std::iter::from_generator")Experimental

Creates a new iterator where each iteration calls the provided generator.
* [empty](fn.empty "fn std::iter::empty")
Creates an iterator that yields nothing.
* [from\_fn](fn.from_fn "fn std::iter::from_fn")
Creates a new iterator where each iteration calls the provided closure `F: FnMut() -> Option<T>`.
* [once](fn.once "fn std::iter::once")
Creates an iterator that yields an element exactly once.
* [once\_with](fn.once_with "fn std::iter::once_with")
Creates an iterator that lazily generates a value exactly once by invoking the provided closure.
* [repeat](fn.repeat "fn std::iter::repeat")
Creates a new iterator that endlessly repeats a single element.
* [repeat\_with](fn.repeat_with "fn std::iter::repeat_with")
Creates a new iterator that repeats elements of type `A` endlessly by applying the provided closure, the repeater, `F: FnMut() -> A`.
* [successors](fn.successors "fn std::iter::successors")
Creates a new iterator where each successive item is computed based on the preceding one.
* [zip](fn.zip "fn std::iter::zip")
Converts the arguments to iterators and zips them.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/iter/index.html>

Trait std::iter::Iterator
=========================



```
pub trait Iterator {
    type Item;

Show 75 methods    // Required method
    fn next(&mut self) -> Option<Self::Item>;

    // Provided methods
    fn next_chunk<const N: usize>(
        &mut self
    ) -> Result<[Self::Item; N], IntoIter<Self::Item, N>>
       where Self: Sized { ... }
    fn size_hint(&self) -> (usize, Option<usize>) { ... }
    fn count(self) -> usize
       where Self: Sized { ... }
    fn last(self) -> Option<Self::Item>
       where Self: Sized { ... }
    fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> { ... }
    fn nth(&mut self, n: usize) -> Option<Self::Item> { ... }
    fn step_by(self, step: usize) -> StepBy<Self> ⓘ
       where Self: Sized { ... }
    fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter> ⓘ
       where Self: Sized,
             U: IntoIterator<Item = Self::Item> { ... }
    fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter> ⓘ
       where Self: Sized,
             U: IntoIterator { ... }
    fn intersperse(self, separator: Self::Item) -> Intersperse<Self> ⓘ
       where Self: Sized,
             Self::Item: Clone { ... }
    fn intersperse_with<G>(self, separator: G) -> IntersperseWith<Self, G> ⓘ
       where Self: Sized,
             G: FnMut() -> Self::Item { ... }
    fn map<B, F>(self, f: F) -> Map<Self, F> ⓘ
       where Self: Sized,
             F: FnMut(Self::Item) -> B { ... }
    fn for_each<F>(self, f: F)
       where Self: Sized,
             F: FnMut(Self::Item) { ... }
    fn filter<P>(self, predicate: P) -> Filter<Self, P> ⓘ
       where Self: Sized,
             P: FnMut(&Self::Item) -> bool { ... }
    fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> ⓘ
       where Self: Sized,
             F: FnMut(Self::Item) -> Option<B> { ... }
    fn enumerate(self) -> Enumerate<Self> ⓘ
       where Self: Sized { ... }
    fn peekable(self) -> Peekable<Self> ⓘ
       where Self: Sized { ... }
    fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> ⓘ
       where Self: Sized,
             P: FnMut(&Self::Item) -> bool { ... }
    fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> ⓘ
       where Self: Sized,
             P: FnMut(&Self::Item) -> bool { ... }
    fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P> ⓘ
       where Self: Sized,
             P: FnMut(Self::Item) -> Option<B> { ... }
    fn skip(self, n: usize) -> Skip<Self> ⓘ
       where Self: Sized { ... }
    fn take(self, n: usize) -> Take<Self> ⓘ
       where Self: Sized { ... }
    fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F> ⓘ
       where Self: Sized,
             F: FnMut(&mut St, Self::Item) -> Option<B> { ... }
    fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F> ⓘ
       where Self: Sized,
             U: IntoIterator,
             F: FnMut(Self::Item) -> U { ... }
    fn flatten(self) -> Flatten<Self> ⓘ
       where Self: Sized,
             Self::Item: IntoIterator { ... }
    fn fuse(self) -> Fuse<Self> ⓘ
       where Self: Sized { ... }
    fn inspect<F>(self, f: F) -> Inspect<Self, F> ⓘ
       where Self: Sized,
             F: FnMut(&Self::Item) { ... }
    fn by_ref(&mut self) -> &mut Self
       where Self: Sized { ... }
    fn collect<B>(self) -> B
       where B: FromIterator<Self::Item>,
             Self: Sized { ... }
    fn try_collect<B>(
        &mut self
    ) -> <<Self::Item as Try>::Residual as Residual<B>>::TryType
       where Self: Sized,
             Self::Item: Try,
             <Self::Item as Try>::Residual: Residual<B>,
             B: FromIterator<<Self::Item as Try>::Output> { ... }
    fn collect_into<E>(self, collection: &mut E) -> &mut E
       where E: Extend<Self::Item>,
             Self: Sized { ... }
    fn partition<B, F>(self, f: F) -> (B, B)
       where Self: Sized,
             B: Default + Extend<Self::Item>,
             F: FnMut(&Self::Item) -> bool { ... }
    fn partition_in_place<'a, T, P>(self, predicate: P) -> usize
       where T: 'a,
             Self: Sized + DoubleEndedIterator<Item = &'a mut T>,
             P: FnMut(&T) -> bool { ... }
    fn is_partitioned<P>(self, predicate: P) -> bool
       where Self: Sized,
             P: FnMut(Self::Item) -> bool { ... }
    fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
       where Self: Sized,
             F: FnMut(B, Self::Item) -> R,
             R: Try<Output = B> { ... }
    fn try_for_each<F, R>(&mut self, f: F) -> R
       where Self: Sized,
             F: FnMut(Self::Item) -> R,
             R: Try<Output = ()> { ... }
    fn fold<B, F>(self, init: B, f: F) -> B
       where Self: Sized,
             F: FnMut(B, Self::Item) -> B { ... }
    fn reduce<F>(self, f: F) -> Option<Self::Item>
       where Self: Sized,
             F: FnMut(Self::Item, Self::Item) -> Self::Item { ... }
    fn try_reduce<F, R>(
        &mut self,
        f: F
    ) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryType
       where Self: Sized,
             F: FnMut(Self::Item, Self::Item) -> R,
             R: Try<Output = Self::Item>,
             <R as Try>::Residual: Residual<Option<Self::Item>> { ... }
    fn all<F>(&mut self, f: F) -> bool
       where Self: Sized,
             F: FnMut(Self::Item) -> bool { ... }
    fn any<F>(&mut self, f: F) -> bool
       where Self: Sized,
             F: FnMut(Self::Item) -> bool { ... }
    fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
       where Self: Sized,
             P: FnMut(&Self::Item) -> bool { ... }
    fn find_map<B, F>(&mut self, f: F) -> Option<B>
       where Self: Sized,
             F: FnMut(Self::Item) -> Option<B> { ... }
    fn try_find<F, R>(
        &mut self,
        f: F
    ) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryType
       where Self: Sized,
             F: FnMut(&Self::Item) -> R,
             R: Try<Output = bool>,
             <R as Try>::Residual: Residual<Option<Self::Item>> { ... }
    fn position<P>(&mut self, predicate: P) -> Option<usize>
       where Self: Sized,
             P: FnMut(Self::Item) -> bool { ... }
    fn rposition<P>(&mut self, predicate: P) -> Option<usize>
       where P: FnMut(Self::Item) -> bool,
             Self: Sized + ExactSizeIterator + DoubleEndedIterator { ... }
    fn max(self) -> Option<Self::Item>
       where Self: Sized,
             Self::Item: Ord { ... }
    fn min(self) -> Option<Self::Item>
       where Self: Sized,
             Self::Item: Ord { ... }
    fn max_by_key<B, F>(self, f: F) -> Option<Self::Item>
       where B: Ord,
             Self: Sized,
             F: FnMut(&Self::Item) -> B { ... }
    fn max_by<F>(self, compare: F) -> Option<Self::Item>
       where Self: Sized,
             F: FnMut(&Self::Item, &Self::Item) -> Ordering { ... }
    fn min_by_key<B, F>(self, f: F) -> Option<Self::Item>
       where B: Ord,
             Self: Sized,
             F: FnMut(&Self::Item) -> B { ... }
    fn min_by<F>(self, compare: F) -> Option<Self::Item>
       where Self: Sized,
             F: FnMut(&Self::Item, &Self::Item) -> Ordering { ... }
    fn rev(self) -> Rev<Self> ⓘ
       where Self: Sized + DoubleEndedIterator { ... }
    fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)
       where FromA: Default + Extend<A>,
             FromB: Default + Extend<B>,
             Self: Sized + Iterator<Item = (A, B)> { ... }
    fn copied<'a, T>(self) -> Copied<Self> ⓘ
       where T: 'a + Copy,
             Self: Sized + Iterator<Item = &'a T> { ... }
    fn cloned<'a, T>(self) -> Cloned<Self> ⓘ
       where T: 'a + Clone,
             Self: Sized + Iterator<Item = &'a T> { ... }
    fn cycle(self) -> Cycle<Self> ⓘ
       where Self: Sized + Clone { ... }
    fn array_chunks<const N: usize>(self) -> ArrayChunks<Self, N> ⓘ
       where Self: Sized { ... }
    fn sum<S>(self) -> S
       where Self: Sized,
             S: Sum<Self::Item> { ... }
    fn product<P>(self) -> P
       where Self: Sized,
             P: Product<Self::Item> { ... }
    fn cmp<I>(self, other: I) -> Ordering
       where I: IntoIterator<Item = Self::Item>,
             Self::Item: Ord,
             Self: Sized { ... }
    fn cmp_by<I, F>(self, other: I, cmp: F) -> Ordering
       where Self: Sized,
             I: IntoIterator,
             F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Ordering { ... }
    fn partial_cmp<I>(self, other: I) -> Option<Ordering>
       where I: IntoIterator,
             Self::Item: PartialOrd<<I as IntoIterator>::Item>,
             Self: Sized { ... }
    fn partial_cmp_by<I, F>(self, other: I, partial_cmp: F) -> Option<Ordering>
       where Self: Sized,
             I: IntoIterator,
             F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Option<Ordering> { ... }
    fn eq<I>(self, other: I) -> bool
       where I: IntoIterator,
             Self::Item: PartialEq<<I as IntoIterator>::Item>,
             Self: Sized { ... }
    fn eq_by<I, F>(self, other: I, eq: F) -> bool
       where Self: Sized,
             I: IntoIterator,
             F: FnMut(Self::Item, <I as IntoIterator>::Item) -> bool { ... }
    fn ne<I>(self, other: I) -> bool
       where I: IntoIterator,
             Self::Item: PartialEq<<I as IntoIterator>::Item>,
             Self: Sized { ... }
    fn lt<I>(self, other: I) -> bool
       where I: IntoIterator,
             Self::Item: PartialOrd<<I as IntoIterator>::Item>,
             Self: Sized { ... }
    fn le<I>(self, other: I) -> bool
       where I: IntoIterator,
             Self::Item: PartialOrd<<I as IntoIterator>::Item>,
             Self: Sized { ... }
    fn gt<I>(self, other: I) -> bool
       where I: IntoIterator,
             Self::Item: PartialOrd<<I as IntoIterator>::Item>,
             Self: Sized { ... }
    fn ge<I>(self, other: I) -> bool
       where I: IntoIterator,
             Self::Item: PartialOrd<<I as IntoIterator>::Item>,
             Self: Sized { ... }
    fn is_sorted(self) -> bool
       where Self: Sized,
             Self::Item: PartialOrd<Self::Item> { ... }
    fn is_sorted_by<F>(self, compare: F) -> bool
       where Self: Sized,
             F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering> { ... }
    fn is_sorted_by_key<F, K>(self, f: F) -> bool
       where Self: Sized,
             F: FnMut(Self::Item) -> K,
             K: PartialOrd<K> { ... }
}
```

A trait for dealing with iterators.

 This is the main iterator trait. For more about the concept of iterators generally, please see the [module-level documentation](index "mod std::iter"). In particular, you may want to know how to [implement `Iterator`](index#implementing-iterator "mod std::iter").

 Required Associated Types
-------------------------



[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#77)
```
type Item
```

The type of the elements being iterated over.

 

Required Methods
----------------



[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#111)
```
fn next(&mut self) -> Option<Self::Item>
```

Advances the iterator and returns the next value.

 Returns [`None`](../option/enum.option#variant.None "variant std::option::Option::None") when iteration is finished. Individual iterator implementations may choose to resume iteration, and so calling `next()` again may or may not eventually start returning [`Some(Item)`](../option/enum.option#variant.Some "variant std::option::Option::Some") again at some point.

 ##### Examples

 Basic usage:

 
```
let a = [1, 2, 3];

let mut iter = a.iter();

// A call to next() returns the next value...
assert_eq!(Some(&1), iter.next());
assert_eq!(Some(&2), iter.next());
assert_eq!(Some(&3), iter.next());

// ... and then None once it's over.
assert_eq!(None, iter.next());

// More calls may or may not return `None`. Here, they always will.
assert_eq!(None, iter.next());
assert_eq!(None, iter.next());
```
 

Provided Methods
----------------



[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#146-150)
```
fn next_chunk<const N: usize>(
    &mut self
) -> Result<[Self::Item; N], IntoIter<Self::Item, N>>
where
    Self: 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.

 If there are not enough elements to fill the array then `Err` is returned containing an iterator over the remaining elements.

 ##### Examples

 Basic usage:

 
```
#![feature(iter_next_chunk)]

let mut iter = "lorem".chars();

assert_eq!(iter.next_chunk().unwrap(), ['l', 'o']);              // N is inferred as 2
assert_eq!(iter.next_chunk().unwrap(), ['r', 'e', 'm']);         // N is inferred as 3
assert_eq!(iter.next_chunk::<4>().unwrap_err().as_slice(), &[]); // N is explicitly 4
```
 Split a string and get the first three items.

 
```
#![feature(iter_next_chunk)]

let quote = "not all those who wander are lost";
let [first, second, third] = quote.split_whitespace().next_chunk().unwrap();
assert_eq!(first, "not");
assert_eq!(second, "all");
assert_eq!(third, "those");
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#224)
```
fn size_hint(&self) -> (usize, Option<usize>)
```

Returns the bounds on the remaining length of the iterator.

 Specifically, `size_hint()` returns a tuple where the first element is the lower bound, and the second element is the upper bound.

 The second half of the tuple that is returned is an `[Option](../option/enum.option "enum std::option::Option")<[usize](../primitive.usize "primitive usize")>`. A [`None`](../option/enum.option#variant.None "variant std::option::Option::None") here means that either there is no known upper bound, or the upper bound is larger than [`usize`](../primitive.usize "primitive usize").

 ##### Implementation notes

 It is not enforced that an iterator implementation yields the declared number of elements. A buggy iterator may yield less than the lower bound or more than the upper bound of elements.

 `size_hint()` is primarily intended to be used for optimizations such as reserving space for the elements of the iterator, but must not be trusted to e.g., omit bounds checks in unsafe code. An incorrect implementation of `size_hint()` should not lead to memory safety violations.

 That said, the implementation should provide a correct estimation, because otherwise it would be a violation of the trait’s protocol.

 The default implementation returns `(0, [None](../option/enum.option#variant.None "variant std::option::Option::None"))` which is correct for any iterator.

 ##### Examples

 Basic usage:

 
```
let a = [1, 2, 3];
let mut iter = a.iter();

assert_eq!((3, Some(3)), iter.size_hint());
let _ = iter.next();
assert_eq!((2, Some(2)), iter.size_hint());
```
 A more complex example:

 
```
// The even numbers in the range of zero to nine.
let iter = (0..10).filter(|x| x % 2 == 0);

// We might iterate from zero to ten times. Knowing that it's five
// exactly wouldn't be possible without executing filter().
assert_eq!((0, Some(10)), iter.size_hint());

// Let's add five more numbers with chain()
let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);

// now both bounds are increased by five
assert_eq!((5, Some(15)), iter.size_hint());
```
 Returning `None` for an upper bound:

 
```
// an infinite iterator has no upper bound
// and the maximum possible lower bound
let iter = 0..;

assert_eq!((usize::MAX, None), iter.size_hint());
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#262-264)
```
fn count(self) -> usize
where
    Self: Sized,
```

Consumes the iterator, counting the number of iterations and returning it.

 This method will call [`next`](trait.iterator#tymethod.next "method std::iter::Iterator::next") repeatedly until [`None`](../option/enum.option#variant.None "variant std::option::Option::None") is encountered, returning the number of times it saw [`Some`](../option/enum.option#variant.Some "variant std::option::Option::Some"). Note that [`next`](trait.iterator#tymethod.next "method std::iter::Iterator::next") has to be called at least once even if the iterator does not have any elements.

 ##### Overflow Behavior

 The method does no guarding against overflows, so counting elements of an iterator with more than [`usize::MAX`](../primitive.usize#associatedconstant.MAX "associated constant usize::MAX") elements either produces the wrong result or panics. If debug assertions are enabled, a panic is guaranteed.

 ##### Panics

 This function might panic if the iterator has more than [`usize::MAX`](../primitive.usize#associatedconstant.MAX "associated constant usize::MAX") elements.

 ##### Examples

 Basic usage:

 
```
let a = [1, 2, 3];
assert_eq!(a.iter().count(), 3);

let a = [1, 2, 3, 4, 5];
assert_eq!(a.iter().count(), 5);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#293-295)
```
fn last(self) -> Option<Self::Item>
where
    Self: Sized,
```

Consumes the iterator, returning the last element.

 This method will evaluate the iterator until it returns [`None`](../option/enum.option#variant.None "variant std::option::Option::None"). While doing so, it keeps track of the current element. After [`None`](../option/enum.option#variant.None "variant std::option::Option::None") is returned, `last()` will then return the last element it saw.

 ##### Examples

 Basic usage:

 
```
let a = [1, 2, 3];
assert_eq!(a.iter().last(), Some(&3));

let a = [1, 2, 3, 4, 5];
assert_eq!(a.iter().last(), Some(&5));
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#342)
```
fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize>
```

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

 This method will eagerly skip `n` elements by calling [`next`](trait.iterator#tymethod.next "method std::iter::Iterator::next") up to `n` times until [`None`](../option/enum.option#variant.None "variant std::option::Option::None") is encountered.

 `advance_by(n)` will return `Ok(())` if the iterator successfully advances by `n` elements, or a `Err(NonZeroUsize)` with value `k` if [`None`](../option/enum.option#variant.None "variant std::option::Option::None") is encountered, where `k` is remaining number of steps that could not be advanced because the iterator ran out. If `self` is empty and `n` is non-zero, then this returns `Err(n)`. Otherwise, `k` is always less than `n`.

 Calling `advance_by(0)` can do meaningful work, for example [`Flatten`](struct.flatten "struct std::iter::Flatten") can advance its outer iterator until it finds an inner iterator that is not empty, which then often allows it to return a more accurate `size_hint()` than in its initial state.

 ##### Examples

 Basic usage:

 
```
#![feature(iter_advance_by)]

use std::num::NonZeroUsize;
let a = [1, 2, 3, 4];
let mut iter = a.iter();

assert_eq!(iter.advance_by(2), Ok(()));
assert_eq!(iter.next(), Some(&3));
assert_eq!(iter.advance_by(0), Ok(()));
assert_eq!(iter.advance_by(100), Err(NonZeroUsize::new(99).unwrap())); // only `&4` was skipped
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#394)
```
fn nth(&mut self, n: usize) -> Option<Self::Item>
```

Returns the `n`th element of the iterator.

 Like most indexing operations, the count starts from zero, so `nth(0)` returns the first value, `nth(1)` the second, and so on.

 Note that all preceding elements, as well as the returned element, will be consumed from the iterator. That means that the preceding elements will be discarded, and also that calling `nth(0)` multiple times on the same iterator will return different elements.

 `nth()` will return [`None`](../option/enum.option#variant.None "variant std::option::Option::None") if `n` is greater than or equal to the length of the iterator.

 ##### Examples

 Basic usage:

 
```
let a = [1, 2, 3];
assert_eq!(a.iter().nth(1), Some(&2));
```
 Calling `nth()` multiple times doesn’t rewind the iterator:

 
```
let a = [1, 2, 3];

let mut iter = a.iter();

assert_eq!(iter.nth(1), Some(&2));
assert_eq!(iter.nth(1), None);
```
 Returning `None` if there are less than `n + 1` elements:

 
```
let a = [1, 2, 3];
assert_eq!(a.iter().nth(10), None);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#447-449)1.28.0
```
fn step_by(self, step: usize) -> StepBy<Self> ⓘ
where
    Self: Sized,
```

Creates an iterator starting at the same point, but stepping by the given amount at each iteration.

 Note 1: The first element of the iterator will always be returned, regardless of the step given.

 Note 2: The time at which ignored elements are pulled is not fixed. `StepBy` behaves like the sequence `self.next()`, `self.nth(step-1)`, `self.nth(step-1)`, …, but is also free to behave like the sequence `advance_n_and_return_first(&mut self, step)`, `advance_n_and_return_first(&mut self, step)`, … Which way is used may change for some iterators for performance reasons. The second way will advance the iterator earlier and may consume more items.

 `advance_n_and_return_first` is the equivalent of:

 
```
fn advance_n_and_return_first<I>(iter: &mut I, n: usize) -> Option<I::Item>
where
    I: Iterator,
{
    let next = iter.next();
    if n > 1 {
        iter.nth(n - 2);
    }
    next
}
```
 ##### Panics

 The method will panic if the given step is `0`.

 ##### Examples

 Basic usage:

 
```
let a = [0, 1, 2, 3, 4, 5];
let mut iter = a.iter().step_by(2);

assert_eq!(iter.next(), Some(&0));
assert_eq!(iter.next(), Some(&2));
assert_eq!(iter.next(), Some(&4));
assert_eq!(iter.next(), None);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#519-522)
```
fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter> ⓘ
where
    Self: Sized,
    U: IntoIterator<Item = Self::Item>,
```

Takes two iterators and creates a new iterator over both in sequence.

 `chain()` will return a new iterator which will first iterate over values from the first iterator and then over values from the second iterator.

 In other words, it links two iterators together, in a chain. 🔗

 [`once`](fn.once "fn std::iter::once") is commonly used to adapt a single value into a chain of other kinds of iteration.

 ##### Examples

 Basic usage:

 
```
let a1 = [1, 2, 3];
let a2 = [4, 5, 6];

let mut iter = a1.iter().chain(a2.iter());

assert_eq!(iter.next(), Some(&1));
assert_eq!(iter.next(), Some(&2));
assert_eq!(iter.next(), Some(&3));
assert_eq!(iter.next(), Some(&4));
assert_eq!(iter.next(), Some(&5));
assert_eq!(iter.next(), Some(&6));
assert_eq!(iter.next(), None);
```
 Since the argument to `chain()` uses [`IntoIterator`](trait.intoiterator "trait std::iter::IntoIterator"), we can pass anything that can be converted into an [`Iterator`](trait.iterator "trait std::iter::Iterator"), not just an [`Iterator`](trait.iterator "trait std::iter::Iterator") itself. For example, slices (`&[T]`) implement [`IntoIterator`](trait.intoiterator "trait std::iter::IntoIterator"), and so can be passed to `chain()` directly:

 
```
let s1 = &[1, 2, 3];
let s2 = &[4, 5, 6];

let mut iter = s1.iter().chain(s2);

assert_eq!(iter.next(), Some(&1));
assert_eq!(iter.next(), Some(&2));
assert_eq!(iter.next(), Some(&3));
assert_eq!(iter.next(), Some(&4));
assert_eq!(iter.next(), Some(&5));
assert_eq!(iter.next(), Some(&6));
assert_eq!(iter.next(), None);
```
 If you work with Windows API, you may wish to convert [`OsStr`](../ffi/struct.osstr) to `Vec<u16>`:

 
```
#[cfg(windows)]
fn os_str_to_utf16(s: &std::ffi::OsStr) -> Vec<u16> {
    use std::os::windows::ffi::OsStrExt;
    s.encode_wide().chain(std::iter::once(0)).collect()
}
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#638-641)
```
fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter> ⓘ
where
    Self: Sized,
    U: IntoIterator,
```

‘Zips up’ two iterators into a single iterator of pairs.

 `zip()` returns a new iterator that will iterate over two other iterators, returning a tuple where the first element comes from the first iterator, and the second element comes from the second iterator.

 In other words, it zips two iterators together, into a single one.

 If either iterator returns [`None`](../option/enum.option#variant.None "variant std::option::Option::None"), [`next`](trait.iterator#tymethod.next "method std::iter::Iterator::next") from the zipped iterator will return [`None`](../option/enum.option#variant.None "variant std::option::Option::None"). If the zipped iterator has no more elements to return then each further attempt to advance it will first try to advance the first iterator at most one time and if it still yielded an item try to advance the second iterator at most one time.

 To ‘undo’ the result of zipping up two iterators, see [`unzip`](trait.iterator#method.unzip "method std::iter::Iterator::unzip").

 ##### Examples

 Basic usage:

 
```
let a1 = [1, 2, 3];
let a2 = [4, 5, 6];

let mut iter = a1.iter().zip(a2.iter());

assert_eq!(iter.next(), Some((&1, &4)));
assert_eq!(iter.next(), Some((&2, &5)));
assert_eq!(iter.next(), Some((&3, &6)));
assert_eq!(iter.next(), None);
```
 Since the argument to `zip()` uses [`IntoIterator`](trait.intoiterator "trait std::iter::IntoIterator"), we can pass anything that can be converted into an [`Iterator`](trait.iterator "trait std::iter::Iterator"), not just an [`Iterator`](trait.iterator "trait std::iter::Iterator") itself. For example, slices (`&[T]`) implement [`IntoIterator`](trait.intoiterator "trait std::iter::IntoIterator"), and so can be passed to `zip()` directly:

 
```
let s1 = &[1, 2, 3];
let s2 = &[4, 5, 6];

let mut iter = s1.iter().zip(s2);

assert_eq!(iter.next(), Some((&1, &4)));
assert_eq!(iter.next(), Some((&2, &5)));
assert_eq!(iter.next(), Some((&3, &6)));
assert_eq!(iter.next(), None);
```
 `zip()` is often used to zip an infinite iterator to a finite one. This works because the finite iterator will eventually return [`None`](../option/enum.option#variant.None "variant std::option::Option::None"), ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`](trait.iterator#method.enumerate "method std::iter::Iterator::enumerate"):

 
```
let enumerate: Vec<_> = "foo".chars().enumerate().collect();

let zipper: Vec<_> = (0..).zip("foo".chars()).collect();

assert_eq!((0, 'f'), enumerate[0]);
assert_eq!((0, 'f'), zipper[0]);

assert_eq!((1, 'o'), enumerate[1]);
assert_eq!((1, 'o'), zipper[1]);

assert_eq!((2, 'o'), enumerate[2]);
assert_eq!((2, 'o'), zipper[2]);
```
 If both iterators have roughly equivalent syntax, it may be more readable to use [`zip`](fn.zip "fn std::iter::zip"):

 
```
use std::iter::zip;

let a = [1, 2, 3];
let b = [2, 3, 4];

let mut zipped = zip(
    a.into_iter().map(|x| x * 2).skip(1),
    b.into_iter().map(|x| x * 2).skip(1),
);

assert_eq!(zipped.next(), Some((4, 6)));
assert_eq!(zipped.next(), Some((6, 8)));
assert_eq!(zipped.next(), None);
```
 compared to:

 
```
let mut zipped = a
    .into_iter()
    .map(|x| x * 2)
    .skip(1)
    .zip(b.into_iter().map(|x| x * 2).skip(1));
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#681-684)
```
fn intersperse(self, separator: Self::Item) -> Intersperse<Self> ⓘ
where
    Self: Sized,
    Self::Item: 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.

 In case `separator` does not implement [`Clone`](../clone/trait.clone "trait std::clone::Clone") or needs to be computed every time, use [`intersperse_with`](trait.iterator#method.intersperse_with "method std::iter::Iterator::intersperse_with").

 ##### Examples

 Basic usage:

 
```
#![feature(iter_intersperse)]

let mut a = [0, 1, 2].iter().intersperse(&100);
assert_eq!(a.next(), Some(&0));   // The first element from `a`.
assert_eq!(a.next(), Some(&100)); // The separator.
assert_eq!(a.next(), Some(&1));   // The next element from `a`.
assert_eq!(a.next(), Some(&100)); // The separator.
assert_eq!(a.next(), Some(&2));   // The last element from `a`.
assert_eq!(a.next(), None);       // The iterator is finished.
```
 `intersperse` can be very useful to join an iterator’s items using a common element:

 
```
#![feature(iter_intersperse)]

let hello = ["Hello", "World", "!"].iter().copied().intersperse(" ").collect::<String>();
assert_eq!(hello, "Hello World !");
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#740-743)
```
fn intersperse_with<G>(self, separator: G) -> IntersperseWith<Self, G> ⓘ
where
    Self: Sized,
    G: FnMut() -> Self::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.

 The closure will be called exactly once each time an item is placed between two adjacent items from the underlying iterator; specifically, the closure is not called if the underlying iterator yields less than two items and after the last item is yielded.

 If the iterator’s item implements [`Clone`](../clone/trait.clone "trait std::clone::Clone"), it may be easier to use [`intersperse`](trait.iterator#method.intersperse "method std::iter::Iterator::intersperse").

 ##### Examples

 Basic usage:

 
```
#![feature(iter_intersperse)]

#[derive(PartialEq, Debug)]
struct NotClone(usize);

let v = [NotClone(0), NotClone(1), NotClone(2)];
let mut it = v.into_iter().intersperse_with(|| NotClone(99));

assert_eq!(it.next(), Some(NotClone(0)));  // The first element from `v`.
assert_eq!(it.next(), Some(NotClone(99))); // The separator.
assert_eq!(it.next(), Some(NotClone(1)));  // The next element from `v`.
assert_eq!(it.next(), Some(NotClone(99))); // The separator.
assert_eq!(it.next(), Some(NotClone(2)));  // The last element from `v`.
assert_eq!(it.next(), None);               // The iterator is finished.
```
 `intersperse_with` can be used in situations where the separator needs to be computed:

 
```
#![feature(iter_intersperse)]

let src = ["Hello", "to", "all", "people", "!!"].iter().copied();

// The closure mutably borrows its context to generate an item.
let mut happy_emojis = [" ❤️ ", " 😀 "].iter().copied();
let separator = || happy_emojis.next().unwrap_or(" 🦀 ");

let result = src.intersperse_with(separator).collect::<String>();
assert_eq!(result, "Hello ❤️ to 😀 all 🦀 people 🦀 !!");
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#800-803)
```
fn map<B, F>(self, f: F) -> Map<Self, F> ⓘ
where
    Self: Sized,
    F: FnMut(Self::Item) -> B,
```

Takes a closure and creates an iterator which calls that closure on each element.

 `map()` transforms one iterator into another, by means of its argument: something that implements [`FnMut`](../ops/trait.fnmut "trait std::ops::FnMut"). It produces a new iterator which calls this closure on each element of the original iterator.

 If you are good at thinking in types, you can think of `map()` like this: If you have an iterator that gives you elements of some type `A`, and you want an iterator of some other type `B`, you can use `map()`, passing a closure that takes an `A` and returns a `B`.

 `map()` is conceptually similar to a [`for`](../../book/ch03-05-control-flow#looping-through-a-collection-with-for) loop. However, as `map()` is lazy, it is best used when you’re already working with other iterators. If you’re doing some sort of looping for a side effect, it’s considered more idiomatic to use [`for`](../../book/ch03-05-control-flow#looping-through-a-collection-with-for) than `map()`.

 ##### Examples

 Basic usage:

 
```
let a = [1, 2, 3];

let mut iter = a.iter().map(|x| 2 * x);

assert_eq!(iter.next(), Some(2));
assert_eq!(iter.next(), Some(4));
assert_eq!(iter.next(), Some(6));
assert_eq!(iter.next(), None);
```
 If you’re doing some sort of side effect, prefer [`for`](../../book/ch03-05-control-flow#looping-through-a-collection-with-for) to `map()`:

 
```
// don't do this:
(0..5).map(|x| println!("{x}"));

// it won't even execute, as it is lazy. Rust will warn you about this.

// Instead, use for:
for x in 0..5 {
    println!("{x}");
}
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#846-849)1.21.0
```
fn for_each<F>(self, f: F)
where
    Self: Sized,
    F: FnMut(Self::Item),
```

Calls a closure on each element of an iterator.

 This is equivalent to using a [`for`](../../book/ch03-05-control-flow#looping-through-a-collection-with-for) loop on the iterator, although `break` and `continue` are not possible from a closure. It’s generally more idiomatic to use a `for` loop, but `for_each` may be more legible when processing items at the end of longer iterator chains. In some cases `for_each` may also be faster than a loop, because it will use internal iteration on adapters like `Chain`.

 ##### Examples

 Basic usage:

 
```
use std::sync::mpsc::channel;

let (tx, rx) = channel();
(0..5).map(|x| x * 2 + 1)
      .for_each(move |x| tx.send(x).unwrap());

let v: Vec<_> = rx.iter().collect();
assert_eq!(v, vec![1, 3, 5, 7, 9]);
```
 For such a small example, a `for` loop may be cleaner, but `for_each` might be preferable to keep a functional style with longer iterators:

 
```
(0..5).flat_map(|x| x * 100 .. x * 110)
      .enumerate()
      .filter(|&(i, x)| (i + x) % 3 == 0)
      .for_each(|(i, x)| println!("{i}:{x}"));
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#922-925)
```
fn filter<P>(self, predicate: P) -> Filter<Self, P> ⓘ
where
    Self: Sized,
    P: FnMut(&Self::Item) -> bool,
```

Creates an iterator which uses a closure to determine if an element should be yielded.

 Given an element the closure must return `true` or `false`. The returned iterator will yield only the elements for which the closure returns true.

 ##### Examples

 Basic usage:

 
```
let a = [0i32, 1, 2];

let mut iter = a.iter().filter(|x| x.is_positive());

assert_eq!(iter.next(), Some(&1));
assert_eq!(iter.next(), Some(&2));
assert_eq!(iter.next(), None);
```
 Because the closure passed to `filter()` takes a reference, and many iterators iterate over references, this leads to a possibly confusing situation, where the type of the closure is a double reference:

 
```
let a = [0, 1, 2];

let mut iter = a.iter().filter(|x| **x > 1); // need two *s!

assert_eq!(iter.next(), Some(&2));
assert_eq!(iter.next(), None);
```
 It’s common to instead use destructuring on the argument to strip away one:

 
```
let a = [0, 1, 2];

let mut iter = a.iter().filter(|&x| *x > 1); // both & and *

assert_eq!(iter.next(), Some(&2));
assert_eq!(iter.next(), None);
```
 or both:

 
```
let a = [0, 1, 2];

let mut iter = a.iter().filter(|&&x| x > 1); // two &s

assert_eq!(iter.next(), Some(&2));
assert_eq!(iter.next(), None);
```
 of these layers.

 Note that `iter.filter(f).next()` is equivalent to `iter.find(f)`.

 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#968-971)
```
fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> ⓘ
where
    Self: Sized,
    F: FnMut(Self::Item) -> Option<B>,
```

Creates an iterator that both filters and maps.

 The returned iterator yields only the `value`s for which the supplied closure returns `Some(value)`.

 `filter_map` can be used to make chains of [`filter`](trait.iterator#method.filter "method std::iter::Iterator::filter") and [`map`](trait.iterator#method.map "method std::iter::Iterator::map") more concise. The example below shows how a `map().filter().map()` can be shortened to a single call to `filter_map`.

 ##### Examples

 Basic usage:

 
```
let a = ["1", "two", "NaN", "four", "5"];

let mut iter = a.iter().filter_map(|s| s.parse().ok());

assert_eq!(iter.next(), Some(1));
assert_eq!(iter.next(), Some(5));
assert_eq!(iter.next(), None);
```
 Here’s the same example, but with [`filter`](trait.iterator#method.filter "method std::iter::Iterator::filter") and [`map`](trait.iterator#method.map "method std::iter::Iterator::map"):

 
```
let a = ["1", "two", "NaN", "four", "5"];
let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());
assert_eq!(iter.next(), Some(1));
assert_eq!(iter.next(), Some(5));
assert_eq!(iter.next(), None);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1015-1017)
```
fn enumerate(self) -> Enumerate<Self> ⓘ
where
    Self: Sized,
```

Creates an iterator which gives the current iteration count as well as the next value.

 The iterator returned yields pairs `(i, val)`, where `i` is the current index of iteration and `val` is the value returned by the iterator.

 `enumerate()` keeps its count as a [`usize`](../primitive.usize "primitive usize"). If you want to count by a different sized integer, the [`zip`](trait.iterator#method.zip "method std::iter::Iterator::zip") function provides similar functionality.

 ##### Overflow Behavior

 The method does no guarding against overflows, so enumerating more than [`usize::MAX`](../primitive.usize#associatedconstant.MAX "associated constant usize::MAX") elements either produces the wrong result or panics. If debug assertions are enabled, a panic is guaranteed.

 ##### Panics

 The returned iterator might panic if the to-be-returned index would overflow a [`usize`](../primitive.usize "primitive usize").

 ##### Examples

 
```
let a = ['a', 'b', 'c'];

let mut iter = a.iter().enumerate();

assert_eq!(iter.next(), Some((0, &'a')));
assert_eq!(iter.next(), Some((1, &'b')));
assert_eq!(iter.next(), Some((2, &'c')));
assert_eq!(iter.next(), None);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1087-1089)
```
fn peekable(self) -> Peekable<Self> ⓘ
where
    Self: Sized,
```

Creates an iterator which can use the [`peek`](struct.peekable#method.peek "method std::iter::Peekable::peek") and [`peek_mut`](struct.peekable#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.

 Note that the underlying iterator is still advanced when [`peek`](struct.peekable#method.peek "method std::iter::Peekable::peek") or [`peek_mut`](struct.peekable#method.peek_mut "method std::iter::Peekable::peek_mut") are called for the first time: In order to retrieve the next element, [`next`](trait.iterator#tymethod.next "method std::iter::Iterator::next") is called on the underlying iterator, hence any side effects (i.e. anything other than fetching the next value) of the [`next`](trait.iterator#tymethod.next "method std::iter::Iterator::next") method will occur.

 ##### Examples

 Basic usage:

 
```
let xs = [1, 2, 3];

let mut iter = xs.iter().peekable();

// peek() lets us see into the future
assert_eq!(iter.peek(), Some(&&1));
assert_eq!(iter.next(), Some(&1));

assert_eq!(iter.next(), Some(&2));

// we can peek() multiple times, the iterator won't advance
assert_eq!(iter.peek(), Some(&&3));
assert_eq!(iter.peek(), Some(&&3));

assert_eq!(iter.next(), Some(&3));

// after the iterator is finished, so is peek()
assert_eq!(iter.peek(), None);
assert_eq!(iter.next(), None);
```
 Using [`peek_mut`](struct.peekable#method.peek_mut "method std::iter::Peekable::peek_mut") to mutate the next item without advancing the iterator:

 
```
let xs = [1, 2, 3];

let mut iter = xs.iter().peekable();

// `peek_mut()` lets us see into the future
assert_eq!(iter.peek_mut(), Some(&mut &1));
assert_eq!(iter.peek_mut(), Some(&mut &1));
assert_eq!(iter.next(), Some(&1));

if let Some(mut p) = iter.peek_mut() {
    assert_eq!(*p, &2);
    // put a value into the iterator
    *p = &1000;
}

// The value reappears as the iterator continues
assert_eq!(iter.collect::<Vec<_>>(), vec![&1000, &3]);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1153-1156)
```
fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> ⓘ
where
    Self: Sized,
    P: FnMut(&Self::Item) -> bool,
```

Creates an iterator that [`skip`](trait.iterator#method.skip "method std::iter::Iterator::skip")s elements based on a predicate.

 `skip_while()` takes a closure as an argument. It will call this closure on each element of the iterator, and ignore elements until it returns `false`.

 After `false` is returned, `skip_while()`’s job is over, and the rest of the elements are yielded.

 ##### Examples

 Basic usage:

 
```
let a = [-1i32, 0, 1];

let mut iter = a.iter().skip_while(|x| x.is_negative());

assert_eq!(iter.next(), Some(&0));
assert_eq!(iter.next(), Some(&1));
assert_eq!(iter.next(), None);
```
 Because the closure passed to `skip_while()` takes a reference, and many iterators iterate over references, this leads to a possibly confusing situation, where the type of the closure argument is a double reference:

 
```
let a = [-1, 0, 1];

let mut iter = a.iter().skip_while(|x| **x < 0); // need two *s!

assert_eq!(iter.next(), Some(&0));
assert_eq!(iter.next(), Some(&1));
assert_eq!(iter.next(), None);
```
 Stopping after an initial `false`:

 
```
let a = [-1, 0, 1, -2];

let mut iter = a.iter().skip_while(|x| **x < 0);

assert_eq!(iter.next(), Some(&0));
assert_eq!(iter.next(), Some(&1));

// while this would have been false, since we already got a false,
// skip_while() isn't used any more
assert_eq!(iter.next(), Some(&-2));

assert_eq!(iter.next(), None);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1235-1238)
```
fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> ⓘ
where
    Self: Sized,
    P: FnMut(&Self::Item) -> bool,
```

Creates an iterator that yields elements based on a predicate.

 `take_while()` takes a closure as an argument. It will call this closure on each element of the iterator, and yield elements while it returns `true`.

 After `false` is returned, `take_while()`’s job is over, and the rest of the elements are ignored.

 ##### Examples

 Basic usage:

 
```
let a = [-1i32, 0, 1];

let mut iter = a.iter().take_while(|x| x.is_negative());

assert_eq!(iter.next(), Some(&-1));
assert_eq!(iter.next(), None);
```
 Because the closure passed to `take_while()` takes a reference, and many iterators iterate over references, this leads to a possibly confusing situation, where the type of the closure is a double reference:

 
```
let a = [-1, 0, 1];

let mut iter = a.iter().take_while(|x| **x < 0); // need two *s!

assert_eq!(iter.next(), Some(&-1));
assert_eq!(iter.next(), None);
```
 Stopping after an initial `false`:

 
```
let a = [-1, 0, 1, -2];

let mut iter = a.iter().take_while(|x| **x < 0);

assert_eq!(iter.next(), Some(&-1));

// We have more elements that are less than zero, but since we already
// got a false, take_while() isn't used any more
assert_eq!(iter.next(), None);
```
 Because `take_while()` needs to look at the value in order to see if it should be included or not, consuming iterators will see that it is removed:

 
```
let a = [1, 2, 3, 4];
let mut iter = a.iter();

let result: Vec<i32> = iter.by_ref()
                           .take_while(|n| **n != 3)
                           .cloned()
                           .collect();

assert_eq!(result, &[1, 2]);

let result: Vec<i32> = iter.cloned().collect();

assert_eq!(result, &[4]);
```
 The `3` is no longer there, because it was consumed in order to see if the iteration should stop, but wasn’t placed back into the iterator.

 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1324-1327)1.57.0
```
fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P> ⓘ
where
    Self: Sized,
    P: FnMut(Self::Item) -> Option<B>,
```

Creates an iterator that both yields elements based on a predicate and maps.

 `map_while()` takes a closure as an argument. It will call this closure on each element of the iterator, and yield elements while it returns [`Some(_)`](../option/enum.option#variant.Some "variant std::option::Option::Some").

 ##### Examples

 Basic usage:

 
```
let a = [-1i32, 4, 0, 1];

let mut iter = a.iter().map_while(|x| 16i32.checked_div(*x));

assert_eq!(iter.next(), Some(-16));
assert_eq!(iter.next(), Some(4));
assert_eq!(iter.next(), None);
```
 Here’s the same example, but with [`take_while`](trait.iterator#method.take_while "method std::iter::Iterator::take_while") and [`map`](trait.iterator#method.map "method std::iter::Iterator::map"):

 
```
let a = [-1i32, 4, 0, 1];

let mut iter = a.iter()
                .map(|x| 16i32.checked_div(*x))
                .take_while(|x| x.is_some())
                .map(|x| x.unwrap());

assert_eq!(iter.next(), Some(-16));
assert_eq!(iter.next(), Some(4));
assert_eq!(iter.next(), None);
```
 Stopping after an initial [`None`](../option/enum.option#variant.None "variant std::option::Option::None"):

 
```
let a = [0, 1, 2, -3, 4, 5, -6];

let iter = a.iter().map_while(|x| u32::try_from(*x).ok());
let vec = iter.collect::<Vec<_>>();

// We have more elements which could fit in u32 (4, 5), but `map_while` returned `None` for `-3`
// (as the `predicate` returned `None`) and `collect` stops at the first `None` encountered.
assert_eq!(vec, vec![0, 1, 2]);
```
 Because `map_while()` needs to look at the value in order to see if it should be included or not, consuming iterators will see that it is removed:

 
```
let a = [1, 2, -3, 4];
let mut iter = a.iter();

let result: Vec<u32> = iter.by_ref()
                           .map_while(|n| u32::try_from(*n).ok())
                           .collect();

assert_eq!(result, &[1, 2]);

let result: Vec<i32> = iter.cloned().collect();

assert_eq!(result, &[4]);
```
 The `-3` is no longer there, because it was consumed in order to see if the iteration should stop, but wasn’t placed back into the iterator.

 Note that unlike [`take_while`](trait.iterator#method.take_while "method std::iter::Iterator::take_while") this iterator is **not** fused. It is also not specified what this iterator returns after the first [`None`](../option/enum.option#variant.None "variant std::option::Option::None") is returned. If you need fused iterator, use [`fuse`](trait.iterator#method.fuse "method std::iter::Iterator::fuse").

 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1356-1358)
```
fn skip(self, n: usize) -> Skip<Self> ⓘ
where
    Self: Sized,
```

Creates an iterator that skips the first `n` elements.

 `skip(n)` skips elements until `n` elements are skipped or the end of the iterator is reached (whichever happens first). After that, all the remaining elements are yielded. In particular, if the original iterator is too short, then the returned iterator is empty.

 Rather than overriding this method directly, instead override the `nth` method.

 ##### Examples

 Basic usage:

 
```
let a = [1, 2, 3];

let mut iter = a.iter().skip(2);

assert_eq!(iter.next(), Some(&3));
assert_eq!(iter.next(), None);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1410-1412)
```
fn take(self, n: usize) -> Take<Self> ⓘ
where
    Self: Sized,
```

Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner.

 `take(n)` yields elements until `n` elements are yielded or the end of the iterator is reached (whichever happens first). The returned iterator is a prefix of length `n` if the original iterator contains at least `n` elements, otherwise it contains all of the (fewer than `n`) elements of the original iterator.

 ##### Examples

 Basic usage:

 
```
let a = [1, 2, 3];

let mut iter = a.iter().take(2);

assert_eq!(iter.next(), Some(&1));
assert_eq!(iter.next(), Some(&2));
assert_eq!(iter.next(), None);
```
 `take()` is often used with an infinite iterator, to make it finite:

 
```
let mut iter = (0..).take(3);

assert_eq!(iter.next(), Some(0));
assert_eq!(iter.next(), Some(1));
assert_eq!(iter.next(), Some(2));
assert_eq!(iter.next(), None);
```
 If less than `n` elements are available, `take` will limit itself to the size of the underlying iterator:

 
```
let v = [1, 2];
let mut iter = v.into_iter().take(5);
assert_eq!(iter.next(), Some(1));
assert_eq!(iter.next(), Some(2));
assert_eq!(iter.next(), None);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1460-1463)
```
fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F> ⓘ
where
    Self: Sized,
    F: FnMut(&mut St, Self::Item) -> Option<B>,
```

An iterator adapter which, like [`fold`](trait.iterator#method.fold "method std::iter::Iterator::fold"), holds internal state, but unlike [`fold`](trait.iterator#method.fold "method std::iter::Iterator::fold"), produces a new iterator.

 `scan()` takes two arguments: an initial value which seeds the internal state, and a closure with two arguments, the first being a mutable reference to the internal state and the second an iterator element. The closure can assign to the internal state to share state between iterations.

 On iteration, the closure will be applied to each element of the iterator and the return value from the closure, an [`Option`](../option/enum.option "enum std::option::Option"), is returned by the `next` method. Thus the closure can return `Some(value)` to yield `value`, or `None` to end the iteration.

 ##### Examples

 Basic usage:

 
```
let a = [1, 2, 3, 4];

let mut iter = a.iter().scan(1, |state, &x| {
    // each iteration, we'll multiply the state by the element ...
    *state = *state * x;

    // ... and terminate if the state exceeds 6
    if *state > 6 {
        return None;
    }
    // ... else yield the negation of the state
    Some(-*state)
});

assert_eq!(iter.next(), Some(-1));
assert_eq!(iter.next(), Some(-2));
assert_eq!(iter.next(), Some(-6));
assert_eq!(iter.next(), None);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1501-1505)
```
fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F> ⓘ
where
    Self: Sized,
    U: IntoIterator,
    F: FnMut(Self::Item) -> U,
```

Creates an iterator that works like map, but flattens nested structure.

 The [`map`](trait.iterator#method.map "method std::iter::Iterator::map") adapter is very useful, but only when the closure argument produces values. If it produces an iterator instead, there’s an extra layer of indirection. `flat_map()` will remove this extra layer on its own.

 You can think of `flat_map(f)` as the semantic equivalent of [`map`](trait.iterator#method.map "method std::iter::Iterator::map")ping, and then [`flatten`](trait.iterator#method.flatten "method std::iter::Iterator::flatten")ing as in `map(f).flatten()`.

 Another way of thinking about `flat_map()`: [`map`](trait.iterator#method.map "method std::iter::Iterator::map")’s closure returns one item for each element, and `flat_map()`’s closure returns an iterator for each element.

 ##### Examples

 Basic usage:

 
```
let words = ["alpha", "beta", "gamma"];

// chars() returns an iterator
let merged: String = words.iter()
                          .flat_map(|s| s.chars())
                          .collect();
assert_eq!(merged, "alphabetagamma");
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1586-1589)1.29.0
```
fn flatten(self) -> Flatten<Self> ⓘ
where
    Self: Sized,
    Self::Item: IntoIterator,
```

Creates an iterator that flattens nested structure.

 This is useful when you have an iterator of iterators or an iterator of things that can be turned into iterators and you want to remove one level of indirection.

 ##### Examples

 Basic usage:

 
```
let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
let flattened = data.into_iter().flatten().collect::<Vec<u8>>();
assert_eq!(flattened, &[1, 2, 3, 4, 5, 6]);
```
 Mapping and then flattening:

 
```
let words = ["alpha", "beta", "gamma"];

// chars() returns an iterator
let merged: String = words.iter()
                          .map(|s| s.chars())
                          .flatten()
                          .collect();
assert_eq!(merged, "alphabetagamma");
```
 You can also rewrite this in terms of [`flat_map()`](trait.iterator#method.flat_map "method std::iter::Iterator::flat_map"), which is preferable in this case since it conveys intent more clearly:

 
```
let words = ["alpha", "beta", "gamma"];

// chars() returns an iterator
let merged: String = words.iter()
                          .flat_map(|s| s.chars())
                          .collect();
assert_eq!(merged, "alphabetagamma");
```
 Flattening works on any `IntoIterator` type, including `Option` and `Result`:

 
```
let options = vec![Some(123), Some(321), None, Some(231)];
let flattened_options: Vec<_> = options.into_iter().flatten().collect();
assert_eq!(flattened_options, vec![123, 321, 231]);

let results = vec![Ok(123), Ok(321), Err(456), Ok(231)];
let flattened_results: Vec<_> = results.into_iter().flatten().collect();
assert_eq!(flattened_results, vec![123, 321, 231]);
```
 Flattening only removes one level of nesting at a time:

 
```
let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];

let d2 = d3.iter().flatten().collect::<Vec<_>>();
assert_eq!(d2, [&[1, 2], &[3, 4], &[5, 6], &[7, 8]]);

let d1 = d3.iter().flatten().flatten().collect::<Vec<_>>();
assert_eq!(d1, [&1, &2, &3, &4, &5, &6, &7, &8]);
```
 Here we see that `flatten()` does not perform a “deep” flatten. Instead, only one level of nesting is removed. That is, if you `flatten()` a three-dimensional array, the result will be two-dimensional and not one-dimensional. To get a one-dimensional structure, you have to `flatten()` again.

 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1655-1657)
```
fn fuse(self) -> Fuse<Self> ⓘ
where
    Self: Sized,
```

Creates an iterator which ends after the first [`None`](../option/enum.option#variant.None "variant std::option::Option::None").

 After an iterator returns [`None`](../option/enum.option#variant.None "variant std::option::Option::None"), future calls may or may not yield [`Some(T)`](../option/enum.option#variant.Some "variant std::option::Option::Some") again. `fuse()` adapts an iterator, ensuring that after a [`None`](../option/enum.option#variant.None "variant std::option::Option::None") is given, it will always return [`None`](../option/enum.option#variant.None "variant std::option::Option::None") forever.

 Note that the [`Fuse`](struct.fuse "struct std::iter::Fuse") wrapper is a no-op on iterators that implement the [`FusedIterator`](trait.fusediterator "trait std::iter::FusedIterator") trait. `fuse()` may therefore behave incorrectly if the [`FusedIterator`](trait.fusediterator "trait std::iter::FusedIterator") trait is improperly implemented.

 ##### Examples

 Basic usage:

 
```
// an iterator which alternates between Some and None
struct Alternate {
    state: i32,
}

impl Iterator for Alternate {
    type Item = i32;

    fn next(&mut self) -> Option<i32> {
        let val = self.state;
        self.state = self.state + 1;

        // if it's even, Some(i32), else None
        if val % 2 == 0 {
            Some(val)
        } else {
            None
        }
    }
}

let mut iter = Alternate { state: 0 };

// we can see our iterator going back and forth
assert_eq!(iter.next(), Some(0));
assert_eq!(iter.next(), None);
assert_eq!(iter.next(), Some(2));
assert_eq!(iter.next(), None);

// however, once we fuse it...
let mut iter = iter.fuse();

assert_eq!(iter.next(), Some(4));
assert_eq!(iter.next(), None);

// it will always return `None` after the first time.
assert_eq!(iter.next(), None);
assert_eq!(iter.next(), None);
assert_eq!(iter.next(), None);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1740-1743)
```
fn inspect<F>(self, f: F) -> Inspect<Self, F> ⓘ
where
    Self: Sized,
    F: FnMut(&Self::Item),
```

Does something with each element of an iterator, passing the value on.

 When using iterators, you’ll often chain several of them together. While working on such code, you might want to check out what’s happening at various parts in the pipeline. To do that, insert a call to `inspect()`.

 It’s more common for `inspect()` to be used as a debugging tool than to exist in your final code, but applications may find it useful in certain situations when errors need to be logged before being discarded.

 ##### Examples

 Basic usage:

 
```
let a = [1, 4, 2, 3];

// this iterator sequence is complex.
let sum = a.iter()
    .cloned()
    .filter(|x| x % 2 == 0)
    .fold(0, |sum, i| sum + i);

println!("{sum}");

// let's add some inspect() calls to investigate what's happening
let sum = a.iter()
    .cloned()
    .inspect(|x| println!("about to filter: {x}"))
    .filter(|x| x % 2 == 0)
    .inspect(|x| println!("made it through filter: {x}"))
    .fold(0, |sum, i| sum + i);

println!("{sum}");
```
 This will print:

 
```
6
about to filter: 1
about to filter: 4
made it through filter: 4
about to filter: 2
made it through filter: 2
about to filter: 3
6

```
 Logging errors before discarding them:

 
```
let lines = ["1", "2", "a"];

let sum: i32 = lines
    .iter()
    .map(|line| line.parse::<i32>())
    .inspect(|num| {
        if let Err(ref e) = *num {
            println!("Parsing error: {e}");
        }
    })
    .filter_map(Result::ok)
    .sum();

println!("Sum: {sum}");
```
 This will print:

 
```
Parsing error: invalid digit found in string
Sum: 3

```


[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1771-1773)
```
fn by_ref(&mut self) -> &mut Self
where
    Self: Sized,
```

Borrows an iterator, rather than consuming it.

 This is useful to allow applying iterator adapters while still retaining ownership of the original iterator.

 ##### Examples

 Basic usage:

 
```
let mut words = ["hello", "world", "of", "Rust"].into_iter();

// Take the first two words.
let hello_world: Vec<_> = words.by_ref().take(2).collect();
assert_eq!(hello_world, vec!["hello", "world"]);

// Collect the rest of the words.
// We can only do this because we used `by_ref` earlier.
let of_rust: Vec<_> = words.collect();
assert_eq!(of_rust, vec!["of", "Rust"]);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1891-1893)
```
fn collect<B>(self) -> B
where
    B: FromIterator<Self::Item>,
    Self: Sized,
```

Transforms an iterator into a collection.

 `collect()` can take anything iterable, and turn it into a relevant collection. This is one of the more powerful methods in the standard library, used in a variety of contexts.

 The most basic pattern in which `collect()` is used is to turn one collection into another. You take a collection, call [`iter`](trait.iterator#tymethod.next "method std::iter::Iterator::next") on it, do a bunch of transformations, and then `collect()` at the end.

 `collect()` can also create instances of types that are not typical collections. For example, a [`String`](../string/struct.string) can be built from [`char`](../primitive.char "primitive char")s, and an iterator of [`Result<T, E>`](../result/enum.result "enum std::result::Result") items can be collected into `Result<Collection<T>, E>`. See the examples below for more.

 Because `collect()` is so general, it can cause problems with type inference. As such, `collect()` is one of the few times you’ll see the syntax affectionately known as the ‘turbofish’: `::<>`. This helps the inference algorithm understand specifically which collection you’re trying to collect into.

 ##### Examples

 Basic usage:

 
```
let a = [1, 2, 3];

let doubled: Vec<i32> = a.iter()
                         .map(|&x| x * 2)
                         .collect();

assert_eq!(vec![2, 4, 6], doubled);
```
 Note that we needed the `: Vec<i32>` on the left-hand side. This is because we could collect into, for example, a [`VecDeque<T>`](../collections/struct.vecdeque) instead:

 
```
use std::collections::VecDeque;

let a = [1, 2, 3];

let doubled: VecDeque<i32> = a.iter().map(|&x| x * 2).collect();

assert_eq!(2, doubled[0]);
assert_eq!(4, doubled[1]);
assert_eq!(6, doubled[2]);
```
 Using the ‘turbofish’ instead of annotating `doubled`:

 
```
let a = [1, 2, 3];

let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();

assert_eq!(vec![2, 4, 6], doubled);
```
 Because `collect()` only cares about what you’re collecting into, you can still use a partial type hint, `_`, with the turbofish:

 
```
let a = [1, 2, 3];

let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();

assert_eq!(vec![2, 4, 6], doubled);
```
 Using `collect()` to make a [`String`](../string/struct.string):

 
```
let chars = ['g', 'd', 'k', 'k', 'n'];

let hello: String = chars.iter()
    .map(|&x| x as u8)
    .map(|x| (x + 1) as char)
    .collect();

assert_eq!("hello", hello);
```
 If you have a list of [`Result<T, E>`](../result/enum.result "enum std::result::Result")s, you can use `collect()` to see if any of them failed:

 
```
let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];

let result: Result<Vec<_>, &str> = results.iter().cloned().collect();

// gives us the first error
assert_eq!(Err("nope"), result);

let results = [Ok(1), Ok(3)];

let result: Result<Vec<_>, &str> = results.iter().cloned().collect();

// gives us the list of answers
assert_eq!(Ok(vec![1, 3]), result);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#1970-1975)
```
fn try_collect<B>(
    &mut self
) -> <<Self::Item as Try>::Residual as Residual<B>>::TryType
where
    Self: Sized,
    Self::Item: Try,
    <Self::Item as Try>::Residual: Residual<B>,
    B: FromIterator<<Self::Item as 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.

 `try_collect()` is a variation of [`collect()`](trait.iterator#method.collect "method std::iter::Iterator::collect") that allows fallible conversions during collection. Its main use case is simplifying conversions from iterators yielding [`Option<T>`](../option/enum.option "enum std::option::Option") into `Option<Collection<T>>`, or similarly for other [`Try`](../ops/trait.try "trait std::ops::Try") types (e.g. [`Result`](../result/enum.result "enum std::result::Result")).

 Importantly, `try_collect()` doesn’t require that the outer [`Try`](../ops/trait.try "trait std::ops::Try") type also implements [`FromIterator`](trait.fromiterator "trait std::iter::FromIterator"); only the inner type produced on `Try::Output` must implement it. Concretely, this means that collecting into `ControlFlow<_, Vec<i32>>` is valid because `Vec<i32>` implements [`FromIterator`](trait.fromiterator "trait std::iter::FromIterator"), even though [`ControlFlow`](../ops/enum.controlflow "enum std::ops::ControlFlow") doesn’t.

 Also, if a failure is encountered during `try_collect()`, the iterator is still valid and may continue to be used, in which case it will continue iterating starting after the element that triggered the failure. See the last example below for an example of how this works.

 ##### Examples

 Successfully collecting an iterator of `Option<i32>` into `Option<Vec<i32>>`:

 
```
#![feature(iterator_try_collect)]

let u = vec![Some(1), Some(2), Some(3)];
let v = u.into_iter().try_collect::<Vec<i32>>();
assert_eq!(v, Some(vec![1, 2, 3]));
```
 Failing to collect in the same way:

 
```
#![feature(iterator_try_collect)]

let u = vec![Some(1), Some(2), None, Some(3)];
let v = u.into_iter().try_collect::<Vec<i32>>();
assert_eq!(v, None);
```
 A similar example, but with `Result`:

 
```
#![feature(iterator_try_collect)]

let u: Vec<Result<i32, ()>> = vec![Ok(1), Ok(2), Ok(3)];
let v = u.into_iter().try_collect::<Vec<i32>>();
assert_eq!(v, Ok(vec![1, 2, 3]));

let u = vec![Ok(1), Ok(2), Err(()), Ok(3)];
let v = u.into_iter().try_collect::<Vec<i32>>();
assert_eq!(v, Err(()));
```
 Finally, even [`ControlFlow`](../ops/enum.controlflow "enum std::ops::ControlFlow") works, despite the fact that it doesn’t implement [`FromIterator`](trait.fromiterator "trait std::iter::FromIterator"). Note also that the iterator can continue to be used, even if a failure is encountered:

 
```
#![feature(iterator_try_collect)]

use core::ops::ControlFlow::{Break, Continue};

let u = [Continue(1), Continue(2), Break(3), Continue(4), Continue(5)];
let mut it = u.into_iter();

let v = it.try_collect::<Vec<_>>();
assert_eq!(v, Break(3));

let v = it.try_collect::<Vec<_>>();
assert_eq!(v, Continue(vec![4, 5]));
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2044-2046)
```
fn collect_into<E>(self, collection: &mut E) -> &mut E
where
    E: Extend<Self::Item>,
    Self: 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.

 This method consumes the iterator and adds all its items to the passed collection. The collection is then returned, so the call chain can be continued.

 This is useful when you already have a collection and wants to add the iterator items to it.

 This method is a convenience method to call [Extend::extend](trait.extend), but instead of being called on a collection, it’s called on an iterator.

 ##### Examples

 Basic usage:

 
```
#![feature(iter_collect_into)]

let a = [1, 2, 3];
let mut vec: Vec::<i32> = vec![0, 1];

a.iter().map(|&x| x * 2).collect_into(&mut vec);
a.iter().map(|&x| x * 10).collect_into(&mut vec);

assert_eq!(vec, vec![0, 1, 2, 4, 6, 10, 20, 30]);
```
 `Vec` can have a manual set capacity to avoid reallocating it:

 
```
#![feature(iter_collect_into)]

let a = [1, 2, 3];
let mut vec: Vec::<i32> = Vec::with_capacity(6);

a.iter().map(|&x| x * 2).collect_into(&mut vec);
a.iter().map(|&x| x * 10).collect_into(&mut vec);

assert_eq!(6, vec.capacity());
assert_eq!(vec, vec![2, 4, 6, 10, 20, 30]);
```
 The returned mutable reference can be used to continue the call chain:

 
```
#![feature(iter_collect_into)]

let a = [1, 2, 3];
let mut vec: Vec::<i32> = Vec::with_capacity(6);

let count = a.iter().collect_into(&mut vec).iter().count();

assert_eq!(count, vec.len());
assert_eq!(vec, vec![1, 2, 3]);

let count = a.iter().collect_into(&mut vec).iter().count();

assert_eq!(count, vec.len());
assert_eq!(vec, vec![1, 2, 3, 1, 2, 3]);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2079-2083)
```
fn partition<B, F>(self, f: F) -> (B, B)
where
    Self: Sized,
    B: Default + Extend<Self::Item>,
    F: FnMut(&Self::Item) -> bool,
```

Consumes an iterator, creating two collections from it.

 The predicate passed to `partition()` can return `true`, or `false`. `partition()` returns a pair, all of the elements for which it returned `true`, and all of the elements for which it returned `false`.

 See also [`is_partitioned()`](trait.iterator#method.is_partitioned "method std::iter::Iterator::is_partitioned") and [`partition_in_place()`](trait.iterator#method.partition_in_place "method std::iter::Iterator::partition_in_place").

 ##### Examples

 Basic usage:

 
```
let a = [1, 2, 3];

let (even, odd): (Vec<_>, Vec<_>) = a
    .into_iter()
    .partition(|n| n % 2 == 0);

assert_eq!(even, vec![2]);
assert_eq!(odd, vec![1, 3]);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2142-2145)
```
fn partition_in_place<'a, T, P>(self, predicate: P) -> usize
where
    T: 'a,
    Self: Sized + DoubleEndedIterator<Item = &'a mut T>,
    P: FnMut(&T) -> bool,
```

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

 The relative order of partitioned items is not maintained.

 ##### Current implementation

 The current algorithm tries to find the first element for which the predicate evaluates to false and the last element for which it evaluates to true, and repeatedly swaps them.

 Time complexity: *O*(*n*)

 See also [`is_partitioned()`](trait.iterator#method.is_partitioned "method std::iter::Iterator::is_partitioned") and [`partition()`](trait.iterator#method.partition "method std::iter::Iterator::partition").

 ##### Examples

 
```
#![feature(iter_partition_in_place)]

let mut a = [1, 2, 3, 4, 5, 6, 7];

// Partition in-place between evens and odds
let i = a.iter_mut().partition_in_place(|&n| n % 2 == 0);

assert_eq!(i, 3);
assert!(a[..i].iter().all(|&n| n % 2 == 0)); // evens
assert!(a[i..].iter().all(|&n| n % 2 == 1)); // odds
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2200-2203)
```
fn is_partitioned<P>(self, predicate: P) -> bool
where
    Self: Sized,
    P: FnMut(Self::Item) -> bool,
```

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

 See also [`partition()`](trait.iterator#method.partition "method std::iter::Iterator::partition") and [`partition_in_place()`](trait.iterator#method.partition_in_place "method std::iter::Iterator::partition_in_place").

 ##### Examples

 
```
#![feature(iter_is_partitioned)]

assert!("Iterator".chars().is_partitioned(char::is_uppercase));
assert!(!"IntoIterator".chars().is_partitioned(char::is_uppercase));
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2295-2299)1.27.0
```
fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
where
    Self: Sized,
    F: FnMut(B, Self::Item) -> R,
    R: Try<Output = B>,
```

An iterator method that applies a function as long as it returns successfully, producing a single, final value.

 `try_fold()` takes two arguments: an initial value, and a closure with two arguments: an ‘accumulator’, and an element. The closure either returns successfully, with the value that the accumulator should have for the next iteration, or it returns failure, with an error value that is propagated back to the caller immediately (short-circuiting).

 The initial value is the value the accumulator will have on the first call. If applying the closure succeeded against every element of the iterator, `try_fold()` returns the final accumulator as success.

 Folding is useful whenever you have a collection of something, and want to produce a single value from it.

 ##### Note to Implementors

 Several of the other (forward) methods have default implementations in terms of this one, so try to implement this explicitly if it can do something better than the default `for` loop implementation.

 In particular, try to have this call `try_fold()` on the internal parts from which this iterator is composed. If multiple calls are needed, the `?` operator may be convenient for chaining the accumulator value along, but beware any invariants that need to be upheld before those early returns. This is a `&mut self` method, so iteration needs to be resumable after hitting an error here.

 ##### Examples

 Basic usage:

 
```
let a = [1, 2, 3];

// the checked sum of all of the elements of the array
let sum = a.iter().try_fold(0i8, |acc, &x| acc.checked_add(x));

assert_eq!(sum, Some(6));
```
 Short-circuiting:

 
```
let a = [10, 20, 30, 100, 40, 50];
let mut it = a.iter();

// This sum overflows when adding the 100 element
let sum = it.try_fold(0i8, |acc, &x| acc.checked_add(x));
assert_eq!(sum, None);

// Because it short-circuited, the remaining elements are still
// available through the iterator.
assert_eq!(it.len(), 2);
assert_eq!(it.next(), Some(&40));
```
 While you cannot `break` from a closure, the [`ControlFlow`](../ops/enum.controlflow "enum std::ops::ControlFlow") type allows a similar idea:

 
```
use std::ops::ControlFlow;

let triangular = (1..30).try_fold(0_i8, |prev, x| {
    if let Some(next) = prev.checked_add(x) {
        ControlFlow::Continue(next)
    } else {
        ControlFlow::Break(prev)
    }
});
assert_eq!(triangular, ControlFlow::Break(120));

let triangular = (1..30).try_fold(0_u64, |prev, x| {
    if let Some(next) = prev.checked_add(x) {
        ControlFlow::Continue(next)
    } else {
        ControlFlow::Break(prev)
    }
});
assert_eq!(triangular, ControlFlow::Continue(435));
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2354-2358)1.27.0
```
fn try_for_each<F, R>(&mut self, f: F) -> R
where
    Self: Sized,
    F: FnMut(Self::Item) -> R,
    R: Try<Output = ()>,
```

An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error.

 This can also be thought of as the fallible form of [`for_each()`](trait.iterator#method.for_each "method std::iter::Iterator::for_each") or as the stateless version of [`try_fold()`](trait.iterator#method.try_fold "method std::iter::Iterator::try_fold").

 ##### Examples

 
```
use std::fs::rename;
use std::io::{stdout, Write};
use std::path::Path;

let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];

let res = data.iter().try_for_each(|x| writeln!(stdout(), "{x}"));
assert!(res.is_ok());

let mut it = data.iter().cloned();
let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
assert!(res.is_err());
// It short-circuited, so the remaining items are still in the iterator:
assert_eq!(it.next(), Some("stale_bread.json"));
```
 The [`ControlFlow`](../ops/enum.controlflow "enum std::ops::ControlFlow") type can be used with this method for the situations in which you’d use `break` and `continue` in a normal loop:

 
```
use std::ops::ControlFlow;

let r = (2..100).try_for_each(|x| {
    if 323 % x == 0 {
        return ControlFlow::Break(x)
    }

    ControlFlow::Continue(())
});
assert_eq!(r, ControlFlow::Break(17));
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2474-2477)
```
fn fold<B, F>(self, init: B, f: F) -> B
where
    Self: Sized,
    F: FnMut(B, Self::Item) -> B,
```

Folds every element into an accumulator by applying an operation, returning the final result.

 `fold()` takes two arguments: an initial value, and a closure with two arguments: an ‘accumulator’, and an element. The closure returns the value that the accumulator should have for the next iteration.

 The initial value is the value the accumulator will have on the first call.

 After applying this closure to every element of the iterator, `fold()` returns the accumulator.

 This operation is sometimes called ‘reduce’ or ‘inject’.

 Folding is useful whenever you have a collection of something, and want to produce a single value from it.

 Note: `fold()`, and similar methods that traverse the entire iterator, might not terminate for infinite iterators, even on traits for which a result is determinable in finite time.

 Note: [`reduce()`](trait.iterator#method.reduce "method std::iter::Iterator::reduce") can be used to use the first element as the initial value, if the accumulator type and item type is the same.

 Note: `fold()` combines elements in a *left-associative* fashion. For associative operators like `+`, the order the elements are combined in is not important, but for non-associative operators like `-` the order will affect the final result. For a *right-associative* version of `fold()`, see [`DoubleEndedIterator::rfold()`](trait.doubleendediterator#method.rfold "method std::iter::DoubleEndedIterator::rfold").

 ##### Note to Implementors

 Several of the other (forward) methods have default implementations in terms of this one, so try to implement this explicitly if it can do something better than the default `for` loop implementation.

 In particular, try to have this call `fold()` on the internal parts from which this iterator is composed.

 ##### Examples

 Basic usage:

 
```
let a = [1, 2, 3];

// the sum of all of the elements of the array
let sum = a.iter().fold(0, |acc, x| acc + x);

assert_eq!(sum, 6);
```
 Let’s walk through each step of the iteration here:

 


| element | acc | x | result |
| --- | --- | --- | --- |
|  | 0 |  |  |
| 1 | 0 | 1 | 1 |
| 2 | 1 | 2 | 3 |
| 3 | 3 | 3 | 6 |

  And so, our final result, `6`.

 This example demonstrates the left-associative nature of `fold()`: it builds a string, starting with an initial value and continuing with each element from the front until the back:

 
```
let numbers = [1, 2, 3, 4, 5];

let zero = "0".to_string();

let result = numbers.iter().fold(zero, |acc, &x| {
    format!("({acc} + {x})")
});

assert_eq!(result, "(((((0 + 1) + 2) + 3) + 4) + 5)");
```
 It’s common for people who haven’t used iterators a lot to use a `for` loop with a list of things to build up a result. Those can be turned into `fold()`s:

 
```
let numbers = [1, 2, 3, 4, 5];

let mut result = 0;

// for loop:
for i in &numbers {
    result = result + i;
}

// fold:
let result2 = numbers.iter().fold(0, |acc, &x| acc + x);

// they're the same
assert_eq!(result, result2);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2512-2515)1.51.0
```
fn reduce<F>(self, f: F) -> Option<Self::Item>
where
    Self: Sized,
    F: FnMut(Self::Item, Self::Item) -> Self::Item,
```

Reduces the elements to a single one, by repeatedly applying a reducing operation.

 If the iterator is empty, returns [`None`](../option/enum.option#variant.None "variant std::option::Option::None"); otherwise, returns the result of the reduction.

 The reducing function is a closure with two arguments: an ‘accumulator’, and an element. For iterators with at least one element, this is the same as [`fold()`](trait.iterator#method.fold "method std::iter::Iterator::fold") with the first element of the iterator as the initial accumulator value, folding every subsequent element into it.

 ##### Example

 
```
let reduced: i32 = (1..10).reduce(|acc, e| acc + e).unwrap();
assert_eq!(reduced, 45);

// Which is equivalent to doing it with `fold`:
let folded: i32 = (1..10).fold(0, |acc, e| acc + e);
assert_eq!(reduced, folded);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2584-2589)
```
fn try_reduce<F, R>(
    &mut self,
    f: F
) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryType
where
    Self: Sized,
    F: FnMut(Self::Item, Self::Item) -> R,
    R: Try<Output = Self::Item>,
    <R as Try>::Residual: Residual<Option<Self::Item>>,
```

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

 The return type of this method depends on the return type of the closure. If the closure returns `Result<Self::Item, E>`, then this function will return `Result<Option<Self::Item>, E>`. If the closure returns `Option<Self::Item>`, then this function will return `Option<Option<Self::Item>>`.

 When called on an empty iterator, this function will return either `Some(None)` or `Ok(None)` depending on the type of the provided closure.

 For iterators with at least one element, this is essentially the same as calling [`try_fold()`](trait.iterator#method.try_fold "method std::iter::Iterator::try_fold") with the first element of the iterator as the initial accumulator value.

 ##### Examples

 Safely calculate the sum of a series of numbers:

 
```
#![feature(iterator_try_reduce)]

let numbers: Vec<usize> = vec![10, 20, 5, 23, 0];
let sum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));
assert_eq!(sum, Some(Some(58)));
```
 Determine when a reduction short circuited:

 
```
#![feature(iterator_try_reduce)]

let numbers = vec![1, 2, 3, usize::MAX, 4, 5];
let sum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));
assert_eq!(sum, None);
```
 Determine when a reduction was not performed because there are no elements:

 
```
#![feature(iterator_try_reduce)]

let numbers: Vec<usize> = Vec::new();
let sum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));
assert_eq!(sum, Some(None));
```
 Use a [`Result`](../result/enum.result "enum std::result::Result") instead of an [`Option`](../option/enum.option "enum std::option::Option"):

 
```
#![feature(iterator_try_reduce)]

let numbers = vec!["1", "2", "3", "4", "5"];
let max: Result<Option<_>, <usize as std::str::FromStr>::Err> =
    numbers.into_iter().try_reduce(|x, y| {
        if x.parse::<usize>()? > y.parse::<usize>()? { Ok(x) } else { Ok(y) }
    });
assert_eq!(max, Ok(Some("5")));
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2642-2645)
```
fn all<F>(&mut self, f: F) -> bool
where
    Self: Sized,
    F: FnMut(Self::Item) -> bool,
```

Tests if every element of the iterator matches a predicate.

 `all()` takes a closure that returns `true` or `false`. It applies this closure to each element of the iterator, and if they all return `true`, then so does `all()`. If any of them return `false`, it returns `false`.

 `all()` is short-circuiting; in other words, it will stop processing as soon as it finds a `false`, given that no matter what else happens, the result will also be `false`.

 An empty iterator returns `true`.

 ##### Examples

 Basic usage:

 
```
let a = [1, 2, 3];

assert!(a.iter().all(|&x| x > 0));

assert!(!a.iter().all(|&x| x > 2));
```
 Stopping at the first `false`:

 
```
let a = [1, 2, 3];

let mut iter = a.iter();

assert!(!iter.all(|&x| x != 2));

// we can still use `iter`, as there are more elements.
assert_eq!(iter.next(), Some(&3));
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2696-2699)
```
fn any<F>(&mut self, f: F) -> bool
where
    Self: Sized,
    F: FnMut(Self::Item) -> bool,
```

Tests if any element of the iterator matches a predicate.

 `any()` takes a closure that returns `true` or `false`. It applies this closure to each element of the iterator, and if any of them return `true`, then so does `any()`. If they all return `false`, it returns `false`.

 `any()` is short-circuiting; in other words, it will stop processing as soon as it finds a `true`, given that no matter what else happens, the result will also be `true`.

 An empty iterator returns `false`.

 ##### Examples

 Basic usage:

 
```
let a = [1, 2, 3];

assert!(a.iter().any(|&x| x > 0));

assert!(!a.iter().any(|&x| x > 5));
```
 Stopping at the first `true`:

 
```
let a = [1, 2, 3];

let mut iter = a.iter();

assert!(iter.any(|&x| x != 2));

// we can still use `iter`, as there are more elements.
assert_eq!(iter.next(), Some(&2));
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2760-2763)
```
fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
where
    Self: Sized,
    P: FnMut(&Self::Item) -> bool,
```

Searches for an element of an iterator that satisfies a predicate.

 `find()` takes a closure that returns `true` or `false`. It applies this closure to each element of the iterator, and if any of them return `true`, then `find()` returns [`Some(element)`](../option/enum.option#variant.Some "variant std::option::Option::Some"). If they all return `false`, it returns [`None`](../option/enum.option#variant.None "variant std::option::Option::None").

 `find()` is short-circuiting; in other words, it will stop processing as soon as the closure returns `true`.

 Because `find()` takes a reference, and many iterators iterate over references, this leads to a possibly confusing situation where the argument is a double reference. You can see this effect in the examples below, with `&&x`.

 If you need the index of the element, see [`position()`](trait.iterator#method.position "method std::iter::Iterator::position").

 ##### Examples

 Basic usage:

 
```
let a = [1, 2, 3];

assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));

assert_eq!(a.iter().find(|&&x| x == 5), None);
```
 Stopping at the first `true`:

 
```
let a = [1, 2, 3];

let mut iter = a.iter();

assert_eq!(iter.find(|&&x| x == 2), Some(&2));

// we can still use `iter`, as there are more elements.
assert_eq!(iter.next(), Some(&3));
```
 Note that `iter.find(f)` is equivalent to `iter.filter(f).next()`.

 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2792-2795)1.30.0
```
fn find_map<B, F>(&mut self, f: F) -> Option<B>
where
    Self: Sized,
    F: FnMut(Self::Item) -> Option<B>,
```

Applies function to the elements of iterator and returns the first non-none result.

 `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.

 ##### Examples

 
```
let a = ["lol", "NaN", "2", "5"];

let first_number = a.iter().find_map(|s| s.parse().ok());

assert_eq!(first_number, Some(2));
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2849-2854)
```
fn try_find<F, R>(
    &mut self,
    f: F
) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryType
where
    Self: Sized,
    F: FnMut(&Self::Item) -> R,
    R: Try<Output = bool>,
    <R as Try>::Residual: Residual<Option<Self::Item>>,
```

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

 The return type of this method depends on the return type of the closure. If you return `Result<bool, E>` from the closure, you’ll get a `Result<Option<Self::Item>, E>`. If you return `Option<bool>` from the closure, you’ll get an `Option<Option<Self::Item>>`.

 ##### Examples

 
```
#![feature(try_find)]

let a = ["1", "2", "lol", "NaN", "5"];

let is_my_num = |s: &str, search: i32| -> Result<bool, std::num::ParseIntError> {
    Ok(s.parse::<i32>()?  == search)
};

let result = a.iter().try_find(|&&s| is_my_num(s, 2));
assert_eq!(result, Ok(Some(&"2")));

let result = a.iter().try_find(|&&s| is_my_num(s, 5));
assert!(result.is_err());
```
 This also supports other types which implement `Try`, not just `Result`.

 
```
#![feature(try_find)]

use std::num::NonZeroU32;
let a = [3, 5, 7, 4, 9, 0, 11];
let result = a.iter().try_find(|&&x| NonZeroU32::new(x).map(|y| y.is_power_of_two()));
assert_eq!(result, Some(Some(&4)));
let result = a.iter().take(3).try_find(|&&x| NonZeroU32::new(x).map(|y| y.is_power_of_two()));
assert_eq!(result, Some(None));
let result = a.iter().rev().try_find(|&&x| NonZeroU32::new(x).map(|y| y.is_power_of_two()));
assert_eq!(result, None);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2932-2935)
```
fn position<P>(&mut self, predicate: P) -> Option<usize>
where
    Self: Sized,
    P: FnMut(Self::Item) -> bool,
```

Searches for an element in an iterator, returning its index.

 `position()` takes a closure that returns `true` or `false`. It applies this closure to each element of the iterator, and if one of them returns `true`, then `position()` returns [`Some(index)`](../option/enum.option#variant.Some "variant std::option::Option::Some"). If all of them return `false`, it returns [`None`](../option/enum.option#variant.None "variant std::option::Option::None").

 `position()` is short-circuiting; in other words, it will stop processing as soon as it finds a `true`.

 ##### Overflow Behavior

 The method does no guarding against overflows, so if there are more than [`usize::MAX`](../primitive.usize#associatedconstant.MAX "associated constant usize::MAX") non-matching elements, it either produces the wrong result or panics. If debug assertions are enabled, a panic is guaranteed.

 ##### Panics

 This function might panic if the iterator has more than `usize::MAX` non-matching elements.

 ##### Examples

 Basic usage:

 
```
let a = [1, 2, 3];

assert_eq!(a.iter().position(|&x| x == 2), Some(1));

assert_eq!(a.iter().position(|&x| x == 5), None);
```
 Stopping at the first `true`:

 
```
let a = [1, 2, 3, 4];

let mut iter = a.iter();

assert_eq!(iter.position(|&x| x >= 2), Some(1));

// we can still use `iter`, as there are more elements.
assert_eq!(iter.next(), Some(&3));

// The returned index depends on iterator state
assert_eq!(iter.position(|&x| x == 4), Some(0));

```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#2990-2993)
```
fn rposition<P>(&mut self, predicate: P) -> Option<usize>
where
    P: FnMut(Self::Item) -> bool,
    Self: Sized + ExactSizeIterator + DoubleEndedIterator,
```

Searches for an element in an iterator from the right, returning its index.

 `rposition()` takes a closure that returns `true` or `false`. It applies this closure to each element of the iterator, starting from the end, and if one of them returns `true`, then `rposition()` returns [`Some(index)`](../option/enum.option#variant.Some "variant std::option::Option::Some"). If all of them return `false`, it returns [`None`](../option/enum.option#variant.None "variant std::option::Option::None").

 `rposition()` is short-circuiting; in other words, it will stop processing as soon as it finds a `true`.

 ##### Examples

 Basic usage:

 
```
let a = [1, 2, 3];

assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));

assert_eq!(a.iter().rposition(|&x| x == 5), None);
```
 Stopping at the first `true`:

 
```
let a = [-1, 2, 3, 4];

let mut iter = a.iter();

assert_eq!(iter.rposition(|&x| x >= 2), Some(3));

// we can still use `iter`, as there are more elements.
assert_eq!(iter.next(), Some(&-1));
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3042-3045)
```
fn max(self) -> Option<Self::Item>
where
    Self: Sized,
    Self::Item: Ord,
```

Returns the maximum element of an iterator.

 If several elements are equally maximum, the last element is returned. If the iterator is empty, [`None`](../option/enum.option#variant.None "variant std::option::Option::None") is returned.

 Note that [`f32`](../primitive.f32 "primitive f32")/[`f64`](../primitive.f64 "primitive f64") doesn’t implement [`Ord`](../cmp/trait.ord "trait std::cmp::Ord") due to NaN being incomparable. You can work around this by using [`Iterator::reduce`](trait.iterator#method.reduce "method std::iter::Iterator::reduce"):

 
```
assert_eq!(
    [2.4, f32::NAN, 1.3]
        .into_iter()
        .reduce(f32::max)
        .unwrap(),
    2.4
);
```
 ##### Examples

 Basic usage:

 
```
let a = [1, 2, 3];
let b: Vec<u32> = Vec::new();

assert_eq!(a.iter().max(), Some(&3));
assert_eq!(b.iter().max(), None);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3081-3084)
```
fn min(self) -> Option<Self::Item>
where
    Self: Sized,
    Self::Item: Ord,
```

Returns the minimum element of an iterator.

 If several elements are equally minimum, the first element is returned. If the iterator is empty, [`None`](../option/enum.option#variant.None "variant std::option::Option::None") is returned.

 Note that [`f32`](../primitive.f32 "primitive f32")/[`f64`](../primitive.f64 "primitive f64") doesn’t implement [`Ord`](../cmp/trait.ord "trait std::cmp::Ord") due to NaN being incomparable. You can work around this by using [`Iterator::reduce`](trait.iterator#method.reduce "method std::iter::Iterator::reduce"):

 
```
assert_eq!(
    [2.4, f32::NAN, 1.3]
        .into_iter()
        .reduce(f32::min)
        .unwrap(),
    1.3
);
```
 ##### Examples

 Basic usage:

 
```
let a = [1, 2, 3];
let b: Vec<u32> = Vec::new();

assert_eq!(a.iter().min(), Some(&1));
assert_eq!(b.iter().min(), None);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3104-3107)1.6.0
```
fn max_by_key<B, F>(self, f: F) -> Option<Self::Item>
where
    B: Ord,
    Self: Sized,
    F: FnMut(&Self::Item) -> B,
```

Returns the element that gives the maximum value from the specified function.

 If several elements are equally maximum, the last element is returned. If the iterator is empty, [`None`](../option/enum.option#variant.None "variant std::option::Option::None") is returned.

 ##### Examples

 
```
let a = [-3_i32, 0, 1, 5, -10];
assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3138-3141)1.15.0
```
fn max_by<F>(self, compare: F) -> Option<Self::Item>
where
    Self: Sized,
    F: FnMut(&Self::Item, &Self::Item) -> Ordering,
```

Returns the element that gives the maximum value with respect to the specified comparison function.

 If several elements are equally maximum, the last element is returned. If the iterator is empty, [`None`](../option/enum.option#variant.None "variant std::option::Option::None") is returned.

 ##### Examples

 
```
let a = [-3_i32, 0, 1, 5, -10];
assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3166-3169)1.6.0
```
fn min_by_key<B, F>(self, f: F) -> Option<Self::Item>
where
    B: Ord,
    Self: Sized,
    F: FnMut(&Self::Item) -> B,
```

Returns the element that gives the minimum value from the specified function.

 If several elements are equally minimum, the first element is returned. If the iterator is empty, [`None`](../option/enum.option#variant.None "variant std::option::Option::None") is returned.

 ##### Examples

 
```
let a = [-3_i32, 0, 1, 5, -10];
assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3200-3203)1.15.0
```
fn min_by<F>(self, compare: F) -> Option<Self::Item>
where
    Self: Sized,
    F: FnMut(&Self::Item, &Self::Item) -> Ordering,
```

Returns the element that gives the minimum value with respect to the specified comparison function.

 If several elements are equally minimum, the first element is returned. If the iterator is empty, [`None`](../option/enum.option#variant.None "variant std::option::Option::None") is returned.

 ##### Examples

 
```
let a = [-3_i32, 0, 1, 5, -10];
assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3238-3240)
```
fn rev(self) -> Rev<Self> ⓘ
where
    Self: Sized + DoubleEndedIterator,
```

Reverses an iterator’s direction.

 Usually, iterators iterate from left to right. After using `rev()`, an iterator will instead iterate from right to left.

 This is only possible if the iterator has an end, so `rev()` only works on [`DoubleEndedIterator`](trait.doubleendediterator "trait std::iter::DoubleEndedIterator")s.

 ##### Examples

 
```
let a = [1, 2, 3];

let mut iter = a.iter().rev();

assert_eq!(iter.next(), Some(&3));
assert_eq!(iter.next(), Some(&2));
assert_eq!(iter.next(), Some(&1));

assert_eq!(iter.next(), None);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3277-3281)
```
fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)
where
    FromA: Default + Extend<A>,
    FromB: Default + Extend<B>,
    Self: Sized + Iterator<Item = (A, B)>,
```

Converts an iterator of pairs into a pair of containers.

 `unzip()` consumes an entire iterator of pairs, producing two collections: one from the left elements of the pairs, and one from the right elements.

 This function is, in some sense, the opposite of [`zip`](trait.iterator#method.zip "method std::iter::Iterator::zip").

 ##### Examples

 Basic usage:

 
```
let a = [(1, 2), (3, 4), (5, 6)];

let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();

assert_eq!(left, [1, 3, 5]);
assert_eq!(right, [2, 4, 6]);

// you can also unzip multiple nested tuples at once
let a = [(1, (2, 3)), (4, (5, 6))];

let (x, (y, z)): (Vec<_>, (Vec<_>, Vec<_>)) = a.iter().cloned().unzip();
assert_eq!(x, [1, 4]);
assert_eq!(y, [2, 5]);
assert_eq!(z, [3, 6]);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3310-3313)1.36.0
```
fn copied<'a, T>(self) -> Copied<Self> ⓘ
where
    T: 'a + Copy,
    Self: Sized + Iterator<Item = &'a T>,
```

Creates an iterator which copies all of its elements.

 This is useful when you have an iterator over `&T`, but you need an iterator over `T`.

 ##### Examples

 Basic usage:

 
```
let a = [1, 2, 3];

let v_copied: Vec<_> = a.iter().copied().collect();

// copied is the same as .map(|&x| x)
let v_map: Vec<_> = a.iter().map(|&x| x).collect();

assert_eq!(v_copied, vec![1, 2, 3]);
assert_eq!(v_map, vec![1, 2, 3]);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3358-3361)
```
fn cloned<'a, T>(self) -> Cloned<Self> ⓘ
where
    T: 'a + Clone,
    Self: Sized + Iterator<Item = &'a T>,
```

Creates an iterator which [`clone`](../clone/trait.clone#tymethod.clone "method std::clone::Clone::clone")s all of its elements.

 This is useful when you have an iterator over `&T`, but you need an iterator over `T`.

 There is no guarantee whatsoever about the `clone` method actually being called *or* optimized away. So code should not depend on either.

 ##### Examples

 Basic usage:

 
```
let a = [1, 2, 3];

let v_cloned: Vec<_> = a.iter().cloned().collect();

// cloned is the same as .map(|&x| x), for integers
let v_map: Vec<_> = a.iter().map(|&x| x).collect();

assert_eq!(v_cloned, vec![1, 2, 3]);
assert_eq!(v_map, vec![1, 2, 3]);
```
 To get the best performance, try to clone late:

 
```
let a = [vec![0_u8, 1, 2], vec![3, 4], vec![23]];
// don't do this:
let slower: Vec<_> = a.iter().cloned().filter(|s| s.len() == 1).collect();
assert_eq!(&[vec![23]], &slower[..]);
// instead call `cloned` late
let faster: Vec<_> = a.iter().filter(|s| s.len() == 1).cloned().collect();
assert_eq!(&[vec![23]], &faster[..]);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3393-3395)
```
fn cycle(self) -> Cycle<Self> ⓘ
where
    Self: Sized + Clone,
```

Repeats an iterator endlessly.

 Instead of stopping at [`None`](../option/enum.option#variant.None "variant std::option::Option::None"), the iterator will instead start again, from the beginning. After iterating again, it will start at the beginning again. And again. And again. Forever. Note that in case the original iterator is empty, the resulting iterator will also be empty.

 ##### Examples

 Basic usage:

 
```
let a = [1, 2, 3];

let mut it = a.iter().cycle();

assert_eq!(it.next(), Some(&1));
assert_eq!(it.next(), Some(&2));
assert_eq!(it.next(), Some(&3));
assert_eq!(it.next(), Some(&1));
assert_eq!(it.next(), Some(&2));
assert_eq!(it.next(), Some(&3));
assert_eq!(it.next(), Some(&1));
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3437-3439)
```
fn array_chunks<const N: usize>(self) -> ArrayChunks<Self, N> ⓘ
where
    Self: 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.

 The chunks do not overlap. If `N` does not divide the length of the iterator, then the last up to `N-1` elements will be omitted and can be retrieved from the [`.into_remainder()`](struct.arraychunks#method.into_remainder "method std::iter::ArrayChunks::into_remainder") function of the iterator.

 ##### Panics

 Panics if `N` is 0.

 ##### Examples

 Basic usage:

 
```
#![feature(iter_array_chunks)]

let mut iter = "lorem".chars().array_chunks();
assert_eq!(iter.next(), Some(['l', 'o']));
assert_eq!(iter.next(), Some(['r', 'e']));
assert_eq!(iter.next(), None);
assert_eq!(iter.into_remainder().unwrap().as_slice(), &['m']);
```
 
```
#![feature(iter_array_chunks)]

let data = [1, 1, 2, -2, 6, 0, 3, 1];
//          ^-----^  ^------^
for [x, y, z] in data.iter().array_chunks() {
    assert_eq!(x + y + z, 4);
}
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3471-3474)1.11.0
```
fn sum<S>(self) -> S
where
    Self: Sized,
    S: Sum<Self::Item>,
```

Sums the elements of an iterator.

 Takes each element, adds them together, and returns the result.

 An empty iterator returns the zero value of the type.

 `sum()` can be used to sum any type implementing [`Sum`](trait.sum "trait std::iter::Sum"), including [`Option`](../option/enum.option#method.sum "associated function std::option::Option::sum") and [`Result`](../result/enum.result#method.sum "associated function std::result::Result::sum").

 ##### Panics

 When calling `sum()` and a primitive integer type is being returned, this method will panic if the computation overflows and debug assertions are enabled.

 ##### Examples

 Basic usage:

 
```
let a = [1, 2, 3];
let sum: i32 = a.iter().sum();

assert_eq!(sum, 6);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3504-3507)1.11.0
```
fn product<P>(self) -> P
where
    Self: Sized,
    P: Product<Self::Item>,
```

Iterates over the entire iterator, multiplying all the elements

 An empty iterator returns the one value of the type.

 `product()` can be used to multiply any type implementing [`Product`](trait.product "trait std::iter::Product"), including [`Option`](../option/enum.option#method.product "associated function std::option::Option::product") and [`Result`](../result/enum.result#method.product "associated function std::result::Result::product").

 ##### Panics

 When calling `product()` and a primitive integer type is being returned, method will panic if the computation overflows and debug assertions are enabled.

 ##### Examples

 
```
fn factorial(n: u32) -> u32 {
    (1..=n).product()
}
assert_eq!(factorial(0), 1);
assert_eq!(factorial(1), 1);
assert_eq!(factorial(5), 120);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3526-3530)1.5.0
```
fn cmp<I>(self, other: I) -> Ordering
where
    I: IntoIterator<Item = Self::Item>,
    Self::Item: Ord,
    Self: Sized,
```

[Lexicographically](../cmp/trait.ord#lexicographical-comparison "trait std::cmp::Ord") compares the elements of this [`Iterator`](trait.iterator "trait std::iter::Iterator") with those of another.

 ##### Examples

 
```
use std::cmp::Ordering;

assert_eq!([1].iter().cmp([1].iter()), Ordering::Equal);
assert_eq!([1].iter().cmp([1, 2].iter()), Ordering::Less);
assert_eq!([1, 2].iter().cmp([1].iter()), Ordering::Greater);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3556-3560)
```
fn cmp_by<I, F>(self, other: I, cmp: F) -> Ordering
where
    Self: Sized,
    I: IntoIterator,
    F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Ordering,
```

🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295))

[Lexicographically](../cmp/trait.ord#lexicographical-comparison "trait std::cmp::Ord") compares the elements of this [`Iterator`](trait.iterator "trait std::iter::Iterator") with those of another with respect to the specified comparison function.

 ##### Examples

 Basic usage:

 
```
#![feature(iter_order_by)]

use std::cmp::Ordering;

let xs = [1, 2, 3, 4];
let ys = [1, 4, 9, 16];

assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| x.cmp(&y)), Ordering::Less);
assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (x * x).cmp(&y)), Ordering::Equal);
assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (2 * x).cmp(&y)), Ordering::Greater);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3613-3617)1.5.0
```
fn partial_cmp<I>(self, other: I) -> Option<Ordering>
where
    I: IntoIterator,
    Self::Item: PartialOrd<<I as IntoIterator>::Item>,
    Self: Sized,
```

[Lexicographically](../cmp/trait.ord#lexicographical-comparison "trait std::cmp::Ord") compares the [`PartialOrd`](../cmp/trait.partialord "trait std::cmp::PartialOrd") elements of this [`Iterator`](trait.iterator "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.

 ##### Examples

 
```
use std::cmp::Ordering;

assert_eq!([1.].iter().partial_cmp([1.].iter()), Some(Ordering::Equal));
assert_eq!([1.].iter().partial_cmp([1., 2.].iter()), Some(Ordering::Less));
assert_eq!([1., 2.].iter().partial_cmp([1.].iter()), Some(Ordering::Greater));
```
 For floating-point numbers, NaN does not have a total order and will result in `None` when compared:

 
```
assert_eq!([f64::NAN].iter().partial_cmp([1.].iter()), None);
```
 The results are determined by the order of evaluation.

 
```
use std::cmp::Ordering;

assert_eq!([1.0, f64::NAN].iter().partial_cmp([2.0, f64::NAN].iter()), Some(Ordering::Less));
assert_eq!([2.0, f64::NAN].iter().partial_cmp([1.0, f64::NAN].iter()), Some(Ordering::Greater));
assert_eq!([f64::NAN, 1.0].iter().partial_cmp([f64::NAN, 2.0].iter()), None);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3652-3656)
```
fn partial_cmp_by<I, F>(self, other: I, partial_cmp: F) -> Option<Ordering>
where
    Self: Sized,
    I: IntoIterator,
    F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Option<Ordering>,
```

🔬This is a nightly-only experimental API. (`iter_order_by` [#64295](https://github.com/rust-lang/rust/issues/64295))

[Lexicographically](../cmp/trait.ord#lexicographical-comparison "trait std::cmp::Ord") compares the elements of this [`Iterator`](trait.iterator "trait std::iter::Iterator") with those of another with respect to the specified comparison function.

 ##### Examples

 Basic usage:

 
```
#![feature(iter_order_by)]

use std::cmp::Ordering;

let xs = [1.0, 2.0, 3.0, 4.0];
let ys = [1.0, 4.0, 9.0, 16.0];

assert_eq!(
    xs.iter().partial_cmp_by(&ys, |&x, &y| x.partial_cmp(&y)),
    Some(Ordering::Less)
);
assert_eq!(
    xs.iter().partial_cmp_by(&ys, |&x, &y| (x * x).partial_cmp(&y)),
    Some(Ordering::Equal)
);
assert_eq!(
    xs.iter().partial_cmp_by(&ys, |&x, &y| (2.0 * x).partial_cmp(&y)),
    Some(Ordering::Greater)
);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3686-3690)1.5.0
```
fn eq<I>(self, other: I) -> bool
where
    I: IntoIterator,
    Self::Item: PartialEq<<I as IntoIterator>::Item>,
    Self: Sized,
```

Determines if the elements of this [`Iterator`](trait.iterator "trait std::iter::Iterator") are equal to those of another.

 ##### Examples

 
```
assert_eq!([1].iter().eq([1].iter()), true);
assert_eq!([1].iter().eq([1, 2].iter()), false);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3712-3716)
```
fn eq_by<I, F>(self, other: I, eq: F) -> bool
where
    Self: Sized,
    I: IntoIterator,
    F: FnMut(Self::Item, <I as IntoIterator>::Item) -> bool,
```

🔬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`](trait.iterator "trait std::iter::Iterator") are equal to those of another with respect to the specified equality function.

 ##### Examples

 Basic usage:

 
```
#![feature(iter_order_by)]

let xs = [1, 2, 3, 4];
let ys = [1, 4, 9, 16];

assert!(xs.iter().eq_by(&ys, |&x, &y| x * x == y));
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3745-3749)1.5.0
```
fn ne<I>(self, other: I) -> bool
where
    I: IntoIterator,
    Self::Item: PartialEq<<I as IntoIterator>::Item>,
    Self: Sized,
```

Determines if the elements of this [`Iterator`](trait.iterator "trait std::iter::Iterator") are not equal to those of another.

 ##### Examples

 
```
assert_eq!([1].iter().ne([1].iter()), false);
assert_eq!([1].iter().ne([1, 2].iter()), true);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3767-3771)1.5.0
```
fn lt<I>(self, other: I) -> bool
where
    I: IntoIterator,
    Self::Item: PartialOrd<<I as IntoIterator>::Item>,
    Self: Sized,
```

Determines if the elements of this [`Iterator`](trait.iterator "trait std::iter::Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison "trait std::cmp::Ord") less than those of another.

 ##### Examples

 
```
assert_eq!([1].iter().lt([1].iter()), false);
assert_eq!([1].iter().lt([1, 2].iter()), true);
assert_eq!([1, 2].iter().lt([1].iter()), false);
assert_eq!([1, 2].iter().lt([1, 2].iter()), false);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3789-3793)1.5.0
```
fn le<I>(self, other: I) -> bool
where
    I: IntoIterator,
    Self::Item: PartialOrd<<I as IntoIterator>::Item>,
    Self: Sized,
```

Determines if the elements of this [`Iterator`](trait.iterator "trait std::iter::Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison "trait std::cmp::Ord") less or equal to those of another.

 ##### Examples

 
```
assert_eq!([1].iter().le([1].iter()), true);
assert_eq!([1].iter().le([1, 2].iter()), true);
assert_eq!([1, 2].iter().le([1].iter()), false);
assert_eq!([1, 2].iter().le([1, 2].iter()), true);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3811-3815)1.5.0
```
fn gt<I>(self, other: I) -> bool
where
    I: IntoIterator,
    Self::Item: PartialOrd<<I as IntoIterator>::Item>,
    Self: Sized,
```

Determines if the elements of this [`Iterator`](trait.iterator "trait std::iter::Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison "trait std::cmp::Ord") greater than those of another.

 ##### Examples

 
```
assert_eq!([1].iter().gt([1].iter()), false);
assert_eq!([1].iter().gt([1, 2].iter()), false);
assert_eq!([1, 2].iter().gt([1].iter()), true);
assert_eq!([1, 2].iter().gt([1, 2].iter()), false);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3833-3837)1.5.0
```
fn ge<I>(self, other: I) -> bool
where
    I: IntoIterator,
    Self::Item: PartialOrd<<I as IntoIterator>::Item>,
    Self: Sized,
```

Determines if the elements of this [`Iterator`](trait.iterator "trait std::iter::Iterator") are [lexicographically](../cmp/trait.ord#lexicographical-comparison "trait std::cmp::Ord") greater than or equal to those of another.

 ##### Examples

 
```
assert_eq!([1].iter().ge([1].iter()), true);
assert_eq!([1].iter().ge([1, 2].iter()), false);
assert_eq!([1, 2].iter().ge([1].iter()), true);
assert_eq!([1, 2].iter().ge([1, 2].iter()), true);
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3865-3868)
```
fn is_sorted(self) -> bool
where
    Self: Sized,
    Self::Item: PartialOrd<Self::Item>,
```

🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485))

Checks if the elements of this iterator are sorted.

 That is, for each element `a` and its following element `b`, `a <= b` must hold. If the iterator yields exactly zero or one element, `true` is returned.

 Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition implies that this function returns `false` if any two consecutive items are not comparable.

 ##### Examples

 
```
#![feature(is_sorted)]

assert!([1, 2, 2, 9].iter().is_sorted());
assert!(![1, 3, 2, 4].iter().is_sorted());
assert!([0].iter().is_sorted());
assert!(std::iter::empty::<i32>().is_sorted());
assert!(![0.0, 1.0, f32::NAN].iter().is_sorted());
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3894-3897)
```
fn is_sorted_by<F>(self, compare: F) -> bool
where
    Self: Sized,
    F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
```

🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485))

Checks if the elements of this iterator are sorted using the given comparator function.

 Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare` function to determine the ordering of two elements. Apart from that, it’s equivalent to [`is_sorted`](trait.iterator#method.is_sorted "method std::iter::Iterator::is_sorted"); see its documentation for more information.

 ##### Examples

 
```
#![feature(is_sorted)]

assert!([1, 2, 2, 9].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
assert!(![1, 3, 2, 4].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
assert!([0].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| a.partial_cmp(b)));
assert!(![0.0, 1.0, f32::NAN].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
```
 
[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#3941-3945)
```
fn is_sorted_by_key<F, K>(self, f: F) -> bool
where
    Self: Sized,
    F: FnMut(Self::Item) -> K,
    K: PartialOrd<K>,
```

🔬This is a nightly-only experimental API. (`is_sorted` [#53485](https://github.com/rust-lang/rust/issues/53485))

Checks if the elements of this iterator are sorted using the given key extraction function.

 Instead of comparing the iterator’s elements directly, this function compares the keys of the elements, as determined by `f`. Apart from that, it’s equivalent to [`is_sorted`](trait.iterator#method.is_sorted "method std::iter::Iterator::is_sorted"); see its documentation for more information.

 ##### Examples

 
```
#![feature(is_sorted)]

assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len()));
assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));
```
 

Implementors
------------



[source](https://doc.rust-lang.org/src/core/ascii.rs.html#100)
```
impl Iterator for std::ascii::EscapeDefault
```

```
type Item = u8
```

[source](https://doc.rust-lang.org/src/core/char/mod.rs.html#328)1.20.0
```
impl Iterator for std::char::EscapeDebug
```

```
type Item = char
```

[source](https://doc.rust-lang.org/src/core/char/mod.rs.html#238)
```
impl Iterator for std::char::EscapeDefault
```

```
type Item = char
```

[source](https://doc.rust-lang.org/src/core/char/mod.rs.html#163)
```
impl Iterator for std::char::EscapeUnicode
```

```
type Item = char
```

[source](https://doc.rust-lang.org/src/core/char/mod.rs.html#387)
```
impl Iterator for ToLowercase
```

```
type Item = char
```

[source](https://doc.rust-lang.org/src/core/char/mod.rs.html#421)
```
impl Iterator for ToUppercase
```

```
type Item = char
```

[source](https://doc.rust-lang.org/src/std/env.rs.html#802-810)
```
impl Iterator for Args
```

```
type Item = String
```

[source](https://doc.rust-lang.org/src/std/env.rs.html#843-851)
```
impl Iterator for ArgsOs
```

```
type Item = OsString
```

[source](https://doc.rust-lang.org/src/std/env.rs.html#168-176)
```
impl Iterator for Vars
```

```
type Item = (String, String)
```

[source](https://doc.rust-lang.org/src/std/env.rs.html#186-194)
```
impl Iterator for VarsOs
```

```
type Item = (OsString, OsString)
```

[source](https://doc.rust-lang.org/src/std/fs.rs.html#1642-1648)
```
impl Iterator for ReadDir
```

```
type Item = Result<DirEntry, Error>
```

[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#1035-1040)
```
impl Iterator for IntoIncoming
```

```
type Item = Result<TcpStream, Error>
```

[source](https://doc.rust-lang.org/src/core/str/iter.rs.html#232)
```
impl Iterator for std::str::Bytes<'_>
```

```
type Item = u8
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2968)1.6.0
```
impl Iterator for std::string::Drain<'_>
```

```
type Item = char
```

[source](https://doc.rust-lang.org/src/core/error.rs.html#426)
```
impl<'a> Iterator for Source<'a>
```

```
type Item = &'a (dyn Error + 'static)
```

[source](https://doc.rust-lang.org/src/std/env.rs.html#433-441)
```
impl<'a> Iterator for SplitPaths<'a>
```

```
type Item = PathBuf
```

[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#1024-1029)
```
impl<'a> Iterator for std::net::Incoming<'a>
```

```
type Item = Result<TcpStream, Error>
```

[source](https://doc.rust-lang.org/src/std/os/unix/net/listener.rs.html#380-390)1.10.0
```
impl<'a> Iterator for std::os::unix::net::Incoming<'a>Available on Unix only.
```

```
type Item = Result<UnixStream, Error>
```

[source](https://doc.rust-lang.org/src/std/os/unix/net/ancillary.rs.html#530-561)
```
impl<'a> Iterator for Messages<'a>Available on (Android or Linux) and Unix only.
```

```
type Item = Result<AncillaryData<'a>, AncillaryError>
```

[source](https://doc.rust-lang.org/src/std/os/unix/net/ancillary.rs.html#431-437)
```
impl<'a> Iterator for ScmCredentials<'a>Available on (Android or Linux) and Unix only.
```

```
type Item = SocketCred
```

[source](https://doc.rust-lang.org/src/std/os/unix/net/ancillary.rs.html#390-396)
```
impl<'a> Iterator for ScmRights<'a>Available on (Android or Linux) and Unix only.
```

```
type Item = i32
```

[source](https://doc.rust-lang.org/src/std/sys_common/wtf8.rs.html#930-960)
```
impl<'a> Iterator for EncodeWide<'a>
```

```
type Item = u16
```

[source](https://doc.rust-lang.org/src/std/path.rs.html#1097-1106)1.28.0
```
impl<'a> Iterator for Ancestors<'a>
```

```
type Item = &'a Path
```

[source](https://doc.rust-lang.org/src/std/path.rs.html#891-941)
```
impl<'a> Iterator for Components<'a>
```

```
type Item = Component<'a>
```

[source](https://doc.rust-lang.org/src/std/path.rs.html#870-877)
```
impl<'a> Iterator for std::path::Iter<'a>
```

```
type Item = &'a OsStr
```

[source](https://doc.rust-lang.org/src/std/process.rs.html#1139-1147)1.57.0
```
impl<'a> Iterator for CommandArgs<'a>
```

```
type Item = &'a OsStr
```

[source](https://doc.rust-lang.org/src/std/sys_common/process.rs.html#112-120)1.57.0
```
impl<'a> Iterator for CommandEnvs<'a>
```

```
type Item = (&'a OsStr, Option<&'a OsStr>)
```

[source](https://doc.rust-lang.org/src/core/slice/ascii.rs.html#211)1.60.0
```
impl<'a> Iterator for EscapeAscii<'a>
```

```
type Item = u8
```

[source](https://doc.rust-lang.org/src/core/str/iter.rs.html#134)
```
impl<'a> Iterator for CharIndices<'a>
```

```
type Item = (usize, char)
```

[source](https://doc.rust-lang.org/src/core/str/iter.rs.html#37)
```
impl<'a> Iterator for Chars<'a>
```

```
type Item = char
```

[source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1419)1.8.0
```
impl<'a> Iterator for EncodeUtf16<'a>
```

```
type Item = u16
```

[source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1516)1.34.0
```
impl<'a> Iterator for std::str::EscapeDebug<'a>
```

```
type Item = char
```

[source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1516)1.34.0
```
impl<'a> Iterator for std::str::EscapeDefault<'a>
```

```
type Item = char
```

[source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1516)1.34.0
```
impl<'a> Iterator for std::str::EscapeUnicode<'a>
```

```
type Item = char
```

[source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1110)
```
impl<'a> Iterator for std::str::Lines<'a>
```

```
type Item = &'a str
```

[source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1152)
```
impl<'a> Iterator for LinesAny<'a>
```

```
type Item = &'a str
```

[source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1275)1.34.0
```
impl<'a> Iterator for SplitAsciiWhitespace<'a>
```

```
type Item = &'a str
```

[source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1219)1.1.0
```
impl<'a> Iterator for SplitWhitespace<'a>
```

```
type Item = &'a str
```

[source](https://doc.rust-lang.org/src/core/str/lossy.rs.html#164)
```
impl<'a> Iterator for Utf8Chunks<'a>
```

```
type Item = Utf8Chunk<'a>
```

[source](https://doc.rust-lang.org/src/core/option.rs.html#2215)
```
impl<'a, A> Iterator for std::option::Iter<'a, A>
```

```
type Item = &'a A
```

[source](https://doc.rust-lang.org/src/core/option.rs.html#2265)
```
impl<'a, A> Iterator for std::option::IterMut<'a, A>
```

```
type Item = &'a mut A
```

[source](https://doc.rust-lang.org/src/core/iter/adapters/cloned.rs.html#32)1.1.0
```
impl<'a, I, T> Iterator for Cloned<I>
where
    T: 'a + Clone,
    I: Iterator<Item = &'a T>,
```

```
type Item = T
```

[source](https://doc.rust-lang.org/src/core/iter/adapters/copied.rs.html#40)1.36.0
```
impl<'a, I, T> Iterator for Copied<I>
where
    T: 'a + Copy,
    I: Iterator<Item = &'a T>,
```

```
type Item = T
```

[source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1550-1561)
```
impl<'a, K> Iterator for std::collections::hash_set::Drain<'a, K>
```

```
type Item = K
```

[source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1490-1501)
```
impl<'a, K> Iterator for std::collections::hash_set::Iter<'a, K>
```

```
type Item = &'a K
```

[source](https://doc.rust-lang.org/src/alloc/collections/btree/map.rs.html#1526)
```
impl<'a, K, V> Iterator for std::collections::btree_map::Iter<'a, K, V>
where
    K: 'a,
    V: 'a,
```

```
type Item = (&'a K, &'a V)
```

[source](https://doc.rust-lang.org/src/alloc/collections/btree/map.rs.html#1601)
```
impl<'a, K, V> Iterator for std::collections::btree_map::IterMut<'a, K, V>
```

```
type Item = (&'a K, &'a mut V)
```

[source](https://doc.rust-lang.org/src/alloc/collections/btree/map.rs.html#1779)
```
impl<'a, K, V> Iterator for std::collections::btree_map::Keys<'a, K, V>
```

```
type Item = &'a K
```

[source](https://doc.rust-lang.org/src/alloc/collections/btree/map.rs.html#2018)1.17.0
```
impl<'a, K, V> Iterator for std::collections::btree_map::Range<'a, K, V>
```

```
type Item = (&'a K, &'a V)
```

[source](https://doc.rust-lang.org/src/alloc/collections/btree/map.rs.html#2226)1.17.0
```
impl<'a, K, V> Iterator for RangeMut<'a, K, V>
```

```
type Item = (&'a K, &'a mut V)
```

[source](https://doc.rust-lang.org/src/alloc/collections/btree/map.rs.html#1848)
```
impl<'a, K, V> Iterator for std::collections::btree_map::Values<'a, K, V>
```

```
type Item = &'a V
```

[source](https://doc.rust-lang.org/src/alloc/collections/btree/map.rs.html#2059)1.10.0
```
impl<'a, K, V> Iterator for std::collections::btree_map::ValuesMut<'a, K, V>
```

```
type Item = &'a mut V
```

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#2449-2460)1.6.0
```
impl<'a, K, V> Iterator for std::collections::hash_map::Drain<'a, K, V>
```

```
type Item = (K, V)
```

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#2225-2236)
```
impl<'a, K, V> Iterator for std::collections::hash_map::Iter<'a, K, V>
```

```
type Item = (&'a K, &'a V)
```

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#2249-2260)
```
impl<'a, K, V> Iterator for std::collections::hash_map::IterMut<'a, K, V>
```

```
type Item = (&'a K, &'a mut V)
```

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#2313-2324)
```
impl<'a, K, V> Iterator for std::collections::hash_map::Keys<'a, K, V>
```

```
type Item = &'a K
```

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#2336-2347)
```
impl<'a, K, V> Iterator for std::collections::hash_map::Values<'a, K, V>
```

```
type Item = &'a V
```

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#2359-2370)1.10.0
```
impl<'a, K, V> Iterator for std::collections::hash_map::ValuesMut<'a, K, V>
```

```
type Item = &'a mut V
```

[source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1023-1039)1.5.0
```
impl<'a, P> Iterator for MatchIndices<'a, P>
where
    P: Pattern<'a>,
```

```
type Item = (usize, &'a str)
```

[source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1080-1096)1.2.0
```
impl<'a, P> Iterator for Matches<'a, P>
where
    P: Pattern<'a>,
```

```
type Item = &'a str
```

[source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1023-1039)1.5.0
```
impl<'a, P> Iterator for RMatchIndices<'a, P>
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
```

```
type Item = (usize, &'a str)
```

[source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1080-1096)1.2.0
```
impl<'a, P> Iterator for RMatches<'a, P>
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
```

```
type Item = &'a str
```

[source](https://doc.rust-lang.org/src/core/str/iter.rs.html#731-747)
```
impl<'a, P> Iterator for std::str::RSplit<'a, P>
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
```

```
type Item = &'a str
```

[source](https://doc.rust-lang.org/src/core/str/iter.rs.html#922-938)
```
impl<'a, P> Iterator for std::str::RSplitN<'a, P>
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
```

```
type Item = &'a str
```

[source](https://doc.rust-lang.org/src/core/str/iter.rs.html#795-811)
```
impl<'a, P> Iterator for RSplitTerminator<'a, P>
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
```

```
type Item = &'a str
```

[source](https://doc.rust-lang.org/src/core/str/iter.rs.html#731-747)
```
impl<'a, P> Iterator for std::str::Split<'a, P>
where
    P: Pattern<'a>,
```

```
type Item = &'a str
```

[source](https://doc.rust-lang.org/src/core/str/iter.rs.html#1338)1.51.0
```
impl<'a, P> Iterator for std::str::SplitInclusive<'a, P>
where
    P: Pattern<'a>,
```

```
type Item = &'a str
```

[source](https://doc.rust-lang.org/src/core/str/iter.rs.html#922-938)
```
impl<'a, P> Iterator for std::str::SplitN<'a, P>
where
    P: Pattern<'a>,
```

```
type Item = &'a str
```

[source](https://doc.rust-lang.org/src/core/str/iter.rs.html#795-811)
```
impl<'a, P> Iterator for SplitTerminator<'a, P>
where
    P: Pattern<'a>,
```

```
type Item = &'a str
```

[source](https://doc.rust-lang.org/src/alloc/collections/binary_heap/mod.rs.html#1377)
```
impl<'a, T> Iterator for std::collections::binary_heap::Iter<'a, T>
```

```
type Item = &'a T
```

[source](https://doc.rust-lang.org/src/alloc/collections/btree/set.rs.html#1489)
```
impl<'a, T> Iterator for std::collections::btree_set::Iter<'a, T>
```

```
type Item = &'a T
```

[source](https://doc.rust-lang.org/src/alloc/collections/btree/set.rs.html#1602)1.17.0
```
impl<'a, T> Iterator for std::collections::btree_set::Range<'a, T>
```

```
type Item = &'a T
```

[source](https://doc.rust-lang.org/src/alloc/collections/btree/set.rs.html#1726)
```
impl<'a, T> Iterator for std::collections::btree_set::SymmetricDifference<'a, T>
where
    T: Ord,
```

```
type Item = &'a T
```

[source](https://doc.rust-lang.org/src/alloc/collections/btree/set.rs.html#1821)
```
impl<'a, T> Iterator for std::collections::btree_set::Union<'a, T>
where
    T: Ord,
```

```
type Item = &'a T
```

[source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1087)
```
impl<'a, T> Iterator for std::collections::linked_list::Iter<'a, T>
```

```
type Item = &'a T
```

[source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1155)
```
impl<'a, T> Iterator for std::collections::linked_list::IterMut<'a, T>
```

```
type Item = &'a mut T
```

[source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter.rs.html#40)
```
impl<'a, T> Iterator for std::collections::vec_deque::Iter<'a, T>
```

```
type Item = &'a T
```

[source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/iter_mut.rs.html#32)
```
impl<'a, T> Iterator for std::collections::vec_deque::IterMut<'a, T>
```

```
type Item = &'a mut T
```

[source](https://doc.rust-lang.org/src/core/result.rs.html#1756)
```
impl<'a, T> Iterator for std::result::Iter<'a, T>
```

```
type Item = &'a T
```

[source](https://doc.rust-lang.org/src/core/result.rs.html#1805)
```
impl<'a, T> Iterator for std::result::IterMut<'a, T>
```

```
type Item = &'a mut T
```

[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#1465)
```
impl<'a, T> Iterator for Chunks<'a, T>
```

```
type Item = &'a [T]
```

[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#1865)1.31.0
```
impl<'a, T> Iterator for ChunksExact<'a, T>
```

```
type Item = &'a [T]
```

[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#2023)1.31.0
```
impl<'a, T> Iterator for ChunksExactMut<'a, T>
```

```
type Item = &'a mut [T]
```

[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#1647)
```
impl<'a, T> Iterator for ChunksMut<'a, T>
```

```
type Item = &'a mut [T]
```

[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#131-139)
```
impl<'a, T> Iterator for std::slice::Iter<'a, T>
```

```
type Item = &'a T
```

[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#363)
```
impl<'a, T> Iterator for std::slice::IterMut<'a, T>
```

```
type Item = &'a mut T
```

[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#2543)1.31.0
```
impl<'a, T> Iterator for RChunks<'a, T>
```

```
type Item = &'a [T]
```

[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#2937)1.31.0
```
impl<'a, T> Iterator for RChunksExact<'a, T>
```

```
type Item = &'a [T]
```

[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#3097)1.31.0
```
impl<'a, T> Iterator for RChunksExactMut<'a, T>
```

```
type Item = &'a mut [T]
```

[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#2715)1.31.0
```
impl<'a, T> Iterator for RChunksMut<'a, T>
```

```
type Item = &'a mut [T]
```

[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#1317)
```
impl<'a, T> Iterator for Windows<'a, T>
```

```
type Item = &'a [T]
```

[source](https://doc.rust-lang.org/src/std/sync/mpsc/mod.rs.html#1055-1061)
```
impl<'a, T> Iterator for std::sync::mpsc::Iter<'a, T>
```

```
type Item = T
```

[source](https://doc.rust-lang.org/src/std/sync/mpsc/mod.rs.html#1064-1070)1.15.0
```
impl<'a, T> Iterator for TryIter<'a, T>
```

```
type Item = T
```

[source](https://doc.rust-lang.org/src/alloc/collections/btree/set.rs.html#1670)
```
impl<'a, T, A> Iterator for std::collections::btree_set::Difference<'a, T, A>
where
    T: Ord,
    A: Allocator + Clone,
```

```
type Item = &'a T
```

[source](https://doc.rust-lang.org/src/alloc/collections/btree/set.rs.html#1771)
```
impl<'a, T, A> Iterator for std::collections::btree_set::Intersection<'a, T, A>
where
    T: Ord,
    A: Allocator + Clone,
```

```
type Item = &'a T
```

[source](https://doc.rust-lang.org/src/alloc/collections/btree/set.rs.html#1317)
```
impl<'a, T, F, A> Iterator for std::collections::btree_set::DrainFilter<'_, T, F, A>
where
    A: Allocator + Clone,
    F: 'a + FnMut(&T) -> bool,
```

```
type Item = T
```

[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#3261)
```
impl<'a, T, P> Iterator for GroupBy<'a, T, P>
where
    T: 'a,
    P: FnMut(&T, &T) -> bool,
```

```
type Item = &'a [T]
```

[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#3348)
```
impl<'a, T, P> Iterator for GroupByMut<'a, T, P>
where
    T: 'a,
    P: FnMut(&T, &T) -> bool,
```

```
type Item = &'a mut [T]
```

[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#948)1.27.0
```
impl<'a, T, P> Iterator for std::slice::RSplit<'a, T, P>
where
    P: FnMut(&T) -> bool,
```

```
type Item = &'a [T]
```

[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#1045)1.27.0
```
impl<'a, T, P> Iterator for RSplitMut<'a, T, P>
where
    P: FnMut(&T) -> bool,
```

```
type Item = &'a mut [T]
```

[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#1276)
```
impl<'a, T, P> Iterator for std::slice::RSplitN<'a, T, P>
where
    P: FnMut(&T) -> bool,
```

```
type Item = &'a [T]
```

[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#1278)
```
impl<'a, T, P> Iterator for RSplitNMut<'a, T, P>
where
    P: FnMut(&T) -> bool,
```

```
type Item = &'a mut [T]
```

[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#444)
```
impl<'a, T, P> Iterator for std::slice::Split<'a, T, P>
where
    P: FnMut(&T) -> bool,
```

```
type Item = &'a [T]
```

[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#577)1.51.0
```
impl<'a, T, P> Iterator for std::slice::SplitInclusive<'a, T, P>
where
    P: FnMut(&T) -> bool,
```

```
type Item = &'a [T]
```

[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#816)1.51.0
```
impl<'a, T, P> Iterator for SplitInclusiveMut<'a, T, P>
where
    P: FnMut(&T) -> bool,
```

```
type Item = &'a mut [T]
```

[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#698)
```
impl<'a, T, P> Iterator for SplitMut<'a, T, P>
where
    P: FnMut(&T) -> bool,
```

```
type Item = &'a mut [T]
```

[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#1275)
```
impl<'a, T, P> Iterator for std::slice::SplitN<'a, T, P>
where
    P: FnMut(&T) -> bool,
```

```
type Item = &'a [T]
```

[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#1277)
```
impl<'a, T, P> Iterator for SplitNMut<'a, T, P>
where
    P: FnMut(&T) -> bool,
```

```
type Item = &'a mut [T]
```

[source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1670-1692)
```
impl<'a, T, S> Iterator for std::collections::hash_set::Difference<'a, T, S>
where
    T: Eq + Hash,
    S: BuildHasher,
```

```
type Item = &'a T
```

[source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1618-1640)
```
impl<'a, T, S> Iterator for std::collections::hash_set::Intersection<'a, T, S>
where
    T: Eq + Hash,
    S: BuildHasher,
```

```
type Item = &'a T
```

[source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1722-1737)
```
impl<'a, T, S> Iterator for std::collections::hash_set::SymmetricDifference<'a, T, S>
where
    T: Eq + Hash,
    S: BuildHasher,
```

```
type Item = &'a T
```

[source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1786-1801)
```
impl<'a, T, S> Iterator for std::collections::hash_set::Union<'a, T, S>
where
    T: Eq + Hash,
    S: BuildHasher,
```

```
type Item = &'a T
```

[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#2313)
```
impl<'a, T, const N: usize> Iterator for std::slice::ArrayChunks<'a, T, N>
```

```
type Item = &'a [T; N]
```

[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#2431)
```
impl<'a, T, const N: usize> Iterator for ArrayChunksMut<'a, T, N>
```

```
type Item = &'a mut [T; N]
```

[source](https://doc.rust-lang.org/src/core/slice/iter.rs.html#2174)
```
impl<'a, T, const N: usize> Iterator for ArrayWindows<'a, T, N>
```

```
type Item = &'a [T; N]
```

[source](https://doc.rust-lang.org/src/core/iter/range.rs.html#706)
```
impl<A> Iterator for std::ops::Range<A>
where
    A: Step,
```

```
type Item = A
```

[source](https://doc.rust-lang.org/src/core/iter/range.rs.html#865)
```
impl<A> Iterator for RangeFrom<A>
where
    A: Step,
```

```
type Item = A
```

[source](https://doc.rust-lang.org/src/core/iter/range.rs.html#1101)1.26.0
```
impl<A> Iterator for RangeInclusive<A>
where
    A: Step,
```

```
type Item = A
```

[source](https://doc.rust-lang.org/src/core/option.rs.html#2306)
```
impl<A> Iterator for std::option::IntoIter<A>
```

```
type Item = A
```

[source](https://doc.rust-lang.org/src/core/iter/sources/repeat.rs.html#70)
```
impl<A> Iterator for Repeat<A>
where
    A: Clone,
```

```
type Item = A
```

[source](https://doc.rust-lang.org/src/core/iter/adapters/chain.rs.html#42)
```
impl<A, B> Iterator for Chain<A, B>
where
    A: Iterator,
    B: Iterator<Item = <A as Iterator>::Item>,
```

```
type Item = <A as Iterator>::Item
```

[source](https://doc.rust-lang.org/src/core/iter/adapters/zip.rs.html#75)
```
impl<A, B> Iterator for Zip<A, B>
where
    A: Iterator,
    B: Iterator,
```

```
type Item = (<A as Iterator>::Item, <B as Iterator>::Item)
```

[source](https://doc.rust-lang.org/src/core/iter/sources/once_with.rs.html#88)1.43.0
```
impl<A, F> Iterator for OnceWith<F>
where
    F: FnOnce() -> A,
```

```
type Item = A
```

[source](https://doc.rust-lang.org/src/core/iter/sources/repeat_with.rs.html#88)1.28.0
```
impl<A, F> Iterator for RepeatWith<F>
where
    F: FnMut() -> A,
```

```
type Item = A
```

[source](https://doc.rust-lang.org/src/core/iter/adapters/filter_map.rs.html#54)
```
impl<B, I, F> Iterator for FilterMap<I, F>
where
    I: Iterator,
    F: FnMut(<I as Iterator>::Item) -> Option<B>,
```

```
type Item = B
```

[source](https://doc.rust-lang.org/src/core/iter/adapters/map.rs.html#95)
```
impl<B, I, F> Iterator for Map<I, F>
where
    I: Iterator,
    F: FnMut(<I as Iterator>::Item) -> B,
```

```
type Item = B
```

[source](https://doc.rust-lang.org/src/core/iter/adapters/map_while.rs.html#34)1.57.0
```
impl<B, I, P> Iterator for MapWhile<I, P>
where
    I: Iterator,
    P: FnMut(<I as Iterator>::Item) -> Option<B>,
```

```
type Item = B
```

[source](https://doc.rust-lang.org/src/core/iter/adapters/scan.rs.html#35)
```
impl<B, I, St, F> Iterator for Scan<I, St, F>
where
    I: Iterator,
    F: FnMut(&mut St, <I as Iterator>::Item) -> Option<B>,
```

```
type Item = B
```

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#2851-2870)
```
impl<B: BufRead> Iterator for std::io::Lines<B>
```

```
type Item = Result<String, Error>
```

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#2820-2836)
```
impl<B: BufRead> Iterator for std::io::Split<B>
```

```
type Item = Result<Vec<u8, Global>, Error>
```

[source](https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#4006)
```
impl<I> Iterator for &mut I
where
    I: Iterator + ?Sized,
```

```
type Item = <I as Iterator>::Item
```

[source](https://doc.rust-lang.org/src/core/char/decode.rs.html#39)1.9.0
```
impl<I> Iterator for DecodeUtf16<I>
where
    I: Iterator<Item = u16>,
```

```
type Item = Result<char, DecodeUtf16Error>
```

[source](https://doc.rust-lang.org/src/core/iter/adapters/by_ref_sized.rs.html#16)
```
impl<I> Iterator for ByRefSized<'_, I>
where
    I: Iterator,
```

```
type Item = <I as Iterator>::Item
```

[source](https://doc.rust-lang.org/src/core/iter/adapters/cycle.rs.html#26)
```
impl<I> Iterator for Cycle<I>
where
    I: Clone + Iterator,
```

```
type Item = <I as Iterator>::Item
```

[source](https://doc.rust-lang.org/src/core/iter/adapters/enumerate.rs.html#29)
```
impl<I> Iterator for Enumerate<I>
where
    I: Iterator,
```

```
type Item = (usize, <I as Iterator>::Item)
```

[source](https://doc.rust-lang.org/src/core/iter/adapters/fuse.rs.html#35)
```
impl<I> Iterator for Fuse<I>
where
    I: Iterator,
```

```
type Item = <I as Iterator>::Item
```

[source](https://doc.rust-lang.org/src/core/iter/adapters/intersperse.rs.html#28)
```
impl<I> Iterator for Intersperse<I>
where
    I: Iterator,
    <I as Iterator>::Item: Clone,
```

```
type Item = <I as Iterator>::Item
```

[source](https://doc.rust-lang.org/src/core/iter/adapters/peekable.rs.html#32)
```
impl<I> Iterator for Peekable<I>
where
    I: Iterator,
```

```
type Item = <I as Iterator>::Item
```

[source](https://doc.rust-lang.org/src/core/iter/adapters/rev.rs.html#26)
```
impl<I> Iterator for Rev<I>
where
    I: DoubleEndedIterator,
```

```
type Item = <I as Iterator>::Item
```

[source](https://doc.rust-lang.org/src/core/iter/adapters/skip.rs.html#28)
```
impl<I> Iterator for Skip<I>
where
    I: Iterator,
```

```
type Item = <I as Iterator>::Item
```

[source](https://doc.rust-lang.org/src/core/iter/adapters/step_by.rs.html#27)1.28.0
```
impl<I> Iterator for StepBy<I>
where
    I: Iterator,
```

```
type Item = <I as Iterator>::Item
```

[source](https://doc.rust-lang.org/src/core/iter/adapters/take.rs.html#28)
```
impl<I> Iterator for Take<I>
where
    I: Iterator,
```

```
type Item = <I as Iterator>::Item
```

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1916)
```
impl<I, A> Iterator for Box<I, A>
where
    I: Iterator + ?Sized,
    A: Allocator,
```

```
type Item = <I as Iterator>::Item
```

[source](https://doc.rust-lang.org/src/alloc/vec/splice.rs.html#31)1.21.0
```
impl<I, A> Iterator for Splice<'_, I, A>
where
    I: Iterator,
    A: Allocator,
```

```
type Item = <I as Iterator>::Item
```

[source](https://doc.rust-lang.org/src/core/iter/adapters/inspect.rs.html#68)
```
impl<I, F> Iterator for Inspect<I, F>
where
    I: Iterator,
    F: FnMut(&<I as Iterator>::Item),
```

```
type Item = <I as Iterator>::Item
```

[source](https://doc.rust-lang.org/src/core/iter/adapters/intersperse.rs.html#117)
```
impl<I, G> Iterator for IntersperseWith<I, G>
where
    I: Iterator,
    G: FnMut() -> <I as Iterator>::Item,
```

```
type Item = <I as Iterator>::Item
```

[source](https://doc.rust-lang.org/src/core/iter/adapters/filter.rs.html#51)
```
impl<I, P> Iterator for Filter<I, P>
where
    I: Iterator,
    P: FnMut(&<I as Iterator>::Item) -> bool,
```

```
type Item = <I as Iterator>::Item
```

[source](https://doc.rust-lang.org/src/core/iter/adapters/skip_while.rs.html#35)
```
impl<I, P> Iterator for SkipWhile<I, P>
where
    I: Iterator,
    P: FnMut(&<I as Iterator>::Item) -> bool,
```

```
type Item = <I as Iterator>::Item
```

[source](https://doc.rust-lang.org/src/core/iter/adapters/take_while.rs.html#35)
```
impl<I, P> Iterator for TakeWhile<I, P>
where
    I: Iterator,
    P: FnMut(&<I as Iterator>::Item) -> bool,
```

```
type Item = <I as Iterator>::Item
```

[source](https://doc.rust-lang.org/src/core/iter/adapters/flatten.rs.html#190)1.29.0
```
impl<I, U> Iterator for Flatten<I>
where
    I: Iterator,
    <I as Iterator>::Item: IntoIterator<IntoIter = U, Item = <U as Iterator>::Item>,
    U: Iterator,
```

```
type Item = <U as Iterator>::Item
```

[source](https://doc.rust-lang.org/src/core/iter/adapters/flatten.rs.html#44)
```
impl<I, U, F> Iterator for FlatMap<I, U, F>
where
    I: Iterator,
    U: IntoIterator,
    F: FnMut(<I as Iterator>::Item) -> U,
```

```
type Item = <U as IntoIterator>::Item
```

[source](https://doc.rust-lang.org/src/core/iter/adapters/array_chunks.rs.html#41)
```
impl<I, const N: usize> Iterator for std::iter::ArrayChunks<I, N>
where
    I: Iterator,
```

```
type Item = [<I as Iterator>::Item; N]
```

[source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1520-1531)
```
impl<K> Iterator for std::collections::hash_set::IntoIter<K>
```

```
type Item = K
```

[source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1580-1594)
```
impl<K, F> Iterator for std::collections::hash_set::DrainFilter<'_, K, F>
where
    F: FnMut(&K) -> bool,
```

```
type Item = K
```

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#2283-2294)
```
impl<K, V> Iterator for std::collections::hash_map::IntoIter<K, V>
```

```
type Item = (K, V)
```

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#2389-2400)1.54.0
```
impl<K, V> Iterator for std::collections::hash_map::IntoKeys<K, V>
```

```
type Item = K
```

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#2419-2430)1.54.0
```
impl<K, V> Iterator for std::collections::hash_map::IntoValues<K, V>
```

```
type Item = V
```

[source](https://doc.rust-lang.org/src/alloc/collections/btree/map.rs.html#1747)
```
impl<K, V, A> Iterator for std::collections::btree_map::IntoIter<K, V, A>
where
    A: Allocator + Clone,
```

```
type Item = (K, V)
```

[source](https://doc.rust-lang.org/src/alloc/collections/btree/map.rs.html#2093)1.54.0
```
impl<K, V, A> Iterator for std::collections::btree_map::IntoKeys<K, V, A>
where
    A: Allocator + Clone,
```

```
type Item = K
```

[source](https://doc.rust-lang.org/src/alloc/collections/btree/map.rs.html#2158)1.54.0
```
impl<K, V, A> Iterator for std::collections::btree_map::IntoValues<K, V, A>
where
    A: Allocator + Clone,
```

```
type Item = V
```

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#2483-2497)
```
impl<K, V, F> Iterator for std::collections::hash_map::DrainFilter<'_, K, V, F>
where
    F: FnMut(&K, &mut V) -> bool,
```

```
type Item = (K, V)
```

[source](https://doc.rust-lang.org/src/alloc/collections/btree/map.rs.html#1955)
```
impl<K, V, F, A> Iterator for std::collections::btree_map::DrainFilter<'_, K, V, F, A>
where
    A: Allocator + Clone,
    F: FnMut(&K, &mut V) -> bool,
```

```
type Item = (K, V)
```

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#2727-2745)
```
impl<R: Read> Iterator for std::io::Bytes<R>
```

```
type Item = Result<u8, Error>
```

[source](https://doc.rust-lang.org/src/alloc/collections/binary_heap/mod.rs.html#1550)1.6.0
```
impl<T> Iterator for std::collections::binary_heap::Drain<'_, T>
```

```
type Item = T
```

[source](https://doc.rust-lang.org/src/alloc/collections/binary_heap/mod.rs.html#1615)
```
impl<T> Iterator for DrainSorted<'_, T>
where
    T: Ord,
```

```
type Item = T
```

[source](https://doc.rust-lang.org/src/alloc/collections/binary_heap/mod.rs.html#1434)
```
impl<T> Iterator for std::collections::binary_heap::IntoIter<T>
```

```
type Item = T
```

[source](https://doc.rust-lang.org/src/alloc/collections/binary_heap/mod.rs.html#1513)
```
impl<T> Iterator for IntoIterSorted<T>
where
    T: Ord,
```

```
type Item = T
```

[source](https://doc.rust-lang.org/src/core/result.rs.html#1851)
```
impl<T> Iterator for std::result::IntoIter<T>
```

```
type Item = T
```

[source](https://doc.rust-lang.org/src/std/sync/mpsc/mod.rs.html#1083-1088)1.1.0
```
impl<T> Iterator for std::sync::mpsc::IntoIter<T>
```

```
type Item = T
```

[source](https://doc.rust-lang.org/src/core/iter/sources/empty.rs.html#40)1.2.0
```
impl<T> Iterator for Empty<T>
```

```
type Item = T
```

[source](https://doc.rust-lang.org/src/core/iter/sources/once.rs.html#69)1.2.0
```
impl<T> Iterator for Once<T>
```

```
type Item = T
```

[source](https://doc.rust-lang.org/src/alloc/collections/btree/set.rs.html#1535)
```
impl<T, A> Iterator for std::collections::btree_set::IntoIter<T, A>
where
    A: Allocator + Clone,
```

```
type Item = T
```

[source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1890)
```
impl<T, A> Iterator for std::collections::linked_list::IntoIter<T, A>
where
    A: Allocator,
```

```
type Item = T
```

[source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/drain.rs.html#179)1.6.0
```
impl<T, A> Iterator for std::collections::vec_deque::Drain<'_, T, A>
where
    A: Allocator,
```

```
type Item = T
```

[source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/into_iter.rs.html#42)
```
impl<T, A> Iterator for std::collections::vec_deque::IntoIter<T, A>
where
    A: Allocator,
```

```
type Item = T
```

[source](https://doc.rust-lang.org/src/alloc/vec/drain.rs.html#152)1.6.0
```
impl<T, A> Iterator for std::vec::Drain<'_, T, A>
where
    A: Allocator,
```

```
type Item = T
```

[source](https://doc.rust-lang.org/src/alloc/vec/into_iter.rs.html#184)
```
impl<T, A> Iterator for std::vec::IntoIter<T, A>
where
    A: Allocator,
```

```
type Item = T
```

[source](https://doc.rust-lang.org/src/core/iter/sources/from_fn.rs.html#61)1.34.0
```
impl<T, F> Iterator for FromFn<F>
where
    F: FnMut() -> Option<T>,
```

```
type Item = T
```

[source](https://doc.rust-lang.org/src/core/iter/sources/successors.rs.html#39)1.34.0
```
impl<T, F> Iterator for Successors<T, F>
where
    F: FnMut(&T) -> Option<T>,
```

```
type Item = T
```

[source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#1824)
```
impl<T, F, A> Iterator for std::collections::linked_list::DrainFilter<'_, T, F, A>
where
    A: Allocator,
    F: FnMut(&mut T) -> bool,
```

```
type Item = T
```

[source](https://doc.rust-lang.org/src/alloc/vec/drain_filter.rs.html#114)
```
impl<T, F, A> Iterator for std::vec::DrainFilter<'_, T, F, A>
where
    A: Allocator,
    F: FnMut(&mut T) -> bool,
```

```
type Item = T
```

[source](https://doc.rust-lang.org/src/core/array/iter.rs.html#236)1.40.0
```
impl<T, const N: usize> Iterator for std::array::IntoIter<T, N>
```

```
type Item = T
```



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/iter/trait.Iterator.html>

Primitive Type array
====================


A fixed-size array, denoted `[T; N]`, for the element type, `T`, and the non-negative compile-time constant size, `N`.

 There are two syntactic forms for creating an array:

 * A list with each element, i.e., `[x, y, z]`.
* A repeat expression `[expr; N]` where `N` is how many times to repeat `expr` in the array. `expr` must either be:


	+ A value of a type implementing the [`Copy`](marker/trait.copy "trait std::marker::Copy") trait
	+ A `const` value

 Note that `[expr; 0]` is allowed, and produces an empty array. This will still evaluate `expr`, however, and immediately drop the resulting value, so be mindful of side effects.

 Arrays of *any* size implement the following traits if the element type allows it:

 * [`Copy`](marker/trait.copy "trait std::marker::Copy")
* [`Clone`](clone/trait.clone "trait std::clone::Clone")
* [`Debug`](fmt/trait.debug "trait std::fmt::Debug")
* [`IntoIterator`](iter/trait.intoiterator "trait std::iter::IntoIterator") (implemented for `[T; N]`, `&[T; N]` and `&mut [T; N]`)
* [`PartialEq`](cmp/trait.partialeq "trait std::cmp::PartialEq"), [`PartialOrd`](cmp/trait.partialord "trait std::cmp::PartialOrd"), [`Eq`](cmp/trait.eq "trait std::cmp::Eq"), [`Ord`](cmp/trait.ord "trait std::cmp::Ord")
* [`Hash`](hash/trait.hash "trait std::hash::Hash")
* [`AsRef`](convert/trait.asref "trait std::convert::AsRef"), [`AsMut`](convert/trait.asmut "trait std::convert::AsMut")
* [`Borrow`](borrow/trait.borrow "trait std::borrow::Borrow"), [`BorrowMut`](borrow/trait.borrowmut "trait std::borrow::BorrowMut")

 Arrays of sizes from 0 to 32 (inclusive) implement the [`Default`](default/trait.default "trait std::default::Default") trait if the element type allows it. As a stopgap, trait implementations are statically generated up to size 32.

 Arrays of sizes from 1 to 12 (inclusive) implement [`From<Tuple>`](convert/trait.from "trait std::convert::From"), where `Tuple` is a homogenous [tuple](primitive.tuple "primitive tuple") of appropriate length.

 Arrays coerce to [slices (`[T]`)](primitive.slice "primitive slice"), so a slice method may be called on an array. Indeed, this provides most of the API for working with arrays.

 Slices have a dynamic size and do not coerce to arrays. Instead, use `slice.try_into().unwrap()` or `<ArrayType>::try_from(slice).unwrap()`.

 Array’s `try_from(slice)` implementations (and the corresponding `slice.try_into()` array implementations) succeed if the input slice length is the same as the result array length. They optimize especially well when the optimizer can easily determine the slice length, e.g. `<[u8; 4]>::try_from(&slice[4..8]).unwrap()`. Array implements [TryFrom](convert/trait.tryfrom "trait std::convert::TryFrom") returning:

 * `[T; N]` copies from the slice’s elements
* `&[T; N]` references the original slice’s elements
* `&mut [T; N]` references the original slice’s elements

 You can move elements out of an array with a [slice pattern](../reference/patterns#slice-patterns). If you want one element, see [`mem::replace`](mem/fn.replace "fn std::mem::replace").

 Examples
--------

 
```
let mut array: [i32; 3] = [0; 3];

array[1] = 1;
array[2] = 2;

assert_eq!([1, 2], &array[1..]);

// This loop prints: 0 1 2
for x in array {
    print!("{x} ");
}
```
 You can also iterate over reference to the array’s elements:

 
```
let array: [i32; 3] = [0; 3];

for x in &array { }
```
 You can use `<ArrayType>::try_from(slice)` or `slice.try_into()` to get an array from a slice:

 
```
let bytes: [u8; 3] = [1, 0, 2];
assert_eq!(1, u16::from_le_bytes(<[u8; 2]>::try_from(&bytes[0..2]).unwrap()));
assert_eq!(512, u16::from_le_bytes(bytes[1..3].try_into().unwrap()));
```
 You can use a [slice pattern](../reference/patterns#slice-patterns) to move elements out of an array:

 
```
fn move_away(_: String) { /* Do interesting things. */ }

let [john, roa] = ["John".to_string(), "Roa".to_string()];
move_away(john);
move_away(roa);
```
 Arrays can be created from homogenous tuples of appropriate length:

 
```
let tuple: (u32, u32, u32) = (1, 2, 3);
let array: [u32; 3] = tuple.into();
```
 Editions
--------

 Prior to Rust 1.53, arrays did not implement [`IntoIterator`](iter/trait.intoiterator "trait std::iter::IntoIterator") by value, so the method call `array.into_iter()` auto-referenced into a [slice iterator](primitive.slice#method.iter "method slice::iter"). Right now, the old behavior is preserved in the 2015 and 2018 editions of Rust for compatibility, ignoring [`IntoIterator`](iter/trait.intoiterator "trait std::iter::IntoIterator") by value. In the future, the behavior on the 2015 and 2018 edition might be made consistent to the behavior of later editions.

 ⓘ
```
// Rust 2015 and 2018:

let array: [i32; 3] = [0; 3];

// This creates a slice iterator, producing references to each value.
for item in array.into_iter().enumerate() {
    let (i, x): (usize, &i32) = item;
    println!("array[{i}] = {x}");
}

// The `array_into_iter` lint suggests this change for future compatibility:
for item in array.iter().enumerate() {
    let (i, x): (usize, &i32) = item;
    println!("array[{i}] = {x}");
}

// You can explicitly iterate an array by value using `IntoIterator::into_iter`
for item in IntoIterator::into_iter(array).enumerate() {
    let (i, x): (usize, i32) = item;
    println!("array[{i}] = {x}");
}
```

 Starting in the 2021 edition, `array.into_iter()` uses `IntoIterator` normally to iterate by value, and `iter()` should be used to iterate by reference like previous editions.

 ⓘ
```
// Rust 2021:

let array: [i32; 3] = [0; 3];

// This iterates by reference:
for item in array.iter().enumerate() {
    let (i, x): (usize, &i32) = item;
    println!("array[{i}] = {x}");
}

// This iterates by value:
for item in array.into_iter().enumerate() {
    let (i, x): (usize, i32) = item;
    println!("array[{i}] = {x}");
}
```

 Future language versions might start treating the `array.into_iter()` syntax on editions 2015 and 2018 the same as on edition 2021. So code using those older editions should still be written with this change in mind, to prevent breakage in the future. The safest way to accomplish this is to avoid the `into_iter` syntax on those editions. If an edition update is not viable/desired, there are multiple alternatives:

 * use `iter`, equivalent to the old behavior, creating references
* use [`IntoIterator::into_iter`](iter/trait.intoiterator#tymethod.into_iter "method std::iter::IntoIterator::into_iter"), equivalent to the post-2021 behavior (Rust 1.53+)
* replace `for ... in array.into_iter() {` with `for ... in array {`, equivalent to the post-2021 behavior (Rust 1.53+)

 ⓘ
```
// Rust 2015 and 2018:

let array: [i32; 3] = [0; 3];

// This iterates by reference:
for item in array.iter() {
    let x: &i32 = item;
    println!("{x}");
}

// This iterates by value:
for item in IntoIterator::into_iter(array) {
    let x: i32 = item;
    println!("{x}");
}

// This iterates by value:
for item in array {
    let x: i32 = item;
    println!("{x}");
}

// IntoIter can also start a chain.
// This iterates by value:
for item in IntoIterator::into_iter(array).enumerate() {
    let (i, x): (usize, i32) = item;
    println!("array[{i}] = {x}");
}
```

 Implementations
---------------



[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#454)
```
impl<T, const N: usize> [T; N]
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#497-499)1.55.0
```
pub fn map<F, U>(self, f: F) -> [U; N]
where
    F: FnMut(T) -> U,
```

Returns an array of the same size as `self`, with function `f` applied to each element in order.

 If you don’t necessarily need a new fixed-size array, consider using [`Iterator::map`](iter/trait.iterator#method.map "method std::iter::Iterator::map") instead.

 ##### Note on performance and stack usage

 Unfortunately, usages of this method are currently not always optimized as well as they could be. This mainly concerns large arrays, as mapping over small arrays seem to be optimized just fine. Also note that in debug mode (i.e. without any optimizations), this method can use a lot of stack space (a few times the size of the array or more).

 Therefore, in performance-critical code, try to avoid using this method on large arrays or check the emitted code. Also try to avoid chained maps (e.g. `arr.map(...).map(...)`).

 In many cases, you can instead use [`Iterator::map`](iter/trait.iterator#method.map "method std::iter::Iterator::map") by calling `.iter()` or `.into_iter()` on your array. `[T; N]::map` is only necessary if you really need a new array of the same size as the result. Rust’s lazy iterators tend to get optimized very well.

 ##### Examples

 
```
let x = [1, 2, 3];
let y = x.map(|v| v + 1);
assert_eq!(y, [2, 3, 4]);

let x = [1, 2, 3];
let mut temp = 0;
let y = x.map(|v| { temp += 1; v * temp });
assert_eq!(y, [1, 4, 9]);

let x = ["Ferris", "Bueller's", "Day", "Off"];
let y = x.map(|v| v.len());
assert_eq!(y, [6, 9, 3, 3]);
```
 
[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#532-536)
```
pub fn try_map<F, R>(
    self,
    f: F
) -> <<R as Try>::Residual as Residual<[<R as Try>::Output; N]>>::TryType
where
    F: FnMut(T) -> R,
    R: Try,
    <R as Try>::Residual: Residual<[<R as Try>::Output; N]>,
```

🔬This is a nightly-only experimental API. (`array_try_map` [#79711](https://github.com/rust-lang/rust/issues/79711))

A fallible function `f` applied to each element on array `self` in order to return an array the same size as `self` or the first error encountered.

 The return type of this function depends on the return type of the closure. If you return `Result<T, E>` from the closure, you’ll get a `Result<[T; N], E>`. If you return `Option<T>` from the closure, you’ll get an `Option<[T; N]>`.

 ##### Examples

 
```
#![feature(array_try_map)]
let a = ["1", "2", "3"];
let b = a.try_map(|v| v.parse::<u32>()).unwrap().map(|v| v + 1);
assert_eq!(b, [2, 3, 4]);

let a = ["1", "2a", "3"];
let b = a.try_map(|v| v.parse::<u32>());
assert!(b.is_err());

use std::num::NonZeroU32;
let z = [1, 2, 0, 3, 4];
assert_eq!(z.try_map(NonZeroU32::new), None);
let a = [1, 2, 3];
let b = a.try_map(NonZeroU32::new);
let c = b.map(|x| x.map(NonZeroU32::get));
assert_eq!(c, Some(a));
```
 
[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#558)
```
pub fn zip<U>(self, rhs: [U; N]) -> [(T, U); N]
```

🔬This is a nightly-only experimental API. (`array_zip` [#80094](https://github.com/rust-lang/rust/issues/80094))

‘Zips up’ two arrays into a single array of pairs.

 `zip()` returns a new array where every element is a tuple where the first element comes from the first array, and the second element comes from the second array. In other words, it zips two arrays together, into a single one.

 ##### Examples

 
```
#![feature(array_zip)]
let x = [1, 2, 3];
let y = [4, 5, 6];
let z = x.zip(y);
assert_eq!(z, [(1, 4), (2, 5), (3, 6)]);
```
 
[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#567)1.57.0 (const: 1.57.0)
```
pub const fn as_slice(&self) -> &[T]
```

Returns a slice containing the entire array. Equivalent to `&s[..]`.

 
[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#574)1.57.0
```
pub fn as_mut_slice(&mut self) -> &mut [T]
```

Returns a mutable slice containing the entire array. Equivalent to `&mut s[..]`.

 
[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#607)
```
pub fn each_ref(&self) -> [&T; N]
```

🔬This is a nightly-only experimental API. (`array_methods` [#76118](https://github.com/rust-lang/rust/issues/76118))

Borrows each element and returns an array of references with the same size as `self`.

 ##### Example

 
```
#![feature(array_methods)]

let floats = [3.1, 2.7, -1.0];
let float_refs: [&f64; 3] = floats.each_ref();
assert_eq!(float_refs, [&3.1, &2.7, &-1.0]);
```
 This method is particularly useful if combined with other methods, like [`map`](#method.map). This way, you can avoid moving the original array if its elements are not [`Copy`](marker/trait.copy "trait std::marker::Copy").

 
```
#![feature(array_methods)]

let strings = ["Ferris".to_string(), "♥".to_string(), "Rust".to_string()];
let is_ascii = strings.each_ref().map(|s| s.is_ascii());
assert_eq!(is_ascii, [true, false, true]);

// We can still access the original array: it has not been moved.
assert_eq!(strings.len(), 3);
```
 
[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#627)
```
pub fn each_mut(&mut self) -> [&mut T; N]
```

🔬This is a nightly-only experimental API. (`array_methods` [#76118](https://github.com/rust-lang/rust/issues/76118))

Borrows each element mutably and returns an array of mutable references with the same size as `self`.

 ##### Example

 
```
#![feature(array_methods)]

let mut floats = [3.1, 2.7, -1.0];
let float_refs: [&mut f64; 3] = floats.each_mut();
*float_refs[0] = 0.0;
assert_eq!(float_refs, [&mut 0.0, &mut 2.7, &mut -1.0]);
assert_eq!(floats, [0.0, 2.7, -1.0]);
```
 
[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#672)
```
pub fn split_array_ref<const M: usize>(&self) -> (&[T; M], &[T])
```

🔬This is a nightly-only experimental API. (`split_array` [#90091](https://github.com/rust-lang/rust/issues/90091))

Divides one array reference into two at an index.

 The first will contain all indices from `[0, M)` (excluding the index `M` itself) and the second will contain all indices from `[M, N)` (excluding the index `N` itself).

 ##### Panics

 Panics if `M > N`.

 ##### Examples

 
```
#![feature(split_array)]

let v = [1, 2, 3, 4, 5, 6];

{
   let (left, right) = v.split_array_ref::<0>();
   assert_eq!(left, &[]);
   assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
}

{
    let (left, right) = v.split_array_ref::<2>();
    assert_eq!(left, &[1, 2]);
    assert_eq!(right, &[3, 4, 5, 6]);
}

{
    let (left, right) = v.split_array_ref::<6>();
    assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
    assert_eq!(right, &[]);
}
```
 
[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#705)
```
pub fn split_array_mut<const M: usize>(&mut self) -> (&mut [T; M], &mut [T])
```

🔬This is a nightly-only experimental API. (`split_array` [#90091](https://github.com/rust-lang/rust/issues/90091))

Divides one mutable array reference into two at an index.

 The first will contain all indices from `[0, M)` (excluding the index `M` itself) and the second will contain all indices from `[M, N)` (excluding the index `N` itself).

 ##### Panics

 Panics if `M > N`.

 ##### Examples

 
```
#![feature(split_array)]

let mut v = [1, 0, 3, 0, 5, 6];
let (left, right) = v.split_array_mut::<2>();
assert_eq!(left, &mut [1, 0][..]);
assert_eq!(right, &mut [3, 0, 5, 6]);
left[1] = 2;
right[1] = 4;
assert_eq!(v, [1, 2, 3, 4, 5, 6]);
```
 
[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#750)
```
pub fn rsplit_array_ref<const M: usize>(&self) -> (&[T], &[T; M])
```

🔬This is a nightly-only experimental API. (`split_array` [#90091](https://github.com/rust-lang/rust/issues/90091))

Divides one array reference into two at an index from the end.

 The first will contain all indices from `[0, N - M)` (excluding the index `N - M` itself) and the second will contain all indices from `[N - M, N)` (excluding the index `N` itself).

 ##### Panics

 Panics if `M > N`.

 ##### Examples

 
```
#![feature(split_array)]

let v = [1, 2, 3, 4, 5, 6];

{
   let (left, right) = v.rsplit_array_ref::<0>();
   assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
   assert_eq!(right, &[]);
}

{
    let (left, right) = v.rsplit_array_ref::<2>();
    assert_eq!(left, &[1, 2, 3, 4]);
    assert_eq!(right, &[5, 6]);
}

{
    let (left, right) = v.rsplit_array_ref::<6>();
    assert_eq!(left, &[]);
    assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
}
```
 
[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#783)
```
pub fn rsplit_array_mut<const M: usize>(&mut self) -> (&mut [T], &mut [T; M])
```

🔬This is a nightly-only experimental API. (`split_array` [#90091](https://github.com/rust-lang/rust/issues/90091))

Divides one mutable array reference into two at an index from the end.

 The first will contain all indices from `[0, N - M)` (excluding the index `N - M` itself) and the second will contain all indices from `[N - M, N)` (excluding the index `N` itself).

 ##### Panics

 Panics if `M > N`.

 ##### Examples

 
```
#![feature(split_array)]

let mut v = [1, 0, 3, 0, 5, 6];
let (left, right) = v.rsplit_array_mut::<4>();
assert_eq!(left, &mut [1, 0]);
assert_eq!(right, &mut [3, 0, 5, 6][..]);
left[1] = 2;
right[1] = 4;
assert_eq!(v, [1, 2, 3, 4, 5, 6]);
```
 

[source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#1294)
```
impl<T, const N: usize> [MaybeUninit<T>; N]
```

[source](https://doc.rust-lang.org/src/core/mem/maybe_uninit.rs.html#1308)
```
pub const fn transpose(self) -> MaybeUninit<[T; N]>
```

🔬This is a nightly-only experimental API. (`maybe_uninit_uninit_array_transpose` [#96097](https://github.com/rust-lang/rust/issues/96097))

Transposes a `[MaybeUninit<T>; N]` into a `MaybeUninit<[T; N]>`.

 ##### Examples

 
```
#![feature(maybe_uninit_uninit_array_transpose)]

let data = [MaybeUninit::<u8>::uninit(); 1000];
let data: MaybeUninit<[u8; 1000]> = data.transpose();
```
 

[source](https://doc.rust-lang.org/src/core/array/ascii.rs.html#4)
```
impl<const N: usize> [u8; N]
```

[source](https://doc.rust-lang.org/src/core/array/ascii.rs.html#23)
```
pub const fn as_ascii(&self) -> Option<&[AsciiChar; N]>
```

🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998))

Converts this array of bytes into a array of ASCII characters, or returns `None` if any of the characters is non-ASCII.

 ##### Examples

 
```
#![feature(ascii_char)]
#![feature(const_option)]

const HEX_DIGITS: [std::ascii::Char; 16] =
    *b"0123456789abcdef".as_ascii().unwrap();

assert_eq!(HEX_DIGITS[1].as_str(), "1");
assert_eq!(HEX_DIGITS[10].as_str(), "a");
```
 
[source](https://doc.rust-lang.org/src/core/array/ascii.rs.html#41)
```
pub const unsafe fn as_ascii_unchecked(&self) -> &[AsciiChar; N]
```

🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998))

Converts this array of bytes into a array of ASCII characters, without checking whether they’re valid.

 ##### Safety

 Every byte in the array must be in `0..=127`, or else this is UB.

 


Trait Implementations
---------------------



[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#167)
```
impl<T, const N: usize> AsMut<[T]> for [T; N]
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#169)
```
fn as_mut(&mut self) -> &mut [T]
```
Converts this type into a mutable reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/vector.rs.html#824)
```
impl<T, const N: usize> AsMut<[T; N]> for Simd<T, N>
where
    LaneCount<N>: SupportedLaneCount,
    T: SimdElement,
```

[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/vector.rs.html#830)
```
fn as_mut(&mut self) -> &mut [T; N]
```
Converts this type into a mutable reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#159)
```
impl<T, const N: usize> AsRef<[T]> for [T; N]
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#161)
```
fn as_ref(&self) -> &[T]
```
Converts this type into a shared reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/vector.rs.html#813)
```
impl<T, const N: usize> AsRef<[T; N]> for Simd<T, N>
where
    LaneCount<N>: SupportedLaneCount,
    T: SimdElement,
```

[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/vector.rs.html#819)
```
fn as_ref(&self) -> &[T; N]
```
Converts this type into a shared reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#175)1.4.0
```
impl<T, const N: usize> Borrow<[T]> for [T; N]
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#176)
```
fn borrow(&self) -> &[T]
```
Immutably borrows from an owned value. [Read more](borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#182)1.4.0
```
impl<T, const N: usize> BorrowMut<[T]> for [T; N]
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#183)
```
fn borrow_mut(&mut self) -> &mut [T]
```
Mutably borrows from an owned value. [Read more](borrow/trait.borrowmut#tymethod.borrow_mut)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#400)1.58.0
```
impl<T, const N: usize> Clone for [T; N]
where
    T: Clone,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#402)
```
fn clone(&self) -> [T; N]
```
Returns a copy of the value. [Read more](clone/trait.clone#tymethod.clone)

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#407)
```
fn clone_from(&mut self, other: &[T; N])
```
Performs copy-assignment from `source`. [Read more](clone/trait.clone#method.clone_from)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#313)
```
impl<T, const N: usize> Debug for [T; N]
where
    T: Debug,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#314)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter. [Read more](fmt/trait.debug#tymethod.fmt)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 0]
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 0]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 1]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 1]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 10]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 10]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 11]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 11]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 12]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 12]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 13]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 13]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 14]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 14]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 15]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 15]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 16]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 16]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 17]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 17]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 18]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 18]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 19]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 19]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 2]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 2]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 20]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 20]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 21]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 21]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 22]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 22]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 23]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 23]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 24]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 24]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 25]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 25]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 26]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 26]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 27]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 27]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 28]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 28]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 29]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 29]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 3]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 3]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 30]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 30]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 31]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 31]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 32]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 32]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 4]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 4]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 5]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 5]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 6]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 6]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 7]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 7]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 8]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 8]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)1.4.0
```
impl<T> Default for [T; 9]
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#452)
```
fn default() -> [T; 9]
```
Returns the “default value” for a type. [Read more](default/trait.default#tymethod.default)


[source](https://doc.rust-lang.org/src/alloc/collections/btree/map.rs.html#2377)1.56.0
```
impl<K, V, const N: usize> From<[(K, V); N]> for BTreeMap<K, V, Global>
where
    K: Ord,
```

[source](https://doc.rust-lang.org/src/alloc/collections/btree/map.rs.html#2387)
```
fn from(arr: [(K, V); N]) -> BTreeMap<K, V, Global>
```

Converts a `[(K, V); N]` into a `BTreeMap<(K, V)>`.

 
```
use std::collections::BTreeMap;

let map1 = BTreeMap::from([(1, 2), (3, 4)]);
let map2: BTreeMap<_, _> = [(1, 2), (3, 4)].into();
assert_eq!(map1, map2);
```
 

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#1357-1373)1.56.0
```
impl<K, V, const N: usize> From<[(K, V); N]> for HashMap<K, V, RandomState>
where
    K: Eq + Hash,
```

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#1370-1372)
```
fn from(arr: [(K, V); N]) -> Self
```

##### Examples

 
```
use std::collections::HashMap;

let map1 = HashMap::from([(1, 2), (3, 4)]);
let map2: HashMap<_, _> = [(1, 2), (3, 4)].into();
assert_eq!(map1, map2);
```
 

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)1.71.0
```
impl<T> From<[T; 1]> for (T,)
```

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)
```
fn from(array: [T; 1]) -> (T,)
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)1.71.0
```
impl<T> From<[T; 10]> for (T, T, T, T, T, T, T, T, T, T)
```

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)
```
fn from(array: [T; 10]) -> (T, T, T, T, T, T, T, T, T, T)
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)1.71.0
```
impl<T> From<[T; 11]> for (T, T, T, T, T, T, T, T, T, T, T)
```

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)
```
fn from(array: [T; 11]) -> (T, T, T, T, T, T, T, T, T, T, T)
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)1.71.0
```
impl<T> From<[T; 12]> for (T, T, T, T, T, T, T, T, T, T, T, T)
```

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)
```
fn from(array: [T; 12]) -> (T, T, T, T, T, T, T, T, T, T, T, T)
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)1.71.0
```
impl<T> From<[T; 2]> for (T, T)
```

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)
```
fn from(array: [T; 2]) -> (T, T)
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)1.71.0
```
impl<T> From<[T; 3]> for (T, T, T)
```

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)
```
fn from(array: [T; 3]) -> (T, T, T)
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)1.71.0
```
impl<T> From<[T; 4]> for (T, T, T, T)
```

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)
```
fn from(array: [T; 4]) -> (T, T, T, T)
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)1.71.0
```
impl<T> From<[T; 5]> for (T, T, T, T, T)
```

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)
```
fn from(array: [T; 5]) -> (T, T, T, T, T)
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)1.71.0
```
impl<T> From<[T; 6]> for (T, T, T, T, T, T)
```

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)
```
fn from(array: [T; 6]) -> (T, T, T, T, T, T)
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)1.71.0
```
impl<T> From<[T; 7]> for (T, T, T, T, T, T, T)
```

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)
```
fn from(array: [T; 7]) -> (T, T, T, T, T, T, T)
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)1.71.0
```
impl<T> From<[T; 8]> for (T, T, T, T, T, T, T, T)
```

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)
```
fn from(array: [T; 8]) -> (T, T, T, T, T, T, T, T)
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)1.71.0
```
impl<T> From<[T; 9]> for (T, T, T, T, T, T, T, T, T)
```

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)
```
fn from(array: [T; 9]) -> (T, T, T, T, T, T, T, T, T)
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/alloc/collections/btree/set.rs.html#1223)1.56.0
```
impl<T, const N: usize> From<[T; N]> for BTreeSet<T, Global>
where
    T: Ord,
```

[source](https://doc.rust-lang.org/src/alloc/collections/btree/set.rs.html#1233)
```
fn from(arr: [T; N]) -> BTreeSet<T, Global>
```

Converts a `[T; N]` into a `BTreeSet<T>`.

 
```
use std::collections::BTreeSet;

let set1 = BTreeSet::from([1, 2, 3, 4]);
let set2: BTreeSet<_> = [1, 2, 3, 4].into();
assert_eq!(set1, set2);
```
 

[source](https://doc.rust-lang.org/src/alloc/collections/binary_heap/mod.rs.html#1652)1.56.0
```
impl<T, const N: usize> From<[T; N]> for BinaryHeap<T>
where
    T: Ord,
```

[source](https://doc.rust-lang.org/src/alloc/collections/binary_heap/mod.rs.html#1662)
```
fn from(arr: [T; N]) -> BinaryHeap<T>
```
 
```
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);
}
```
 

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1607)1.45.0
```
impl<T, const N: usize> From<[T; N]> for Box<[T], Global>
```

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1618)
```
fn from(array: [T; N]) -> Box<[T], Global>
```

Converts a `[T; N]` into a `Box<[T]>`

 This conversion moves the array to newly heap-allocated memory.

 ##### Examples

 
```
let boxed: Box<[u8]> = Box::from([4, 2]);
println!("{boxed:?}");
```
 

[source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1042-1058)1.56.0
```
impl<T, const N: usize> From<[T; N]> for HashSet<T, RandomState>
where
    T: Eq + Hash,
```

[source](https://doc.rust-lang.org/src/std/collections/hash/set.rs.html#1055-1057)
```
fn from(arr: [T; N]) -> Self
```

##### Examples

 
```
use std::collections::HashSet;

let set1 = HashSet::from([1, 2, 3, 4]);
let set2: HashSet<_> = [1, 2, 3, 4].into();
assert_eq!(set1, set2);
```
 

[source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#2078)1.56.0
```
impl<T, const N: usize> From<[T; N]> for LinkedList<T, Global>
```

[source](https://doc.rust-lang.org/src/alloc/collections/linked_list.rs.html#2088)
```
fn from(arr: [T; N]) -> LinkedList<T, Global>
```

Converts a `[T; N]` into a `LinkedList<T>`.

 
```
use std::collections::LinkedList;

let list1 = LinkedList::from([1, 2, 3, 4]);
let list2: LinkedList<_> = [1, 2, 3, 4].into();
assert_eq!(list1, list2);
```
 

[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/vector.rs.html#859)
```
impl<T, const N: usize> From<[T; N]> for Simd<T, N>
where
    LaneCount<N>: SupportedLaneCount,
    T: SimdElement,
```

[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/vector.rs.html#864)
```
fn from(array: [T; N]) -> Simd<T, N>
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3110)1.44.0
```
impl<T, const N: usize> From<[T; N]> for Vec<T, Global>
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3119)
```
fn from(s: [T; N]) -> Vec<T, Global>
```

Allocate a `Vec<T>` and move `s`’s items into it.

 ##### Examples

 
```
assert_eq!(Vec::from([1, 2, 3]), vec![1, 2, 3]);
```
 

[source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2902)1.56.0
```
impl<T, const N: usize> From<[T; N]> for VecDeque<T, Global>
```

[source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2912)
```
fn from(arr: [T; N]) -> VecDeque<T, Global>
```

Converts a `[T; N]` into a `VecDeque<T>`.

 
```
use std::collections::VecDeque;

let deq1 = VecDeque::from([1, 2, 3, 4]);
let deq2: VecDeque<_> = [1, 2, 3, 4].into();
assert_eq!(deq1, deq2);
```
 

[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/masks.rs.html#267)
```
impl<T, const LANES: usize> From<[bool; LANES]> for Mask<T, LANES>
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
```

[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/masks.rs.html#273)
```
fn from(array: [bool; LANES]) -> Mask<T, LANES>
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#2044)1.17.0
```
impl From<[u16; 8]> for IpAddr
```

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#2067)
```
fn from(segments: [u16; 8]) -> IpAddr
```

Creates an `IpAddr::V6` from an eight element 16-bit array.

 ##### Examples

 
```
use std::net::{IpAddr, Ipv6Addr};

let addr = IpAddr::from([
    525u16, 524u16, 523u16, 522u16,
    521u16, 520u16, 519u16, 518u16,
]);
assert_eq!(
    IpAddr::V6(Ipv6Addr::new(
        0x20d, 0x20c,
        0x20b, 0x20a,
        0x209, 0x208,
        0x207, 0x206
    )),
    addr
);
```
 

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#1985)1.16.0
```
impl From<[u16; 8]> for Ipv6Addr
```

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#2008)
```
fn from(segments: [u16; 8]) -> Ipv6Addr
```

Creates an `Ipv6Addr` from an eight element 16-bit array.

 ##### Examples

 
```
use std::net::Ipv6Addr;

let addr = Ipv6Addr::from([
    525u16, 524u16, 523u16, 522u16,
    521u16, 520u16, 519u16, 518u16,
]);
assert_eq!(
    Ipv6Addr::new(
        0x20d, 0x20c,
        0x20b, 0x20a,
        0x209, 0x208,
        0x207, 0x206
    ),
    addr
);
```
 

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#2015)1.17.0
```
impl From<[u8; 16]> for IpAddr
```

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#2038)
```
fn from(octets: [u8; 16]) -> IpAddr
```

Creates an `IpAddr::V6` from a sixteen element byte array.

 ##### Examples

 
```
use std::net::{IpAddr, Ipv6Addr};

let addr = IpAddr::from([
    25u8, 24u8, 23u8, 22u8, 21u8, 20u8, 19u8, 18u8,
    17u8, 16u8, 15u8, 14u8, 13u8, 12u8, 11u8, 10u8,
]);
assert_eq!(
    IpAddr::V6(Ipv6Addr::new(
        0x1918, 0x1716,
        0x1514, 0x1312,
        0x1110, 0x0f0e,
        0x0d0c, 0x0b0a
    )),
    addr
);
```
 

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#1956)1.9.0
```
impl From<[u8; 16]> for Ipv6Addr
```

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#1979)
```
fn from(octets: [u8; 16]) -> Ipv6Addr
```

Creates an `Ipv6Addr` from a sixteen element byte array.

 ##### Examples

 
```
use std::net::Ipv6Addr;

let addr = Ipv6Addr::from([
    25u8, 24u8, 23u8, 22u8, 21u8, 20u8, 19u8, 18u8,
    17u8, 16u8, 15u8, 14u8, 13u8, 12u8, 11u8, 10u8,
]);
assert_eq!(
    Ipv6Addr::new(
        0x1918, 0x1716,
        0x1514, 0x1312,
        0x1110, 0x0f0e,
        0x0d0c, 0x0b0a
    ),
    addr
);
```
 

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#1125)1.17.0
```
impl From<[u8; 4]> for IpAddr
```

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#1137)
```
fn from(octets: [u8; 4]) -> IpAddr
```

Creates an `IpAddr::V4` from a four element byte array.

 ##### 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);
```
 

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#1107)1.9.0
```
impl From<[u8; 4]> for Ipv4Addr
```

[source](https://doc.rust-lang.org/src/core/net/ip_addr.rs.html#1119)
```
fn from(octets: [u8; 4]) -> Ipv4Addr
```

Creates an `Ipv4Addr` from a four element byte array.

 ##### Examples

 
```
use std::net::Ipv4Addr;

let addr = Ipv4Addr::from([13u8, 12u8, 11u8, 10u8]);
assert_eq!(Ipv4Addr::new(13, 12, 11, 10), addr);
```
 

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)1.71.0
```
impl<T> From<(T,)> for [T; 1]
```

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)
```
fn from(tuple: (T,)) -> [T; 1]
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)1.71.0
```
impl<T> From<(T, T)> for [T; 2]
```

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)
```
fn from(tuple: (T, T)) -> [T; 2]
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)1.71.0
```
impl<T> From<(T, T, T)> for [T; 3]
```

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)
```
fn from(tuple: (T, T, T)) -> [T; 3]
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)1.71.0
```
impl<T> From<(T, T, T, T)> for [T; 4]
```

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)
```
fn from(tuple: (T, T, T, T)) -> [T; 4]
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)1.71.0
```
impl<T> From<(T, T, T, T, T)> for [T; 5]
```

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)
```
fn from(tuple: (T, T, T, T, T)) -> [T; 5]
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)1.71.0
```
impl<T> From<(T, T, T, T, T, T)> for [T; 6]
```

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)
```
fn from(tuple: (T, T, T, T, T, T)) -> [T; 6]
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)1.71.0
```
impl<T> From<(T, T, T, T, T, T, T)> for [T; 7]
```

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)
```
fn from(tuple: (T, T, T, T, T, T, T)) -> [T; 7]
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)1.71.0
```
impl<T> From<(T, T, T, T, T, T, T, T)> for [T; 8]
```

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)
```
fn from(tuple: (T, T, T, T, T, T, T, T)) -> [T; 8]
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)1.71.0
```
impl<T> From<(T, T, T, T, T, T, T, T, T)> for [T; 9]
```

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)
```
fn from(tuple: (T, T, T, T, T, T, T, T, T)) -> [T; 9]
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)1.71.0
```
impl<T> From<(T, T, T, T, T, T, T, T, T, T)> for [T; 10]
```

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)
```
fn from(tuple: (T, T, T, T, T, T, T, T, T, T)) -> [T; 10]
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)1.71.0
```
impl<T> From<(T, T, T, T, T, T, T, T, T, T, T)> for [T; 11]
```

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)
```
fn from(tuple: (T, T, T, T, T, T, T, T, T, T, T)) -> [T; 11]
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)1.71.0
```
impl<T> From<(T, T, T, T, T, T, T, T, T, T, T, T)> for [T; 12]
```

[source](https://doc.rust-lang.org/src/core/tuple.rs.html#197)
```
fn from(tuple: (T, T, T, T, T, T, T, T, T, T, T, T)) -> [T; 12]
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/masks.rs.html#278)
```
impl<T, const LANES: usize> From<Mask<T, LANES>> for [bool; LANES]
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
```

[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/masks.rs.html#284)
```
fn from(vector: Mask<T, LANES>) -> [bool; LANES]
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/vector.rs.html#869)
```
impl<T, const N: usize> From<Simd<T, N>> for [T; N]
where
    LaneCount<N>: SupportedLaneCount,
    T: SimdElement,
```

[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/vector.rs.html#874)
```
fn from(vector: Simd<T, N>) -> [T; N]
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#306)
```
impl<T, const N: usize> Hash for [T; N]
where
    T: Hash,
```

The hash of an array is the same as that of the corresponding slice, as required by the `Borrow` implementation.

 
```
use std::hash::BuildHasher;

let b = std::collections::hash_map::RandomState::new();
let a: [u8; 3] = [0xa8, 0x3c, 0x09];
let s: &[u8] = &[0xa8, 0x3c, 0x09];
assert_eq!(b.hash_one(a), b.hash_one(s));
```
 

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#307)
```
fn hash<H>(&self, state: &mut H)
where
    H: Hasher,
```
Feeds this value into the given [`Hasher`](hash/trait.hasher "trait std::hash::Hasher"). [Read more](hash/trait.hash#tymethod.hash)

[source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#237-239)1.3.0
```
fn hash_slice<H>(data: &[Self], state: &mut H)
where
    H: Hasher,
    Self: Sized,
```
Feeds a slice of this type into the given [`Hasher`](hash/trait.hasher "trait std::hash::Hasher"). [Read more](hash/trait.hash#method.hash_slice)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#340)1.50.0
```
impl<T, I, const N: usize> Index<I> for [T; N]
where
    [T]: Index<I>,
```


```
type Output = <[T] as Index<I>>::Output
```
The returned type after indexing.
[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#347)
```
fn index(&self, index: I) -> &<[T; N] as Index<I>>::Output
```
Performs the indexing (`container[index]`) operation. [Read more](ops/trait.index#tymethod.index)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#353)1.50.0
```
impl<T, I, const N: usize> IndexMut<I> for [T; N]
where
    [T]: IndexMut<I>,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#358)
```
fn index_mut(&mut self, index: I) -> &mut <[T; N] as Index<I>>::Output
```
Performs the mutable indexing (`container[index]`) operation. [Read more](ops/trait.indexmut#tymethod.index_mut)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#320)
```
impl<'a, T, const N: usize> IntoIterator for &'a [T; N]
```


```
type Item = &'a T
```
The type of the elements being iterated over.

```
type IntoIter = Iter<'a, T>
```
Which kind of iterator are we turning this into?
[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#324)
```
fn into_iter(self) -> Iter<'a, T> ⓘ
```
Creates an iterator from a value. [Read more](iter/trait.intoiterator#tymethod.into_iter)


[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#330)
```
impl<'a, T, const N: usize> IntoIterator for &'a mut [T; N]
```


```
type Item = &'a mut T
```
The type of the elements being iterated over.

```
type IntoIter = IterMut<'a, T>
```
Which kind of iterator are we turning this into?
[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#334)
```
fn into_iter(self) -> IterMut<'a, T> ⓘ
```
Creates an iterator from a value. [Read more](iter/trait.intoiterator#tymethod.into_iter)


[source](https://doc.rust-lang.org/src/core/array/iter.rs.html#44)1.53.0
```
impl<T, const N: usize> IntoIterator for [T; N]
```

[source](https://doc.rust-lang.org/src/core/array/iter.rs.html#56)
```
fn into_iter(self) -> <[T; N] as IntoIterator>::IntoIter
```

Creates a consuming iterator, that is, one that moves each value out of the array (from start to end). The array cannot be used after calling this unless `T` implements `Copy`, so the whole array is copied.

 Arrays have special behavior when calling `.into_iter()` prior to the 2021 edition – see the [array](primitive.array "primitive array") Editions section for more information.

 

```
type Item = T
```
The type of the elements being iterated over.

```
type IntoIter = IntoIter<T, N>
```
Which kind of iterator are we turning this into?

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#389)
```
impl<T, const N: usize> Ord for [T; N]
where
    T: Ord,
```

Implements comparison of arrays [lexicographically](cmp/trait.ord#lexicographical-comparison "trait std::cmp::Ord").

 

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#391)
```
fn cmp(&self, other: &[T; N]) -> Ordering
```
This method returns an [`Ordering`](cmp/enum.ordering "enum std::cmp::Ordering") between `self` and `other`. [Read more](cmp/trait.ord#tymethod.cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#790-792)1.21.0
```
fn max(self, other: Self) -> Self
where
    Self: Sized,
```
Compares and returns the maximum of two values. [Read more](cmp/trait.ord#method.max)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#810-812)1.21.0
```
fn min(self, other: Self) -> Self
where
    Self: Sized,
```
Compares and returns the minimum of two values. [Read more](cmp/trait.ord#method.min)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#835-838)1.50.0
```
fn clamp(self, min: Self, max: Self) -> Self
where
    Self: Sized + PartialOrd<Self>,
```
Restrict a value to a certain interval. [Read more](cmp/trait.ord#method.clamp)


[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#66)
```
impl<A, B, const N: usize> PartialEq<&[B]> for [A; N]
where
    A: PartialEq<B>,
```

[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#71)
```
fn eq(&self, other: &&[B]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#75)
```
fn ne(&self, other: &&[B]) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#37)
```
impl<T, U, A, const N: usize> PartialEq<&[U; N]> for Vec<T, A>
where
    A: Allocator,
    T: PartialEq<U>,
```

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#37)
```
fn eq(&self, other: &&[U; N]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#37)
```
fn ne(&self, other: &&[U; N]) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2705)1.17.0
```
impl<T, U, A, const N: usize> PartialEq<&[U; N]> for VecDeque<T, A>
where
    A: Allocator,
    T: PartialEq<U>,
```

[source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2705)
```
fn eq(&self, other: &&[U; N]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#226)
```
fn ne(&self, other: &Rhs) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#96)
```
impl<A, B, const N: usize> PartialEq<&mut [B]> for [A; N]
where
    A: PartialEq<B>,
```

[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#101)
```
fn eq(&self, other: &&mut [B]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#105)
```
fn ne(&self, other: &&mut [B]) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2706)1.17.0
```
impl<T, U, A, const N: usize> PartialEq<&mut [U; N]> for VecDeque<T, A>
where
    A: Allocator,
    T: PartialEq<U>,
```

[source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2706)
```
fn eq(&self, other: &&mut [U; N]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#226)
```
fn ne(&self, other: &Rhs) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#81)
```
impl<A, B, const N: usize> PartialEq<[A; N]> for &[B]
where
    B: PartialEq<A>,
```

[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#86)
```
fn eq(&self, other: &[A; N]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#90)
```
fn ne(&self, other: &[A; N]) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#111)
```
impl<A, B, const N: usize> PartialEq<[A; N]> for &mut [B]
where
    B: PartialEq<A>,
```

[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#116)
```
fn eq(&self, other: &[A; N]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#120)
```
fn ne(&self, other: &[A; N]) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#43)
```
impl<A, B, const N: usize> PartialEq<[A; N]> for [B]
where
    B: PartialEq<A>,
```

[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#48)
```
fn eq(&self, other: &[A; N]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#56)
```
fn ne(&self, other: &[A; N]) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#20)
```
impl<A, B, const N: usize> PartialEq<[B]> for [A; N]
where
    A: PartialEq<B>,
```

[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#25)
```
fn eq(&self, other: &[B]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#33)
```
fn ne(&self, other: &[B]) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#5)
```
impl<A, B, const N: usize> PartialEq<[B; N]> for [A; N]
where
    A: PartialEq<B>,
```

[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#10)
```
fn eq(&self, other: &[B; N]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#14)
```
fn ne(&self, other: &[B; N]) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#36)
```
impl<T, U, A, const N: usize> PartialEq<[U; N]> for Vec<T, A>
where
    A: Allocator,
    T: PartialEq<U>,
```

[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#36)
```
fn eq(&self, other: &[U; N]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/alloc/vec/partial_eq.rs.html#36)
```
fn ne(&self, other: &[U; N]) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2704)1.17.0
```
impl<T, U, A, const N: usize> PartialEq<[U; N]> for VecDeque<T, A>
where
    A: Allocator,
    T: PartialEq<U>,
```

[source](https://doc.rust-lang.org/src/alloc/collections/vec_deque/mod.rs.html#2704)
```
fn eq(&self, other: &[U; N]) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#226)
```
fn ne(&self, other: &Rhs) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#364)
```
impl<T, const N: usize> PartialOrd<[T; N]> for [T; N]
where
    T: PartialOrd<T>,
```

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#366)
```
fn partial_cmp(&self, other: &[T; N]) -> Option<Ordering>
```
This method returns an ordering between `self` and `other` values if one exists. [Read more](cmp/trait.partialord#tymethod.partial_cmp)

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#370)
```
fn lt(&self, other: &[T; N]) -> bool
```
This method tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](cmp/trait.partialord#method.lt)

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#374)
```
fn le(&self, other: &[T; N]) -> bool
```
This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](cmp/trait.partialord#method.le)

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#378)
```
fn ge(&self, other: &[T; N]) -> bool
```
This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](cmp/trait.partialord#method.ge)

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#382)
```
fn gt(&self, other: &[T; N]) -> bool
```
This method tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](cmp/trait.partialord#method.gt)


[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#817)
```
impl<'a, 'b, const N: usize> Pattern<'a> for &'b [char; N]
```

Searches for chars that are equal to any of the [`char`](primitive.char "primitive char")s in the array.

 #### Examples

 
```
assert_eq!("Hello world".find(&['o', 'l']), Some(2));
assert_eq!("Hello world".find(&['h', 'w']), Some(6));
```
 


```
type Searcher = CharArrayRefSearcher<'a, 'b, N>
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Associated searcher for this pattern
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#818)
```
fn into_searcher(self, haystack: &'a str) -> CharArrayRefSearcher<'a, 'b, N>
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Constructs the associated searcher from `self` and the `haystack` to search in.
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#818)
```
fn is_contained_in(self, haystack: &'a str) -> bool
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Checks whether the pattern matches anywhere in the haystack
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#818)
```
fn is_prefix_of(self, haystack: &'a str) -> bool
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Checks whether the pattern matches at the front of the haystack
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#818)
```
fn strip_prefix_of(self, haystack: &'a str) -> Option<&'a str>
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Removes the pattern from the front of haystack, if it matches.
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#818)
```
fn is_suffix_of(self, haystack: &'a str) -> bool
where
    CharArrayRefSearcher<'a, 'b, N>: ReverseSearcher<'a>,
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Checks whether the pattern matches at the back of the haystack
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#818)
```
fn strip_suffix_of(self, haystack: &'a str) -> Option<&'a str>
where
    CharArrayRefSearcher<'a, 'b, N>: ReverseSearcher<'a>,
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Removes the pattern from the back of haystack, if it matches.

[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#797)
```
impl<'a, const N: usize> Pattern<'a> for [char; N]
```

Searches for chars that are equal to any of the [`char`](primitive.char "primitive char")s in the array.

 #### Examples

 
```
assert_eq!("Hello world".find(['o', 'l']), Some(2));
assert_eq!("Hello world".find(['h', 'w']), Some(6));
```
 


```
type Searcher = CharArraySearcher<'a, N>
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Associated searcher for this pattern
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#798)
```
fn into_searcher(self, haystack: &'a str) -> CharArraySearcher<'a, N>
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Constructs the associated searcher from `self` and the `haystack` to search in.
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#798)
```
fn is_contained_in(self, haystack: &'a str) -> bool
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Checks whether the pattern matches anywhere in the haystack
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#798)
```
fn is_prefix_of(self, haystack: &'a str) -> bool
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Checks whether the pattern matches at the front of the haystack
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#798)
```
fn strip_prefix_of(self, haystack: &'a str) -> Option<&'a str>
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Removes the pattern from the front of haystack, if it matches.
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#798)
```
fn is_suffix_of(self, haystack: &'a str) -> bool
where
    CharArraySearcher<'a, N>: ReverseSearcher<'a>,
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Checks whether the pattern matches at the back of the haystack
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#798)
```
fn strip_suffix_of(self, haystack: &'a str) -> Option<&'a str>
where
    CharArraySearcher<'a, N>: ReverseSearcher<'a>,
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Removes the pattern from the back of haystack, if it matches.

[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4675)1.51.0
```
impl<T, const N: usize> SlicePattern for [T; N]
```


```
type Item = T
```

🔬This is a nightly-only experimental API. (`slice_pattern` [#56345](https://github.com/rust-lang/rust/issues/56345))
The element type of the slice being matched on.
[source](https://doc.rust-lang.org/src/core/slice/mod.rs.html#4679)
```
fn as_slice(&self) -> &[<[T; N] as SlicePattern>::Item]
```

🔬This is a nightly-only experimental API. (`slice_pattern` [#56345](https://github.com/rust-lang/rust/issues/56345))
Currently, the consumers of `SlicePattern` need a slice.

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#201)1.34.0
```
impl<T, const N: usize> TryFrom<&[T]> for [T; N]
where
    T: Copy,
```

Tries to create an array `[T; N]` by copying from a slice `&[T]`. Succeeds if `slice.len() == N`.

 
```
let bytes: [u8; 3] = [1, 0, 2];

let bytes_head: [u8; 2] = <[u8; 2]>::try_from(&bytes[0..2]).unwrap();
assert_eq!(1, u16::from_le_bytes(bytes_head));

let bytes_tail: [u8; 2] = bytes[1..3].try_into().unwrap();
assert_eq!(512, u16::from_le_bytes(bytes_tail));
```
 


```
type Error = TryFromSliceError
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#208)
```
fn try_from(slice: &[T]) -> Result<[T; N], TryFromSliceError>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#251)1.34.0
```
impl<'a, T, const N: usize> TryFrom<&'a [T]> for &'a [T; N]
```

Tries to create an array ref `&[T; N]` from a slice ref `&[T]`. Succeeds if `slice.len() == N`.

 
```
let bytes: [u8; 3] = [1, 0, 2];

let bytes_head: &[u8; 2] = <&[u8; 2]>::try_from(&bytes[0..2]).unwrap();
assert_eq!(1, u16::from_le_bytes(*bytes_head));

let bytes_tail: &[u8; 2] = bytes[1..3].try_into().unwrap();
assert_eq!(512, u16::from_le_bytes(*bytes_tail));
```
 


```
type Error = TryFromSliceError
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#255)
```
fn try_from(slice: &'a [T]) -> Result<&'a [T; N], TryFromSliceError>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#279)1.34.0
```
impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut [T; N]
```

Tries to create a mutable array ref `&mut [T; N]` from a mutable slice ref `&mut [T]`. Succeeds if `slice.len() == N`.

 
```
let mut bytes: [u8; 3] = [1, 0, 2];

let bytes_head: &mut [u8; 2] = <&mut [u8; 2]>::try_from(&mut bytes[0..2]).unwrap();
assert_eq!(1, u16::from_le_bytes(*bytes_head));

let bytes_tail: &mut [u8; 2] = (&mut bytes[1..3]).try_into().unwrap();
assert_eq!(512, u16::from_le_bytes(*bytes_tail));
```
 


```
type Error = TryFromSliceError
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#283)
```
fn try_from(slice: &'a mut [T]) -> Result<&'a mut [T; N], TryFromSliceError>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#226)1.59.0
```
impl<T, const N: usize> TryFrom<&mut [T]> for [T; N]
where
    T: Copy,
```

Tries to create an array `[T; N]` by copying from a mutable slice `&mut [T]`. Succeeds if `slice.len() == N`.

 
```
let mut bytes: [u8; 3] = [1, 0, 2];

let bytes_head: [u8; 2] = <[u8; 2]>::try_from(&mut bytes[0..2]).unwrap();
assert_eq!(1, u16::from_le_bytes(bytes_head));

let bytes_tail: [u8; 2] = (&mut bytes[1..3]).try_into().unwrap();
assert_eq!(512, u16::from_le_bytes(bytes_tail));
```
 


```
type Error = TryFromSliceError
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#233)
```
fn try_from(slice: &mut [T]) -> Result<[T; N], TryFromSliceError>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1640)1.43.0
```
impl<T, const N: usize> TryFrom<Box<[T], Global>> for Box<[T; N], Global>
```

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1652)
```
fn try_from(
    boxed_slice: Box<[T], Global>
) -> Result<Box<[T; N], Global>, <Box<[T; N], Global> as TryFrom<Box<[T], Global>>>::Error>
```

Attempts to convert a `Box<[T]>` into a `Box<[T; N]>`.

 The conversion occurs in-place and does not require a new memory allocation.

 ##### Errors

 Returns the old `Box<[T]>` in the `Err` variant if `boxed_slice.len()` does not equal `N`.

 

```
type Error = Box<[T], Global>
```
The type returned in the event of a conversion error.

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3215)1.48.0
```
impl<T, A, const N: usize> TryFrom<Vec<T, A>> for [T; N]
where
    A: Allocator,
```

[source](https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#3244)
```
fn try_from(vec: Vec<T, A>) -> Result<[T; N], Vec<T, A>>
```

Gets the entire contents of the `Vec<T>` as an array, if its size exactly matches that of the requested array.

 ##### Examples

 
```
assert_eq!(vec![1, 2, 3].try_into(), Ok([1, 2, 3]));
assert_eq!(<Vec<i32>>::new().try_into(), Ok([]));
```
 If the length doesn’t match, the input comes back in `Err`:

 
```
let r: Result<[i32; 4], _> = (0..10).collect::<Vec<_>>().try_into();
assert_eq!(r, Err(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
```
 If you’re fine with just getting a prefix of the `Vec<T>`, you can call [`.truncate(N)`](vec/struct.vec#method.truncate "method std::vec::Vec::truncate") first.

 
```
let mut v = String::from("hello world").into_bytes();
v.sort();
v.truncate(2);
let [a, b]: [_; 2] = v.try_into().unwrap();
assert_eq!(a, b' ');
assert_eq!(b, b'd');
```
 

```
type Error = Vec<T, A>
```
The type returned in the event of a conversion error.

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1663)1.66.0
```
impl<T, const N: usize> TryFrom<Vec<T, Global>> for Box<[T; N], Global>
```

[source](https://doc.rust-lang.org/src/alloc/boxed.rs.html#1684)
```
fn try_from(
    vec: Vec<T, Global>
) -> Result<Box<[T; N], Global>, <Box<[T; N], Global> as TryFrom<Vec<T, Global>>>::Error>
```

Attempts to convert a `Vec<T>` into a `Box<[T; N]>`.

 Like [`Vec::into_boxed_slice`](vec/struct.vec#method.into_boxed_slice "method std::vec::Vec::into_boxed_slice"), this is in-place if `vec.capacity() == N`, but will require a reallocation otherwise.

 ##### Errors

 Returns the original `Vec<T>` in the `Err` variant if `boxed_slice.len()` does not equal `N`.

 ##### Examples

 This can be used with [`vec!`](macro.vec "macro std::vec") to create an array on the heap:

 
```
let state: Box<[f32; 100]> = vec![1.0; 100].try_into().unwrap();
assert_eq!(state.len(), 100);
```
 

```
type Error = Vec<T, Global>
```
The type returned in the event of a conversion error.

[source](https://doc.rust-lang.org/src/core/marker.rs.html#989-1000)
```
impl<T, const N: usize> ConstParamTy for [T; N]
where
    T: ConstParamTy,
```
[source](https://doc.rust-lang.org/src/core/array/mod.rs.html#397)1.58.0
```
impl<T, const N: usize> Copy for [T; N]
where
    T: Copy,
```
[source](https://doc.rust-lang.org/src/core/array/equality.rs.html#130)
```
impl<T, const N: usize> Eq for [T; N]
where
    T: Eq,
```
[source](https://doc.rust-lang.org/src/core/marker.rs.html#262-273)
```
impl<T, const N: usize> StructuralEq for [T; N]
```


Auto Trait Implementations
--------------------------




```
impl<T, const N: usize> RefUnwindSafe for [T; N]
where
    T: RefUnwindSafe,
```

```
impl<T, const N: usize> Send for [T; N]
where
    T: Send,
```

```
impl<T, const N: usize> Sync for [T; N]
where
    T: Sync,
```

```
impl<T, const N: usize> Unpin for [T; N]
where
    T: Unpin,
```

```
impl<T, const N: usize> UnwindSafe for [T; N]
where
    T: UnwindSafe,
```


Blanket Implementations
-----------------------



[source](https://doc.rust-lang.org/src/core/any.rs.html#200)
```
impl<T> Any for T
where
    T: 'static + ?Sized,
```

[source](https://doc.rust-lang.org/src/core/any.rs.html#201)
```
fn type_id(&self) -> TypeId
```
Gets the `TypeId` of `self`. [Read more](any/trait.any#tymethod.type_id)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#208)
```
impl<T> Borrow<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#210)
```
fn borrow(&self) -> &T
```
Immutably borrows from an owned value. [Read more](borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#216)
```
impl<T> BorrowMut<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#217)
```
fn borrow_mut(&mut self) -> &mut T
```
Mutably borrows from an owned value. [Read more](borrow/trait.borrowmut#tymethod.borrow_mut)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#723)
```
impl<T> From<T> for T
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#726)
```
fn from(t: T) -> T
```

Returns the argument unchanged.

 

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#707)
```
impl<T, U> Into<U> for T
where
    U: From<T>,
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#716)
```
fn into(self) -> U
```

Calls `U::from(self)`.

 That is, this conversion is whatever the implementation of `[From](convert/trait.from "trait std::convert::From")<T> for U` chooses to do.

 

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#82)
```
impl<T> ToOwned for T
where
    T: Clone,
```


```
type Owned = T
```
The resulting type after obtaining ownership.
[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#87)
```
fn to_owned(&self) -> T
```
Creates owned data from borrowed data, usually by cloning. [Read more](borrow/trait.toowned#tymethod.to_owned)

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#91)
```
fn clone_into(&self, target: &mut T)
```
Uses borrowed data to replace owned data, usually by cloning. [Read more](borrow/trait.toowned#method.clone_into)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#763)
```
impl<T, U> TryFrom<U> for T
where
    U: Into<T>,
```


```
type Error = Infallible
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#770)
```
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#748)
```
impl<T, U> TryInto<U> for T
where
    U: TryFrom<T>,
```


```
type Error = <U as TryFrom<T>>::Error
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#755)
```
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
```
Performs the conversion.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/primitive.array.html>

Module std::boxed
=================


The `Box<T>` type for heap allocation.

 [`Box<T>`](struct.box "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.

 Examples
--------

 Move a value from the stack to the heap by creating a [`Box`](struct.box "struct std::boxed::Box"):

 
```
let val: u8 = 5;
let boxed: Box<u8> = Box::new(val);
```
 Move a value from a [`Box`](struct.box "struct std::boxed::Box") back to the stack by [dereferencing](../ops/trait.deref "trait std::ops::Deref"):

 
```
let boxed: Box<u8> = Box::new(5);
let val: u8 = *boxed;
```
 Creating a recursive data structure:

 
```
#[derive(Debug)]
enum List<T> {
    Cons(T, Box<List<T>>),
    Nil,
}

let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
println!("{list:?}");
```
 This will print `Cons(1, Cons(2, Nil))`.

 Recursive structures must be boxed, because if the definition of `Cons` looked like this:

 ⓘ
```
Cons(T, List<T>),
```

 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<T>`](struct.box "struct std::boxed::Box"), which has a defined size, we know how big `Cons` needs to be.

 Memory layout
-------------

 For non-zero-sized values, a [`Box`](struct.box "struct std::boxed::Box") will use the [`Global`](../alloc/struct.global "struct std::alloc::Global") allocator for its allocation. It is valid to convert both ways between a [`Box`](struct.box "struct std::boxed::Box") and a raw pointer allocated with the [`Global`](../alloc/struct.global "struct std::alloc::Global") allocator, given that the [`Layout`](../alloc/struct.layout "struct std::alloc::Layout") used with the allocator is correct for the type. More precisely, a `value: *mut T` that has been allocated with the [`Global`](../alloc/struct.global "struct std::alloc::Global") allocator with `Layout::for_value(&*value)` may be converted into a box using [`Box::<T>::from_raw(value)`](struct.box#method.from_raw "associated function std::boxed::Box::from_raw"). Conversely, the memory backing a `value: *mut T` obtained from [`Box::<T>::into_raw`](struct.box#method.into_raw "associated function std::boxed::Box::into_raw") may be deallocated using the [`Global`](../alloc/struct.global "struct std::alloc::Global") allocator with [`Layout::for_value(&*value)`](../alloc/struct.layout#method.for_value "associated function std::alloc::Layout::for_value").

 For zero-sized values, the `Box` pointer still has to be [valid](../ptr/index#safety "mod std::ptr") for reads and writes and sufficiently aligned. In particular, casting any aligned non-zero integer literal to a raw pointer produces a valid pointer, but a pointer pointing into previously allocated memory that since got freed is not valid. The recommended way to build a Box to a ZST if `Box::new` cannot be used is to use [`ptr::NonNull::dangling`](../ptr/struct.nonnull#method.dangling "associated function std::ptr::NonNull::dangling").

 So long as `T: Sized`, a `Box<T>` 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<T>` 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<Foo>`, which captures the ownership constraints. Note also that the nullable argument to `foo_delete` is represented in Rust as `Option<Box<Foo>>`, since `Box<Foo>` cannot be null.

 
```
#[repr(C)]
pub struct Foo;

#[no_mangle]
pub extern "C" fn foo_new() -> Box<Foo> {
    Box::new(Foo)
}

#[no_mangle]
pub extern "C" fn foo_delete(_: Option<Box<Foo>>) {}
```
 Even though `Box<T>` 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<T>` and expect things to work. `Box<T>` values will always be fully aligned, non-null pointers. Moreover, the destructor for `Box<T>` will attempt to free the value with the global allocator. In general, the best practice is to only use `Box<T>` for pointers that originated from the global allocator.

 **Important.** At least at present, you should avoid using `Box<T>` 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<T>` 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).

 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<T>` are the same as for `&mut T`. `Box<T>` 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).

 Structs
-------


* [ThinBox](struct.thinbox "struct std::boxed::ThinBox")Experimental

ThinBox.
* [Box](struct.box "struct std::boxed::Box")
A pointer type that uniquely owns a heap allocation of type `T`.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/boxed/index.html>

Macro std::format
=================



```
macro_rules! format {
    ($($arg:tt)*) => { ... };
}
```

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 [`std::fmt`](fmt/index) for more information.

 A common use for `format!` is concatenation and interpolation of strings. The same convention is used with [`print!`](macro.print) and [`write!`](macro.write "macro std::write") macros, depending on the intended destination of the string.

 To convert a single value to a string, use the [`to_string`](string/trait.tostring "trait std::string::ToString") method. This will use the [`Display`](fmt/trait.display "trait std::fmt::Display") formatting trait.

 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.

 Examples
--------

 
```
format!("test");
format!("hello {}", "world!");
format!("x = {}, y = {y}", 10, y = 30);
let (x, y) = (1, 2);
format!("{x} + {y} = 3");
```


 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/macro.format.html>

Trait std::str::FromStr
=======================



```
pub trait FromStr: Sized {
    type Err;

    // Required method
    fn from_str(s: &str) -> Result<Self, Self::Err>;
}
```

Parse a value from a string

 `FromStr`’s [`from_str`](trait.fromstr#tymethod.from_str "associated function std::str::FromStr::from_str") method is often used implicitly, through [`str`](../primitive.str "primitive str")’s [`parse`](../primitive.str#method.parse "method str::parse") method. See [`parse`](../primitive.str#method.parse "method str::parse")’s documentation for examples.

 `FromStr` does not have a lifetime parameter, and so you can only parse types that do not contain a lifetime parameter themselves. In other words, you can parse an `i32` with `FromStr`, but not a `&i32`. You can parse a struct that contains an `i32`, but not one that contains an `&i32`.

 Examples
--------

 Basic implementation of `FromStr` on an example `Point` type:

 
```
use std::str::FromStr;

#[derive(Debug, PartialEq)]
struct Point {
    x: i32,
    y: i32
}

#[derive(Debug, PartialEq, Eq)]
struct ParsePointError;

impl FromStr for Point {
    type Err = ParsePointError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let (x, y) = s
            .strip_prefix('(')
            .and_then(|s| s.strip_suffix(')'))
            .and_then(|s| s.split_once(','))
            .ok_or(ParsePointError)?;

        let x_fromstr = x.parse::<i32>().map_err(|_| ParsePointError)?;
        let y_fromstr = y.parse::<i32>().map_err(|_| ParsePointError)?;

        Ok(Point { x: x_fromstr, y: y_fromstr })
    }
}

let expected = Ok(Point { x: 1, y: 2 });
// Explicit call
assert_eq!(Point::from_str("(1,2)"), expected);
// Implicit calls, through parse
assert_eq!("(1,2)".parse(), expected);
assert_eq!("(1,2)".parse::<Point>(), expected);
// Invalid input string
assert!(Point::from_str("(1 2)").is_err());
```
 Required Associated Types
-------------------------



[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#554)
```
type Err
```

The associated error which can be returned from parsing.

 

Required Methods
----------------



[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#575)
```
fn from_str(s: &str) -> Result<Self, Self::Err>
```

Parses a string `s` to return a value of this type.

 If parsing succeeds, return the value inside [`Ok`](../result/enum.result#variant.Ok "variant std::result::Result::Ok"), otherwise when the string is ill-formatted return an error specific to the inside [`Err`](../result/enum.result#variant.Err "variant std::result::Result::Err"). The error type is specific to the implementation of the trait.

 ##### Examples

 Basic usage with [`i32`](../primitive.i32 "primitive i32"), a type that implements `FromStr`:

 
```
use std::str::FromStr;

let s = "5";
let x = i32::from_str(s).unwrap();

assert_eq!(5, x);
```
 

Implementors
------------



[source](https://doc.rust-lang.org/src/core/net/parser.rs.html#295)1.7.0
```
impl FromStr for IpAddr
```

```
type Err = AddrParseError
```

[source](https://doc.rust-lang.org/src/core/net/parser.rs.html#432)
```
impl FromStr for SocketAddr
```

```
type Err = AddrParseError
```

[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#579)
```
impl FromStr for bool
```

```
type Err = ParseBoolError
```

[source](https://doc.rust-lang.org/src/core/char/convert.rs.html#176)1.20.0
```
impl FromStr for char
```

```
type Err = ParseCharError
```

[source](https://doc.rust-lang.org/src/core/num/dec2flt/mod.rs.html#163)
```
impl FromStr for f32
```

```
type Err = ParseFloatError
```

[source](https://doc.rust-lang.org/src/core/num/dec2flt/mod.rs.html#164)
```
impl FromStr for f64
```

```
type Err = ParseFloatError
```

[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#1404)
```
impl FromStr for i8
```

```
type Err = ParseIntError
```

[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#1404)
```
impl FromStr for i16
```

```
type Err = ParseIntError
```

[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#1404)
```
impl FromStr for i32
```

```
type Err = ParseIntError
```

[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#1404)
```
impl FromStr for i64
```

```
type Err = ParseIntError
```

[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#1404)
```
impl FromStr for i128
```

```
type Err = ParseIntError
```

[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#1404)
```
impl FromStr for isize
```

```
type Err = ParseIntError
```

[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#1404)
```
impl FromStr for u8
```

```
type Err = ParseIntError
```

[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#1404)
```
impl FromStr for u16
```

```
type Err = ParseIntError
```

[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#1404)
```
impl FromStr for u32
```

```
type Err = ParseIntError
```

[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#1404)
```
impl FromStr for u64
```

```
type Err = ParseIntError
```

[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#1404)
```
impl FromStr for u128
```

```
type Err = ParseIntError
```

[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#1404)
```
impl FromStr for usize
```

```
type Err = ParseIntError
```

[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1355-1362)1.45.0
```
impl FromStr for OsString
```

```
type Err = Infallible
```

[source](https://doc.rust-lang.org/src/core/net/parser.rs.html#326)
```
impl FromStr for Ipv4Addr
```

```
type Err = AddrParseError
```

[source](https://doc.rust-lang.org/src/core/net/parser.rs.html#352)
```
impl FromStr for Ipv6Addr
```

```
type Err = AddrParseError
```

[source](https://doc.rust-lang.org/src/core/net/parser.rs.html#378)1.5.0
```
impl FromStr for SocketAddrV4
```

```
type Err = AddrParseError
```

[source](https://doc.rust-lang.org/src/core/net/parser.rs.html#404)1.5.0
```
impl FromStr for SocketAddrV6
```

```
type Err = AddrParseError
```

[source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#195-196)1.35.0
```
impl FromStr for NonZeroI8
```

```
type Err = ParseIntError
```

[source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#195-196)1.35.0
```
impl FromStr for NonZeroI16
```

```
type Err = ParseIntError
```

[source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#195-196)1.35.0
```
impl FromStr for NonZeroI32
```

```
type Err = ParseIntError
```

[source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#195-196)1.35.0
```
impl FromStr for NonZeroI64
```

```
type Err = ParseIntError
```

[source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#195-196)1.35.0
```
impl FromStr for NonZeroI128
```

```
type Err = ParseIntError
```

[source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#195-196)1.35.0
```
impl FromStr for NonZeroIsize
```

```
type Err = ParseIntError
```

[source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#195-196)1.35.0
```
impl FromStr for NonZeroU8
```

```
type Err = ParseIntError
```

[source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#195-196)1.35.0
```
impl FromStr for NonZeroU16
```

```
type Err = ParseIntError
```

[source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#195-196)1.35.0
```
impl FromStr for NonZeroU32
```

```
type Err = ParseIntError
```

[source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#195-196)1.35.0
```
impl FromStr for NonZeroU64
```

```
type Err = ParseIntError
```

[source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#195-196)1.35.0
```
impl FromStr for NonZeroU128
```

```
type Err = ParseIntError
```

[source](https://doc.rust-lang.org/src/core/num/nonzero.rs.html#195-196)1.35.0
```
impl FromStr for NonZeroUsize
```

```
type Err = ParseIntError
```

[source](https://doc.rust-lang.org/src/std/path.rs.html#1742-1749)1.32.0
```
impl FromStr for PathBuf
```

```
type Err = Infallible
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2469)
```
impl FromStr for String
```

```
type Err = Infallible
```



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/str/trait.FromStr.html>

Struct std::rc::Rc
==================



```
pub struct Rc<T>
where
    T: ?Sized,{ /* private fields */ }
```

A single-threaded reference-counting pointer. ‘Rc’ stands for ‘Reference Counted’.

 See the [module-level documentation](index) for more details.

 The inherent methods of `Rc` are all associated functions, which means that you have to call them as e.g., [`Rc::get_mut(&mut value)`](struct.rc#method.get_mut "associated function std::rc::Rc::get_mut") instead of `value.get_mut()`. This avoids conflicts with methods of the inner type `T`.

 Implementations
---------------



[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#360)
```
impl<T> Rc<T>
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#372)
```
pub fn new(value: T) -> Rc<T>
```

Constructs a new `Rc<T>`.

 ##### Examples

 
```
use std::rc::Rc;

let five = Rc::new(5);
```
 
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#438-440)1.60.0
```
pub fn new_cyclic<F>(data_fn: F) -> Rc<T>
where
    F: FnOnce(&Weak<T>) -> T,
```

Constructs a new `Rc<T>` while giving you a `Weak<T>` to the allocation, to allow you to construct a `T` which holds a weak pointer to itself.

 Generally, a structure circularly referencing itself, either directly or indirectly, should not hold a strong reference to itself to prevent a memory leak. Using this function, you get access to the weak pointer during the initialization of `T`, before the `Rc<T>` is created, such that you can clone and store it inside the `T`.

 `new_cyclic` first allocates the managed allocation for the `Rc<T>`, then calls your closure, giving it a `Weak<T>` to this allocation, and only afterwards completes the construction of the `Rc<T>` by placing the `T` returned from your closure into the allocation.

 Since the new `Rc<T>` is not fully-constructed until `Rc<T>::new_cyclic` returns, calling [`upgrade`](struct.weak#method.upgrade "method std::rc::Weak::upgrade") on the weak reference inside your closure will fail and result in a `None` value.

 ##### Panics

 If `data_fn` panics, the panic is propagated to the caller, and the temporary [`Weak<T>`](struct.weak "struct std::rc::Weak") is dropped normally.

 ##### Examples

 
```
use std::rc::{Rc, Weak};

struct Gadget {
    me: Weak<Gadget>,
}

impl Gadget {
    /// Construct a reference counted Gadget.
    fn new() -> Rc<Self> {
        // `me` is a `Weak<Gadget>` pointing at the new allocation of the
        // `Rc` we're constructing.
        Rc::new_cyclic(|me| {
            // Create the actual struct here.
            Gadget { me: me.clone() }
        })
    }

    /// Return a reference counted pointer to Self.
    fn me(&self) -> Rc<Self> {
        self.me.upgrade().unwrap()
    }
}
```
 
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#502)
```
pub fn new_uninit() -> Rc<MaybeUninit<T>>
```

🔬This is a nightly-only experimental API. (`new_uninit` [#63291](https://github.com/rust-lang/rust/issues/63291))

Constructs a new `Rc` with uninitialized contents.

 ##### Examples

 
```
#![feature(new_uninit)]
#![feature(get_mut_unchecked)]

use std::rc::Rc;

let mut five = Rc::<u32>::new_uninit();

// Deferred initialization:
Rc::get_mut(&mut five).unwrap().write(5);

let five = unsafe { five.assume_init() };

assert_eq!(*five, 5)
```
 
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#535)
```
pub fn new_zeroed() -> Rc<MaybeUninit<T>>
```

🔬This is a nightly-only experimental API. (`new_uninit` [#63291](https://github.com/rust-lang/rust/issues/63291))

Constructs a new `Rc` with uninitialized contents, with the memory being filled with `0` bytes.

 See [`MaybeUninit::zeroed`](../mem/union.maybeuninit#method.zeroed "associated function std::mem::MaybeUninit::zeroed") for examples of correct and incorrect usage of this method.

 ##### Examples

 
```
#![feature(new_uninit)]

use std::rc::Rc;

let zero = Rc::<u32>::new_zeroed();
let zero = unsafe { zero.assume_init() };

assert_eq!(*zero, 0)
```
 
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#557)
```
pub fn try_new(value: T) -> Result<Rc<T>, AllocError>
```

🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838))

Constructs a new `Rc<T>`, returning an error if the allocation fails

 ##### Examples

 
```
#![feature(allocator_api)]
use std::rc::Rc;

let five = Rc::try_new(5);
```
 
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#592)
```
pub fn try_new_uninit() -> Result<Rc<MaybeUninit<T>>, AllocError>
```

🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838))

Constructs a new `Rc` with uninitialized contents, returning an error if the allocation fails

 ##### Examples

 
```
#![feature(allocator_api, new_uninit)]
#![feature(get_mut_unchecked)]

use std::rc::Rc;

let mut five = Rc::<u32>::try_new_uninit()?;

// Deferred initialization:
Rc::get_mut(&mut five).unwrap().write(5);

let five = unsafe { five.assume_init() };

assert_eq!(*five, 5);
```
 
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#625)
```
pub fn try_new_zeroed() -> Result<Rc<MaybeUninit<T>>, AllocError>
```

🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838))

Constructs a new `Rc` with uninitialized contents, with the memory being filled with `0` bytes, returning an error if the allocation fails

 See [`MaybeUninit::zeroed`](../mem/union.maybeuninit#method.zeroed "associated function std::mem::MaybeUninit::zeroed") for examples of correct and incorrect usage of this method.

 ##### Examples

 
```
#![feature(allocator_api, new_uninit)]

use std::rc::Rc;

let zero = Rc::<u32>::try_new_zeroed()?;
let zero = unsafe { zero.assume_init() };

assert_eq!(*zero, 0);
```
 
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#639)1.33.0
```
pub fn pin(value: T) -> Pin<Rc<T>>
```

Constructs a new `Pin<Rc<T>>`. If `T` does not implement `Unpin`, then `value` will be pinned in memory and unable to be moved.

 
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#664)1.4.0
```
pub fn try_unwrap(this: Rc<T>) -> Result<T, Rc<T>>
```

Returns the inner value, if the `Rc` has exactly one strong reference.

 Otherwise, an [`Err`](../result/enum.result#variant.Err "variant std::result::Result::Err") is returned with the same `Rc` that was passed in.

 This will succeed even if there are outstanding weak references.

 ##### Examples

 
```
use std::rc::Rc;

let x = Rc::new(3);
assert_eq!(Rc::try_unwrap(x), Ok(3));

let x = Rc::new(4);
let _y = Rc::clone(&x);
assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
```
 
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#697)1.70.0
```
pub fn into_inner(this: Rc<T>) -> Option<T>
```

Returns the inner value, if the `Rc` has exactly one strong reference.

 Otherwise, [`None`](../option/enum.option#variant.None "variant std::option::Option::None") is returned and the `Rc` is dropped.

 This will succeed even if there are outstanding weak references.

 If `Rc::into_inner` is called on every clone of this `Rc`, it is guaranteed that exactly one of the calls returns the inner value. This means in particular that the inner value is not dropped.

 This is equivalent to `Rc::try_unwrap(this).ok()`. (Note that these are not equivalent for [`Arc`](../sync/struct.arc "struct std::sync::Arc"), due to race conditions that do not apply to `Rc`.)

 

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#702)
```
impl<T> Rc<[T]>
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#728)
```
pub fn new_uninit_slice(len: usize) -> Rc<[MaybeUninit<T>]>
```

🔬This is a nightly-only experimental API. (`new_uninit` [#63291](https://github.com/rust-lang/rust/issues/63291))

Constructs a new reference-counted slice with uninitialized contents.

 ##### Examples

 
```
#![feature(new_uninit)]
#![feature(get_mut_unchecked)]

use std::rc::Rc;

let mut values = Rc::<[u32]>::new_uninit_slice(3);

// Deferred initialization:
let data = Rc::get_mut(&mut values).unwrap();
data[0].write(1);
data[1].write(2);
data[2].write(3);

let values = unsafe { values.assume_init() };

assert_eq!(*values, [1, 2, 3])
```
 
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#755)
```
pub fn new_zeroed_slice(len: usize) -> Rc<[MaybeUninit<T>]>
```

🔬This is a nightly-only experimental API. (`new_uninit` [#63291](https://github.com/rust-lang/rust/issues/63291))

Constructs a new reference-counted slice with uninitialized contents, with the memory being filled with `0` bytes.

 See [`MaybeUninit::zeroed`](../mem/union.maybeuninit#method.zeroed "associated function std::mem::MaybeUninit::zeroed") for examples of correct and incorrect usage of this method.

 ##### Examples

 
```
#![feature(new_uninit)]

use std::rc::Rc;

let values = Rc::<[u32]>::new_zeroed_slice(3);
let values = unsafe { values.assume_init() };

assert_eq!(*values, [0, 0, 0])
```
 

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#769)
```
impl<T> Rc<MaybeUninit<T>>
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#801)
```
pub unsafe fn assume_init(self) -> Rc<T>
```

🔬This is a nightly-only experimental API. (`new_uninit` [#63291](https://github.com/rust-lang/rust/issues/63291))

Converts to `Rc<T>`.

 ##### Safety

 As with [`MaybeUninit::assume_init`](../mem/union.maybeuninit#method.assume_init "method std::mem::MaybeUninit::assume_init"), it is up to the caller to guarantee that the inner value really is in an initialized state. Calling this when the content is not yet fully initialized causes immediate undefined behavior.

 ##### Examples

 
```
#![feature(new_uninit)]
#![feature(get_mut_unchecked)]

use std::rc::Rc;

let mut five = Rc::<u32>::new_uninit();

// Deferred initialization:
Rc::get_mut(&mut five).unwrap().write(5);

let five = unsafe { five.assume_init() };

assert_eq!(*five, 5)
```
 

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#806)
```
impl<T> Rc<[MaybeUninit<T>]>
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#841)
```
pub unsafe fn assume_init(self) -> Rc<[T]>
```

🔬This is a nightly-only experimental API. (`new_uninit` [#63291](https://github.com/rust-lang/rust/issues/63291))

Converts to `Rc<[T]>`.

 ##### Safety

 As with [`MaybeUninit::assume_init`](../mem/union.maybeuninit#method.assume_init "method std::mem::MaybeUninit::assume_init"), it is up to the caller to guarantee that the inner value really is in an initialized state. Calling this when the content is not yet fully initialized causes immediate undefined behavior.

 ##### Examples

 
```
#![feature(new_uninit)]
#![feature(get_mut_unchecked)]

use std::rc::Rc;

let mut values = Rc::<[u32]>::new_uninit_slice(3);

// Deferred initialization:
let data = Rc::get_mut(&mut values).unwrap();
data[0].write(1);
data[1].write(2);
data[2].write(3);

let values = unsafe { values.assume_init() };

assert_eq!(*values, [1, 2, 3])
```
 

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#846)
```
impl<T> Rc<T>
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#862)1.17.0
```
pub fn into_raw(this: Rc<T>) -> *const T
```

Consumes the `Rc`, returning the wrapped pointer.

 To avoid a memory leak the pointer must be converted back to an `Rc` using [`Rc::from_raw`](struct.rc#method.from_raw "associated function std::rc::Rc::from_raw").

 ##### Examples

 
```
use std::rc::Rc;

let x = Rc::new("hello".to_owned());
let x_ptr = Rc::into_raw(x);
assert_eq!(unsafe { &*x_ptr }, "hello");
```
 
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#885)1.45.0
```
pub fn as_ptr(this: &Rc<T>) -> *const T
```

Provides a raw pointer to the data.

 The counts are not affected in any way and the `Rc` is not consumed. The pointer is valid for as long there are strong counts in the `Rc`.

 ##### Examples

 
```
use std::rc::Rc;

let x = Rc::new("hello".to_owned());
let y = Rc::clone(&x);
let x_ptr = Rc::as_ptr(&x);
assert_eq!(x_ptr, Rc::as_ptr(&y));
assert_eq!(unsafe { &*x_ptr }, "hello");
```
 
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#931)1.17.0
```
pub unsafe fn from_raw(ptr: *const T) -> Rc<T>
```

Constructs an `Rc<T>` from a raw pointer.

 The raw pointer must have been previously returned by a call to [`Rc<U>::into_raw`](struct.rc#method.into_raw "associated function std::rc::Rc::into_raw") where `U` must have the same size and alignment as `T`. This is trivially true if `U` is `T`. Note that if `U` is not `T` but has the same size and alignment, this is basically like transmuting references of different types. See [`mem::transmute`](../mem/fn.transmute "fn std::mem::transmute") for more information on what restrictions apply in this case.

 The user of `from_raw` has to make sure a specific value of `T` is only dropped once.

 This function is unsafe because improper use may lead to memory unsafety, even if the returned `Rc<T>` is never accessed.

 ##### Examples

 
```
use std::rc::Rc;

let x = Rc::new("hello".to_owned());
let x_ptr = Rc::into_raw(x);

unsafe {
    // Convert back to an `Rc` to prevent leak.
    let x = Rc::from_raw(x_ptr);
    assert_eq!(&*x, "hello");

    // Further calls to `Rc::from_raw(x_ptr)` would be memory-unsafe.
}

// The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
```
 
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#954)1.4.0
```
pub fn downgrade(this: &Rc<T>) -> Weak<T>
```

Creates a new [`Weak`](struct.weak "struct std::rc::Weak") pointer to this allocation.

 ##### Examples

 
```
use std::rc::Rc;

let five = Rc::new(5);

let weak_five = Rc::downgrade(&five);
```
 
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#975)1.15.0
```
pub fn weak_count(this: &Rc<T>) -> usize
```

Gets the number of [`Weak`](struct.weak "struct std::rc::Weak") pointers to this allocation.

 ##### Examples

 
```
use std::rc::Rc;

let five = Rc::new(5);
let _weak_five = Rc::downgrade(&five);

assert_eq!(1, Rc::weak_count(&five));
```
 
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#993)1.15.0
```
pub fn strong_count(this: &Rc<T>) -> usize
```

Gets the number of strong (`Rc`) pointers to this allocation.

 ##### Examples

 
```
use std::rc::Rc;

let five = Rc::new(5);
let _also_five = Rc::clone(&five);

assert_eq!(2, Rc::strong_count(&five));
```
 
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1023)1.53.0
```
pub unsafe fn increment_strong_count(ptr: *const T)
```

Increments the strong reference count on the `Rc<T>` associated with the provided pointer by one.

 ##### Safety

 The pointer must have been obtained through `Rc::into_raw`, and the associated `Rc` instance must be valid (i.e. the strong count must be at least 1) for the duration of this method.

 ##### Examples

 
```
use std::rc::Rc;

let five = Rc::new(5);

unsafe {
    let ptr = Rc::into_raw(five);
    Rc::increment_strong_count(ptr);

    let five = Rc::from_raw(ptr);
    assert_eq!(2, Rc::strong_count(&five));
}
```
 
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1060)1.53.0
```
pub unsafe fn decrement_strong_count(ptr: *const T)
```

Decrements the strong reference count on the `Rc<T>` associated with the provided pointer by one.

 ##### Safety

 The pointer must have been obtained through `Rc::into_raw`, and the associated `Rc` instance must be valid (i.e. the strong count must be at least 1) when invoking this method. This method can be used to release the final `Rc` and backing storage, but **should not** be called after the final `Rc` has been released.

 ##### Examples

 
```
use std::rc::Rc;

let five = Rc::new(5);

unsafe {
    let ptr = Rc::into_raw(five);
    Rc::increment_strong_count(ptr);

    let five = Rc::from_raw(ptr);
    assert_eq!(2, Rc::strong_count(&five));
    Rc::decrement_strong_count(ptr);
    assert_eq!(1, Rc::strong_count(&five));
}
```
 
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1097)1.4.0
```
pub fn get_mut(this: &mut Rc<T>) -> Option<&mut T>
```

Returns a mutable reference into the given `Rc`, if there are no other `Rc` or [`Weak`](struct.weak "struct std::rc::Weak") pointers to the same allocation.

 Returns [`None`](../option/enum.option#variant.None "variant std::option::Option::None") otherwise, because it is not safe to mutate a shared value.

 See also [`make_mut`](struct.rc#method.make_mut "associated function std::rc::Rc::make_mut"), which will [`clone`](../clone/trait.clone#tymethod.clone "method std::clone::Clone::clone") the inner value when there are other `Rc` pointers.

 ##### Examples

 
```
use std::rc::Rc;

let mut x = Rc::new(3);
*Rc::get_mut(&mut x).unwrap() = 4;
assert_eq!(*x, 4);

let _y = Rc::clone(&x);
assert!(Rc::get_mut(&mut x).is_none());
```
 
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1163)
```
pub unsafe fn get_mut_unchecked(this: &mut Rc<T>) -> &mut T
```

🔬This is a nightly-only experimental API. (`get_mut_unchecked` [#63292](https://github.com/rust-lang/rust/issues/63292))

Returns a mutable reference into the given `Rc`, without any check.

 See also [`get_mut`](struct.rc#method.get_mut "associated function std::rc::Rc::get_mut"), which is safe and does appropriate checks.

 ##### Safety

 If any other `Rc` or [`Weak`](struct.weak "struct std::rc::Weak") pointers to the same allocation exist, then they must not be dereferenced or have active borrows for the duration of the returned borrow, and their inner type must be exactly the same as the inner type of this Rc (including lifetimes). This is trivially the case if no such pointers exist, for example immediately after `Rc::new`.

 ##### Examples

 
```
#![feature(get_mut_unchecked)]

use std::rc::Rc;

let mut x = Rc::new(String::new());
unsafe {
    Rc::get_mut_unchecked(&mut x).push_str("foo")
}
assert_eq!(*x, "foo");
```
 Other `Rc` pointers to the same allocation must be to the same type.

 
```
#![feature(get_mut_unchecked)]

use std::rc::Rc;

let x: Rc<str> = Rc::from("Hello, world!");
let mut y: Rc<[u8]> = x.clone().into();
unsafe {
    // this is Undefined Behavior, because x's inner type is str, not [u8]
    Rc::get_mut_unchecked(&mut y).fill(0xff); // 0xff is invalid in UTF-8
}
println!("{}", &*x); // Invalid UTF-8 in a str
```
 Other `Rc` pointers to the same allocation must be to the exact same type, including lifetimes.

 
```
#![feature(get_mut_unchecked)]

use std::rc::Rc;

let x: Rc<&str> = Rc::new("Hello, world!");
{
    let s = String::from("Oh, no!");
    let mut y: Rc<&str> = x.clone().into();
    unsafe {
        // this is Undefined Behavior, because x's inner type
        // is &'long str, not &'short str
        *Rc::get_mut_unchecked(&mut y) = &s;
    }
}
println!("{}", &*x); // Use-after-free
```
 
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1186)1.17.0
```
pub fn ptr_eq(this: &Rc<T>, other: &Rc<T>) -> bool
```

Returns `true` if the two `Rc`s point to the same allocation in a vein similar to [`ptr::eq`](../ptr/fn.eq "fn std::ptr::eq"). See [that function](../ptr/fn.eq "fn std::ptr::eq") for caveats when comparing `dyn Trait` pointers.

 ##### Examples

 
```
use std::rc::Rc;

let five = Rc::new(5);
let same_five = Rc::clone(&five);
let other_five = Rc::new(5);

assert!(Rc::ptr_eq(&five, &same_five));
assert!(!Rc::ptr_eq(&five, &other_five));
```
 

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1191)
```
impl<T> Rc<T>
where
    T: Clone,
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1245)1.4.0
```
pub fn make_mut(this: &mut Rc<T>) -> &mut T
```

Makes a mutable reference into the given `Rc`.

 If there are other `Rc` pointers to the same allocation, then `make_mut` will [`clone`](../clone/trait.clone#tymethod.clone "method std::clone::Clone::clone") the inner value to a new allocation to ensure unique ownership. This is also referred to as clone-on-write.

 However, if there are no other `Rc` pointers to this allocation, but some [`Weak`](struct.weak "struct std::rc::Weak") pointers, then the [`Weak`](struct.weak "struct std::rc::Weak") pointers will be disassociated and the inner value will not be cloned.

 See also [`get_mut`](struct.rc#method.get_mut "associated function std::rc::Rc::get_mut"), which will fail rather than cloning the inner value or disassociating [`Weak`](struct.weak "struct std::rc::Weak") pointers.

 ##### Examples

 
```
use std::rc::Rc;

let mut data = Rc::new(5);

*Rc::make_mut(&mut data) += 1;         // Won't clone anything
let mut other_data = Rc::clone(&data); // Won't clone inner data
*Rc::make_mut(&mut data) += 1;         // Clones inner data
*Rc::make_mut(&mut data) += 1;         // Won't clone anything
*Rc::make_mut(&mut other_data) *= 2;   // Won't clone anything

// Now `data` and `other_data` point to different allocations.
assert_eq!(*data, 8);
assert_eq!(*other_data, 12);
```
 [`Weak`](struct.weak "struct std::rc::Weak") pointers will be disassociated:

 
```
use std::rc::Rc;

let mut data = Rc::new(75);
let weak = Rc::downgrade(&data);

assert!(75 == *data);
assert!(75 == *weak.upgrade().unwrap());

*Rc::make_mut(&mut data) += 1;

assert!(76 == *data);
assert!(weak.upgrade().is_none());
```
 
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1308)
```
pub fn unwrap_or_clone(this: Rc<T>) -> T
```

🔬This is a nightly-only experimental API. (`arc_unwrap_or_clone` [#93610](https://github.com/rust-lang/rust/issues/93610))

If we have the only reference to `T` then unwrap it. Otherwise, clone `T` and return the clone.

 Assuming `rc_t` is of type `Rc<T>`, this function is functionally equivalent to `(*rc_t).clone()`, but will avoid cloning the inner value where possible.

 ##### Examples

 
```
#![feature(arc_unwrap_or_clone)]
let inner = String::from("test");
let ptr = inner.as_ptr();

let rc = Rc::new(inner);
let inner = Rc::unwrap_or_clone(rc);
// The inner value was not cloned
assert!(ptr::eq(ptr, inner.as_ptr()));

let rc = Rc::new(inner);
let rc2 = rc.clone();
let inner = Rc::unwrap_or_clone(rc);
// Because there were 2 references, we had to clone the inner value.
assert!(!ptr::eq(ptr, inner.as_ptr()));
// `rc2` is the last reference, so when we unwrap it we get back
// the original `String`.
let inner = Rc::unwrap_or_clone(rc2);
assert!(ptr::eq(ptr, inner.as_ptr()));
```
 

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1313)
```
impl Rc<dyn Any + 'static>
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1334)1.29.0
```
pub fn downcast<T>(self) -> Result<Rc<T>, Rc<dyn Any + 'static>>
where
    T: Any,
```

Attempt to downcast the `Rc<dyn Any>` to a concrete type.

 ##### Examples

 
```
use std::any::Any;
use std::rc::Rc;

fn print_if_string(value: Rc<dyn Any>) {
    if let Ok(string) = value.downcast::<String>() {
        println!("String ({}): {}", string.len(), string);
    }
}

let my_string = "Hello World".to_string();
print_if_string(Rc::new(my_string));
print_if_string(Rc::new(0i8));
```
 
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1374)
```
pub unsafe fn downcast_unchecked<T>(self) -> Rc<T>
where
    T: Any,
```

🔬This is a nightly-only experimental API. (`downcast_unchecked` [#90850](https://github.com/rust-lang/rust/issues/90850))

Downcasts the `Rc<dyn Any>` to a concrete type.

 For a safe alternative see [`downcast`](struct.rc#method.downcast "method std::rc::Rc::downcast").

 ##### Examples

 
```
#![feature(downcast_unchecked)]

use std::any::Any;
use std::rc::Rc;

let x: Rc<dyn Any> = Rc::new(1_usize);

unsafe {
    assert_eq!(*x.downcast_unchecked::<usize>(), 1);
}
```
 ##### Safety

 The contained value must be of type `T`. Calling this method with the incorrect type is *undefined behavior*.

 


Trait Implementations
---------------------



[source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#403-408)1.69.0
```
impl<T: AsFd> AsFd for Rc<T>
```

[source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#405-407)
```
fn as_fd(&self) -> BorrowedFd<'_>
```
Borrows the file descriptor. [Read more](../os/fd/trait.asfd#tymethod.as_fd)


[source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#461-466)1.71.0
```
impl<T: AsHandle> AsHandle for Rc<T>Available on Windows only.
```

[source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#463-465)
```
fn as_handle(&self) -> BorrowedHandle<'_>
```
Borrows the handle. [Read more](../os/windows/io/trait.ashandle#tymethod.as_handle)


[source](https://doc.rust-lang.org/src/std/os/fd/raw.rs.html#258-263)1.69.0
```
impl<T: AsRawFd> AsRawFd for Rc<T>
```

[source](https://doc.rust-lang.org/src/std/os/fd/raw.rs.html#260-262)
```
fn as_raw_fd(&self) -> RawFd
```
Extracts the raw file descriptor. [Read more](../os/fd/trait.asrawfd#tymethod.as_raw_fd)


[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2719)1.5.0
```
impl<T> AsRef<T> for Rc<T>
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2720)
```
fn as_ref(&self) -> &T
```
Converts this type into a shared reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/std/os/windows/io/socket.rs.html#278-283)1.71.0
```
impl<T: AsSocket> AsSocket for Rc<T>Available on Windows only.
```

[source](https://doc.rust-lang.org/src/std/os/windows/io/socket.rs.html#280-282)
```
fn as_socket(&self) -> BorrowedSocket<'_>
```
Borrows the socket.

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2712)
```
impl<T> Borrow<T> for Rc<T>
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2713)
```
fn borrow(&self) -> &T
```
Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1624)
```
impl<T> Clone for Rc<T>
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1640)
```
fn clone(&self) -> Rc<T>
```

Makes a clone of the `Rc` pointer.

 This creates another pointer to the same allocation, increasing the strong reference count.

 ##### Examples

 
```
use std::rc::Rc;

let five = Rc::new(5);

let _ = Rc::clone(&five);
```
 
[source](https://doc.rust-lang.org/src/core/clone.rs.html#129)
```
fn clone_from(&mut self, source: &Self)
```
Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from)


[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1894)
```
impl<T> Debug for Rc<T>
where
    T: Debug + ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1895)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt)


[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1650)
```
impl<T> Default for Rc<T>
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1662)
```
fn default() -> Rc<T>
```

Creates a new `Rc<T>`, with the `Default` value for `T`.

 ##### Examples

 
```
use std::rc::Rc;

let x: Rc<i32> = Default::default();
assert_eq!(*x, 0);
```
 

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1565)
```
impl<T> Deref for Rc<T>
where
    T: ?Sized,
```


```
type Target = T
```
The resulting type after dereferencing.
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1569)
```
fn deref(&self) -> &T
```
Dereferences the value.

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1887)
```
impl<T> Display for Rc<T>
where
    T: Display + ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1888)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter. [Read more](../fmt/trait.display#tymethod.fmt)


[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1578)
```
impl<T> Drop for Rc<T>
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1604)
```
fn drop(&mut self)
```

Drops the `Rc`.

 This will decrement the strong reference count. If the strong reference count reaches zero then the only other references (if any) are [`Weak`](struct.weak "struct std::rc::Weak"), so we `drop` the inner value.

 ##### Examples

 
```
use std::rc::Rc;

struct Foo;

impl Drop for Foo {
    fn drop(&mut self) {
        println!("dropped!");
    }
}

let foo  = Rc::new(Foo);
let foo2 = Rc::clone(&foo);

drop(foo);    // Doesn't print anything
drop(foo2);   // Prints "dropped!"
```
 

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1930)1.21.0
```
impl<T> From<&[T]> for Rc<[T]>
where
    T: Clone,
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1942)
```
fn from(v: &[T]) -> Rc<[T]>
```

Allocate a reference-counted slice and fill it by cloning `v`’s items.

 ##### Example

 
```
let original: &[i32] = &[1, 2, 3];
let shared: Rc<[i32]> = Rc::from(original);
assert_eq!(&[1, 2, 3], &shared[..]);
```
 

[source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#900)1.24.0
```
impl From<&CStr> for Rc<CStr>
```

[source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#904)
```
fn from(s: &CStr) -> Rc<CStr>
```

Converts a `&CStr` into a `Rc<CStr>`, by copying the contents into a newly allocated [`Rc`](struct.rc "struct std::rc::Rc").

 

[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1066-1073)1.24.0
```
impl From<&OsStr> for Rc<OsStr>
```

[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1069-1072)
```
fn from(s: &OsStr) -> Rc<OsStr>
```

Copies the string into a newly allocated `[Rc](struct.rc "struct std::rc::Rc")<[OsStr](../ffi/struct.osstr "struct std::ffi::OsStr")>`.

 

[source](https://doc.rust-lang.org/src/std/path.rs.html#1892-1899)1.24.0
```
impl From<&Path> for Rc<Path>
```

[source](https://doc.rust-lang.org/src/std/path.rs.html#1895-1898)
```
fn from(s: &Path) -> Rc<Path>
```

Converts a [`Path`](../path/struct.path "struct std::path::Path") into an [`Rc`](struct.rc "struct std::rc::Rc") by copying the [`Path`](../path/struct.path "struct std::path::Path") data into a new [`Rc`](struct.rc "struct std::rc::Rc") buffer.

 

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1949)1.21.0
```
impl From<&str> for Rc<str>
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1960)
```
fn from(v: &str) -> Rc<str>
```

Allocate a reference-counted string slice and copy `v` into it.

 ##### Example

 
```
let shared: Rc<str> = Rc::from("statue");
assert_eq!("statue", &shared[..]);
```
 

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1987)1.21.0
```
impl<T> From<Box<T, Global>> for Rc<T>
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1999)
```
fn from(v: Box<T, Global>) -> Rc<T>
```

Move a boxed object to a new, reference counted, allocation.

 ##### Example

 
```
let original: Box<i32> = Box::new(1);
let shared: Rc<i32> = Rc::from(original);
assert_eq!(1, *shared);
```
 

[source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#889)1.24.0
```
impl From<CString> for Rc<CStr>
```

[source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#893)
```
fn from(s: CString) -> Rc<CStr>
```

Converts a [`CString`](../ffi/struct.cstring "struct std::ffi::CString") into an `[Rc](struct.rc "struct std::rc::Rc")<[CStr](../ffi/struct.cstr "struct std::ffi::CStr")>` by moving the [`CString`](../ffi/struct.cstring "struct std::ffi::CString") data into a new [`Arc`](../sync/struct.arc "struct std::sync::Arc") buffer.

 

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2029)1.45.0
```
impl<'a, B> From<Cow<'a, B>> for Rc<B>
where
    B: ToOwned + ?Sized,
    Rc<B>: From<&'a B> + From<<B as ToOwned>::Owned>,
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2047)
```
fn from(cow: Cow<'a, B>) -> Rc<B>
```

Create a reference-counted pointer from a clone-on-write pointer by copying its content.

 ##### Example

 
```
let cow: Cow<'_, str> = Cow::Borrowed("eggplant");
let shared: Rc<str> = Rc::from(cow);
assert_eq!("eggplant", &shared[..]);
```
 

[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1055-1063)1.24.0
```
impl From<OsString> for Rc<OsStr>
```

[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1059-1062)
```
fn from(s: OsString) -> Rc<OsStr>
```

Converts an [`OsString`](../ffi/struct.osstring "struct std::ffi::OsString") into an `[Rc](struct.rc "struct std::rc::Rc")<[OsStr](../ffi/struct.osstr "struct std::ffi::OsStr")>` by moving the [`OsString`](../ffi/struct.osstring "struct std::ffi::OsString") data into a new [`Rc`](struct.rc "struct std::rc::Rc") buffer.

 

[source](https://doc.rust-lang.org/src/std/path.rs.html#1881-1889)1.24.0
```
impl From<PathBuf> for Rc<Path>
```

[source](https://doc.rust-lang.org/src/std/path.rs.html#1885-1888)
```
fn from(s: PathBuf) -> Rc<Path>
```

Converts a [`PathBuf`](../path/struct.pathbuf "struct std::path::PathBuf") into an `[Rc](struct.rc "struct std::rc::Rc")<[Path](../path/struct.path "struct std::path::Path")>` by moving the [`PathBuf`](../path/struct.pathbuf "struct std::path::PathBuf") data into a new [`Rc`](struct.rc "struct std::rc::Rc") buffer.

 

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2056)1.62.0
```
impl From<Rc<str>> for Rc<[u8]>
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2068)
```
fn from(rc: Rc<str>) -> Rc<[u8]>
```

Converts a reference-counted string slice into a byte slice.

 ##### Example

 
```
let string: Rc<str> = Rc::from("eggplant");
let bytes: Rc<[u8]> = Rc::from(string);
assert_eq!("eggplant".as_bytes(), bytes.as_ref());
```
 

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1968)1.21.0
```
impl From<String> for Rc<str>
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1980)
```
fn from(v: String) -> Rc<str>
```

Allocate a reference-counted string slice and copy `v` into it.

 ##### Example

 
```
let original: String = "statue".to_owned();
let shared: Rc<str> = Rc::from(original);
assert_eq!("statue", &shared[..]);
```
 

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1909)1.6.0
```
impl<T> From<T> for Rc<T>
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1923)
```
fn from(t: T) -> Rc<T>
```

Converts a generic type `T` into an `Rc<T>`

 The conversion allocates on the heap and moves `t` from the stack into it.

 ##### Example

 
```
let x = 5;
let rc = Rc::new(5);

assert_eq!(Rc::from(x), rc);
```
 

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2006)1.21.0
```
impl<T> From<Vec<T, Global>> for Rc<[T]>
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2018)
```
fn from(v: Vec<T, Global>) -> Rc<[T]>
```

Allocate a reference-counted slice and move `v`’s items into it.

 ##### Example

 
```
let original: Box<Vec<i32>> = Box::new(vec![1, 2, 3]);
let shared: Rc<Vec<i32>> = Rc::from(original);
assert_eq!(vec![1, 2, 3], *shared);
```
 

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2089)1.37.0
```
impl<T> FromIterator<T> for Rc<[T]>
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2128)
```
fn from_iter<I>(iter: I) -> Rc<[T]>
where
    I: IntoIterator<Item = T>,
```

Takes each element in the `Iterator` and collects it into an `Rc<[T]>`.

 ##### Performance characteristics


###### [The general case](#the-general-case)

 In the general case, collecting into `Rc<[T]>` is done by first collecting into a `Vec<T>`. That is, when writing the following:

 
```
let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect();
```
 this behaves as if we wrote:

 
```
let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0)
    .collect::<Vec<_>>() // The first set of allocations happens here.
    .into(); // A second allocation for `Rc<[T]>` happens here.
```
 This will allocate as many times as needed for constructing the `Vec<T>` and then it will allocate once for turning the `Vec<T>` into the `Rc<[T]>`.

 ###### [Iterators of known length](#iterators-of-known-length)

 When your `Iterator` implements `TrustedLen` and is of an exact size, a single allocation will be made for the `Rc<[T]>`. For example:

 
```
let evens: Rc<[u8]> = (0..10).collect(); // Just a single allocation happens here.
```
 

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1880)
```
impl<T> Hash for Rc<T>
where
    T: Hash + ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1881)
```
fn hash<H>(&self, state: &mut H)
where
    H: Hasher,
```
Feeds this value into the given [`Hasher`](../hash/trait.hasher "trait std::hash::Hasher"). [Read more](../hash/trait.hash#tymethod.hash)

[source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#237-239)1.3.0
```
fn hash_slice<H>(data: &[Self], state: &mut H)
where
    H: Hasher,
    Self: Sized,
```
Feeds a slice of this type into the given [`Hasher`](../hash/trait.hasher "trait std::hash::Hasher"). [Read more](../hash/trait.hash#method.hash_slice)


[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1858)
```
impl<T> Ord for Rc<T>
where
    T: Ord + ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1874)
```
fn cmp(&self, other: &Rc<T>) -> Ordering
```

Comparison for two `Rc`s.

 The two are compared by calling `cmp()` on their inner values.

 ##### Examples

 
```
use std::rc::Rc;
use std::cmp::Ordering;

let five = Rc::new(5);

assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
```
 
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#790-792)1.21.0
```
fn max(self, other: Self) -> Self
where
    Self: Sized,
```
Compares and returns the maximum of two values. [Read more](../cmp/trait.ord#method.max)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#810-812)1.21.0
```
fn min(self, other: Self) -> Self
where
    Self: Sized,
```
Compares and returns the minimum of two values. [Read more](../cmp/trait.ord#method.min)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#835-838)1.50.0
```
fn clamp(self, min: Self, max: Self) -> Self
where
    Self: Sized + PartialOrd<Self>,
```
Restrict a value to a certain interval. [Read more](../cmp/trait.ord#method.clamp)


[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1713)
```
impl<T> PartialEq<Rc<T>> for Rc<T>
where
    T: PartialEq<T> + ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1733)
```
fn eq(&self, other: &Rc<T>) -> bool
```

Equality for two `Rc`s.

 Two `Rc`s are equal if their inner values are equal, even if they are stored in different allocation.

 If `T` also implements `Eq` (implying reflexivity of equality), two `Rc`s that point to the same allocation are always equal.

 ##### Examples

 
```
use std::rc::Rc;

let five = Rc::new(5);

assert!(five == Rc::new(5));
```
 
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1755)
```
fn ne(&self, other: &Rc<T>) -> bool
```

Inequality for two `Rc`s.

 Two `Rc`s are not equal if their inner values are not equal.

 If `T` also implements `Eq` (implying reflexivity of equality), two `Rc`s that point to the same allocation are always equal.

 ##### Examples

 
```
use std::rc::Rc;

let five = Rc::new(5);

assert!(five != Rc::new(6));
```
 

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1764)
```
impl<T> PartialOrd<Rc<T>> for Rc<T>
where
    T: PartialOrd<T> + ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1780)
```
fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering>
```

Partial comparison for two `Rc`s.

 The two are compared by calling `partial_cmp()` on their inner values.

 ##### Examples

 
```
use std::rc::Rc;
use std::cmp::Ordering;

let five = Rc::new(5);

assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
```
 
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1798)
```
fn lt(&self, other: &Rc<T>) -> bool
```

Less-than comparison for two `Rc`s.

 The two are compared by calling `<` on their inner values.

 ##### Examples

 
```
use std::rc::Rc;

let five = Rc::new(5);

assert!(five < Rc::new(6));
```
 
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1816)
```
fn le(&self, other: &Rc<T>) -> bool
```

‘Less than or equal to’ comparison for two `Rc`s.

 The two are compared by calling `<=` on their inner values.

 ##### Examples

 
```
use std::rc::Rc;

let five = Rc::new(5);

assert!(five <= Rc::new(5));
```
 
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1834)
```
fn gt(&self, other: &Rc<T>) -> bool
```

Greater-than comparison for two `Rc`s.

 The two are compared by calling `>` on their inner values.

 ##### Examples

 
```
use std::rc::Rc;

let five = Rc::new(5);

assert!(five > Rc::new(4));
```
 
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1852)
```
fn ge(&self, other: &Rc<T>) -> bool
```

‘Greater than or equal to’ comparison for two `Rc`s.

 The two are compared by calling `>=` on their inner values.

 ##### Examples

 
```
use std::rc::Rc;

let five = Rc::new(5);

assert!(five >= Rc::new(5));
```
 

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1901)
```
impl<T> Pointer for Rc<T>
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1902)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter.

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2075)1.43.0
```
impl<T, const N: usize> TryFrom<Rc<[T]>> for Rc<[T; N]>
```


```
type Error = Rc<[T]>
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2078)
```
fn try_from(
    boxed_slice: Rc<[T]>
) -> Result<Rc<[T; N]>, <Rc<[T; N]> as TryFrom<Rc<[T]>>>::Error>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#338)
```
impl<T, U> CoerceUnsized<Rc<U>> for Rc<T>
where
    T: Unsize<U> + ?Sized,
    U: ?Sized,
```
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#341)
```
impl<T, U> DispatchFromDyn<Rc<U>> for Rc<T>
where
    T: Unsize<U> + ?Sized,
    U: ?Sized,
```
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#1761)
```
impl<T> Eq for Rc<T>
where
    T: Eq + ?Sized,
```
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#335)1.58.0
```
impl<T> RefUnwindSafe for Rc<T>
where
    T: RefUnwindSafe + ?Sized,
```
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#322)
```
impl<T> !Send for Rc<T>
where
    T: ?Sized,
```
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#330)
```
impl<T> !Sync for Rc<T>
where
    T: ?Sized,
```
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#2726)1.33.0
```
impl<T> Unpin for Rc<T>
where
    T: ?Sized,
```
[source](https://doc.rust-lang.org/src/alloc/rc.rs.html#333)1.9.0
```
impl<T> UnwindSafe for Rc<T>
where
    T: RefUnwindSafe + ?Sized,
```


Blanket Implementations
-----------------------



[source](https://doc.rust-lang.org/src/core/any.rs.html#200)
```
impl<T> Any for T
where
    T: 'static + ?Sized,
```

[source](https://doc.rust-lang.org/src/core/any.rs.html#201)
```
fn type_id(&self) -> TypeId
```
Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#208)
```
impl<T> Borrow<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#210)
```
fn borrow(&self) -> &T
```
Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#216)
```
impl<T> BorrowMut<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#217)
```
fn borrow_mut(&mut self) -> &mut T
```
Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#740)
```
impl<T> From<!> for T
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#741)
```
fn from(t: !) -> T
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#723)
```
impl<T> From<T> for T
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#726)
```
fn from(t: T) -> T
```

Returns the argument unchanged.

 

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#707)
```
impl<T, U> Into<U> for T
where
    U: From<T>,
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#716)
```
fn into(self) -> U
```

Calls `U::from(self)`.

 That is, this conversion is whatever the implementation of `[From](../convert/trait.from "trait std::convert::From")<T> for U` chooses to do.

 

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#82)
```
impl<T> ToOwned for T
where
    T: Clone,
```


```
type Owned = T
```
The resulting type after obtaining ownership.
[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#87)
```
fn to_owned(&self) -> T
```
Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned)

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#91)
```
fn clone_into(&self, target: &mut T)
```
Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2513)
```
impl<T> ToString for T
where
    T: Display + ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2519)
```
default fn to_string(&self) -> String
```
Converts the given value to a `String`. [Read more](../string/trait.tostring#tymethod.to_string)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#763)
```
impl<T, U> TryFrom<U> for T
where
    U: Into<T>,
```


```
type Error = Infallible
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#770)
```
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#748)
```
impl<T, U> TryInto<U> for T
where
    U: TryFrom<T>,
```


```
type Error = <U as TryFrom<T>>::Error
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#755)
```
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
```
Performs the conversion.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/rc/struct.Rc.html>

Struct std::cell::Cell
======================



```
#[repr(transparent)]pub struct Cell<T>
where
    T: ?Sized,{ /* private fields */ }
```

A mutable memory location.

 Memory layout
-------------

 `Cell<T>` has the same [memory layout and caveats as `UnsafeCell<T>`](struct.unsafecell#memory-layout "struct std::cell::UnsafeCell"). In particular, this means that `Cell<T>` has the same in-memory representation as its inner type `T`.

 Examples
--------

 In this example, you can see that `Cell<T>` enables mutation inside an immutable struct. In other words, it enables “interior mutability”.

 
```
use std::cell::Cell;

struct SomeStruct {
    regular_field: u8,
    special_field: Cell<u8>,
}

let my_struct = SomeStruct {
    regular_field: 0,
    special_field: Cell::new(1),
};

let new_value = 100;

// ERROR: `my_struct` is immutable
// my_struct.regular_field = new_value;

// WORKS: although `my_struct` is immutable, `special_field` is a `Cell`,
// which can always be mutated
my_struct.special_field.set(new_value);
assert_eq!(my_struct.special_field.get(), new_value);
```
 See the [module-level documentation](index "mod std::cell") for more.

 Implementations
---------------



[source](https://doc.rust-lang.org/src/core/cell.rs.html#380)
```
impl<T> Cell<T>
```

[source](https://doc.rust-lang.org/src/core/cell.rs.html#393)const: 1.24.0
```
pub const fn new(value: T) -> Cell<T>
```

Creates a new `Cell` containing the given value.

 ##### Examples

 
```
use std::cell::Cell;

let c = Cell::new(5);
```
 
[source](https://doc.rust-lang.org/src/core/cell.rs.html#410)
```
pub fn set(&self, val: T)
```

Sets the contained value.

 ##### Examples

 
```
use std::cell::Cell;

let c = Cell::new(5);

c.set(10);
```
 
[source](https://doc.rust-lang.org/src/core/cell.rs.html#431)1.17.0
```
pub fn swap(&self, other: &Cell<T>)
```

Swaps the values of two `Cell`s. Difference with `std::mem::swap` is that this function doesn’t require `&mut` reference.

 ##### Examples

 
```
use std::cell::Cell;

let c1 = Cell::new(5i32);
let c2 = Cell::new(10i32);
c1.swap(&c2);
assert_eq!(10, c1.get());
assert_eq!(5, c2.get());
```
 
[source](https://doc.rust-lang.org/src/core/cell.rs.html#458)1.17.0
```
pub fn replace(&self, val: T) -> T
```

Replaces the contained value with `val`, and returns the old contained value.

 ##### Examples

 
```
use std::cell::Cell;

let cell = Cell::new(5);
assert_eq!(cell.get(), 5);
assert_eq!(cell.replace(10), 5);
assert_eq!(cell.get(), 10);
```
 
[source](https://doc.rust-lang.org/src/core/cell.rs.html#478)1.17.0 (const: [unstable](https://github.com/rust-lang/rust/issues/78729 "Tracking issue for const_cell_into_inner"))
```
pub fn into_inner(self) -> T
```

Unwraps the value, consuming the cell.

 ##### Examples

 
```
use std::cell::Cell;

let c = Cell::new(5);
let five = c.into_inner();

assert_eq!(five, 5);
```
 

[source](https://doc.rust-lang.org/src/core/cell.rs.html#483)
```
impl<T> Cell<T>
where
    T: Copy,
```

[source](https://doc.rust-lang.org/src/core/cell.rs.html#497)
```
pub fn get(&self) -> T
```

Returns a copy of the contained value.

 ##### Examples

 
```
use std::cell::Cell;

let c = Cell::new(5);

let five = c.get();
```
 
[source](https://doc.rust-lang.org/src/core/cell.rs.html#520-522)
```
pub fn update<F>(&self, f: F) -> T
where
    F: FnOnce(T) -> T,
```

🔬This is a nightly-only experimental API. (`cell_update` [#50186](https://github.com/rust-lang/rust/issues/50186))

Updates the contained value using a function and returns the new value.

 ##### Examples

 
```
#![feature(cell_update)]

use std::cell::Cell;

let c = Cell::new(5);
let new = c.update(|x| x + 1);

assert_eq!(new, 6);
assert_eq!(c.get(), 6);
```
 

[source](https://doc.rust-lang.org/src/core/cell.rs.html#531)
```
impl<T> Cell<T>
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/cell.rs.html#546)1.12.0 (const: 1.32.0)
```
pub const fn as_ptr(&self) -> *mut T
```

Returns a raw pointer to the underlying data in this cell.

 ##### Examples

 
```
use std::cell::Cell;

let c = Cell::new(5);

let ptr = c.as_ptr();
```
 
[source](https://doc.rust-lang.org/src/core/cell.rs.html#574)1.11.0
```
pub fn get_mut(&mut self) -> &mut T
```

Returns a mutable reference to the underlying data.

 This call borrows `Cell` mutably (at compile-time) which guarantees that we possess the only reference.

 However be cautious: this method expects `self` to be mutable, which is generally not the case when using a `Cell`. If you require interior mutability by reference, consider using `RefCell` which provides run-time checked mutable borrows through its [`borrow_mut`](struct.refcell#method.borrow_mut "method std::cell::RefCell::borrow_mut") method.

 ##### Examples

 
```
use std::cell::Cell;

let mut c = Cell::new(5);
*c.get_mut() += 1;

assert_eq!(c.get(), 6);
```
 
[source](https://doc.rust-lang.org/src/core/cell.rs.html#593)1.37.0
```
pub fn from_mut(t: &mut T) -> &Cell<T>
```

Returns a `&Cell<T>` from a `&mut T`

 ##### Examples

 
```
use std::cell::Cell;

let slice: &mut [i32] = &mut [1, 2, 3];
let cell_slice: &Cell<[i32]> = Cell::from_mut(slice);
let slice_cell: &[Cell<i32>] = cell_slice.as_slice_of_cells();

assert_eq!(slice_cell.len(), 3);
```
 

[source](https://doc.rust-lang.org/src/core/cell.rs.html#599)
```
impl<T> Cell<T>
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/cell.rs.html#614)1.17.0
```
pub fn take(&self) -> T
```

Takes the value of the cell, leaving `Default::default()` in its place.

 ##### Examples

 
```
use std::cell::Cell;

let c = Cell::new(5);
let five = c.take();

assert_eq!(five, 5);
assert_eq!(c.into_inner(), 0);
```
 

[source](https://doc.rust-lang.org/src/core/cell.rs.html#632)
```
impl<T> Cell<[T]>
```

[source](https://doc.rust-lang.org/src/core/cell.rs.html#647)1.37.0
```
pub fn as_slice_of_cells(&self) -> &[Cell<T>]
```

Returns a `&[Cell<T>]` from a `&Cell<[T]>`

 ##### Examples

 
```
use std::cell::Cell;

let slice: &mut [i32] = &mut [1, 2, 3];
let cell_slice: &Cell<[i32]> = Cell::from_mut(slice);
let slice_cell: &[Cell<i32>] = cell_slice.as_slice_of_cells();

assert_eq!(slice_cell.len(), 3);
```
 

[source](https://doc.rust-lang.org/src/core/cell.rs.html#653)
```
impl<T, const N: usize> Cell<[T; N]>
```

[source](https://doc.rust-lang.org/src/core/cell.rs.html#667)
```
pub fn as_array_of_cells(&self) -> &[Cell<T>; N]
```

🔬This is a nightly-only experimental API. (`as_array_of_cells` [#88248](https://github.com/rust-lang/rust/issues/88248))

Returns a `&[Cell<T>; N]` from a `&Cell<[T; N]>`

 ##### Examples

 
```
#![feature(as_array_of_cells)]
use std::cell::Cell;

let mut array: [i32; 3] = [1, 2, 3];
let cell_array: &Cell<[i32; 3]> = Cell::from_mut(&mut array);
let array_cell: &[Cell<i32>; 3] = cell_array.as_array_of_cells();
```
 


Trait Implementations
---------------------



[source](https://doc.rust-lang.org/src/core/cell.rs.html#309)
```
impl<T> Clone for Cell<T>
where
    T: Copy,
```

[source](https://doc.rust-lang.org/src/core/cell.rs.html#311)
```
fn clone(&self) -> Cell<T>
```
Returns a copy of the value. [Read more](../clone/trait.clone#tymethod.clone)

[source](https://doc.rust-lang.org/src/core/clone.rs.html#129)
```
fn clone_from(&mut self, source: &Self)
```
Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from)


[source](https://doc.rust-lang.org/src/core/fmt/mod.rs.html#2515)
```
impl<T> Debug for Cell<T>
where
    T: Copy + Debug,
```

[source](https://doc.rust-lang.org/src/core/fmt/mod.rs.html#2516)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt)


[source](https://doc.rust-lang.org/src/core/cell.rs.html#317)
```
impl<T> Default for Cell<T>
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/cell.rs.html#320)
```
fn default() -> Cell<T>
```

Creates a `Cell<T>`, with the `Default` value for T.

 

[source](https://doc.rust-lang.org/src/core/cell.rs.html#373)1.12.0
```
impl<T> From<T> for Cell<T>
```

[source](https://doc.rust-lang.org/src/core/cell.rs.html#375)
```
fn from(t: T) -> Cell<T>
```

Creates a new `Cell<T>` containing the given value.

 

[source](https://doc.rust-lang.org/src/core/cell.rs.html#365)1.10.0
```
impl<T> Ord for Cell<T>
where
    T: Ord + Copy,
```

[source](https://doc.rust-lang.org/src/core/cell.rs.html#367)
```
fn cmp(&self, other: &Cell<T>) -> Ordering
```
This method returns an [`Ordering`](../cmp/enum.ordering "enum std::cmp::Ordering") between `self` and `other`. [Read more](../cmp/trait.ord#tymethod.cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#790-792)1.21.0
```
fn max(self, other: Self) -> Self
where
    Self: Sized,
```
Compares and returns the maximum of two values. [Read more](../cmp/trait.ord#method.max)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#810-812)1.21.0
```
fn min(self, other: Self) -> Self
where
    Self: Sized,
```
Compares and returns the minimum of two values. [Read more](../cmp/trait.ord#method.min)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#835-838)1.50.0
```
fn clamp(self, min: Self, max: Self) -> Self
where
    Self: Sized + PartialOrd<Self>,
```
Restrict a value to a certain interval. [Read more](../cmp/trait.ord#method.clamp)


[source](https://doc.rust-lang.org/src/core/cell.rs.html#326)
```
impl<T> PartialEq<Cell<T>> for Cell<T>
where
    T: PartialEq<T> + Copy,
```

[source](https://doc.rust-lang.org/src/core/cell.rs.html#328)
```
fn eq(&self, other: &Cell<T>) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#226)
```
fn ne(&self, other: &Rhs) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/cell.rs.html#337)1.10.0
```
impl<T> PartialOrd<Cell<T>> for Cell<T>
where
    T: PartialOrd<T> + Copy,
```

[source](https://doc.rust-lang.org/src/core/cell.rs.html#339)
```
fn partial_cmp(&self, other: &Cell<T>) -> Option<Ordering>
```
This method returns an ordering between `self` and `other` values if one exists. [Read more](../cmp/trait.partialord#tymethod.partial_cmp)

[source](https://doc.rust-lang.org/src/core/cell.rs.html#344)
```
fn lt(&self, other: &Cell<T>) -> bool
```
This method tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](../cmp/trait.partialord#method.lt)

[source](https://doc.rust-lang.org/src/core/cell.rs.html#349)
```
fn le(&self, other: &Cell<T>) -> bool
```
This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](../cmp/trait.partialord#method.le)

[source](https://doc.rust-lang.org/src/core/cell.rs.html#354)
```
fn gt(&self, other: &Cell<T>) -> bool
```
This method tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](../cmp/trait.partialord#method.gt)

[source](https://doc.rust-lang.org/src/core/cell.rs.html#359)
```
fn ge(&self, other: &Cell<T>) -> bool
```
This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](../cmp/trait.partialord#method.ge)


[source](https://doc.rust-lang.org/src/core/cell.rs.html#620)
```
impl<T, U> CoerceUnsized<Cell<U>> for Cell<T>
where
    T: CoerceUnsized<U>,
```
[source](https://doc.rust-lang.org/src/core/cell.rs.html#630)
```
impl<T, U> DispatchFromDyn<Cell<U>> for Cell<T>
where
    T: DispatchFromDyn<U>,
```
[source](https://doc.rust-lang.org/src/core/cell.rs.html#334)1.2.0
```
impl<T> Eq for Cell<T>
where
    T: Eq + Copy,
```
[source](https://doc.rust-lang.org/src/core/cell.rs.html#298)
```
impl<T> Send for Cell<T>
where
    T: Send + ?Sized,
```
[source](https://doc.rust-lang.org/src/core/cell.rs.html#306)
```
impl<T> !Sync for Cell<T>
where
    T: ?Sized,
```


Auto Trait Implementations
--------------------------




```
impl<T> !RefUnwindSafe for Cell<T>
```

```
impl<T: ?Sized> Unpin for Cell<T>
where
    T: Unpin,
```

```
impl<T: ?Sized> UnwindSafe for Cell<T>
where
    T: UnwindSafe,
```


Blanket Implementations
-----------------------



[source](https://doc.rust-lang.org/src/core/any.rs.html#200)
```
impl<T> Any for T
where
    T: 'static + ?Sized,
```

[source](https://doc.rust-lang.org/src/core/any.rs.html#201)
```
fn type_id(&self) -> TypeId
```
Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#208)
```
impl<T> Borrow<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#210)
```
fn borrow(&self) -> &T
```
Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#216)
```
impl<T> BorrowMut<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#217)
```
fn borrow_mut(&mut self) -> &mut T
```
Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#740)
```
impl<T> From<!> for T
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#741)
```
fn from(t: !) -> T
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#723)
```
impl<T> From<T> for T
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#726)
```
fn from(t: T) -> T
```

Returns the argument unchanged.

 

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#707)
```
impl<T, U> Into<U> for T
where
    U: From<T>,
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#716)
```
fn into(self) -> U
```

Calls `U::from(self)`.

 That is, this conversion is whatever the implementation of `[From](../convert/trait.from "trait std::convert::From")<T> for U` chooses to do.

 

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#82)
```
impl<T> ToOwned for T
where
    T: Clone,
```


```
type Owned = T
```
The resulting type after obtaining ownership.
[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#87)
```
fn to_owned(&self) -> T
```
Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned)

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#91)
```
fn clone_into(&self, target: &mut T)
```
Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#763)
```
impl<T, U> TryFrom<U> for T
where
    U: Into<T>,
```


```
type Error = Infallible
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#770)
```
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#748)
```
impl<T, U> TryInto<U> for T
where
    U: TryFrom<T>,
```


```
type Error = <U as TryFrom<T>>::Error
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#755)
```
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
```
Performs the conversion.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/cell/struct.Cell.html>

Struct std::cell::RefCell
=========================



```
pub struct RefCell<T>
where
    T: ?Sized,{ /* private fields */ }
```

A mutable memory location with dynamically checked borrow rules

 See the [module-level documentation](index "mod std::cell") for more.

 Implementations
---------------



[source](https://doc.rust-lang.org/src/core/cell.rs.html#769)
```
impl<T> RefCell<T>
```

[source](https://doc.rust-lang.org/src/core/cell.rs.html#782)const: 1.24.0
```
pub const fn new(value: T) -> RefCell<T>
```

Creates a new `RefCell` containing `value`.

 ##### Examples

 
```
use std::cell::RefCell;

let c = RefCell::new(5);
```
 
[source](https://doc.rust-lang.org/src/core/cell.rs.html#805)const: [unstable](https://github.com/rust-lang/rust/issues/78729 "Tracking issue for const_cell_into_inner")
```
pub fn into_inner(self) -> T
```

Consumes the `RefCell`, returning the wrapped value.

 ##### Examples

 
```
use std::cell::RefCell;

let c = RefCell::new(5);

let five = c.into_inner();
```
 
[source](https://doc.rust-lang.org/src/core/cell.rs.html#832)1.24.0
```
pub fn replace(&self, t: T) -> T
```

Replaces the wrapped value with a new one, returning the old value, without deinitializing either one.

 This function corresponds to [`std::mem::replace`](../mem/fn.replace).

 ##### Panics

 Panics if the value is currently borrowed.

 ##### Examples

 
```
use std::cell::RefCell;
let cell = RefCell::new(5);
let old_value = cell.replace(6);
assert_eq!(old_value, 5);
assert_eq!(cell, RefCell::new(6));
```
 
[source](https://doc.rust-lang.org/src/core/cell.rs.html#855)1.35.0
```
pub fn replace_with<F>(&self, f: F) -> T
where
    F: FnOnce(&mut T) -> T,
```

Replaces the wrapped value with a new one computed from `f`, returning the old value, without deinitializing either one.

 ##### Panics

 Panics if the value is currently borrowed.

 ##### Examples

 
```
use std::cell::RefCell;
let cell = RefCell::new(5);
let old_value = cell.replace_with(|&mut old| old + 1);
assert_eq!(old_value, 5);
assert_eq!(cell, RefCell::new(6));
```
 
[source](https://doc.rust-lang.org/src/core/cell.rs.html#883)1.24.0
```
pub fn swap(&self, other: &RefCell<T>)
```

Swaps the wrapped value of `self` with the wrapped value of `other`, without deinitializing either one.

 This function corresponds to [`std::mem::swap`](../mem/fn.swap).

 ##### Panics

 Panics if the value in either `RefCell` is currently borrowed, or if `self` and `other` point to the same `RefCell`.

 ##### Examples

 
```
use std::cell::RefCell;
let c = RefCell::new(5);
let d = RefCell::new(6);
c.swap(&d);
assert_eq!(c, RefCell::new(6));
assert_eq!(d, RefCell::new(5));
```
 

[source](https://doc.rust-lang.org/src/core/cell.rs.html#888)
```
impl<T> RefCell<T>
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/cell.rs.html#923)
```
pub fn borrow(&self) -> Ref<'_, T>
```

Immutably borrows the wrapped value.

 The borrow lasts until the returned `Ref` exits scope. Multiple immutable borrows can be taken out at the same time.

 ##### Panics

 Panics if the value is currently mutably borrowed. For a non-panicking variant, use [`try_borrow`](#method.try_borrow).

 ##### Examples

 
```
use std::cell::RefCell;

let c = RefCell::new(5);

let borrowed_five = c.borrow();
let borrowed_five2 = c.borrow();
```
 An example of panic:

 ⓘ
```
use std::cell::RefCell;

let c = RefCell::new(5);

let m = c.borrow_mut();
let b = c.borrow(); // this causes a panic
```

 
[source](https://doc.rust-lang.org/src/core/cell.rs.html#955)1.13.0
```
pub fn try_borrow(&self) -> Result<Ref<'_, T>, BorrowError>
```

Immutably borrows the wrapped value, returning an error if the value is currently mutably borrowed.

 The borrow lasts until the returned `Ref` exits scope. Multiple immutable borrows can be taken out at the same time.

 This is the non-panicking variant of [`borrow`](#method.borrow).

 ##### Examples

 
```
use std::cell::RefCell;

let c = RefCell::new(5);

{
    let m = c.borrow_mut();
    assert!(c.try_borrow().is_err());
}

{
    let m = c.borrow();
    assert!(c.try_borrow().is_ok());
}
```
 
[source](https://doc.rust-lang.org/src/core/cell.rs.html#1016)
```
pub fn borrow_mut(&self) -> RefMut<'_, T>
```

Mutably borrows the wrapped value.

 The borrow lasts until the returned `RefMut` or all `RefMut`s derived from it exit scope. The value cannot be borrowed while this borrow is active.

 ##### Panics

 Panics if the value is currently borrowed. For a non-panicking variant, use [`try_borrow_mut`](#method.try_borrow_mut).

 ##### Examples

 
```
use std::cell::RefCell;

let c = RefCell::new("hello".to_owned());

*c.borrow_mut() = "bonjour".to_owned();

assert_eq!(&*c.borrow(), "bonjour");
```
 An example of panic:

 ⓘ
```
use std::cell::RefCell;

let c = RefCell::new(5);
let m = c.borrow();

let b = c.borrow_mut(); // this causes a panic
```

 
[source](https://doc.rust-lang.org/src/core/cell.rs.html#1045)1.13.0
```
pub fn try_borrow_mut(&self) -> Result<RefMut<'_, T>, BorrowMutError>
```

Mutably borrows the wrapped value, returning an error if the value is currently borrowed.

 The borrow lasts until the returned `RefMut` or all `RefMut`s derived from it exit scope. The value cannot be borrowed while this borrow is active.

 This is the non-panicking variant of [`borrow_mut`](#method.borrow_mut).

 ##### Examples

 
```
use std::cell::RefCell;

let c = RefCell::new(5);

{
    let m = c.borrow();
    assert!(c.try_borrow_mut().is_err());
}

assert!(c.try_borrow_mut().is_ok());
```
 
[source](https://doc.rust-lang.org/src/core/cell.rs.html#1079)1.12.0
```
pub fn as_ptr(&self) -> *mut T
```

Returns a raw pointer to the underlying data in this cell.

 ##### Examples

 
```
use std::cell::RefCell;

let c = RefCell::new(5);

let ptr = c.as_ptr();
```
 
[source](https://doc.rust-lang.org/src/core/cell.rs.html#1112)1.11.0
```
pub fn get_mut(&mut self) -> &mut T
```

Returns a mutable reference to the underlying data.

 Since this method borrows `RefCell` mutably, it is statically guaranteed that no borrows to the underlying data exist. The dynamic checks inherent in [`borrow_mut`](struct.refcell#method.borrow_mut "method std::cell::RefCell::borrow_mut") and most other methods of `RefCell` are therefore unnecessary.

 This method can only be called if `RefCell` can be mutably borrowed, which in general is only the case directly after the `RefCell` has been created. In these situations, skipping the aforementioned dynamic borrowing checks may yield better ergonomics and runtime-performance.

 In most situations where `RefCell` is used, it can’t be borrowed mutably. Use [`borrow_mut`](struct.refcell#method.borrow_mut "method std::cell::RefCell::borrow_mut") to get mutable access to the underlying data then.

 ##### Examples

 
```
use std::cell::RefCell;

let mut c = RefCell::new(5);
*c.get_mut() += 1;

assert_eq!(c, RefCell::new(6));
```
 
[source](https://doc.rust-lang.org/src/core/cell.rs.html#1138)
```
pub fn undo_leak(&mut self) -> &mut T
```

🔬This is a nightly-only experimental API. (`cell_leak` [#69099](https://github.com/rust-lang/rust/issues/69099))

Undo the effect of leaked guards on the borrow state of the `RefCell`.

 This call is similar to [`get_mut`](struct.refcell#method.get_mut "method std::cell::RefCell::get_mut") but more specialized. It borrows `RefCell` mutably to ensure no borrows exist and then resets the state tracking shared borrows. This is relevant if some `Ref` or `RefMut` borrows have been leaked.

 ##### Examples

 
```
#![feature(cell_leak)]
use std::cell::RefCell;

let mut c = RefCell::new(0);
std::mem::forget(c.borrow_mut());

assert!(c.try_borrow().is_err());
c.undo_leak();
assert!(c.try_borrow().is_ok());
```
 
[source](https://doc.rust-lang.org/src/core/cell.rs.html#1172)1.37.0
```
pub unsafe fn try_borrow_unguarded(&self) -> Result<&T, BorrowError>
```

Immutably borrows the wrapped value, returning an error if the value is currently mutably borrowed.

 ##### Safety

 Unlike `RefCell::borrow`, this method is unsafe because it does not return a `Ref`, thus leaving the borrow flag untouched. Mutably borrowing the `RefCell` while the reference returned by this method is alive is undefined behaviour.

 ##### Examples

 
```
use std::cell::RefCell;

let c = RefCell::new(5);

{
    let m = c.borrow_mut();
    assert!(unsafe { c.try_borrow_unguarded() }.is_err());
}

{
    let m = c.borrow();
    assert!(unsafe { c.try_borrow_unguarded() }.is_ok());
}
```
 

[source](https://doc.rust-lang.org/src/core/cell.rs.html#1191)
```
impl<T> RefCell<T>
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/cell.rs.html#1210)1.50.0
```
pub fn take(&self) -> T
```

Takes the wrapped value, leaving `Default::default()` in its place.

 ##### Panics

 Panics if the value is currently borrowed.

 ##### Examples

 
```
use std::cell::RefCell;

let c = RefCell::new(5);
let five = c.take();

assert_eq!(five, 5);
assert_eq!(c.into_inner(), 0);
```
 


Trait Implementations
---------------------



[source](https://doc.rust-lang.org/src/core/cell.rs.html#1222)
```
impl<T> Clone for RefCell<T>
where
    T: Clone,
```

[source](https://doc.rust-lang.org/src/core/cell.rs.html#1228)
```
fn clone(&self) -> RefCell<T>
```

##### Panics

 Panics if the value is currently mutably borrowed.

 
[source](https://doc.rust-lang.org/src/core/cell.rs.html#1237)
```
fn clone_from(&mut self, other: &RefCell<T>)
```

##### Panics

 Panics if `other` is currently mutably borrowed.

 

[source](https://doc.rust-lang.org/src/core/fmt/mod.rs.html#2522)
```
impl<T> Debug for RefCell<T>
where
    T: Debug + ?Sized,
```

[source](https://doc.rust-lang.org/src/core/fmt/mod.rs.html#2523)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt)


[source](https://doc.rust-lang.org/src/core/cell.rs.html#1243)
```
impl<T> Default for RefCell<T>
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/core/cell.rs.html#1246)
```
fn default() -> RefCell<T>
```

Creates a `RefCell<T>`, with the `Default` value for T.

 

[source](https://doc.rust-lang.org/src/core/cell.rs.html#1320)1.12.0
```
impl<T> From<T> for RefCell<T>
```

[source](https://doc.rust-lang.org/src/core/cell.rs.html#1322)
```
fn from(t: T) -> RefCell<T>
```

Creates a new `RefCell<T>` containing the given value.

 

[source](https://doc.rust-lang.org/src/core/cell.rs.html#1309)1.10.0
```
impl<T> Ord for RefCell<T>
where
    T: Ord + ?Sized,
```

[source](https://doc.rust-lang.org/src/core/cell.rs.html#1314)
```
fn cmp(&self, other: &RefCell<T>) -> Ordering
```

##### Panics

 Panics if the value in either `RefCell` is currently mutably borrowed.

 

[source](https://doc.rust-lang.org/src/core/cell.rs.html#1252)
```
impl<T> PartialEq<RefCell<T>> for RefCell<T>
where
    T: PartialEq<T> + ?Sized,
```

[source](https://doc.rust-lang.org/src/core/cell.rs.html#1257)
```
fn eq(&self, other: &RefCell<T>) -> bool
```

##### Panics

 Panics if the value in either `RefCell` is currently mutably borrowed.

 
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#226)
```
fn ne(&self, other: &Rhs) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/cell.rs.html#1266)1.10.0
```
impl<T> PartialOrd<RefCell<T>> for RefCell<T>
where
    T: PartialOrd<T> + ?Sized,
```

[source](https://doc.rust-lang.org/src/core/cell.rs.html#1271)
```
fn partial_cmp(&self, other: &RefCell<T>) -> Option<Ordering>
```

##### Panics

 Panics if the value in either `RefCell` is currently mutably borrowed.

 
[source](https://doc.rust-lang.org/src/core/cell.rs.html#1279)
```
fn lt(&self, other: &RefCell<T>) -> bool
```

##### Panics

 Panics if the value in either `RefCell` is currently mutably borrowed.

 
[source](https://doc.rust-lang.org/src/core/cell.rs.html#1287)
```
fn le(&self, other: &RefCell<T>) -> bool
```

##### Panics

 Panics if the value in either `RefCell` is currently mutably borrowed.

 
[source](https://doc.rust-lang.org/src/core/cell.rs.html#1295)
```
fn gt(&self, other: &RefCell<T>) -> bool
```

##### Panics

 Panics if the value in either `RefCell` is currently mutably borrowed.

 
[source](https://doc.rust-lang.org/src/core/cell.rs.html#1303)
```
fn ge(&self, other: &RefCell<T>) -> bool
```

##### Panics

 Panics if the value in either `RefCell` is currently mutably borrowed.

 

[source](https://doc.rust-lang.org/src/core/cell.rs.html#1328)
```
impl<T, U> CoerceUnsized<RefCell<U>> for RefCell<T>
where
    T: CoerceUnsized<U>,
```
[source](https://doc.rust-lang.org/src/core/cell.rs.html#1263)1.2.0
```
impl<T> Eq for RefCell<T>
where
    T: Eq + ?Sized,
```
[source](https://doc.rust-lang.org/src/core/cell.rs.html#1216)
```
impl<T> Send for RefCell<T>
where
    T: Send + ?Sized,
```
[source](https://doc.rust-lang.org/src/core/cell.rs.html#1219)
```
impl<T> !Sync for RefCell<T>
where
    T: ?Sized,
```


Auto Trait Implementations
--------------------------




```
impl<T> !RefUnwindSafe for RefCell<T>
```

```
impl<T: ?Sized> Unpin for RefCell<T>
where
    T: Unpin,
```

```
impl<T: ?Sized> UnwindSafe for RefCell<T>
where
    T: UnwindSafe,
```


Blanket Implementations
-----------------------



[source](https://doc.rust-lang.org/src/core/any.rs.html#200)
```
impl<T> Any for T
where
    T: 'static + ?Sized,
```

[source](https://doc.rust-lang.org/src/core/any.rs.html#201)
```
fn type_id(&self) -> TypeId
```
Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#208)
```
impl<T> Borrow<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#210)
```
fn borrow(&self) -> &T
```
Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#216)
```
impl<T> BorrowMut<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#217)
```
fn borrow_mut(&mut self) -> &mut T
```
Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#740)
```
impl<T> From<!> for T
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#741)
```
fn from(t: !) -> T
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#723)
```
impl<T> From<T> for T
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#726)
```
fn from(t: T) -> T
```

Returns the argument unchanged.

 

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#707)
```
impl<T, U> Into<U> for T
where
    U: From<T>,
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#716)
```
fn into(self) -> U
```

Calls `U::from(self)`.

 That is, this conversion is whatever the implementation of `[From](../convert/trait.from "trait std::convert::From")<T> for U` chooses to do.

 

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#82)
```
impl<T> ToOwned for T
where
    T: Clone,
```


```
type Owned = T
```
The resulting type after obtaining ownership.
[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#87)
```
fn to_owned(&self) -> T
```
Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned)

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#91)
```
fn clone_into(&self, target: &mut T)
```
Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#763)
```
impl<T, U> TryFrom<U> for T
where
    U: Into<T>,
```


```
type Error = Infallible
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#770)
```
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#748)
```
impl<T, U> TryInto<U> for T
where
    U: TryFrom<T>,
```


```
type Error = <U as TryFrom<T>>::Error
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#755)
```
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
```
Performs the conversion.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/cell/struct.RefCell.html>

Struct std::sync::Arc
=====================



```
pub struct Arc<T>
where
    T: ?Sized,{ /* private fields */ }
```

A thread-safe reference-counting pointer. ‘Arc’ stands for ‘Atomically Reference Counted’.

 The type `Arc<T>` provides shared ownership of a value of type `T`, allocated in the heap. Invoking [`clone`](../clone/trait.clone#tymethod.clone "method std::clone::Clone::clone") on `Arc` produces a new `Arc` instance, which points to the same allocation on the heap as the source `Arc`, while increasing a reference count. When the last `Arc` 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 `Arc` is no exception: you cannot generally obtain a mutable reference to something inside an `Arc`. If you need to mutate through an `Arc`, use [`Mutex`](struct.mutex), [`RwLock`](struct.rwlock), or one of the [`Atomic`](atomic/index "mod std::sync::atomic") types.

 **Note**: This type is only available on platforms that support atomic loads and stores of pointers, which includes all platforms that support the `std` crate but not all those which only support [`alloc`](https://doc.rust-lang.org/alloc/index.html "mod alloc"). This may be detected at compile time using `#[cfg(target_has_atomic = "ptr")]`.

 ### Thread Safety

 Unlike [`Rc<T>`](../rc/struct.rc "struct std::rc::Rc"), `Arc<T>` uses atomic operations for its reference counting. This means that it is thread-safe. The disadvantage is that atomic operations are more expensive than ordinary memory accesses. If you are not sharing reference-counted allocations between threads, consider using [`Rc<T>`](../rc/struct.rc "struct std::rc::Rc") for lower overhead. [`Rc<T>`](../rc/struct.rc "struct std::rc::Rc") is a safe default, because the compiler will catch any attempt to send an [`Rc<T>`](../rc/struct.rc "struct std::rc::Rc") between threads. However, a library might choose `Arc<T>` in order to give library consumers more flexibility.

 `Arc<T>` will implement [`Send`](../marker/trait.send "trait std::marker::Send") and [`Sync`](../marker/trait.sync "trait std::marker::Sync") as long as the `T` implements [`Send`](../marker/trait.send "trait std::marker::Send") and [`Sync`](../marker/trait.sync "trait std::marker::Sync"). Why can’t you put a non-thread-safe type `T` in an `Arc<T>` to make it thread-safe? This may be a bit counter-intuitive at first: after all, isn’t the point of `Arc<T>` thread safety? The key is this: `Arc<T>` makes it thread safe to have multiple ownership of the same data, but it doesn’t add thread safety to its data. Consider `Arc<[RefCell<T>](../cell/struct.refcell "struct std::cell::RefCell")>`. [`RefCell<T>`](../cell/struct.refcell "struct std::cell::RefCell") isn’t [`Sync`](../marker/trait.sync "trait std::marker::Sync"), and if `Arc<T>` was always [`Send`](../marker/trait.send "trait std::marker::Send"), `Arc<[RefCell<T>](../cell/struct.refcell "struct std::cell::RefCell")>` would be as well. But then we’d have a problem: [`RefCell<T>`](../cell/struct.refcell "struct std::cell::RefCell") is not thread safe; it keeps track of the borrowing count using non-atomic operations.

 In the end, this means that you may need to pair `Arc<T>` with some sort of [`std::sync`](index) type, usually [`Mutex<T>`](struct.mutex).

 ### Breaking cycles with `Weak`

 The [`downgrade`](struct.arc#method.downgrade "associated function std::sync::Arc::downgrade") method can be used to create a non-owning [`Weak`](struct.weak "struct std::sync::Weak") pointer. A [`Weak`](struct.weak "struct std::sync::Weak") pointer can be [`upgrade`](struct.weak#method.upgrade "method std::sync::Weak::upgrade")d to an `Arc`, but this will return [`None`](../option/enum.option#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 value) alive.

 A cycle between `Arc` pointers will never be deallocated. For this reason, [`Weak`](struct.weak "struct std::sync::Weak") is used to break cycles. For example, a tree could have strong `Arc` pointers from parent nodes to children, and [`Weak`](struct.weak "struct std::sync::Weak") pointers from children back to their parents.

 Cloning references
------------------

 Creating a new reference from an existing reference-counted pointer is done using the `Clone` trait implemented for [`Arc<T>`](struct.arc "struct std::sync::Arc") and [`Weak<T>`](struct.weak "struct std::sync::Weak").

 
```
use std::sync::Arc;
let foo = Arc::new(vec![1.0, 2.0, 3.0]);
// The two syntaxes below are equivalent.
let a = foo.clone();
let b = Arc::clone(&foo);
// a, b, and foo are all Arcs that point to the same memory location
```
 ### 
`Deref` behavior

 `Arc<T>` automatically dereferences to `T` (via the [`Deref`](../ops/trait.deref "trait std::ops::Deref") trait), so you can call `T`’s methods on a value of type `Arc<T>`. To avoid name clashes with `T`’s methods, the methods of `Arc<T>` itself are associated functions, called using [fully qualified syntax](../../book/ch19-03-advanced-traits#fully-qualified-syntax-for-disambiguation-calling-methods-with-the-same-name):

 
```
use std::sync::Arc;

let my_arc = Arc::new(());
let my_weak = Arc::downgrade(&my_arc);
```
 `Arc<T>`’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::sync::Arc;

let arc = Arc::new(());
// Method-call syntax
let arc2 = arc.clone();
// Fully qualified syntax
let arc3 = Arc::clone(&arc);
```
 [`Weak<T>`](struct.weak "struct std::sync::Weak") does not auto-dereference to `T`, because the inner value may have already been dropped.

 Examples
--------

 Sharing some immutable data between threads:

 
```
use std::sync::Arc;
use std::thread;

let five = Arc::new(5);

for _ in 0..10 {
    let five = Arc::clone(&five);

    thread::spawn(move || {
        println!("{five:?}");
    });
}
```
 Sharing a mutable [`AtomicUsize`](atomic/struct.atomicusize "sync::atomic::AtomicUsize"):

 
```
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;

let val = Arc::new(AtomicUsize::new(5));

for _ in 0..10 {
    let val = Arc::clone(&val);

    thread::spawn(move || {
        let v = val.fetch_add(1, Ordering::SeqCst);
        println!("{v:?}");
    });
}
```
 See the [`rc` documentation](../rc/index#examples "mod std::rc") for more examples of reference counting in general.

 Implementations
---------------



[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#353)
```
impl<T> Arc<T>
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#366)
```
pub fn new(data: T) -> Arc<T>
```

Constructs a new `Arc<T>`.

 ##### Examples

 
```
use std::sync::Arc;

let five = Arc::new(5);
```
 
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#431-433)1.60.0
```
pub fn new_cyclic<F>(data_fn: F) -> Arc<T>
where
    F: FnOnce(&Weak<T>) -> T,
```

Constructs a new `Arc<T>` while giving you a `Weak<T>` to the allocation, to allow you to construct a `T` which holds a weak pointer to itself.

 Generally, a structure circularly referencing itself, either directly or indirectly, should not hold a strong reference to itself to prevent a memory leak. Using this function, you get access to the weak pointer during the initialization of `T`, before the `Arc<T>` is created, such that you can clone and store it inside the `T`.

 `new_cyclic` first allocates the managed allocation for the `Arc<T>`, then calls your closure, giving it a `Weak<T>` to this allocation, and only afterwards completes the construction of the `Arc<T>` by placing the `T` returned from your closure into the allocation.

 Since the new `Arc<T>` is not fully-constructed until `Arc<T>::new_cyclic` returns, calling [`upgrade`](struct.weak#method.upgrade "method std::sync::Weak::upgrade") on the weak reference inside your closure will fail and result in a `None` value.

 ##### Panics

 If `data_fn` panics, the panic is propagated to the caller, and the temporary [`Weak<T>`](struct.weak "struct std::sync::Weak") is dropped normally.

 ##### Example

 
```
use std::sync::{Arc, Weak};

struct Gadget {
    me: Weak<Gadget>,
}

impl Gadget {
    /// Construct a reference counted Gadget.
    fn new() -> Arc<Self> {
        // `me` is a `Weak<Gadget>` pointing at the new allocation of the
        // `Arc` we're constructing.
        Arc::new_cyclic(|me| {
            // Create the actual struct here.
            Gadget { me: me.clone() }
        })
    }

    /// Return a reference counted pointer to Self.
    fn me(&self) -> Arc<Self> {
        self.me.upgrade().unwrap()
    }
}
```
 
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#508)
```
pub fn new_uninit() -> Arc<MaybeUninit<T>>
```

🔬This is a nightly-only experimental API. (`new_uninit` [#63291](https://github.com/rust-lang/rust/issues/63291))

Constructs a new `Arc` with uninitialized contents.

 ##### Examples

 
```
#![feature(new_uninit)]
#![feature(get_mut_unchecked)]

use std::sync::Arc;

let mut five = Arc::<u32>::new_uninit();

// Deferred initialization:
Arc::get_mut(&mut five).unwrap().write(5);

let five = unsafe { five.assume_init() };

assert_eq!(*five, 5)
```
 
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#542)
```
pub fn new_zeroed() -> Arc<MaybeUninit<T>>
```

🔬This is a nightly-only experimental API. (`new_uninit` [#63291](https://github.com/rust-lang/rust/issues/63291))

Constructs a new `Arc` with uninitialized contents, with the memory being filled with `0` bytes.

 See [`MaybeUninit::zeroed`](../mem/union.maybeuninit#method.zeroed "associated function std::mem::MaybeUninit::zeroed") for examples of correct and incorrect usage of this method.

 ##### Examples

 
```
#![feature(new_uninit)]

use std::sync::Arc;

let zero = Arc::<u32>::new_zeroed();
let zero = unsafe { zero.assume_init() };

assert_eq!(*zero, 0)
```
 
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#557)1.33.0
```
pub fn pin(data: T) -> Pin<Arc<T>>
```

Constructs a new `Pin<Arc<T>>`. If `T` does not implement `Unpin`, then `data` will be pinned in memory and unable to be moved.

 
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#564)
```
pub fn try_pin(data: T) -> Result<Pin<Arc<T>>, AllocError>
```

🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838))

Constructs a new `Pin<Arc<T>>`, return an error if allocation fails.

 
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#581)
```
pub fn try_new(data: T) -> Result<Arc<T>, AllocError>
```

🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838))

Constructs a new `Arc<T>`, returning an error if allocation fails.

 ##### Examples

 
```
#![feature(allocator_api)]
use std::sync::Arc;

let five = Arc::try_new(5)?;
```
 
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#615)
```
pub fn try_new_uninit() -> Result<Arc<MaybeUninit<T>>, AllocError>
```

🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838))

Constructs a new `Arc` with uninitialized contents, returning an error if allocation fails.

 ##### Examples

 
```
#![feature(new_uninit, allocator_api)]
#![feature(get_mut_unchecked)]

use std::sync::Arc;

let mut five = Arc::<u32>::try_new_uninit()?;

// Deferred initialization:
Arc::get_mut(&mut five).unwrap().write(5);

let five = unsafe { five.assume_init() };

assert_eq!(*five, 5);
```
 
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#648)
```
pub fn try_new_zeroed() -> Result<Arc<MaybeUninit<T>>, AllocError>
```

🔬This is a nightly-only experimental API. (`allocator_api` [#32838](https://github.com/rust-lang/rust/issues/32838))

Constructs a new `Arc` with uninitialized contents, with the memory being filled with `0` bytes, returning an error if allocation fails.

 See [`MaybeUninit::zeroed`](../mem/union.maybeuninit#method.zeroed "associated function std::mem::MaybeUninit::zeroed") for examples of correct and incorrect usage of this method.

 ##### Examples

 
```
#![feature(new_uninit, allocator_api)]

use std::sync::Arc;

let zero = Arc::<u32>::try_new_zeroed()?;
let zero = unsafe { zero.assume_init() };

assert_eq!(*zero, 0);
```
 
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#689)1.4.0
```
pub fn try_unwrap(this: Arc<T>) -> Result<T, Arc<T>>
```

Returns the inner value, if the `Arc` has exactly one strong reference.

 Otherwise, an [`Err`](../result/enum.result#variant.Err "variant std::result::Result::Err") is returned with the same `Arc` that was passed in.

 This will succeed even if there are outstanding weak references.

 It is strongly recommended to use [`Arc::into_inner`](struct.arc#method.into_inner "associated function std::sync::Arc::into_inner") instead if you don’t want to keep the `Arc` in the [`Err`](../result/enum.result#variant.Err "variant std::result::Result::Err") case. Immediately dropping the [`Err`](../result/enum.result#variant.Err "variant std::result::Result::Err") payload, like in the expression `Arc::try_unwrap(this).ok()`, can still cause the strong count to drop to zero and the inner value of the `Arc` to be dropped: For instance if two threads each execute this expression in parallel, then there is a race condition. The threads could first both check whether they have the last clone of their `Arc` via `Arc::try_unwrap`, and then both drop their `Arc` in the call to [`ok`](../result/enum.result#method.ok "method std::result::Result::ok"), taking the strong count from two down to zero.

 ##### Examples

 
```
use std::sync::Arc;

let x = Arc::new(3);
assert_eq!(Arc::try_unwrap(x), Ok(3));

let x = Arc::new(4);
let _y = Arc::clone(&x);
assert_eq!(*Arc::try_unwrap(x).unwrap_err(), 4);
```
 
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#799)1.70.0
```
pub fn into_inner(this: Arc<T>) -> Option<T>
```

Returns the inner value, if the `Arc` has exactly one strong reference.

 Otherwise, [`None`](../option/enum.option#variant.None "variant std::option::Option::None") is returned and the `Arc` is dropped.

 This will succeed even if there are outstanding weak references.

 If `Arc::into_inner` is called on every clone of this `Arc`, it is guaranteed that exactly one of the calls returns the inner value. This means in particular that the inner value is not dropped.

 The similar expression `Arc::try_unwrap(this).ok()` does not offer such a guarantee. See the last example below and the documentation of [`Arc::try_unwrap`](struct.arc#method.try_unwrap "associated function std::sync::Arc::try_unwrap").

 ##### Examples

 Minimal example demonstrating the guarantee that `Arc::into_inner` gives.

 
```
use std::sync::Arc;

let x = Arc::new(3);
let y = Arc::clone(&x);

// Two threads calling `Arc::into_inner` on both clones of an `Arc`:
let x_thread = std::thread::spawn(|| Arc::into_inner(x));
let y_thread = std::thread::spawn(|| Arc::into_inner(y));

let x_inner_value = x_thread.join().unwrap();
let y_inner_value = y_thread.join().unwrap();

// One of the threads is guaranteed to receive the inner value:
assert!(matches!(
    (x_inner_value, y_inner_value),
    (None, Some(3)) | (Some(3), None)
));
// The result could also be `(None, None)` if the threads called
// `Arc::try_unwrap(x).ok()` and `Arc::try_unwrap(y).ok()` instead.
```
 A more practical example demonstrating the need for `Arc::into_inner`:

 
```
use std::sync::Arc;

// Definition of a simple singly linked list using `Arc`:
#[derive(Clone)]
struct LinkedList<T>(Option<Arc<Node<T>>>);
struct Node<T>(T, Option<Arc<Node<T>>>);

// Dropping a long `LinkedList<T>` relying on the destructor of `Arc`
// can cause a stack overflow. To prevent this, we can provide a
// manual `Drop` implementation that does the destruction in a loop:
impl<T> Drop for LinkedList<T> {
    fn drop(&mut self) {
        let mut link = self.0.take();
        while let Some(arc_node) = link.take() {
            if let Some(Node(_value, next)) = Arc::into_inner(arc_node) {
                link = next;
            }
        }
    }
}

// Implementation of `new` and `push` omitted
impl<T> LinkedList<T> {
    /* ... */
}

// The following code could have still caused a stack overflow
// despite the manual `Drop` impl if that `Drop` impl had used
// `Arc::try_unwrap(arc).ok()` instead of `Arc::into_inner(arc)`.

// Create a long list and clone it
let mut x = LinkedList::new();
for i in 0..100000 {
    x.push(i); // Adds i to the front of x
}
let y = x.clone();

// Drop the clones in parallel
let x_thread = std::thread::spawn(|| drop(x));
let y_thread = std::thread::spawn(|| drop(y));
x_thread.join().unwrap();
y_thread.join().unwrap();
```
 

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#825)
```
impl<T> Arc<[T]>
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#852)
```
pub fn new_uninit_slice(len: usize) -> Arc<[MaybeUninit<T>]>
```

🔬This is a nightly-only experimental API. (`new_uninit` [#63291](https://github.com/rust-lang/rust/issues/63291))

Constructs a new atomically reference-counted slice with uninitialized contents.

 ##### Examples

 
```
#![feature(new_uninit)]
#![feature(get_mut_unchecked)]

use std::sync::Arc;

let mut values = Arc::<[u32]>::new_uninit_slice(3);

// Deferred initialization:
let data = Arc::get_mut(&mut values).unwrap();
data[0].write(1);
data[1].write(2);
data[2].write(3);

let values = unsafe { values.assume_init() };

assert_eq!(*values, [1, 2, 3])
```
 
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#880)
```
pub fn new_zeroed_slice(len: usize) -> Arc<[MaybeUninit<T>]>
```

🔬This is a nightly-only experimental API. (`new_uninit` [#63291](https://github.com/rust-lang/rust/issues/63291))

Constructs a new atomically reference-counted slice with uninitialized contents, with the memory being filled with `0` bytes.

 See [`MaybeUninit::zeroed`](../mem/union.maybeuninit#method.zeroed "associated function std::mem::MaybeUninit::zeroed") for examples of correct and incorrect usage of this method.

 ##### Examples

 
```
#![feature(new_uninit)]

use std::sync::Arc;

let values = Arc::<[u32]>::new_zeroed_slice(3);
let values = unsafe { values.assume_init() };

assert_eq!(*values, [0, 0, 0])
```
 

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#894)
```
impl<T> Arc<MaybeUninit<T>>
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#927)
```
pub unsafe fn assume_init(self) -> Arc<T>
```

🔬This is a nightly-only experimental API. (`new_uninit` [#63291](https://github.com/rust-lang/rust/issues/63291))

Converts to `Arc<T>`.

 ##### Safety

 As with [`MaybeUninit::assume_init`](../mem/union.maybeuninit#method.assume_init "method std::mem::MaybeUninit::assume_init"), it is up to the caller to guarantee that the inner value really is in an initialized state. Calling this when the content is not yet fully initialized causes immediate undefined behavior.

 ##### Examples

 
```
#![feature(new_uninit)]
#![feature(get_mut_unchecked)]

use std::sync::Arc;

let mut five = Arc::<u32>::new_uninit();

// Deferred initialization:
Arc::get_mut(&mut five).unwrap().write(5);

let five = unsafe { five.assume_init() };

assert_eq!(*five, 5)
```
 

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#932)
```
impl<T> Arc<[MaybeUninit<T>]>
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#968)
```
pub unsafe fn assume_init(self) -> Arc<[T]>
```

🔬This is a nightly-only experimental API. (`new_uninit` [#63291](https://github.com/rust-lang/rust/issues/63291))

Converts to `Arc<[T]>`.

 ##### Safety

 As with [`MaybeUninit::assume_init`](../mem/union.maybeuninit#method.assume_init "method std::mem::MaybeUninit::assume_init"), it is up to the caller to guarantee that the inner value really is in an initialized state. Calling this when the content is not yet fully initialized causes immediate undefined behavior.

 ##### Examples

 
```
#![feature(new_uninit)]
#![feature(get_mut_unchecked)]

use std::sync::Arc;

let mut values = Arc::<[u32]>::new_uninit_slice(3);

// Deferred initialization:
let data = Arc::get_mut(&mut values).unwrap();
data[0].write(1);
data[1].write(2);
data[2].write(3);

let values = unsafe { values.assume_init() };

assert_eq!(*values, [1, 2, 3])
```
 

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#973)
```
impl<T> Arc<T>
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#990)1.17.0
```
pub fn into_raw(this: Arc<T>) -> *const T
```

Consumes the `Arc`, returning the wrapped pointer.

 To avoid a memory leak the pointer must be converted back to an `Arc` using [`Arc::from_raw`](struct.arc#method.from_raw "associated function std::sync::Arc::from_raw").

 ##### Examples

 
```
use std::sync::Arc;

let x = Arc::new("hello".to_owned());
let x_ptr = Arc::into_raw(x);
assert_eq!(unsafe { &*x_ptr }, "hello");
```
 
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#1014)1.45.0
```
pub fn as_ptr(this: &Arc<T>) -> *const T
```

Provides a raw pointer to the data.

 The counts are not affected in any way and the `Arc` is not consumed. The pointer is valid for as long as there are strong counts in the `Arc`.

 ##### Examples

 
```
use std::sync::Arc;

let x = Arc::new("hello".to_owned());
let y = Arc::clone(&x);
let x_ptr = Arc::as_ptr(&x);
assert_eq!(x_ptr, Arc::as_ptr(&y));
assert_eq!(unsafe { &*x_ptr }, "hello");
```
 
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#1061)1.17.0
```
pub unsafe fn from_raw(ptr: *const T) -> Arc<T>
```

Constructs an `Arc<T>` from a raw pointer.

 The raw pointer must have been previously returned by a call to [`Arc<U>::into_raw`](struct.arc#method.into_raw "associated function std::sync::Arc::into_raw") where `U` must have the same size and alignment as `T`. This is trivially true if `U` is `T`. Note that if `U` is not `T` but has the same size and alignment, this is basically like transmuting references of different types. See [`mem::transmute`](../mem/fn.transmute "fn std::mem::transmute") for more information on what restrictions apply in this case.

 The user of `from_raw` has to make sure a specific value of `T` is only dropped once.

 This function is unsafe because improper use may lead to memory unsafety, even if the returned `Arc<T>` is never accessed.

 ##### Examples

 
```
use std::sync::Arc;

let x = Arc::new("hello".to_owned());
let x_ptr = Arc::into_raw(x);

unsafe {
    // Convert back to an `Arc` to prevent leak.
    let x = Arc::from_raw(x_ptr);
    assert_eq!(&*x, "hello");

    // Further calls to `Arc::from_raw(x_ptr)` would be memory-unsafe.
}

// The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
```
 
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#1086)1.4.0
```
pub fn downgrade(this: &Arc<T>) -> Weak<T>
```

Creates a new [`Weak`](struct.weak "struct std::sync::Weak") pointer to this allocation.

 ##### Examples

 
```
use std::sync::Arc;

let five = Arc::new(5);

let weak_five = Arc::downgrade(&five);
```
 
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#1143)1.15.0
```
pub fn weak_count(this: &Arc<T>) -> usize
```

Gets the number of [`Weak`](struct.weak "struct std::sync::Weak") pointers to this allocation.

 ##### Safety

 This method by itself is safe, but using it correctly requires extra care. Another thread can change the weak count at any time, including potentially between calling this method and acting on the result.

 ##### Examples

 
```
use std::sync::Arc;

let five = Arc::new(5);
let _weak_five = Arc::downgrade(&five);

// This assertion is deterministic because we haven't shared
// the `Arc` or `Weak` between threads.
assert_eq!(1, Arc::weak_count(&five));
```
 
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#1173)1.15.0
```
pub fn strong_count(this: &Arc<T>) -> usize
```

Gets the number of strong (`Arc`) pointers to this allocation.

 ##### Safety

 This method by itself is safe, but using it correctly requires extra care. Another thread can change the strong count at any time, including potentially between calling this method and acting on the result.

 ##### Examples

 
```
use std::sync::Arc;

let five = Arc::new(5);
let _also_five = Arc::clone(&five);

// This assertion is deterministic because we haven't shared
// the `Arc` between threads.
assert_eq!(2, Arc::strong_count(&five));
```
 
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#1205)1.51.0
```
pub unsafe fn increment_strong_count(ptr: *const T)
```

Increments the strong reference count on the `Arc<T>` associated with the provided pointer by one.

 ##### Safety

 The pointer must have been obtained through `Arc::into_raw`, and the associated `Arc` instance must be valid (i.e. the strong count must be at least 1) for the duration of this method.

 ##### Examples

 
```
use std::sync::Arc;

let five = Arc::new(5);

unsafe {
    let ptr = Arc::into_raw(five);
    Arc::increment_strong_count(ptr);

    // This assertion is deterministic because we haven't shared
    // the `Arc` between threads.
    let five = Arc::from_raw(ptr);
    assert_eq!(2, Arc::strong_count(&five));
}
```
 
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#1244)1.51.0
```
pub unsafe fn decrement_strong_count(ptr: *const T)
```

Decrements the strong reference count on the `Arc<T>` associated with the provided pointer by one.

 ##### Safety

 The pointer must have been obtained through `Arc::into_raw`, and the associated `Arc` instance must be valid (i.e. the strong count must be at least 1) when invoking this method. This method can be used to release the final `Arc` and backing storage, but **should not** be called after the final `Arc` has been released.

 ##### Examples

 
```
use std::sync::Arc;

let five = Arc::new(5);

unsafe {
    let ptr = Arc::into_raw(five);
    Arc::increment_strong_count(ptr);

    // Those assertions are deterministic because we haven't shared
    // the `Arc` between threads.
    let five = Arc::from_raw(ptr);
    assert_eq!(2, Arc::strong_count(&five));
    Arc::decrement_strong_count(ptr);
    assert_eq!(1, Arc::strong_count(&five));
}
```
 
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#1289)1.17.0
```
pub fn ptr_eq(this: &Arc<T>, other: &Arc<T>) -> bool
```

Returns `true` if the two `Arc`s point to the same allocation in a vein similar to [`ptr::eq`](../ptr/fn.eq "ptr::eq"). See [that function](../ptr/fn.eq "ptr::eq") for caveats when comparing `dyn Trait` pointers.

 ##### Examples

 
```
use std::sync::Arc;

let five = Arc::new(5);
let same_five = Arc::clone(&five);
let other_five = Arc::new(5);

assert!(Arc::ptr_eq(&five, &same_five));
assert!(!Arc::ptr_eq(&five, &other_five));
```
 

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#1552)
```
impl<T> Arc<T>
where
    T: Clone,
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#1606)1.4.0
```
pub fn make_mut(this: &mut Arc<T>) -> &mut T
```

Makes a mutable reference into the given `Arc`.

 If there are other `Arc` pointers to the same allocation, then `make_mut` will [`clone`](../clone/trait.clone#tymethod.clone "method std::clone::Clone::clone") the inner value to a new allocation to ensure unique ownership. This is also referred to as clone-on-write.

 However, if there are no other `Arc` pointers to this allocation, but some [`Weak`](struct.weak "struct std::sync::Weak") pointers, then the [`Weak`](struct.weak "struct std::sync::Weak") pointers will be dissociated and the inner value will not be cloned.

 See also [`get_mut`](struct.arc#method.get_mut "associated function std::sync::Arc::get_mut"), which will fail rather than cloning the inner value or dissociating [`Weak`](struct.weak "struct std::sync::Weak") pointers.

 ##### Examples

 
```
use std::sync::Arc;

let mut data = Arc::new(5);

*Arc::make_mut(&mut data) += 1;         // Won't clone anything
let mut other_data = Arc::clone(&data); // Won't clone inner data
*Arc::make_mut(&mut data) += 1;         // Clones inner data
*Arc::make_mut(&mut data) += 1;         // Won't clone anything
*Arc::make_mut(&mut other_data) *= 2;   // Won't clone anything

// Now `data` and `other_data` point to different allocations.
assert_eq!(*data, 8);
assert_eq!(*other_data, 12);
```
 [`Weak`](struct.weak "struct std::sync::Weak") pointers will be dissociated:

 
```
use std::sync::Arc;

let mut data = Arc::new(75);
let weak = Arc::downgrade(&data);

assert!(75 == *data);
assert!(75 == *weak.upgrade().unwrap());

*Arc::make_mut(&mut data) += 1;

assert!(76 == *data);
assert!(weak.upgrade().is_none());
```
 
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#1690)
```
pub fn unwrap_or_clone(this: Arc<T>) -> T
```

🔬This is a nightly-only experimental API. (`arc_unwrap_or_clone` [#93610](https://github.com/rust-lang/rust/issues/93610))

If we have the only reference to `T` then unwrap it. Otherwise, clone `T` and return the clone.

 Assuming `arc_t` is of type `Arc<T>`, this function is functionally equivalent to `(*arc_t).clone()`, but will avoid cloning the inner value where possible.

 ##### Examples

 
```
#![feature(arc_unwrap_or_clone)]
let inner = String::from("test");
let ptr = inner.as_ptr();

let arc = Arc::new(inner);
let inner = Arc::unwrap_or_clone(arc);
// The inner value was not cloned
assert!(ptr::eq(ptr, inner.as_ptr()));

let arc = Arc::new(inner);
let arc2 = arc.clone();
let inner = Arc::unwrap_or_clone(arc);
// Because there were 2 references, we had to clone the inner value.
assert!(!ptr::eq(ptr, inner.as_ptr()));
// `arc2` is the last reference, so when we unwrap it we get back
// the original `String`.
let inner = Arc::unwrap_or_clone(arc2);
assert!(ptr::eq(ptr, inner.as_ptr()));
```
 

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#1695)
```
impl<T> Arc<T>
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#1722)1.4.0
```
pub fn get_mut(this: &mut Arc<T>) -> Option<&mut T>
```

Returns a mutable reference into the given `Arc`, if there are no other `Arc` or [`Weak`](struct.weak "struct std::sync::Weak") pointers to the same allocation.

 Returns [`None`](../option/enum.option#variant.None "variant std::option::Option::None") otherwise, because it is not safe to mutate a shared value.

 See also [`make_mut`](struct.arc#method.make_mut "associated function std::sync::Arc::make_mut"), which will [`clone`](../clone/trait.clone#tymethod.clone "method std::clone::Clone::clone") the inner value when there are other `Arc` pointers.

 ##### Examples

 
```
use std::sync::Arc;

let mut x = Arc::new(3);
*Arc::get_mut(&mut x).unwrap() = 4;
assert_eq!(*x, 4);

let _y = Arc::clone(&x);
assert!(Arc::get_mut(&mut x).is_none());
```
 
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#1797)
```
pub unsafe fn get_mut_unchecked(this: &mut Arc<T>) -> &mut T
```

🔬This is a nightly-only experimental API. (`get_mut_unchecked` [#63292](https://github.com/rust-lang/rust/issues/63292))

Returns a mutable reference into the given `Arc`, without any check.

 See also [`get_mut`](struct.arc#method.get_mut "associated function std::sync::Arc::get_mut"), which is safe and does appropriate checks.

 ##### Safety

 If any other `Arc` or [`Weak`](struct.weak "struct std::sync::Weak") pointers to the same allocation exist, then they must not be dereferenced or have active borrows for the duration of the returned borrow, and their inner type must be exactly the same as the inner type of this Rc (including lifetimes). This is trivially the case if no such pointers exist, for example immediately after `Arc::new`.

 ##### Examples

 
```
#![feature(get_mut_unchecked)]

use std::sync::Arc;

let mut x = Arc::new(String::new());
unsafe {
    Arc::get_mut_unchecked(&mut x).push_str("foo")
}
assert_eq!(*x, "foo");
```
 Other `Arc` pointers to the same allocation must be to the same type.

 
```
#![feature(get_mut_unchecked)]

use std::sync::Arc;

let x: Arc<str> = Arc::from("Hello, world!");
let mut y: Arc<[u8]> = x.clone().into();
unsafe {
    // this is Undefined Behavior, because x's inner type is str, not [u8]
    Arc::get_mut_unchecked(&mut y).fill(0xff); // 0xff is invalid in UTF-8
}
println!("{}", &*x); // Invalid UTF-8 in a str
```
 Other `Arc` pointers to the same allocation must be to the exact same type, including lifetimes.

 
```
#![feature(get_mut_unchecked)]

use std::sync::Arc;

let x: Arc<&str> = Arc::new("Hello, world!");
{
    let s = String::from("Oh, no!");
    let mut y: Arc<&str> = x.clone().into();
    unsafe {
        // this is Undefined Behavior, because x's inner type
        // is &'long str, not &'short str
        *Arc::get_mut_unchecked(&mut y) = &s;
    }
}
println!("{}", &*x); // Use-after-free
```
 

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#1904)
```
impl Arc<dyn Any + Sync + Send + 'static>
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#1925-1927)1.29.0
```
pub fn downcast<T>(self) -> Result<Arc<T>, Arc<dyn Any + Sync + Send + 'static>>
where
    T: Any + Send + Sync,
```

Attempt to downcast the `Arc<dyn Any + Send + Sync>` to a concrete type.

 ##### Examples

 
```
use std::any::Any;
use std::sync::Arc;

fn print_if_string(value: Arc<dyn Any + Send + Sync>) {
    if let Ok(string) = value.downcast::<String>() {
        println!("String ({}): {}", string.len(), string);
    }
}

let my_string = "Hello World".to_string();
print_if_string(Arc::new(my_string));
print_if_string(Arc::new(0i8));
```
 
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#1968-1970)
```
pub unsafe fn downcast_unchecked<T>(self) -> Arc<T>
where
    T: Any + Send + Sync,
```

🔬This is a nightly-only experimental API. (`downcast_unchecked` [#90850](https://github.com/rust-lang/rust/issues/90850))

Downcasts the `Arc<dyn Any + Send + Sync>` to a concrete type.

 For a safe alternative see [`downcast`](struct.arc#method.downcast "method std::sync::Arc::downcast").

 ##### Examples

 
```
#![feature(downcast_unchecked)]

use std::any::Any;
use std::sync::Arc;

let x: Arc<dyn Any + Send + Sync> = Arc::new(1_usize);

unsafe {
    assert_eq!(*x.downcast_unchecked::<usize>(), 1);
}
```
 ##### Safety

 The contained value must be of type `T`. Calling this method with the incorrect type is *undefined behavior*.

 


Trait Implementations
---------------------



[source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#395-400)1.64.0
```
impl<T: AsFd> AsFd for Arc<T>
```

This impl allows implementing traits that require `AsFd` on Arc.

 
```
use std::net::UdpSocket;
use std::sync::Arc;

trait MyTrait: AsFd {}
impl MyTrait for Arc<UdpSocket> {}
impl MyTrait for Box<UdpSocket> {}
```
 

[source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#397-399)
```
fn as_fd(&self) -> BorrowedFd<'_>
```
Borrows the file descriptor. [Read more](../os/fd/trait.asfd#tymethod.as_fd)


[source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#453-458)1.71.0
```
impl<T: AsHandle> AsHandle for Arc<T>Available on Windows only.
```

This impl allows implementing traits that require `AsHandle` on Arc.

 
```
use std::fs::File;
use std::sync::Arc;

trait MyTrait: AsHandle {}
impl MyTrait for Arc<File> {}
impl MyTrait for Box<File> {}
```
 

[source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#455-457)
```
fn as_handle(&self) -> BorrowedHandle<'_>
```
Borrows the handle. [Read more](../os/windows/io/trait.ashandle#tymethod.as_handle)


[source](https://doc.rust-lang.org/src/std/os/fd/raw.rs.html#250-255)1.63.0
```
impl<T: AsRawFd> AsRawFd for Arc<T>
```

This impl allows implementing traits that require `AsRawFd` on Arc.

 
```
use std::net::UdpSocket;
use std::sync::Arc;
trait MyTrait: AsRawFd {
}
impl MyTrait for Arc<UdpSocket> {}
impl MyTrait for Box<UdpSocket> {}
```
 

[source](https://doc.rust-lang.org/src/std/os/fd/raw.rs.html#252-254)
```
fn as_raw_fd(&self) -> RawFd
```
Extracts the raw file descriptor. [Read more](../os/fd/trait.asrawfd#tymethod.as_raw_fd)


[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2922)1.5.0
```
impl<T> AsRef<T> for Arc<T>
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2923)
```
fn as_ref(&self) -> &T
```
Converts this type into a shared reference of the (usually inferred) input type.

[source](https://doc.rust-lang.org/src/std/os/windows/io/socket.rs.html#270-275)1.71.0
```
impl<T: AsSocket> AsSocket for Arc<T>Available on Windows only.
```

This impl allows implementing traits that require `AsSocket` on Arc.

 
```
use std::net::UdpSocket;
use std::sync::Arc;

trait MyTrait: AsSocket {}
impl MyTrait for Arc<UdpSocket> {}
impl MyTrait for Box<UdpSocket> {}
```
 

[source](https://doc.rust-lang.org/src/std/os/windows/io/socket.rs.html#272-274)
```
fn as_socket(&self) -> BorrowedSocket<'_>
```
Borrows the socket.

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2915)
```
impl<T> Borrow<T> for Arc<T>
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2916)
```
fn borrow(&self) -> &T
```
Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#1486)
```
impl<T> Clone for Arc<T>
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#1502)
```
fn clone(&self) -> Arc<T>
```

Makes a clone of the `Arc` pointer.

 This creates another pointer to the same allocation, increasing the strong reference count.

 ##### Examples

 
```
use std::sync::Arc;

let five = Arc::new(5);

let _ = Arc::clone(&five);
```
 
[source](https://doc.rust-lang.org/src/core/clone.rs.html#129)
```
fn clone_from(&mut self, source: &Self)
```
Performs copy-assignment from `source`. [Read more](../clone/trait.clone#method.clone_from)


[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2610)
```
impl<T> Debug for Arc<T>
where
    T: Debug + ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2611)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt)


[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2625)
```
impl<T> Default for Arc<T>
where
    T: Default,
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2636)
```
fn default() -> Arc<T>
```

Creates a new `Arc<T>`, with the `Default` value for `T`.

 ##### Examples

 
```
use std::sync::Arc;

let x: Arc<i32> = Default::default();
assert_eq!(*x, 0);
```
 

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#1540)
```
impl<T> Deref for Arc<T>
where
    T: ?Sized,
```


```
type Target = T
```
The resulting type after dereferencing.
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#1544)
```
fn deref(&self) -> &T
```
Dereferences the value.

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2603)
```
impl<T> Display for Arc<T>
where
    T: Display + ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2604)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter. [Read more](../fmt/trait.display#tymethod.fmt)


[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#1833)
```
impl<T> Drop for Arc<T>
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#1860)
```
fn drop(&mut self)
```

Drops the `Arc`.

 This will decrement the strong reference count. If the strong reference count reaches zero then the only other references (if any) are [`Weak`](struct.weak "struct std::sync::Weak"), so we `drop` the inner value.

 ##### Examples

 
```
use std::sync::Arc;

struct Foo;

impl Drop for Foo {
    fn drop(&mut self) {
        println!("dropped!");
    }
}

let foo  = Arc::new(Foo);
let foo2 = Arc::clone(&foo);

drop(foo);    // Doesn't print anything
drop(foo2);   // Prints "dropped!"
```
 

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2954)1.52.0
```
impl<T> Error for Arc<T>
where
    T: Error + ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2956)
```
fn description(&self) -> &str
```

👎Deprecated since 1.42.0: use the Display impl or to\_string()
 [Read more](../error/trait.error#method.description)

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2961)
```
fn cause(&self) -> Option<&dyn Error>
```

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2965)
```
fn source(&self) -> Option<&(dyn Error + 'static)>
```
The lower-level source of this error, if any. [Read more](../error/trait.error#method.source)

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2969)
```
fn provide<'a>(&'a self, req: &mut Demand<'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](../error/trait.error#method.provide)


[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2672)1.21.0
```
impl<T> From<&[T]> for Arc<[T]>
where
    T: Clone,
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2684)
```
fn from(v: &[T]) -> Arc<[T]>
```

Allocate a reference-counted slice and fill it by cloning `v`’s items.

 ##### Example

 
```
let original: &[i32] = &[1, 2, 3];
let shared: Arc<[i32]> = Arc::from(original);
assert_eq!(&[1, 2, 3], &shared[..]);
```
 

[source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#878)1.24.0
```
impl From<&CStr> for Arc<CStr>
```

[source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#882)
```
fn from(s: &CStr) -> Arc<CStr>
```

Converts a `&CStr` into a `Arc<CStr>`, by copying the contents into a newly allocated [`Arc`](struct.arc "struct std::sync::Arc").

 

[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1045-1052)1.24.0
```
impl From<&OsStr> for Arc<OsStr>
```

[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1048-1051)
```
fn from(s: &OsStr) -> Arc<OsStr>
```

Copies the string into a newly allocated `[Arc](struct.arc "struct std::sync::Arc")<[OsStr](../ffi/struct.osstr "struct std::ffi::OsStr")>`.

 

[source](https://doc.rust-lang.org/src/std/path.rs.html#1871-1878)1.24.0
```
impl From<&Path> for Arc<Path>
```

[source](https://doc.rust-lang.org/src/std/path.rs.html#1874-1877)
```
fn from(s: &Path) -> Arc<Path>
```

Converts a [`Path`](../path/struct.path "struct std::path::Path") into an [`Arc`](struct.arc "struct std::sync::Arc") by copying the [`Path`](../path/struct.path "struct std::path::Path") data into a new [`Arc`](struct.arc "struct std::sync::Arc") buffer.

 

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2691)1.21.0
```
impl From<&str> for Arc<str>
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2702)
```
fn from(v: &str) -> Arc<str>
```

Allocate a reference-counted `str` and copy `v` into it.

 ##### Example

 
```
let shared: Arc<str> = Arc::from("eggplant");
assert_eq!("eggplant", &shared[..]);
```
 

[source](https://doc.rust-lang.org/src/alloc/task.rs.html#108)1.51.0
```
impl<W> From<Arc<W>> for RawWaker
where
    W: Wake + Send + Sync + 'static,
```

[source](https://doc.rust-lang.org/src/alloc/task.rs.html#112)
```
fn from(waker: Arc<W>) -> RawWaker
```

Use a `Wake`-able type as a `RawWaker`.

 No heap allocations or atomic operations are used for this conversion.

 

[source](https://doc.rust-lang.org/src/alloc/task.rs.html#96)1.51.0
```
impl<W> From<Arc<W>> for Waker
where
    W: Wake + Send + Sync + 'static,
```

[source](https://doc.rust-lang.org/src/alloc/task.rs.html#100)
```
fn from(waker: Arc<W>) -> Waker
```

Use a `Wake`-able type as a `Waker`.

 No heap allocations or atomic operations are used for this conversion.

 

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2798)1.62.0
```
impl From<Arc<str>> for Arc<[u8]>
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2810)
```
fn from(rc: Arc<str>) -> Arc<[u8]>
```

Converts an atomically reference-counted string slice into a byte slice.

 ##### Example

 
```
let string: Arc<str> = Arc::from("eggplant");
let bytes: Arc<[u8]> = Arc::from(string);
assert_eq!("eggplant".as_bytes(), bytes.as_ref());
```
 

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2729)1.21.0
```
impl<T> From<Box<T, Global>> for Arc<T>
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2741)
```
fn from(v: Box<T, Global>) -> Arc<T>
```

Move a boxed object to a new, reference-counted allocation.

 ##### Example

 
```
let unique: Box<str> = Box::from("eggplant");
let shared: Arc<str> = Arc::from(unique);
assert_eq!("eggplant", &shared[..]);
```
 

[source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#866)1.24.0
```
impl From<CString> for Arc<CStr>
```

[source](https://doc.rust-lang.org/src/alloc/ffi/c_str.rs.html#870)
```
fn from(s: CString) -> Arc<CStr>
```

Converts a [`CString`](../ffi/struct.cstring "struct std::ffi::CString") into an `[Arc](struct.arc "struct std::sync::Arc")<[CStr](../ffi/struct.cstr "struct std::ffi::CStr")>` by moving the [`CString`](../ffi/struct.cstring "struct std::ffi::CString") data into a new [`Arc`](struct.arc "struct std::sync::Arc") buffer.

 

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2771)1.45.0
```
impl<'a, B> From<Cow<'a, B>> for Arc<B>
where
    B: ToOwned + ?Sized,
    Arc<B>: From<&'a B> + From<<B as ToOwned>::Owned>,
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2789)
```
fn from(cow: Cow<'a, B>) -> Arc<B>
```

Create an atomically reference-counted pointer from a clone-on-write pointer by copying its content.

 ##### Example

 
```
let cow: Cow<'_, str> = Cow::Borrowed("eggplant");
let shared: Arc<str> = Arc::from(cow);
assert_eq!("eggplant", &shared[..]);
```
 

[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1034-1042)1.24.0
```
impl From<OsString> for Arc<OsStr>
```

[source](https://doc.rust-lang.org/src/std/ffi/os_str.rs.html#1038-1041)
```
fn from(s: OsString) -> Arc<OsStr>
```

Converts an [`OsString`](../ffi/struct.osstring "struct std::ffi::OsString") into an `[Arc](struct.arc "struct std::sync::Arc")<[OsStr](../ffi/struct.osstr "struct std::ffi::OsStr")>` by moving the [`OsString`](../ffi/struct.osstring "struct std::ffi::OsString") data into a new [`Arc`](struct.arc "struct std::sync::Arc") buffer.

 

[source](https://doc.rust-lang.org/src/std/path.rs.html#1860-1868)1.24.0
```
impl From<PathBuf> for Arc<Path>
```

[source](https://doc.rust-lang.org/src/std/path.rs.html#1864-1867)
```
fn from(s: PathBuf) -> Arc<Path>
```

Converts a [`PathBuf`](../path/struct.pathbuf "struct std::path::PathBuf") into an `[Arc](struct.arc "struct std::sync::Arc")<[Path](../path/struct.path "struct std::path::Path")>` by moving the [`PathBuf`](../path/struct.pathbuf "struct std::path::PathBuf") data into a new [`Arc`](struct.arc "struct std::sync::Arc") buffer.

 

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2710)1.21.0
```
impl From<String> for Arc<str>
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2722)
```
fn from(v: String) -> Arc<str>
```

Allocate a reference-counted `str` and copy `v` into it.

 ##### Example

 
```
let unique: String = "eggplant".to_owned();
let shared: Arc<str> = Arc::from(unique);
assert_eq!("eggplant", &shared[..]);
```
 

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2650)1.6.0
```
impl<T> From<T> for Arc<T>
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2665)
```
fn from(t: T) -> Arc<T>
```

Converts a `T` into an `Arc<T>`

 The conversion moves the value into a newly allocated `Arc`. It is equivalent to calling `Arc::new(t)`.

 ##### Example

 
```
let x = 5;
let arc = Arc::new(5);

assert_eq!(Arc::from(x), arc);
```
 

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2748)1.21.0
```
impl<T> From<Vec<T, Global>> for Arc<[T]>
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2760)
```
fn from(v: Vec<T, Global>) -> Arc<[T]>
```

Allocate a reference-counted slice and move `v`’s items into it.

 ##### Example

 
```
let unique: Vec<i32> = vec![1, 2, 3];
let shared: Arc<[i32]> = Arc::from(unique);
assert_eq!(&[1, 2, 3], &shared[..]);
```
 

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2831)1.37.0
```
impl<T> FromIterator<T> for Arc<[T]>
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2870)
```
fn from_iter<I>(iter: I) -> Arc<[T]>
where
    I: IntoIterator<Item = T>,
```

Takes each element in the `Iterator` and collects it into an `Arc<[T]>`.

 ##### Performance characteristics


###### [The general case](#the-general-case)

 In the general case, collecting into `Arc<[T]>` is done by first collecting into a `Vec<T>`. That is, when writing the following:

 
```
let evens: Arc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect();
```
 this behaves as if we wrote:

 
```
let evens: Arc<[u8]> = (0..10).filter(|&x| x % 2 == 0)
    .collect::<Vec<_>>() // The first set of allocations happens here.
    .into(); // A second allocation for `Arc<[T]>` happens here.
```
 This will allocate as many times as needed for constructing the `Vec<T>` and then it will allocate once for turning the `Vec<T>` into the `Arc<[T]>`.

 ###### [Iterators of known length](#iterators-of-known-length)

 When your `Iterator` implements `TrustedLen` and is of an exact size, a single allocation will be made for the `Arc<[T]>`. For example:

 
```
let evens: Arc<[u8]> = (0..10).collect(); // Just a single allocation happens here.
```
 

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2642)
```
impl<T> Hash for Arc<T>
where
    T: Hash + ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2643)
```
fn hash<H>(&self, state: &mut H)
where
    H: Hasher,
```
Feeds this value into the given [`Hasher`](../hash/trait.hasher "trait std::hash::Hasher"). [Read more](../hash/trait.hash#tymethod.hash)

[source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#237-239)1.3.0
```
fn hash_slice<H>(data: &[Self], state: &mut H)
where
    H: Hasher,
    Self: Sized,
```
Feeds a slice of this type into the given [`Hasher`](../hash/trait.hasher "trait std::hash::Hasher"). [Read more](../hash/trait.hash#method.hash_slice)


[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2580)
```
impl<T> Ord for Arc<T>
where
    T: Ord + ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2595)
```
fn cmp(&self, other: &Arc<T>) -> Ordering
```

Comparison for two `Arc`s.

 The two are compared by calling `cmp()` on their inner values.

 ##### Examples

 
```
use std::sync::Arc;
use std::cmp::Ordering;

let five = Arc::new(5);

assert_eq!(Ordering::Less, five.cmp(&Arc::new(6)));
```
 
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#790-792)1.21.0
```
fn max(self, other: Self) -> Self
where
    Self: Sized,
```
Compares and returns the maximum of two values. [Read more](../cmp/trait.ord#method.max)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#810-812)1.21.0
```
fn min(self, other: Self) -> Self
where
    Self: Sized,
```
Compares and returns the minimum of two values. [Read more](../cmp/trait.ord#method.min)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#835-838)1.50.0
```
fn clamp(self, min: Self, max: Self) -> Self
where
    Self: Sized + PartialOrd<Self>,
```
Restrict a value to a certain interval. [Read more](../cmp/trait.ord#method.clamp)


[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2446)
```
impl<T> PartialEq<Arc<T>> for Arc<T>
where
    T: PartialEq<T> + ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2465)
```
fn eq(&self, other: &Arc<T>) -> bool
```

Equality for two `Arc`s.

 Two `Arc`s are equal if their inner values are equal, even if they are stored in different allocation.

 If `T` also implements `Eq` (implying reflexivity of equality), two `Arc`s that point to the same allocation are always equal.

 ##### Examples

 
```
use std::sync::Arc;

let five = Arc::new(5);

assert!(five == Arc::new(5));
```
 
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2486)
```
fn ne(&self, other: &Arc<T>) -> bool
```

Inequality for two `Arc`s.

 Two `Arc`s are not equal if their inner values are not equal.

 If `T` also implements `Eq` (implying reflexivity of equality), two `Arc`s that point to the same value are always equal.

 ##### Examples

 
```
use std::sync::Arc;

let five = Arc::new(5);

assert!(five != Arc::new(6));
```
 

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2492)
```
impl<T> PartialOrd<Arc<T>> for Arc<T>
where
    T: PartialOrd<T> + ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2507)
```
fn partial_cmp(&self, other: &Arc<T>) -> Option<Ordering>
```

Partial comparison for two `Arc`s.

 The two are compared by calling `partial_cmp()` on their inner values.

 ##### Examples

 
```
use std::sync::Arc;
use std::cmp::Ordering;

let five = Arc::new(5);

assert_eq!(Some(Ordering::Less), five.partial_cmp(&Arc::new(6)));
```
 
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2524)
```
fn lt(&self, other: &Arc<T>) -> bool
```

Less-than comparison for two `Arc`s.

 The two are compared by calling `<` on their inner values.

 ##### Examples

 
```
use std::sync::Arc;

let five = Arc::new(5);

assert!(five < Arc::new(6));
```
 
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2541)
```
fn le(&self, other: &Arc<T>) -> bool
```

‘Less than or equal to’ comparison for two `Arc`s.

 The two are compared by calling `<=` on their inner values.

 ##### Examples

 
```
use std::sync::Arc;

let five = Arc::new(5);

assert!(five <= Arc::new(5));
```
 
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2558)
```
fn gt(&self, other: &Arc<T>) -> bool
```

Greater-than comparison for two `Arc`s.

 The two are compared by calling `>` on their inner values.

 ##### Examples

 
```
use std::sync::Arc;

let five = Arc::new(5);

assert!(five > Arc::new(4));
```
 
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2575)
```
fn ge(&self, other: &Arc<T>) -> bool
```

‘Greater than or equal to’ comparison for two `Arc`s.

 The two are compared by calling `>=` on their inner values.

 ##### Examples

 
```
use std::sync::Arc;

let five = Arc::new(5);

assert!(five >= Arc::new(5));
```
 

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2617)
```
impl<T> Pointer for Arc<T>
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2618)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter.

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2817)1.43.0
```
impl<T, const N: usize> TryFrom<Arc<[T]>> for Arc<[T; N]>
```


```
type Error = Arc<[T]>
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2820)
```
fn try_from(
    boxed_slice: Arc<[T]>
) -> Result<Arc<[T; N]>, <Arc<[T; N]> as TryFrom<Arc<[T]>>>::Error>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#263)
```
impl<T, U> CoerceUnsized<Arc<U>> for Arc<T>
where
    T: Unsize<U> + ?Sized,
    U: ?Sized,
```
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#266)
```
impl<T, U> DispatchFromDyn<Arc<U>> for Arc<T>
where
    T: Unsize<U> + ?Sized,
    U: ?Sized,
```
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2600)
```
impl<T> Eq for Arc<T>
where
    T: Eq + ?Sized,
```
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#255)
```
impl<T> Send for Arc<T>
where
    T: Sync + Send + ?Sized,
```
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#257)
```
impl<T> Sync for Arc<T>
where
    T: Sync + Send + ?Sized,
```
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#2929)1.33.0
```
impl<T> Unpin for Arc<T>
where
    T: ?Sized,
```
[source](https://doc.rust-lang.org/src/alloc/sync.rs.html#260)1.9.0
```
impl<T> UnwindSafe for Arc<T>
where
    T: RefUnwindSafe + ?Sized,
```


Auto Trait Implementations
--------------------------



```
impl<T: ?Sized> RefUnwindSafe for Arc<T>
where
    T: RefUnwindSafe,
```

Blanket Implementations
-----------------------



[source](https://doc.rust-lang.org/src/core/any.rs.html#200)
```
impl<T> Any for T
where
    T: 'static + ?Sized,
```

[source](https://doc.rust-lang.org/src/core/any.rs.html#201)
```
fn type_id(&self) -> TypeId
```
Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#208)
```
impl<T> Borrow<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#210)
```
fn borrow(&self) -> &T
```
Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#216)
```
impl<T> BorrowMut<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#217)
```
fn borrow_mut(&mut self) -> &mut T
```
Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#740)
```
impl<T> From<!> for T
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#741)
```
fn from(t: !) -> T
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#723)
```
impl<T> From<T> for T
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#726)
```
fn from(t: T) -> T
```

Returns the argument unchanged.

 

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#707)
```
impl<T, U> Into<U> for T
where
    U: From<T>,
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#716)
```
fn into(self) -> U
```

Calls `U::from(self)`.

 That is, this conversion is whatever the implementation of `[From](../convert/trait.from "trait std::convert::From")<T> for U` chooses to do.

 

[source](https://doc.rust-lang.org/src/core/error.rs.html#198)
```
impl<E> Provider for E
where
    E: Error + ?Sized,
```

[source](https://doc.rust-lang.org/src/core/error.rs.html#202)
```
fn provide<'a>(&'a self, demand: &mut Demand<'a>)
```

🔬This is a nightly-only experimental API. (`provide_any` [#96024](https://github.com/rust-lang/rust/issues/96024))
Data providers should implement this method to provide *all* values they are able to provide by using `demand`. [Read more](../any/trait.provider#tymethod.provide)


[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#82)
```
impl<T> ToOwned for T
where
    T: Clone,
```


```
type Owned = T
```
The resulting type after obtaining ownership.
[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#87)
```
fn to_owned(&self) -> T
```
Creates owned data from borrowed data, usually by cloning. [Read more](../borrow/trait.toowned#tymethod.to_owned)

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#91)
```
fn clone_into(&self, target: &mut T)
```
Uses borrowed data to replace owned data, usually by cloning. [Read more](../borrow/trait.toowned#method.clone_into)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2513)
```
impl<T> ToString for T
where
    T: Display + ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2519)
```
default fn to_string(&self) -> String
```
Converts the given value to a `String`. [Read more](../string/trait.tostring#tymethod.to_string)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#763)
```
impl<T, U> TryFrom<U> for T
where
    U: Into<T>,
```


```
type Error = Infallible
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#770)
```
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#748)
```
impl<T, U> TryInto<U> for T
where
    U: TryFrom<T>,
```


```
type Error = <U as TryFrom<T>>::Error
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#755)
```
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
```
Performs the conversion.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/sync/struct.Arc.html>

Struct std::sync::Mutex
=======================



```
pub struct Mutex<T: ?Sized> { /* private fields */ }
```

A mutual exclusion primitive useful for protecting shared data

 This mutex will block threads waiting for the lock to become available. The mutex can be created via a [`new`](struct.mutex#method.new "associated function std::sync::Mutex::new") constructor. Each mutex has a type parameter which represents the data that it is protecting. The data can only be accessed through the RAII guards returned from [`lock`](struct.mutex#method.lock "method std::sync::Mutex::lock") and [`try_lock`](struct.mutex#method.try_lock "method std::sync::Mutex::try_lock"), which guarantees that the data is only ever accessed when the mutex is locked.

 Poisoning
---------

 The mutexes in this module implement a strategy called “poisoning” where a mutex is considered poisoned whenever a thread panics while holding the mutex. Once a mutex is poisoned, all other threads are unable to access the data by default as it is likely tainted (some invariant is not being upheld).

 For a mutex, this means that the [`lock`](struct.mutex#method.lock "method std::sync::Mutex::lock") and [`try_lock`](struct.mutex#method.try_lock "method std::sync::Mutex::try_lock") methods return a [`Result`](../result/enum.result "enum std::result::Result") which indicates whether a mutex has been poisoned or not. Most usage of a mutex will simply [`unwrap()`](../result/enum.result#method.unwrap "method std::result::Result::unwrap") these results, propagating panics among threads to ensure that a possibly invalid invariant is not witnessed.

 A poisoned mutex, however, does not prevent all access to the underlying data. The [`PoisonError`](struct.poisonerror "struct std::sync::PoisonError") type has an [`into_inner`](struct.poisonerror#method.into_inner "method std::sync::PoisonError::into_inner") method which will return the guard that would have otherwise been returned on a successful lock. This allows access to the data, despite the lock being poisoned.

 Examples
--------

 
```
use std::sync::{Arc, Mutex};
use std::thread;
use std::sync::mpsc::channel;

const N: usize = 10;

// Spawn a few threads to increment a shared variable (non-atomically), and
// let the main thread know once all increments are done.
//
// Here we're using an Arc to share memory among threads, and the data inside
// the Arc is protected with a mutex.
let data = Arc::new(Mutex::new(0));

let (tx, rx) = channel();
for _ in 0..N {
    let (data, tx) = (Arc::clone(&data), tx.clone());
    thread::spawn(move || {
        // The shared state can only be accessed once the lock is held.
        // Our non-atomic increment is safe because we're the only thread
        // which can access the shared state when the lock is held.
        //
        // We unwrap() the return value to assert that we are not expecting
        // threads to ever fail while holding the lock.
        let mut data = data.lock().unwrap();
        *data += 1;
        if *data == N {
            tx.send(()).unwrap();
        }
        // the lock is unlocked here when `data` goes out of scope.
    });
}

rx.recv().unwrap();
```
 To recover from a poisoned mutex:

 
```
use std::sync::{Arc, Mutex};
use std::thread;

let lock = Arc::new(Mutex::new(0_u32));
let lock2 = Arc::clone(&lock);

let _ = thread::spawn(move || -> () {
    // This thread will acquire the mutex first, unwrapping the result of
    // `lock` because the lock has not been poisoned.
    let _guard = lock2.lock().unwrap();

    // This panic while holding the lock (`_guard` is in scope) will poison
    // the mutex.
    panic!();
}).join();

// The lock is poisoned by this point, but the returned result can be
// pattern matched on to return the underlying guard on both branches.
let mut guard = match lock.lock() {
    Ok(guard) => guard,
    Err(poisoned) => poisoned.into_inner(),
};

*guard += 1;
```
 To unlock a mutex guard sooner than the end of the enclosing scope, either create an inner scope or drop the guard manually.

 
```
use std::sync::{Arc, Mutex};
use std::thread;

const N: usize = 3;

let data_mutex = Arc::new(Mutex::new(vec![1, 2, 3, 4]));
let res_mutex = Arc::new(Mutex::new(0));

let mut threads = Vec::with_capacity(N);
(0..N).for_each(|_| {
    let data_mutex_clone = Arc::clone(&data_mutex);
    let res_mutex_clone = Arc::clone(&res_mutex);

    threads.push(thread::spawn(move || {
        // Here we use a block to limit the lifetime of the lock guard.
        let result = {
            let mut data = data_mutex_clone.lock().unwrap();
            // This is the result of some important and long-ish work.
            let result = data.iter().fold(0, |acc, x| acc + x * 2);
            data.push(result);
            result
            // The mutex guard gets dropped here, together with any other values
            // created in the critical section.
        };
        // The guard created here is a temporary dropped at the end of the statement, i.e.
        // the lock would not remain being held even if the thread did some additional work.
        *res_mutex_clone.lock().unwrap() += result;
    }));
});

let mut data = data_mutex.lock().unwrap();
// This is the result of some important and long-ish work.
let result = data.iter().fold(0, |acc, x| acc + x * 2);
data.push(result);
// We drop the `data` explicitly because it's not necessary anymore and the
// thread still has work to do. This allow other threads to start working on
// the data immediately, without waiting for the rest of the unrelated work
// to be done here.
//
// It's even more important here than in the threads because we `.join` the
// threads after that. If we had not dropped the mutex guard, a thread could
// be waiting forever for it, causing a deadlock.
// As in the threads, a block could have been used instead of calling the
// `drop` function.
drop(data);
// Here the mutex guard is not assigned to a variable and so, even if the
// scope does not end after this line, the mutex is still released: there is
// no deadlock.
*res_mutex.lock().unwrap() += result;

threads.into_iter().for_each(|thread| {
    thread
        .join()
        .expect("The thread creating or execution failed !")
});

assert_eq!(*res_mutex.lock().unwrap(), 800);
```
 Implementations
---------------



[source](https://doc.rust-lang.org/src/std/sync/mutex.rs.html#216-232)
```
impl<T> Mutex<T>
```

[source](https://doc.rust-lang.org/src/std/sync/mutex.rs.html#229-231)const: 1.63.0
```
pub const fn new(t: T) -> Mutex<T>
```

Creates a new mutex in an unlocked state ready for use.

 ##### Examples

 
```
use std::sync::Mutex;

let mutex = Mutex::new(0);
```
 

[source](https://doc.rust-lang.org/src/std/sync/mutex.rs.html#234-462)
```
impl<T: ?Sized> Mutex<T>
```

[source](https://doc.rust-lang.org/src/std/sync/mutex.rs.html#271-276)
```
pub fn lock(&self) -> LockResult<MutexGuard<'_, T>>
```

Acquires a mutex, blocking the current thread until it is able to do so.

 This function will block the local thread until it is available to acquire the mutex. Upon returning, the thread is the only thread with the lock held. An RAII guard is returned to allow scoped unlock of the lock. When the guard goes out of scope, the mutex will be unlocked.

 The exact behavior on locking a mutex in the thread which already holds the lock is left unspecified. However, this function will not return on the second call (it might panic or deadlock, for example).

 ##### Errors

 If another user of this mutex panicked while holding the mutex, then this call will return an error once the mutex is acquired.

 ##### Panics

 This function might panic when called if the lock is already held by the current thread.

 ##### Examples

 
```
use std::sync::{Arc, Mutex};
use std::thread;

let mutex = Arc::new(Mutex::new(0));
let c_mutex = Arc::clone(&mutex);

thread::spawn(move || {
    *c_mutex.lock().unwrap() = 10;
}).join().expect("thread::spawn failed");
assert_eq!(*mutex.lock().unwrap(), 10);
```
 
[source](https://doc.rust-lang.org/src/std/sync/mutex.rs.html#318-326)
```
pub fn try_lock(&self) -> TryLockResult<MutexGuard<'_, T>>
```

Attempts to acquire this lock.

 If the lock could not be acquired at this time, then [`Err`](../result/enum.result#variant.Err "variant std::result::Result::Err") is returned. Otherwise, an RAII guard is returned. The lock will be unlocked when the guard is dropped.

 This function does not block.

 ##### Errors

 If another user of this mutex panicked while holding the mutex, then this call will return the [`Poisoned`](enum.trylockerror#variant.Poisoned "variant std::sync::TryLockError::Poisoned") error if the mutex would otherwise be acquired.

 If the mutex could not be acquired because it is already locked, then this call will return the [`WouldBlock`](enum.trylockerror#variant.WouldBlock "variant std::sync::TryLockError::WouldBlock") error.

 ##### Examples

 
```
use std::sync::{Arc, Mutex};
use std::thread;

let mutex = Arc::new(Mutex::new(0));
let c_mutex = Arc::clone(&mutex);

thread::spawn(move || {
    let mut lock = c_mutex.try_lock();
    if let Ok(ref mut mutex) = lock {
        **mutex = 10;
    } else {
        println!("try_lock failed");
    }
}).join().expect("thread::spawn failed");
assert_eq!(*mutex.lock().unwrap(), 10);
```
 
[source](https://doc.rust-lang.org/src/std/sync/mutex.rs.html#344-346)
```
pub fn unlock(guard: MutexGuard<'_, T>)
```

🔬This is a nightly-only experimental API. (`mutex_unlock` [#81872](https://github.com/rust-lang/rust/issues/81872))

Immediately drops the guard, and consequently unlocks the mutex.

 This function is equivalent to calling [`drop`](../mem/fn.drop "fn std::mem::drop") on the guard but is more self-documenting. Alternately, the guard will be automatically dropped when it goes out of scope.

 
```
#![feature(mutex_unlock)]

use std::sync::Mutex;
let mutex = Mutex::new(0);

let mut guard = mutex.lock().unwrap();
*guard += 20;
Mutex::unlock(guard);
```
 
[source](https://doc.rust-lang.org/src/std/sync/mutex.rs.html#371-373)1.2.0
```
pub fn is_poisoned(&self) -> bool
```

Determines whether the mutex is poisoned.

 If another thread is active, the mutex can still become poisoned at any time. You should not trust a `false` value for program correctness without additional synchronization.

 ##### Examples

 
```
use std::sync::{Arc, Mutex};
use std::thread;

let mutex = Arc::new(Mutex::new(0));
let c_mutex = Arc::clone(&mutex);

let _ = thread::spawn(move || {
    let _lock = c_mutex.lock().unwrap();
    panic!(); // the mutex gets poisoned
}).join();
assert_eq!(mutex.is_poisoned(), true);
```
 
[source](https://doc.rust-lang.org/src/std/sync/mutex.rs.html#410-412)
```
pub fn clear_poison(&self)
```

🔬This is a nightly-only experimental API. (`mutex_unpoison` [#96469](https://github.com/rust-lang/rust/issues/96469))

Clear the poisoned state from a mutex

 If the mutex is poisoned, it will remain poisoned until this function is called. This allows recovering from a poisoned state and marking that it has recovered. For example, if the value is overwritten by a known-good value, then the mutex can be marked as un-poisoned. Or possibly, the value could be inspected to determine if it is in a consistent state, and if so the poison is removed.

 ##### Examples

 
```
#![feature(mutex_unpoison)]

use std::sync::{Arc, Mutex};
use std::thread;

let mutex = Arc::new(Mutex::new(0));
let c_mutex = Arc::clone(&mutex);

let _ = thread::spawn(move || {
    let _lock = c_mutex.lock().unwrap();
    panic!(); // the mutex gets poisoned
}).join();

assert_eq!(mutex.is_poisoned(), true);
let x = mutex.lock().unwrap_or_else(|mut e| {
    **e.get_mut() = 1;
    mutex.clear_poison();
    e.into_inner()
});
assert_eq!(mutex.is_poisoned(), false);
assert_eq!(*x, 1);
```
 
[source](https://doc.rust-lang.org/src/std/sync/mutex.rs.html#430-436)1.6.0
```
pub fn into_inner(self) -> LockResult<T>
where
    T: Sized,
```

Consumes this mutex, returning the underlying data.

 ##### Errors

 If another user of this mutex panicked while holding the mutex, then this call will return an error instead.

 ##### Examples

 
```
use std::sync::Mutex;

let mutex = Mutex::new(0);
assert_eq!(mutex.into_inner().unwrap(), 0);
```
 
[source](https://doc.rust-lang.org/src/std/sync/mutex.rs.html#458-461)1.6.0
```
pub fn get_mut(&mut self) -> LockResult<&mut T>
```

Returns a mutable reference to the underlying data.

 Since this call borrows the `Mutex` mutably, no actual locking needs to take place – the mutable borrow statically guarantees no locks exist.

 ##### Errors

 If another user of this mutex panicked while holding the mutex, then this call will return an error instead.

 ##### Examples

 
```
use std::sync::Mutex;

let mut mutex = Mutex::new(0);
*mutex.get_mut().unwrap() = 10;
assert_eq!(*mutex.lock().unwrap(), 10);
```
 


Trait Implementations
---------------------



[source](https://doc.rust-lang.org/src/std/sync/mutex.rs.html#482-505)
```
impl<T: ?Sized + Debug> Debug for Mutex<T>
```

[source](https://doc.rust-lang.org/src/std/sync/mutex.rs.html#483-504)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result
```
Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt)


[source](https://doc.rust-lang.org/src/std/sync/mutex.rs.html#474-479)1.10.0
```
impl<T: ?Sized + Default> Default for Mutex<T>
```

[source](https://doc.rust-lang.org/src/std/sync/mutex.rs.html#476-478)
```
fn default() -> Mutex<T>
```

Creates a `Mutex<T>`, with the `Default` value for T.

 

[source](https://doc.rust-lang.org/src/std/sync/mutex.rs.html#465-471)1.24.0
```
impl<T> From<T> for Mutex<T>
```

[source](https://doc.rust-lang.org/src/std/sync/mutex.rs.html#468-470)
```
fn from(t: T) -> Self
```

Creates a new mutex in an unlocked state ready for use. This is equivalent to [`Mutex::new`](struct.mutex#method.new "associated function std::sync::Mutex::new").

 

[source](https://doc.rust-lang.org/src/std/panic.rs.html#72)1.12.0
```
impl<T: ?Sized> RefUnwindSafe for Mutex<T>
```
[source](https://doc.rust-lang.org/src/std/sync/mutex.rs.html#184)
```
impl<T: ?Sized + Send> Send for Mutex<T>
```
[source](https://doc.rust-lang.org/src/std/sync/mutex.rs.html#186)
```
impl<T: ?Sized + Send> Sync for Mutex<T>
```
[source](https://doc.rust-lang.org/src/std/panic.rs.html#67)1.9.0
```
impl<T: ?Sized> UnwindSafe for Mutex<T>
```


Auto Trait Implementations
--------------------------



```
impl<T: ?Sized> Unpin for Mutex<T>
where
    T: Unpin,
```

Blanket Implementations
-----------------------



[source](https://doc.rust-lang.org/src/core/any.rs.html#200)
```
impl<T> Any for T
where
    T: 'static + ?Sized,
```

[source](https://doc.rust-lang.org/src/core/any.rs.html#201)
```
fn type_id(&self) -> TypeId
```
Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#208)
```
impl<T> Borrow<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#210)
```
fn borrow(&self) -> &T
```
Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#216)
```
impl<T> BorrowMut<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#217)
```
fn borrow_mut(&mut self) -> &mut T
```
Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#740)
```
impl<T> From<!> for T
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#741)
```
fn from(t: !) -> T
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#723)
```
impl<T> From<T> for T
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#726)
```
fn from(t: T) -> T
```

Returns the argument unchanged.

 

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#707)
```
impl<T, U> Into<U> for T
where
    U: From<T>,
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#716)
```
fn into(self) -> U
```

Calls `U::from(self)`.

 That is, this conversion is whatever the implementation of `[From](../convert/trait.from "trait std::convert::From")<T> for U` chooses to do.

 

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#763)
```
impl<T, U> TryFrom<U> for T
where
    U: Into<T>,
```


```
type Error = Infallible
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#770)
```
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#748)
```
impl<T, U> TryInto<U> for T
where
    U: TryFrom<T>,
```


```
type Error = <U as TryFrom<T>>::Error
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#755)
```
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
```
Performs the conversion.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/sync/struct.Mutex.html>

Struct std::collections::hash\_map::HashMap
===========================================



```
pub struct HashMap<K, V, S = RandomState> { /* private fields */ }
```

A [hash map](../index#use-a-hashmap-when "mod std::collections") implemented with quadratic probing and SIMD lookup.

 By default, `HashMap` uses a hashing algorithm selected to provide resistance against HashDoS attacks. The algorithm is randomly seeded, and a reasonable best-effort is made to generate this seed from a high quality, secure source of randomness provided by the host without blocking the program. Because of this, the randomness of the seed depends on the output quality of the system’s random number generator when the seed is created. In particular, seeds generated when the system’s entropy pool is abnormally low such as during system boot may be of a lower quality.

 The default hashing algorithm is currently SipHash 1-3, though this is subject to change at any point in the future. While its performance is very competitive for medium sized keys, other hashing algorithms will outperform it for small keys such as integers as well as large keys such as long strings, though those algorithms will typically *not* protect against attacks such as HashDoS.

 The hashing algorithm can be replaced on a per-`HashMap` basis using the [`default`](../../default/trait.default#tymethod.default "associated function std::default::Default::default"), [`with_hasher`](struct.hashmap#method.with_hasher "associated function std::collections::hash_map::HashMap::with_hasher"), and [`with_capacity_and_hasher`](struct.hashmap#method.with_capacity_and_hasher "associated function std::collections::hash_map::HashMap::with_capacity_and_hasher") methods. There are many alternative [hashing algorithms available on crates.io](https://crates.io/keywords/hasher).

 It is required that the keys implement the [`Eq`](../../cmp/trait.eq "trait std::cmp::Eq") and [`Hash`](../../hash/trait.hash "trait std::hash::Hash") traits, although this can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`. If you implement these yourself, it is important that the following property holds:

 
```
k1 == k2 -> hash(k1) == hash(k2)

```
 In other words, if two keys are equal, their hashes must be equal.

 It is a logic error for a key to be modified in such a way that the key’s hash, as determined by the [`Hash`](../../hash/trait.hash "trait std::hash::Hash") trait, or its equality, as determined by the [`Eq`](../../cmp/trait.eq "trait std::cmp::Eq") trait, changes while it is in the map. This is normally only possible through [`Cell`](../../cell/struct.cell "struct std::cell::Cell"), [`RefCell`](../../cell/struct.refcell "struct std::cell::RefCell"), global state, I/O, or unsafe code. The behavior resulting from such a logic error is not specified, but will be encapsulated to the `HashMap` that observed the logic error and not result in undefined behavior. This could include panics, incorrect results, aborts, memory leaks, and non-termination.

 The hash table implementation is a Rust port of Google’s [SwissTable](https://abseil.io/blog/20180927-swisstables). The original C++ version of SwissTable can be found [here](https://github.com/abseil/abseil-cpp/blob/master/absl/container/internal/raw_hash_set.h), and this [CppCon talk](https://www.youtube.com/watch?v=ncHmEUmJZf4) gives an overview of how the algorithm works.

 Examples
--------

 
```
use std::collections::HashMap;

// Type inference lets us omit an explicit type signature (which
// would be `HashMap<String, String>` in this example).
let mut book_reviews = HashMap::new();

// Review some books.
book_reviews.insert(
    "Adventures of Huckleberry Finn".to_string(),
    "My favorite book.".to_string(),
);
book_reviews.insert(
    "Grimms' Fairy Tales".to_string(),
    "Masterpiece.".to_string(),
);
book_reviews.insert(
    "Pride and Prejudice".to_string(),
    "Very enjoyable.".to_string(),
);
book_reviews.insert(
    "The Adventures of Sherlock Holmes".to_string(),
    "Eye lyked it alot.".to_string(),
);

// Check for a specific one.
// When collections store owned values (String), they can still be
// queried using references (&str).
if !book_reviews.contains_key("Les Misérables") {
    println!("We've got {} reviews, but Les Misérables ain't one.",
             book_reviews.len());
}

// oops, this review has a lot of spelling mistakes, let's delete it.
book_reviews.remove("The Adventures of Sherlock Holmes");

// Look up the values associated with some keys.
let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
for &book in &to_find {
    match book_reviews.get(book) {
        Some(review) => println!("{book}: {review}"),
        None => println!("{book} is unreviewed.")
    }
}

// Look up the value for a key (will panic if the key is not found).
println!("Review for Jane: {}", book_reviews["Pride and Prejudice"]);

// Iterate over everything.
for (book, review) in &book_reviews {
    println!("{book}: \"{review}\"");
}
```
 A `HashMap` with a known list of items can be initialized from an array:

 
```
use std::collections::HashMap;

let solar_distance = HashMap::from([
    ("Mercury", 0.4),
    ("Venus", 0.7),
    ("Earth", 1.0),
    ("Mars", 1.5),
]);
```
 `HashMap` implements an [`Entry` API](#method.entry), which allows for complex methods of getting, setting, updating and removing keys and their values:

 
```
use std::collections::HashMap;

// type inference lets us omit an explicit type signature (which
// would be `HashMap<&str, u8>` in this example).
let mut player_stats = HashMap::new();

fn random_stat_buff() -> u8 {
    // could actually return some random value here - let's just return
    // some fixed value for now
    42
}

// insert a key only if it doesn't already exist
player_stats.entry("health").or_insert(100);

// insert a key using a function that provides a new value only if it
// doesn't already exist
player_stats.entry("defence").or_insert_with(random_stat_buff);

// update a key, guarding against the key possibly not being set
let stat = player_stats.entry("attack").or_insert(100);
*stat += random_stat_buff();

// modify an entry before an insert with in-place mutation
player_stats.entry("mana").and_modify(|mana| *mana += 200).or_insert(100);
```
 The easiest way to use `HashMap` with a custom key type is to derive [`Eq`](../../cmp/trait.eq "trait std::cmp::Eq") and [`Hash`](../../hash/trait.hash "trait std::hash::Hash"). We must also derive [`PartialEq`](../../cmp/trait.partialeq "trait std::cmp::PartialEq").

 
```
use std::collections::HashMap;

#[derive(Hash, Eq, PartialEq, Debug)]
struct Viking {
    name: String,
    country: String,
}

impl Viking {
    /// Creates a new Viking.
    fn new(name: &str, country: &str) -> Viking {
        Viking { name: name.to_string(), country: country.to_string() }
    }
}

// Use a HashMap to store the vikings' health points.
let vikings = HashMap::from([
    (Viking::new("Einar", "Norway"), 25),
    (Viking::new("Olaf", "Denmark"), 24),
    (Viking::new("Harald", "Iceland"), 12),
]);

// Use derived implementation to print the status of the vikings.
for (viking, health) in &vikings {
    println!("{viking:?} has {health} hp");
}
```
 Implementations
---------------



[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#218-255)
```
impl<K, V> HashMap<K, V, RandomState>
```

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#233-235)
```
pub fn new() -> HashMap<K, V, RandomState>
```

Creates an empty `HashMap`.

 The hash map is initially created with a capacity of 0, so it will not allocate until it is first inserted into.

 ##### Examples

 
```
use std::collections::HashMap;
let mut map: HashMap<&str, i32> = HashMap::new();
```
 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#252-254)
```
pub fn with_capacity(capacity: usize) -> HashMap<K, V, RandomState>
```

Creates an empty `HashMap` with at least the specified capacity.

 The hash map 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 0, the hash map will not allocate.

 ##### Examples

 
```
use std::collections::HashMap;
let mut map: HashMap<&str, i32> = HashMap::with_capacity(10);
```
 

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#257-730)
```
impl<K, V, S> HashMap<K, V, S>
```

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#284-286)1.7.0 (const: [unstable](https://github.com/rust-lang/rust/issues/102575 "Tracking issue for const_collections_with_hasher"))
```
pub fn with_hasher(hash_builder: S) -> HashMap<K, V, S>
```

Creates an empty `HashMap` which will use the given hash builder to hash keys.

 The created map has the default initial capacity.

 Warning: `hash_builder` is normally randomly generated, and is designed to allow HashMaps to be resistant to attacks that cause many collisions and very poor performance. Setting it manually using this function can expose a DoS attack vector.

 The `hash_builder` passed should implement the [`BuildHasher`](../../hash/trait.buildhasher "trait std::hash::BuildHasher") trait for the HashMap to be useful, see its documentation for details.

 ##### Examples

 
```
use std::collections::HashMap;
use std::collections::hash_map::RandomState;

let s = RandomState::new();
let mut map = HashMap::with_hasher(s);
map.insert(1, 2);
```
 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#315-317)1.7.0
```
pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> HashMap<K, V, S>
```

Creates an empty `HashMap` with at least the specified capacity, using `hasher` to hash the keys.

 The hash map 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 0, the hash map will not allocate.

 Warning: `hasher` is normally randomly generated, and is designed to allow HashMaps to be resistant to attacks that cause many collisions and very poor performance. Setting it manually using this function can expose a DoS attack vector.

 The `hasher` passed should implement the [`BuildHasher`](../../hash/trait.buildhasher "trait std::hash::BuildHasher") trait for the HashMap to be useful, see its documentation for details.

 ##### Examples

 
```
use std::collections::HashMap;
use std::collections::hash_map::RandomState;

let s = RandomState::new();
let mut map = HashMap::with_capacity_and_hasher(10, s);
map.insert(1, 2);
```
 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#333-335)
```
pub fn capacity(&self) -> usize
```

Returns the number of elements the map can hold without reallocating.

 This number is a lower bound; the `HashMap<K, V>` might be able to hold more, but is guaranteed to be able to hold at least this many.

 ##### Examples

 
```
use std::collections::HashMap;
let map: HashMap<i32, i32> = HashMap::with_capacity(100);
assert!(map.capacity() >= 100);
```
 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#361-363)
```
pub fn keys(&self) -> Keys<'_, K, V> ⓘ
```

An iterator visiting all keys in arbitrary order. The iterator element type is `&'a K`.

 ##### Examples

 
```
use std::collections::HashMap;

let map = HashMap::from([
    ("a", 1),
    ("b", 2),
    ("c", 3),
]);

for key in map.keys() {
    println!("{key}");
}
```
 ##### Performance

 In the current implementation, iterating over keys takes O(capacity) time instead of O(len) because it internally visits empty buckets too.

 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#394-396)1.54.0
```
pub fn into_keys(self) -> IntoKeys<K, V> ⓘ
```

Creates a consuming iterator visiting all the keys in arbitrary order. The map cannot be used after calling this. The iterator element type is `K`.

 ##### Examples

 
```
use std::collections::HashMap;

let map = HashMap::from([
    ("a", 1),
    ("b", 2),
    ("c", 3),
]);

let mut vec: Vec<&str> = map.into_keys().collect();
// The `IntoKeys` iterator produces keys in arbitrary order, so the
// keys must be sorted to test them against a sorted array.
vec.sort_unstable();
assert_eq!(vec, ["a", "b", "c"]);
```
 ##### Performance

 In the current implementation, iterating over keys takes O(capacity) time instead of O(len) because it internally visits empty buckets too.

 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#422-424)
```
pub fn values(&self) -> Values<'_, K, V> ⓘ
```

An iterator visiting all values in arbitrary order. The iterator element type is `&'a V`.

 ##### Examples

 
```
use std::collections::HashMap;

let map = HashMap::from([
    ("a", 1),
    ("b", 2),
    ("c", 3),
]);

for val in map.values() {
    println!("{val}");
}
```
 ##### Performance

 In the current implementation, iterating over values takes O(capacity) time instead of O(len) because it internally visits empty buckets too.

 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#454-456)1.10.0
```
pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> ⓘ
```

An iterator visiting all values mutably in arbitrary order. The iterator element type is `&'a mut V`.

 ##### Examples

 
```
use std::collections::HashMap;

let mut map = HashMap::from([
    ("a", 1),
    ("b", 2),
    ("c", 3),
]);

for val in map.values_mut() {
    *val = *val + 10;
}

for val in map.values() {
    println!("{val}");
}
```
 ##### Performance

 In the current implementation, iterating over values takes O(capacity) time instead of O(len) because it internally visits empty buckets too.

 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#487-489)1.54.0
```
pub fn into_values(self) -> IntoValues<K, V> ⓘ
```

Creates a consuming iterator visiting all the values in arbitrary order. The map cannot be used after calling this. The iterator element type is `V`.

 ##### Examples

 
```
use std::collections::HashMap;

let map = HashMap::from([
    ("a", 1),
    ("b", 2),
    ("c", 3),
]);

let mut vec: Vec<i32> = map.into_values().collect();
// The `IntoValues` iterator produces values in arbitrary order, so
// the values must be sorted to test them against a sorted array.
vec.sort_unstable();
assert_eq!(vec, [1, 2, 3]);
```
 ##### Performance

 In the current implementation, iterating over values takes O(capacity) time instead of O(len) because it internally visits empty buckets too.

 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#516-518)
```
pub fn iter(&self) -> Iter<'_, K, V> ⓘ
```

An iterator visiting all key-value pairs in arbitrary order. The iterator element type is `(&'a K, &'a V)`.

 ##### Examples

 
```
use std::collections::HashMap;

let map = HashMap::from([
    ("a", 1),
    ("b", 2),
    ("c", 3),
]);

for (key, val) in map.iter() {
    println!("key: {key} val: {val}");
}
```
 ##### Performance

 In the current implementation, iterating over map takes O(capacity) time instead of O(len) because it internally visits empty buckets too.

 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#551-553)
```
pub fn iter_mut(&mut self) -> IterMut<'_, K, V> ⓘ
```

An iterator visiting all key-value pairs in arbitrary order, with mutable references to the values. The iterator element type is `(&'a K, &'a mut V)`.

 ##### Examples

 
```
use std::collections::HashMap;

let mut map = HashMap::from([
    ("a", 1),
    ("b", 2),
    ("c", 3),
]);

// Update all values
for (_, val) in map.iter_mut() {
    *val *= 2;
}

for (key, val) in &map {
    println!("key: {key} val: {val}");
}
```
 ##### Performance

 In the current implementation, iterating over map takes O(capacity) time instead of O(len) because it internally visits empty buckets too.

 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#568-570)
```
pub fn len(&self) -> usize
```

Returns the number of elements in the map.

 ##### Examples

 
```
use std::collections::HashMap;

let mut a = HashMap::new();
assert_eq!(a.len(), 0);
a.insert(1, "a");
assert_eq!(a.len(), 1);
```
 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#586-588)
```
pub fn is_empty(&self) -> bool
```

Returns `true` if the map contains no elements.

 ##### Examples

 
```
use std::collections::HashMap;

let mut a = HashMap::new();
assert!(a.is_empty());
a.insert(1, "a");
assert!(!a.is_empty());
```
 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#616-618)1.6.0
```
pub fn drain(&mut self) -> Drain<'_, K, V> ⓘ
```

Clears the map, returning all key-value pairs as an iterator. Keeps the allocated memory for reuse.

 If the returned iterator is dropped before being fully consumed, it drops the remaining key-value pairs. The returned iterator keeps a mutable borrow on the map to optimize its implementation.

 ##### Examples

 
```
use std::collections::HashMap;

let mut a = HashMap::new();
a.insert(1, "a");
a.insert(2, "b");

for (k, v) in a.drain().take(1) {
    assert!(k == 1 || k == 2);
    assert!(v == "a" || v == "b");
}

assert!(a.is_empty());
```
 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#658-663)
```
pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, K, V, F> ⓘ
where
    F: FnMut(&K, &mut V) -> bool,
```

🔬This is a nightly-only experimental API. (`hash_drain_filter` [#59618](https://github.com/rust-lang/rust/issues/59618))

Creates an iterator which uses a closure to determine if an element should be removed.

 If the closure returns true, the element is removed from the map and yielded. If the closure returns false, or panics, the element remains in the map and will not be yielded.

 Note that `drain_filter` lets you mutate every value in the filter closure, regardless of whether you choose to keep or remove it.

 If the iterator is only partially consumed or not consumed at all, each of the remaining elements will still be subjected to the closure and removed and dropped if it returns true.

 It is unspecified how many more elements will be subjected to the closure if a panic occurs in the closure, or a panic occurs while dropping an element, or if the `DrainFilter` value is leaked.

 ##### Examples

 Splitting a map into even and odd keys, reusing the original map:

 
```
#![feature(hash_drain_filter)]
use std::collections::HashMap;

let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
let drained: HashMap<i32, i32> = map.drain_filter(|k, _v| k % 2 == 0).collect();

let mut evens = drained.keys().copied().collect::<Vec<_>>();
let mut odds = map.keys().copied().collect::<Vec<_>>();
evens.sort();
odds.sort();

assert_eq!(evens, vec![0, 2, 4, 6]);
assert_eq!(odds, vec![1, 3, 5, 7]);
```
 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#687-692)1.18.0
```
pub fn retain<F>(&mut self, f: F)
where
    F: FnMut(&K, &mut V) -> bool,
```

Retains only the elements specified by the predicate.

 In other words, remove all pairs `(k, v)` for which `f(&k, &mut v)` returns `false`. The elements are visited in unsorted (and unspecified) order.

 ##### Examples

 
```
use std::collections::HashMap;

let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
map.retain(|&k, _| k % 2 == 0);
assert_eq!(map.len(), 4);
```
 ##### Performance

 In the current implementation, this operation takes O(capacity) time instead of O(len) because it internally visits empty buckets too.

 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#709-711)
```
pub fn clear(&mut self)
```

Clears the map, removing all key-value pairs. Keeps the allocated memory for reuse.

 ##### Examples

 
```
use std::collections::HashMap;

let mut a = HashMap::new();
a.insert(1, "a");
a.clear();
assert!(a.is_empty());
```
 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#727-729)1.9.0
```
pub fn hasher(&self) -> &S
```

Returns a reference to the map’s [`BuildHasher`](../../hash/trait.buildhasher "trait std::hash::BuildHasher").

 ##### Examples

 
```
use std::collections::HashMap;
use std::collections::hash_map::RandomState;

let hasher = RandomState::new();
let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
let hasher: &RandomState = map.hasher();
```
 

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#732-1193)
```
impl<K, V, S> HashMap<K, V, S>
where
    K: Eq + Hash,
    S: BuildHasher,
```

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#756-758)
```
pub fn reserve(&mut self, additional: usize)
```

Reserves capacity for at least `additional` more elements to be inserted in the `HashMap`. The collection may reserve more space to speculatively avoid frequent reallocations. After calling `reserve`, capacity will be greater than or equal to `self.len() + additional`. Does nothing if capacity is already sufficient.

 ##### Panics

 Panics if the new allocation size overflows [`usize`](../../primitive.usize "primitive usize").

 ##### Examples

 
```
use std::collections::HashMap;
let mut map: HashMap<&str, i32> = HashMap::new();
map.reserve(10);
```
 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#782-784)1.57.0
```
pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>
```

Tries to reserve capacity for at least `additional` more elements to be inserted in the `HashMap`. The collection may reserve more space to speculatively avoid frequent reallocations. 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.

 ##### Errors

 If the capacity overflows, or the allocator reports a failure, then an error is returned.

 ##### Examples

 
```
use std::collections::HashMap;

let mut map: HashMap<&str, isize> = HashMap::new();
map.try_reserve(10).expect("why is the test harness OOMing on a handful of bytes?");
```
 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#804-806)
```
pub fn shrink_to_fit(&mut self)
```

Shrinks the capacity of the map as much as possible. It will drop down as much as possible while maintaining the internal rules and possibly leaving some space in accordance with the resize policy.

 ##### Examples

 
```
use std::collections::HashMap;

let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
map.insert(1, 2);
map.insert(3, 4);
assert!(map.capacity() >= 100);
map.shrink_to_fit();
assert!(map.capacity() >= 2);
```
 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#830-832)1.56.0
```
pub fn shrink_to(&mut self, min_capacity: usize)
```

Shrinks the capacity of the map with a lower limit. It will drop down no lower than the supplied limit while maintaining the internal rules and possibly leaving some space in accordance with the resize policy.

 If the current capacity is less than the lower limit, this is a no-op.

 ##### Examples

 
```
use std::collections::HashMap;

let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
map.insert(1, 2);
map.insert(3, 4);
assert!(map.capacity() >= 100);
map.shrink_to(10);
assert!(map.capacity() >= 10);
map.shrink_to(0);
assert!(map.capacity() >= 2);
```
 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#854-856)
```
pub fn entry(&mut self, key: K) -> Entry<'_, K, V>
```

Gets the given key’s corresponding entry in the map for in-place manipulation.

 ##### Examples

 
```
use std::collections::HashMap;

let mut letters = HashMap::new();

for ch in "a short treatise on fungi".chars() {
    letters.entry(ch).and_modify(|counter| *counter += 1).or_insert(1);
}

assert_eq!(letters[&'s'], 2);
assert_eq!(letters[&'t'], 3);
assert_eq!(letters[&'u'], 1);
assert_eq!(letters.get(&'y'), None);
```
 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#876-882)
```
pub fn get<Q>(&self, k: &Q) -> Option<&V>
where
    K: Borrow<Q>,
    Q: Hash + Eq + ?Sized,
```

Returns a reference to the value corresponding to the key.

 The key may be any borrowed form of the map’s key type, but [`Hash`](../../hash/trait.hash "trait std::hash::Hash") and [`Eq`](../../cmp/trait.eq "trait std::cmp::Eq") on the borrowed form *must* match those for the key type.

 ##### Examples

 
```
use std::collections::HashMap;

let mut map = HashMap::new();
map.insert(1, "a");
assert_eq!(map.get(&1), Some(&"a"));
assert_eq!(map.get(&2), None);
```
 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#902-908)1.40.0
```
pub fn get_key_value<Q>(&self, k: &Q) -> Option<(&K, &V)>
where
    K: Borrow<Q>,
    Q: Hash + Eq + ?Sized,
```

Returns the key-value pair corresponding to the supplied key.

 The supplied key may be any borrowed form of the map’s key type, but [`Hash`](../../hash/trait.hash "trait std::hash::Hash") and [`Eq`](../../cmp/trait.eq "trait std::cmp::Eq") on the borrowed form *must* match those for the key type.

 ##### Examples

 
```
use std::collections::HashMap;

let mut map = HashMap::new();
map.insert(1, "a");
assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
assert_eq!(map.get_key_value(&2), None);
```
 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#956-962)
```
pub fn get_many_mut<Q, const N: usize>(
    &mut self,
    ks: [&Q; N]
) -> Option<[&mut V; N]>
where
    K: Borrow<Q>,
    Q: Hash + Eq + ?Sized,
```

🔬This is a nightly-only experimental API. (`map_many_mut` [#97601](https://github.com/rust-lang/rust/issues/97601))

Attempts to get mutable references to `N` values in the map at once.

 Returns an array of length `N` with the results of each query. For soundness, at most one mutable reference will be returned to any value. `None` will be returned if any of the keys are duplicates or missing.

 ##### Examples

 
```
#![feature(map_many_mut)]
use std::collections::HashMap;

let mut libraries = HashMap::new();
libraries.insert("Bodleian Library".to_string(), 1602);
libraries.insert("Athenæum".to_string(), 1807);
libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
libraries.insert("Library of Congress".to_string(), 1800);

let got = libraries.get_many_mut([
    "Athenæum",
    "Library of Congress",
]);
assert_eq!(
    got,
    Some([
        &mut 1807,
        &mut 1800,
    ]),
);

// Missing keys result in None
let got = libraries.get_many_mut([
    "Athenæum",
    "New York Public Library",
]);
assert_eq!(got, None);

// Duplicate keys result in None
let got = libraries.get_many_mut([
    "Athenæum",
    "Athenæum",
]);
assert_eq!(got, None);
```
 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#1012-1021)
```
pub unsafe fn get_many_unchecked_mut<Q, const N: usize>(
    &mut self,
    ks: [&Q; N]
) -> Option<[&mut V; N]>
where
    K: Borrow<Q>,
    Q: Hash + Eq + ?Sized,
```

🔬This is a nightly-only experimental API. (`map_many_mut` [#97601](https://github.com/rust-lang/rust/issues/97601))

Attempts to get mutable references to `N` values in the map at once, without validating that the values are unique.

 Returns an array of length `N` with the results of each query. `None` will be returned if any of the keys are missing.

 For a safe alternative see [`get_many_mut`](struct.hashmap#method.get_many_mut "method std::collections::hash_map::HashMap::get_many_mut").

 ##### Safety

 Calling this method with overlapping keys is *[undefined behavior](../../../reference/behavior-considered-undefined)* even if the resulting references are not used.

 ##### Examples

 
```
#![feature(map_many_mut)]
use std::collections::HashMap;

let mut libraries = HashMap::new();
libraries.insert("Bodleian Library".to_string(), 1602);
libraries.insert("Athenæum".to_string(), 1807);
libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
libraries.insert("Library of Congress".to_string(), 1800);

let got = libraries.get_many_mut([
    "Athenæum",
    "Library of Congress",
]);
assert_eq!(
    got,
    Some([
        &mut 1807,
        &mut 1800,
    ]),
);

// Missing keys result in None
let got = libraries.get_many_mut([
    "Athenæum",
    "New York Public Library",
]);
assert_eq!(got, None);
```
 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#1041-1047)
```
pub fn contains_key<Q>(&self, k: &Q) -> bool
where
    K: Borrow<Q>,
    Q: Hash + Eq + ?Sized,
```

Returns `true` if the map contains a value for the specified key.

 The key may be any borrowed form of the map’s key type, but [`Hash`](../../hash/trait.hash "trait std::hash::Hash") and [`Eq`](../../cmp/trait.eq "trait std::cmp::Eq") on the borrowed form *must* match those for the key type.

 ##### Examples

 
```
use std::collections::HashMap;

let mut map = HashMap::new();
map.insert(1, "a");
assert_eq!(map.contains_key(&1), true);
assert_eq!(map.contains_key(&2), false);
```
 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#1069-1075)
```
pub fn get_mut<Q>(&mut self, k: &Q) -> Option<&mut V>
where
    K: Borrow<Q>,
    Q: Hash + Eq + ?Sized,
```

Returns a mutable reference to the value corresponding to the key.

 The key may be any borrowed form of the map’s key type, but [`Hash`](../../hash/trait.hash "trait std::hash::Hash") and [`Eq`](../../cmp/trait.eq "trait std::cmp::Eq") on the borrowed form *must* match those for the key type.

 ##### Examples

 
```
use std::collections::HashMap;

let mut map = HashMap::new();
map.insert(1, "a");
if let Some(x) = map.get_mut(&1) {
    *x = "b";
}
assert_eq!(map[&1], "b");
```
 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#1103-1105)
```
pub fn insert(&mut self, k: K, v: V) -> Option<V>
```

Inserts a key-value pair into the map.

 If the map did not have this key present, [`None`](../../option/enum.option#variant.None "variant std::option::Option::None") is returned.

 If the map did have this key present, the value is updated, and the old value is returned. The key is not updated, though; this matters for types that can be `==` without being identical. See the [module-level documentation](../index#insert-and-complex-keys "mod std::collections") for more.

 ##### Examples

 
```
use std::collections::HashMap;

let mut map = HashMap::new();
assert_eq!(map.insert(37, "a"), None);
assert_eq!(map.is_empty(), false);

map.insert(37, "b");
assert_eq!(map.insert(37, "c"), Some("b"));
assert_eq!(map[&37], "c");
```
 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#1131-1136)
```
pub fn try_insert(
    &mut self,
    key: K,
    value: V
) -> Result<&mut V, OccupiedError<'_, K, V>>
```

🔬This is a nightly-only experimental API. (`map_try_insert` [#82766](https://github.com/rust-lang/rust/issues/82766))

Tries to insert a key-value pair into the map, and returns a mutable reference to the value in the entry.

 If the map already had this key present, nothing is updated, and an error containing the occupied entry and the value is returned.

 ##### Examples

 Basic usage:

 
```
#![feature(map_try_insert)]

use std::collections::HashMap;

let mut map = HashMap::new();
assert_eq!(map.try_insert(37, "a").unwrap(), &"a");

let err = map.try_insert(37, "b").unwrap_err();
assert_eq!(err.entry.key(), &37);
assert_eq!(err.entry.get(), &"a");
assert_eq!(err.value, "b");
```
 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#1157-1163)
```
pub fn remove<Q>(&mut self, k: &Q) -> Option<V>
where
    K: Borrow<Q>,
    Q: Hash + Eq + ?Sized,
```

Removes a key from the map, returning the value at the key if the key was previously in the map.

 The key may be any borrowed form of the map’s key type, but [`Hash`](../../hash/trait.hash "trait std::hash::Hash") and [`Eq`](../../cmp/trait.eq "trait std::cmp::Eq") on the borrowed form *must* match those for the key type.

 ##### Examples

 
```
use std::collections::HashMap;

let mut map = HashMap::new();
map.insert(1, "a");
assert_eq!(map.remove(&1), Some("a"));
assert_eq!(map.remove(&1), None);
```
 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#1186-1192)1.27.0
```
pub fn remove_entry<Q>(&mut self, k: &Q) -> Option<(K, V)>
where
    K: Borrow<Q>,
    Q: Hash + Eq + ?Sized,
```

Removes a key from the map, returning the stored key and value if the key was previously in the map.

 The key may be any borrowed form of the map’s key type, but [`Hash`](../../hash/trait.hash "trait std::hash::Hash") and [`Eq`](../../cmp/trait.eq "trait std::cmp::Eq") on the borrowed form *must* match those for the key type.

 ##### Examples

 
```
use std::collections::HashMap;

let mut map = HashMap::new();
map.insert(1, "a");
assert_eq!(map.remove_entry(&1), Some((1, "a")));
assert_eq!(map.remove(&1), None);
```
 

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#1195-1256)
```
impl<K, V, S> HashMap<K, V, S>
where
    S: BuildHasher,
```

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#1232-1234)
```
pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut<'_, K, V, S>
```

🔬This is a nightly-only experimental API. (`hash_raw_entry` [#56167](https://github.com/rust-lang/rust/issues/56167))

Creates a raw entry builder for the HashMap.

 Raw entries provide the lowest level of control for searching and manipulating a map. They must be manually initialized with a hash and then manually searched. After this, insertions into a vacant entry still require an owned key to be provided.

 Raw entries are useful for such exotic situations as:

 * Hash memoization
* Deferring the creation of an owned key until it is known to be required
* Using a search key that doesn’t work with the Borrow trait
* Using custom comparison logic without newtype wrappers

 Because raw entries provide much more low-level control, it’s much easier to put the HashMap into an inconsistent state which, while memory-safe, will cause the map to produce seemingly random results. Higher-level and more foolproof APIs like `entry` should be preferred when possible.

 In particular, the hash used to initialized the raw entry must still be consistent with the hash of the key that is ultimately stored in the entry. This is because implementations of HashMap may need to recompute hashes when resizing, at which point only the keys are available.

 Raw entries give mutable access to the keys. This must not be used to modify how the key would compare or hash, as the map will not re-evaluate where the key should go, meaning the keys may become “lost” if their location does not reflect their state. For instance, if you change a key so that the map now contains keys which compare equal, search may start acting erratically, with two keys randomly masking each other. Implementations are free to assume this doesn’t happen (within the limits of memory-safety).

 
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#1253-1255)
```
pub fn raw_entry(&self) -> RawEntryBuilder<'_, K, V, S>
```

🔬This is a nightly-only experimental API. (`hash_raw_entry` [#56167](https://github.com/rust-lang/rust/issues/56167))

Creates a raw immutable entry builder for the HashMap.

 Raw entries provide the lowest level of control for searching and manipulating a map. They must be manually initialized with a hash and then manually searched.

 This is useful for

 * Hash memoization
* Using a search key that doesn’t work with the Borrow trait
* Using custom comparison logic without newtype wrappers

 Unless you are in such a situation, higher-level and more foolproof APIs like `get` should be preferred.

 Immutable raw entries have very limited use; you might instead want `raw_entry_mut`.

 


Trait Implementations
---------------------



[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#1259-1274)
```
impl<K, V, S> Clone for HashMap<K, V, S>
where
    K: Clone,
    V: Clone,
    S: Clone,
```

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#1266-1268)
```
fn clone(&self) -> Self
```
Returns a copy of the value. [Read more](../../clone/trait.clone#tymethod.clone)

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#1271-1273)
```
fn clone_from(&mut self, other: &Self)
```
Performs copy-assignment from `source`. [Read more](../../clone/trait.clone#method.clone_from)


[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#1302-1310)
```
impl<K, V, S> Debug for HashMap<K, V, S>
where
    K: Debug,
    V: Debug,
```

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#1307-1309)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result
```
Formats the value using the given formatter. [Read more](../../fmt/trait.debug#tymethod.fmt)


[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#1313-1322)
```
impl<K, V, S> Default for HashMap<K, V, S>
where
    S: Default,
```

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#1319-1321)
```
fn default() -> HashMap<K, V, S>
```

Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.

 

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#3051-3071)1.4.0
```
impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S>
where
    K: Eq + Hash + Copy,
    V: Copy,
    S: BuildHasher,
```

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#3058-3060)
```
fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T)
```
Extends a collection with the contents of an iterator. [Read more](../../iter/trait.extend#tymethod.extend)

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#3063-3065)
```
fn extend_one(&mut self, (k, v): (&'a K, &'a V))
```

🔬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/src/std/collections/hash/map.rs.html#3068-3070)
```
fn extend_reserve(&mut self, additional: usize)
```

🔬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](../../iter/trait.extend#method.extend_reserve)


[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#3029-3048)
```
impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
where
    K: Eq + Hash,
    S: BuildHasher,
```

Inserts all new key-values from the iterator and replaces values with existing keys with new values returned from the iterator.

 

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#3035-3037)
```
fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T)
```
Extends a collection with the contents of an iterator. [Read more](../../iter/trait.extend#tymethod.extend)

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#3040-3042)
```
fn extend_one(&mut self, (k, v): (K, V))
```

🔬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/src/std/collections/hash/map.rs.html#3045-3047)
```
fn extend_reserve(&mut self, additional: usize)
```

🔬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](../../iter/trait.extend#method.extend_reserve)


[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#1357-1373)1.56.0
```
impl<K, V, const N: usize> From<[(K, V); N]> for HashMap<K, V, RandomState>
where
    K: Eq + Hash,
```

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#1370-1372)
```
fn from(arr: [(K, V); N]) -> Self
```

##### Examples

 
```
use std::collections::HashMap;

let map1 = HashMap::from([(1, 2), (3, 4)]);
let map2: HashMap<_, _> = [(1, 2), (3, 4)].into();
assert_eq!(map1, map2);
```
 

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#3014-3024)
```
impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
where
    K: Eq + Hash,
    S: BuildHasher + Default,
```

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#3019-3023)
```
fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S>
```
Creates a value from an iterator. [Read more](../../iter/trait.fromiterator#tymethod.from_iter)


[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#1325-1342)
```
impl<K, Q, V, S> Index<&Q> for HashMap<K, V, S>
where
    K: Eq + Hash + Borrow<Q>,
    Q: Eq + Hash + ?Sized,
    S: BuildHasher,
```

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#1339-1341)
```
fn index(&self, key: &Q) -> &V
```

Returns a reference to the value corresponding to the supplied key.

 ##### Panics

 Panics if the key is not present in the `HashMap`.

 

```
type Output = V
```
The returned type after indexing.

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#2171-2180)
```
impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S>
```


```
type Item = (&'a K, &'a V)
```
The type of the elements being iterated over.

```
type IntoIter = Iter<'a, K, V>
```
Which kind of iterator are we turning this into?
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#2177-2179)
```
fn into_iter(self) -> Iter<'a, K, V> ⓘ
```
Creates an iterator from a value. [Read more](../../iter/trait.intoiterator#tymethod.into_iter)


[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#2183-2192)
```
impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S>
```


```
type Item = (&'a K, &'a mut V)
```
The type of the elements being iterated over.

```
type IntoIter = IterMut<'a, K, V>
```
Which kind of iterator are we turning this into?
[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#2189-2191)
```
fn into_iter(self) -> IterMut<'a, K, V> ⓘ
```
Creates an iterator from a value. [Read more](../../iter/trait.intoiterator#tymethod.into_iter)


[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#2195-2222)
```
impl<K, V, S> IntoIterator for HashMap<K, V, S>
```

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#2219-2221)
```
fn into_iter(self) -> IntoIter<K, V> ⓘ
```

Creates a consuming iterator, that is, one that moves each key-value pair out of the map in arbitrary order. The map cannot be used after calling this.

 ##### Examples

 
```
use std::collections::HashMap;

let map = HashMap::from([
    ("a", 1),
    ("b", 2),
    ("c", 3),
]);

// Not possible with .iter()
let vec: Vec<(&str, i32)> = map.into_iter().collect();
```
 

```
type Item = (K, V)
```
The type of the elements being iterated over.

```
type IntoIter = IntoIter<K, V>
```
Which kind of iterator are we turning this into?

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#1277-1290)
```
impl<K, V, S> PartialEq<HashMap<K, V, S>> for HashMap<K, V, S>
where
    K: Eq + Hash,
    V: PartialEq,
    S: BuildHasher,
```

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#1283-1289)
```
fn eq(&self, other: &HashMap<K, V, S>) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#226)
```
fn ne(&self, other: &Rhs) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#1293-1299)
```
impl<K, V, S> Eq for HashMap<K, V, S>
where
    K: Eq + Hash,
    V: Eq,
    S: BuildHasher,
```
[source](https://doc.rust-lang.org/src/std/panic.rs.html#78-84)1.36.0
```
impl<K, V, S> UnwindSafe for HashMap<K, V, S>
where
    K: UnwindSafe,
    V: UnwindSafe,
    S: UnwindSafe,
```


Auto Trait Implementations
--------------------------




```
impl<K, V, S> RefUnwindSafe for HashMap<K, V, S>
where
    K: RefUnwindSafe,
    S: RefUnwindSafe,
    V: RefUnwindSafe,
```

```
impl<K, V, S> Send for HashMap<K, V, S>
where
    K: Send,
    S: Send,
    V: Send,
```

```
impl<K, V, S> Sync for HashMap<K, V, S>
where
    K: Sync,
    S: Sync,
    V: Sync,
```

```
impl<K, V, S> Unpin for HashMap<K, V, S>
where
    K: Unpin,
    S: Unpin,
    V: Unpin,
```


Blanket Implementations
-----------------------



[source](https://doc.rust-lang.org/src/core/any.rs.html#200)
```
impl<T> Any for T
where
    T: 'static + ?Sized,
```

[source](https://doc.rust-lang.org/src/core/any.rs.html#201)
```
fn type_id(&self) -> TypeId
```
Gets the `TypeId` of `self`. [Read more](../../any/trait.any#tymethod.type_id)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#208)
```
impl<T> Borrow<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#210)
```
fn borrow(&self) -> &T
```
Immutably borrows from an owned value. [Read more](../../borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#216)
```
impl<T> BorrowMut<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#217)
```
fn borrow_mut(&mut self) -> &mut T
```
Mutably borrows from an owned value. [Read more](../../borrow/trait.borrowmut#tymethod.borrow_mut)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#723)
```
impl<T> From<T> for T
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#726)
```
fn from(t: T) -> T
```

Returns the argument unchanged.

 

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#707)
```
impl<T, U> Into<U> for T
where
    U: From<T>,
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#716)
```
fn into(self) -> U
```

Calls `U::from(self)`.

 That is, this conversion is whatever the implementation of `[From](../../convert/trait.from "trait std::convert::From")<T> for U` chooses to do.

 

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#82)
```
impl<T> ToOwned for T
where
    T: Clone,
```


```
type Owned = T
```
The resulting type after obtaining ownership.
[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#87)
```
fn to_owned(&self) -> T
```
Creates owned data from borrowed data, usually by cloning. [Read more](../../borrow/trait.toowned#tymethod.to_owned)

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#91)
```
fn clone_into(&self, target: &mut T)
```
Uses borrowed data to replace owned data, usually by cloning. [Read more](../../borrow/trait.toowned#method.clone_into)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#763)
```
impl<T, U> TryFrom<U> for T
where
    U: Into<T>,
```


```
type Error = Infallible
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#770)
```
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#748)
```
impl<T, U> TryInto<U> for T
where
    U: TryFrom<T>,
```


```
type Error = <U as TryFrom<T>>::Error
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#755)
```
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
```
Performs the conversion.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/collections/hash_map/struct.HashMap.html>

Struct std::fs::File
====================



```
pub struct File { /* private fields */ }
```

An object providing access to an open file on the filesystem.

 An instance of a `File` can be read and/or written depending on what options it was opened with. Files also implement [`Seek`](../io/trait.seek "trait std::io::Seek") to alter the logical cursor that the file contains internally.

 Files are automatically closed when they go out of scope. Errors detected on closing are ignored by the implementation of `Drop`. Use the method [`sync_all`](struct.file#method.sync_all "method std::fs::File::sync_all") if these errors must be manually handled.

 Examples
--------

 Creates a new file and write bytes to it (you can also use [`write()`](fn.write "fn std::fs::write")):

 
```
use std::fs::File;
use std::io::prelude::*;

fn main() -> std::io::Result<()> {
    let mut file = File::create("foo.txt")?;
    file.write_all(b"Hello, world!")?;
    Ok(())
}
```
 Read the contents of a file into a [`String`](../string/struct.string "struct std::string::String") (you can also use [`read`](fn.read "fn std::fs::read")):

 
```
use std::fs::File;
use std::io::prelude::*;

fn main() -> std::io::Result<()> {
    let mut file = File::open("foo.txt")?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    assert_eq!(contents, "Hello, world!");
    Ok(())
}
```
 It can be more efficient to read the contents of a file with a buffered [`Read`](../io/trait.read "trait std::io::Read")er. This can be accomplished with [`BufReader<R>`](../io/struct.bufreader "struct std::io::BufReader"):

 
```
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;

fn main() -> std::io::Result<()> {
    let file = File::open("foo.txt")?;
    let mut buf_reader = BufReader::new(file);
    let mut contents = String::new();
    buf_reader.read_to_string(&mut contents)?;
    assert_eq!(contents, "Hello, world!");
    Ok(())
}
```
 Note that, although read and write methods require a `&mut File`, because of the interfaces for [`Read`](../io/trait.read "trait std::io::Read") and [`Write`](../io/trait.write "trait std::io::Write"), the holder of a `&File` can still modify the file, either through methods that take `&File` or by retrieving the underlying OS object and modifying the file that way. Additionally, many operating systems allow concurrent modification of files by different processes. Avoid assuming that holding a `&File` means that the file will not change.

 Platform-specific behavior
--------------------------

 On Windows, the implementation of [`Read`](../io/trait.read "trait std::io::Read") and [`Write`](../io/trait.write "trait std::io::Write") traits for `File` perform synchronous I/O operations. Therefore the underlying file must not have been opened for asynchronous I/O (e.g. by using `FILE_FLAG_OVERLAPPED`).

 Implementations
---------------



[source](https://doc.rust-lang.org/src/std/fs.rs.html#333-704)
```
impl File
```

[source](https://doc.rust-lang.org/src/std/fs.rs.html#361-363)
```
pub fn open<P: AsRef<Path>>(path: P) -> Result<File>
```

Attempts to open a file in read-only mode.

 See the [`OpenOptions::open`](struct.openoptions#method.open "method std::fs::OpenOptions::open") method for more details.

 If you only need to read the entire file contents, consider [`std::fs::read()`](fn.read "fn std::fs::read") or [`std::fs::read_to_string()`](fn.read_to_string "fn std::fs::read_to_string") instead.

 ##### Errors

 This function will return an error if `path` does not already exist. Other errors may also be returned according to [`OpenOptions::open`](struct.openoptions#method.open "method std::fs::OpenOptions::open").

 ##### Examples

 
```
use std::fs::File;
use std::io::Read;

fn main() -> std::io::Result<()> {
    let mut f = File::open("foo.txt")?;
    let mut data = vec![];
    f.read_to_end(&mut data)?;
    Ok(())
}
```
 
[source](https://doc.rust-lang.org/src/std/fs.rs.html#390-392)
```
pub fn create<P: AsRef<Path>>(path: P) -> Result<File>
```

Opens a file in write-only mode.

 This function will create a file if it does not exist, and will truncate it if it does.

 Depending on the platform, this function may fail if the full directory path does not exist. See the [`OpenOptions::open`](struct.openoptions#method.open "method std::fs::OpenOptions::open") function for more details.

 See also [`std::fs::write()`](fn.write "fn std::fs::write") for a simple function to create a file with a given data.

 ##### Examples

 
```
use std::fs::File;
use std::io::Write;

fn main() -> std::io::Result<()> {
    let mut f = File::create("foo.txt")?;
    f.write_all(&1234_u32.to_be_bytes())?;
    Ok(())
}
```
 
[source](https://doc.rust-lang.org/src/std/fs.rs.html#421-423)
```
pub fn create_new<P: AsRef<Path>>(path: P) -> Result<File>
```

🔬This is a nightly-only experimental API. (`file_create_new` [#105135](https://github.com/rust-lang/rust/issues/105135))

Creates a new file in read-write mode; error if the file exists.

 This function will create a file if it does not exist, or return an error if it does. This way, if the call succeeds, the file returned is guaranteed to be new.

 This option is useful because it is atomic. Otherwise between checking whether a file exists and creating a new one, the file may have been created by another process (a TOCTOU race condition / attack).

 This can also be written using `File::options().read(true).write(true).create_new(true).open(...)`.

 ##### Examples

 
```
#![feature(file_create_new)]

use std::fs::File;
use std::io::Write;

fn main() -> std::io::Result<()> {
    let mut f = File::create_new("foo.txt")?;
    f.write_all("Hello, world!".as_bytes())?;
    Ok(())
}
```
 
[source](https://doc.rust-lang.org/src/std/fs.rs.html#453-455)1.58.0
```
pub fn options() -> OpenOptions
```

Returns a new OpenOptions object.

 This function returns a new OpenOptions object that you can use to open or create a file with specific options if `open()` or `create()` are not appropriate.

 It is equivalent to `OpenOptions::new()`, but allows you to write more readable code. Instead of `OpenOptions::new().append(true).open("example.log")`, you can write `File::options().append(true).open("example.log")`. This also avoids the need to import `OpenOptions`.

 See the [`OpenOptions::new`](struct.openoptions#method.new "associated function std::fs::OpenOptions::new") function for more details.

 ##### Examples

 
```
use std::fs::File;
use std::io::Write;

fn main() -> std::io::Result<()> {
    let mut f = File::options().append(true).open("example.log")?;
    writeln!(&mut f, "new line")?;
    Ok(())
}
```
 
[source](https://doc.rust-lang.org/src/std/fs.rs.html#481-483)
```
pub fn sync_all(&self) -> Result<()>
```

Attempts to sync all OS-internal metadata to disk.

 This function will attempt to ensure that all in-memory data reaches the filesystem before returning.

 This can be used to handle errors that would otherwise only be caught when the `File` is closed. Dropping a file will ignore errors in synchronizing this in-memory data.

 ##### Examples

 
```
use std::fs::File;
use std::io::prelude::*;

fn main() -> std::io::Result<()> {
    let mut f = File::create("foo.txt")?;
    f.write_all(b"Hello, world!")?;

    f.sync_all()?;
    Ok(())
}
```
 
[source](https://doc.rust-lang.org/src/std/fs.rs.html#512-514)
```
pub fn sync_data(&self) -> Result<()>
```

This function is similar to [`sync_all`](struct.file#method.sync_all "method std::fs::File::sync_all"), except that it might not synchronize file metadata to the filesystem.

 This is intended for use cases that must synchronize content, but don’t need the metadata on disk. The goal of this method is to reduce disk operations.

 Note that some platforms may simply implement this in terms of [`sync_all`](struct.file#method.sync_all "method std::fs::File::sync_all").

 ##### Examples

 
```
use std::fs::File;
use std::io::prelude::*;

fn main() -> std::io::Result<()> {
    let mut f = File::create("foo.txt")?;
    f.write_all(b"Hello, world!")?;

    f.sync_data()?;
    Ok(())
}
```
 
[source](https://doc.rust-lang.org/src/std/fs.rs.html#550-552)
```
pub fn set_len(&self, size: u64) -> Result<()>
```

Truncates or extends the underlying file, updating the size of this file to become `size`.

 If the `size` is less than the current file’s size, then the file will be shrunk. If it is greater than the current file’s size, then the file will be extended to `size` and have all of the intermediate data filled in with 0s.

 The file’s cursor isn’t changed. In particular, if the cursor was at the end and the file is shrunk using this operation, the cursor will now be past the end.

 ##### Errors

 This function will return an error if the file is not opened for writing. Also, [`std::io::ErrorKind::InvalidInput`](../io/enum.errorkind#variant.InvalidInput "variant std::io::ErrorKind::InvalidInput") will be returned if the desired length would cause an overflow due to the implementation specifics.

 ##### Examples

 
```
use std::fs::File;

fn main() -> std::io::Result<()> {
    let mut f = File::create("foo.txt")?;
    f.set_len(10)?;
    Ok(())
}
```
 Note that this method alters the content of the underlying file, even though it takes `&self` rather than `&mut self`.

 
[source](https://doc.rust-lang.org/src/std/fs.rs.html#568-570)
```
pub fn metadata(&self) -> Result<Metadata>
```

Queries metadata about the underlying file.

 ##### Examples

 
```
use std::fs::File;

fn main() -> std::io::Result<()> {
    let mut f = File::open("foo.txt")?;
    let metadata = f.metadata()?;
    Ok(())
}
```
 
[source](https://doc.rust-lang.org/src/std/fs.rs.html#612-614)1.9.0
```
pub fn try_clone(&self) -> Result<File>
```

Creates a new `File` instance that shares the same underlying file handle as the existing `File` instance. Reads, writes, and seeks will affect both `File` instances simultaneously.

 ##### Examples

 Creates two handles for a file named `foo.txt`:

 
```
use std::fs::File;

fn main() -> std::io::Result<()> {
    let mut file = File::open("foo.txt")?;
    let file_copy = file.try_clone()?;
    Ok(())
}
```
 Assuming there’s a file named `foo.txt` with contents `abcdef\n`, create two handles, seek one of them, and read the remaining bytes from the other handle:

 
```
use std::fs::File;
use std::io::SeekFrom;
use std::io::prelude::*;

fn main() -> std::io::Result<()> {
    let mut file = File::open("foo.txt")?;
    let mut file_copy = file.try_clone()?;

    file.seek(SeekFrom::Start(3))?;

    let mut contents = vec![];
    file_copy.read_to_end(&mut contents)?;
    assert_eq!(contents, b"def\n");
    Ok(())
}
```
 
[source](https://doc.rust-lang.org/src/std/fs.rs.html#649-651)1.16.0
```
pub fn set_permissions(&self, perm: Permissions) -> Result<()>
```

Changes the permissions on the underlying file.

 ##### Platform-specific behavior

 This function currently corresponds to the `fchmod` function on Unix and the `SetFileInformationByHandle` function on Windows. Note that, this [may change in the future](../io/index#platform-specific-behavior "mod std::io").

 ##### Errors

 This function will return an error if the user lacks permission change attributes on the underlying file. It may also return an error in other os-specific unspecified cases.

 ##### Examples

 
```
fn main() -> std::io::Result<()> {
    use std::fs::File;

    let file = File::open("foo.txt")?;
    let mut perms = file.metadata()?.permissions();
    perms.set_readonly(true);
    file.set_permissions(perms)?;
    Ok(())
}
```
 Note that this method alters the permissions of the underlying file, even though it takes `&self` rather than `&mut self`.

 
[source](https://doc.rust-lang.org/src/std/fs.rs.html#692-694)
```
pub fn set_times(&self, times: FileTimes) -> Result<()>
```

🔬This is a nightly-only experimental API. (`file_set_times` [#98245](https://github.com/rust-lang/rust/issues/98245))

Changes the timestamps of the underlying file.

 ##### Platform-specific behavior

 This function currently corresponds to the `futimens` function on Unix (falling back to `futimes` on macOS before 10.13) and the `SetFileTime` function on Windows. Note that this [may change in the future](../io/index#platform-specific-behavior "mod std::io").

 ##### Errors

 This function will return an error if the user lacks permission to change timestamps on the underlying file. It may also return an error in other os-specific unspecified cases.

 This function may return an error if the operating system lacks support to change one or more of the timestamps set in the `FileTimes` structure.

 ##### Examples

 
```
#![feature(file_set_times)]

fn main() -> std::io::Result<()> {
    use std::fs::{self, File, FileTimes};

    let src = fs::metadata("src")?;
    let dest = File::options().write(true).open("dest")?;
    let times = FileTimes::new()
        .set_accessed(src.accessed()?)
        .set_modified(src.modified()?);
    dest.set_times(times)?;
    Ok(())
}
```
 
[source](https://doc.rust-lang.org/src/std/fs.rs.html#701-703)
```
pub fn set_modified(&self, time: SystemTime) -> Result<()>
```

🔬This is a nightly-only experimental API. (`file_set_times` [#98245](https://github.com/rust-lang/rust/issues/98245))

Changes the modification time of the underlying file.

 This is an alias for `set_times(FileTimes::new().set_modified(time))`.

 


Trait Implementations
---------------------



[source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#278-283)1.63.0
```
impl AsFd for File
```

[source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#280-282)
```
fn as_fd(&self) -> BorrowedFd<'_>
```
Borrows the file descriptor. [Read more](../os/fd/trait.asfd#tymethod.as_fd)


[source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#496-501)1.63.0
```
impl AsHandle for FileAvailable on Windows only.
```

[source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#498-500)
```
fn as_handle(&self) -> BorrowedHandle<'_>
```
Borrows the handle. [Read more](../os/windows/io/trait.ashandle#tymethod.as_handle)


[source](https://doc.rust-lang.org/src/std/os/fd/raw.rs.html#165-170)
```
impl AsRawFd for File
```

[source](https://doc.rust-lang.org/src/std/os/fd/raw.rs.html#167-169)
```
fn as_raw_fd(&self) -> RawFd
```
Extracts the raw file descriptor. [Read more](../os/fd/trait.asrawfd#tymethod.as_raw_fd)


[source](https://doc.rust-lang.org/src/std/os/windows/io/raw.rs.html#96-101)
```
impl AsRawHandle for FileAvailable on Windows only.
```

[source](https://doc.rust-lang.org/src/std/os/windows/io/raw.rs.html#98-100)
```
fn as_raw_handle(&self) -> RawHandle
```
Extracts the raw handle. [Read more](../os/windows/io/trait.asrawhandle#tymethod.as_raw_handle)


[source](https://doc.rust-lang.org/src/std/fs.rs.html#730-734)
```
impl Debug for File
```

[source](https://doc.rust-lang.org/src/std/fs.rs.html#731-733)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result
```
Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt)


[source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#241-254)1.15.0
```
impl FileExt for FileAvailable on Unix only.
```

[source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#242-244)
```
fn read_at(&self, buf: &mut [u8], offset: u64) -> Result<usize>
```
Reads a number of bytes starting from a given offset. [Read more](../os/unix/fs/trait.fileext#tymethod.read_at)

[source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#245-247)
```
fn read_vectored_at(
    &self,
    bufs: &mut [IoSliceMut<'_>],
    offset: u64
) -> Result<usize>
```

🔬This is a nightly-only experimental API. (`unix_file_vectored_at` [#89517](https://github.com/rust-lang/rust/issues/89517))
Like `read_at`, except that it reads into a slice of buffers. [Read more](../os/unix/fs/trait.fileext#method.read_vectored_at)

[source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#248-250)
```
fn write_at(&self, buf: &[u8], offset: u64) -> Result<usize>
```
Writes a number of bytes starting from a given offset. [Read more](../os/unix/fs/trait.fileext#tymethod.write_at)

[source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#251-253)
```
fn write_vectored_at(&self, bufs: &[IoSlice<'_>], offset: u64) -> Result<usize>
```

🔬This is a nightly-only experimental API. (`unix_file_vectored_at` [#89517](https://github.com/rust-lang/rust/issues/89517))
Like `write_at`, except that it writes from a slice of buffers. [Read more](../os/unix/fs/trait.fileext#method.write_vectored_at)

[source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#117-135)1.33.0
```
fn read_exact_at(&self, buf: &mut [u8], offset: u64) -> Result<()>
```
Reads the exact number of byte required to fill `buf` from the given offset. [Read more](../os/unix/fs/trait.fileext#method.read_exact_at)

[source](https://doc.rust-lang.org/src/std/os/unix/fs.rs.html#219-237)1.33.0
```
fn write_all_at(&self, buf: &[u8], offset: u64) -> Result<()>
```
Attempts to write an entire buffer starting from a given offset. [Read more](../os/unix/fs/trait.fileext#method.write_all_at)


[source](https://doc.rust-lang.org/src/std/os/windows/fs.rs.html#88-96)1.15.0
```
impl FileExt for FileAvailable on Windows only.
```

[source](https://doc.rust-lang.org/src/std/os/windows/fs.rs.html#89-91)
```
fn seek_read(&self, buf: &mut [u8], offset: u64) -> Result<usize>
```
Seeks to a given position and reads a number of bytes. [Read more](../os/windows/fs/trait.fileext#tymethod.seek_read)

[source](https://doc.rust-lang.org/src/std/os/windows/fs.rs.html#93-95)
```
fn seek_write(&self, buf: &[u8], offset: u64) -> Result<usize>
```
Seeks to a given position and writes a number of bytes. [Read more](../os/windows/fs/trait.fileext#tymethod.seek_write)


[source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#231-295)
```
impl FileExt for FileAvailable on WASI only.
```

[source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#232-234)
```
fn read_vectored_at(
    &self,
    bufs: &mut [IoSliceMut<'_>],
    offset: u64
) -> Result<usize>
```

🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213))
Reads a number of bytes starting from a given offset. [Read more](../os/wasi/fs/trait.fileext#tymethod.read_vectored_at)

[source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#236-238)
```
fn write_vectored_at(&self, bufs: &[IoSlice<'_>], offset: u64) -> Result<usize>
```

🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213))
Writes a number of bytes starting from a given offset. [Read more](../os/wasi/fs/trait.fileext#tymethod.write_vectored_at)

[source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#240-242)
```
fn tell(&self) -> Result<u64>
```

🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213))
Returns the current position within the file. [Read more](../os/wasi/fs/trait.fileext#tymethod.tell)

[source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#244-246)
```
fn fdstat_set_flags(&self, flags: u16) -> Result<()>
```

🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213))
Adjust the flags associated with this file. [Read more](../os/wasi/fs/trait.fileext#tymethod.fdstat_set_flags)

[source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#248-250)
```
fn fdstat_set_rights(&self, rights: u64, inheriting: u64) -> Result<()>
```

🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213))
Adjust the rights associated with this file. [Read more](../os/wasi/fs/trait.fileext#tymethod.fdstat_set_rights)

[source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#252-269)
```
fn advise(&self, offset: u64, len: u64, advice: u8) -> Result<()>
```

🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213))
Provide file advisory information on a file descriptor. [Read more](../os/wasi/fs/trait.fileext#tymethod.advise)

[source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#271-273)
```
fn allocate(&self, offset: u64, len: u64) -> Result<()>
```

🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213))
Force the allocation of space in a file. [Read more](../os/wasi/fs/trait.fileext#tymethod.allocate)

[source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#275-277)
```
fn create_directory<P: AsRef<Path>>(&self, dir: P) -> Result<()>
```

🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213))
Create a directory. [Read more](../os/wasi/fs/trait.fileext#tymethod.create_directory)

[source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#279-281)
```
fn read_link<P: AsRef<Path>>(&self, path: P) -> Result<PathBuf>
```

🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213))
Read the contents of a symbolic link. [Read more](../os/wasi/fs/trait.fileext#tymethod.read_link)

[source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#283-286)
```
fn metadata_at<P: AsRef<Path>>(
    &self,
    lookup_flags: u32,
    path: P
) -> Result<Metadata>
```

🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213))
Return the attributes of a file or directory. [Read more](../os/wasi/fs/trait.fileext#tymethod.metadata_at)

[source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#288-290)
```
fn remove_file<P: AsRef<Path>>(&self, path: P) -> Result<()>
```

🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213))
Unlink a file. [Read more](../os/wasi/fs/trait.fileext#tymethod.remove_file)

[source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#292-294)
```
fn remove_directory<P: AsRef<Path>>(&self, path: P) -> Result<()>
```

🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213))
Remove a directory. [Read more](../os/wasi/fs/trait.fileext#tymethod.remove_directory)

[source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#30-33)
```
fn read_at(&self, buf: &mut [u8], offset: u64) -> Result<usize>
```

🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213))
Reads a number of bytes starting from a given offset. [Read more](../os/wasi/fs/trait.fileext#method.read_at)

[source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#76-94)1.33.0
```
fn read_exact_at(&self, buf: &mut [u8], offset: u64) -> Result<()>
```
Reads the exact number of byte required to fill `buf` from the given offset. [Read more](../os/wasi/fs/trait.fileext#method.read_exact_at)

[source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#110-113)
```
fn write_at(&self, buf: &[u8], offset: u64) -> Result<usize>
```

🔬This is a nightly-only experimental API. (`wasi_ext` [#71213](https://github.com/rust-lang/rust/issues/71213))
Writes a number of bytes starting from a given offset. [Read more](../os/wasi/fs/trait.fileext#method.write_at)

[source](https://doc.rust-lang.org/src/std/os/wasi/fs.rs.html#152-170)1.33.0
```
fn write_all_at(&self, buf: &[u8], offset: u64) -> Result<()>
```
Attempts to write an entire buffer starting from a given offset. [Read more](../os/wasi/fs/trait.fileext#method.write_all_at)


[source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#286-291)1.63.0
```
impl From<File> for OwnedFd
```

[source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#288-290)
```
fn from(file: File) -> OwnedFd
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#504-509)1.63.0
```
impl From<File> for OwnedHandleAvailable on Windows only.
```

[source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#506-508)
```
fn from(file: File) -> OwnedHandle
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/std/process.rs.html#1468-1492)1.20.0
```
impl From<File> for Stdio
```

[source](https://doc.rust-lang.org/src/std/process.rs.html#1489-1491)
```
fn from(file: File) -> Stdio
```

Converts a [`File`](struct.file "struct std::fs::File") into a [`Stdio`](../process/struct.stdio "struct std::process::Stdio").

 ##### Examples

 `File` will be converted to `Stdio` using `Stdio::from` under the hood.

 
```
use std::fs::File;
use std::process::Command;

// With the `foo.txt` file containing "Hello, world!"
let file = File::open("foo.txt").unwrap();

let reverse = Command::new("rev")
    .stdin(file)  // Implicit File conversion into a Stdio
    .output()
    .expect("failed reverse command");

assert_eq!(reverse.stdout, b"!dlrow ,olleH");
```
 

[source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#294-299)1.63.0
```
impl From<OwnedFd> for File
```

[source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#296-298)
```
fn from(owned_fd: OwnedFd) -> Self
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#512-517)1.63.0
```
impl From<OwnedHandle> for FileAvailable on Windows only.
```

[source](https://doc.rust-lang.org/src/std/os/windows/io/handle.rs.html#514-516)
```
fn from(owned: OwnedHandle) -> Self
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/std/os/fd/raw.rs.html#172-177)1.1.0
```
impl FromRawFd for File
```

[source](https://doc.rust-lang.org/src/std/os/fd/raw.rs.html#174-176)
```
unsafe fn from_raw_fd(fd: RawFd) -> File ⓘ
```
Constructs a new instance of `Self` from the given raw file descriptor. [Read more](../os/fd/trait.fromrawfd#tymethod.from_raw_fd)


[source](https://doc.rust-lang.org/src/std/os/windows/io/raw.rs.html#158-166)1.1.0
```
impl FromRawHandle for FileAvailable on Windows only.
```

[source](https://doc.rust-lang.org/src/std/os/windows/io/raw.rs.html#160-165)
```
unsafe fn from_raw_handle(handle: RawHandle) -> File ⓘ
```
Constructs a new I/O object from the specified raw handle. [Read more](../os/windows/io/trait.fromrawhandle#tymethod.from_raw_handle)


[source](https://doc.rust-lang.org/src/std/os/fd/raw.rs.html#179-184)1.4.0
```
impl IntoRawFd for File
```

[source](https://doc.rust-lang.org/src/std/os/fd/raw.rs.html#181-183)
```
fn into_raw_fd(self) -> RawFd
```
Consumes this object, returning the raw underlying file descriptor. [Read more](../os/fd/trait.intorawfd#tymethod.into_raw_fd)


[source](https://doc.rust-lang.org/src/std/os/windows/io/raw.rs.html#169-174)1.4.0
```
impl IntoRawHandle for FileAvailable on Windows only.
```

[source](https://doc.rust-lang.org/src/std/os/windows/io/raw.rs.html#171-173)
```
fn into_raw_handle(self) -> RawHandle
```
Consumes this object, returning the raw underlying handle. [Read more](../os/windows/io/trait.intorawhandle#tymethod.into_raw_handle)


[source](https://doc.rust-lang.org/src/std/io/stdio.rs.html#1085)1.70.0
```
impl IsTerminal for File
```

[source](https://doc.rust-lang.org/src/std/io/stdio.rs.html#1085)
```
fn is_terminal(&self) -> bool
```
Returns `true` if the descriptor/handle refers to a terminal/tty. [Read more](../io/trait.isterminal#tymethod.is_terminal)


[source](https://doc.rust-lang.org/src/std/fs.rs.html#804-835)
```
impl Read for &File
```

[source](https://doc.rust-lang.org/src/std/fs.rs.html#805-807)
```
fn read(&mut self, buf: &mut [u8]) -> Result<usize>
```
Pull some bytes from this source into the specified buffer, returning how many bytes were read. [Read more](../io/trait.read#tymethod.read)

[source](https://doc.rust-lang.org/src/std/fs.rs.html#809-811)
```
fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> Result<()>
```

🔬This is a nightly-only experimental API. (`read_buf` [#78485](https://github.com/rust-lang/rust/issues/78485))
Pull some bytes from this source into the specified buffer. [Read more](../io/trait.read#method.read_buf)

[source](https://doc.rust-lang.org/src/std/fs.rs.html#813-815)
```
fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
```
Like `read`, except that it reads into a slice of buffers. [Read more](../io/trait.read#method.read_vectored)

[source](https://doc.rust-lang.org/src/std/fs.rs.html#818-820)
```
fn is_read_vectored(&self) -> bool
```

🔬This is a nightly-only experimental API. (`can_vector` [#69941](https://github.com/rust-lang/rust/issues/69941))
Determines if this `Read`er has an efficient `read_vectored` implementation. [Read more](../io/trait.read#method.is_read_vectored)

[source](https://doc.rust-lang.org/src/std/fs.rs.html#823-827)
```
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize>
```
Read all bytes until EOF in this source, placing them into `buf`. [Read more](../io/trait.read#method.read_to_end)

[source](https://doc.rust-lang.org/src/std/fs.rs.html#830-834)
```
fn read_to_string(&mut self, buf: &mut String) -> Result<usize>
```
Read all bytes until EOF in this source, appending them to `buf`. [Read more](../io/trait.read#method.read_to_string)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#824-826)1.6.0
```
fn read_exact(&mut self, buf: &mut [u8]) -> Result<()>
```
Read the exact number of bytes required to fill `buf`. [Read more](../io/trait.read#method.read_exact)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#858-873)
```
fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<()>
```

🔬This is a nightly-only experimental API. (`read_buf` [#78485](https://github.com/rust-lang/rust/issues/78485))
Read the exact number of bytes required to fill `cursor`. [Read more](../io/trait.read#method.read_buf_exact)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#910-915)
```
fn by_ref(&mut self) -> &mut Self
where
    Self: Sized,
```
Creates a “by reference” adaptor for this instance of `Read`. [Read more](../io/trait.read#method.by_ref)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#953-958)
```
fn bytes(self) -> Bytes<Self> ⓘ
where
    Self: Sized,
```
Transforms this `Read` instance to an [`Iterator`](../iter/trait.iterator "trait std::iter::Iterator") over its bytes. [Read more](../io/trait.read#method.bytes)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#991-996)
```
fn chain<R: Read>(self, next: R) -> Chain<Self, R> ⓘ
where
    Self: Sized,
```
Creates an adapter which will chain this stream with another. [Read more](../io/trait.read#method.chain)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1030-1035)
```
fn take(self, limit: u64) -> Take<Self> ⓘ
where
    Self: Sized,
```
Creates an adapter which will read at most `limit` bytes from it. [Read more](../io/trait.read#method.take)


[source](https://doc.rust-lang.org/src/std/fs.rs.html#746-777)
```
impl Read for File
```

[source](https://doc.rust-lang.org/src/std/fs.rs.html#747-749)
```
fn read(&mut self, buf: &mut [u8]) -> Result<usize>
```
Pull some bytes from this source into the specified buffer, returning how many bytes were read. [Read more](../io/trait.read#tymethod.read)

[source](https://doc.rust-lang.org/src/std/fs.rs.html#751-753)
```
fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
```
Like `read`, except that it reads into a slice of buffers. [Read more](../io/trait.read#method.read_vectored)

[source](https://doc.rust-lang.org/src/std/fs.rs.html#755-757)
```
fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> Result<()>
```

🔬This is a nightly-only experimental API. (`read_buf` [#78485](https://github.com/rust-lang/rust/issues/78485))
Pull some bytes from this source into the specified buffer. [Read more](../io/trait.read#method.read_buf)

[source](https://doc.rust-lang.org/src/std/fs.rs.html#760-762)
```
fn is_read_vectored(&self) -> bool
```

🔬This is a nightly-only experimental API. (`can_vector` [#69941](https://github.com/rust-lang/rust/issues/69941))
Determines if this `Read`er has an efficient `read_vectored` implementation. [Read more](../io/trait.read#method.is_read_vectored)

[source](https://doc.rust-lang.org/src/std/fs.rs.html#765-769)
```
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize>
```
Read all bytes until EOF in this source, placing them into `buf`. [Read more](../io/trait.read#method.read_to_end)

[source](https://doc.rust-lang.org/src/std/fs.rs.html#772-776)
```
fn read_to_string(&mut self, buf: &mut String) -> Result<usize>
```
Read all bytes until EOF in this source, appending them to `buf`. [Read more](../io/trait.read#method.read_to_string)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#824-826)1.6.0
```
fn read_exact(&mut self, buf: &mut [u8]) -> Result<()>
```
Read the exact number of bytes required to fill `buf`. [Read more](../io/trait.read#method.read_exact)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#858-873)
```
fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<()>
```

🔬This is a nightly-only experimental API. (`read_buf` [#78485](https://github.com/rust-lang/rust/issues/78485))
Read the exact number of bytes required to fill `cursor`. [Read more](../io/trait.read#method.read_buf_exact)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#910-915)
```
fn by_ref(&mut self) -> &mut Self
where
    Self: Sized,
```
Creates a “by reference” adaptor for this instance of `Read`. [Read more](../io/trait.read#method.by_ref)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#953-958)
```
fn bytes(self) -> Bytes<Self> ⓘ
where
    Self: Sized,
```
Transforms this `Read` instance to an [`Iterator`](../iter/trait.iterator "trait std::iter::Iterator") over its bytes. [Read more](../io/trait.read#method.bytes)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#991-996)
```
fn chain<R: Read>(self, next: R) -> Chain<Self, R> ⓘ
where
    Self: Sized,
```
Creates an adapter which will chain this stream with another. [Read more](../io/trait.read#method.chain)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1030-1035)
```
fn take(self, limit: u64) -> Take<Self> ⓘ
where
    Self: Sized,
```
Creates an adapter which will read at most `limit` bytes from it. [Read more](../io/trait.read#method.take)


[source](https://doc.rust-lang.org/src/std/fs.rs.html#856-860)
```
impl Seek for &File
```

[source](https://doc.rust-lang.org/src/std/fs.rs.html#857-859)
```
fn seek(&mut self, pos: SeekFrom) -> Result<u64>
```
Seek to an offset, in bytes, in a stream. [Read more](../io/trait.seek#tymethod.seek)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1830-1833)1.55.0
```
fn rewind(&mut self) -> Result<()>
```
Rewind to the beginning of a stream. [Read more](../io/trait.seek#method.rewind)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1870-1881)
```
fn stream_len(&mut self) -> Result<u64>
```

🔬This is a nightly-only experimental API. (`seek_stream_len` [#59359](https://github.com/rust-lang/rust/issues/59359))
Returns the length of this stream (in bytes). [Read more](../io/trait.seek#method.stream_len)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1907-1909)1.51.0
```
fn stream_position(&mut self) -> Result<u64>
```
Returns the current seek position from the start of the stream. [Read more](../io/trait.seek#method.stream_position)


[source](https://doc.rust-lang.org/src/std/fs.rs.html#798-802)
```
impl Seek for File
```

[source](https://doc.rust-lang.org/src/std/fs.rs.html#799-801)
```
fn seek(&mut self, pos: SeekFrom) -> Result<u64>
```
Seek to an offset, in bytes, in a stream. [Read more](../io/trait.seek#tymethod.seek)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1830-1833)1.55.0
```
fn rewind(&mut self) -> Result<()>
```
Rewind to the beginning of a stream. [Read more](../io/trait.seek#method.rewind)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1870-1881)
```
fn stream_len(&mut self) -> Result<u64>
```

🔬This is a nightly-only experimental API. (`seek_stream_len` [#59359](https://github.com/rust-lang/rust/issues/59359))
Returns the length of this stream (in bytes). [Read more](../io/trait.seek#method.stream_len)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1907-1909)1.51.0
```
fn stream_position(&mut self) -> Result<u64>
```
Returns the current seek position from the start of the stream. [Read more](../io/trait.seek#method.stream_position)


[source](https://doc.rust-lang.org/src/std/fs.rs.html#837-854)
```
impl Write for &File
```

[source](https://doc.rust-lang.org/src/std/fs.rs.html#838-840)
```
fn write(&mut self, buf: &[u8]) -> Result<usize>
```
Write a buffer into this writer, returning how many bytes were written. [Read more](../io/trait.write#tymethod.write)

[source](https://doc.rust-lang.org/src/std/fs.rs.html#842-844)
```
fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize>
```
Like [`write`](../io/trait.write#tymethod.write "method std::io::Write::write"), except that it writes from a slice of buffers. [Read more](../io/trait.write#method.write_vectored)

[source](https://doc.rust-lang.org/src/std/fs.rs.html#847-849)
```
fn is_write_vectored(&self) -> bool
```

🔬This is a nightly-only experimental API. (`can_vector` [#69941](https://github.com/rust-lang/rust/issues/69941))
Determines if this `Write`r has an efficient [`write_vectored`](../io/trait.write#method.write_vectored "method std::io::Write::write_vectored") implementation. [Read more](../io/trait.write#method.is_write_vectored)

[source](https://doc.rust-lang.org/src/std/fs.rs.html#851-853)
```
fn flush(&mut self) -> Result<()>
```
Flush this output stream, ensuring that all intermediately buffered contents reach their destination. [Read more](../io/trait.write#tymethod.flush)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1571-1586)
```
fn write_all(&mut self, buf: &[u8]) -> Result<()>
```
Attempts to write an entire buffer into this writer. [Read more](../io/trait.write#method.write_all)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1636-1654)
```
fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<()>
```

🔬This is a nightly-only experimental API. (`write_all_vectored` [#70436](https://github.com/rust-lang/rust/issues/70436))
Attempts to write multiple buffers into this writer. [Read more](../io/trait.write#method.write_all_vectored)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1692-1724)
```
fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result<()>
```
Writes a formatted string into this writer, returning any error encountered. [Read more](../io/trait.write#method.write_fmt)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1748-1753)
```
fn by_ref(&mut self) -> &mut Self
where
    Self: Sized,
```
Creates a “by reference” adapter for this instance of `Write`. [Read more](../io/trait.write#method.by_ref)


[source](https://doc.rust-lang.org/src/std/fs.rs.html#779-796)
```
impl Write for File
```

[source](https://doc.rust-lang.org/src/std/fs.rs.html#780-782)
```
fn write(&mut self, buf: &[u8]) -> Result<usize>
```
Write a buffer into this writer, returning how many bytes were written. [Read more](../io/trait.write#tymethod.write)

[source](https://doc.rust-lang.org/src/std/fs.rs.html#784-786)
```
fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize>
```
Like [`write`](../io/trait.write#tymethod.write "method std::io::Write::write"), except that it writes from a slice of buffers. [Read more](../io/trait.write#method.write_vectored)

[source](https://doc.rust-lang.org/src/std/fs.rs.html#789-791)
```
fn is_write_vectored(&self) -> bool
```

🔬This is a nightly-only experimental API. (`can_vector` [#69941](https://github.com/rust-lang/rust/issues/69941))
Determines if this `Write`r has an efficient [`write_vectored`](../io/trait.write#method.write_vectored "method std::io::Write::write_vectored") implementation. [Read more](../io/trait.write#method.is_write_vectored)

[source](https://doc.rust-lang.org/src/std/fs.rs.html#793-795)
```
fn flush(&mut self) -> Result<()>
```
Flush this output stream, ensuring that all intermediately buffered contents reach their destination. [Read more](../io/trait.write#tymethod.flush)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1571-1586)
```
fn write_all(&mut self, buf: &[u8]) -> Result<()>
```
Attempts to write an entire buffer into this writer. [Read more](../io/trait.write#method.write_all)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1636-1654)
```
fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<()>
```

🔬This is a nightly-only experimental API. (`write_all_vectored` [#70436](https://github.com/rust-lang/rust/issues/70436))
Attempts to write multiple buffers into this writer. [Read more](../io/trait.write#method.write_all_vectored)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1692-1724)
```
fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result<()>
```
Writes a formatted string into this writer, returning any error encountered. [Read more](../io/trait.write#method.write_fmt)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1748-1753)
```
fn by_ref(&mut self) -> &mut Self
where
    Self: Sized,
```
Creates a “by reference” adapter for this instance of `Write`. [Read more](../io/trait.write#method.by_ref)



Auto Trait Implementations
--------------------------




```
impl RefUnwindSafe for File
```

```
impl Send for File
```

```
impl Sync for File
```

```
impl Unpin for File
```

```
impl UnwindSafe for File
```


Blanket Implementations
-----------------------



[source](https://doc.rust-lang.org/src/core/any.rs.html#200)
```
impl<T> Any for T
where
    T: 'static + ?Sized,
```

[source](https://doc.rust-lang.org/src/core/any.rs.html#201)
```
fn type_id(&self) -> TypeId
```
Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#208)
```
impl<T> Borrow<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#210)
```
fn borrow(&self) -> &T
```
Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#216)
```
impl<T> BorrowMut<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#217)
```
fn borrow_mut(&mut self) -> &mut T
```
Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#723)
```
impl<T> From<T> for T
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#726)
```
fn from(t: T) -> T
```

Returns the argument unchanged.

 

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#707)
```
impl<T, U> Into<U> for T
where
    U: From<T>,
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#716)
```
fn into(self) -> U
```

Calls `U::from(self)`.

 That is, this conversion is whatever the implementation of `[From](../convert/trait.from "trait std::convert::From")<T> for U` chooses to do.

 

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#763)
```
impl<T, U> TryFrom<U> for T
where
    U: Into<T>,
```


```
type Error = Infallible
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#770)
```
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#748)
```
impl<T, U> TryInto<U> for T
where
    U: TryFrom<T>,
```


```
type Error = <U as TryFrom<T>>::Error
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#755)
```
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
```
Performs the conversion.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/fs/struct.File.html>

Struct std::net::TcpStream
==========================



```
pub struct TcpStream(_);
```

A TCP stream between a local and a remote socket.

 After creating a `TcpStream` by either [`connect`](struct.tcpstream#method.connect "associated function std::net::TcpStream::connect")ing to a remote host or [`accept`](struct.tcplistener#method.accept "method std::net::TcpListener::accept")ing a connection on a [`TcpListener`](struct.tcplistener "struct std::net::TcpListener"), data can be transmitted by [reading](../io/trait.read "trait std::io::Read") and [writing](../io/trait.write "trait std::io::Write") to it.

 The connection will be closed when the value is dropped. The reading and writing portions of the connection can also be shut down individually with the [`shutdown`](struct.tcpstream#method.shutdown "method std::net::TcpStream::shutdown") method.

 The Transmission Control Protocol is specified in [IETF RFC 793](https://tools.ietf.org/html/rfc793).

 Examples
--------

 
```
use std::io::prelude::*;
use std::net::TcpStream;

fn main() -> std::io::Result<()> {
    let mut stream = TcpStream::connect("127.0.0.1:34254")?;

    stream.write(&[1])?;
    stream.read(&mut [0; 128])?;
    Ok(())
} // the stream is closed here
```
 Implementations
---------------



[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#113-608)
```
impl TcpStream
```

[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#156-158)
```
pub fn connect<A: ToSocketAddrs>(addr: A) -> Result<TcpStream>
```

Opens a TCP connection to a remote host.

 `addr` is an address of the remote host. Anything which implements [`ToSocketAddrs`](trait.tosocketaddrs "trait std::net::ToSocketAddrs") trait can be supplied for the address; see this trait documentation for concrete examples.

 If `addr` yields multiple addresses, `connect` will be attempted with each of the addresses until a connection is successful. If none of the addresses result in a successful connection, the error returned from the last connection attempt (the last address) is returned.

 ##### Examples

 Open a TCP connection to `127.0.0.1:8080`:

 
```
use std::net::TcpStream;

if let Ok(stream) = TcpStream::connect("127.0.0.1:8080") {
    println!("Connected to the server!");
} else {
    println!("Couldn't connect to server...");
}
```
 Open a TCP connection to `127.0.0.1:8080`. If the connection fails, open a TCP connection to `127.0.0.1:8081`:

 
```
use std::net::{SocketAddr, TcpStream};

let addrs = [
    SocketAddr::from(([127, 0, 0, 1], 8080)),
    SocketAddr::from(([127, 0, 0, 1], 8081)),
];
if let Ok(stream) = TcpStream::connect(&addrs[..]) {
    println!("Connected to the server!");
} else {
    println!("Couldn't connect to server...");
}
```
 
[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#172-174)1.21.0
```
pub fn connect_timeout(
    addr: &SocketAddr,
    timeout: Duration
) -> Result<TcpStream>
```

Opens a TCP connection to a remote host with a timeout.

 Unlike `connect`, `connect_timeout` takes a single [`SocketAddr`](enum.socketaddr "enum std::net::SocketAddr") since timeout must be applied to individual addresses.

 It is an error to pass a zero `Duration` to this function.

 Unlike other methods on `TcpStream`, this does not correspond to a single system call. It instead calls `connect` in nonblocking mode and then uses an OS-specific mechanism to await the completion of the connection request.

 
[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#189-191)
```
pub fn peer_addr(&self) -> Result<SocketAddr>
```

Returns the socket address of the remote peer of this TCP connection.

 ##### Examples

 
```
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream};

let stream = TcpStream::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
assert_eq!(stream.peer_addr().unwrap(),
           SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
```
 
[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#206-208)
```
pub fn local_addr(&self) -> Result<SocketAddr>
```

Returns the socket address of the local half of this TCP connection.

 ##### Examples

 
```
use std::net::{IpAddr, Ipv4Addr, TcpStream};

let stream = TcpStream::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
assert_eq!(stream.local_addr().unwrap().ip(),
           IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
```
 
[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#233-235)
```
pub fn shutdown(&self, how: Shutdown) -> Result<()>
```

Shuts down the read, write, or both halves of this connection.

 This function will cause all pending and future I/O on the specified portions to return immediately with an appropriate value (see the documentation of [`Shutdown`](enum.shutdown "enum std::net::Shutdown")).

 ##### Platform-specific behavior

 Calling this function multiple times may result in different behavior, depending on the operating system. On Linux, the second call will return `Ok(())`, but on macOS, it will return `ErrorKind::NotConnected`. This may change in the future.

 ##### Examples

 
```
use std::net::{Shutdown, TcpStream};

let stream = TcpStream::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
stream.shutdown(Shutdown::Both).expect("shutdown call failed");
```
 
[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#254-256)
```
pub fn try_clone(&self) -> Result<TcpStream>
```

Creates a new independently owned handle to the underlying socket.

 The returned `TcpStream` is a reference to the same stream that this object references. Both handles will read and write the same stream of data, and options set on one stream will be propagated to the other stream.

 ##### Examples

 
```
use std::net::TcpStream;

let stream = TcpStream::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
let stream_clone = stream.try_clone().expect("clone failed...");
```
 
[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#298-300)1.4.0
```
pub fn set_read_timeout(&self, dur: Option<Duration>) -> Result<()>
```

Sets the read timeout to the timeout specified.

 If the value specified is [`None`](../option/enum.option#variant.None "variant std::option::Option::None"), then [`read`](../io/trait.read#tymethod.read "method std::io::Read::read") calls will block indefinitely. An [`Err`](../result/enum.result#variant.Err "variant std::result::Result::Err") is returned if the zero [`Duration`](../time/struct.duration "struct std::time::Duration") is passed to this method.

 ##### Platform-specific behavior

 Platforms may return a different error code whenever a read times out as a result of setting this option. For example Unix typically returns an error of the kind [`WouldBlock`](../io/enum.errorkind#variant.WouldBlock "variant std::io::ErrorKind::WouldBlock"), but Windows may return [`TimedOut`](../io/enum.errorkind#variant.TimedOut "variant std::io::ErrorKind::TimedOut").

 ##### Examples

 
```
use std::net::TcpStream;

let stream = TcpStream::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
stream.set_read_timeout(None).expect("set_read_timeout call failed");
```
 An [`Err`](../result/enum.result#variant.Err "variant std::result::Result::Err") is returned if the zero [`Duration`](../time/struct.duration "struct std::time::Duration") is passed to this method:

 
```
use std::io;
use std::net::TcpStream;
use std::time::Duration;

let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
let result = stream.set_read_timeout(Some(Duration::new(0, 0)));
let err = result.unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
```
 
[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#342-344)1.4.0
```
pub fn set_write_timeout(&self, dur: Option<Duration>) -> Result<()>
```

Sets the write timeout to the timeout specified.

 If the value specified is [`None`](../option/enum.option#variant.None "variant std::option::Option::None"), then [`write`](../io/trait.write#tymethod.write "method std::io::Write::write") calls will block indefinitely. An [`Err`](../result/enum.result#variant.Err "variant std::result::Result::Err") is returned if the zero [`Duration`](../time/struct.duration "struct std::time::Duration") is passed to this method.

 ##### Platform-specific behavior

 Platforms may return a different error code whenever a write times out as a result of setting this option. For example Unix typically returns an error of the kind [`WouldBlock`](../io/enum.errorkind#variant.WouldBlock "variant std::io::ErrorKind::WouldBlock"), but Windows may return [`TimedOut`](../io/enum.errorkind#variant.TimedOut "variant std::io::ErrorKind::TimedOut").

 ##### Examples

 
```
use std::net::TcpStream;

let stream = TcpStream::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
stream.set_write_timeout(None).expect("set_write_timeout call failed");
```
 An [`Err`](../result/enum.result#variant.Err "variant std::result::Result::Err") is returned if the zero [`Duration`](../time/struct.duration "struct std::time::Duration") is passed to this method:

 
```
use std::io;
use std::net::TcpStream;
use std::time::Duration;

let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
let result = stream.set_write_timeout(Some(Duration::new(0, 0)));
let err = result.unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
```
 
[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#367-369)1.4.0
```
pub fn read_timeout(&self) -> Result<Option<Duration>>
```

Returns the read timeout of this socket.

 If the timeout is [`None`](../option/enum.option#variant.None "variant std::option::Option::None"), then [`read`](../io/trait.read#tymethod.read "method std::io::Read::read") calls will block indefinitely.

 ##### Platform-specific behavior

 Some platforms do not provide access to the current timeout.

 ##### Examples

 
```
use std::net::TcpStream;

let stream = TcpStream::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
stream.set_read_timeout(None).expect("set_read_timeout call failed");
assert_eq!(stream.read_timeout().unwrap(), None);
```
 
[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#392-394)1.4.0
```
pub fn write_timeout(&self) -> Result<Option<Duration>>
```

Returns the write timeout of this socket.

 If the timeout is [`None`](../option/enum.option#variant.None "variant std::option::Option::None"), then [`write`](../io/trait.write#tymethod.write "method std::io::Write::write") calls will block indefinitely.

 ##### Platform-specific behavior

 Some platforms do not provide access to the current timeout.

 ##### Examples

 
```
use std::net::TcpStream;

let stream = TcpStream::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
stream.set_write_timeout(None).expect("set_write_timeout call failed");
assert_eq!(stream.write_timeout().unwrap(), None);
```
 
[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#414-416)1.18.0
```
pub fn peek(&self, buf: &mut [u8]) -> Result<usize>
```

Receives data on the socket from the remote address to which it is connected, without removing that data from the queue. On success, returns the number of bytes peeked.

 Successive calls return the same data. This is accomplished by passing `MSG_PEEK` as a flag to the underlying `recv` system call.

 ##### Examples

 
```
use std::net::TcpStream;

let stream = TcpStream::connect("127.0.0.1:8000")
                       .expect("Couldn't connect to the server...");
let mut buf = [0; 10];
let len = stream.peek(&mut buf).expect("peek failed");
```
 
[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#439-441)
```
pub fn set_linger(&self, linger: Option<Duration>) -> Result<()>
```

🔬This is a nightly-only experimental API. (`tcp_linger` [#88494](https://github.com/rust-lang/rust/issues/88494))

Sets the value of the `SO_LINGER` option on this socket.

 This value controls how the socket is closed when data remains to be sent. If `SO_LINGER` is set, the socket will remain open for the specified duration as the system attempts to send pending data. Otherwise, the system may close the socket immediately, or wait for a default timeout.

 ##### Examples

 
```
#![feature(tcp_linger)]

use std::net::TcpStream;
use std::time::Duration;

let stream = TcpStream::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
stream.set_linger(Some(Duration::from_secs(0))).expect("set_linger call failed");
```
 
[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#461-463)
```
pub fn linger(&self) -> Result<Option<Duration>>
```

🔬This is a nightly-only experimental API. (`tcp_linger` [#88494](https://github.com/rust-lang/rust/issues/88494))

Gets the value of the `SO_LINGER` option on this socket.

 For more information about this option, see [`TcpStream::set_linger`](struct.tcpstream#method.set_linger "method std::net::TcpStream::set_linger").

 ##### Examples

 
```
#![feature(tcp_linger)]

use std::net::TcpStream;
use std::time::Duration;

let stream = TcpStream::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
stream.set_linger(Some(Duration::from_secs(0))).expect("set_linger call failed");
assert_eq!(stream.linger().unwrap(), Some(Duration::from_secs(0)));
```
 
[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#483-485)1.9.0
```
pub fn set_nodelay(&self, nodelay: bool) -> Result<()>
```

Sets the value of the `TCP_NODELAY` option on this socket.

 If set, this option disables the Nagle algorithm. This means that segments are always sent as soon as possible, even if there is only a small amount of data. When not set, data is buffered until there is a sufficient amount to send out, thereby avoiding the frequent sending of small packets.

 ##### Examples

 
```
use std::net::TcpStream;

let stream = TcpStream::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
stream.set_nodelay(true).expect("set_nodelay call failed");
```
 
[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#502-504)1.9.0
```
pub fn nodelay(&self) -> Result<bool>
```

Gets the value of the `TCP_NODELAY` option on this socket.

 For more information about this option, see [`TcpStream::set_nodelay`](struct.tcpstream#method.set_nodelay "method std::net::TcpStream::set_nodelay").

 ##### Examples

 
```
use std::net::TcpStream;

let stream = TcpStream::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
stream.set_nodelay(true).expect("set_nodelay call failed");
assert_eq!(stream.nodelay().unwrap_or(false), true);
```
 
[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#521-523)1.9.0
```
pub fn set_ttl(&self, ttl: u32) -> Result<()>
```

Sets the value for the `IP_TTL` option on this socket.

 This value sets the time-to-live field that is used in every packet sent from this socket.

 ##### Examples

 
```
use std::net::TcpStream;

let stream = TcpStream::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
stream.set_ttl(100).expect("set_ttl call failed");
```
 
[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#540-542)1.9.0
```
pub fn ttl(&self) -> Result<u32>
```

Gets the value of the `IP_TTL` option for this socket.

 For more information about this option, see [`TcpStream::set_ttl`](struct.tcpstream#method.set_ttl "method std::net::TcpStream::set_ttl").

 ##### Examples

 
```
use std::net::TcpStream;

let stream = TcpStream::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
stream.set_ttl(100).expect("set_ttl call failed");
assert_eq!(stream.ttl().unwrap_or(0), 100);
```
 
[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#560-562)1.9.0
```
pub fn take_error(&self) -> Result<Option<Error>>
```

Gets the value of the `SO_ERROR` option on this socket.

 This will retrieve the stored error in the underlying socket, clearing the field in the process. This can be useful for checking errors between calls.

 ##### Examples

 
```
use std::net::TcpStream;

let stream = TcpStream::connect("127.0.0.1:8080")
                       .expect("Couldn't connect to the server...");
stream.take_error().expect("No error was expected...");
```
 
[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#605-607)1.9.0
```
pub fn set_nonblocking(&self, nonblocking: bool) -> Result<()>
```

Moves this TCP stream into or out of nonblocking mode.

 This will result in `read`, `write`, `recv` and `send` operations becoming nonblocking, i.e., immediately returning from their calls. If the IO operation is successful, `Ok` is returned and no further action is required. If the IO operation could not be completed and needs to be retried, an error with kind [`io::ErrorKind::WouldBlock`](../io/enum.errorkind#variant.WouldBlock "variant std::io::ErrorKind::WouldBlock") is returned.

 On Unix platforms, calling this method corresponds to calling `fcntl` `FIONBIO`. On Windows calling this method corresponds to calling `ioctlsocket` `FIONBIO`.

 ##### Examples

 Reading bytes from a TCP stream in non-blocking mode:

 
```
use std::io::{self, Read};
use std::net::TcpStream;

let mut stream = TcpStream::connect("127.0.0.1:7878")
    .expect("Couldn't connect to the server...");
stream.set_nonblocking(true).expect("set_nonblocking call failed");

let mut buf = vec![];
loop {
    match stream.read_to_end(&mut buf) {
        Ok(_) => break,
        Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
            // wait until network socket is ready, typically implemented
            // via platform-specific APIs such as epoll or IOCP
            wait_for_fd();
        }
        Err(e) => panic!("encountered IO error: {e}"),
    };
};
println!("bytes: {buf:?}");
```
 


Trait Implementations
---------------------



[source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#302-307)1.63.0
```
impl AsFd for TcpStream
```

[source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#304-306)
```
fn as_fd(&self) -> BorrowedFd<'_>
```
Borrows the file descriptor. [Read more](../os/fd/trait.asfd#tymethod.as_fd)


[source](https://doc.rust-lang.org/src/std/os/fd/net.rs.html#17)
```
impl AsRawFd for TcpStream
```

[source](https://doc.rust-lang.org/src/std/os/fd/net.rs.html#17)
```
fn as_raw_fd(&self) -> RawFd
```
Extracts the raw file descriptor. [Read more](../os/fd/trait.asrawfd#tymethod.as_raw_fd)


[source](https://doc.rust-lang.org/src/std/os/windows/io/raw.rs.html#236-241)
```
impl AsRawSocket for TcpStreamAvailable on Windows only.
```

[source](https://doc.rust-lang.org/src/std/os/windows/io/raw.rs.html#238-240)
```
fn as_raw_socket(&self) -> RawSocket
```
Extracts the raw socket. [Read more](../os/windows/io/trait.asrawsocket#tymethod.as_raw_socket)


[source](https://doc.rust-lang.org/src/std/os/windows/io/socket.rs.html#313-318)1.63.0
```
impl AsSocket for TcpStreamAvailable on Windows only.
```

[source](https://doc.rust-lang.org/src/std/os/windows/io/socket.rs.html#315-317)
```
fn as_socket(&self) -> BorrowedSocket<'_>
```
Borrows the socket.

[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#713-717)
```
impl Debug for TcpStream
```

[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#714-716)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result
```
Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt)


[source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#318-325)1.63.0
```
impl From<OwnedFd> for TcpStream
```

[source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#320-324)
```
fn from(owned_fd: OwnedFd) -> Self
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/std/os/windows/io/socket.rs.html#329-334)1.63.0
```
impl From<OwnedSocket> for TcpStreamAvailable on Windows only.
```

[source](https://doc.rust-lang.org/src/std/os/windows/io/socket.rs.html#331-333)
```
fn from(owned: OwnedSocket) -> Self
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#310-315)1.63.0
```
impl From<TcpStream> for OwnedFd
```

[source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#312-314)
```
fn from(tcp_stream: TcpStream) -> OwnedFd
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/std/os/windows/io/socket.rs.html#321-326)1.63.0
```
impl From<TcpStream> for OwnedSocketAvailable on Windows only.
```

[source](https://doc.rust-lang.org/src/std/os/windows/io/socket.rs.html#323-325)
```
fn from(tcp_stream: TcpStream) -> OwnedSocket
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/std/os/fd/net.rs.html#33)1.1.0
```
impl FromRawFd for TcpStream
```

[source](https://doc.rust-lang.org/src/std/os/fd/net.rs.html#33)
```
unsafe fn from_raw_fd(fd: RawFd) -> TcpStream ⓘ
```
Constructs a new instance of `Self` from the given raw file descriptor. [Read more](../os/fd/trait.fromrawfd#tymethod.from_raw_fd)


[source](https://doc.rust-lang.org/src/std/os/windows/io/raw.rs.html#258-264)1.1.0
```
impl FromRawSocket for TcpStreamAvailable on Windows only.
```

[source](https://doc.rust-lang.org/src/std/os/windows/io/raw.rs.html#260-263)
```
unsafe fn from_raw_socket(sock: RawSocket) -> TcpStream ⓘ
```
Constructs a new I/O object from the specified raw socket. [Read more](../os/windows/io/trait.fromrawsocket#tymethod.from_raw_socket)


[source](https://doc.rust-lang.org/src/std/os/fd/net.rs.html#46)1.4.0
```
impl IntoRawFd for TcpStream
```

[source](https://doc.rust-lang.org/src/std/os/fd/net.rs.html#46)
```
fn into_raw_fd(self) -> RawFd
```
Consumes this object, returning the raw underlying file descriptor. [Read more](../os/fd/trait.intorawfd#tymethod.into_raw_fd)


[source](https://doc.rust-lang.org/src/std/os/windows/io/raw.rs.html#283-288)1.4.0
```
impl IntoRawSocket for TcpStreamAvailable on Windows only.
```

[source](https://doc.rust-lang.org/src/std/os/windows/io/raw.rs.html#285-287)
```
fn into_raw_socket(self) -> RawSocket
```
Consumes this object, returning the raw underlying socket. [Read more](../os/windows/io/trait.intorawsocket#tymethod.into_raw_socket)


[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#655-672)
```
impl Read for &TcpStream
```

[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#656-658)
```
fn read(&mut self, buf: &mut [u8]) -> Result<usize>
```
Pull some bytes from this source into the specified buffer, returning how many bytes were read. [Read more](../io/trait.read#tymethod.read)

[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#660-662)
```
fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<()>
```

🔬This is a nightly-only experimental API. (`read_buf` [#78485](https://github.com/rust-lang/rust/issues/78485))
Pull some bytes from this source into the specified buffer. [Read more](../io/trait.read#method.read_buf)

[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#664-666)
```
fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
```
Like `read`, except that it reads into a slice of buffers. [Read more](../io/trait.read#method.read_vectored)

[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#669-671)
```
fn is_read_vectored(&self) -> bool
```

🔬This is a nightly-only experimental API. (`can_vector` [#69941](https://github.com/rust-lang/rust/issues/69941))
Determines if this `Read`er has an efficient `read_vectored` implementation. [Read more](../io/trait.read#method.is_read_vectored)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#726-728)
```
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize>
```
Read all bytes until EOF in this source, placing them into `buf`. [Read more](../io/trait.read#method.read_to_end)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#769-771)
```
fn read_to_string(&mut self, buf: &mut String) -> Result<usize>
```
Read all bytes until EOF in this source, appending them to `buf`. [Read more](../io/trait.read#method.read_to_string)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#824-826)1.6.0
```
fn read_exact(&mut self, buf: &mut [u8]) -> Result<()>
```
Read the exact number of bytes required to fill `buf`. [Read more](../io/trait.read#method.read_exact)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#858-873)
```
fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<()>
```

🔬This is a nightly-only experimental API. (`read_buf` [#78485](https://github.com/rust-lang/rust/issues/78485))
Read the exact number of bytes required to fill `cursor`. [Read more](../io/trait.read#method.read_buf_exact)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#910-915)
```
fn by_ref(&mut self) -> &mut Self
where
    Self: Sized,
```
Creates a “by reference” adaptor for this instance of `Read`. [Read more](../io/trait.read#method.by_ref)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#953-958)
```
fn bytes(self) -> Bytes<Self> ⓘ
where
    Self: Sized,
```
Transforms this `Read` instance to an [`Iterator`](../iter/trait.iterator "trait std::iter::Iterator") over its bytes. [Read more](../io/trait.read#method.bytes)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#991-996)
```
fn chain<R: Read>(self, next: R) -> Chain<Self, R> ⓘ
where
    Self: Sized,
```
Creates an adapter which will chain this stream with another. [Read more](../io/trait.read#method.chain)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1030-1035)
```
fn take(self, limit: u64) -> Take<Self> ⓘ
where
    Self: Sized,
```
Creates an adapter which will read at most `limit` bytes from it. [Read more](../io/trait.read#method.take)


[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#617-634)
```
impl Read for TcpStream
```

[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#618-620)
```
fn read(&mut self, buf: &mut [u8]) -> Result<usize>
```
Pull some bytes from this source into the specified buffer, returning how many bytes were read. [Read more](../io/trait.read#tymethod.read)

[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#622-624)
```
fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<()>
```

🔬This is a nightly-only experimental API. (`read_buf` [#78485](https://github.com/rust-lang/rust/issues/78485))
Pull some bytes from this source into the specified buffer. [Read more](../io/trait.read#method.read_buf)

[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#626-628)
```
fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
```
Like `read`, except that it reads into a slice of buffers. [Read more](../io/trait.read#method.read_vectored)

[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#631-633)
```
fn is_read_vectored(&self) -> bool
```

🔬This is a nightly-only experimental API. (`can_vector` [#69941](https://github.com/rust-lang/rust/issues/69941))
Determines if this `Read`er has an efficient `read_vectored` implementation. [Read more](../io/trait.read#method.is_read_vectored)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#726-728)
```
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize>
```
Read all bytes until EOF in this source, placing them into `buf`. [Read more](../io/trait.read#method.read_to_end)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#769-771)
```
fn read_to_string(&mut self, buf: &mut String) -> Result<usize>
```
Read all bytes until EOF in this source, appending them to `buf`. [Read more](../io/trait.read#method.read_to_string)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#824-826)1.6.0
```
fn read_exact(&mut self, buf: &mut [u8]) -> Result<()>
```
Read the exact number of bytes required to fill `buf`. [Read more](../io/trait.read#method.read_exact)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#858-873)
```
fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<()>
```

🔬This is a nightly-only experimental API. (`read_buf` [#78485](https://github.com/rust-lang/rust/issues/78485))
Read the exact number of bytes required to fill `cursor`. [Read more](../io/trait.read#method.read_buf_exact)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#910-915)
```
fn by_ref(&mut self) -> &mut Self
where
    Self: Sized,
```
Creates a “by reference” adaptor for this instance of `Read`. [Read more](../io/trait.read#method.by_ref)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#953-958)
```
fn bytes(self) -> Bytes<Self> ⓘ
where
    Self: Sized,
```
Transforms this `Read` instance to an [`Iterator`](../iter/trait.iterator "trait std::iter::Iterator") over its bytes. [Read more](../io/trait.read#method.bytes)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#991-996)
```
fn chain<R: Read>(self, next: R) -> Chain<Self, R> ⓘ
where
    Self: Sized,
```
Creates an adapter which will chain this stream with another. [Read more](../io/trait.read#method.chain)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1030-1035)
```
fn take(self, limit: u64) -> Take<Self> ⓘ
where
    Self: Sized,
```
Creates an adapter which will read at most `limit` bytes from it. [Read more](../io/trait.read#method.take)


[source](https://doc.rust-lang.org/src/std/os/net/linux_ext/tcp.rs.html#62-70)
```
impl TcpStreamExt for TcpStreamAvailable on Linux or Android only.
```

[source](https://doc.rust-lang.org/src/std/os/net/linux_ext/tcp.rs.html#63-65)
```
fn set_quickack(&self, quickack: bool) -> Result<()>
```

🔬This is a nightly-only experimental API. (`tcp_quickack` [#96256](https://github.com/rust-lang/rust/issues/96256))

Available on **Linux** only.Enable or disable `TCP_QUICKACK`. [Read more](../os/linux/net/trait.tcpstreamext#tymethod.set_quickack)

[source](https://doc.rust-lang.org/src/std/os/net/linux_ext/tcp.rs.html#67-69)
```
fn quickack(&self) -> Result<bool>
```

🔬This is a nightly-only experimental API. (`tcp_quickack` [#96256](https://github.com/rust-lang/rust/issues/96256))

Available on **Linux** only.Gets the value of the `TCP_QUICKACK` option on this socket. [Read more](../os/linux/net/trait.tcpstreamext#tymethod.quickack)


[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#674-691)
```
impl Write for &TcpStream
```

[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#675-677)
```
fn write(&mut self, buf: &[u8]) -> Result<usize>
```
Write a buffer into this writer, returning how many bytes were written. [Read more](../io/trait.write#tymethod.write)

[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#679-681)
```
fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize>
```
Like [`write`](../io/trait.write#tymethod.write "method std::io::Write::write"), except that it writes from a slice of buffers. [Read more](../io/trait.write#method.write_vectored)

[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#684-686)
```
fn is_write_vectored(&self) -> bool
```

🔬This is a nightly-only experimental API. (`can_vector` [#69941](https://github.com/rust-lang/rust/issues/69941))
Determines if this `Write`r has an efficient [`write_vectored`](../io/trait.write#method.write_vectored "method std::io::Write::write_vectored") implementation. [Read more](../io/trait.write#method.is_write_vectored)

[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#688-690)
```
fn flush(&mut self) -> Result<()>
```
Flush this output stream, ensuring that all intermediately buffered contents reach their destination. [Read more](../io/trait.write#tymethod.flush)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1571-1586)
```
fn write_all(&mut self, buf: &[u8]) -> Result<()>
```
Attempts to write an entire buffer into this writer. [Read more](../io/trait.write#method.write_all)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1636-1654)
```
fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<()>
```

🔬This is a nightly-only experimental API. (`write_all_vectored` [#70436](https://github.com/rust-lang/rust/issues/70436))
Attempts to write multiple buffers into this writer. [Read more](../io/trait.write#method.write_all_vectored)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1692-1724)
```
fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result<()>
```
Writes a formatted string into this writer, returning any error encountered. [Read more](../io/trait.write#method.write_fmt)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1748-1753)
```
fn by_ref(&mut self) -> &mut Self
where
    Self: Sized,
```
Creates a “by reference” adapter for this instance of `Write`. [Read more](../io/trait.write#method.by_ref)


[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#636-653)
```
impl Write for TcpStream
```

[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#637-639)
```
fn write(&mut self, buf: &[u8]) -> Result<usize>
```
Write a buffer into this writer, returning how many bytes were written. [Read more](../io/trait.write#tymethod.write)

[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#641-643)
```
fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize>
```
Like [`write`](../io/trait.write#tymethod.write "method std::io::Write::write"), except that it writes from a slice of buffers. [Read more](../io/trait.write#method.write_vectored)

[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#646-648)
```
fn is_write_vectored(&self) -> bool
```

🔬This is a nightly-only experimental API. (`can_vector` [#69941](https://github.com/rust-lang/rust/issues/69941))
Determines if this `Write`r has an efficient [`write_vectored`](../io/trait.write#method.write_vectored "method std::io::Write::write_vectored") implementation. [Read more](../io/trait.write#method.is_write_vectored)

[source](https://doc.rust-lang.org/src/std/net/tcp.rs.html#650-652)
```
fn flush(&mut self) -> Result<()>
```
Flush this output stream, ensuring that all intermediately buffered contents reach their destination. [Read more](../io/trait.write#tymethod.flush)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1571-1586)
```
fn write_all(&mut self, buf: &[u8]) -> Result<()>
```
Attempts to write an entire buffer into this writer. [Read more](../io/trait.write#method.write_all)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1636-1654)
```
fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<()>
```

🔬This is a nightly-only experimental API. (`write_all_vectored` [#70436](https://github.com/rust-lang/rust/issues/70436))
Attempts to write multiple buffers into this writer. [Read more](../io/trait.write#method.write_all_vectored)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1692-1724)
```
fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result<()>
```
Writes a formatted string into this writer, returning any error encountered. [Read more](../io/trait.write#method.write_fmt)

[source](https://doc.rust-lang.org/src/std/io/mod.rs.html#1748-1753)
```
fn by_ref(&mut self) -> &mut Self
where
    Self: Sized,
```
Creates a “by reference” adapter for this instance of `Write`. [Read more](../io/trait.write#method.by_ref)



Auto Trait Implementations
--------------------------




```
impl RefUnwindSafe for TcpStream
```

```
impl Send for TcpStream
```

```
impl Sync for TcpStream
```

```
impl Unpin for TcpStream
```

```
impl UnwindSafe for TcpStream
```


Blanket Implementations
-----------------------



[source](https://doc.rust-lang.org/src/core/any.rs.html#200)
```
impl<T> Any for T
where
    T: 'static + ?Sized,
```

[source](https://doc.rust-lang.org/src/core/any.rs.html#201)
```
fn type_id(&self) -> TypeId
```
Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#208)
```
impl<T> Borrow<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#210)
```
fn borrow(&self) -> &T
```
Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#216)
```
impl<T> BorrowMut<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#217)
```
fn borrow_mut(&mut self) -> &mut T
```
Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#723)
```
impl<T> From<T> for T
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#726)
```
fn from(t: T) -> T
```

Returns the argument unchanged.

 

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#707)
```
impl<T, U> Into<U> for T
where
    U: From<T>,
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#716)
```
fn into(self) -> U
```

Calls `U::from(self)`.

 That is, this conversion is whatever the implementation of `[From](../convert/trait.from "trait std::convert::From")<T> for U` chooses to do.

 

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#763)
```
impl<T, U> TryFrom<U> for T
where
    U: Into<T>,
```


```
type Error = Infallible
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#770)
```
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#748)
```
impl<T, U> TryInto<U> for T
where
    U: TryFrom<T>,
```


```
type Error = <U as TryFrom<T>>::Error
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#755)
```
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
```
Performs the conversion.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/net/struct.TcpStream.html>

Struct std::net::UdpSocket
==========================



```
pub struct UdpSocket(_);
```

A UDP socket.

 After creating a `UdpSocket` by [`bind`](struct.udpsocket#method.bind "associated function std::net::UdpSocket::bind")ing it to a socket address, data can be [sent to](struct.udpsocket#method.send_to "method std::net::UdpSocket::send_to") and [received from](struct.udpsocket#method.recv_from "method std::net::UdpSocket::recv_from") any other socket address.

 Although UDP is a connectionless protocol, this implementation provides an interface to set an address where data should be sent and received from. After setting a remote address with [`connect`](struct.udpsocket#method.connect "method std::net::UdpSocket::connect"), data can be sent to and received from that address with [`send`](struct.udpsocket#method.send "method std::net::UdpSocket::send") and [`recv`](struct.udpsocket#method.recv "method std::net::UdpSocket::recv").

 As stated in the User Datagram Protocol’s specification in [IETF RFC 768](https://tools.ietf.org/html/rfc768), UDP is an unordered, unreliable protocol; refer to [`TcpListener`](struct.tcplistener "struct std::net::TcpListener") and [`TcpStream`](struct.tcpstream "struct std::net::TcpStream") for TCP primitives.

 Examples
--------

 
```
use std::net::UdpSocket;

fn main() -> std::io::Result<()> {
    {
        let socket = UdpSocket::bind("127.0.0.1:34254")?;

        // Receives a single datagram message on the socket. If `buf` is too small to hold
        // the message, it will be cut off.
        let mut buf = [0; 10];
        let (amt, src) = socket.recv_from(&mut buf)?;

        // Redeclare `buf` as slice of the received data and send reverse data back to origin.
        let buf = &mut buf[..amt];
        buf.reverse();
        socket.send_to(buf, &src)?;
    } // the socket is closed here
    Ok(())
}
```
 Implementations
---------------



[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#60-791)
```
impl UdpSocket
```

[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#103-105)
```
pub fn bind<A: ToSocketAddrs>(addr: A) -> Result<UdpSocket>
```

Creates a UDP socket from the given address.

 The address type can be any implementor of [`ToSocketAddrs`](trait.tosocketaddrs "trait std::net::ToSocketAddrs") trait. See its documentation for concrete examples.

 If `addr` yields multiple addresses, `bind` will be attempted with each of the addresses until one succeeds and returns the socket. If none of the addresses succeed in creating a socket, the error returned from the last attempt (the last address) is returned.

 ##### Examples

 Creates a UDP socket bound to `127.0.0.1:3400`:

 
```
use std::net::UdpSocket;

let socket = UdpSocket::bind("127.0.0.1:3400").expect("couldn't bind to address");
```
 Creates a UDP socket bound to `127.0.0.1:3400`. If the socket cannot be bound to that address, create a UDP socket bound to `127.0.0.1:3401`:

 
```
use std::net::{SocketAddr, UdpSocket};

let addrs = [
    SocketAddr::from(([127, 0, 0, 1], 3400)),
    SocketAddr::from(([127, 0, 0, 1], 3401)),
];
let socket = UdpSocket::bind(&addrs[..]).expect("couldn't bind to address");
```
 Creates a UDP socket bound to a port assigned by the operating system at `127.0.0.1`.

 
```
use std::net::UdpSocket;

let socket = UdpSocket::bind("127.0.0.1:0").unwrap();
```
 
[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#126-128)
```
pub fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, SocketAddr)>
```

Receives a single datagram message on the socket. On success, returns the number of bytes read and the origin.

 The function must be called with valid byte array `buf` of sufficient size to hold the message bytes. If a message is too long to fit in the supplied buffer, excess bytes may be discarded.

 ##### Examples

 
```
use std::net::UdpSocket;

let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
let mut buf = [0; 10];
let (number_of_bytes, src_addr) = socket.recv_from(&mut buf)
                                        .expect("Didn't receive data");
let filled_buf = &mut buf[..number_of_bytes];
```
 
[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#155-157)1.18.0
```
pub fn peek_from(&self, buf: &mut [u8]) -> Result<(usize, SocketAddr)>
```

Receives a single datagram message on the socket, without removing it from the queue. On success, returns the number of bytes read and the origin.

 The function must be called with valid byte array `buf` of sufficient size to hold the message bytes. If a message is too long to fit in the supplied buffer, excess bytes may be discarded.

 Successive calls return the same data. This is accomplished by passing `MSG_PEEK` as a flag to the underlying `recvfrom` system call.

 Do not use this function to implement busy waiting, instead use `libc::poll` to synchronize IO events on one or more sockets.

 ##### Examples

 
```
use std::net::UdpSocket;

let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
let mut buf = [0; 10];
let (number_of_bytes, src_addr) = socket.peek_from(&mut buf)
                                        .expect("Didn't receive data");
let filled_buf = &mut buf[..number_of_bytes];
```
 
[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#184-191)
```
pub fn send_to<A: ToSocketAddrs>(&self, buf: &[u8], addr: A) -> Result<usize>
```

Sends data on the socket to the given address. On success, returns the number of bytes written.

 Address type can be any implementor of [`ToSocketAddrs`](trait.tosocketaddrs "trait std::net::ToSocketAddrs") trait. See its documentation for concrete examples.

 It is possible for `addr` to yield multiple addresses, but `send_to` will only send data to the first address yielded by `addr`.

 This will return an error when the IP version of the local socket does not match that returned from [`ToSocketAddrs`](trait.tosocketaddrs "trait std::net::ToSocketAddrs").

 See [Issue #34202](https://github.com/rust-lang/rust/issues/34202) for more details.

 ##### Examples

 
```
use std::net::UdpSocket;

let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
socket.send_to(&[0; 10], "127.0.0.1:4242").expect("couldn't send data");
```
 
[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#218-220)1.40.0
```
pub fn peer_addr(&self) -> Result<SocketAddr>
```

Returns the socket address of the remote peer this socket was connected to.

 ##### Examples

 
```
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket};

let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
socket.connect("192.168.0.1:41203").expect("couldn't connect to address");
assert_eq!(socket.peer_addr().unwrap(),
           SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(192, 168, 0, 1), 41203)));
```
 If the socket isn’t connected, it will return a [`NotConnected`](../io/enum.errorkind#variant.NotConnected "variant std::io::ErrorKind::NotConnected") error.

 
```
use std::net::UdpSocket;

let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
assert_eq!(socket.peer_addr().unwrap_err().kind(),
           std::io::ErrorKind::NotConnected);
```
 
[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#234-236)
```
pub fn local_addr(&self) -> Result<SocketAddr>
```

Returns the socket address that this socket was created from.

 ##### Examples

 
```
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket};

let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
assert_eq!(socket.local_addr().unwrap(),
           SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 34254)));
```
 
[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#253-255)
```
pub fn try_clone(&self) -> Result<UdpSocket>
```

Creates a new independently owned handle to the underlying socket.

 The returned `UdpSocket` is a reference to the same socket that this object references. Both handles will read and write the same port, and options set on one socket will be propagated to the other.

 ##### Examples

 
```
use std::net::UdpSocket;

let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
let socket_clone = socket.try_clone().expect("couldn't clone the socket");
```
 
[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#296-298)1.4.0
```
pub fn set_read_timeout(&self, dur: Option<Duration>) -> Result<()>
```

Sets the read timeout to the timeout specified.

 If the value specified is [`None`](../option/enum.option#variant.None "variant std::option::Option::None"), then [`read`](../io/trait.read#tymethod.read "method std::io::Read::read") calls will block indefinitely. An [`Err`](../result/enum.result#variant.Err "variant std::result::Result::Err") is returned if the zero [`Duration`](../time/struct.duration "struct std::time::Duration") is passed to this method.

 ##### Platform-specific behavior

 Platforms may return a different error code whenever a read times out as a result of setting this option. For example Unix typically returns an error of the kind [`WouldBlock`](../io/enum.errorkind#variant.WouldBlock "variant std::io::ErrorKind::WouldBlock"), but Windows may return [`TimedOut`](../io/enum.errorkind#variant.TimedOut "variant std::io::ErrorKind::TimedOut").

 ##### Examples

 
```
use std::net::UdpSocket;

let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
socket.set_read_timeout(None).expect("set_read_timeout call failed");
```
 An [`Err`](../result/enum.result#variant.Err "variant std::result::Result::Err") is returned if the zero [`Duration`](../time/struct.duration "struct std::time::Duration") is passed to this method:

 
```
use std::io;
use std::net::UdpSocket;
use std::time::Duration;

let socket = UdpSocket::bind("127.0.0.1:34254").unwrap();
let result = socket.set_read_timeout(Some(Duration::new(0, 0)));
let err = result.unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
```
 
[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#339-341)1.4.0
```
pub fn set_write_timeout(&self, dur: Option<Duration>) -> Result<()>
```

Sets the write timeout to the timeout specified.

 If the value specified is [`None`](../option/enum.option#variant.None "variant std::option::Option::None"), then [`write`](../io/trait.write#tymethod.write "method std::io::Write::write") calls will block indefinitely. An [`Err`](../result/enum.result#variant.Err "variant std::result::Result::Err") is returned if the zero [`Duration`](../time/struct.duration "struct std::time::Duration") is passed to this method.

 ##### Platform-specific behavior

 Platforms may return a different error code whenever a write times out as a result of setting this option. For example Unix typically returns an error of the kind [`WouldBlock`](../io/enum.errorkind#variant.WouldBlock "variant std::io::ErrorKind::WouldBlock"), but Windows may return [`TimedOut`](../io/enum.errorkind#variant.TimedOut "variant std::io::ErrorKind::TimedOut").

 ##### Examples

 
```
use std::net::UdpSocket;

let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
socket.set_write_timeout(None).expect("set_write_timeout call failed");
```
 An [`Err`](../result/enum.result#variant.Err "variant std::result::Result::Err") is returned if the zero [`Duration`](../time/struct.duration "struct std::time::Duration") is passed to this method:

 
```
use std::io;
use std::net::UdpSocket;
use std::time::Duration;

let socket = UdpSocket::bind("127.0.0.1:34254").unwrap();
let result = socket.set_write_timeout(Some(Duration::new(0, 0)));
let err = result.unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
```
 
[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#359-361)1.4.0
```
pub fn read_timeout(&self) -> Result<Option<Duration>>
```

Returns the read timeout of this socket.

 If the timeout is [`None`](../option/enum.option#variant.None "variant std::option::Option::None"), then [`read`](../io/trait.read#tymethod.read "method std::io::Read::read") calls will block indefinitely.

 ##### Examples

 
```
use std::net::UdpSocket;

let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
socket.set_read_timeout(None).expect("set_read_timeout call failed");
assert_eq!(socket.read_timeout().unwrap(), None);
```
 
[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#379-381)1.4.0
```
pub fn write_timeout(&self) -> Result<Option<Duration>>
```

Returns the write timeout of this socket.

 If the timeout is [`None`](../option/enum.option#variant.None "variant std::option::Option::None"), then [`write`](../io/trait.write#tymethod.write "method std::io::Write::write") calls will block indefinitely.

 ##### Examples

 
```
use std::net::UdpSocket;

let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
socket.set_write_timeout(None).expect("set_write_timeout call failed");
assert_eq!(socket.write_timeout().unwrap(), None);
```
 
[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#397-399)1.9.0
```
pub fn set_broadcast(&self, broadcast: bool) -> Result<()>
```

Sets the value of the `SO_BROADCAST` option for this socket.

 When enabled, this socket is allowed to send packets to a broadcast address.

 ##### Examples

 
```
use std::net::UdpSocket;

let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
socket.set_broadcast(false).expect("set_broadcast call failed");
```
 
[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#415-417)1.9.0
```
pub fn broadcast(&self) -> Result<bool>
```

Gets the value of the `SO_BROADCAST` option for this socket.

 For more information about this option, see [`UdpSocket::set_broadcast`](struct.udpsocket#method.set_broadcast "method std::net::UdpSocket::set_broadcast").

 ##### Examples

 
```
use std::net::UdpSocket;

let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
socket.set_broadcast(false).expect("set_broadcast call failed");
assert_eq!(socket.broadcast().unwrap(), false);
```
 
[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#433-435)1.9.0
```
pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> Result<()>
```

Sets the value of the `IP_MULTICAST_LOOP` option for this socket.

 If enabled, multicast packets will be looped back to the local socket. Note that this might not have any effect on IPv6 sockets.

 ##### Examples

 
```
use std::net::UdpSocket;

let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
socket.set_multicast_loop_v4(false).expect("set_multicast_loop_v4 call failed");
```
 
[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#451-453)1.9.0
```
pub fn multicast_loop_v4(&self) -> Result<bool>
```

Gets the value of the `IP_MULTICAST_LOOP` option for this socket.

 For more information about this option, see [`UdpSocket::set_multicast_loop_v4`](struct.udpsocket#method.set_multicast_loop_v4 "method std::net::UdpSocket::set_multicast_loop_v4").

 ##### Examples

 
```
use std::net::UdpSocket;

let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
socket.set_multicast_loop_v4(false).expect("set_multicast_loop_v4 call failed");
assert_eq!(socket.multicast_loop_v4().unwrap(), false);
```
 
[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#472-474)1.9.0
```
pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> Result<()>
```

Sets the value of the `IP_MULTICAST_TTL` option for this socket.

 Indicates the time-to-live value of outgoing multicast packets for this socket. The default value is 1 which means that multicast packets don’t leave the local network unless explicitly requested.

 Note that this might not have any effect on IPv6 sockets.

 ##### Examples

 
```
use std::net::UdpSocket;

let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
socket.set_multicast_ttl_v4(42).expect("set_multicast_ttl_v4 call failed");
```
 
[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#490-492)1.9.0
```
pub fn multicast_ttl_v4(&self) -> Result<u32>
```

Gets the value of the `IP_MULTICAST_TTL` option for this socket.

 For more information about this option, see [`UdpSocket::set_multicast_ttl_v4`](struct.udpsocket#method.set_multicast_ttl_v4 "method std::net::UdpSocket::set_multicast_ttl_v4").

 ##### Examples

 
```
use std::net::UdpSocket;

let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
socket.set_multicast_ttl_v4(42).expect("set_multicast_ttl_v4 call failed");
assert_eq!(socket.multicast_ttl_v4().unwrap(), 42);
```
 
[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#508-510)1.9.0
```
pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> Result<()>
```

Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket.

 Controls whether this socket sees the multicast packets it sends itself. Note that this might not have any affect on IPv4 sockets.

 ##### Examples

 
```
use std::net::UdpSocket;

let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
socket.set_multicast_loop_v6(false).expect("set_multicast_loop_v6 call failed");
```
 
[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#526-528)1.9.0
```
pub fn multicast_loop_v6(&self) -> Result<bool>
```

Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket.

 For more information about this option, see [`UdpSocket::set_multicast_loop_v6`](struct.udpsocket#method.set_multicast_loop_v6 "method std::net::UdpSocket::set_multicast_loop_v6").

 ##### Examples

 
```
use std::net::UdpSocket;

let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
socket.set_multicast_loop_v6(false).expect("set_multicast_loop_v6 call failed");
assert_eq!(socket.multicast_loop_v6().unwrap(), false);
```
 
[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#544-546)1.9.0
```
pub fn set_ttl(&self, ttl: u32) -> Result<()>
```

Sets the value for the `IP_TTL` option on this socket.

 This value sets the time-to-live field that is used in every packet sent from this socket.

 ##### Examples

 
```
use std::net::UdpSocket;

let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
socket.set_ttl(42).expect("set_ttl call failed");
```
 
[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#562-564)1.9.0
```
pub fn ttl(&self) -> Result<u32>
```

Gets the value of the `IP_TTL` option for this socket.

 For more information about this option, see [`UdpSocket::set_ttl`](struct.udpsocket#method.set_ttl "method std::net::UdpSocket::set_ttl").

 ##### Examples

 
```
use std::net::UdpSocket;

let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
socket.set_ttl(42).expect("set_ttl call failed");
assert_eq!(socket.ttl().unwrap(), 42);
```
 
[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#574-576)1.9.0
```
pub fn join_multicast_v4(
    &self,
    multiaddr: &Ipv4Addr,
    interface: &Ipv4Addr
) -> Result<()>
```

Executes an operation of the `IP_ADD_MEMBERSHIP` type.

 This function specifies a new multicast group for this socket to join. The address must be a valid multicast address, and `interface` is the address of the local interface with which the system should join the multicast group. If it’s equal to `INADDR_ANY` then an appropriate interface is chosen by the system.

 
[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#584-586)1.9.0
```
pub fn join_multicast_v6(
    &self,
    multiaddr: &Ipv6Addr,
    interface: u32
) -> Result<()>
```

Executes an operation of the `IPV6_ADD_MEMBERSHIP` type.

 This function specifies a new multicast group for this socket to join. The address must be a valid multicast address, and `interface` is the index of the interface to join/leave (or 0 to indicate any interface).

 
[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#592-594)1.9.0
```
pub fn leave_multicast_v4(
    &self,
    multiaddr: &Ipv4Addr,
    interface: &Ipv4Addr
) -> Result<()>
```

Executes an operation of the `IP_DROP_MEMBERSHIP` type.

 For more information about this option, see [`UdpSocket::join_multicast_v4`](struct.udpsocket#method.join_multicast_v4 "method std::net::UdpSocket::join_multicast_v4").

 
[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#600-602)1.9.0
```
pub fn leave_multicast_v6(
    &self,
    multiaddr: &Ipv6Addr,
    interface: u32
) -> Result<()>
```

Executes an operation of the `IPV6_DROP_MEMBERSHIP` type.

 For more information about this option, see [`UdpSocket::join_multicast_v6`](struct.udpsocket#method.join_multicast_v6 "method std::net::UdpSocket::join_multicast_v6").

 
[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#623-625)1.9.0
```
pub fn take_error(&self) -> Result<Option<Error>>
```

Gets the value of the `SO_ERROR` option on this socket.

 This will retrieve the stored error in the underlying socket, clearing the field in the process. This can be useful for checking errors between calls.

 ##### Examples

 
```
use std::net::UdpSocket;

let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
match socket.take_error() {
    Ok(Some(error)) => println!("UdpSocket error: {error:?}"),
    Ok(None) => println!("No error"),
    Err(error) => println!("UdpSocket.take_error failed: {error:?}"),
}
```
 
[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#656-658)1.9.0
```
pub fn connect<A: ToSocketAddrs>(&self, addr: A) -> Result<()>
```

Connects this UDP socket to a remote address, allowing the `send` and `recv` syscalls to be used to send data and also applies filters to only receive data from the specified address.

 If `addr` yields multiple addresses, `connect` will be attempted with each of the addresses until the underlying OS function returns no error. Note that usually, a successful `connect` call does not specify that there is a remote server listening on the port, rather, such an error would only be detected after the first send. If the OS returns an error for each of the specified addresses, the error returned from the last connection attempt (the last address) is returned.

 ##### Examples

 Creates a UDP socket bound to `127.0.0.1:3400` and connect the socket to `127.0.0.1:8080`:

 
```
use std::net::UdpSocket;

let socket = UdpSocket::bind("127.0.0.1:3400").expect("couldn't bind to address");
socket.connect("127.0.0.1:8080").expect("connect function failed");
```
 Unlike in the TCP case, passing an array of addresses to the `connect` function of a UDP socket is not a useful thing to do: The OS will be unable to determine whether something is listening on the remote address without the application sending data.

 
[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#675-677)1.9.0
```
pub fn send(&self, buf: &[u8]) -> Result<usize>
```

Sends data on the socket to the remote address to which it is connected.

 [`UdpSocket::connect`](struct.udpsocket#method.connect "method std::net::UdpSocket::connect") will connect this socket to a remote address. This method will fail if the socket is not connected.

 ##### Examples

 
```
use std::net::UdpSocket;

let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
socket.connect("127.0.0.1:8080").expect("connect function failed");
socket.send(&[0, 1, 2]).expect("couldn't send message");
```
 
[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#703-705)1.9.0
```
pub fn recv(&self, buf: &mut [u8]) -> Result<usize>
```

Receives a single datagram message on the socket from the remote address to which it is connected. On success, returns the number of bytes read.

 The function must be called with valid byte array `buf` of sufficient size to hold the message bytes. If a message is too long to fit in the supplied buffer, excess bytes may be discarded.

 [`UdpSocket::connect`](struct.udpsocket#method.connect "method std::net::UdpSocket::connect") will connect this socket to a remote address. This method will fail if the socket is not connected.

 ##### Examples

 
```
use std::net::UdpSocket;

let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
socket.connect("127.0.0.1:8080").expect("connect function failed");
let mut buf = [0; 10];
match socket.recv(&mut buf) {
    Ok(received) => println!("received {received} bytes {:?}", &buf[..received]),
    Err(e) => println!("recv function failed: {e:?}"),
}
```
 
[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#743-745)1.18.0
```
pub fn peek(&self, buf: &mut [u8]) -> Result<usize>
```

Receives single datagram on the socket from the remote address to which it is connected, without removing the message from input queue. On success, returns the number of bytes peeked.

 The function must be called with valid byte array `buf` of sufficient size to hold the message bytes. If a message is too long to fit in the supplied buffer, excess bytes may be discarded.

 Successive calls return the same data. This is accomplished by passing `MSG_PEEK` as a flag to the underlying `recv` system call.

 Do not use this function to implement busy waiting, instead use `libc::poll` to synchronize IO events on one or more sockets.

 [`UdpSocket::connect`](struct.udpsocket#method.connect "method std::net::UdpSocket::connect") will connect this socket to a remote address. This method will fail if the socket is not connected.

 ##### Errors

 This method will fail if the socket is not connected. The `connect` method will connect this socket to a remote address.

 ##### Examples

 
```
use std::net::UdpSocket;

let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
socket.connect("127.0.0.1:8080").expect("connect function failed");
let mut buf = [0; 10];
match socket.peek(&mut buf) {
    Ok(received) => println!("received {received} bytes"),
    Err(e) => println!("peek function failed: {e:?}"),
}
```
 
[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#788-790)1.9.0
```
pub fn set_nonblocking(&self, nonblocking: bool) -> Result<()>
```

Moves this UDP socket into or out of nonblocking mode.

 This will result in `recv`, `recv_from`, `send`, and `send_to` operations becoming nonblocking, i.e., immediately returning from their calls. If the IO operation is successful, `Ok` is returned and no further action is required. If the IO operation could not be completed and needs to be retried, an error with kind [`io::ErrorKind::WouldBlock`](../io/enum.errorkind#variant.WouldBlock "variant std::io::ErrorKind::WouldBlock") is returned.

 On Unix platforms, calling this method corresponds to calling `fcntl` `FIONBIO`. On Windows calling this method corresponds to calling `ioctlsocket` `FIONBIO`.

 ##### Examples

 Creates a UDP socket bound to `127.0.0.1:7878` and read bytes in nonblocking mode:

 
```
use std::io;
use std::net::UdpSocket;

let socket = UdpSocket::bind("127.0.0.1:7878").unwrap();
socket.set_nonblocking(true).unwrap();

let mut buf = [0; 10];
let (num_bytes_read, _) = loop {
    match socket.recv_from(&mut buf) {
        Ok(n) => break n,
        Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
            // wait until network socket is ready, typically implemented
            // via platform-specific APIs such as epoll or IOCP
            wait_for_fd();
        }
        Err(e) => panic!("encountered IO error: {e}"),
    }
};
println!("bytes: {:?}", &buf[..num_bytes_read]);
```
 


Trait Implementations
---------------------



[source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#354-359)1.63.0
```
impl AsFd for UdpSocket
```

[source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#356-358)
```
fn as_fd(&self) -> BorrowedFd<'_>
```
Borrows the file descriptor. [Read more](../os/fd/trait.asfd#tymethod.as_fd)


[source](https://doc.rust-lang.org/src/std/os/fd/net.rs.html#17)
```
impl AsRawFd for UdpSocket
```

[source](https://doc.rust-lang.org/src/std/os/fd/net.rs.html#17)
```
fn as_raw_fd(&self) -> RawFd
```
Extracts the raw file descriptor. [Read more](../os/fd/trait.asrawfd#tymethod.as_raw_fd)


[source](https://doc.rust-lang.org/src/std/os/windows/io/raw.rs.html#250-255)
```
impl AsRawSocket for UdpSocketAvailable on Windows only.
```

[source](https://doc.rust-lang.org/src/std/os/windows/io/raw.rs.html#252-254)
```
fn as_raw_socket(&self) -> RawSocket
```
Extracts the raw socket. [Read more](../os/windows/io/trait.asrawsocket#tymethod.as_raw_socket)


[source](https://doc.rust-lang.org/src/std/os/windows/io/socket.rs.html#361-366)1.63.0
```
impl AsSocket for UdpSocketAvailable on Windows only.
```

[source](https://doc.rust-lang.org/src/std/os/windows/io/socket.rs.html#363-365)
```
fn as_socket(&self) -> BorrowedSocket<'_>
```
Borrows the socket.

[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#819-823)
```
impl Debug for UdpSocket
```

[source](https://doc.rust-lang.org/src/std/net/udp.rs.html#820-822)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result
```
Formats the value using the given formatter. [Read more](../fmt/trait.debug#tymethod.fmt)


[source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#370-377)1.63.0
```
impl From<OwnedFd> for UdpSocket
```

[source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#372-376)
```
fn from(owned_fd: OwnedFd) -> Self
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/std/os/windows/io/socket.rs.html#377-382)1.63.0
```
impl From<OwnedSocket> for UdpSocketAvailable on Windows only.
```

[source](https://doc.rust-lang.org/src/std/os/windows/io/socket.rs.html#379-381)
```
fn from(owned: OwnedSocket) -> Self
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#362-367)1.63.0
```
impl From<UdpSocket> for OwnedFd
```

[source](https://doc.rust-lang.org/src/std/os/fd/owned.rs.html#364-366)
```
fn from(udp_socket: UdpSocket) -> OwnedFd
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/std/os/windows/io/socket.rs.html#369-374)1.63.0
```
impl From<UdpSocket> for OwnedSocketAvailable on Windows only.
```

[source](https://doc.rust-lang.org/src/std/os/windows/io/socket.rs.html#371-373)
```
fn from(udp_socket: UdpSocket) -> OwnedSocket
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/std/os/fd/net.rs.html#33)1.1.0
```
impl FromRawFd for UdpSocket
```

[source](https://doc.rust-lang.org/src/std/os/fd/net.rs.html#33)
```
unsafe fn from_raw_fd(fd: RawFd) -> UdpSocket
```
Constructs a new instance of `Self` from the given raw file descriptor. [Read more](../os/fd/trait.fromrawfd#tymethod.from_raw_fd)


[source](https://doc.rust-lang.org/src/std/os/windows/io/raw.rs.html#274-280)1.1.0
```
impl FromRawSocket for UdpSocketAvailable on Windows only.
```

[source](https://doc.rust-lang.org/src/std/os/windows/io/raw.rs.html#276-279)
```
unsafe fn from_raw_socket(sock: RawSocket) -> UdpSocket
```
Constructs a new I/O object from the specified raw socket. [Read more](../os/windows/io/trait.fromrawsocket#tymethod.from_raw_socket)


[source](https://doc.rust-lang.org/src/std/os/fd/net.rs.html#46)1.4.0
```
impl IntoRawFd for UdpSocket
```

[source](https://doc.rust-lang.org/src/std/os/fd/net.rs.html#46)
```
fn into_raw_fd(self) -> RawFd
```
Consumes this object, returning the raw underlying file descriptor. [Read more](../os/fd/trait.intorawfd#tymethod.into_raw_fd)


[source](https://doc.rust-lang.org/src/std/os/windows/io/raw.rs.html#299-304)1.4.0
```
impl IntoRawSocket for UdpSocketAvailable on Windows only.
```

[source](https://doc.rust-lang.org/src/std/os/windows/io/raw.rs.html#301-303)
```
fn into_raw_socket(self) -> RawSocket
```
Consumes this object, returning the raw underlying socket. [Read more](../os/windows/io/trait.intorawsocket#tymethod.into_raw_socket)



Auto Trait Implementations
--------------------------




```
impl RefUnwindSafe for UdpSocket
```

```
impl Send for UdpSocket
```

```
impl Sync for UdpSocket
```

```
impl Unpin for UdpSocket
```

```
impl UnwindSafe for UdpSocket
```


Blanket Implementations
-----------------------



[source](https://doc.rust-lang.org/src/core/any.rs.html#200)
```
impl<T> Any for T
where
    T: 'static + ?Sized,
```

[source](https://doc.rust-lang.org/src/core/any.rs.html#201)
```
fn type_id(&self) -> TypeId
```
Gets the `TypeId` of `self`. [Read more](../any/trait.any#tymethod.type_id)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#208)
```
impl<T> Borrow<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#210)
```
fn borrow(&self) -> &T
```
Immutably borrows from an owned value. [Read more](../borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#216)
```
impl<T> BorrowMut<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#217)
```
fn borrow_mut(&mut self) -> &mut T
```
Mutably borrows from an owned value. [Read more](../borrow/trait.borrowmut#tymethod.borrow_mut)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#723)
```
impl<T> From<T> for T
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#726)
```
fn from(t: T) -> T
```

Returns the argument unchanged.

 

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#707)
```
impl<T, U> Into<U> for T
where
    U: From<T>,
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#716)
```
fn into(self) -> U
```

Calls `U::from(self)`.

 That is, this conversion is whatever the implementation of `[From](../convert/trait.from "trait std::convert::From")<T> for U` chooses to do.

 

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#763)
```
impl<T, U> TryFrom<U> for T
where
    U: Into<T>,
```


```
type Error = Infallible
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#770)
```
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#748)
```
impl<T, U> TryInto<U> for T
where
    U: TryFrom<T>,
```


```
type Error = <U as TryFrom<T>>::Error
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#755)
```
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
```
Performs the conversion.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/net/struct.UdpSocket.html>

Module std::fs
==============


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

 Structs
-------


* [FileTimes](struct.filetimes "struct std::fs::FileTimes")Experimental

Representation of the various timestamps on a file.
* [DirBuilder](struct.dirbuilder "struct std::fs::DirBuilder")
A builder used to create directories in various manners.
* [DirEntry](struct.direntry "struct std::fs::DirEntry")
Entries returned by the [`ReadDir`](struct.readdir "struct std::fs::ReadDir") iterator.
* [File](struct.file "struct std::fs::File")
An object providing access to an open file on the filesystem.
* [FileType](struct.filetype "struct std::fs::FileType")
A structure representing a type of file with accessors for each file type. It is returned by [`Metadata::file_type`](struct.metadata#method.file_type "method std::fs::Metadata::file_type") method.
* [Metadata](struct.metadata "struct std::fs::Metadata")
Metadata information about a file.
* [OpenOptions](struct.openoptions "struct std::fs::OpenOptions")
Options and flags which can be used to configure how a file is opened.
* [Permissions](struct.permissions "struct std::fs::Permissions")
Representation of the various permissions on a file.
* [ReadDir](struct.readdir "struct std::fs::ReadDir")
Iterator over the entries in a directory.


Functions
---------


* [try\_exists](fn.try_exists "fn std::fs::try_exists")Experimental

Returns `Ok(true)` if the path points at an existing entity.
* [canonicalize](fn.canonicalize "fn std::fs::canonicalize")
Returns the canonical, absolute form of a path with all intermediate components normalized and symbolic links resolved.
* [copy](fn.copy "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](fn.create_dir "fn std::fs::create_dir")
Creates a new, empty directory at the provided path
* [create\_dir\_all](fn.create_dir_all "fn std::fs::create_dir_all")
Recursively create a directory and all of its parent components if they are missing.
* [hard\_link](fn.hard_link "fn std::fs::hard_link")
Creates a new hard link on the filesystem.
* [metadata](fn.metadata "fn std::fs::metadata")
Given a path, query the file system to get information about a file, directory, etc.
* [read](fn.read "fn std::fs::read")
Read the entire contents of a file into a bytes vector.
* [read\_dir](fn.read_dir "fn std::fs::read_dir")
Returns an iterator over the entries within a directory.
* [read\_link](fn.read_link "fn std::fs::read_link")
Reads a symbolic link, returning the file that the link points to.
* [read\_to\_string](fn.read_to_string "fn std::fs::read_to_string")
Read the entire contents of a file into a string.
* [remove\_dir](fn.remove_dir "fn std::fs::remove_dir")
Removes an empty directory.
* [remove\_dir\_all](fn.remove_dir_all "fn std::fs::remove_dir_all")
Removes a directory at this path, after removing all its contents. Use carefully!
* [remove\_file](fn.remove_file "fn std::fs::remove_file")
Removes a file from the filesystem.
* [rename](fn.rename "fn std::fs::rename")
Rename a file or directory to a new name, replacing the original file if `to` already exists.
* [set\_permissions](fn.set_permissions "fn std::fs::set_permissions")
Changes the permissions found on a file or a directory.
* [soft\_link](fn.soft_link "fn std::fs::soft_link")Deprecated

Creates a new symbolic link on the filesystem.
* [symlink\_metadata](fn.symlink_metadata "fn std::fs::symlink_metadata")
Query the metadata about a file without following symlinks.
* [write](fn.write "fn std::fs::write")
Write a slice as the entire contents of a file.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/fs/index.html>

Module std::net
===============


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.

 Organization
------------

 * [`TcpListener`](struct.tcplistener "struct std::net::TcpListener") and [`TcpStream`](struct.tcpstream "struct std::net::TcpStream") provide functionality for communication over TCP
* [`UdpSocket`](struct.udpsocket "struct std::net::UdpSocket") provides functionality for communication over UDP
* [`IpAddr`](enum.ipaddr "enum std::net::IpAddr") represents IP addresses of either IPv4 or IPv6; [`Ipv4Addr`](struct.ipv4addr "struct std::net::Ipv4Addr") and [`Ipv6Addr`](struct.ipv6addr "struct std::net::Ipv6Addr") are respectively IPv4 and IPv6 addresses
* [`SocketAddr`](enum.socketaddr "enum std::net::SocketAddr") represents socket addresses of either IPv4 or IPv6; [`SocketAddrV4`](struct.socketaddrv4 "struct std::net::SocketAddrV4") and [`SocketAddrV6`](struct.socketaddrv6 "struct std::net::SocketAddrV6") are respectively IPv4 and IPv6 socket addresses
* [`ToSocketAddrs`](trait.tosocketaddrs "trait std::net::ToSocketAddrs") is a trait that is used for generic address resolution when interacting with networking objects like [`TcpListener`](struct.tcplistener "struct std::net::TcpListener"), [`TcpStream`](struct.tcpstream "struct std::net::TcpStream") or [`UdpSocket`](struct.udpsocket "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
-------


* [IntoIncoming](struct.intoincoming "struct std::net::IntoIncoming")Experimental

An iterator that infinitely [`accept`](struct.tcplistener#method.accept "method std::net::TcpListener::accept")s connections on a [`TcpListener`](struct.tcplistener "struct std::net::TcpListener").
* [AddrParseError](struct.addrparseerror "struct std::net::AddrParseError")
An error which can be returned when parsing an IP address or a socket address.
* [Incoming](struct.incoming "struct std::net::Incoming")
An iterator that infinitely [`accept`](struct.tcplistener#method.accept "method std::net::TcpListener::accept")s connections on a [`TcpListener`](struct.tcplistener "struct std::net::TcpListener").
* [Ipv4Addr](struct.ipv4addr "struct std::net::Ipv4Addr")
An IPv4 address.
* [Ipv6Addr](struct.ipv6addr "struct std::net::Ipv6Addr")
An IPv6 address.
* [SocketAddrV4](struct.socketaddrv4 "struct std::net::SocketAddrV4")
An IPv4 socket address.
* [SocketAddrV6](struct.socketaddrv6 "struct std::net::SocketAddrV6")
An IPv6 socket address.
* [TcpListener](struct.tcplistener "struct std::net::TcpListener")
A TCP socket server, listening for connections.
* [TcpStream](struct.tcpstream "struct std::net::TcpStream")
A TCP stream between a local and a remote socket.
* [UdpSocket](struct.udpsocket "struct std::net::UdpSocket")
A UDP socket.


Enums
-----


* [Ipv6MulticastScope](enum.ipv6multicastscope "enum std::net::Ipv6MulticastScope")Experimental

Scope of an [IPv6 multicast address](struct.ipv6addr "struct std::net::Ipv6Addr") as defined in [IETF RFC 7346 section 2](https://tools.ietf.org/html/rfc7346#section-2).
* [IpAddr](enum.ipaddr "enum std::net::IpAddr")
An IP address, either IPv4 or IPv6.
* [Shutdown](enum.shutdown "enum std::net::Shutdown")
Possible values which can be passed to the [`TcpStream::shutdown`](struct.tcpstream#method.shutdown "method std::net::TcpStream::shutdown") method.
* [SocketAddr](enum.socketaddr "enum std::net::SocketAddr")
An internet socket address, either IPv4 or IPv6.


Traits
------


* [ToSocketAddrs](trait.tosocketaddrs "trait std::net::ToSocketAddrs")
A trait for objects which can be converted or resolved to one or more [`SocketAddr`](enum.socketaddr "enum std::net::SocketAddr") values.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/net/index.html>

Module std::sync
================


Useful synchronization primitives.

 ### 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:

 
```
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;
    }
}
```
 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.

 ### 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](atomic/fn.compiler_fence "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](atomic/fn.fence "fn std::sync::atomic::fence") to ensure memory accesses are made visible to other CPUs in the right order.
	+ [atomic operations](atomic/index "mod std::sync::atomic") to ensure simultaneous access to the same memory location doesn’t lead to undefined behavior.

 ### 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`](struct.arc "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`](struct.barrier "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`](struct.condvar "struct std::sync::Condvar"): Condition Variable, providing the ability to block a thread while waiting for an event to occur.
* [`mpsc`](mpsc/index "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.
* [`Mutex`](struct.mutex "struct std::sync::Mutex"): Mutual Exclusion mechanism, which ensures that at most one thread at a time is able to access some data.
* [`Once`](struct.once "struct std::sync::Once"): Used for a thread-safe, one-time global initialization routine
* [`OnceLock`](struct.oncelock "struct std::sync::OnceLock"): Used for thread-safe, one-time initialization of a global variable.
* [`RwLock`](struct.rwlock "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
-------


* [atomic](atomic/index "mod std::sync::atomic")
Atomic types
* [mpsc](mpsc/index "mod std::sync::mpsc")
Multi-producer, single-consumer FIFO queue communication primitives.


Structs
-------


* [Exclusive](struct.exclusive "struct std::sync::Exclusive")Experimental


`Exclusive` provides only *mutable* access, also referred to as *exclusive* access to the underlying value. It provides no *immutable*, or *shared* access to the underlying value.
* [LazyLock](struct.lazylock "struct std::sync::LazyLock")Experimental

A value which is initialized on the first access.
* [Arc](struct.arc "struct std::sync::Arc")
A thread-safe reference-counting pointer. ‘Arc’ stands for ‘Atomically Reference Counted’.
* [Barrier](struct.barrier "struct std::sync::Barrier")
A barrier enables multiple threads to synchronize the beginning of some computation.
* [BarrierWaitResult](struct.barrierwaitresult "struct std::sync::BarrierWaitResult")
A `BarrierWaitResult` is returned by [`Barrier::wait()`](struct.barrier#method.wait "method std::sync::Barrier::wait") when all threads in the [`Barrier`](struct.barrier "struct std::sync::Barrier") have rendezvoused.
* [Condvar](struct.condvar "struct std::sync::Condvar")
A Condition Variable
* [Mutex](struct.mutex "struct std::sync::Mutex")
A mutual exclusion primitive useful for protecting shared data
* [MutexGuard](struct.mutexguard "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](struct.once "struct std::sync::Once")
A synchronization primitive which can be used to run a one-time global initialization. Useful for one-time initialization for FFI or related functionality. This type can only be constructed with [`Once::new()`](struct.once#method.new "associated function std::sync::Once::new").
* [OnceLock](struct.oncelock "struct std::sync::OnceLock")
A synchronization primitive which can be written to only once.
* [OnceState](struct.oncestate "struct std::sync::OnceState")
State yielded to [`Once::call_once_force()`](struct.once#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`](struct.once "struct std::sync::Once").
* [PoisonError](struct.poisonerror "struct std::sync::PoisonError")
A type of error which can be returned whenever a lock is acquired.
* [RwLock](struct.rwlock "struct std::sync::RwLock")
A reader-writer lock
* [RwLockReadGuard](struct.rwlockreadguard "struct std::sync::RwLockReadGuard")
RAII structure used to release the shared read access of a lock when dropped.
* [RwLockWriteGuard](struct.rwlockwriteguard "struct std::sync::RwLockWriteGuard")
RAII structure used to release the exclusive write access of a lock when dropped.
* [WaitTimeoutResult](struct.waittimeoutresult "struct std::sync::WaitTimeoutResult")
A type indicating whether a timed wait on a condition variable returned due to a time out or not.
* [Weak](struct.weak "struct std::sync::Weak")

`Weak` is a version of [`Arc`](struct.arc "struct std::sync::Arc") that holds a non-owning reference to the managed allocation. The allocation is accessed by calling [`upgrade`](struct.weak#method.upgrade "method std::sync::Weak::upgrade") on the `Weak` pointer, which returns an `[Option](../option/enum.option "enum std::option::Option")<[Arc](struct.arc "struct std::sync::Arc")<T>>`.


Enums
-----


* [TryLockError](enum.trylockerror "enum std::sync::TryLockError")
An enumeration of possible errors associated with a [`TryLockResult`](type.trylockresult "type std::sync::TryLockResult") which can occur while trying to acquire a lock, from the [`try_lock`](struct.mutex#method.try_lock "method std::sync::Mutex::try_lock") method on a [`Mutex`](struct.mutex "struct std::sync::Mutex") or the [`try_read`](struct.rwlock#method.try_read "method std::sync::RwLock::try_read") and [`try_write`](struct.rwlock#method.try_write "method std::sync::RwLock::try_write") methods on an [`RwLock`](struct.rwlock "struct std::sync::RwLock").


Constants
---------


* [ONCE\_INIT](constant.once_init "constant std::sync::ONCE_INIT")Deprecated

Initialization value for static [`Once`](struct.once "struct std::sync::Once") values.


Type Definitions
----------------


* [LockResult](type.lockresult "type std::sync::LockResult")
A type alias for the result of a lock method which can be poisoned.
* [TryLockResult](type.trylockresult "type std::sync::TryLockResult")
A type alias for the result of a nonblocking locking method.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/sync/index.html>

Module std::sync::mpsc
======================


Multi-producer, single-consumer FIFO queue communication primitives.

 This module provides message-based communication over channels, concretely defined among three types:

 * [`Sender`](struct.sender "struct std::sync::mpsc::Sender")
* [`SyncSender`](struct.syncsender "struct std::sync::mpsc::SyncSender")
* [`Receiver`](struct.receiver "struct std::sync::mpsc::Receiver")

 A [`Sender`](struct.sender "struct std::sync::mpsc::Sender") or [`SyncSender`](struct.syncsender "struct std::sync::mpsc::SyncSender") is used to send data to a [`Receiver`](struct.receiver "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`](fn.channel "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`](fn.sync_channel "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.

 ### Disconnection

 The send and receive operations on channels will all return a [`Result`](../../result/enum.result "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`](../../result/enum.result#variant.Err "variant std::result::Result::Err") will be returned. Many applications will continue to [`unwrap`](../../result/enum.result#method.unwrap "method std::result::Result::unwrap") the results returned from this module, instigating a propagation of failure among threads if one unexpectedly dies.

 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);
```
 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);
}
```
 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::<i32>();
drop(tx);
assert!(rx.recv().is_err());
```
 Synchronous channels:

 
```
use std::thread;
use std::sync::mpsc::sync_channel;

let (tx, rx) = sync_channel::<i32>(0);
thread::spawn(move|| {
    // This will wait for the parent thread to start receiving
    tx.send(53).unwrap();
});
rx.recv().unwrap();
```
 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");
```
 Structs
-------


* [IntoIter](struct.intoiter "struct std::sync::mpsc::IntoIter")
An owning iterator over messages on a [`Receiver`](struct.receiver "struct std::sync::mpsc::Receiver"), created by [`into_iter`](struct.receiver#method.into_iter "method std::sync::mpsc::Receiver::into_iter").
* [Iter](struct.iter "struct std::sync::mpsc::Iter")
An iterator over messages on a [`Receiver`](struct.receiver "struct std::sync::mpsc::Receiver"), created by [`iter`](struct.receiver#method.iter "method std::sync::mpsc::Receiver::iter").
* [Receiver](struct.receiver "struct std::sync::mpsc::Receiver")
The receiving half of Rust’s [`channel`](fn.channel "fn std::sync::mpsc::channel") (or [`sync_channel`](fn.sync_channel "fn std::sync::mpsc::sync_channel")) type. This half can only be owned by one thread.
* [RecvError](struct.recverror "struct std::sync::mpsc::RecvError")
An error returned from the [`recv`](struct.receiver#method.recv "method std::sync::mpsc::Receiver::recv") function on a [`Receiver`](struct.receiver "struct std::sync::mpsc::Receiver").
* [SendError](struct.senderror "struct std::sync::mpsc::SendError")
An error returned from the [`Sender::send`](struct.sender#method.send "method std::sync::mpsc::Sender::send") or [`SyncSender::send`](struct.syncsender#method.send "method std::sync::mpsc::SyncSender::send") function on **channel**s.
* [Sender](struct.sender "struct std::sync::mpsc::Sender")
The sending-half of Rust’s asynchronous [`channel`](fn.channel "fn std::sync::mpsc::channel") type. This half can only be owned by one thread, but it can be cloned to send to other threads.
* [SyncSender](struct.syncsender "struct std::sync::mpsc::SyncSender")
The sending-half of Rust’s synchronous [`sync_channel`](fn.sync_channel "fn std::sync::mpsc::sync_channel") type.
* [TryIter](struct.tryiter "struct std::sync::mpsc::TryIter")
An iterator that attempts to yield all pending values for a [`Receiver`](struct.receiver "struct std::sync::mpsc::Receiver"), created by [`try_iter`](struct.receiver#method.try_iter "method std::sync::mpsc::Receiver::try_iter").


Enums
-----


* [RecvTimeoutError](enum.recvtimeouterror "enum std::sync::mpsc::RecvTimeoutError")
This enumeration is the list of possible errors that made [`recv_timeout`](struct.receiver#method.recv_timeout "method std::sync::mpsc::Receiver::recv_timeout") unable to return data when called. This can occur with both a [`channel`](fn.channel "fn std::sync::mpsc::channel") and a [`sync_channel`](fn.sync_channel "fn std::sync::mpsc::sync_channel").
* [TryRecvError](enum.tryrecverror "enum std::sync::mpsc::TryRecvError")
This enumeration is the list of the possible reasons that [`try_recv`](struct.receiver#method.try_recv "method std::sync::mpsc::Receiver::try_recv") could not return data when called. This can occur with both a [`channel`](fn.channel "fn std::sync::mpsc::channel") and a [`sync_channel`](fn.sync_channel "fn std::sync::mpsc::sync_channel").
* [TrySendError](enum.trysenderror "enum std::sync::mpsc::TrySendError")
This enumeration is the list of the possible error outcomes for the [`try_send`](struct.syncsender#method.try_send "method std::sync::mpsc::SyncSender::try_send") method.


Functions
---------


* [channel](fn.channel "fn std::sync::mpsc::channel")
Creates a new asynchronous channel, returning the sender/receiver halves. All data sent on the [`Sender`](struct.sender "struct std::sync::mpsc::Sender") will become available on the [`Receiver`](struct.receiver "struct std::sync::mpsc::Receiver") in the same order as it was sent, and no [`send`](struct.sender#method.send "method std::sync::mpsc::Sender::send") will block the calling thread (this channel has an “infinite buffer”, unlike [`sync_channel`](fn.sync_channel "fn std::sync::mpsc::sync_channel"), which will block after its buffer limit is reached). [`recv`](struct.receiver#method.recv "method std::sync::mpsc::Receiver::recv") will block until a message is available while there is at least one [`Sender`](struct.sender "struct std::sync::mpsc::Sender") alive (including clones).
* [sync\_channel](fn.sync_channel "fn std::sync::mpsc::sync_channel")
Creates a new synchronous, bounded channel. All data sent on the [`SyncSender`](struct.syncsender "struct std::sync::mpsc::SyncSender") will become available on the [`Receiver`](struct.receiver "struct std::sync::mpsc::Receiver") in the same order as it was sent. Like asynchronous [`channel`](fn.channel "fn std::sync::mpsc::channel")s, the [`Receiver`](struct.receiver "struct std::sync::mpsc::Receiver") will block until a message becomes available. `sync_channel` differs greatly in the semantics of the sender, however.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/sync/mpsc/index.html>

Primitive Type never
====================



🔬This is a nightly-only experimental API. (`never_type` [#35121](https://github.com/rust-lang/rust/issues/35121))
The `!` type, also called “never”.

 `!` represents the type of computations which never resolve to any value at all. For example, the [`exit`](process/fn.exit "fn std::process::exit") function `fn exit(code: i32) -> !` exits the process without ever returning, and so returns `!`.

 `break`, `continue` and `return` expressions also have type `!`. For example we are allowed to write:

 
```
#![feature(never_type)]
let x: ! = {
    return 123
};
```
 Although the `let` is pointless here, it illustrates the meaning of `!`. Since `x` is never assigned a value (because `return` returns from the entire function), `x` can be given type `!`. We could also replace `return 123` with a `panic!` or a never-ending `loop` and this code would still be valid.

 A more realistic usage of `!` is in this code:

 
```
let num: u32 = match get_a_number() {
    Some(num) => num,
    None => break,
};
```
 Both match arms must produce values of type [`u32`](primitive.u32 "primitive u32"), but since `break` never produces a value at all we know it can never produce a value which isn’t a [`u32`](primitive.u32 "primitive u32"). This illustrates another behaviour of the `!` type - expressions with type `!` will coerce into any other type.

 
`!` and generics
-----------------


### Infallible errors

 The main place you’ll see `!` used explicitly is in generic code. Consider the [`FromStr`](str/trait.fromstr "trait std::str::FromStr") trait:

 
```
trait FromStr: Sized {
    type Err;
    fn from_str(s: &str) -> Result<Self, Self::Err>;
}
```
 When implementing this trait for [`String`](string/struct.string "struct std::string::String") we need to pick a type for [`Err`](result/enum.result#variant.Err "variant std::result::Result::Err"). And since converting a string into a string will never result in an error, the appropriate type is `!`. (Currently the type actually used is an enum with no variants, though this is only because `!` was added to Rust at a later date and it may change in the future.) With an [`Err`](result/enum.result#variant.Err "variant std::result::Result::Err") type of `!`, if we have to call [`String::from_str`](str/trait.fromstr#tymethod.from_str "associated function std::str::FromStr::from_str") for some reason the result will be a [`Result<String, !>`](result/enum.result "enum std::result::Result") which we can unpack like this:

 
```
#![feature(exhaustive_patterns)]
use std::str::FromStr;
let Ok(s) = String::from_str("hello");
```
 Since the [`Err`](result/enum.result#variant.Err "variant std::result::Result::Err") variant contains a `!`, it can never occur. If the `exhaustive_patterns` feature is present this means we can exhaustively match on [`Result<T, !>`](result/enum.result "enum std::result::Result") by just taking the [`Ok`](result/enum.result#variant.Ok "variant std::result::Result::Ok") variant. This illustrates another behaviour of `!` - it can be used to “delete” certain enum variants from generic types like `Result`.

 ### Infinite loops

 While [`Result<T, !>`](result/enum.result "enum std::result::Result") is very useful for removing errors, `!` can also be used to remove successes as well. If we think of [`Result<T, !>`](result/enum.result "enum std::result::Result") as “if this function returns, it has not errored,” we get a very intuitive idea of [`Result<!, E>`](result/enum.result "enum std::result::Result") as well: if the function returns, it *has* errored.

 For example, consider the case of a simple web server, which can be simplified to:

 ⓘ
```
loop {
    let (client, request) = get_request().expect("disconnected");
    let response = request.process();
    response.send(client);
}
```

 Currently, this isn’t ideal, because we simply panic whenever we fail to get a new connection. Instead, we’d like to keep track of this error, like this:

 ⓘ
```
loop {
    match get_request() {
        Err(err) => break err,
        Ok((client, request)) => {
            let response = request.process();
            response.send(client);
        },
    }
}
```

 Now, when the server disconnects, we exit the loop with an error instead of panicking. While it might be intuitive to simply return the error, we might want to wrap it in a [`Result<!, E>`](result/enum.result "enum std::result::Result") instead:

 ⓘ
```
fn server_loop() -> Result<!, ConnectionError> {
    loop {
        let (client, request) = get_request()?;
        let response = request.process();
        response.send(client);
    }
}
```

 Now, we can use `?` instead of `match`, and the return type makes a lot more sense: if the loop ever stops, it means that an error occurred. We don’t even have to wrap the loop in an `Ok` because `!` coerces to `Result<!, ConnectionError>` automatically.

 
`!` and traits
---------------

 When writing your own traits, `!` should have an `impl` whenever there is an obvious `impl` which doesn’t `panic!`. The reason is that functions returning an `impl Trait` where `!` does not have an `impl` of `Trait` cannot diverge as their only possible code path. In other words, they can’t return `!` from every code path. As an example, this code doesn’t compile:

 ⓘ
```
use std::ops::Add;

fn foo() -> impl Add<u32> {
    unimplemented!()
}
```

 But this code does:

 
```
use std::ops::Add;

fn foo() -> impl Add<u32> {
    if true {
        unimplemented!()
    } else {
        0
    }
}
```
 The reason is that, in the first example, there are many possible types that `!` could coerce to, because many types implement `Add<u32>`. However, in the second example, the `else` branch returns a `0`, which the compiler infers from the return type to be of type `u32`. Since `u32` is a concrete type, `!` can and will be coerced to it. See issue [#36375](https://github.com/rust-lang/rust/issues/36375) for more information on this quirk of `!`.

 As it turns out, though, most traits can have an `impl` for `!`. Take [`Debug`](fmt/trait.debug "trait std::fmt::Debug") for example:

 
```
#![feature(never_type)]
impl Debug for ! {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        *self
    }
}
```
 Once again we’re using `!`’s ability to coerce into any other type, in this case [`fmt::Result`](fmt/type.result "type std::fmt::Result"). Since this method takes a `&!` as an argument we know that it can never be called (because there is no value of type `!` for it to be called with). Writing `*self` essentially tells the compiler “We know that this code can never be run, so just treat the entire function body as having type [`fmt::Result`](fmt/type.result "type std::fmt::Result")”. This pattern can be used a lot when implementing traits for `!`. Generally, any trait which only has methods which take a `self` parameter should have such an impl.

 On the other hand, one trait which would not be appropriate to implement is [`Default`](default/trait.default "trait std::default::Default"):

 
```
trait Default {
    fn default() -> Self;
}
```
 Since `!` has no values, it has no default value either. It’s true that we could write an `impl` for this which simply panics, but the same is true for any type (we could `impl Default` for (eg.) [`File`](fs/struct.file "struct std::fs::File") by just making [`default()`](default/trait.default#tymethod.default "associated function std::default::Default::default") panic.)

 Trait Implementations
---------------------



[source](https://doc.rust-lang.org/src/core/clone.rs.html#197)
```
impl Clone for !
```

[source](https://doc.rust-lang.org/src/core/clone.rs.html#199)
```
fn clone(&self) -> !
```
Returns a copy of the value. [Read more](clone/trait.clone#tymethod.clone)

[source](https://doc.rust-lang.org/src/core/clone.rs.html#129)1.0.0
```
fn clone_from(&mut self, source: &Self)
```
Performs copy-assignment from `source`. [Read more](clone/trait.clone#method.clone_from)


[source](https://doc.rust-lang.org/src/core/fmt/mod.rs.html#2281)
```
impl Debug for !
```

[source](https://doc.rust-lang.org/src/core/fmt/mod.rs.html#2283)
```
fn fmt(&self, _: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter. [Read more](fmt/trait.debug#tymethod.fmt)


[source](https://doc.rust-lang.org/src/core/fmt/mod.rs.html#2289)
```
impl Display for !
```

[source](https://doc.rust-lang.org/src/core/fmt/mod.rs.html#2291)
```
fn fmt(&self, _: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter. [Read more](fmt/trait.display#tymethod.fmt)


[source](https://doc.rust-lang.org/src/core/error.rs.html#216)
```
impl Error for !
```

[source](https://doc.rust-lang.org/src/core/error.rs.html#84)1.30.0
```
fn source(&self) -> Option<&(dyn Error + 'static)>
```
The lower-level source of this error, if any. [Read more](error/trait.error#method.source)

[source](https://doc.rust-lang.org/src/core/error.rs.html#110)1.0.0
```
fn description(&self) -> &str
```

👎Deprecated since 1.42.0: use the Display impl or to\_string()
 [Read more](error/trait.error#method.description)

[source](https://doc.rust-lang.org/src/core/error.rs.html#120)1.0.0
```
fn cause(&self) -> Option<&dyn Error>
```

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
[source](https://doc.rust-lang.org/src/core/error.rs.html#194)
```
fn provide<'a>(&'a self, demand: &mut Demand<'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](error/trait.error#method.provide)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#917)1.34.0
```
impl From<!> for Infallible
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#919)
```
fn from(x: !) -> Infallible
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/num/error.rs.html#36)
```
impl From<!> for TryFromIntError
```

[source](https://doc.rust-lang.org/src/core/num/error.rs.html#38)
```
fn from(never: !) -> TryFromIntError
```
Converts to this type from the input type.

[source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#867)1.29.0
```
impl Hash for !
```

[source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#869)
```
fn hash<H>(&self, _: &mut H)
where
    H: Hasher,
```
Feeds this value into the given [`Hasher`](hash/trait.hasher "trait std::hash::Hasher"). [Read more](hash/trait.hash#tymethod.hash)

[source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#237-239)1.3.0
```
fn hash_slice<H>(data: &[Self], state: &mut H)
where
    H: Hasher,
    Self: Sized,
```
Feeds a slice of this type into the given [`Hasher`](hash/trait.hasher "trait std::hash::Hasher"). [Read more](hash/trait.hash#method.hash_slice)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#71)1.60.0
```
impl Not for !
```


```
type Output = !
```
The resulting type after applying the `!` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#75)
```
fn not(self) -> !
```
Performs the unary `!` operation. [Read more](ops/trait.not#tymethod.not)


[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1433)
```
impl Ord for !
```

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1435)
```
fn cmp(&self, _: &!) -> Ordering
```
This method returns an [`Ordering`](cmp/enum.ordering "enum std::cmp::Ordering") between `self` and `other`. [Read more](cmp/trait.ord#tymethod.cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#790-792)1.21.0
```
fn max(self, other: Self) -> Self
where
    Self: Sized,
```
Compares and returns the maximum of two values. [Read more](cmp/trait.ord#method.max)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#810-812)1.21.0
```
fn min(self, other: Self) -> Self
where
    Self: Sized,
```
Compares and returns the minimum of two values. [Read more](cmp/trait.ord#method.min)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#835-838)1.50.0
```
fn clamp(self, min: Self, max: Self) -> Self
where
    Self: Sized + PartialOrd<Self>,
```
Restrict a value to a certain interval. [Read more](cmp/trait.ord#method.clamp)


[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1414)
```
impl PartialEq<!> for !
```

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1416)
```
fn eq(&self, _: &!) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#226)1.0.0
```
fn ne(&self, other: &Rhs) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1425)
```
impl PartialOrd<!> for !
```

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1427)
```
fn partial_cmp(&self, _: &!) -> Option<Ordering>
```
This method returns an ordering between `self` and `other` values if one exists. [Read more](cmp/trait.partialord#tymethod.partial_cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1067)1.0.0
```
fn lt(&self, other: &Rhs) -> bool
```
This method tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](cmp/trait.partialord#method.lt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1084)1.0.0
```
fn le(&self, other: &Rhs) -> bool
```
This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](cmp/trait.partialord#method.le)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1100)1.0.0
```
fn gt(&self, other: &Rhs) -> bool
```
This method tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](cmp/trait.partialord#method.gt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1117)1.0.0
```
fn ge(&self, other: &Rhs) -> bool
```
This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](cmp/trait.partialord#method.ge)


[source](https://doc.rust-lang.org/src/std/process.rs.html#2250-2254)1.61.0
```
impl Termination for !
```

[source](https://doc.rust-lang.org/src/std/process.rs.html#2251-2253)
```
fn report(self) -> ExitCode
```
Is called to get the representation of the value as status code. This status code is returned to the operating system.

[source](https://doc.rust-lang.org/src/core/marker.rs.html#480)
```
impl Copy for !
```
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1422)
```
impl Eq for !
```


Blanket Implementations
-----------------------



[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#740)
```
impl<T> From<!> for T
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#741)
```
fn from(t: !) -> T
```
Converts to this type from the input type.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/primitive.never.html>

Primitive Type bool
===================


The boolean type.

 The `bool` represents a value, which could only be either [`true`](keyword.true) or [`false`](keyword.false). If you cast a `bool` into an integer, [`true`](keyword.true) will be 1 and [`false`](keyword.false) will be 0.

 Basic usage
-----------

 `bool` implements various traits, such as [`BitAnd`](ops/trait.bitand "trait std::ops::BitAnd"), [`BitOr`](ops/trait.bitor "trait std::ops::BitOr"), [`Not`](ops/trait.not "trait std::ops::Not"), etc., which allow us to perform boolean operations using `&`, `|` and `!`.

 [`if`](keyword.if) requires a `bool` value as its conditional. [`assert!`](macro.assert "macro std::assert"), which is an important macro in testing, checks whether an expression is [`true`](keyword.true) and panics if it isn’t.

 
```
let bool_val = true & false | false;
assert!(!bool_val);
```
 Examples
--------

 A trivial example of the usage of `bool`:

 
```
let praise_the_borrow_checker = true;

// using the `if` conditional
if praise_the_borrow_checker {
    println!("oh, yeah!");
} else {
    println!("what?!!");
}

// ... or, a match pattern
match praise_the_borrow_checker {
    true => println!("keep praising!"),
    false => println!("you should praise!"),
}
```
 Also, since `bool` implements the [`Copy`](marker/trait.copy "trait std::marker::Copy") trait, we don’t have to worry about the move semantics (just like the integer and float primitives).

 Now an example of `bool` cast to integer type:

 
```
assert_eq!(true as i32, 1);
assert_eq!(false as i32, 0);
```
 Implementations
---------------



[source](https://doc.rust-lang.org/src/core/bool.rs.html#3)
```
impl bool
```

[source](https://doc.rust-lang.org/src/core/bool.rs.html#33)1.62.0
```
pub fn then_some<T>(self, t: T) -> Option<T>
```

Returns `Some(t)` if the `bool` is [`true`](keyword.true), or `None` otherwise.

 Arguments passed to `then_some` are eagerly evaluated; if you are passing the result of a function call, it is recommended to use [`then`](primitive.bool#method.then "method bool::then"), which is lazily evaluated.

 ##### Examples

 
```
assert_eq!(false.then_some(0), None);
assert_eq!(true.then_some(0), Some(0));
```
 
```
let mut a = 0;
let mut function_with_side_effects = || { a += 1; };

true.then_some(function_with_side_effects());
false.then_some(function_with_side_effects());

// `a` is incremented twice because the value passed to `then_some` is
// evaluated eagerly.
assert_eq!(a, 2);
```
 
[source](https://doc.rust-lang.org/src/core/bool.rs.html#59)1.50.0
```
pub fn then<T, F>(self, f: F) -> Option<T>
where
    F: FnOnce() -> T,
```

Returns `Some(f())` if the `bool` is [`true`](keyword.true), or `None` otherwise.

 ##### Examples

 
```
assert_eq!(false.then(|| 0), None);
assert_eq!(true.then(|| 0), Some(0));
```
 
```
let mut a = 0;

true.then(|| { a += 1; });
false.then(|| { a += 1; });

// `a` is incremented once because the closure is evaluated lazily by
// `then`.
assert_eq!(a, 1);
```
 


Trait Implementations
---------------------



[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#178)
```
impl BitAnd<&bool> for &bool
```


```
type Output = <bool as BitAnd<bool>>::Output
```
The resulting type after applying the `&` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#178)
```
fn bitand(self, other: &bool) -> <bool as BitAnd<bool>>::Output
```
Performs the `&` operation. [Read more](ops/trait.bitand#tymethod.bitand)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#178)
```
impl BitAnd<&bool> for bool
```


```
type Output = <bool as BitAnd<bool>>::Output
```
The resulting type after applying the `&` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#178)
```
fn bitand(self, other: &bool) -> <bool as BitAnd<bool>>::Output
```
Performs the `&` operation. [Read more](ops/trait.bitand#tymethod.bitand)


[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/masks.rs.html#363)
```
impl<T, const LANES: usize> BitAnd<Mask<T, LANES>> for bool
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
```


```
type Output = Mask<T, LANES>
```
The resulting type after applying the `&` operator.
[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/masks.rs.html#371)
```
fn bitand(self, rhs: Mask<T, LANES>) -> Mask<T, LANES>
```
Performs the `&` operation. [Read more](ops/trait.bitand#tymethod.bitand)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#178)
```
impl<'a> BitAnd<bool> for &'a bool
```


```
type Output = <bool as BitAnd<bool>>::Output
```
The resulting type after applying the `&` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#178)
```
fn bitand(self, other: bool) -> <bool as BitAnd<bool>>::Output
```
Performs the `&` operation. [Read more](ops/trait.bitand#tymethod.bitand)


[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/masks.rs.html#350)
```
impl<T, const LANES: usize> BitAnd<bool> for Mask<T, LANES>
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
```


```
type Output = Mask<T, LANES>
```
The resulting type after applying the `&` operator.
[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/masks.rs.html#358)
```
fn bitand(self, rhs: bool) -> Mask<T, LANES>
```
Performs the `&` operation. [Read more](ops/trait.bitand#tymethod.bitand)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#178)
```
impl BitAnd<bool> for bool
```


```
type Output = bool
```
The resulting type after applying the `&` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#178)
```
fn bitand(self, rhs: bool) -> bool
```
Performs the `&` operation. [Read more](ops/trait.bitand#tymethod.bitand)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#726)1.22.0
```
impl BitAndAssign<&bool> for bool
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#726)
```
fn bitand_assign(&mut self, other: &bool)
```
Performs the `&=` operation. [Read more](ops/trait.bitandassign#tymethod.bitand_assign)


[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/masks.rs.html#478)
```
impl<T, const LANES: usize> BitAndAssign<bool> for Mask<T, LANES>
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
```

[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/masks.rs.html#484)
```
fn bitand_assign(&mut self, rhs: bool)
```
Performs the `&=` operation. [Read more](ops/trait.bitandassign#tymethod.bitand_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#726)1.8.0
```
impl BitAndAssign<bool> for bool
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#726)
```
fn bitand_assign(&mut self, other: bool)
```
Performs the `&=` operation. [Read more](ops/trait.bitandassign#tymethod.bitand_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#278)
```
impl BitOr<&bool> for &bool
```


```
type Output = <bool as BitOr<bool>>::Output
```
The resulting type after applying the `|` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#278)
```
fn bitor(self, other: &bool) -> <bool as BitOr<bool>>::Output
```
Performs the `|` operation. [Read more](ops/trait.bitor#tymethod.bitor)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#278)
```
impl BitOr<&bool> for bool
```


```
type Output = <bool as BitOr<bool>>::Output
```
The resulting type after applying the `|` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#278)
```
fn bitor(self, other: &bool) -> <bool as BitOr<bool>>::Output
```
Performs the `|` operation. [Read more](ops/trait.bitor#tymethod.bitor)


[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/masks.rs.html#402)
```
impl<T, const LANES: usize> BitOr<Mask<T, LANES>> for bool
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
```


```
type Output = Mask<T, LANES>
```
The resulting type after applying the `|` operator.
[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/masks.rs.html#410)
```
fn bitor(self, rhs: Mask<T, LANES>) -> Mask<T, LANES>
```
Performs the `|` operation. [Read more](ops/trait.bitor#tymethod.bitor)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#278)
```
impl<'a> BitOr<bool> for &'a bool
```


```
type Output = <bool as BitOr<bool>>::Output
```
The resulting type after applying the `|` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#278)
```
fn bitor(self, other: bool) -> <bool as BitOr<bool>>::Output
```
Performs the `|` operation. [Read more](ops/trait.bitor#tymethod.bitor)


[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/masks.rs.html#389)
```
impl<T, const LANES: usize> BitOr<bool> for Mask<T, LANES>
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
```


```
type Output = Mask<T, LANES>
```
The resulting type after applying the `|` operator.
[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/masks.rs.html#397)
```
fn bitor(self, rhs: bool) -> Mask<T, LANES>
```
Performs the `|` operation. [Read more](ops/trait.bitor#tymethod.bitor)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#278)
```
impl BitOr<bool> for bool
```


```
type Output = bool
```
The resulting type after applying the `|` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#278)
```
fn bitor(self, rhs: bool) -> bool
```
Performs the `|` operation. [Read more](ops/trait.bitor#tymethod.bitor)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#797)1.22.0
```
impl BitOrAssign<&bool> for bool
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#797)
```
fn bitor_assign(&mut self, other: &bool)
```
Performs the `|=` operation. [Read more](ops/trait.bitorassign#tymethod.bitor_assign)


[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/masks.rs.html#500)
```
impl<T, const LANES: usize> BitOrAssign<bool> for Mask<T, LANES>
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
```

[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/masks.rs.html#506)
```
fn bitor_assign(&mut self, rhs: bool)
```
Performs the `|=` operation. [Read more](ops/trait.bitorassign#tymethod.bitor_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#797)1.8.0
```
impl BitOrAssign<bool> for bool
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#797)
```
fn bitor_assign(&mut self, other: bool)
```
Performs the `|=` operation. [Read more](ops/trait.bitorassign#tymethod.bitor_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#378)
```
impl BitXor<&bool> for &bool
```


```
type Output = <bool as BitXor<bool>>::Output
```
The resulting type after applying the `^` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#378)
```
fn bitxor(self, other: &bool) -> <bool as BitXor<bool>>::Output
```
Performs the `^` operation. [Read more](ops/trait.bitxor#tymethod.bitxor)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#378)
```
impl BitXor<&bool> for bool
```


```
type Output = <bool as BitXor<bool>>::Output
```
The resulting type after applying the `^` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#378)
```
fn bitxor(self, other: &bool) -> <bool as BitXor<bool>>::Output
```
Performs the `^` operation. [Read more](ops/trait.bitxor#tymethod.bitxor)


[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/masks.rs.html#441)
```
impl<T, const LANES: usize> BitXor<Mask<T, LANES>> for bool
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
```


```
type Output = Mask<T, LANES>
```
The resulting type after applying the `^` operator.
[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/masks.rs.html#449)
```
fn bitxor(self, rhs: Mask<T, LANES>) -> <bool as BitXor<Mask<T, LANES>>>::Output
```
Performs the `^` operation. [Read more](ops/trait.bitxor#tymethod.bitxor)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#378)
```
impl<'a> BitXor<bool> for &'a bool
```


```
type Output = <bool as BitXor<bool>>::Output
```
The resulting type after applying the `^` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#378)
```
fn bitxor(self, other: bool) -> <bool as BitXor<bool>>::Output
```
Performs the `^` operation. [Read more](ops/trait.bitxor#tymethod.bitxor)


[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/masks.rs.html#428)
```
impl<T, const LANES: usize> BitXor<bool> for Mask<T, LANES>
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
```


```
type Output = Mask<T, LANES>
```
The resulting type after applying the `^` operator.
[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/masks.rs.html#436)
```
fn bitxor(self, rhs: bool) -> <Mask<T, LANES> as BitXor<bool>>::Output
```
Performs the `^` operation. [Read more](ops/trait.bitxor#tymethod.bitxor)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#378)
```
impl BitXor<bool> for bool
```


```
type Output = bool
```
The resulting type after applying the `^` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#378)
```
fn bitxor(self, other: bool) -> bool
```
Performs the `^` operation. [Read more](ops/trait.bitxor#tymethod.bitxor)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#868)1.22.0
```
impl BitXorAssign<&bool> for bool
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#868)
```
fn bitxor_assign(&mut self, other: &bool)
```
Performs the `^=` operation. [Read more](ops/trait.bitxorassign#tymethod.bitxor_assign)


[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/masks.rs.html#522)
```
impl<T, const LANES: usize> BitXorAssign<bool> for Mask<T, LANES>
where
    T: MaskElement,
    LaneCount<LANES>: SupportedLaneCount,
```

[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/masks.rs.html#528)
```
fn bitxor_assign(&mut self, rhs: bool)
```
Performs the `^=` operation. [Read more](ops/trait.bitxorassign#tymethod.bitxor_assign)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#868)1.8.0
```
impl BitXorAssign<bool> for bool
```

[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#868)
```
fn bitxor_assign(&mut self, other: bool)
```
Performs the `^=` operation. [Read more](ops/trait.bitxorassign#tymethod.bitxor_assign)


[source](https://doc.rust-lang.org/src/core/clone.rs.html#189-194)
```
impl Clone for bool
```

[source](https://doc.rust-lang.org/src/core/clone.rs.html#189-194)
```
fn clone(&self) -> bool
```
Returns a copy of the value. [Read more](clone/trait.clone#tymethod.clone)

[source](https://doc.rust-lang.org/src/core/clone.rs.html#129)
```
fn clone_from(&mut self, source: &Self)
```
Performs copy-assignment from `source`. [Read more](clone/trait.clone#method.clone_from)


[source](https://doc.rust-lang.org/src/core/fmt/mod.rs.html#2297)
```
impl Debug for bool
```

[source](https://doc.rust-lang.org/src/core/fmt/mod.rs.html#2299)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter. [Read more](fmt/trait.debug#tymethod.fmt)


[source](https://doc.rust-lang.org/src/core/default.rs.html#203)
```
impl Default for bool
```

[source](https://doc.rust-lang.org/src/core/default.rs.html#203)
```
fn default() -> bool
```

Returns the default value of `false`

 

[source](https://doc.rust-lang.org/src/core/fmt/mod.rs.html#2305)
```
impl Display for bool
```

[source](https://doc.rust-lang.org/src/core/fmt/mod.rs.html#2306)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter. [Read more](fmt/trait.display#tymethod.fmt)


[source](https://doc.rust-lang.org/src/core/sync/atomic.rs.html#1917)1.24.0
```
impl From<bool> for AtomicBool
```

[source](https://doc.rust-lang.org/src/core/sync/atomic.rs.html#1928)
```
fn from(b: bool) -> AtomicBool
```

Converts a `bool` into an `AtomicBool`.

 ##### Examples

 
```
use std::sync::atomic::AtomicBool;
let atomic_bool = AtomicBool::from(true);
assert_eq!(format!("{atomic_bool:?}"), "true")
```
 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#172)1.68.0
```
impl From<bool> for f32
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#186)
```
fn from(small: bool) -> f32
```

Converts `bool` to `f32` losslessly. The resulting value is positive `0.0` for `false` and `1.0` for `true` values.

 ##### Examples

 
```
let x: f32 = false.into();
assert_eq!(x, 0.0);
assert!(x.is_sign_positive());

let y: f32 = true.into();
assert_eq!(y, 1.0);
```
 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#191)1.68.0
```
impl From<bool> for f64
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#205)
```
fn from(small: bool) -> f64
```

Converts `bool` to `f64` losslessly. The resulting value is positive `0.0` for `false` and `1.0` for `true` values.

 ##### Examples

 
```
let x: f64 = false.into();
assert_eq!(x, 0.0);
assert!(x.is_sign_positive());

let y: f64 = true.into();
assert_eq!(y, 1.0);
```
 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#95)1.28.0
```
impl From<bool> for i128
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#95)
```
fn from(small: bool) -> i128
```

Converts a `bool` to a `i128`. The resulting value is `0` for `false` and `1` for `true` values.

 ##### Examples

 
```
assert_eq!(i128::from(true), 1);
assert_eq!(i128::from(false), 0);
```
 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#92)1.28.0
```
impl From<bool> for i16
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#92)
```
fn from(small: bool) -> i16
```

Converts a `bool` to a `i16`. The resulting value is `0` for `false` and `1` for `true` values.

 ##### Examples

 
```
assert_eq!(i16::from(true), 1);
assert_eq!(i16::from(false), 0);
```
 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#93)1.28.0
```
impl From<bool> for i32
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#93)
```
fn from(small: bool) -> i32
```

Converts a `bool` to a `i32`. The resulting value is `0` for `false` and `1` for `true` values.

 ##### Examples

 
```
assert_eq!(i32::from(true), 1);
assert_eq!(i32::from(false), 0);
```
 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#94)1.28.0
```
impl From<bool> for i64
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#94)
```
fn from(small: bool) -> i64
```

Converts a `bool` to a `i64`. The resulting value is `0` for `false` and `1` for `true` values.

 ##### Examples

 
```
assert_eq!(i64::from(true), 1);
assert_eq!(i64::from(false), 0);
```
 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#91)1.28.0
```
impl From<bool> for i8
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#91)
```
fn from(small: bool) -> i8
```

Converts a `bool` to a `i8`. The resulting value is `0` for `false` and `1` for `true` values.

 ##### Examples

 
```
assert_eq!(i8::from(true), 1);
assert_eq!(i8::from(false), 0);
```
 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#96)1.28.0
```
impl From<bool> for isize
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#96)
```
fn from(small: bool) -> isize
```

Converts a `bool` to a `isize`. The resulting value is `0` for `false` and `1` for `true` values.

 ##### Examples

 
```
assert_eq!(isize::from(true), 1);
assert_eq!(isize::from(false), 0);
```
 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#89)1.28.0
```
impl From<bool> for u128
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#89)
```
fn from(small: bool) -> u128
```

Converts a `bool` to a `u128`. The resulting value is `0` for `false` and `1` for `true` values.

 ##### Examples

 
```
assert_eq!(u128::from(true), 1);
assert_eq!(u128::from(false), 0);
```
 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#86)1.28.0
```
impl From<bool> for u16
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#86)
```
fn from(small: bool) -> u16
```

Converts a `bool` to a `u16`. The resulting value is `0` for `false` and `1` for `true` values.

 ##### Examples

 
```
assert_eq!(u16::from(true), 1);
assert_eq!(u16::from(false), 0);
```
 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#87)1.28.0
```
impl From<bool> for u32
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#87)
```
fn from(small: bool) -> u32
```

Converts a `bool` to a `u32`. The resulting value is `0` for `false` and `1` for `true` values.

 ##### Examples

 
```
assert_eq!(u32::from(true), 1);
assert_eq!(u32::from(false), 0);
```
 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#88)1.28.0
```
impl From<bool> for u64
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#88)
```
fn from(small: bool) -> u64
```

Converts a `bool` to a `u64`. The resulting value is `0` for `false` and `1` for `true` values.

 ##### Examples

 
```
assert_eq!(u64::from(true), 1);
assert_eq!(u64::from(false), 0);
```
 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#85)1.28.0
```
impl From<bool> for u8
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#85)
```
fn from(small: bool) -> u8
```

Converts a `bool` to a `u8`. The resulting value is `0` for `false` and `1` for `true` values.

 ##### Examples

 
```
assert_eq!(u8::from(true), 1);
assert_eq!(u8::from(false), 0);
```
 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#90)1.28.0
```
impl From<bool> for usize
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#90)
```
fn from(small: bool) -> usize
```

Converts a `bool` to a `usize`. The resulting value is `0` for `false` and `1` for `true` values.

 ##### Examples

 
```
assert_eq!(usize::from(true), 1);
assert_eq!(usize::from(false), 0);
```
 

[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#579)
```
impl FromStr for bool
```

[source](https://doc.rust-lang.org/src/core/str/traits.rs.html#605)
```
fn from_str(s: &str) -> Result<bool, ParseBoolError>
```

Parse a `bool` from a string.

 The only accepted values are `"true"` and `"false"`. Any other input will return an error.

 ##### Examples

 
```
use std::str::FromStr;

assert_eq!(FromStr::from_str("true"), Ok(true));
assert_eq!(FromStr::from_str("false"), Ok(false));
assert!(<bool as FromStr>::from_str("not even a boolean").is_err());
```
 Note, in many cases, the `.parse()` method on `str` is more proper.

 
```
assert_eq!("true".parse(), Ok(true));
assert_eq!("false".parse(), Ok(false));
assert!("not even a boolean".parse::<bool>().is_err());
```
 

```
type Err = ParseBoolError
```
The associated error which can be returned from parsing.

[source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#843)
```
impl Hash for bool
```

[source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#845)
```
fn hash<H>(&self, state: &mut H)
where
    H: Hasher,
```
Feeds this value into the given [`Hasher`](hash/trait.hasher "trait std::hash::Hasher"). [Read more](hash/trait.hash#tymethod.hash)

[source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#237-239)1.3.0
```
fn hash_slice<H>(data: &[Self], state: &mut H)
where
    H: Hasher,
    Self: Sized,
```
Feeds a slice of this type into the given [`Hasher`](hash/trait.hasher "trait std::hash::Hasher"). [Read more](hash/trait.hash#method.hash_slice)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#68)
```
impl Not for &bool
```


```
type Output = <bool as Not>::Output
```
The resulting type after applying the `!` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#68)
```
fn not(self) -> <bool as Not>::Output
```
Performs the unary `!` operation. [Read more](ops/trait.not#tymethod.not)


[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#68)
```
impl Not for bool
```


```
type Output = bool
```
The resulting type after applying the `!` operator.
[source](https://doc.rust-lang.org/src/core/ops/bit.rs.html#68)
```
fn not(self) -> bool
```
Performs the unary `!` operation. [Read more](ops/trait.not#tymethod.not)


[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1395)
```
impl Ord for bool
```

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1397)
```
fn cmp(&self, other: &bool) -> Ordering
```
This method returns an [`Ordering`](cmp/enum.ordering "enum std::cmp::Ordering") between `self` and `other`. [Read more](cmp/trait.ord#tymethod.cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#790-792)1.21.0
```
fn max(self, other: Self) -> Self
where
    Self: Sized,
```
Compares and returns the maximum of two values. [Read more](cmp/trait.ord#method.max)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#810-812)1.21.0
```
fn min(self, other: Self) -> Self
where
    Self: Sized,
```
Compares and returns the minimum of two values. [Read more](cmp/trait.ord#method.min)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#835-838)1.50.0
```
fn clamp(self, min: Self, max: Self) -> Self
where
    Self: Sized + PartialOrd<Self>,
```
Restrict a value to a certain interval. [Read more](cmp/trait.ord#method.clamp)


[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1298-1300)
```
impl PartialEq<bool> for bool
```

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1298-1300)
```
fn eq(&self, other: &bool) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1298-1300)
```
fn ne(&self, other: &bool) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1345)
```
impl PartialOrd<bool> for bool
```

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1347)
```
fn partial_cmp(&self, other: &bool) -> Option<Ordering>
```
This method returns an ordering between `self` and `other` values if one exists. [Read more](cmp/trait.partialord#tymethod.partial_cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1067)
```
fn lt(&self, other: &Rhs) -> bool
```
This method tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](cmp/trait.partialord#method.lt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1084)
```
fn le(&self, other: &Rhs) -> bool
```
This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](cmp/trait.partialord#method.le)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1100)
```
fn gt(&self, other: &Rhs) -> bool
```
This method tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](cmp/trait.partialord#method.gt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1117)
```
fn ge(&self, other: &Rhs) -> bool
```
This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](cmp/trait.partialord#method.ge)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2549)1.68.0
```
impl ToString for bool
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2551)
```
fn to_string(&self) -> String
```
Converts the given value to a `String`. [Read more](string/trait.tostring#tymethod.to_string)


[source](https://doc.rust-lang.org/src/core/marker.rs.html#989-1000)
```
impl ConstParamTy for bool
```
[source](https://doc.rust-lang.org/src/core/marker.rs.html#467-477)
```
impl Copy for bool
```
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1309)
```
impl Eq for bool
```
[source](https://doc.rust-lang.org/src/core/marker.rs.html#262-273)
```
impl StructuralEq for bool
```


Auto Trait Implementations
--------------------------




```
impl RefUnwindSafe for bool
```

```
impl Send for bool
```

```
impl Sync for bool
```

```
impl Unpin for bool
```

```
impl UnwindSafe for bool
```


Blanket Implementations
-----------------------



[source](https://doc.rust-lang.org/src/core/any.rs.html#200)
```
impl<T> Any for T
where
    T: 'static + ?Sized,
```

[source](https://doc.rust-lang.org/src/core/any.rs.html#201)
```
fn type_id(&self) -> TypeId
```
Gets the `TypeId` of `self`. [Read more](any/trait.any#tymethod.type_id)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#208)
```
impl<T> Borrow<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#210)
```
fn borrow(&self) -> &T
```
Immutably borrows from an owned value. [Read more](borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#216)
```
impl<T> BorrowMut<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#217)
```
fn borrow_mut(&mut self) -> &mut T
```
Mutably borrows from an owned value. [Read more](borrow/trait.borrowmut#tymethod.borrow_mut)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#723)
```
impl<T> From<T> for T
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#726)
```
fn from(t: T) -> T
```

Returns the argument unchanged.

 

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#707)
```
impl<T, U> Into<U> for T
where
    U: From<T>,
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#716)
```
fn into(self) -> U
```

Calls `U::from(self)`.

 That is, this conversion is whatever the implementation of `[From](convert/trait.from "trait std::convert::From")<T> for U` chooses to do.

 

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#82)
```
impl<T> ToOwned for T
where
    T: Clone,
```


```
type Owned = T
```
The resulting type after obtaining ownership.
[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#87)
```
fn to_owned(&self) -> T
```
Creates owned data from borrowed data, usually by cloning. [Read more](borrow/trait.toowned#tymethod.to_owned)

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#91)
```
fn clone_into(&self, target: &mut T)
```
Uses borrowed data to replace owned data, usually by cloning. [Read more](borrow/trait.toowned#method.clone_into)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2513)
```
impl<T> ToString for T
where
    T: Display + ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2519)
```
default fn to_string(&self) -> String
```
Converts the given value to a `String`. [Read more](string/trait.tostring#tymethod.to_string)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#763)
```
impl<T, U> TryFrom<U> for T
where
    U: Into<T>,
```


```
type Error = Infallible
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#770)
```
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#748)
```
impl<T, U> TryInto<U> for T
where
    U: TryFrom<T>,
```


```
type Error = <U as TryFrom<T>>::Error
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#755)
```
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
```
Performs the conversion.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/primitive.bool.html>

Primitive Type char
===================


A character type.

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

 This documentation describes a number of methods and trait implementations on the `char` type. For technical reasons, there is additional, separate documentation in [the `std::char` module](char/index) as well.

 Validity
--------

 A `char` is a ‘[Unicode scalar value](https://www.unicode.org/glossary/#unicode_scalar_value)’, which is any ‘[Unicode code point](https://www.unicode.org/glossary/#code_point)’ other than a [surrogate code point](https://www.unicode.org/glossary/#surrogate_code_point). This has a fixed numerical definition: code points are in the range 0 to 0x10FFFF, inclusive. Surrogate code points, used by UTF-16, are in the range 0xD800 to 0xDFFF.

 No `char` may be constructed, whether as a literal or at runtime, that is not a Unicode scalar value:

 ⓘ
```
// Each of these is a compiler error
['\u{D800}', '\u{DFFF}', '\u{110000}'];
```

 ⓘ
```
// Panics; from_u32 returns None.
char::from_u32(0xDE01).unwrap();
```

 
```
// Undefined behaviour
unsafe { char::from_u32_unchecked(0x110000) };
```
 USVs are also the exact set of values that may be encoded in UTF-8. Because `char` values are USVs and `str` values are valid UTF-8, it is safe to store any `char` in a `str` or read any character from a `str` as a `char`.

 The gap in valid `char` values is understood by the compiler, so in the below example the two ranges are understood to cover the whole range of possible `char` values and there is no error for a [non-exhaustive match](../book/ch06-02-match#matches-are-exhaustive).

 
```
let c: char = 'a';
match c {
    '\0' ..= '\u{D7FF}' => false,
    '\u{E000}' ..= '\u{10FFFF}' => true,
};
```
 All USVs are valid `char` values, but not all of them represent a real character. Many USVs are not currently assigned to a character, but may be in the future (“reserved”); some will never be a character (“noncharacters”); and some may be given different meanings by different users (“private use”).

 Representation
--------------

 `char` is always four bytes in size. This is a different representation than a given character would have as part of a [`String`](string/struct.string "struct std::string::String"). For example:

 
```
let v = vec!['h', 'e', 'l', 'l', 'o'];

// five elements times four bytes for each element
assert_eq!(20, v.len() * std::mem::size_of::<char>());

let s = String::from("hello");

// five elements times one byte per element
assert_eq!(5, s.len() * std::mem::size_of::<u8>());
```
 As always, remember that a human intuition for ‘character’ might not map to Unicode’s definitions. For example, despite looking similar, the ‘é’ character is one Unicode code point while ‘é’ is two Unicode code points:

 
```
let mut chars = "é".chars();
// U+00e9: 'latin small letter e with acute'
assert_eq!(Some('\u{00e9}'), chars.next());
assert_eq!(None, chars.next());

let mut chars = "é".chars();
// U+0065: 'latin small letter e'
assert_eq!(Some('\u{0065}'), chars.next());
// U+0301: 'combining acute accent'
assert_eq!(Some('\u{0301}'), chars.next());
assert_eq!(None, chars.next());
```
 This means that the contents of the first string above *will* fit into a `char` while the contents of the second string *will not*. Trying to create a `char` literal with the contents of the second string gives an error:

 
```
error: character literal may only contain one codepoint: 'é'
let c = 'é';
        ^^^

```
 Another implication of the 4-byte fixed size of a `char` is that per-`char` processing can end up using a lot more memory:

 
```
let s = String::from("love: ❤️");
let v: Vec<char> = s.chars().collect();

assert_eq!(12, std::mem::size_of_val(&s[..]));
assert_eq!(32, std::mem::size_of_val(&v[..]));
```
 Implementations
---------------



[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#11)
```
impl char
```

[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#26)1.52.0
```
pub const MAX: char = '\u{10ffff}'
```

The highest valid code point a `char` can have, `'\u{10FFFF}'`.

 ##### Examples

 
```
let c: char = something_which_returns_char();
assert!(c <= char::MAX);

let value_at_max = char::MAX as u32;
assert_eq!(char::from_u32(value_at_max), Some('\u{10FFFF}'));
assert_eq!(char::from_u32(value_at_max + 1), None);
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#34)1.52.0
```
pub const REPLACEMENT_CHARACTER: char = '�'
```

`U+FFFD REPLACEMENT CHARACTER` (�) is used in Unicode to represent a decoding error.

 It can occur, for example, when giving ill-formed UTF-8 bytes to [`String::from_utf8_lossy`](string/struct.string#method.from_utf8_lossy).

 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#47)1.52.0
```
pub const UNICODE_VERSION: (u8, u8, u8) = crate::unicode::UNICODE_VERSION
```

The version of [Unicode](https://www.unicode.org/) that the Unicode parts of `char` and `str` methods are based on.

 New versions of Unicode are released regularly and subsequently all methods in the standard library depending on Unicode are updated. Therefore the behavior of some `char` and `str` methods and the value of this constant changes over time. This is *not* considered to be a breaking change.

 The version numbering scheme is explained in [Unicode 11.0 or later, Section 3.1 Versions of the Unicode Standard](https://www.unicode.org/versions/Unicode11.0.0/ch03.pdf#page=4).

 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#93)1.52.0
```
pub fn decode_utf16<I>(iter: I) -> DecodeUtf16<<I as IntoIterator>::IntoIter> ⓘ
where
    I: IntoIterator<Item = u16>,
```

Creates an iterator over the UTF-16 encoded code points in `iter`, returning unpaired surrogates as `Err`s.

 ##### Examples

 Basic usage:

 
```
// 𝄞mus<invalid>ic<invalid>
let v = [
    0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834,
];

assert_eq!(
    char::decode_utf16(v)
        .map(|r| r.map_err(|e| e.unpaired_surrogate()))
        .collect::<Vec<_>>(),
    vec![
        Ok('𝄞'),
        Ok('m'), Ok('u'), Ok('s'),
        Err(0xDD1E),
        Ok('i'), Ok('c'),
        Err(0xD834)
    ]
);
```
 A lossy decoder can be obtained by replacing `Err` results with the replacement character:

 
```
// 𝄞mus<invalid>ic<invalid>
let v = [
    0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834,
];

assert_eq!(
    char::decode_utf16(v)
       .map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER))
       .collect::<String>(),
    "𝄞mus�ic�"
);
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#139)1.52.0 (const: 1.67.0)
```
pub const fn from_u32(i: u32) -> Option<char>
```

Converts a `u32` to a `char`.

 Note that all `char`s are valid [`u32`](primitive.u32 "primitive u32")s, and can be cast to one with [`as`](keyword.as):

 
```
let c = '💯';
let i = c as u32;

assert_eq!(128175, i);
```
 However, the reverse is not true: not all valid [`u32`](primitive.u32 "primitive u32")s are valid `char`s. `from_u32()` will return `None` if the input is not a valid value for a `char`.

 For an unsafe version of this function which ignores these checks, see [`from_u32_unchecked`](#method.from_u32_unchecked).

 ##### Examples

 Basic usage:

 
```
let c = char::from_u32(0x2764);

assert_eq!(Some('❤'), c);
```
 Returning `None` when the input is not a valid `char`:

 
```
let c = char::from_u32(0x110000);

assert_eq!(None, c);
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#180)1.52.0 (const: [unstable](https://github.com/rust-lang/rust/issues/89259 "Tracking issue for const_char_from_u32_unchecked"))
```
pub unsafe fn from_u32_unchecked(i: u32) -> char
```

Converts a `u32` to a `char`, ignoring validity.

 Note that all `char`s are valid [`u32`](primitive.u32 "primitive u32")s, and can be cast to one with `as`:

 
```
let c = '💯';
let i = c as u32;

assert_eq!(128175, i);
```
 However, the reverse is not true: not all valid [`u32`](primitive.u32 "primitive u32")s are valid `char`s. `from_u32_unchecked()` will ignore this, and blindly cast to `char`, possibly creating an invalid one.

 ##### Safety

 This function is unsafe, as it may construct invalid `char` values.

 For a safe version of this function, see the [`from_u32`](#method.from_u32) function.

 ##### Examples

 Basic usage:

 
```
let c = unsafe { char::from_u32_unchecked(0x2764) };

assert_eq!('❤', c);
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#232)1.52.0 (const: 1.67.0)
```
pub const fn from_digit(num: u32, radix: u32) -> Option<char>
```

Converts a digit in the given radix to a `char`.

 A ‘radix’ here is sometimes also called a ‘base’. A radix of two indicates a binary number, a radix of ten, decimal, and a radix of sixteen, hexadecimal, to give some common values. Arbitrary radices are supported.

 `from_digit()` will return `None` if the input is not a digit in the given radix.

 ##### Panics

 Panics if given a radix larger than 36.

 ##### Examples

 Basic usage:

 
```
let c = char::from_digit(4, 10);

assert_eq!(Some('4'), c);

// Decimal 11 is a single digit in base 16
let c = char::from_digit(11, 16);

assert_eq!(Some('b'), c);
```
 Returning `None` when the input is not a digit:

 
```
let c = char::from_digit(20, 10);

assert_eq!(None, c);
```
 Passing a large radix, causing a panic:

 ⓘ
```
// this panics
let _c = char::from_digit(1, 37);
```

 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#278)
```
pub fn is_digit(self, radix: u32) -> bool
```

Checks if a `char` is a digit in the given radix.

 A ‘radix’ here is sometimes also called a ‘base’. A radix of two indicates a binary number, a radix of ten, decimal, and a radix of sixteen, hexadecimal, to give some common values. Arbitrary radices are supported.

 Compared to [`is_numeric()`](#method.is_numeric), this function only recognizes the characters `0-9`, `a-z` and `A-Z`.

 ‘Digit’ is defined to be only the following characters:

 * `0-9`
* `a-z`
* `A-Z`

 For a more comprehensive understanding of ‘digit’, see [`is_numeric()`](#method.is_numeric).

 ##### Panics

 Panics if given a radix larger than 36.

 ##### Examples

 Basic usage:

 
```
assert!('1'.is_digit(10));
assert!('f'.is_digit(16));
assert!(!'f'.is_digit(10));
```
 Passing a large radix, causing a panic:

 ⓘ
```
// this panics
'1'.is_digit(37);
```

 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#330)const: 1.67.0
```
pub const fn to_digit(self, radix: u32) -> Option<u32>
```

Converts a `char` to a digit in the given radix.

 A ‘radix’ here is sometimes also called a ‘base’. A radix of two indicates a binary number, a radix of ten, decimal, and a radix of sixteen, hexadecimal, to give some common values. Arbitrary radices are supported.

 ‘Digit’ is defined to be only the following characters:

 * `0-9`
* `a-z`
* `A-Z`

 ##### Errors

 Returns `None` if the `char` does not refer to a digit in the given radix.

 ##### Panics

 Panics if given a radix larger than 36.

 ##### Examples

 Basic usage:

 
```
assert_eq!('1'.to_digit(10), Some(1));
assert_eq!('f'.to_digit(16), Some(15));
```
 Passing a non-digit results in failure:

 
```
assert_eq!('f'.to_digit(10), None);
assert_eq!('z'.to_digit(16), None);
```
 Passing a large radix, causing a panic:

 ⓘ
```
// this panics
let _ = '1'.to_digit(37);
```

 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#383)
```
pub fn escape_unicode(self) -> EscapeUnicode ⓘ
```

Returns an iterator that yields the hexadecimal Unicode escape of a character as `char`s.

 This will escape characters with the Rust syntax of the form `\u{NNNNNN}` where `NNNNNN` is a hexadecimal representation.

 ##### Examples

 As an iterator:

 
```
for c in '❤'.escape_unicode() {
    print!("{c}");
}
println!();
```
 Using `println!` directly:

 
```
println!("{}", '❤'.escape_unicode());
```
 Both are equivalent to:

 
```
println!("\\u{{2764}}");
```
 Using [`to_string`](string/trait.tostring#tymethod.to_string):

 
```
assert_eq!('❤'.escape_unicode().to_string(), "\\u{2764}");
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#448)1.20.0
```
pub fn escape_debug(self) -> EscapeDebug ⓘ
```

Returns an iterator that yields the literal escape code of a character as `char`s.

 This will escape the characters similar to the [`Debug`](fmt/trait.debug "trait std::fmt::Debug") implementations of `str` or `char`.

 ##### Examples

 As an iterator:

 
```
for c in '\n'.escape_debug() {
    print!("{c}");
}
println!();
```
 Using `println!` directly:

 
```
println!("{}", '\n'.escape_debug());
```
 Both are equivalent to:

 
```
println!("\\n");
```
 Using [`to_string`](string/trait.tostring#tymethod.to_string):

 
```
assert_eq!('\n'.escape_debug().to_string(), "\\n");
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#504)
```
pub fn escape_default(self) -> EscapeDefault ⓘ
```

Returns an iterator that yields the literal escape code of a character as `char`s.

 The default is chosen with a bias toward producing literals that are legal in a variety of languages, including C++11 and similar C-family languages. The exact rules are:

 * Tab is escaped as `\t`.
* Carriage return is escaped as `\r`.
* Line feed is escaped as `\n`.
* Single quote is escaped as `\'`.
* Double quote is escaped as `\"`.
* Backslash is escaped as `\\`.
* Any character in the ‘printable ASCII’ range `0x20` .. `0x7e` inclusive is not escaped.
* All other characters are given hexadecimal Unicode escapes; see [`escape_unicode`](#method.escape_unicode).

 ##### Examples

 As an iterator:

 
```
for c in '"'.escape_default() {
    print!("{c}");
}
println!();
```
 Using `println!` directly:

 
```
println!("{}", '"'.escape_default());
```
 Both are equivalent to:

 
```
println!("\\\"");
```
 Using [`to_string`](string/trait.tostring#tymethod.to_string):

 
```
assert_eq!('"'.escape_default().to_string(), "\\\"");
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#563)const: 1.52.0
```
pub const fn len_utf8(self) -> usize
```

Returns the number of bytes this `char` would need if encoded in UTF-8.

 That number of bytes is always between 1 and 4, inclusive.

 ##### Examples

 Basic usage:

 
```
let len = 'A'.len_utf8();
assert_eq!(len, 1);

let len = 'ß'.len_utf8();
assert_eq!(len, 2);

let len = 'ℝ'.len_utf8();
assert_eq!(len, 3);

let len = '💣'.len_utf8();
assert_eq!(len, 4);
```
 The `&str` type guarantees that its contents are UTF-8, and so we can compare the length it would take if each code point was represented as a `char` vs in the `&str` itself:

 
```
// as chars
let eastern = '東';
let capital = '京';

// both can be represented as three bytes
assert_eq!(3, eastern.len_utf8());
assert_eq!(3, capital.len_utf8());

// as a &str, these two are encoded in UTF-8
let tokyo = "東京";

let len = eastern.len_utf8() + capital.len_utf8();

// we can see that they take six bytes total...
assert_eq!(6, tokyo.len());

// ... just like the &str
assert_eq!(len, tokyo.len());
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#594)const: 1.52.0
```
pub const fn len_utf16(self) -> usize
```

Returns the number of 16-bit code units this `char` would need if encoded in UTF-16.

 That number of code units is always either 1 or 2, for unicode scalar values in the [basic multilingual plane](http://www.unicode.org/glossary/#basic_multilingual_plane) or [supplementary planes](http://www.unicode.org/glossary/#supplementary_planes) respectively.

 See the documentation for [`len_utf8()`](#method.len_utf8) for more explanation of this concept. This function is a mirror, but for UTF-16 instead of UTF-8.

 ##### Examples

 Basic usage:

 
```
let n = 'ß'.len_utf16();
assert_eq!(n, 1);

let len = '💣'.len_utf16();
assert_eq!(len, 2);
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#631)1.15.0
```
pub fn encode_utf8(self, dst: &mut [u8]) -> &mut str
```

Encodes this character as UTF-8 into the provided byte buffer, and then returns the subslice of the buffer that contains the encoded character.

 ##### Panics

 Panics if the buffer is not large enough. A buffer of length four is large enough to encode any `char`.

 ##### Examples

 In both of these examples, ‘ß’ takes two bytes to encode.

 
```
let mut b = [0; 2];

let result = 'ß'.encode_utf8(&mut b);

assert_eq!(result, "ß");

assert_eq!(result.len(), 2);
```
 A buffer that’s too small:

 ⓘ
```
let mut b = [0; 1];

// this panics
'ß'.encode_utf8(&mut b);
```

 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#666)1.15.0
```
pub fn encode_utf16(self, dst: &mut [u16]) -> &mut [u16]
```

Encodes this character as UTF-16 into the provided `u16` buffer, and then returns the subslice of the buffer that contains the encoded character.

 ##### Panics

 Panics if the buffer is not large enough. A buffer of length 2 is large enough to encode any `char`.

 ##### Examples

 In both of these examples, ‘𝕊’ takes two `u16`s to encode.

 
```
let mut b = [0; 2];

let result = '𝕊'.encode_utf16(&mut b);

assert_eq!(result.len(), 2);
```
 A buffer that’s too small:

 ⓘ
```
let mut b = [0; 1];

// this panics
'𝕊'.encode_utf16(&mut b);
```

 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#694)
```
pub fn is_alphabetic(self) -> bool
```

Returns `true` if this `char` has the `Alphabetic` property.

 `Alphabetic` is described in Chapter 4 (Character Properties) of the [Unicode Standard](https://www.unicode.org/versions/latest/) and specified in the [Unicode Character Database](https://www.unicode.org/reports/tr44/) [`DerivedCoreProperties.txt`](https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt).

 ##### Examples

 Basic usage:

 
```
assert!('a'.is_alphabetic());
assert!('京'.is_alphabetic());

let c = '💝';
// love is many things, but it is not alphabetic
assert!(!c.is_alphabetic());
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#736)const: [unstable](https://github.com/rust-lang/rust/issues/101400 "Tracking issue for const_unicode_case_lookup")
```
pub fn is_lowercase(self) -> bool
```

Returns `true` if this `char` has the `Lowercase` property.

 `Lowercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard](https://www.unicode.org/versions/latest/) and specified in the [Unicode Character Database](https://www.unicode.org/reports/tr44/) [`DerivedCoreProperties.txt`](https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt).

 ##### Examples

 Basic usage:

 
```
assert!('a'.is_lowercase());
assert!('δ'.is_lowercase());
assert!(!'A'.is_lowercase());
assert!(!'Δ'.is_lowercase());

// The various Chinese scripts and punctuation do not have case, and so:
assert!(!'中'.is_lowercase());
assert!(!' '.is_lowercase());
```
 In a const context:

 
```
#![feature(const_unicode_case_lookup)]
const CAPITAL_DELTA_IS_LOWERCASE: bool = 'Δ'.is_lowercase();
assert!(!CAPITAL_DELTA_IS_LOWERCASE);
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#778)const: [unstable](https://github.com/rust-lang/rust/issues/101400 "Tracking issue for const_unicode_case_lookup")
```
pub fn is_uppercase(self) -> bool
```

Returns `true` if this `char` has the `Uppercase` property.

 `Uppercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard](https://www.unicode.org/versions/latest/) and specified in the [Unicode Character Database](https://www.unicode.org/reports/tr44/) [`DerivedCoreProperties.txt`](https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt).

 ##### Examples

 Basic usage:

 
```
assert!(!'a'.is_uppercase());
assert!(!'δ'.is_uppercase());
assert!('A'.is_uppercase());
assert!('Δ'.is_uppercase());

// The various Chinese scripts and punctuation do not have case, and so:
assert!(!'中'.is_uppercase());
assert!(!' '.is_uppercase());
```
 In a const context:

 
```
#![feature(const_unicode_case_lookup)]
const CAPITAL_DELTA_IS_UPPERCASE: bool = 'Δ'.is_uppercase();
assert!(CAPITAL_DELTA_IS_UPPERCASE);
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#810)
```
pub fn is_whitespace(self) -> bool
```

Returns `true` if this `char` has the `White_Space` property.

 `White_Space` is specified in the [Unicode Character Database](https://www.unicode.org/reports/tr44/) [`PropList.txt`](https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt).

 ##### Examples

 Basic usage:

 
```
assert!(' '.is_whitespace());

// line break
assert!('\n'.is_whitespace());

// a non-breaking space
assert!('\u{A0}'.is_whitespace());

assert!(!'越'.is_whitespace());
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#839)
```
pub fn is_alphanumeric(self) -> bool
```

Returns `true` if this `char` satisfies either [`is_alphabetic()`](#method.is_alphabetic) or [`is_numeric()`](#method.is_numeric).

 ##### Examples

 Basic usage:

 
```
assert!('٣'.is_alphanumeric());
assert!('7'.is_alphanumeric());
assert!('৬'.is_alphanumeric());
assert!('¾'.is_alphanumeric());
assert!('①'.is_alphanumeric());
assert!('K'.is_alphanumeric());
assert!('و'.is_alphanumeric());
assert!('藏'.is_alphanumeric());
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#865)
```
pub fn is_control(self) -> bool
```

Returns `true` if this `char` has the general category for control codes.

 Control codes (code points with the general category of `Cc`) are described in Chapter 4 (Character Properties) of the [Unicode Standard](https://www.unicode.org/versions/latest/) and specified in the [Unicode Character Database](https://www.unicode.org/reports/tr44/) [`UnicodeData.txt`](https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt).

 ##### Examples

 Basic usage:

 
```
// U+009C, STRING TERMINATOR
assert!(''.is_control());
assert!(!'q'.is_control());
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#920)
```
pub fn is_numeric(self) -> bool
```

Returns `true` if this `char` has one of the general categories for numbers.

 The general categories for numbers (`Nd` for decimal digits, `Nl` for letter-like numeric characters, and `No` for other numeric characters) are specified in the [Unicode Character Database](https://www.unicode.org/reports/tr44/) [`UnicodeData.txt`](https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt).

 This method doesn’t cover everything that could be considered a number, e.g. ideographic numbers like ‘三’. If you want everything including characters with overlapping purposes then you might want to use a unicode or language-processing library that exposes the appropriate character properties instead of looking at the unicode categories.

 If you want to parse ASCII decimal digits (0-9) or ASCII base-N, use `is_ascii_digit` or `is_digit` instead.

 ##### Examples

 Basic usage:

 
```
assert!('٣'.is_numeric());
assert!('7'.is_numeric());
assert!('৬'.is_numeric());
assert!('¾'.is_numeric());
assert!('①'.is_numeric());
assert!(!'K'.is_numeric());
assert!(!'و'.is_numeric());
assert!(!'藏'.is_numeric());
assert!(!'三'.is_numeric());
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#990)
```
pub fn to_lowercase(self) -> ToLowercase ⓘ
```

Returns an iterator that yields the lowercase mapping of this `char` as one or more `char`s.

 If this `char` does not have a lowercase mapping, the iterator yields the same `char`.

 If this `char` has a one-to-one lowercase mapping given by the [Unicode Character Database](https://www.unicode.org/reports/tr44/) [`UnicodeData.txt`](https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt), the iterator yields that `char`.

 If this `char` requires special considerations (e.g. multiple `char`s) the iterator yields the `char`(s) given by [`SpecialCasing.txt`](https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt).

 This operation performs an unconditional mapping without tailoring. That is, the conversion is independent of context and language.

 In the [Unicode Standard](https://www.unicode.org/versions/latest/), Chapter 4 (Character Properties) discusses case mapping in general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.

 ##### Examples

 As an iterator:

 
```
for c in 'İ'.to_lowercase() {
    print!("{c}");
}
println!();
```
 Using `println!` directly:

 
```
println!("{}", 'İ'.to_lowercase());
```
 Both are equivalent to:

 
```
println!("i\u{307}");
```
 Using [`to_string`](string/trait.tostring#tymethod.to_string):

 
```
assert_eq!('C'.to_lowercase().to_string(), "c");

// Sometimes the result is more than one character:
assert_eq!('İ'.to_lowercase().to_string(), "i\u{307}");

// Characters that do not have both uppercase and lowercase
// convert into themselves.
assert_eq!('山'.to_lowercase().to_string(), "山");
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#1082)
```
pub fn to_uppercase(self) -> ToUppercase ⓘ
```

Returns an iterator that yields the uppercase mapping of this `char` as one or more `char`s.

 If this `char` does not have an uppercase mapping, the iterator yields the same `char`.

 If this `char` has a one-to-one uppercase mapping given by the [Unicode Character Database](https://www.unicode.org/reports/tr44/) [`UnicodeData.txt`](https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt), the iterator yields that `char`.

 If this `char` requires special considerations (e.g. multiple `char`s) the iterator yields the `char`(s) given by [`SpecialCasing.txt`](https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt).

 This operation performs an unconditional mapping without tailoring. That is, the conversion is independent of context and language.

 In the [Unicode Standard](https://www.unicode.org/versions/latest/), Chapter 4 (Character Properties) discusses case mapping in general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.

 ##### Examples

 As an iterator:

 
```
for c in 'ß'.to_uppercase() {
    print!("{c}");
}
println!();
```
 Using `println!` directly:

 
```
println!("{}", 'ß'.to_uppercase());
```
 Both are equivalent to:

 
```
println!("SS");
```
 Using [`to_string`](string/trait.tostring#tymethod.to_string):

 
```
assert_eq!('c'.to_uppercase().to_string(), "C");

// Sometimes the result is more than one character:
assert_eq!('ß'.to_uppercase().to_string(), "SS");

// Characters that do not have both uppercase and lowercase
// convert into themselves.
assert_eq!('山'.to_uppercase().to_string(), "山");
```
 ##### Note on locale

 In Turkish, the equivalent of ‘i’ in Latin has five forms instead of two:

 * ‘Dotless’: I / ı, sometimes written ï
* ‘Dotted’: İ / i

 Note that the lowercase dotted ‘i’ is the same as the Latin. Therefore:

 
```
let upper_i = 'i'.to_uppercase().to_string();
```
 The value of `upper_i` here relies on the language of the text: if we’re in `en-US`, it should be `"I"`, but if we’re in `tr_TR`, it should be `"İ"`. `to_uppercase()` does not take this into account, and so:

 
```
let upper_i = 'i'.to_uppercase().to_string();

assert_eq!(upper_i, "I");
```
 holds across languages.

 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#1101)1.23.0 (const: 1.32.0)
```
pub const fn is_ascii(&self) -> bool
```

Checks if the value is within the ASCII range.

 ##### Examples

 
```
let ascii = 'a';
let non_ascii = '❤';

assert!(ascii.is_ascii());
assert!(!non_ascii.is_ascii());
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#1114)
```
pub const fn as_ascii(&self) -> Option<AsciiChar>
```

🔬This is a nightly-only experimental API. (`ascii_char` [#110998](https://github.com/rust-lang/rust/issues/110998))

Returns `Some` if the value is within the ASCII range, or `None` if it’s not.

 This is preferred to [`Self::is_ascii`](primitive.char#method.is_ascii "method char::is_ascii") when you’re passing the value along to something else that can take [`ascii::Char`](ascii/enum.char "enum std::ascii::Char") rather than needing to check again for itself whether the value is in ASCII.

 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#1149)1.23.0 (const: 1.52.0)
```
pub const fn to_ascii_uppercase(&self) -> char
```

Makes a copy of the value in its ASCII upper case equivalent.

 ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, but non-ASCII letters are unchanged.

 To uppercase the value in-place, use [`make_ascii_uppercase()`](#method.make_ascii_uppercase).

 To uppercase ASCII characters in addition to non-ASCII characters, use [`to_uppercase()`](#method.to_uppercase).

 ##### Examples

 
```
let ascii = 'a';
let non_ascii = '❤';

assert_eq!('A', ascii.to_ascii_uppercase());
assert_eq!('❤', non_ascii.to_ascii_uppercase());
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#1183)1.23.0 (const: 1.52.0)
```
pub const fn to_ascii_lowercase(&self) -> char
```

Makes a copy of the value in its ASCII lower case equivalent.

 ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’, but non-ASCII letters are unchanged.

 To lowercase the value in-place, use [`make_ascii_lowercase()`](#method.make_ascii_lowercase).

 To lowercase ASCII characters in addition to non-ASCII characters, use [`to_lowercase()`](#method.to_lowercase).

 ##### Examples

 
```
let ascii = 'A';
let non_ascii = '❤';

assert_eq!('a', ascii.to_ascii_lowercase());
assert_eq!('❤', non_ascii.to_ascii_lowercase());
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#1211)1.23.0 (const: 1.52.0)
```
pub const fn eq_ignore_ascii_case(&self, other: &char) -> bool
```

Checks that two values are an ASCII case-insensitive match.

 Equivalent to `[to\_ascii\_lowercase](#method.to_ascii_lowercase)(a) == [to\_ascii\_lowercase](#method.to_ascii_lowercase)(b)`.

 ##### Examples

 
```
let upper_a = 'A';
let lower_a = 'a';
let lower_z = 'z';

assert!(upper_a.eq_ignore_ascii_case(&lower_a));
assert!(upper_a.eq_ignore_ascii_case(&upper_a));
assert!(!upper_a.eq_ignore_ascii_case(&lower_z));
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#1236)1.23.0
```
pub fn make_ascii_uppercase(&mut self)
```

Converts this type to its ASCII upper case equivalent in-place.

 ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, but non-ASCII letters are unchanged.

 To return a new uppercased value without modifying the existing one, use [`to_ascii_uppercase()`](#method.to_ascii_uppercase).

 ##### Examples

 
```
let mut ascii = 'a';

ascii.make_ascii_uppercase();

assert_eq!('A', ascii);
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#1261)1.23.0
```
pub fn make_ascii_lowercase(&mut self)
```

Converts this type to its ASCII lower case equivalent in-place.

 ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’, but non-ASCII letters are unchanged.

 To return a new lowercased value without modifying the existing one, use [`to_ascii_lowercase()`](#method.to_ascii_lowercase).

 ##### Examples

 
```
let mut ascii = 'A';

ascii.make_ascii_lowercase();

assert_eq!('a', ascii);
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#1297)1.24.0 (const: 1.47.0)
```
pub const fn is_ascii_alphabetic(&self) -> bool
```

Checks if the value is an ASCII alphabetic character:

 * U+0041 ‘A’ ..= U+005A ‘Z’, or
* U+0061 ‘a’ ..= U+007A ‘z’.

 ##### Examples

 
```
let uppercase_a = 'A';
let uppercase_g = 'G';
let a = 'a';
let g = 'g';
let zero = '0';
let percent = '%';
let space = ' ';
let lf = '\n';
let esc = '\x1b';

assert!(uppercase_a.is_ascii_alphabetic());
assert!(uppercase_g.is_ascii_alphabetic());
assert!(a.is_ascii_alphabetic());
assert!(g.is_ascii_alphabetic());
assert!(!zero.is_ascii_alphabetic());
assert!(!percent.is_ascii_alphabetic());
assert!(!space.is_ascii_alphabetic());
assert!(!lf.is_ascii_alphabetic());
assert!(!esc.is_ascii_alphabetic());
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#1331)1.24.0 (const: 1.47.0)
```
pub const fn is_ascii_uppercase(&self) -> bool
```

Checks if the value is an ASCII uppercase character: U+0041 ‘A’ ..= U+005A ‘Z’.

 ##### Examples

 
```
let uppercase_a = 'A';
let uppercase_g = 'G';
let a = 'a';
let g = 'g';
let zero = '0';
let percent = '%';
let space = ' ';
let lf = '\n';
let esc = '\x1b';

assert!(uppercase_a.is_ascii_uppercase());
assert!(uppercase_g.is_ascii_uppercase());
assert!(!a.is_ascii_uppercase());
assert!(!g.is_ascii_uppercase());
assert!(!zero.is_ascii_uppercase());
assert!(!percent.is_ascii_uppercase());
assert!(!space.is_ascii_uppercase());
assert!(!lf.is_ascii_uppercase());
assert!(!esc.is_ascii_uppercase());
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#1365)1.24.0 (const: 1.47.0)
```
pub const fn is_ascii_lowercase(&self) -> bool
```

Checks if the value is an ASCII lowercase character: U+0061 ‘a’ ..= U+007A ‘z’.

 ##### Examples

 
```
let uppercase_a = 'A';
let uppercase_g = 'G';
let a = 'a';
let g = 'g';
let zero = '0';
let percent = '%';
let space = ' ';
let lf = '\n';
let esc = '\x1b';

assert!(!uppercase_a.is_ascii_lowercase());
assert!(!uppercase_g.is_ascii_lowercase());
assert!(a.is_ascii_lowercase());
assert!(g.is_ascii_lowercase());
assert!(!zero.is_ascii_lowercase());
assert!(!percent.is_ascii_lowercase());
assert!(!space.is_ascii_lowercase());
assert!(!lf.is_ascii_lowercase());
assert!(!esc.is_ascii_lowercase());
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#1402)1.24.0 (const: 1.47.0)
```
pub const fn is_ascii_alphanumeric(&self) -> bool
```

Checks if the value is an ASCII alphanumeric character:

 * U+0041 ‘A’ ..= U+005A ‘Z’, or
* U+0061 ‘a’ ..= U+007A ‘z’, or
* U+0030 ‘0’ ..= U+0039 ‘9’.

 ##### Examples

 
```
let uppercase_a = 'A';
let uppercase_g = 'G';
let a = 'a';
let g = 'g';
let zero = '0';
let percent = '%';
let space = ' ';
let lf = '\n';
let esc = '\x1b';

assert!(uppercase_a.is_ascii_alphanumeric());
assert!(uppercase_g.is_ascii_alphanumeric());
assert!(a.is_ascii_alphanumeric());
assert!(g.is_ascii_alphanumeric());
assert!(zero.is_ascii_alphanumeric());
assert!(!percent.is_ascii_alphanumeric());
assert!(!space.is_ascii_alphanumeric());
assert!(!lf.is_ascii_alphanumeric());
assert!(!esc.is_ascii_alphanumeric());
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#1436)1.24.0 (const: 1.47.0)
```
pub const fn is_ascii_digit(&self) -> bool
```

Checks if the value is an ASCII decimal digit: U+0030 ‘0’ ..= U+0039 ‘9’.

 ##### Examples

 
```
let uppercase_a = 'A';
let uppercase_g = 'G';
let a = 'a';
let g = 'g';
let zero = '0';
let percent = '%';
let space = ' ';
let lf = '\n';
let esc = '\x1b';

assert!(!uppercase_a.is_ascii_digit());
assert!(!uppercase_g.is_ascii_digit());
assert!(!a.is_ascii_digit());
assert!(!g.is_ascii_digit());
assert!(zero.is_ascii_digit());
assert!(!percent.is_ascii_digit());
assert!(!space.is_ascii_digit());
assert!(!lf.is_ascii_digit());
assert!(!esc.is_ascii_digit());
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#1468)const: [unstable](https://github.com/rust-lang/rust/issues/101288 "Tracking issue for is_ascii_octdigit")
```
pub fn is_ascii_octdigit(&self) -> bool
```

🔬This is a nightly-only experimental API. (`is_ascii_octdigit` [#101288](https://github.com/rust-lang/rust/issues/101288))

Checks if the value is an ASCII octal digit: U+0030 ‘0’ ..= U+0037 ‘7’.

 ##### Examples

 
```
#![feature(is_ascii_octdigit)]

let uppercase_a = 'A';
let a = 'a';
let zero = '0';
let seven = '7';
let nine = '9';
let percent = '%';
let lf = '\n';

assert!(!uppercase_a.is_ascii_octdigit());
assert!(!a.is_ascii_octdigit());
assert!(zero.is_ascii_octdigit());
assert!(seven.is_ascii_octdigit());
assert!(!nine.is_ascii_octdigit());
assert!(!percent.is_ascii_octdigit());
assert!(!lf.is_ascii_octdigit());
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#1505)1.24.0 (const: 1.47.0)
```
pub const fn is_ascii_hexdigit(&self) -> bool
```

Checks if the value is an ASCII hexadecimal digit:

 * U+0030 ‘0’ ..= U+0039 ‘9’, or
* U+0041 ‘A’ ..= U+0046 ‘F’, or
* U+0061 ‘a’ ..= U+0066 ‘f’.

 ##### Examples

 
```
let uppercase_a = 'A';
let uppercase_g = 'G';
let a = 'a';
let g = 'g';
let zero = '0';
let percent = '%';
let space = ' ';
let lf = '\n';
let esc = '\x1b';

assert!(uppercase_a.is_ascii_hexdigit());
assert!(!uppercase_g.is_ascii_hexdigit());
assert!(a.is_ascii_hexdigit());
assert!(!g.is_ascii_hexdigit());
assert!(zero.is_ascii_hexdigit());
assert!(!percent.is_ascii_hexdigit());
assert!(!space.is_ascii_hexdigit());
assert!(!lf.is_ascii_hexdigit());
assert!(!esc.is_ascii_hexdigit());
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#1543)1.24.0 (const: 1.47.0)
```
pub const fn is_ascii_punctuation(&self) -> bool
```

Checks if the value is an ASCII punctuation character:

 * U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
* U+003A ..= U+0040 `: ; < = > ? @`, or
* U+005B ..= U+0060 `[ \ ] ^ _ `` , or
* U+007B ..= U+007E `{ | } ~`

 ##### Examples

 
```
let uppercase_a = 'A';
let uppercase_g = 'G';
let a = 'a';
let g = 'g';
let zero = '0';
let percent = '%';
let space = ' ';
let lf = '\n';
let esc = '\x1b';

assert!(!uppercase_a.is_ascii_punctuation());
assert!(!uppercase_g.is_ascii_punctuation());
assert!(!a.is_ascii_punctuation());
assert!(!g.is_ascii_punctuation());
assert!(!zero.is_ascii_punctuation());
assert!(percent.is_ascii_punctuation());
assert!(!space.is_ascii_punctuation());
assert!(!lf.is_ascii_punctuation());
assert!(!esc.is_ascii_punctuation());
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#1577)1.24.0 (const: 1.47.0)
```
pub const fn is_ascii_graphic(&self) -> bool
```

Checks if the value is an ASCII graphic character: U+0021 ‘!’ ..= U+007E ‘~’.

 ##### Examples

 
```
let uppercase_a = 'A';
let uppercase_g = 'G';
let a = 'a';
let g = 'g';
let zero = '0';
let percent = '%';
let space = ' ';
let lf = '\n';
let esc = '\x1b';

assert!(uppercase_a.is_ascii_graphic());
assert!(uppercase_g.is_ascii_graphic());
assert!(a.is_ascii_graphic());
assert!(g.is_ascii_graphic());
assert!(zero.is_ascii_graphic());
assert!(percent.is_ascii_graphic());
assert!(!space.is_ascii_graphic());
assert!(!lf.is_ascii_graphic());
assert!(!esc.is_ascii_graphic());
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#1628)1.24.0 (const: 1.47.0)
```
pub const fn is_ascii_whitespace(&self) -> bool
```

Checks if the value is an ASCII whitespace character: U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED, U+000C FORM FEED, or U+000D 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 U+000B 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.

 ##### Examples

 
```
let uppercase_a = 'A';
let uppercase_g = 'G';
let a = 'a';
let g = 'g';
let zero = '0';
let percent = '%';
let space = ' ';
let lf = '\n';
let esc = '\x1b';

assert!(!uppercase_a.is_ascii_whitespace());
assert!(!uppercase_g.is_ascii_whitespace());
assert!(!a.is_ascii_whitespace());
assert!(!g.is_ascii_whitespace());
assert!(!zero.is_ascii_whitespace());
assert!(!percent.is_ascii_whitespace());
assert!(space.is_ascii_whitespace());
assert!(lf.is_ascii_whitespace());
assert!(!esc.is_ascii_whitespace());
```
 
[source](https://doc.rust-lang.org/src/core/char/methods.rs.html#1664)1.24.0 (const: 1.47.0)
```
pub const fn is_ascii_control(&self) -> bool
```

Checks if the value is an ASCII control character: U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE. Note that most ASCII whitespace characters are control characters, but SPACE is not.

 ##### Examples

 
```
let uppercase_a = 'A';
let uppercase_g = 'G';
let a = 'a';
let g = 'g';
let zero = '0';
let percent = '%';
let space = ' ';
let lf = '\n';
let esc = '\x1b';

assert!(!uppercase_a.is_ascii_control());
assert!(!uppercase_g.is_ascii_control());
assert!(!a.is_ascii_control());
assert!(!g.is_ascii_control());
assert!(!zero.is_ascii_control());
assert!(!percent.is_ascii_control());
assert!(!space.is_ascii_control());
assert!(lf.is_ascii_control());
assert!(esc.is_ascii_control());
```
 


Trait Implementations
---------------------



[source](https://doc.rust-lang.org/src/std/ascii.rs.html#191-195)
```
impl AsciiExt for char
```


```
type Owned = char
```

👎Deprecated since 1.26.0: use inherent methods instead
Container type for copied ASCII characters.
[source](https://doc.rust-lang.org/src/std/ascii.rs.html#194)
```
fn is_ascii(&self) -> bool
```

👎Deprecated since 1.26.0: use inherent methods instead
Checks if the value is within the ASCII range. [Read more](ascii/trait.asciiext#tymethod.is_ascii)

[source](https://doc.rust-lang.org/src/std/ascii.rs.html#194)
```
fn to_ascii_uppercase(&self) -> Self::Owned
```

👎Deprecated since 1.26.0: use inherent methods instead
Makes a copy of the value in its ASCII upper case equivalent. [Read more](ascii/trait.asciiext#tymethod.to_ascii_uppercase)

[source](https://doc.rust-lang.org/src/std/ascii.rs.html#194)
```
fn to_ascii_lowercase(&self) -> Self::Owned
```

👎Deprecated since 1.26.0: use inherent methods instead
Makes a copy of the value in its ASCII lower case equivalent. [Read more](ascii/trait.asciiext#tymethod.to_ascii_lowercase)

[source](https://doc.rust-lang.org/src/std/ascii.rs.html#194)
```
fn eq_ignore_ascii_case(&self, o: &Self) -> bool
```

👎Deprecated since 1.26.0: use inherent methods instead
Checks that two values are an ASCII case-insensitive match. [Read more](ascii/trait.asciiext#tymethod.eq_ignore_ascii_case)

[source](https://doc.rust-lang.org/src/std/ascii.rs.html#194)
```
fn make_ascii_uppercase(&mut self)
```

👎Deprecated since 1.26.0: use inherent methods instead
Converts this type to its ASCII upper case equivalent in-place. [Read more](ascii/trait.asciiext#tymethod.make_ascii_uppercase)

[source](https://doc.rust-lang.org/src/std/ascii.rs.html#194)
```
fn make_ascii_lowercase(&mut self)
```

👎Deprecated since 1.26.0: use inherent methods instead
Converts this type to its ASCII lower case equivalent in-place. [Read more](ascii/trait.asciiext#tymethod.make_ascii_lowercase)


[source](https://doc.rust-lang.org/src/core/clone.rs.html#189-194)
```
impl Clone for char
```

[source](https://doc.rust-lang.org/src/core/clone.rs.html#189-194)
```
fn clone(&self) -> char
```
Returns a copy of the value. [Read more](clone/trait.clone#tymethod.clone)

[source](https://doc.rust-lang.org/src/core/clone.rs.html#129)
```
fn clone_from(&mut self, source: &Self)
```
Performs copy-assignment from `source`. [Read more](clone/trait.clone#method.clone_from)


[source](https://doc.rust-lang.org/src/core/fmt/mod.rs.html#2344)
```
impl Debug for char
```

[source](https://doc.rust-lang.org/src/core/fmt/mod.rs.html#2345)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter. [Read more](fmt/trait.debug#tymethod.fmt)


[source](https://doc.rust-lang.org/src/core/default.rs.html#204)
```
impl Default for char
```

[source](https://doc.rust-lang.org/src/core/default.rs.html#204)
```
fn default() -> char
```

Returns the default value of `\x00`

 

[source](https://doc.rust-lang.org/src/core/fmt/mod.rs.html#2359)
```
impl Display for char
```

[source](https://doc.rust-lang.org/src/core/fmt/mod.rs.html#2360)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter. [Read more](fmt/trait.display#tymethod.fmt)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2102)1.2.0
```
impl<'a> Extend<&'a char> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2103)
```
fn extend<I>(&mut self, iter: I)
where
    I: IntoIterator<Item = &'a char>,
```
Extends a collection with the contents of an iterator. [Read more](iter/trait.extend#tymethod.extend)

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2108)
```
fn extend_one(&mut self, _: &'a 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/src/alloc/string.rs.html#2113)
```
fn extend_reserve(&mut self, additional: usize)
```

🔬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](iter/trait.extend#method.extend_reserve)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2081)
```
impl Extend<char> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2082)
```
fn extend<I>(&mut self, iter: I)
where
    I: IntoIterator<Item = char>,
```
Extends a collection with the contents of an iterator. [Read more](iter/trait.extend#tymethod.extend)

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2090)
```
fn extend_one(&mut self, c: 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/src/alloc/string.rs.html#2095)
```
fn extend_reserve(&mut self, additional: usize)
```

🔬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](iter/trait.extend#method.extend_reserve)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2999)1.46.0
```
impl From<char> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#3009)
```
fn from(c: char) -> String
```

Allocates an owned [`String`](string/struct.string "struct std::string::String") from a single character.

 ##### Example

 
```
let c: char = 'a';
let s: String = String::from(c);
assert_eq!("a", &s[..]);
```
 

[source](https://doc.rust-lang.org/src/core/char/convert.rs.html#70)1.51.0
```
impl From<char> for u128
```

[source](https://doc.rust-lang.org/src/core/char/convert.rs.html#83)
```
fn from(c: char) -> u128
```

Converts a [`char`](primitive.char "primitive char") into a [`u128`](primitive.u128 "primitive u128").

 ##### Examples

 
```
use std::mem;

let c = '⚙';
let u = u128::from(c);
assert!(16 == mem::size_of_val(&u))
```
 

[source](https://doc.rust-lang.org/src/core/char/convert.rs.html#30)1.13.0
```
impl From<char> for u32
```

[source](https://doc.rust-lang.org/src/core/char/convert.rs.html#43)
```
fn from(c: char) -> u32
```

Converts a [`char`](primitive.char "primitive char") into a [`u32`](primitive.u32 "primitive u32").

 ##### Examples

 
```
use std::mem;

let c = 'c';
let u = u32::from(c);
assert!(4 == mem::size_of_val(&u))
```
 

[source](https://doc.rust-lang.org/src/core/char/convert.rs.html#49)1.51.0
```
impl From<char> for u64
```

[source](https://doc.rust-lang.org/src/core/char/convert.rs.html#62)
```
fn from(c: char) -> u64
```

Converts a [`char`](primitive.char "primitive char") into a [`u64`](primitive.u64 "primitive u64").

 ##### Examples

 
```
use std::mem;

let c = '👤';
let u = u64::from(c);
assert!(8 == mem::size_of_val(&u))
```
 

[source](https://doc.rust-lang.org/src/core/char/convert.rs.html#123)1.13.0
```
impl From<u8> for char
```

Maps a byte in 0x00..=0xFF to a `char` whose code point has the same value, in U+0000..=U+00FF.

 Unicode is designed such that this effectively decodes bytes with the character encoding that IANA calls ISO-8859-1. This encoding is compatible with ASCII.

 Note that this is different from ISO/IEC 8859-1 a.k.a. ISO 8859-1 (with one less hyphen), which leaves some “blanks”, byte values that are not assigned to any character. ISO-8859-1 (the IANA one) assigns them to the C0 and C1 control codes.

 Note that this is *also* different from Windows-1252 a.k.a. code page 1252, which is a superset ISO/IEC 8859-1 that assigns some (not all!) blanks to punctuation and various Latin characters.

 To confuse things further, [on the Web](https://encoding.spec.whatwg.org/) `ascii`, `iso-8859-1`, and `windows-1252` are all aliases for a superset of Windows-1252 that fills the remaining blanks with corresponding C0 and C1 control codes.

 

[source](https://doc.rust-lang.org/src/core/char/convert.rs.html#136)
```
fn from(i: u8) -> char
```

Converts a [`u8`](primitive.u8 "primitive u8") into a [`char`](primitive.char "primitive char").

 ##### Examples

 
```
use std::mem;

let u = 32 as u8;
let c = char::from(u);
assert!(4 == mem::size_of_val(&c))
```
 

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2012)1.17.0
```
impl<'a> FromIterator<&'a char> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2013)
```
fn from_iter<I>(iter: I) -> String
where
    I: IntoIterator<Item = &'a char>,
```
Creates a value from an iterator. [Read more](iter/trait.fromiterator#tymethod.from_iter)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2831)1.12.0
```
impl<'a> FromIterator<char> for Cow<'a, str>
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2832)
```
fn from_iter<I>(it: I) -> Cow<'a, str>
where
    I: IntoIterator<Item = char>,
```
Creates a value from an iterator. [Read more](iter/trait.fromiterator#tymethod.from_iter)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2002)
```
impl FromIterator<char> for String
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2003)
```
fn from_iter<I>(iter: I) -> String
where
    I: IntoIterator<Item = char>,
```
Creates a value from an iterator. [Read more](iter/trait.fromiterator#tymethod.from_iter)


[source](https://doc.rust-lang.org/src/core/char/convert.rs.html#176)1.20.0
```
impl FromStr for char
```


```
type Err = ParseCharError
```
The associated error which can be returned from parsing.
[source](https://doc.rust-lang.org/src/core/char/convert.rs.html#180)
```
fn from_str(s: &str) -> Result<char, <char as FromStr>::Err>
```
Parses a string `s` to return a value of this type. [Read more](str/trait.fromstr#tymethod.from_str)


[source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#851)
```
impl Hash for char
```

[source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#853)
```
fn hash<H>(&self, state: &mut H)
where
    H: Hasher,
```
Feeds this value into the given [`Hasher`](hash/trait.hasher "trait std::hash::Hasher"). [Read more](hash/trait.hash#tymethod.hash)

[source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#237-239)1.3.0
```
fn hash_slice<H>(data: &[Self], state: &mut H)
where
    H: Hasher,
    Self: Sized,
```
Feeds a slice of this type into the given [`Hasher`](hash/trait.hasher "trait std::hash::Hasher"). [Read more](hash/trait.hash#method.hash_slice)


[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1411)
```
impl Ord for char
```

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1411)
```
fn cmp(&self, other: &char) -> Ordering
```
This method returns an [`Ordering`](cmp/enum.ordering "enum std::cmp::Ordering") between `self` and `other`. [Read more](cmp/trait.ord#tymethod.cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#790-792)1.21.0
```
fn max(self, other: Self) -> Self
where
    Self: Sized,
```
Compares and returns the maximum of two values. [Read more](cmp/trait.ord#method.max)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#810-812)1.21.0
```
fn min(self, other: Self) -> Self
where
    Self: Sized,
```
Compares and returns the minimum of two values. [Read more](cmp/trait.ord#method.min)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#835-838)1.50.0
```
fn clamp(self, min: Self, max: Self) -> Self
where
    Self: Sized + PartialOrd<Self>,
```
Restrict a value to a certain interval. [Read more](cmp/trait.ord#method.clamp)


[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1298-1300)
```
impl PartialEq<char> for char
```

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1298-1300)
```
fn eq(&self, other: &char) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1298-1300)
```
fn ne(&self, other: &char) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1411)
```
impl PartialOrd<char> for char
```

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1411)
```
fn partial_cmp(&self, other: &char) -> Option<Ordering>
```
This method returns an ordering between `self` and `other` values if one exists. [Read more](cmp/trait.partialord#tymethod.partial_cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1411)
```
fn lt(&self, other: &char) -> bool
```
This method tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](cmp/trait.partialord#method.lt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1411)
```
fn le(&self, other: &char) -> bool
```
This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](cmp/trait.partialord#method.le)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1411)
```
fn ge(&self, other: &char) -> bool
```
This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](cmp/trait.partialord#method.ge)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1411)
```
fn gt(&self, other: &char) -> bool
```
This method tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](cmp/trait.partialord#method.gt)


[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#539)
```
impl<'a> Pattern<'a> for char
```

Searches for chars that are equal to a given [`char`](primitive.char "primitive char").

 #### Examples

 
```
assert_eq!("Hello world".find('o'), Some(4));
```
 


```
type Searcher = CharSearcher<'a>
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Associated searcher for this pattern
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#543)
```
fn into_searcher(self, haystack: &'a str) -> <char as Pattern<'a>>::Searcher
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Constructs the associated searcher from `self` and the `haystack` to search in.
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#557)
```
fn is_contained_in(self, haystack: &'a str) -> bool
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Checks whether the pattern matches anywhere in the haystack
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#567)
```
fn is_prefix_of(self, haystack: &'a str) -> bool
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Checks whether the pattern matches at the front of the haystack
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#572)
```
fn strip_prefix_of(self, haystack: &'a str) -> Option<&'a str>
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Removes the pattern from the front of haystack, if it matches.
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#577-579)
```
fn is_suffix_of(self, haystack: &'a str) -> bool
where
    <char as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Checks whether the pattern matches at the back of the haystack
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#585-587)
```
fn strip_suffix_of(self, haystack: &'a str) -> Option<&'a str>
where
    <char as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Removes the pattern from the back of haystack, if it matches.

[source](https://doc.rust-lang.org/src/core/iter/range.rs.html#409)
```
impl Step for char
```

[source](https://doc.rust-lang.org/src/core/iter/range.rs.html#411)
```
fn steps_between(_: &char, _: &char) -> Option<usize>
```

🔬This is a nightly-only experimental API. (`step_trait` [#42168](https://github.com/rust-lang/rust/issues/42168))
Returns the number of *successor* steps required to get from `start` to `end`. [Read more](iter/trait.step#tymethod.steps_between)

[source](https://doc.rust-lang.org/src/core/iter/range.rs.html#427)
```
fn forward_checked(start: char, count: usize) -> Option<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](iter/trait.step#tymethod.forward_checked)

[source](https://doc.rust-lang.org/src/core/iter/range.rs.html#443)
```
fn backward_checked(start: char, count: usize) -> Option<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](iter/trait.step#tymethod.backward_checked)

[source](https://doc.rust-lang.org/src/core/iter/range.rs.html#455)
```
unsafe fn forward_unchecked(start: char, count: usize) -> 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](iter/trait.step#method.forward_unchecked)

[source](https://doc.rust-lang.org/src/core/iter/range.rs.html#471)
```
unsafe fn backward_unchecked(start: char, count: usize) -> 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](iter/trait.step#method.backward_unchecked)

[source](https://doc.rust-lang.org/src/core/iter/range.rs.html#87)
```
fn forward(start: Self, count: usize) -> 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](iter/trait.step#method.forward)

[source](https://doc.rust-lang.org/src/core/iter/range.rs.html#156)
```
fn backward(start: Self, count: usize) -> 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](iter/trait.step#method.backward)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2540)1.46.0
```
impl ToString for char
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2542)
```
fn to_string(&self) -> String
```
Converts the given value to a `String`. [Read more](string/trait.tostring#tymethod.to_string)


[source](https://doc.rust-lang.org/src/core/char/convert.rs.html#95)1.59.0
```
impl TryFrom<char> for u8
```

Map `char` with code point in U+0000..=U+00FF to byte in 0x00..=0xFF with same value, failing if the code point is greater than U+00FF.

 See [`impl From<u8> for char`](primitive.char#impl-From%3Cu8%3E-for-char "primitive char") for details on the encoding.

 


```
type Error = TryFromCharError
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/char/convert.rs.html#99)
```
fn try_from(c: char) -> Result<u8, <u8 as TryFrom<char>>::Error>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/char/convert.rs.html#214)1.34.0
```
impl TryFrom<u32> for char
```


```
type Error = CharTryFromError
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/char/convert.rs.html#218)
```
fn try_from(i: u32) -> Result<char, <char as TryFrom<u32>>::Error>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/marker.rs.html#989-1000)
```
impl ConstParamTy for char
```
[source](https://doc.rust-lang.org/src/core/marker.rs.html#467-477)
```
impl Copy for char
```
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1309)
```
impl Eq for char
```
[source](https://doc.rust-lang.org/src/core/marker.rs.html#262-273)
```
impl StructuralEq for char
```
[source](https://doc.rust-lang.org/src/core/iter/range.rs.html#17)
```
impl TrustedStep for char
```


Auto Trait Implementations
--------------------------




```
impl RefUnwindSafe for char
```

```
impl Send for char
```

```
impl Sync for char
```

```
impl Unpin for char
```

```
impl UnwindSafe for char
```


Blanket Implementations
-----------------------



[source](https://doc.rust-lang.org/src/core/any.rs.html#200)
```
impl<T> Any for T
where
    T: 'static + ?Sized,
```

[source](https://doc.rust-lang.org/src/core/any.rs.html#201)
```
fn type_id(&self) -> TypeId
```
Gets the `TypeId` of `self`. [Read more](any/trait.any#tymethod.type_id)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#208)
```
impl<T> Borrow<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#210)
```
fn borrow(&self) -> &T
```
Immutably borrows from an owned value. [Read more](borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#216)
```
impl<T> BorrowMut<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#217)
```
fn borrow_mut(&mut self) -> &mut T
```
Mutably borrows from an owned value. [Read more](borrow/trait.borrowmut#tymethod.borrow_mut)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#723)
```
impl<T> From<T> for T
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#726)
```
fn from(t: T) -> T
```

Returns the argument unchanged.

 

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#707)
```
impl<T, U> Into<U> for T
where
    U: From<T>,
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#716)
```
fn into(self) -> U
```

Calls `U::from(self)`.

 That is, this conversion is whatever the implementation of `[From](convert/trait.from "trait std::convert::From")<T> for U` chooses to do.

 

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#82)
```
impl<T> ToOwned for T
where
    T: Clone,
```


```
type Owned = T
```
The resulting type after obtaining ownership.
[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#87)
```
fn to_owned(&self) -> T
```
Creates owned data from borrowed data, usually by cloning. [Read more](borrow/trait.toowned#tymethod.to_owned)

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#91)
```
fn clone_into(&self, target: &mut T)
```
Uses borrowed data to replace owned data, usually by cloning. [Read more](borrow/trait.toowned#method.clone_into)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2513)
```
impl<T> ToString for T
where
    T: Display + ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2519)
```
default fn to_string(&self) -> String
```
Converts the given value to a `String`. [Read more](string/trait.tostring#tymethod.to_string)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#763)
```
impl<T, U> TryFrom<U> for T
where
    U: Into<T>,
```


```
type Error = Infallible
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#770)
```
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#748)
```
impl<T, U> TryInto<U> for T
where
    U: TryFrom<T>,
```


```
type Error = <U as TryFrom<T>>::Error
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#755)
```
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
```
Performs the conversion.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/primitive.char.html>

Primitive Type f32
==================


A 32-bit floating point type (specifically, the “binary32” type defined in IEEE 754-2008).

 This type can represent a wide range of decimal numbers, like `3.5`, `27`, `-113.75`, `0.0078125`, `34359738368`, `0`, `-1`. So unlike integer types (such as `i32`), floating point types can represent non-integer numbers, too.

 However, being able to represent this wide range of numbers comes at the cost of precision: floats can only represent some of the real numbers and calculation with floats round to a nearby representable number. For example, `5.0` and `1.0` can be exactly represented as `f32`, but `1.0 / 5.0` results in `0.20000000298023223876953125` since `0.2` cannot be exactly represented as `f32`. Note, however, that printing floats with `println` and friends will often discard insignificant digits: `println!("{}", 1.0f32 / 5.0f32)` will print `0.2`.

 Additionally, `f32` can represent some special values:

 * −0.0: IEEE 754 floating point numbers have a bit that indicates their sign, so −0.0 is a possible value. For comparison −0.0 = +0.0, but floating point operations can carry the sign bit through arithmetic operations. This means −0.0 × +0.0 produces −0.0 and a negative number rounded to a value smaller than a float can represent also produces −0.0.
* [∞](#associatedconstant.INFINITY) and [−∞](#associatedconstant.NEG_INFINITY): these result from calculations like `1.0 / 0.0`.
* [NaN (not a number)](#associatedconstant.NAN): this value results from calculations like `(-1.0).sqrt()`. NaN has some potentially unexpected behavior:
	+ It is not equal to any float, including itself! This is the reason `f32` doesn’t implement the `Eq` trait.
	+ It is also neither smaller nor greater than any float, making it impossible to sort by the default comparison operation, which is the reason `f32` doesn’t implement the `Ord` trait.
	+ It is also considered *infectious* as almost all calculations where one of the operands is NaN will also result in NaN. The explanations on this page only explicitly document behavior on NaN operands if this default is deviated from.
	+ Lastly, there are multiple bit patterns that are considered NaN. Rust does not currently guarantee that the bit patterns of NaN are preserved over arithmetic operations, and they are not guaranteed to be portable or even fully deterministic! This means that there may be some surprising results upon inspecting the bit patterns, as the same calculations might produce NaNs with different bit patterns.

 When the number resulting from a primitive operation (addition, subtraction, multiplication, or division) on this type is not exactly representable as `f32`, it is rounded according to the roundTiesToEven direction defined in IEEE 754-2008. That means:

 * The result is the representable value closest to the true value, if there is a unique closest representable value.
* If the true value is exactly half-way between two representable values, the result is the one with an even least-significant binary digit.
* If the true value’s magnitude is ≥ `f32::MAX` + 2(`f32::MAX_EXP` − `f32::MANTISSA_DIGITS` − 1), the result is ∞ or −∞ (preserving the true value’s sign).

 For more information on floating point numbers, see [Wikipedia](https://en.wikipedia.org/wiki/Single-precision_floating-point_format).

 *[See also the `std::f32::consts` module](f32/consts/index "mod std::f32::consts").*

 Implementations
---------------



[source](https://doc.rust-lang.org/src/std/f32.rs.html#31-963)
```
impl f32
```

[source](https://doc.rust-lang.org/src/std/f32.rs.html#49-51)
```
pub fn floor(self) -> f32
```

Returns the largest integer less than or equal to `self`.

 ##### Examples

 
```
let f = 3.7_f32;
let g = 3.0_f32;
let h = -3.7_f32;

assert_eq!(f.floor(), 3.0);
assert_eq!(g.floor(), 3.0);
assert_eq!(h.floor(), -4.0);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#68-70)
```
pub fn ceil(self) -> f32
```

Returns the smallest integer greater than or equal to `self`.

 ##### Examples

 
```
let f = 3.01_f32;
let g = 4.0_f32;

assert_eq!(f.ceil(), 4.0);
assert_eq!(g.ceil(), 4.0);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#94-96)
```
pub fn round(self) -> f32
```

Returns the nearest integer to `self`. If a value is half-way between two integers, round away from `0.0`.

 ##### Examples

 
```
let f = 3.3_f32;
let g = -3.3_f32;
let h = -3.7_f32;
let i = 3.5_f32;
let j = 4.5_f32;

assert_eq!(f.round(), 3.0);
assert_eq!(g.round(), -3.0);
assert_eq!(h.round(), -4.0);
assert_eq!(i.round(), 4.0);
assert_eq!(j.round(), 5.0);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#120-122)
```
pub fn round_ties_even(self) -> f32
```

🔬This is a nightly-only experimental API. (`round_ties_even` [#96710](https://github.com/rust-lang/rust/issues/96710))

Returns the nearest integer to a number. Rounds half-way cases to the number with an even least significant digit.

 ##### Examples

 
```
#![feature(round_ties_even)]

let f = 3.3_f32;
let g = -3.3_f32;
let h = 3.5_f32;
let i = 4.5_f32;

assert_eq!(f.round_ties_even(), 3.0);
assert_eq!(g.round_ties_even(), -3.0);
assert_eq!(h.round_ties_even(), 4.0);
assert_eq!(i.round_ties_even(), 4.0);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#142-144)
```
pub fn trunc(self) -> f32
```

Returns the integer part of `self`. This means that non-integer numbers are always truncated towards zero.

 ##### Examples

 
```
let f = 3.7_f32;
let g = 3.0_f32;
let h = -3.7_f32;

assert_eq!(f.trunc(), 3.0);
assert_eq!(g.trunc(), 3.0);
assert_eq!(h.trunc(), -3.0);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#163-165)
```
pub fn fract(self) -> f32
```

Returns the fractional part of `self`.

 ##### Examples

 
```
let x = 3.6_f32;
let y = -3.6_f32;
let abs_difference_x = (x.fract() - 0.6).abs();
let abs_difference_y = (y.fract() - (-0.6)).abs();

assert!(abs_difference_x <= f32::EPSILON);
assert!(abs_difference_y <= f32::EPSILON);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#187-189)
```
pub fn abs(self) -> f32
```

Computes the absolute value of `self`.

 ##### Examples

 
```
let x = 3.5_f32;
let y = -3.5_f32;

let abs_difference_x = (x.abs() - x).abs();
let abs_difference_y = (y.abs() - (-y)).abs();

assert!(abs_difference_x <= f32::EPSILON);
assert!(abs_difference_y <= f32::EPSILON);

assert!(f32::NAN.abs().is_nan());
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#211-213)
```
pub fn signum(self) -> f32
```

Returns a number that represents the sign of `self`.

 * `1.0` if the number is positive, `+0.0` or `INFINITY`
* `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
* NaN if the number is NaN

 ##### Examples

 
```
let f = 3.5_f32;

assert_eq!(f.signum(), 1.0);
assert_eq!(f32::NEG_INFINITY.signum(), -1.0);

assert!(f32::NAN.signum().is_nan());
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#240-242)1.35.0
```
pub fn copysign(self, sign: f32) -> f32
```

Returns a number composed of the magnitude of `self` and the sign of `sign`.

 Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`. If `self` is a NaN, then a NaN with the sign bit of `sign` is returned. Note, however, that conserving the sign bit on NaN across arithmetical operations is not generally guaranteed. See [explanation of NaN as a special value](primitive.f32 "primitive f32") for more info.

 ##### Examples

 
```
let f = 3.5_f32;

assert_eq!(f.copysign(0.42), 3.5_f32);
assert_eq!(f.copysign(-0.42), -3.5_f32);
assert_eq!((-f).copysign(0.42), 3.5_f32);
assert_eq!((-f).copysign(-0.42), -3.5_f32);

assert!(f32::NAN.copysign(1.0).is_nan());
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#268-270)
```
pub fn mul_add(self, a: f32, b: f32) -> f32
```

Fused multiply-add. Computes `(self * a) + b` with only one rounding error, yielding a more accurate result than an unfused multiply-add.

 Using `mul_add` *may* be more performant than an unfused multiply-add if the target architecture has a dedicated `fma` CPU instruction. However, this is not always true, and will be heavily dependant on designing algorithms with specific target hardware in mind.

 ##### Examples

 
```
let m = 10.0_f32;
let x = 4.0_f32;
let b = 60.0_f32;

// 100.0
let abs_difference = (m.mul_add(x, b) - ((m * x) + b)).abs();

assert!(abs_difference <= f32::EPSILON);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#293-299)1.38.0
```
pub fn div_euclid(self, rhs: f32) -> f32
```

Calculates Euclidean division, the matching method for `rem_euclid`.

 This computes the integer `n` such that `self = n * rhs + self.rem_euclid(rhs)`. In other words, the result is `self / rhs` rounded to the integer `n` such that `self >= n * rhs`.

 ##### Examples

 
```
let a: f32 = 7.0;
let b = 4.0;
assert_eq!(a.div_euclid(b), 1.0); // 7.0 > 4.0 * 1.0
assert_eq!((-a).div_euclid(b), -2.0); // -7.0 >= 4.0 * -2.0
assert_eq!(a.div_euclid(-b), -1.0); // 7.0 >= -4.0 * -1.0
assert_eq!((-a).div_euclid(-b), 2.0); // -7.0 >= -4.0 * 2.0
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#328-331)1.38.0
```
pub fn rem_euclid(self, rhs: f32) -> f32
```

Calculates the least nonnegative remainder of `self (mod rhs)`.

 In particular, the return value `r` satisfies `0.0 <= r < rhs.abs()` in most cases. However, due to a floating point round-off error it can result in `r == rhs.abs()`, violating the mathematical definition, if `self` is much smaller than `rhs.abs()` in magnitude and `self < 0.0`. This result is not an element of the function’s codomain, but it is the closest floating point number in the real numbers and thus fulfills the property `self == self.div_euclid(rhs) * rhs + self.rem_euclid(rhs)` approximately.

 ##### Examples

 
```
let a: f32 = 7.0;
let b = 4.0;
assert_eq!(a.rem_euclid(b), 3.0);
assert_eq!((-a).rem_euclid(b), 1.0);
assert_eq!(a.rem_euclid(-b), 3.0);
assert_eq!((-a).rem_euclid(-b), 1.0);
// limitation due to round-off error
assert!((-f32::EPSILON).rem_euclid(3.0) != 0.0);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#351-353)
```
pub fn powi(self, n: i32) -> f32
```

Raises a number to an integer power.

 Using this function is generally faster than using `powf`. It might have a different sequence of rounding operations than `powf`, so the results are not guaranteed to agree.

 ##### Examples

 
```
let x = 2.0_f32;
let abs_difference = (x.powi(2) - (x * x)).abs();

assert!(abs_difference <= f32::EPSILON);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#369-371)
```
pub fn powf(self, n: f32) -> f32
```

Raises a number to a floating point power.

 ##### Examples

 
```
let x = 2.0_f32;
let abs_difference = (x.powf(2.0) - (x * x)).abs();

assert!(abs_difference <= f32::EPSILON);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#394-396)
```
pub fn sqrt(self) -> f32
```

Returns the square root of a number.

 Returns NaN if `self` is a negative number other than `-0.0`.

 ##### Examples

 
```
let positive = 4.0_f32;
let negative = -4.0_f32;
let negative_zero = -0.0_f32;

let abs_difference = (positive.sqrt() - 2.0).abs();

assert!(abs_difference <= f32::EPSILON);
assert!(negative.sqrt().is_nan());
assert!(negative_zero.sqrt() == negative_zero);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#416-418)
```
pub fn exp(self) -> f32
```

Returns `e^(self)`, (the exponential function).

 ##### Examples

 
```
let one = 1.0f32;
// e^1
let e = one.exp();

// ln(e) - 1 == 0
let abs_difference = (e.ln() - 1.0).abs();

assert!(abs_difference <= f32::EPSILON);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#436-438)
```
pub fn exp2(self) -> f32
```

Returns `2^(self)`.

 ##### Examples

 
```
let f = 2.0f32;

// 2^2 - 4 == 0
let abs_difference = (f.exp2() - 4.0).abs();

assert!(abs_difference <= f32::EPSILON);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#458-460)
```
pub fn ln(self) -> f32
```

Returns the natural logarithm of the number.

 ##### Examples

 
```
let one = 1.0f32;
// e^1
let e = one.exp();

// ln(e) - 1 == 0
let abs_difference = (e.ln() - 1.0).abs();

assert!(abs_difference <= f32::EPSILON);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#482-484)
```
pub fn log(self, base: f32) -> f32
```

Returns the logarithm of the number with respect to an arbitrary base.

 The result might not be correctly rounded owing to implementation details; `self.log2()` can produce more accurate results for base 2, and `self.log10()` can produce more accurate results for base 10.

 ##### Examples

 
```
let five = 5.0f32;

// log5(5) - 1 == 0
let abs_difference = (five.log(5.0) - 1.0).abs();

assert!(abs_difference <= f32::EPSILON);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#502-507)
```
pub fn log2(self) -> f32
```

Returns the base 2 logarithm of the number.

 ##### Examples

 
```
let two = 2.0f32;

// log2(2) - 1 == 0
let abs_difference = (two.log2() - 1.0).abs();

assert!(abs_difference <= f32::EPSILON);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#525-527)
```
pub fn log10(self) -> f32
```

Returns the base 10 logarithm of the number.

 ##### Examples

 
```
let ten = 10.0f32;

// log10(10) - 1 == 0
let abs_difference = (ten.log10() - 1.0).abs();

assert!(abs_difference <= f32::EPSILON);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#560-562)
```
pub fn abs_sub(self, other: f32) -> f32
```

👎Deprecated since 1.10.0: you probably meant `(self - other).abs()`: this operation is `(self - other).max(0.0)` except that `abs_sub` also propagates NaNs (also known as `fdimf` in C). If you truly need the positive difference, consider using that expression or the C function `fdimf`, depending on how you wish to handle NaN (please consider filing an issue describing your use-case too).

The positive difference of two numbers.

 * If `self <= other`: `0:0`
* Else: `self - other`

 ##### Examples

 
```
let x = 3.0f32;
let y = -3.0f32;

let abs_difference_x = (x.abs_sub(1.0) - 2.0).abs();
let abs_difference_y = (y.abs_sub(1.0) - 0.0).abs();

assert!(abs_difference_x <= f32::EPSILON);
assert!(abs_difference_y <= f32::EPSILON);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#580-582)
```
pub fn cbrt(self) -> f32
```

Returns the cube root of a number.

 ##### Examples

 
```
let x = 8.0f32;

// x^(1/3) - 2 == 0
let abs_difference = (x.cbrt() - 2.0).abs();

assert!(abs_difference <= f32::EPSILON);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#604-606)
```
pub fn hypot(self, other: f32) -> f32
```

Compute the distance between the origin and a point (`x`, `y`) on the Euclidean plane. Equivalently, compute the length of the hypotenuse of a right-angle triangle with other sides having length `x.abs()` and `y.abs()`.

 ##### Examples

 
```
let x = 2.0f32;
let y = 3.0f32;

// sqrt(x^2 + y^2)
let abs_difference = (x.hypot(y) - (x.powi(2) + y.powi(2)).sqrt()).abs();

assert!(abs_difference <= f32::EPSILON);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#623-625)
```
pub fn sin(self) -> f32
```

Computes the sine of a number (in radians).

 ##### Examples

 
```
let x = std::f32::consts::FRAC_PI_2;

let abs_difference = (x.sin() - 1.0).abs();

assert!(abs_difference <= f32::EPSILON);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#642-644)
```
pub fn cos(self) -> f32
```

Computes the cosine of a number (in radians).

 ##### Examples

 
```
let x = 2.0 * std::f32::consts::PI;

let abs_difference = (x.cos() - 1.0).abs();

assert!(abs_difference <= f32::EPSILON);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#660-662)
```
pub fn tan(self) -> f32
```

Computes the tangent of a number (in radians).

 ##### Examples

 
```
let x = std::f32::consts::FRAC_PI_4;
let abs_difference = (x.tan() - 1.0).abs();

assert!(abs_difference <= f32::EPSILON);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#682-684)
```
pub fn asin(self) -> f32
```

Computes the arcsine of a number. Return value is in radians in the range [-pi/2, pi/2] or NaN if the number is outside the range [-1, 1].

 ##### Examples

 
```
let f = std::f32::consts::FRAC_PI_2;

// asin(sin(pi/2))
let abs_difference = (f.sin().asin() - std::f32::consts::FRAC_PI_2).abs();

assert!(abs_difference <= f32::EPSILON);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#704-706)
```
pub fn acos(self) -> f32
```

Computes the arccosine of a number. Return value is in radians in the range [0, pi] or NaN if the number is outside the range [-1, 1].

 ##### Examples

 
```
let f = std::f32::consts::FRAC_PI_4;

// acos(cos(pi/4))
let abs_difference = (f.cos().acos() - std::f32::consts::FRAC_PI_4).abs();

assert!(abs_difference <= f32::EPSILON);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#725-727)
```
pub fn atan(self) -> f32
```

Computes the arctangent of a number. Return value is in radians in the range [-pi/2, pi/2];

 ##### Examples

 
```
let f = 1.0f32;

// atan(tan(1))
let abs_difference = (f.tan().atan() - 1.0).abs();

assert!(abs_difference <= f32::EPSILON);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#759-761)
```
pub fn atan2(self, other: f32) -> f32
```

Computes the four quadrant arctangent of `self` (`y`) and `other` (`x`) in radians.

 * `x = 0`, `y = 0`: `0`
* `x >= 0`: `arctan(y/x)` -> `[-pi/2, pi/2]`
* `y >= 0`: `arctan(y/x) + pi` -> `(pi/2, pi]`
* `y < 0`: `arctan(y/x) - pi` -> `(-pi, -pi/2)`

 ##### Examples

 
```
// Positive angles measured counter-clockwise
// from positive x axis
// -pi/4 radians (45 deg clockwise)
let x1 = 3.0f32;
let y1 = -3.0f32;

// 3pi/4 radians (135 deg counter-clockwise)
let x2 = -3.0f32;
let y2 = 3.0f32;

let abs_difference_1 = (y1.atan2(x1) - (-std::f32::consts::FRAC_PI_4)).abs();
let abs_difference_2 = (y2.atan2(x2) - (3.0 * std::f32::consts::FRAC_PI_4)).abs();

assert!(abs_difference_1 <= f32::EPSILON);
assert!(abs_difference_2 <= f32::EPSILON);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#781-783)
```
pub fn sin_cos(self) -> (f32, f32)
```

Simultaneously computes the sine and cosine of the number, `x`. Returns `(sin(x), cos(x))`.

 ##### Examples

 
```
let x = std::f32::consts::FRAC_PI_4;
let f = x.sin_cos();

let abs_difference_0 = (f.0 - x.sin()).abs();
let abs_difference_1 = (f.1 - x.cos()).abs();

assert!(abs_difference_0 <= f32::EPSILON);
assert!(abs_difference_1 <= f32::EPSILON);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#803-805)
```
pub fn exp_m1(self) -> f32
```

Returns `e^(self) - 1` in a way that is accurate even if the number is close to zero.

 ##### Examples

 
```
let x = 1e-8_f32;

// for very small x, e^x is approximately 1 + x + x^2 / 2
let approx = x + x * x / 2.0;
let abs_difference = (x.exp_m1() - approx).abs();

assert!(abs_difference < 1e-10);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#825-827)
```
pub fn ln_1p(self) -> f32
```

Returns `ln(1+n)` (natural logarithm) more accurately than if the operations were performed separately.

 ##### Examples

 
```
let x = 1e-8_f32;

// for very small x, ln(1 + x) is approximately x - x^2 / 2
let approx = x - x * x / 2.0;
let abs_difference = (x.ln_1p() - approx).abs();

assert!(abs_difference < 1e-10);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#848-850)
```
pub fn sinh(self) -> f32
```

Hyperbolic sine function.

 ##### Examples

 
```
let e = std::f32::consts::E;
let x = 1.0f32;

let f = x.sinh();
// Solving sinh() at 1 gives `(e^2-1)/(2e)`
let g = ((e * e) - 1.0) / (2.0 * e);
let abs_difference = (f - g).abs();

assert!(abs_difference <= f32::EPSILON);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#871-873)
```
pub fn cosh(self) -> f32
```

Hyperbolic cosine function.

 ##### Examples

 
```
let e = std::f32::consts::E;
let x = 1.0f32;
let f = x.cosh();
// Solving cosh() at 1 gives this result
let g = ((e * e) + 1.0) / (2.0 * e);
let abs_difference = (f - g).abs();

// Same result
assert!(abs_difference <= f32::EPSILON);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#894-896)
```
pub fn tanh(self) -> f32
```

Hyperbolic tangent function.

 ##### Examples

 
```
let e = std::f32::consts::E;
let x = 1.0f32;

let f = x.tanh();
// Solving tanh() at 1 gives `(1 - e^(-2))/(1 + e^(-2))`
let g = (1.0 - e.powi(-2)) / (1.0 + e.powi(-2));
let abs_difference = (f - g).abs();

assert!(abs_difference <= f32::EPSILON);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#914-918)
```
pub fn asinh(self) -> f32
```

Inverse hyperbolic sine function.

 ##### Examples

 
```
let x = 1.0f32;
let f = x.sinh().asinh();

let abs_difference = (f - x).abs();

assert!(abs_difference <= f32::EPSILON);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#936-942)
```
pub fn acosh(self) -> f32
```

Inverse hyperbolic cosine function.

 ##### Examples

 
```
let x = 1.0f32;
let f = x.cosh().acosh();

let abs_difference = (f - x).abs();

assert!(abs_difference <= f32::EPSILON);
```
 
[source](https://doc.rust-lang.org/src/std/f32.rs.html#960-962)
```
pub fn atanh(self) -> f32
```

Inverse hyperbolic tangent function.

 ##### Examples

 
```
let e = std::f32::consts::E;
let f = e.tanh().atanh();

let abs_difference = (f - e).abs();

assert!(abs_difference <= 1e-5);
```
 

[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#350)
```
impl f32
```

[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#353)1.43.0
```
pub const RADIX: u32 = 2u32
```

The radix or base of the internal representation of `f32`.

 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#357)1.43.0
```
pub const MANTISSA_DIGITS: u32 = 24u32
```

Number of significant digits in base 2.

 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#361)1.43.0
```
pub const DIGITS: u32 = 6u32
```

Approximate number of significant digits in base 10.

 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#369)1.43.0
```
pub const EPSILON: f32 = 1.1920929E-7f32
```

[Machine epsilon](https://en.wikipedia.org/wiki/Machine_epsilon) value for `f32`.

 This is the difference between `1.0` and the next larger representable number.

 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#373)1.43.0
```
pub const MIN: f32 = -3.40282347E+38f32
```

Smallest finite `f32` value.

 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#376)1.43.0
```
pub const MIN_POSITIVE: f32 = 1.17549435E-38f32
```

Smallest positive normal `f32` value.

 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#379)1.43.0
```
pub const MAX: f32 = 3.40282347E+38f32
```

Largest finite `f32` value.

 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#383)1.43.0
```
pub const MIN_EXP: i32 = -125i32
```

One greater than the minimum possible normal power of 2 exponent.

 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#386)1.43.0
```
pub const MAX_EXP: i32 = 128i32
```

Maximum possible power of 2 exponent.

 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#390)1.43.0
```
pub const MIN_10_EXP: i32 = -37i32
```

Minimum possible normal power of 10 exponent.

 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#393)1.43.0
```
pub const MAX_10_EXP: i32 = 38i32
```

Maximum possible power of 10 exponent.

 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#406)1.43.0
```
pub const NAN: f32 = NaNf32
```

Not a Number (NaN).

 Note that IEEE 754 doesn’t define just a single NaN value; a plethora of bit patterns are considered to be NaN. Furthermore, the standard makes a difference between a “signaling” and a “quiet” NaN, and allows inspecting its “payload” (the unspecified bits in the bit pattern). This constant isn’t guaranteed to equal to any specific NaN bitpattern, and the stability of its representation over Rust versions and target platforms isn’t guaranteed.

 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#409)1.43.0
```
pub const INFINITY: f32 = +Inff32
```

Infinity (∞).

 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#412)1.43.0
```
pub const NEG_INFINITY: f32 = -Inff32
```

Negative infinity (−∞).

 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#427)const: [unstable](https://github.com/rust-lang/rust/issues/72505 "Tracking issue for const_float_classify")
```
pub fn is_nan(self) -> bool
```

Returns `true` if this value is NaN.

 
```
let nan = f32::NAN;
let f = 7.0_f32;

assert!(nan.is_nan());
assert!(!f.is_nan());
```
 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#460)const: [unstable](https://github.com/rust-lang/rust/issues/72505 "Tracking issue for const_float_classify")
```
pub fn is_infinite(self) -> bool
```

Returns `true` if this value is positive infinity or negative infinity, and `false` otherwise.

 
```
let f = 7.0f32;
let inf = f32::INFINITY;
let neg_inf = f32::NEG_INFINITY;
let nan = f32::NAN;

assert!(!f.is_infinite());
assert!(!nan.is_infinite());

assert!(inf.is_infinite());
assert!(neg_inf.is_infinite());
```
 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#485)const: [unstable](https://github.com/rust-lang/rust/issues/72505 "Tracking issue for const_float_classify")
```
pub fn is_finite(self) -> bool
```

Returns `true` if this number is neither infinite nor NaN.

 
```
let f = 7.0f32;
let inf = f32::INFINITY;
let neg_inf = f32::NEG_INFINITY;
let nan = f32::NAN;

assert!(f.is_finite());

assert!(!nan.is_finite());
assert!(!inf.is_finite());
assert!(!neg_inf.is_finite());
```
 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#513)1.53.0 (const: [unstable](https://github.com/rust-lang/rust/issues/72505 "Tracking issue for const_float_classify"))
```
pub fn is_subnormal(self) -> bool
```

Returns `true` if the number is [subnormal](https://en.wikipedia.org/wiki/Denormal_number).

 
```
let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
let max = f32::MAX;
let lower_than_min = 1.0e-40_f32;
let zero = 0.0_f32;

assert!(!min.is_subnormal());
assert!(!max.is_subnormal());

assert!(!zero.is_subnormal());
assert!(!f32::NAN.is_subnormal());
assert!(!f32::INFINITY.is_subnormal());
// Values between `0` and `min` are Subnormal.
assert!(lower_than_min.is_subnormal());
```
 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#540)const: [unstable](https://github.com/rust-lang/rust/issues/72505 "Tracking issue for const_float_classify")
```
pub fn is_normal(self) -> bool
```

Returns `true` if the number is neither zero, infinite, [subnormal](https://en.wikipedia.org/wiki/Denormal_number), or NaN.

 
```
let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
let max = f32::MAX;
let lower_than_min = 1.0e-40_f32;
let zero = 0.0_f32;

assert!(min.is_normal());
assert!(max.is_normal());

assert!(!zero.is_normal());
assert!(!f32::NAN.is_normal());
assert!(!f32::INFINITY.is_normal());
// Values between `0` and `min` are Subnormal.
assert!(!lower_than_min.is_normal());
```
 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#559)const: [unstable](https://github.com/rust-lang/rust/issues/72505 "Tracking issue for const_float_classify")
```
pub fn classify(self) -> FpCategory
```

Returns the floating point category of the number. If only one property is going to be tested, it is generally faster to use the specific predicate instead.

 
```
use std::num::FpCategory;

let num = 12.4_f32;
let inf = f32::INFINITY;

assert_eq!(num.classify(), FpCategory::Normal);
assert_eq!(inf.classify(), FpCategory::Infinite);
```
 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#652)const: [unstable](https://github.com/rust-lang/rust/issues/72505 "Tracking issue for const_float_classify")
```
pub fn is_sign_positive(self) -> bool
```

Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with positive sign bit and positive infinity. Note that IEEE 754 doesn’t assign any meaning to the sign bit in case of a NaN, and as Rust doesn’t guarantee that the bit pattern of NaNs are conserved over arithmetic operations, the result of `is_sign_positive` on a NaN might produce an unexpected result in some cases. See [explanation of NaN as a special value](primitive.f32 "primitive f32") for more info.

 
```
let f = 7.0_f32;
let g = -7.0_f32;

assert!(f.is_sign_positive());
assert!(!g.is_sign_positive());
```
 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#674)const: [unstable](https://github.com/rust-lang/rust/issues/72505 "Tracking issue for const_float_classify")
```
pub fn is_sign_negative(self) -> bool
```

Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with negative sign bit and negative infinity. Note that IEEE 754 doesn’t assign any meaning to the sign bit in case of a NaN, and as Rust doesn’t guarantee that the bit pattern of NaNs are conserved over arithmetic operations, the result of `is_sign_negative` on a NaN might produce an unexpected result in some cases. See [explanation of NaN as a special value](primitive.f32 "primitive f32") for more info.

 
```
let f = 7.0f32;
let g = -7.0f32;

assert!(!f.is_sign_negative());
assert!(g.is_sign_negative());
```
 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#709)const: [unstable](https://github.com/rust-lang/rust/issues/91399 "Tracking issue for float_next_up_down")
```
pub fn next_up(self) -> f32
```

🔬This is a nightly-only experimental API. (`float_next_up_down` [#91399](https://github.com/rust-lang/rust/issues/91399))

Returns the least number greater than `self`.

 Let `TINY` be the smallest representable positive `f32`. Then,

 * if `self.is_nan()`, this returns `self`;
* if `self` is [`NEG_INFINITY`](primitive.f32#associatedconstant.NEG_INFINITY "associated constant f32::NEG_INFINITY"), this returns [`MIN`](primitive.f32#associatedconstant.MIN "associated constant f32::MIN");
* if `self` is `-TINY`, this returns -0.0;
* if `self` is -0.0 or +0.0, this returns `TINY`;
* if `self` is [`MAX`](primitive.f32#associatedconstant.MAX "associated constant f32::MAX") or [`INFINITY`](primitive.f32#associatedconstant.INFINITY "associated constant f32::INFINITY"), this returns [`INFINITY`](primitive.f32#associatedconstant.INFINITY "associated constant f32::INFINITY");
* otherwise the unique least value greater than `self` is returned.

 The identity `x.next_up() == -(-x).next_down()` holds for all non-NaN `x`. When `x` is finite `x == x.next_up().next_down()` also holds.

 
```
#![feature(float_next_up_down)]
// f32::EPSILON is the difference between 1.0 and the next number up.
assert_eq!(1.0f32.next_up(), 1.0 + f32::EPSILON);
// But not for most numbers.
assert!(0.1f32.next_up() < 0.1 + f32::EPSILON);
assert_eq!(16777216f32.next_up(), 16777218.0);
```
 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#759)const: [unstable](https://github.com/rust-lang/rust/issues/91399 "Tracking issue for float_next_up_down")
```
pub fn next_down(self) -> f32
```

🔬This is a nightly-only experimental API. (`float_next_up_down` [#91399](https://github.com/rust-lang/rust/issues/91399))

Returns the greatest number less than `self`.

 Let `TINY` be the smallest representable positive `f32`. Then,

 * if `self.is_nan()`, this returns `self`;
* if `self` is [`INFINITY`](primitive.f32#associatedconstant.INFINITY "associated constant f32::INFINITY"), this returns [`MAX`](primitive.f32#associatedconstant.MAX "associated constant f32::MAX");
* if `self` is `TINY`, this returns 0.0;
* if `self` is -0.0 or +0.0, this returns `-TINY`;
* if `self` is [`MIN`](primitive.f32#associatedconstant.MIN "associated constant f32::MIN") or [`NEG_INFINITY`](primitive.f32#associatedconstant.NEG_INFINITY "associated constant f32::NEG_INFINITY"), this returns [`NEG_INFINITY`](primitive.f32#associatedconstant.NEG_INFINITY "associated constant f32::NEG_INFINITY");
* otherwise the unique greatest value less than `self` is returned.

 The identity `x.next_down() == -(-x).next_up()` holds for all non-NaN `x`. When `x` is finite `x == x.next_down().next_up()` also holds.

 
```
#![feature(float_next_up_down)]
let x = 1.0f32;
// Clamp value into range [0, 1).
let clamped = x.clamp(0.0, 1.0f32.next_down());
assert!(clamped < 1.0);
assert_eq!(clamped.next_up(), 1.0);
```
 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#792)
```
pub fn recip(self) -> f32
```

Takes the reciprocal (inverse) of a number, `1/x`.

 
```
let x = 2.0_f32;
let abs_difference = (x.recip() - (1.0 / x)).abs();

assert!(abs_difference <= f32::EPSILON);
```
 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#809)1.7.0
```
pub fn to_degrees(self) -> f32
```

Converts radians to degrees.

 
```
let angle = std::f32::consts::PI;

let abs_difference = (angle.to_degrees() - 180.0).abs();

assert!(abs_difference <= f32::EPSILON);
```
 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#828)1.7.0
```
pub fn to_radians(self) -> f32
```

Converts degrees to radians.

 
```
let angle = 180.0f32;

let abs_difference = (angle.to_radians() - std::f32::consts::PI).abs();

assert!(abs_difference <= f32::EPSILON);
```
 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#849)
```
pub fn max(self, other: f32) -> f32
```

Returns the maximum of the two numbers, ignoring NaN.

 If one of the arguments is NaN, then the other argument is returned. This follows the IEEE 754-2008 semantics for maxNum, except for handling of signaling NaNs; this function handles all NaNs the same way and avoids maxNum’s problems with associativity. This also matches the behavior of libm’s fmax.

 
```
let x = 1.0f32;
let y = 2.0f32;

assert_eq!(x.max(y), y);
```
 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#869)
```
pub fn min(self, other: f32) -> f32
```

Returns the minimum of the two numbers, ignoring NaN.

 If one of the arguments is NaN, then the other argument is returned. This follows the IEEE 754-2008 semantics for minNum, except for handling of signaling NaNs; this function handles all NaNs the same way and avoids minNum’s problems with associativity. This also matches the behavior of libm’s fmin.

 
```
let x = 1.0f32;
let y = 2.0f32;

assert_eq!(x.min(y), x);
```
 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#896)
```
pub fn maximum(self, other: f32) -> f32
```

🔬This is a nightly-only experimental API. (`float_minimum_maximum` [#91079](https://github.com/rust-lang/rust/issues/91079))

Returns the maximum of the two numbers, propagating NaN.

 This returns NaN when *either* argument is NaN, as opposed to [`f32::max`](primitive.f32#method.max "method f32::max") which only returns NaN when *both* arguments are NaN.

 
```
#![feature(float_minimum_maximum)]
let x = 1.0f32;
let y = 2.0f32;

assert_eq!(x.maximum(y), y);
assert!(x.maximum(f32::NAN).is_nan());
```
 If one of the arguments is NaN, then NaN is returned. Otherwise this returns the greater of the two numbers. For this operation, -0.0 is considered to be less than +0.0. Note that this follows the semantics specified in IEEE 754-2019.

 Also note that “propagation” of NaNs here doesn’t necessarily mean that the bitpattern of a NaN operand is conserved; see [explanation of NaN as a special value](primitive.f32 "primitive f32") for more info.

 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#931)
```
pub fn minimum(self, other: f32) -> f32
```

🔬This is a nightly-only experimental API. (`float_minimum_maximum` [#91079](https://github.com/rust-lang/rust/issues/91079))

Returns the minimum of the two numbers, propagating NaN.

 This returns NaN when *either* argument is NaN, as opposed to [`f32::min`](primitive.f32#method.min "method f32::min") which only returns NaN when *both* arguments are NaN.

 
```
#![feature(float_minimum_maximum)]
let x = 1.0f32;
let y = 2.0f32;

assert_eq!(x.minimum(y), x);
assert!(x.minimum(f32::NAN).is_nan());
```
 If one of the arguments is NaN, then NaN is returned. Otherwise this returns the lesser of the two numbers. For this operation, -0.0 is considered to be less than +0.0. Note that this follows the semantics specified in IEEE 754-2019.

 Also note that “propagation” of NaNs here doesn’t necessarily mean that the bitpattern of a NaN operand is conserved; see [explanation of NaN as a special value](primitive.f32 "primitive f32") for more info.

 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#956)
```
pub fn midpoint(self, other: f32) -> f32
```

🔬This is a nightly-only experimental API. (`num_midpoint` [#110840](https://github.com/rust-lang/rust/issues/110840))

Calculates the middle point of `self` and `rhs`.

 This returns NaN when *either* argument is NaN or if a combination of +inf and -inf is provided as arguments.

 ##### Examples

 
```
#![feature(num_midpoint)]
assert_eq!(1f32.midpoint(4.0), 2.5);
assert_eq!((-5.5f32).midpoint(8.0), 1.25);
```
 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#1003-1005)1.44.0
```
pub unsafe fn to_int_unchecked<Int>(self) -> Int
where
    f32: FloatToInt<Int>,
```

Rounds toward zero and converts to any primitive integer type, assuming that the value is finite and fits in that type.

 
```
let value = 4.6_f32;
let rounded = unsafe { value.to_int_unchecked::<u16>() };
assert_eq!(rounded, 4);

let value = -128.9_f32;
let rounded = unsafe { value.to_int_unchecked::<i8>() };
assert_eq!(rounded, i8::MIN);
```
 ##### Safety

 The value must:

 * Not be `NaN`
* Not be infinite
* Be representable in the return type `Int`, after truncating off its fractional part

 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#1034)1.20.0 (const: [unstable](https://github.com/rust-lang/rust/issues/72447 "Tracking issue for const_float_bits_conv"))
```
pub fn to_bits(self) -> u32
```

Raw transmutation to `u32`.

 This is currently identical to `transmute::<f32, u32>(self)` on all platforms.

 See [`from_bits`](primitive.f32#method.from_bits "associated function f32::from_bits") for some discussion of the portability of this operation (there are almost no issues).

 Note that this function is distinct from `as` casting, which attempts to preserve the *numeric* value, and not the bitwise value.

 ##### Examples

 
```
assert_ne!((1f32).to_bits(), 1f32 as u32); // to_bits() is not casting!
assert_eq!((12.5f32).to_bits(), 0x41480000);

```
 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#1124)1.20.0 (const: [unstable](https://github.com/rust-lang/rust/issues/72447 "Tracking issue for const_float_bits_conv"))
```
pub fn from_bits(v: u32) -> f32
```

Raw transmutation from `u32`.

 This is currently identical to `transmute::<u32, f32>(v)` on all platforms. It turns out this is incredibly portable, for two reasons:

 * Floats and Ints have the same endianness on all supported platforms.
* IEEE 754 very precisely specifies the bit layout of floats.

 However there is one caveat: prior to the 2008 version of IEEE 754, how to interpret the NaN signaling bit wasn’t actually specified. Most platforms (notably x86 and ARM) picked the interpretation that was ultimately standardized in 2008, but some didn’t (notably MIPS). As a result, all signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.

 Rather than trying to preserve signaling-ness cross-platform, this implementation favors preserving the exact bits. This means that any payloads encoded in NaNs will be preserved even if the result of this method is sent over the network from an x86 machine to a MIPS one.

 If the results of this method are only manipulated by the same architecture that produced them, then there is no portability concern.

 If the input isn’t NaN, then there is no portability concern.

 If you don’t care about signalingness (very likely), then there is no portability concern.

 Note that this function is distinct from `as` casting, which attempts to preserve the *numeric* value, and not the bitwise value.

 ##### Examples

 
```
let v = f32::from_bits(0x41480000);
assert_eq!(v, 12.5);
```
 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#1193)1.40.0 (const: [unstable](https://github.com/rust-lang/rust/issues/72447 "Tracking issue for const_float_bits_conv"))
```
pub fn to_be_bytes(self) -> [u8; 4]
```

Return the memory representation of this floating point number as a byte array in big-endian (network) byte order.

 See [`from_bits`](primitive.f32#method.from_bits "associated function f32::from_bits") for some discussion of the portability of this operation (there are almost no issues).

 ##### Examples

 
```
let bytes = 12.5f32.to_be_bytes();
assert_eq!(bytes, [0x41, 0x48, 0x00, 0x00]);
```
 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#1214)1.40.0 (const: [unstable](https://github.com/rust-lang/rust/issues/72447 "Tracking issue for const_float_bits_conv"))
```
pub fn to_le_bytes(self) -> [u8; 4]
```

Return the memory representation of this floating point number as a byte array in little-endian byte order.

 See [`from_bits`](primitive.f32#method.from_bits "associated function f32::from_bits") for some discussion of the portability of this operation (there are almost no issues).

 ##### Examples

 
```
let bytes = 12.5f32.to_le_bytes();
assert_eq!(bytes, [0x00, 0x00, 0x48, 0x41]);
```
 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#1248)1.40.0 (const: [unstable](https://github.com/rust-lang/rust/issues/72447 "Tracking issue for const_float_bits_conv"))
```
pub fn to_ne_bytes(self) -> [u8; 4]
```

Return the memory representation of this floating point number as a byte array in native byte order.

 As the target platform’s native endianness is used, portable code should use [`to_be_bytes`](primitive.f32#method.to_be_bytes "method f32::to_be_bytes") or [`to_le_bytes`](primitive.f32#method.to_le_bytes "method f32::to_le_bytes"), as appropriate, instead.

 See [`from_bits`](primitive.f32#method.from_bits "associated function f32::from_bits") for some discussion of the portability of this operation (there are almost no issues).

 ##### Examples

 
```
let bytes = 12.5f32.to_ne_bytes();
assert_eq!(
    bytes,
    if cfg!(target_endian = "big") {
        [0x41, 0x48, 0x00, 0x00]
    } else {
        [0x00, 0x00, 0x48, 0x41]
    }
);
```
 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#1267)1.40.0 (const: [unstable](https://github.com/rust-lang/rust/issues/72447 "Tracking issue for const_float_bits_conv"))
```
pub fn from_be_bytes(bytes: [u8; 4]) -> f32
```

Create a floating point value from its representation as a byte array in big endian.

 See [`from_bits`](primitive.f32#method.from_bits "associated function f32::from_bits") for some discussion of the portability of this operation (there are almost no issues).

 ##### Examples

 
```
let value = f32::from_be_bytes([0x41, 0x48, 0x00, 0x00]);
assert_eq!(value, 12.5);
```
 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#1286)1.40.0 (const: [unstable](https://github.com/rust-lang/rust/issues/72447 "Tracking issue for const_float_bits_conv"))
```
pub fn from_le_bytes(bytes: [u8; 4]) -> f32
```

Create a floating point value from its representation as a byte array in little endian.

 See [`from_bits`](primitive.f32#method.from_bits "associated function f32::from_bits") for some discussion of the portability of this operation (there are almost no issues).

 ##### Examples

 
```
let value = f32::from_le_bytes([0x00, 0x00, 0x48, 0x41]);
assert_eq!(value, 12.5);
```
 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#1316)1.40.0 (const: [unstable](https://github.com/rust-lang/rust/issues/72447 "Tracking issue for const_float_bits_conv"))
```
pub fn from_ne_bytes(bytes: [u8; 4]) -> f32
```

Create a floating point value from its representation as a byte array in native endian.

 As the target platform’s native endianness is used, portable code likely wants to use [`from_be_bytes`](primitive.f32#method.from_be_bytes "associated function f32::from_be_bytes") or [`from_le_bytes`](primitive.f32#method.from_le_bytes "associated function f32::from_le_bytes"), as appropriate instead.

 See [`from_bits`](primitive.f32#method.from_bits "associated function f32::from_bits") for some discussion of the portability of this operation (there are almost no issues).

 ##### Examples

 
```
let value = f32::from_ne_bytes(if cfg!(target_endian = "big") {
    [0x41, 0x48, 0x00, 0x00]
} else {
    [0x00, 0x00, 0x48, 0x41]
});
assert_eq!(value, 12.5);
```
 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#1374)1.62.0
```
pub fn total_cmp(&self, other: &f32) -> Ordering
```

Return the ordering between `self` and `other`.

 Unlike the standard partial comparison between floating point numbers, this comparison always produces an ordering in accordance to the `totalOrder` predicate as defined in the IEEE 754 (2008 revision) floating point standard. The values are ordered in the following sequence:

 * negative quiet NaN
* negative signaling NaN
* negative infinity
* negative numbers
* negative subnormal numbers
* negative zero
* positive zero
* positive subnormal numbers
* positive numbers
* positive infinity
* positive signaling NaN
* positive quiet NaN.

 The ordering established by this function does not always agree with the [`PartialOrd`](cmp/trait.partialord "trait std::cmp::PartialOrd") and [`PartialEq`](cmp/trait.partialeq "trait std::cmp::PartialEq") implementations of `f32`. For example, they consider negative and positive zero equal, while `total_cmp` doesn’t.

 The interpretation of the signaling NaN bit follows the definition in the IEEE 754 standard, which may not match the interpretation by some of the older, non-conformant (e.g. MIPS) hardware implementations.

 ##### Example

 
```
struct GoodBoy {
    name: String,
    weight: f32,
}

let mut bois = vec![
    GoodBoy { name: "Pucci".to_owned(), weight: 0.1 },
    GoodBoy { name: "Woofer".to_owned(), weight: 99.0 },
    GoodBoy { name: "Yapper".to_owned(), weight: 10.0 },
    GoodBoy { name: "Chonk".to_owned(), weight: f32::INFINITY },
    GoodBoy { name: "Abs. Unit".to_owned(), weight: f32::NAN },
    GoodBoy { name: "Floaty".to_owned(), weight: -5.0 },
];

bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
```
 
[source](https://doc.rust-lang.org/src/core/num/f32.rs.html#1429)1.50.0
```
pub fn clamp(self, min: f32, max: f32) -> f32
```

Restrict a value to a certain interval unless it is NaN.

 Returns `max` if `self` is greater than `max`, and `min` if `self` is less than `min`. Otherwise this returns `self`.

 Note that this function returns NaN if the initial value was NaN as well.

 ##### Panics

 Panics if `min > max`, `min` is NaN, or `max` is NaN.

 ##### Examples

 
```
assert!((-3.0f32).clamp(-2.0, 1.0) == -2.0);
assert!((0.0f32).clamp(-2.0, 1.0) == 0.0);
assert!((2.0f32).clamp(-2.0, 1.0) == 1.0);
assert!((f32::NAN).clamp(-2.0, 1.0).is_nan());
```
 


Trait Implementations
---------------------



[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#109)
```
impl Add<&f32> for &f32
```


```
type Output = <f32 as Add<f32>>::Output
```
The resulting type after applying the `+` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#109)
```
fn add(self, other: &f32) -> <f32 as Add<f32>>::Output
```
Performs the `+` operation. [Read more](ops/trait.add#tymethod.add)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#109)
```
impl Add<&f32> for f32
```


```
type Output = <f32 as Add<f32>>::Output
```
The resulting type after applying the `+` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#109)
```
fn add(self, other: &f32) -> <f32 as Add<f32>>::Output
```
Performs the `+` operation. [Read more](ops/trait.add#tymethod.add)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#109)
```
impl<'a> Add<f32> for &'a f32
```


```
type Output = <f32 as Add<f32>>::Output
```
The resulting type after applying the `+` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#109)
```
fn add(self, other: f32) -> <f32 as Add<f32>>::Output
```
Performs the `+` operation. [Read more](ops/trait.add#tymethod.add)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#109)
```
impl Add<f32> for f32
```


```
type Output = f32
```
The resulting type after applying the `+` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#109)
```
fn add(self, other: f32) -> f32
```
Performs the `+` operation. [Read more](ops/trait.add#tymethod.add)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#760)1.22.0
```
impl AddAssign<&f32> for f32
```

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#760)
```
fn add_assign(&mut self, other: &f32)
```
Performs the `+=` operation. [Read more](ops/trait.addassign#tymethod.add_assign)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#760)1.8.0
```
impl AddAssign<f32> for f32
```

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#760)
```
fn add_assign(&mut self, other: f32)
```
Performs the `+=` operation. [Read more](ops/trait.addassign#tymethod.add_assign)


[source](https://doc.rust-lang.org/src/core/clone.rs.html#189-194)
```
impl Clone for f32
```

[source](https://doc.rust-lang.org/src/core/clone.rs.html#189-194)
```
fn clone(&self) -> f32
```
Returns a copy of the value. [Read more](clone/trait.clone#tymethod.clone)

[source](https://doc.rust-lang.org/src/core/clone.rs.html#129)
```
fn clone_from(&mut self, source: &Self)
```
Performs copy-assignment from `source`. [Read more](clone/trait.clone#method.clone_from)


[source](https://doc.rust-lang.org/src/core/fmt/float.rs.html#229)
```
impl Debug for f32
```

[source](https://doc.rust-lang.org/src/core/fmt/float.rs.html#229)
```
fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter. [Read more](fmt/trait.debug#tymethod.fmt)


[source](https://doc.rust-lang.org/src/core/default.rs.html#220)
```
impl Default for f32
```

[source](https://doc.rust-lang.org/src/core/default.rs.html#220)
```
fn default() -> f32
```

Returns the default value of `0.0`

 

[source](https://doc.rust-lang.org/src/core/fmt/float.rs.html#229)
```
impl Display for f32
```

[source](https://doc.rust-lang.org/src/core/fmt/float.rs.html#229)
```
fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter. [Read more](fmt/trait.display#tymethod.fmt)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#503)
```
impl Div<&f32> for &f32
```


```
type Output = <f32 as Div<f32>>::Output
```
The resulting type after applying the `/` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#503)
```
fn div(self, other: &f32) -> <f32 as Div<f32>>::Output
```
Performs the `/` operation. [Read more](ops/trait.div#tymethod.div)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#503)
```
impl Div<&f32> for f32
```


```
type Output = <f32 as Div<f32>>::Output
```
The resulting type after applying the `/` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#503)
```
fn div(self, other: &f32) -> <f32 as Div<f32>>::Output
```
Performs the `/` operation. [Read more](ops/trait.div#tymethod.div)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#503)
```
impl<'a> Div<f32> for &'a f32
```


```
type Output = <f32 as Div<f32>>::Output
```
The resulting type after applying the `/` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#503)
```
fn div(self, other: f32) -> <f32 as Div<f32>>::Output
```
Performs the `/` operation. [Read more](ops/trait.div#tymethod.div)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#503)
```
impl Div<f32> for f32
```


```
type Output = f32
```
The resulting type after applying the `/` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#503)
```
fn div(self, other: f32) -> f32
```
Performs the `/` operation. [Read more](ops/trait.div#tymethod.div)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#939)1.22.0
```
impl DivAssign<&f32> for f32
```

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#939)
```
fn div_assign(&mut self, other: &f32)
```
Performs the `/=` operation. [Read more](ops/trait.divassign#tymethod.div_assign)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#939)1.8.0
```
impl DivAssign<f32> for f32
```

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#939)
```
fn div_assign(&mut self, other: f32)
```
Performs the `/=` operation. [Read more](ops/trait.divassign#tymethod.div_assign)


[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#172)1.68.0
```
impl From<bool> for f32
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#186)
```
fn from(small: bool) -> f32
```

Converts `bool` to `f32` losslessly. The resulting value is positive `0.0` for `false` and `1.0` for `true` values.

 ##### Examples

 
```
let x: f32 = false.into();
assert_eq!(x, 0.0);
assert!(x.is_sign_positive());

let y: f32 = true.into();
assert_eq!(y, 1.0);
```
 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#168)1.6.0
```
impl From<f32> for f64
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#168)
```
fn from(small: f32) -> f64
```

Converts `f32` to `f64` losslessly.

 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#156)1.6.0
```
impl From<i16> for f32
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#156)
```
fn from(small: i16) -> f32
```

Converts `i16` to `f32` losslessly.

 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#154)1.6.0
```
impl From<i8> for f32
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#154)
```
fn from(small: i8) -> f32
```

Converts `i8` to `f32` losslessly.

 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#163)1.6.0
```
impl From<u16> for f32
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#163)
```
fn from(small: u16) -> f32
```

Converts `u16` to `f32` losslessly.

 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#161)1.6.0
```
impl From<u8> for f32
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#161)
```
fn from(small: u8) -> f32
```

Converts `u8` to `f32` losslessly.

 

[source](https://doc.rust-lang.org/src/core/num/dec2flt/mod.rs.html#163)
```
impl FromStr for f32
```

[source](https://doc.rust-lang.org/src/core/num/dec2flt/mod.rs.html#163)
```
fn from_str(src: &str) -> Result<f32, ParseFloatError>
```

Converts a string in base 10 to a float. Accepts an optional decimal exponent.

 This function accepts strings such as

 * ‘3.14’
* ‘-3.14’
* ‘2.5E10’, or equivalently, ‘2.5e10’
* ‘2.5E-10’
* ‘5.’
* ‘.5’, or, equivalently, ‘0.5’
* ‘inf’, ‘-inf’, ‘+infinity’, ‘NaN’

 Note that alphabetical characters are not case-sensitive.

 Leading and trailing whitespace represent an error.

 ##### Grammar

 All strings that adhere to the following [EBNF](https://www.w3.org/TR/REC-xml/#sec-notation) grammar when lowercased will result in an [`Ok`](result/enum.result#variant.Ok "variant std::result::Result::Ok") being returned:

 
```
Float  ::= Sign? ( 'inf' | 'infinity' | 'nan' | Number )
Number ::= ( Digit+ |
             Digit+ '.' Digit* |
             Digit* '.' Digit+ ) Exp?
Exp    ::= 'e' Sign? Digit+
Sign   ::= [+-]
Digit  ::= [0-9]

```

##### Arguments

 * src - A string

 ##### Return value

 `Err(ParseFloatError)` if the string did not represent a valid number. Otherwise, `Ok(n)` where `n` is the closest representable floating-point number to the number represented by `src` (following the same rules for rounding as for the results of primitive operations).

 

```
type Err = ParseFloatError
```
The associated error which can be returned from parsing.

[source](https://doc.rust-lang.org/src/core/fmt/float.rs.html#229)
```
impl LowerExp for f32
```

[source](https://doc.rust-lang.org/src/core/fmt/float.rs.html#229)
```
fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter.

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#346)
```
impl Mul<&f32> for &f32
```


```
type Output = <f32 as Mul<f32>>::Output
```
The resulting type after applying the `*` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#346)
```
fn mul(self, other: &f32) -> <f32 as Mul<f32>>::Output
```
Performs the `*` operation. [Read more](ops/trait.mul#tymethod.mul)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#346)
```
impl Mul<&f32> for f32
```


```
type Output = <f32 as Mul<f32>>::Output
```
The resulting type after applying the `*` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#346)
```
fn mul(self, other: &f32) -> <f32 as Mul<f32>>::Output
```
Performs the `*` operation. [Read more](ops/trait.mul#tymethod.mul)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#346)
```
impl<'a> Mul<f32> for &'a f32
```


```
type Output = <f32 as Mul<f32>>::Output
```
The resulting type after applying the `*` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#346)
```
fn mul(self, other: f32) -> <f32 as Mul<f32>>::Output
```
Performs the `*` operation. [Read more](ops/trait.mul#tymethod.mul)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#346)
```
impl Mul<f32> for f32
```


```
type Output = f32
```
The resulting type after applying the `*` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#346)
```
fn mul(self, other: f32) -> f32
```
Performs the `*` operation. [Read more](ops/trait.mul#tymethod.mul)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#883)1.22.0
```
impl MulAssign<&f32> for f32
```

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#883)
```
fn mul_assign(&mut self, other: &f32)
```
Performs the `*=` operation. [Read more](ops/trait.mulassign#tymethod.mul_assign)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#883)1.8.0
```
impl MulAssign<f32> for f32
```

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#883)
```
fn mul_assign(&mut self, other: f32)
```
Performs the `*=` operation. [Read more](ops/trait.mulassign#tymethod.mul_assign)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#694)
```
impl Neg for &f32
```


```
type Output = <f32 as Neg>::Output
```
The resulting type after applying the `-` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#694)
```
fn neg(self) -> <f32 as Neg>::Output
```
Performs the unary `-` operation. [Read more](ops/trait.neg#tymethod.neg)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#694)
```
impl Neg for f32
```


```
type Output = f32
```
The resulting type after applying the `-` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#694)
```
fn neg(self) -> f32
```
Performs the unary `-` operation. [Read more](ops/trait.neg#tymethod.neg)


[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1298-1300)
```
impl PartialEq<f32> for f32
```

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1298-1300)
```
fn eq(&self, other: &f32) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1298-1300)
```
fn ne(&self, other: &f32) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1352)
```
impl PartialOrd<f32> for f32
```

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1352)
```
fn partial_cmp(&self, other: &f32) -> Option<Ordering>
```
This method returns an ordering between `self` and `other` values if one exists. [Read more](cmp/trait.partialord#tymethod.partial_cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1352)
```
fn lt(&self, other: &f32) -> bool
```
This method tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](cmp/trait.partialord#method.lt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1352)
```
fn le(&self, other: &f32) -> bool
```
This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](cmp/trait.partialord#method.le)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1352)
```
fn ge(&self, other: &f32) -> bool
```
This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](cmp/trait.partialord#method.ge)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1352)
```
fn gt(&self, other: &f32) -> bool
```
This method tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](cmp/trait.partialord#method.gt)


[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#150)1.12.0
```
impl<'a> Product<&'a f32> for f32
```

[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#150)
```
fn product<I>(iter: I) -> f32
where
    I: Iterator<Item = &'a f32>,
```
Method which takes an iterator and generates `Self` from the elements by multiplying the items.

[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#150)1.12.0
```
impl Product<f32> for f32
```

[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#150)
```
fn product<I>(iter: I) -> f32
where
    I: Iterator<Item = f32>,
```
Method which takes an iterator and generates `Self` from the elements by multiplying the items.

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#619)
```
impl Rem<&f32> for &f32
```


```
type Output = <f32 as Rem<f32>>::Output
```
The resulting type after applying the `%` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#619)
```
fn rem(self, other: &f32) -> <f32 as Rem<f32>>::Output
```
Performs the `%` operation. [Read more](ops/trait.rem#tymethod.rem)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#619)
```
impl Rem<&f32> for f32
```


```
type Output = <f32 as Rem<f32>>::Output
```
The resulting type after applying the `%` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#619)
```
fn rem(self, other: &f32) -> <f32 as Rem<f32>>::Output
```
Performs the `%` operation. [Read more](ops/trait.rem#tymethod.rem)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#619)
```
impl<'a> Rem<f32> for &'a f32
```


```
type Output = <f32 as Rem<f32>>::Output
```
The resulting type after applying the `%` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#619)
```
fn rem(self, other: f32) -> <f32 as Rem<f32>>::Output
```
Performs the `%` operation. [Read more](ops/trait.rem#tymethod.rem)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#619)
```
impl Rem<f32> for f32
```

The remainder from the division of two floats.

 The remainder has the same sign as the dividend and is computed as: `x - (x / y).trunc() * y`.

 #### Examples

 
```
let x: f32 = 50.50;
let y: f32 = 8.125;
let remainder = x - (x / y).trunc() * y;

// The answer to both operations is 1.75
assert_eq!(x % y, remainder);
```
 


```
type Output = f32
```
The resulting type after applying the `%` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#619)
```
fn rem(self, other: f32) -> f32
```
Performs the `%` operation. [Read more](ops/trait.rem#tymethod.rem)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#999)1.22.0
```
impl RemAssign<&f32> for f32
```

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#999)
```
fn rem_assign(&mut self, other: &f32)
```
Performs the `%=` operation. [Read more](ops/trait.remassign#tymethod.rem_assign)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#999)1.8.0
```
impl RemAssign<f32> for f32
```

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#999)
```
fn rem_assign(&mut self, other: f32)
```
Performs the `%=` operation. [Read more](ops/trait.remassign#tymethod.rem_assign)


[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/vector.rs.html#994)
```
impl SimdElement for f32
```


```
type Mask = i32
```

🔬This is a nightly-only experimental API. (`portable_simd` [#86656](https://github.com/rust-lang/rust/issues/86656))
The mask element type corresponding to this element type.

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#217)
```
impl Sub<&f32> for &f32
```


```
type Output = <f32 as Sub<f32>>::Output
```
The resulting type after applying the `-` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#217)
```
fn sub(self, other: &f32) -> <f32 as Sub<f32>>::Output
```
Performs the `-` operation. [Read more](ops/trait.sub#tymethod.sub)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#217)
```
impl Sub<&f32> for f32
```


```
type Output = <f32 as Sub<f32>>::Output
```
The resulting type after applying the `-` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#217)
```
fn sub(self, other: &f32) -> <f32 as Sub<f32>>::Output
```
Performs the `-` operation. [Read more](ops/trait.sub#tymethod.sub)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#217)
```
impl<'a> Sub<f32> for &'a f32
```


```
type Output = <f32 as Sub<f32>>::Output
```
The resulting type after applying the `-` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#217)
```
fn sub(self, other: f32) -> <f32 as Sub<f32>>::Output
```
Performs the `-` operation. [Read more](ops/trait.sub#tymethod.sub)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#217)
```
impl Sub<f32> for f32
```


```
type Output = f32
```
The resulting type after applying the `-` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#217)
```
fn sub(self, other: f32) -> f32
```
Performs the `-` operation. [Read more](ops/trait.sub#tymethod.sub)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#826)1.22.0
```
impl SubAssign<&f32> for f32
```

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#826)
```
fn sub_assign(&mut self, other: &f32)
```
Performs the `-=` operation. [Read more](ops/trait.subassign#tymethod.sub_assign)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#826)1.8.0
```
impl SubAssign<f32> for f32
```

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#826)
```
fn sub_assign(&mut self, other: f32)
```
Performs the `-=` operation. [Read more](ops/trait.subassign#tymethod.sub_assign)


[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#150)1.12.0
```
impl<'a> Sum<&'a f32> for f32
```

[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#150)
```
fn sum<I>(iter: I) -> f32
where
    I: Iterator<Item = &'a f32>,
```
Method which takes an iterator and generates `Self` from the elements by “summing up” the items.

[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#150)1.12.0
```
impl Sum<f32> for f32
```

[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#150)
```
fn sum<I>(iter: I) -> f32
where
    I: Iterator<Item = f32>,
```
Method which takes an iterator and generates `Self` from the elements by “summing up” the items.

[source](https://doc.rust-lang.org/src/core/fmt/float.rs.html#229)
```
impl UpperExp for f32
```

[source](https://doc.rust-lang.org/src/core/fmt/float.rs.html#229)
```
fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter.

[source](https://doc.rust-lang.org/src/core/marker.rs.html#467-477)
```
impl Copy for f32
```
[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#38)
```
impl FloatToInt<i128> for f32
```
[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#38)
```
impl FloatToInt<i16> for f32
```
[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#38)
```
impl FloatToInt<i32> for f32
```
[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#38)
```
impl FloatToInt<i64> for f32
```
[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#38)
```
impl FloatToInt<i8> for f32
```
[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#38)
```
impl FloatToInt<isize> for f32
```
[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#38)
```
impl FloatToInt<u128> for f32
```
[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#38)
```
impl FloatToInt<u16> for f32
```
[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#38)
```
impl FloatToInt<u32> for f32
```
[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#38)
```
impl FloatToInt<u64> for f32
```
[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#38)
```
impl FloatToInt<u8> for f32
```
[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#38)
```
impl FloatToInt<usize> for f32
```
[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/cast.rs.html#31)
```
impl SimdCast for f32
```


Auto Trait Implementations
--------------------------




```
impl RefUnwindSafe for f32
```

```
impl Send for f32
```

```
impl Sync for f32
```

```
impl Unpin for f32
```

```
impl UnwindSafe for f32
```


Blanket Implementations
-----------------------



[source](https://doc.rust-lang.org/src/core/any.rs.html#200)
```
impl<T> Any for T
where
    T: 'static + ?Sized,
```

[source](https://doc.rust-lang.org/src/core/any.rs.html#201)
```
fn type_id(&self) -> TypeId
```
Gets the `TypeId` of `self`. [Read more](any/trait.any#tymethod.type_id)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#208)
```
impl<T> Borrow<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#210)
```
fn borrow(&self) -> &T
```
Immutably borrows from an owned value. [Read more](borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#216)
```
impl<T> BorrowMut<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#217)
```
fn borrow_mut(&mut self) -> &mut T
```
Mutably borrows from an owned value. [Read more](borrow/trait.borrowmut#tymethod.borrow_mut)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#723)
```
impl<T> From<T> for T
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#726)
```
fn from(t: T) -> T
```

Returns the argument unchanged.

 

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#707)
```
impl<T, U> Into<U> for T
where
    U: From<T>,
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#716)
```
fn into(self) -> U
```

Calls `U::from(self)`.

 That is, this conversion is whatever the implementation of `[From](convert/trait.from "trait std::convert::From")<T> for U` chooses to do.

 

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#82)
```
impl<T> ToOwned for T
where
    T: Clone,
```


```
type Owned = T
```
The resulting type after obtaining ownership.
[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#87)
```
fn to_owned(&self) -> T
```
Creates owned data from borrowed data, usually by cloning. [Read more](borrow/trait.toowned#tymethod.to_owned)

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#91)
```
fn clone_into(&self, target: &mut T)
```
Uses borrowed data to replace owned data, usually by cloning. [Read more](borrow/trait.toowned#method.clone_into)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2513)
```
impl<T> ToString for T
where
    T: Display + ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2519)
```
default fn to_string(&self) -> String
```
Converts the given value to a `String`. [Read more](string/trait.tostring#tymethod.to_string)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#763)
```
impl<T, U> TryFrom<U> for T
where
    U: Into<T>,
```


```
type Error = Infallible
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#770)
```
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#748)
```
impl<T, U> TryInto<U> for T
where
    U: TryFrom<T>,
```


```
type Error = <U as TryFrom<T>>::Error
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#755)
```
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
```
Performs the conversion.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/primitive.f32.html>

Primitive Type f64
==================


A 64-bit floating point type (specifically, the “binary64” type defined in IEEE 754-2008).

 This type is very similar to [`f32`](primitive.f32 "primitive f32"), but has increased precision by using twice as many bits. Please see [the documentation for `f32`](primitive.f32 "primitive f32") or [Wikipedia on double precision values](https://en.wikipedia.org/wiki/Double-precision_floating-point_format) for more information.

 *[See also the `std::f64::consts` module](f64/consts/index "mod std::f64::consts").*

 Implementations
---------------



[source](https://doc.rust-lang.org/src/std/f64.rs.html#31-989)
```
impl f64
```

[source](https://doc.rust-lang.org/src/std/f64.rs.html#49-51)
```
pub fn floor(self) -> f64
```

Returns the largest integer less than or equal to `self`.

 ##### Examples

 
```
let f = 3.7_f64;
let g = 3.0_f64;
let h = -3.7_f64;

assert_eq!(f.floor(), 3.0);
assert_eq!(g.floor(), 3.0);
assert_eq!(h.floor(), -4.0);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#68-70)
```
pub fn ceil(self) -> f64
```

Returns the smallest integer greater than or equal to `self`.

 ##### Examples

 
```
let f = 3.01_f64;
let g = 4.0_f64;

assert_eq!(f.ceil(), 4.0);
assert_eq!(g.ceil(), 4.0);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#94-96)
```
pub fn round(self) -> f64
```

Returns the nearest integer to `self`. If a value is half-way between two integers, round away from `0.0`.

 ##### Examples

 
```
let f = 3.3_f64;
let g = -3.3_f64;
let h = -3.7_f64;
let i = 3.5_f64;
let j = 4.5_f64;

assert_eq!(f.round(), 3.0);
assert_eq!(g.round(), -3.0);
assert_eq!(h.round(), -4.0);
assert_eq!(i.round(), 4.0);
assert_eq!(j.round(), 5.0);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#120-122)
```
pub fn round_ties_even(self) -> f64
```

🔬This is a nightly-only experimental API. (`round_ties_even` [#96710](https://github.com/rust-lang/rust/issues/96710))

Returns the nearest integer to a number. Rounds half-way cases to the number with an even least significant digit.

 ##### Examples

 
```
#![feature(round_ties_even)]

let f = 3.3_f64;
let g = -3.3_f64;
let h = 3.5_f64;
let i = 4.5_f64;

assert_eq!(f.round_ties_even(), 3.0);
assert_eq!(g.round_ties_even(), -3.0);
assert_eq!(h.round_ties_even(), 4.0);
assert_eq!(i.round_ties_even(), 4.0);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#142-144)
```
pub fn trunc(self) -> f64
```

Returns the integer part of `self`. This means that non-integer numbers are always truncated towards zero.

 ##### Examples

 
```
let f = 3.7_f64;
let g = 3.0_f64;
let h = -3.7_f64;

assert_eq!(f.trunc(), 3.0);
assert_eq!(g.trunc(), 3.0);
assert_eq!(h.trunc(), -3.0);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#163-165)
```
pub fn fract(self) -> f64
```

Returns the fractional part of `self`.

 ##### Examples

 
```
let x = 3.6_f64;
let y = -3.6_f64;
let abs_difference_x = (x.fract() - 0.6).abs();
let abs_difference_y = (y.fract() - (-0.6)).abs();

assert!(abs_difference_x < 1e-10);
assert!(abs_difference_y < 1e-10);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#187-189)
```
pub fn abs(self) -> f64
```

Computes the absolute value of `self`.

 ##### Examples

 
```
let x = 3.5_f64;
let y = -3.5_f64;

let abs_difference_x = (x.abs() - x).abs();
let abs_difference_y = (y.abs() - (-y)).abs();

assert!(abs_difference_x < 1e-10);
assert!(abs_difference_y < 1e-10);

assert!(f64::NAN.abs().is_nan());
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#211-213)
```
pub fn signum(self) -> f64
```

Returns a number that represents the sign of `self`.

 * `1.0` if the number is positive, `+0.0` or `INFINITY`
* `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
* NaN if the number is NaN

 ##### Examples

 
```
let f = 3.5_f64;

assert_eq!(f.signum(), 1.0);
assert_eq!(f64::NEG_INFINITY.signum(), -1.0);

assert!(f64::NAN.signum().is_nan());
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#240-242)1.35.0
```
pub fn copysign(self, sign: f64) -> f64
```

Returns a number composed of the magnitude of `self` and the sign of `sign`.

 Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`. If `self` is a NaN, then a NaN with the sign bit of `sign` is returned. Note, however, that conserving the sign bit on NaN across arithmetical operations is not generally guaranteed. See [explanation of NaN as a special value](primitive.f32 "primitive f32") for more info.

 ##### Examples

 
```
let f = 3.5_f64;

assert_eq!(f.copysign(0.42), 3.5_f64);
assert_eq!(f.copysign(-0.42), -3.5_f64);
assert_eq!((-f).copysign(0.42), 3.5_f64);
assert_eq!((-f).copysign(-0.42), -3.5_f64);

assert!(f64::NAN.copysign(1.0).is_nan());
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#268-270)
```
pub fn mul_add(self, a: f64, b: f64) -> f64
```

Fused multiply-add. Computes `(self * a) + b` with only one rounding error, yielding a more accurate result than an unfused multiply-add.

 Using `mul_add` *may* be more performant than an unfused multiply-add if the target architecture has a dedicated `fma` CPU instruction. However, this is not always true, and will be heavily dependant on designing algorithms with specific target hardware in mind.

 ##### Examples

 
```
let m = 10.0_f64;
let x = 4.0_f64;
let b = 60.0_f64;

// 100.0
let abs_difference = (m.mul_add(x, b) - ((m * x) + b)).abs();

assert!(abs_difference < 1e-10);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#293-299)1.38.0
```
pub fn div_euclid(self, rhs: f64) -> f64
```

Calculates Euclidean division, the matching method for `rem_euclid`.

 This computes the integer `n` such that `self = n * rhs + self.rem_euclid(rhs)`. In other words, the result is `self / rhs` rounded to the integer `n` such that `self >= n * rhs`.

 ##### Examples

 
```
let a: f64 = 7.0;
let b = 4.0;
assert_eq!(a.div_euclid(b), 1.0); // 7.0 > 4.0 * 1.0
assert_eq!((-a).div_euclid(b), -2.0); // -7.0 >= 4.0 * -2.0
assert_eq!(a.div_euclid(-b), -1.0); // 7.0 >= -4.0 * -1.0
assert_eq!((-a).div_euclid(-b), 2.0); // -7.0 >= -4.0 * 2.0
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#328-331)1.38.0
```
pub fn rem_euclid(self, rhs: f64) -> f64
```

Calculates the least nonnegative remainder of `self (mod rhs)`.

 In particular, the return value `r` satisfies `0.0 <= r < rhs.abs()` in most cases. However, due to a floating point round-off error it can result in `r == rhs.abs()`, violating the mathematical definition, if `self` is much smaller than `rhs.abs()` in magnitude and `self < 0.0`. This result is not an element of the function’s codomain, but it is the closest floating point number in the real numbers and thus fulfills the property `self == self.div_euclid(rhs) * rhs + self.rem_euclid(rhs)` approximately.

 ##### Examples

 
```
let a: f64 = 7.0;
let b = 4.0;
assert_eq!(a.rem_euclid(b), 3.0);
assert_eq!((-a).rem_euclid(b), 1.0);
assert_eq!(a.rem_euclid(-b), 3.0);
assert_eq!((-a).rem_euclid(-b), 1.0);
// limitation due to round-off error
assert!((-f64::EPSILON).rem_euclid(3.0) != 0.0);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#351-353)
```
pub fn powi(self, n: i32) -> f64
```

Raises a number to an integer power.

 Using this function is generally faster than using `powf`. It might have a different sequence of rounding operations than `powf`, so the results are not guaranteed to agree.

 ##### Examples

 
```
let x = 2.0_f64;
let abs_difference = (x.powi(2) - (x * x)).abs();

assert!(abs_difference < 1e-10);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#369-371)
```
pub fn powf(self, n: f64) -> f64
```

Raises a number to a floating point power.

 ##### Examples

 
```
let x = 2.0_f64;
let abs_difference = (x.powf(2.0) - (x * x)).abs();

assert!(abs_difference < 1e-10);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#394-396)
```
pub fn sqrt(self) -> f64
```

Returns the square root of a number.

 Returns NaN if `self` is a negative number other than `-0.0`.

 ##### Examples

 
```
let positive = 4.0_f64;
let negative = -4.0_f64;
let negative_zero = -0.0_f64;

let abs_difference = (positive.sqrt() - 2.0).abs();

assert!(abs_difference < 1e-10);
assert!(negative.sqrt().is_nan());
assert!(negative_zero.sqrt() == negative_zero);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#416-418)
```
pub fn exp(self) -> f64
```

Returns `e^(self)`, (the exponential function).

 ##### Examples

 
```
let one = 1.0_f64;
// e^1
let e = one.exp();

// ln(e) - 1 == 0
let abs_difference = (e.ln() - 1.0).abs();

assert!(abs_difference < 1e-10);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#436-438)
```
pub fn exp2(self) -> f64
```

Returns `2^(self)`.

 ##### Examples

 
```
let f = 2.0_f64;

// 2^2 - 4 == 0
let abs_difference = (f.exp2() - 4.0).abs();

assert!(abs_difference < 1e-10);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#458-460)
```
pub fn ln(self) -> f64
```

Returns the natural logarithm of the number.

 ##### Examples

 
```
let one = 1.0_f64;
// e^1
let e = one.exp();

// ln(e) - 1 == 0
let abs_difference = (e.ln() - 1.0).abs();

assert!(abs_difference < 1e-10);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#482-484)
```
pub fn log(self, base: f64) -> f64
```

Returns the logarithm of the number with respect to an arbitrary base.

 The result might not be correctly rounded owing to implementation details; `self.log2()` can produce more accurate results for base 2, and `self.log10()` can produce more accurate results for base 10.

 ##### Examples

 
```
let twenty_five = 25.0_f64;

// log5(25) - 2 == 0
let abs_difference = (twenty_five.log(5.0) - 2.0).abs();

assert!(abs_difference < 1e-10);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#502-509)
```
pub fn log2(self) -> f64
```

Returns the base 2 logarithm of the number.

 ##### Examples

 
```
let four = 4.0_f64;

// log2(4) - 2 == 0
let abs_difference = (four.log2() - 2.0).abs();

assert!(abs_difference < 1e-10);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#527-529)
```
pub fn log10(self) -> f64
```

Returns the base 10 logarithm of the number.

 ##### Examples

 
```
let hundred = 100.0_f64;

// log10(100) - 2 == 0
let abs_difference = (hundred.log10() - 2.0).abs();

assert!(abs_difference < 1e-10);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#562-564)
```
pub fn abs_sub(self, other: f64) -> f64
```

👎Deprecated since 1.10.0: you probably meant `(self - other).abs()`: this operation is `(self - other).max(0.0)` except that `abs_sub` also propagates NaNs (also known as `fdim` in C). If you truly need the positive difference, consider using that expression or the C function `fdim`, depending on how you wish to handle NaN (please consider filing an issue describing your use-case too).

The positive difference of two numbers.

 * If `self <= other`: `0:0`
* Else: `self - other`

 ##### Examples

 
```
let x = 3.0_f64;
let y = -3.0_f64;

let abs_difference_x = (x.abs_sub(1.0) - 2.0).abs();
let abs_difference_y = (y.abs_sub(1.0) - 0.0).abs();

assert!(abs_difference_x < 1e-10);
assert!(abs_difference_y < 1e-10);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#582-584)
```
pub fn cbrt(self) -> f64
```

Returns the cube root of a number.

 ##### Examples

 
```
let x = 8.0_f64;

// x^(1/3) - 2 == 0
let abs_difference = (x.cbrt() - 2.0).abs();

assert!(abs_difference < 1e-10);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#606-608)
```
pub fn hypot(self, other: f64) -> f64
```

Compute the distance between the origin and a point (`x`, `y`) on the Euclidean plane. Equivalently, compute the length of the hypotenuse of a right-angle triangle with other sides having length `x.abs()` and `y.abs()`.

 ##### Examples

 
```
let x = 2.0_f64;
let y = 3.0_f64;

// sqrt(x^2 + y^2)
let abs_difference = (x.hypot(y) - (x.powi(2) + y.powi(2)).sqrt()).abs();

assert!(abs_difference < 1e-10);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#625-627)
```
pub fn sin(self) -> f64
```

Computes the sine of a number (in radians).

 ##### Examples

 
```
let x = std::f64::consts::FRAC_PI_2;

let abs_difference = (x.sin() - 1.0).abs();

assert!(abs_difference < 1e-10);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#644-646)
```
pub fn cos(self) -> f64
```

Computes the cosine of a number (in radians).

 ##### Examples

 
```
let x = 2.0 * std::f64::consts::PI;

let abs_difference = (x.cos() - 1.0).abs();

assert!(abs_difference < 1e-10);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#662-664)
```
pub fn tan(self) -> f64
```

Computes the tangent of a number (in radians).

 ##### Examples

 
```
let x = std::f64::consts::FRAC_PI_4;
let abs_difference = (x.tan() - 1.0).abs();

assert!(abs_difference < 1e-14);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#684-686)
```
pub fn asin(self) -> f64
```

Computes the arcsine of a number. Return value is in radians in the range [-pi/2, pi/2] or NaN if the number is outside the range [-1, 1].

 ##### Examples

 
```
let f = std::f64::consts::FRAC_PI_2;

// asin(sin(pi/2))
let abs_difference = (f.sin().asin() - std::f64::consts::FRAC_PI_2).abs();

assert!(abs_difference < 1e-10);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#706-708)
```
pub fn acos(self) -> f64
```

Computes the arccosine of a number. Return value is in radians in the range [0, pi] or NaN if the number is outside the range [-1, 1].

 ##### Examples

 
```
let f = std::f64::consts::FRAC_PI_4;

// acos(cos(pi/4))
let abs_difference = (f.cos().acos() - std::f64::consts::FRAC_PI_4).abs();

assert!(abs_difference < 1e-10);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#727-729)
```
pub fn atan(self) -> f64
```

Computes the arctangent of a number. Return value is in radians in the range [-pi/2, pi/2];

 ##### Examples

 
```
let f = 1.0_f64;

// atan(tan(1))
let abs_difference = (f.tan().atan() - 1.0).abs();

assert!(abs_difference < 1e-10);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#761-763)
```
pub fn atan2(self, other: f64) -> f64
```

Computes the four quadrant arctangent of `self` (`y`) and `other` (`x`) in radians.

 * `x = 0`, `y = 0`: `0`
* `x >= 0`: `arctan(y/x)` -> `[-pi/2, pi/2]`
* `y >= 0`: `arctan(y/x) + pi` -> `(pi/2, pi]`
* `y < 0`: `arctan(y/x) - pi` -> `(-pi, -pi/2)`

 ##### Examples

 
```
// Positive angles measured counter-clockwise
// from positive x axis
// -pi/4 radians (45 deg clockwise)
let x1 = 3.0_f64;
let y1 = -3.0_f64;

// 3pi/4 radians (135 deg counter-clockwise)
let x2 = -3.0_f64;
let y2 = 3.0_f64;

let abs_difference_1 = (y1.atan2(x1) - (-std::f64::consts::FRAC_PI_4)).abs();
let abs_difference_2 = (y2.atan2(x2) - (3.0 * std::f64::consts::FRAC_PI_4)).abs();

assert!(abs_difference_1 < 1e-10);
assert!(abs_difference_2 < 1e-10);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#783-785)
```
pub fn sin_cos(self) -> (f64, f64)
```

Simultaneously computes the sine and cosine of the number, `x`. Returns `(sin(x), cos(x))`.

 ##### Examples

 
```
let x = std::f64::consts::FRAC_PI_4;
let f = x.sin_cos();

let abs_difference_0 = (f.0 - x.sin()).abs();
let abs_difference_1 = (f.1 - x.cos()).abs();

assert!(abs_difference_0 < 1e-10);
assert!(abs_difference_1 < 1e-10);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#805-807)
```
pub fn exp_m1(self) -> f64
```

Returns `e^(self) - 1` in a way that is accurate even if the number is close to zero.

 ##### Examples

 
```
let x = 1e-16_f64;

// for very small x, e^x is approximately 1 + x + x^2 / 2
let approx = x + x * x / 2.0;
let abs_difference = (x.exp_m1() - approx).abs();

assert!(abs_difference < 1e-20);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#827-829)
```
pub fn ln_1p(self) -> f64
```

Returns `ln(1+n)` (natural logarithm) more accurately than if the operations were performed separately.

 ##### Examples

 
```
let x = 1e-16_f64;

// for very small x, ln(1 + x) is approximately x - x^2 / 2
let approx = x - x * x / 2.0;
let abs_difference = (x.ln_1p() - approx).abs();

assert!(abs_difference < 1e-20);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#850-852)
```
pub fn sinh(self) -> f64
```

Hyperbolic sine function.

 ##### Examples

 
```
let e = std::f64::consts::E;
let x = 1.0_f64;

let f = x.sinh();
// Solving sinh() at 1 gives `(e^2-1)/(2e)`
let g = ((e * e) - 1.0) / (2.0 * e);
let abs_difference = (f - g).abs();

assert!(abs_difference < 1e-10);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#873-875)
```
pub fn cosh(self) -> f64
```

Hyperbolic cosine function.

 ##### Examples

 
```
let e = std::f64::consts::E;
let x = 1.0_f64;
let f = x.cosh();
// Solving cosh() at 1 gives this result
let g = ((e * e) + 1.0) / (2.0 * e);
let abs_difference = (f - g).abs();

// Same result
assert!(abs_difference < 1.0e-10);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#896-898)
```
pub fn tanh(self) -> f64
```

Hyperbolic tangent function.

 ##### Examples

 
```
let e = std::f64::consts::E;
let x = 1.0_f64;

let f = x.tanh();
// Solving tanh() at 1 gives `(1 - e^(-2))/(1 + e^(-2))`
let g = (1.0 - e.powi(-2)) / (1.0 + e.powi(-2));
let abs_difference = (f - g).abs();

assert!(abs_difference < 1.0e-10);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#916-920)
```
pub fn asinh(self) -> f64
```

Inverse hyperbolic sine function.

 ##### Examples

 
```
let x = 1.0_f64;
let f = x.sinh().asinh();

let abs_difference = (f - x).abs();

assert!(abs_difference < 1.0e-10);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#938-944)
```
pub fn acosh(self) -> f64
```

Inverse hyperbolic cosine function.

 ##### Examples

 
```
let x = 1.0_f64;
let f = x.cosh().acosh();

let abs_difference = (f - x).abs();

assert!(abs_difference < 1.0e-10);
```
 
[source](https://doc.rust-lang.org/src/std/f64.rs.html#962-964)
```
pub fn atanh(self) -> f64
```

Inverse hyperbolic tangent function.

 ##### Examples

 
```
let e = std::f64::consts::E;
let f = e.tanh().atanh();

let abs_difference = (f - e).abs();

assert!(abs_difference < 1.0e-10);
```
 

[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#350)
```
impl f64
```

[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#353)1.43.0
```
pub const RADIX: u32 = 2u32
```

The radix or base of the internal representation of `f64`.

 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#357)1.43.0
```
pub const MANTISSA_DIGITS: u32 = 53u32
```

Number of significant digits in base 2.

 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#360)1.43.0
```
pub const DIGITS: u32 = 15u32
```

Approximate number of significant digits in base 10.

 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#368)1.43.0
```
pub const EPSILON: f64 = 2.2204460492503131E-16f64
```

[Machine epsilon](https://en.wikipedia.org/wiki/Machine_epsilon) value for `f64`.

 This is the difference between `1.0` and the next larger representable number.

 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#372)1.43.0
```
pub const MIN: f64 = -1.7976931348623157E+308f64
```

Smallest finite `f64` value.

 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#375)1.43.0
```
pub const MIN_POSITIVE: f64 = 2.2250738585072014E-308f64
```

Smallest positive normal `f64` value.

 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#378)1.43.0
```
pub const MAX: f64 = 1.7976931348623157E+308f64
```

Largest finite `f64` value.

 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#382)1.43.0
```
pub const MIN_EXP: i32 = -1_021i32
```

One greater than the minimum possible normal power of 2 exponent.

 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#385)1.43.0
```
pub const MAX_EXP: i32 = 1_024i32
```

Maximum possible power of 2 exponent.

 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#389)1.43.0
```
pub const MIN_10_EXP: i32 = -307i32
```

Minimum possible normal power of 10 exponent.

 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#392)1.43.0
```
pub const MAX_10_EXP: i32 = 308i32
```

Maximum possible power of 10 exponent.

 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#405)1.43.0
```
pub const NAN: f64 = NaNf64
```

Not a Number (NaN).

 Note that IEEE 754 doesn’t define just a single NaN value; a plethora of bit patterns are considered to be NaN. Furthermore, the standard makes a difference between a “signaling” and a “quiet” NaN, and allows inspecting its “payload” (the unspecified bits in the bit pattern). This constant isn’t guaranteed to equal to any specific NaN bitpattern, and the stability of its representation over Rust versions and target platforms isn’t guaranteed.

 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#408)1.43.0
```
pub const INFINITY: f64 = +Inff64
```

Infinity (∞).

 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#411)1.43.0
```
pub const NEG_INFINITY: f64 = -Inff64
```

Negative infinity (−∞).

 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#426)const: [unstable](https://github.com/rust-lang/rust/issues/72505 "Tracking issue for const_float_classify")
```
pub fn is_nan(self) -> bool
```

Returns `true` if this value is NaN.

 
```
let nan = f64::NAN;
let f = 7.0_f64;

assert!(nan.is_nan());
assert!(!f.is_nan());
```
 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#461)const: [unstable](https://github.com/rust-lang/rust/issues/72505 "Tracking issue for const_float_classify")
```
pub fn is_infinite(self) -> bool
```

Returns `true` if this value is positive infinity or negative infinity, and `false` otherwise.

 
```
let f = 7.0f64;
let inf = f64::INFINITY;
let neg_inf = f64::NEG_INFINITY;
let nan = f64::NAN;

assert!(!f.is_infinite());
assert!(!nan.is_infinite());

assert!(inf.is_infinite());
assert!(neg_inf.is_infinite());
```
 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#486)const: [unstable](https://github.com/rust-lang/rust/issues/72505 "Tracking issue for const_float_classify")
```
pub fn is_finite(self) -> bool
```

Returns `true` if this number is neither infinite nor NaN.

 
```
let f = 7.0f64;
let inf: f64 = f64::INFINITY;
let neg_inf: f64 = f64::NEG_INFINITY;
let nan: f64 = f64::NAN;

assert!(f.is_finite());

assert!(!nan.is_finite());
assert!(!inf.is_finite());
assert!(!neg_inf.is_finite());
```
 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#514)1.53.0 (const: [unstable](https://github.com/rust-lang/rust/issues/72505 "Tracking issue for const_float_classify"))
```
pub fn is_subnormal(self) -> bool
```

Returns `true` if the number is [subnormal](https://en.wikipedia.org/wiki/Denormal_number).

 
```
let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308_f64
let max = f64::MAX;
let lower_than_min = 1.0e-308_f64;
let zero = 0.0_f64;

assert!(!min.is_subnormal());
assert!(!max.is_subnormal());

assert!(!zero.is_subnormal());
assert!(!f64::NAN.is_subnormal());
assert!(!f64::INFINITY.is_subnormal());
// Values between `0` and `min` are Subnormal.
assert!(lower_than_min.is_subnormal());
```
 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#541)const: [unstable](https://github.com/rust-lang/rust/issues/72505 "Tracking issue for const_float_classify")
```
pub fn is_normal(self) -> bool
```

Returns `true` if the number is neither zero, infinite, [subnormal](https://en.wikipedia.org/wiki/Denormal_number), or NaN.

 
```
let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308f64
let max = f64::MAX;
let lower_than_min = 1.0e-308_f64;
let zero = 0.0f64;

assert!(min.is_normal());
assert!(max.is_normal());

assert!(!zero.is_normal());
assert!(!f64::NAN.is_normal());
assert!(!f64::INFINITY.is_normal());
// Values between `0` and `min` are Subnormal.
assert!(!lower_than_min.is_normal());
```
 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#560)const: [unstable](https://github.com/rust-lang/rust/issues/72505 "Tracking issue for const_float_classify")
```
pub fn classify(self) -> FpCategory
```

Returns the floating point category of the number. If only one property is going to be tested, it is generally faster to use the specific predicate instead.

 
```
use std::num::FpCategory;

let num = 12.4_f64;
let inf = f64::INFINITY;

assert_eq!(num.classify(), FpCategory::Normal);
assert_eq!(inf.classify(), FpCategory::Infinite);
```
 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#644)const: [unstable](https://github.com/rust-lang/rust/issues/72505 "Tracking issue for const_float_classify")
```
pub fn is_sign_positive(self) -> bool
```

Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with positive sign bit and positive infinity. Note that IEEE 754 doesn’t assign any meaning to the sign bit in case of a NaN, and as Rust doesn’t guarantee that the bit pattern of NaNs are conserved over arithmetic operations, the result of `is_sign_positive` on a NaN might produce an unexpected result in some cases. See [explanation of NaN as a special value](primitive.f32 "primitive f32") for more info.

 
```
let f = 7.0_f64;
let g = -7.0_f64;

assert!(f.is_sign_positive());
assert!(!g.is_sign_positive());
```
 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#675)const: [unstable](https://github.com/rust-lang/rust/issues/72505 "Tracking issue for const_float_classify")
```
pub fn is_sign_negative(self) -> bool
```

Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with negative sign bit and negative infinity. Note that IEEE 754 doesn’t assign any meaning to the sign bit in case of a NaN, and as Rust doesn’t guarantee that the bit pattern of NaNs are conserved over arithmetic operations, the result of `is_sign_negative` on a NaN might produce an unexpected result in some cases. See [explanation of NaN as a special value](primitive.f32 "primitive f32") for more info.

 
```
let f = 7.0_f64;
let g = -7.0_f64;

assert!(!f.is_sign_negative());
assert!(g.is_sign_negative());
```
 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#719)const: [unstable](https://github.com/rust-lang/rust/issues/91399 "Tracking issue for float_next_up_down")
```
pub fn next_up(self) -> f64
```

🔬This is a nightly-only experimental API. (`float_next_up_down` [#91399](https://github.com/rust-lang/rust/issues/91399))

Returns the least number greater than `self`.

 Let `TINY` be the smallest representable positive `f64`. Then,

 * if `self.is_nan()`, this returns `self`;
* if `self` is [`NEG_INFINITY`](primitive.f64#associatedconstant.NEG_INFINITY "associated constant f64::NEG_INFINITY"), this returns [`MIN`](primitive.f64#associatedconstant.MIN "associated constant f64::MIN");
* if `self` is `-TINY`, this returns -0.0;
* if `self` is -0.0 or +0.0, this returns `TINY`;
* if `self` is [`MAX`](primitive.f64#associatedconstant.MAX "associated constant f64::MAX") or [`INFINITY`](primitive.f64#associatedconstant.INFINITY "associated constant f64::INFINITY"), this returns [`INFINITY`](primitive.f64#associatedconstant.INFINITY "associated constant f64::INFINITY");
* otherwise the unique least value greater than `self` is returned.

 The identity `x.next_up() == -(-x).next_down()` holds for all non-NaN `x`. When `x` is finite `x == x.next_up().next_down()` also holds.

 
```
#![feature(float_next_up_down)]
// f64::EPSILON is the difference between 1.0 and the next number up.
assert_eq!(1.0f64.next_up(), 1.0 + f64::EPSILON);
// But not for most numbers.
assert!(0.1f64.next_up() < 0.1 + f64::EPSILON);
assert_eq!(9007199254740992f64.next_up(), 9007199254740994.0);
```
 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#769)const: [unstable](https://github.com/rust-lang/rust/issues/91399 "Tracking issue for float_next_up_down")
```
pub fn next_down(self) -> f64
```

🔬This is a nightly-only experimental API. (`float_next_up_down` [#91399](https://github.com/rust-lang/rust/issues/91399))

Returns the greatest number less than `self`.

 Let `TINY` be the smallest representable positive `f64`. Then,

 * if `self.is_nan()`, this returns `self`;
* if `self` is [`INFINITY`](primitive.f64#associatedconstant.INFINITY "associated constant f64::INFINITY"), this returns [`MAX`](primitive.f64#associatedconstant.MAX "associated constant f64::MAX");
* if `self` is `TINY`, this returns 0.0;
* if `self` is -0.0 or +0.0, this returns `-TINY`;
* if `self` is [`MIN`](primitive.f64#associatedconstant.MIN "associated constant f64::MIN") or [`NEG_INFINITY`](primitive.f64#associatedconstant.NEG_INFINITY "associated constant f64::NEG_INFINITY"), this returns [`NEG_INFINITY`](primitive.f64#associatedconstant.NEG_INFINITY "associated constant f64::NEG_INFINITY");
* otherwise the unique greatest value less than `self` is returned.

 The identity `x.next_down() == -(-x).next_up()` holds for all non-NaN `x`. When `x` is finite `x == x.next_down().next_up()` also holds.

 
```
#![feature(float_next_up_down)]
let x = 1.0f64;
// Clamp value into range [0, 1).
let clamped = x.clamp(0.0, 1.0f64.next_down());
assert!(clamped < 1.0);
assert_eq!(clamped.next_up(), 1.0);
```
 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#802)
```
pub fn recip(self) -> f64
```

Takes the reciprocal (inverse) of a number, `1/x`.

 
```
let x = 2.0_f64;
let abs_difference = (x.recip() - (1.0 / x)).abs();

assert!(abs_difference < 1e-10);
```
 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#819)
```
pub fn to_degrees(self) -> f64
```

Converts radians to degrees.

 
```
let angle = std::f64::consts::PI;

let abs_difference = (angle.to_degrees() - 180.0).abs();

assert!(abs_difference < 1e-10);
```
 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#839)
```
pub fn to_radians(self) -> f64
```

Converts degrees to radians.

 
```
let angle = 180.0_f64;

let abs_difference = (angle.to_radians() - std::f64::consts::PI).abs();

assert!(abs_difference < 1e-10);
```
 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#860)
```
pub fn max(self, other: f64) -> f64
```

Returns the maximum of the two numbers, ignoring NaN.

 If one of the arguments is NaN, then the other argument is returned. This follows the IEEE 754-2008 semantics for maxNum, except for handling of signaling NaNs; this function handles all NaNs the same way and avoids maxNum’s problems with associativity. This also matches the behavior of libm’s fmax.

 
```
let x = 1.0_f64;
let y = 2.0_f64;

assert_eq!(x.max(y), y);
```
 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#880)
```
pub fn min(self, other: f64) -> f64
```

Returns the minimum of the two numbers, ignoring NaN.

 If one of the arguments is NaN, then the other argument is returned. This follows the IEEE 754-2008 semantics for minNum, except for handling of signaling NaNs; this function handles all NaNs the same way and avoids minNum’s problems with associativity. This also matches the behavior of libm’s fmin.

 
```
let x = 1.0_f64;
let y = 2.0_f64;

assert_eq!(x.min(y), x);
```
 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#907)
```
pub fn maximum(self, other: f64) -> f64
```

🔬This is a nightly-only experimental API. (`float_minimum_maximum` [#91079](https://github.com/rust-lang/rust/issues/91079))

Returns the maximum of the two numbers, propagating NaN.

 This returns NaN when *either* argument is NaN, as opposed to [`f64::max`](primitive.f64#method.max "method f64::max") which only returns NaN when *both* arguments are NaN.

 
```
#![feature(float_minimum_maximum)]
let x = 1.0_f64;
let y = 2.0_f64;

assert_eq!(x.maximum(y), y);
assert!(x.maximum(f64::NAN).is_nan());
```
 If one of the arguments is NaN, then NaN is returned. Otherwise this returns the greater of the two numbers. For this operation, -0.0 is considered to be less than +0.0. Note that this follows the semantics specified in IEEE 754-2019.

 Also note that “propagation” of NaNs here doesn’t necessarily mean that the bitpattern of a NaN operand is conserved; see [explanation of NaN as a special value](primitive.f32 "primitive f32") for more info.

 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#942)
```
pub fn minimum(self, other: f64) -> f64
```

🔬This is a nightly-only experimental API. (`float_minimum_maximum` [#91079](https://github.com/rust-lang/rust/issues/91079))

Returns the minimum of the two numbers, propagating NaN.

 This returns NaN when *either* argument is NaN, as opposed to [`f64::min`](primitive.f64#method.min "method f64::min") which only returns NaN when *both* arguments are NaN.

 
```
#![feature(float_minimum_maximum)]
let x = 1.0_f64;
let y = 2.0_f64;

assert_eq!(x.minimum(y), x);
assert!(x.minimum(f64::NAN).is_nan());
```
 If one of the arguments is NaN, then NaN is returned. Otherwise this returns the lesser of the two numbers. For this operation, -0.0 is considered to be less than +0.0. Note that this follows the semantics specified in IEEE 754-2019.

 Also note that “propagation” of NaNs here doesn’t necessarily mean that the bitpattern of a NaN operand is conserved; see [explanation of NaN as a special value](primitive.f32 "primitive f32") for more info.

 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#967)
```
pub fn midpoint(self, other: f64) -> f64
```

🔬This is a nightly-only experimental API. (`num_midpoint` [#110840](https://github.com/rust-lang/rust/issues/110840))

Calculates the middle point of `self` and `rhs`.

 This returns NaN when *either* argument is NaN or if a combination of +inf and -inf is provided as arguments.

 ##### Examples

 
```
#![feature(num_midpoint)]
assert_eq!(1f64.midpoint(4.0), 2.5);
assert_eq!((-5.5f64).midpoint(8.0), 1.25);
```
 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#1014-1016)1.44.0
```
pub unsafe fn to_int_unchecked<Int>(self) -> Int
where
    f64: FloatToInt<Int>,
```

Rounds toward zero and converts to any primitive integer type, assuming that the value is finite and fits in that type.

 
```
let value = 4.6_f64;
let rounded = unsafe { value.to_int_unchecked::<u16>() };
assert_eq!(rounded, 4);

let value = -128.9_f64;
let rounded = unsafe { value.to_int_unchecked::<i8>() };
assert_eq!(rounded, i8::MIN);
```
 ##### Safety

 The value must:

 * Not be `NaN`
* Not be infinite
* Be representable in the return type `Int`, after truncating off its fractional part

 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#1045)1.20.0 (const: [unstable](https://github.com/rust-lang/rust/issues/72447 "Tracking issue for const_float_bits_conv"))
```
pub fn to_bits(self) -> u64
```

Raw transmutation to `u64`.

 This is currently identical to `transmute::<f64, u64>(self)` on all platforms.

 See [`from_bits`](primitive.f64#method.from_bits "associated function f64::from_bits") for some discussion of the portability of this operation (there are almost no issues).

 Note that this function is distinct from `as` casting, which attempts to preserve the *numeric* value, and not the bitwise value.

 ##### Examples

 
```
assert!((1f64).to_bits() != 1f64 as u64); // to_bits() is not casting!
assert_eq!((12.5f64).to_bits(), 0x4029000000000000);

```
 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#1117)1.20.0 (const: [unstable](https://github.com/rust-lang/rust/issues/72447 "Tracking issue for const_float_bits_conv"))
```
pub fn from_bits(v: u64) -> f64
```

Raw transmutation from `u64`.

 This is currently identical to `transmute::<u64, f64>(v)` on all platforms. It turns out this is incredibly portable, for two reasons:

 * Floats and Ints have the same endianness on all supported platforms.
* IEEE 754 very precisely specifies the bit layout of floats.

 However there is one caveat: prior to the 2008 version of IEEE 754, how to interpret the NaN signaling bit wasn’t actually specified. Most platforms (notably x86 and ARM) picked the interpretation that was ultimately standardized in 2008, but some didn’t (notably MIPS). As a result, all signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.

 Rather than trying to preserve signaling-ness cross-platform, this implementation favors preserving the exact bits. This means that any payloads encoded in NaNs will be preserved even if the result of this method is sent over the network from an x86 machine to a MIPS one.

 If the results of this method are only manipulated by the same architecture that produced them, then there is no portability concern.

 If the input isn’t NaN, then there is no portability concern.

 If you don’t care about signaling-ness (very likely), then there is no portability concern.

 Note that this function is distinct from `as` casting, which attempts to preserve the *numeric* value, and not the bitwise value.

 ##### Examples

 
```
let v = f64::from_bits(0x4029000000000000);
assert_eq!(v, 12.5);
```
 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#1191)1.40.0 (const: [unstable](https://github.com/rust-lang/rust/issues/72447 "Tracking issue for const_float_bits_conv"))
```
pub fn to_be_bytes(self) -> [u8; 8]
```

Return the memory representation of this floating point number as a byte array in big-endian (network) byte order.

 See [`from_bits`](primitive.f64#method.from_bits "associated function f64::from_bits") for some discussion of the portability of this operation (there are almost no issues).

 ##### Examples

 
```
let bytes = 12.5f64.to_be_bytes();
assert_eq!(bytes, [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
```
 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#1212)1.40.0 (const: [unstable](https://github.com/rust-lang/rust/issues/72447 "Tracking issue for const_float_bits_conv"))
```
pub fn to_le_bytes(self) -> [u8; 8]
```

Return the memory representation of this floating point number as a byte array in little-endian byte order.

 See [`from_bits`](primitive.f64#method.from_bits "associated function f64::from_bits") for some discussion of the portability of this operation (there are almost no issues).

 ##### Examples

 
```
let bytes = 12.5f64.to_le_bytes();
assert_eq!(bytes, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]);
```
 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#1246)1.40.0 (const: [unstable](https://github.com/rust-lang/rust/issues/72447 "Tracking issue for const_float_bits_conv"))
```
pub fn to_ne_bytes(self) -> [u8; 8]
```

Return the memory representation of this floating point number as a byte array in native byte order.

 As the target platform’s native endianness is used, portable code should use [`to_be_bytes`](primitive.f64#method.to_be_bytes "method f64::to_be_bytes") or [`to_le_bytes`](primitive.f64#method.to_le_bytes "method f64::to_le_bytes"), as appropriate, instead.

 See [`from_bits`](primitive.f64#method.from_bits "associated function f64::from_bits") for some discussion of the portability of this operation (there are almost no issues).

 ##### Examples

 
```
let bytes = 12.5f64.to_ne_bytes();
assert_eq!(
    bytes,
    if cfg!(target_endian = "big") {
        [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
    } else {
        [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]
    }
);
```
 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#1265)1.40.0 (const: [unstable](https://github.com/rust-lang/rust/issues/72447 "Tracking issue for const_float_bits_conv"))
```
pub fn from_be_bytes(bytes: [u8; 8]) -> f64
```

Create a floating point value from its representation as a byte array in big endian.

 See [`from_bits`](primitive.f64#method.from_bits "associated function f64::from_bits") for some discussion of the portability of this operation (there are almost no issues).

 ##### Examples

 
```
let value = f64::from_be_bytes([0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
assert_eq!(value, 12.5);
```
 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#1284)1.40.0 (const: [unstable](https://github.com/rust-lang/rust/issues/72447 "Tracking issue for const_float_bits_conv"))
```
pub fn from_le_bytes(bytes: [u8; 8]) -> f64
```

Create a floating point value from its representation as a byte array in little endian.

 See [`from_bits`](primitive.f64#method.from_bits "associated function f64::from_bits") for some discussion of the portability of this operation (there are almost no issues).

 ##### Examples

 
```
let value = f64::from_le_bytes([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]);
assert_eq!(value, 12.5);
```
 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#1314)1.40.0 (const: [unstable](https://github.com/rust-lang/rust/issues/72447 "Tracking issue for const_float_bits_conv"))
```
pub fn from_ne_bytes(bytes: [u8; 8]) -> f64
```

Create a floating point value from its representation as a byte array in native endian.

 As the target platform’s native endianness is used, portable code likely wants to use [`from_be_bytes`](primitive.f64#method.from_be_bytes "associated function f64::from_be_bytes") or [`from_le_bytes`](primitive.f64#method.from_le_bytes "associated function f64::from_le_bytes"), as appropriate instead.

 See [`from_bits`](primitive.f64#method.from_bits "associated function f64::from_bits") for some discussion of the portability of this operation (there are almost no issues).

 ##### Examples

 
```
let value = f64::from_ne_bytes(if cfg!(target_endian = "big") {
    [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
} else {
    [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]
});
assert_eq!(value, 12.5);
```
 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#1372)1.62.0
```
pub fn total_cmp(&self, other: &f64) -> Ordering
```

Return the ordering between `self` and `other`.

 Unlike the standard partial comparison between floating point numbers, this comparison always produces an ordering in accordance to the `totalOrder` predicate as defined in the IEEE 754 (2008 revision) floating point standard. The values are ordered in the following sequence:

 * negative quiet NaN
* negative signaling NaN
* negative infinity
* negative numbers
* negative subnormal numbers
* negative zero
* positive zero
* positive subnormal numbers
* positive numbers
* positive infinity
* positive signaling NaN
* positive quiet NaN.

 The ordering established by this function does not always agree with the [`PartialOrd`](cmp/trait.partialord "trait std::cmp::PartialOrd") and [`PartialEq`](cmp/trait.partialeq "trait std::cmp::PartialEq") implementations of `f64`. For example, they consider negative and positive zero equal, while `total_cmp` doesn’t.

 The interpretation of the signaling NaN bit follows the definition in the IEEE 754 standard, which may not match the interpretation by some of the older, non-conformant (e.g. MIPS) hardware implementations.

 ##### Example

 
```
struct GoodBoy {
    name: String,
    weight: f64,
}

let mut bois = vec![
    GoodBoy { name: "Pucci".to_owned(), weight: 0.1 },
    GoodBoy { name: "Woofer".to_owned(), weight: 99.0 },
    GoodBoy { name: "Yapper".to_owned(), weight: 10.0 },
    GoodBoy { name: "Chonk".to_owned(), weight: f64::INFINITY },
    GoodBoy { name: "Abs. Unit".to_owned(), weight: f64::NAN },
    GoodBoy { name: "Floaty".to_owned(), weight: -5.0 },
];

bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
```
 
[source](https://doc.rust-lang.org/src/core/num/f64.rs.html#1427)1.50.0
```
pub fn clamp(self, min: f64, max: f64) -> f64
```

Restrict a value to a certain interval unless it is NaN.

 Returns `max` if `self` is greater than `max`, and `min` if `self` is less than `min`. Otherwise this returns `self`.

 Note that this function returns NaN if the initial value was NaN as well.

 ##### Panics

 Panics if `min > max`, `min` is NaN, or `max` is NaN.

 ##### Examples

 
```
assert!((-3.0f64).clamp(-2.0, 1.0) == -2.0);
assert!((0.0f64).clamp(-2.0, 1.0) == 0.0);
assert!((2.0f64).clamp(-2.0, 1.0) == 1.0);
assert!((f64::NAN).clamp(-2.0, 1.0).is_nan());
```
 


Trait Implementations
---------------------



[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#109)
```
impl Add<&f64> for &f64
```


```
type Output = <f64 as Add<f64>>::Output
```
The resulting type after applying the `+` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#109)
```
fn add(self, other: &f64) -> <f64 as Add<f64>>::Output
```
Performs the `+` operation. [Read more](ops/trait.add#tymethod.add)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#109)
```
impl Add<&f64> for f64
```


```
type Output = <f64 as Add<f64>>::Output
```
The resulting type after applying the `+` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#109)
```
fn add(self, other: &f64) -> <f64 as Add<f64>>::Output
```
Performs the `+` operation. [Read more](ops/trait.add#tymethod.add)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#109)
```
impl<'a> Add<f64> for &'a f64
```


```
type Output = <f64 as Add<f64>>::Output
```
The resulting type after applying the `+` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#109)
```
fn add(self, other: f64) -> <f64 as Add<f64>>::Output
```
Performs the `+` operation. [Read more](ops/trait.add#tymethod.add)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#109)
```
impl Add<f64> for f64
```


```
type Output = f64
```
The resulting type after applying the `+` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#109)
```
fn add(self, other: f64) -> f64
```
Performs the `+` operation. [Read more](ops/trait.add#tymethod.add)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#760)1.22.0
```
impl AddAssign<&f64> for f64
```

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#760)
```
fn add_assign(&mut self, other: &f64)
```
Performs the `+=` operation. [Read more](ops/trait.addassign#tymethod.add_assign)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#760)1.8.0
```
impl AddAssign<f64> for f64
```

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#760)
```
fn add_assign(&mut self, other: f64)
```
Performs the `+=` operation. [Read more](ops/trait.addassign#tymethod.add_assign)


[source](https://doc.rust-lang.org/src/core/clone.rs.html#189-194)
```
impl Clone for f64
```

[source](https://doc.rust-lang.org/src/core/clone.rs.html#189-194)
```
fn clone(&self) -> f64
```
Returns a copy of the value. [Read more](clone/trait.clone#tymethod.clone)

[source](https://doc.rust-lang.org/src/core/clone.rs.html#129)
```
fn clone_from(&mut self, source: &Self)
```
Performs copy-assignment from `source`. [Read more](clone/trait.clone#method.clone_from)


[source](https://doc.rust-lang.org/src/core/fmt/float.rs.html#230)
```
impl Debug for f64
```

[source](https://doc.rust-lang.org/src/core/fmt/float.rs.html#230)
```
fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter. [Read more](fmt/trait.debug#tymethod.fmt)


[source](https://doc.rust-lang.org/src/core/default.rs.html#221)
```
impl Default for f64
```

[source](https://doc.rust-lang.org/src/core/default.rs.html#221)
```
fn default() -> f64
```

Returns the default value of `0.0`

 

[source](https://doc.rust-lang.org/src/core/fmt/float.rs.html#230)
```
impl Display for f64
```

[source](https://doc.rust-lang.org/src/core/fmt/float.rs.html#230)
```
fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter. [Read more](fmt/trait.display#tymethod.fmt)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#503)
```
impl Div<&f64> for &f64
```


```
type Output = <f64 as Div<f64>>::Output
```
The resulting type after applying the `/` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#503)
```
fn div(self, other: &f64) -> <f64 as Div<f64>>::Output
```
Performs the `/` operation. [Read more](ops/trait.div#tymethod.div)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#503)
```
impl Div<&f64> for f64
```


```
type Output = <f64 as Div<f64>>::Output
```
The resulting type after applying the `/` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#503)
```
fn div(self, other: &f64) -> <f64 as Div<f64>>::Output
```
Performs the `/` operation. [Read more](ops/trait.div#tymethod.div)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#503)
```
impl<'a> Div<f64> for &'a f64
```


```
type Output = <f64 as Div<f64>>::Output
```
The resulting type after applying the `/` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#503)
```
fn div(self, other: f64) -> <f64 as Div<f64>>::Output
```
Performs the `/` operation. [Read more](ops/trait.div#tymethod.div)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#503)
```
impl Div<f64> for f64
```


```
type Output = f64
```
The resulting type after applying the `/` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#503)
```
fn div(self, other: f64) -> f64
```
Performs the `/` operation. [Read more](ops/trait.div#tymethod.div)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#939)1.22.0
```
impl DivAssign<&f64> for f64
```

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#939)
```
fn div_assign(&mut self, other: &f64)
```
Performs the `/=` operation. [Read more](ops/trait.divassign#tymethod.div_assign)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#939)1.8.0
```
impl DivAssign<f64> for f64
```

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#939)
```
fn div_assign(&mut self, other: f64)
```
Performs the `/=` operation. [Read more](ops/trait.divassign#tymethod.div_assign)


[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#191)1.68.0
```
impl From<bool> for f64
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#205)
```
fn from(small: bool) -> f64
```

Converts `bool` to `f64` losslessly. The resulting value is positive `0.0` for `false` and `1.0` for `true` values.

 ##### Examples

 
```
let x: f64 = false.into();
assert_eq!(x, 0.0);
assert!(x.is_sign_positive());

let y: f64 = true.into();
assert_eq!(y, 1.0);
```
 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#168)1.6.0
```
impl From<f32> for f64
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#168)
```
fn from(small: f32) -> f64
```

Converts `f32` to `f64` losslessly.

 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#157)1.6.0
```
impl From<i16> for f64
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#157)
```
fn from(small: i16) -> f64
```

Converts `i16` to `f64` losslessly.

 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#158)1.6.0
```
impl From<i32> for f64
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#158)
```
fn from(small: i32) -> f64
```

Converts `i32` to `f64` losslessly.

 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#155)1.6.0
```
impl From<i8> for f64
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#155)
```
fn from(small: i8) -> f64
```

Converts `i8` to `f64` losslessly.

 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#164)1.6.0
```
impl From<u16> for f64
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#164)
```
fn from(small: u16) -> f64
```

Converts `u16` to `f64` losslessly.

 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#165)1.6.0
```
impl From<u32> for f64
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#165)
```
fn from(small: u32) -> f64
```

Converts `u32` to `f64` losslessly.

 

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#162)1.6.0
```
impl From<u8> for f64
```

[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#162)
```
fn from(small: u8) -> f64
```

Converts `u8` to `f64` losslessly.

 

[source](https://doc.rust-lang.org/src/core/num/dec2flt/mod.rs.html#164)
```
impl FromStr for f64
```

[source](https://doc.rust-lang.org/src/core/num/dec2flt/mod.rs.html#164)
```
fn from_str(src: &str) -> Result<f64, ParseFloatError>
```

Converts a string in base 10 to a float. Accepts an optional decimal exponent.

 This function accepts strings such as

 * ‘3.14’
* ‘-3.14’
* ‘2.5E10’, or equivalently, ‘2.5e10’
* ‘2.5E-10’
* ‘5.’
* ‘.5’, or, equivalently, ‘0.5’
* ‘inf’, ‘-inf’, ‘+infinity’, ‘NaN’

 Note that alphabetical characters are not case-sensitive.

 Leading and trailing whitespace represent an error.

 ##### Grammar

 All strings that adhere to the following [EBNF](https://www.w3.org/TR/REC-xml/#sec-notation) grammar when lowercased will result in an [`Ok`](result/enum.result#variant.Ok "variant std::result::Result::Ok") being returned:

 
```
Float  ::= Sign? ( 'inf' | 'infinity' | 'nan' | Number )
Number ::= ( Digit+ |
             Digit+ '.' Digit* |
             Digit* '.' Digit+ ) Exp?
Exp    ::= 'e' Sign? Digit+
Sign   ::= [+-]
Digit  ::= [0-9]

```

##### Arguments

 * src - A string

 ##### Return value

 `Err(ParseFloatError)` if the string did not represent a valid number. Otherwise, `Ok(n)` where `n` is the closest representable floating-point number to the number represented by `src` (following the same rules for rounding as for the results of primitive operations).

 

```
type Err = ParseFloatError
```
The associated error which can be returned from parsing.

[source](https://doc.rust-lang.org/src/core/fmt/float.rs.html#230)
```
impl LowerExp for f64
```

[source](https://doc.rust-lang.org/src/core/fmt/float.rs.html#230)
```
fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter.

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#346)
```
impl Mul<&f64> for &f64
```


```
type Output = <f64 as Mul<f64>>::Output
```
The resulting type after applying the `*` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#346)
```
fn mul(self, other: &f64) -> <f64 as Mul<f64>>::Output
```
Performs the `*` operation. [Read more](ops/trait.mul#tymethod.mul)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#346)
```
impl Mul<&f64> for f64
```


```
type Output = <f64 as Mul<f64>>::Output
```
The resulting type after applying the `*` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#346)
```
fn mul(self, other: &f64) -> <f64 as Mul<f64>>::Output
```
Performs the `*` operation. [Read more](ops/trait.mul#tymethod.mul)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#346)
```
impl<'a> Mul<f64> for &'a f64
```


```
type Output = <f64 as Mul<f64>>::Output
```
The resulting type after applying the `*` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#346)
```
fn mul(self, other: f64) -> <f64 as Mul<f64>>::Output
```
Performs the `*` operation. [Read more](ops/trait.mul#tymethod.mul)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#346)
```
impl Mul<f64> for f64
```


```
type Output = f64
```
The resulting type after applying the `*` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#346)
```
fn mul(self, other: f64) -> f64
```
Performs the `*` operation. [Read more](ops/trait.mul#tymethod.mul)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#883)1.22.0
```
impl MulAssign<&f64> for f64
```

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#883)
```
fn mul_assign(&mut self, other: &f64)
```
Performs the `*=` operation. [Read more](ops/trait.mulassign#tymethod.mul_assign)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#883)1.8.0
```
impl MulAssign<f64> for f64
```

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#883)
```
fn mul_assign(&mut self, other: f64)
```
Performs the `*=` operation. [Read more](ops/trait.mulassign#tymethod.mul_assign)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#694)
```
impl Neg for &f64
```


```
type Output = <f64 as Neg>::Output
```
The resulting type after applying the `-` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#694)
```
fn neg(self) -> <f64 as Neg>::Output
```
Performs the unary `-` operation. [Read more](ops/trait.neg#tymethod.neg)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#694)
```
impl Neg for f64
```


```
type Output = f64
```
The resulting type after applying the `-` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#694)
```
fn neg(self) -> f64
```
Performs the unary `-` operation. [Read more](ops/trait.neg#tymethod.neg)


[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1298-1300)
```
impl PartialEq<f64> for f64
```

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1298-1300)
```
fn eq(&self, other: &f64) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1298-1300)
```
fn ne(&self, other: &f64) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1352)
```
impl PartialOrd<f64> for f64
```

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1352)
```
fn partial_cmp(&self, other: &f64) -> Option<Ordering>
```
This method returns an ordering between `self` and `other` values if one exists. [Read more](cmp/trait.partialord#tymethod.partial_cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1352)
```
fn lt(&self, other: &f64) -> bool
```
This method tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](cmp/trait.partialord#method.lt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1352)
```
fn le(&self, other: &f64) -> bool
```
This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](cmp/trait.partialord#method.le)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1352)
```
fn ge(&self, other: &f64) -> bool
```
This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](cmp/trait.partialord#method.ge)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1352)
```
fn gt(&self, other: &f64) -> bool
```
This method tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](cmp/trait.partialord#method.gt)


[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#150)1.12.0
```
impl<'a> Product<&'a f64> for f64
```

[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#150)
```
fn product<I>(iter: I) -> f64
where
    I: Iterator<Item = &'a f64>,
```
Method which takes an iterator and generates `Self` from the elements by multiplying the items.

[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#150)1.12.0
```
impl Product<f64> for f64
```

[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#150)
```
fn product<I>(iter: I) -> f64
where
    I: Iterator<Item = f64>,
```
Method which takes an iterator and generates `Self` from the elements by multiplying the items.

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#619)
```
impl Rem<&f64> for &f64
```


```
type Output = <f64 as Rem<f64>>::Output
```
The resulting type after applying the `%` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#619)
```
fn rem(self, other: &f64) -> <f64 as Rem<f64>>::Output
```
Performs the `%` operation. [Read more](ops/trait.rem#tymethod.rem)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#619)
```
impl Rem<&f64> for f64
```


```
type Output = <f64 as Rem<f64>>::Output
```
The resulting type after applying the `%` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#619)
```
fn rem(self, other: &f64) -> <f64 as Rem<f64>>::Output
```
Performs the `%` operation. [Read more](ops/trait.rem#tymethod.rem)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#619)
```
impl<'a> Rem<f64> for &'a f64
```


```
type Output = <f64 as Rem<f64>>::Output
```
The resulting type after applying the `%` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#619)
```
fn rem(self, other: f64) -> <f64 as Rem<f64>>::Output
```
Performs the `%` operation. [Read more](ops/trait.rem#tymethod.rem)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#619)
```
impl Rem<f64> for f64
```

The remainder from the division of two floats.

 The remainder has the same sign as the dividend and is computed as: `x - (x / y).trunc() * y`.

 #### Examples

 
```
let x: f32 = 50.50;
let y: f32 = 8.125;
let remainder = x - (x / y).trunc() * y;

// The answer to both operations is 1.75
assert_eq!(x % y, remainder);
```
 


```
type Output = f64
```
The resulting type after applying the `%` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#619)
```
fn rem(self, other: f64) -> f64
```
Performs the `%` operation. [Read more](ops/trait.rem#tymethod.rem)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#999)1.22.0
```
impl RemAssign<&f64> for f64
```

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#999)
```
fn rem_assign(&mut self, other: &f64)
```
Performs the `%=` operation. [Read more](ops/trait.remassign#tymethod.rem_assign)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#999)1.8.0
```
impl RemAssign<f64> for f64
```

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#999)
```
fn rem_assign(&mut self, other: f64)
```
Performs the `%=` operation. [Read more](ops/trait.remassign#tymethod.rem_assign)


[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/vector.rs.html#1001)
```
impl SimdElement for f64
```


```
type Mask = i64
```

🔬This is a nightly-only experimental API. (`portable_simd` [#86656](https://github.com/rust-lang/rust/issues/86656))
The mask element type corresponding to this element type.

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#217)
```
impl Sub<&f64> for &f64
```


```
type Output = <f64 as Sub<f64>>::Output
```
The resulting type after applying the `-` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#217)
```
fn sub(self, other: &f64) -> <f64 as Sub<f64>>::Output
```
Performs the `-` operation. [Read more](ops/trait.sub#tymethod.sub)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#217)
```
impl Sub<&f64> for f64
```


```
type Output = <f64 as Sub<f64>>::Output
```
The resulting type after applying the `-` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#217)
```
fn sub(self, other: &f64) -> <f64 as Sub<f64>>::Output
```
Performs the `-` operation. [Read more](ops/trait.sub#tymethod.sub)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#217)
```
impl<'a> Sub<f64> for &'a f64
```


```
type Output = <f64 as Sub<f64>>::Output
```
The resulting type after applying the `-` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#217)
```
fn sub(self, other: f64) -> <f64 as Sub<f64>>::Output
```
Performs the `-` operation. [Read more](ops/trait.sub#tymethod.sub)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#217)
```
impl Sub<f64> for f64
```


```
type Output = f64
```
The resulting type after applying the `-` operator.
[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#217)
```
fn sub(self, other: f64) -> f64
```
Performs the `-` operation. [Read more](ops/trait.sub#tymethod.sub)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#826)1.22.0
```
impl SubAssign<&f64> for f64
```

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#826)
```
fn sub_assign(&mut self, other: &f64)
```
Performs the `-=` operation. [Read more](ops/trait.subassign#tymethod.sub_assign)


[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#826)1.8.0
```
impl SubAssign<f64> for f64
```

[source](https://doc.rust-lang.org/src/core/ops/arith.rs.html#826)
```
fn sub_assign(&mut self, other: f64)
```
Performs the `-=` operation. [Read more](ops/trait.subassign#tymethod.sub_assign)


[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#150)1.12.0
```
impl<'a> Sum<&'a f64> for f64
```

[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#150)
```
fn sum<I>(iter: I) -> f64
where
    I: Iterator<Item = &'a f64>,
```
Method which takes an iterator and generates `Self` from the elements by “summing up” the items.

[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#150)1.12.0
```
impl Sum<f64> for f64
```

[source](https://doc.rust-lang.org/src/core/iter/traits/accum.rs.html#150)
```
fn sum<I>(iter: I) -> f64
where
    I: Iterator<Item = f64>,
```
Method which takes an iterator and generates `Self` from the elements by “summing up” the items.

[source](https://doc.rust-lang.org/src/core/fmt/float.rs.html#230)
```
impl UpperExp for f64
```

[source](https://doc.rust-lang.org/src/core/fmt/float.rs.html#230)
```
fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter.

[source](https://doc.rust-lang.org/src/core/marker.rs.html#467-477)
```
impl Copy for f64
```
[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#39)
```
impl FloatToInt<i128> for f64
```
[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#39)
```
impl FloatToInt<i16> for f64
```
[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#39)
```
impl FloatToInt<i32> for f64
```
[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#39)
```
impl FloatToInt<i64> for f64
```
[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#39)
```
impl FloatToInt<i8> for f64
```
[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#39)
```
impl FloatToInt<isize> for f64
```
[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#39)
```
impl FloatToInt<u128> for f64
```
[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#39)
```
impl FloatToInt<u16> for f64
```
[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#39)
```
impl FloatToInt<u32> for f64
```
[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#39)
```
impl FloatToInt<u64> for f64
```
[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#39)
```
impl FloatToInt<u8> for f64
```
[source](https://doc.rust-lang.org/src/core/convert/num.rs.html#39)
```
impl FloatToInt<usize> for f64
```
[source](https://doc.rust-lang.org/src/core/portable-simd/crates/core_simd/src/cast.rs.html#33)
```
impl SimdCast for f64
```


Auto Trait Implementations
--------------------------




```
impl RefUnwindSafe for f64
```

```
impl Send for f64
```

```
impl Sync for f64
```

```
impl Unpin for f64
```

```
impl UnwindSafe for f64
```


Blanket Implementations
-----------------------



[source](https://doc.rust-lang.org/src/core/any.rs.html#200)
```
impl<T> Any for T
where
    T: 'static + ?Sized,
```

[source](https://doc.rust-lang.org/src/core/any.rs.html#201)
```
fn type_id(&self) -> TypeId
```
Gets the `TypeId` of `self`. [Read more](any/trait.any#tymethod.type_id)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#208)
```
impl<T> Borrow<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#210)
```
fn borrow(&self) -> &T
```
Immutably borrows from an owned value. [Read more](borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#216)
```
impl<T> BorrowMut<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#217)
```
fn borrow_mut(&mut self) -> &mut T
```
Mutably borrows from an owned value. [Read more](borrow/trait.borrowmut#tymethod.borrow_mut)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#723)
```
impl<T> From<T> for T
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#726)
```
fn from(t: T) -> T
```

Returns the argument unchanged.

 

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#707)
```
impl<T, U> Into<U> for T
where
    U: From<T>,
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#716)
```
fn into(self) -> U
```

Calls `U::from(self)`.

 That is, this conversion is whatever the implementation of `[From](convert/trait.from "trait std::convert::From")<T> for U` chooses to do.

 

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#82)
```
impl<T> ToOwned for T
where
    T: Clone,
```


```
type Owned = T
```
The resulting type after obtaining ownership.
[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#87)
```
fn to_owned(&self) -> T
```
Creates owned data from borrowed data, usually by cloning. [Read more](borrow/trait.toowned#tymethod.to_owned)

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#91)
```
fn clone_into(&self, target: &mut T)
```
Uses borrowed data to replace owned data, usually by cloning. [Read more](borrow/trait.toowned#method.clone_into)


[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2513)
```
impl<T> ToString for T
where
    T: Display + ?Sized,
```

[source](https://doc.rust-lang.org/src/alloc/string.rs.html#2519)
```
default fn to_string(&self) -> String
```
Converts the given value to a `String`. [Read more](string/trait.tostring#tymethod.to_string)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#763)
```
impl<T, U> TryFrom<U> for T
where
    U: Into<T>,
```


```
type Error = Infallible
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#770)
```
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#748)
```
impl<T, U> TryInto<U> for T
where
    U: TryFrom<T>,
```


```
type Error = <U as TryFrom<T>>::Error
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#755)
```
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
```
Performs the conversion.



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/primitive.f64.html>

Primitive Type fn
=================


Function pointers, like `fn(usize) -> bool`.

 *See also the traits [`Fn`](ops/trait.fn "trait std::ops::Fn"), [`FnMut`](ops/trait.fnmut "trait std::ops::FnMut"), and [`FnOnce`](ops/trait.fnonce "trait std::ops::FnOnce").*

 Function pointers are pointers that point to *code*, not data. They can be called just like functions. Like references, function pointers are, among other things, assumed to not be null, so if you want to pass a function pointer over FFI and be able to accommodate null pointers, make your type [`Option<fn()>`](option/index#options-and-pointers-nullable-pointers "mod std::option") with your required signature.

 #### Safety

 Plain function pointers are obtained by casting either plain functions, or closures that don’t capture an environment:

 
```
fn add_one(x: usize) -> usize {
    x + 1
}

let ptr: fn(usize) -> usize = add_one;
assert_eq!(ptr(5), 6);

let clos: fn(usize) -> usize = |x| x + 5;
assert_eq!(clos(5), 10);
```
 In addition to varying based on their signature, function pointers come in two flavors: safe and unsafe. Plain `fn()` function pointers can only point to safe functions, while `unsafe fn()` function pointers can point to safe or unsafe functions.

 
```
fn add_one(x: usize) -> usize {
    x + 1
}

unsafe fn add_one_unsafely(x: usize) -> usize {
    x + 1
}

let safe_ptr: fn(usize) -> usize = add_one;

//ERROR: mismatched types: expected normal fn, found unsafe fn
//let bad_ptr: fn(usize) -> usize = add_one_unsafely;

let unsafe_ptr: unsafe fn(usize) -> usize = add_one_unsafely;
let really_safe_ptr: unsafe fn(usize) -> usize = add_one;
```
 #### ABI

 On top of that, function pointers can vary based on what ABI they use. This is achieved by adding the `extern` keyword before the type, followed by the ABI in question. The default ABI is “Rust”, i.e., `fn()` is the exact same type as `extern "Rust" fn()`. A pointer to a function with C ABI would have type `extern "C" fn()`.

 `extern "ABI" { ... }` blocks declare functions with ABI “ABI”. The default here is “C”, i.e., functions declared in an `extern {...}` block have “C” ABI.

 For more information and a list of supported ABIs, see [the nomicon’s section on foreign calling conventions](https://doc.rust-lang.org/nomicon/ffi.html#foreign-calling-conventions).

 #### Variadic functions

 Extern function declarations with the “C” or “cdecl” ABIs can also be *variadic*, allowing them to be called with a variable number of arguments. Normal Rust functions, even those with an `extern "ABI"`, cannot be variadic. For more information, see [the nomicon’s section on variadic functions](https://doc.rust-lang.org/nomicon/ffi.html#variadic-functions).

 #### Creating function pointers

 When `bar` is the name of a function, then the expression `bar` is *not* a function pointer. Rather, it denotes a value of an unnameable type that uniquely identifies the function `bar`. The value is zero-sized because the type already identifies the function. This has the advantage that “calling” the value (it implements the `Fn*` traits) does not require dynamic dispatch.

 This zero-sized type *coerces* to a regular function pointer. For example:

 
```
use std::mem;

fn bar(x: i32) {}

let not_bar_ptr = bar; // `not_bar_ptr` is zero-sized, uniquely identifying `bar`
assert_eq!(mem::size_of_val(&not_bar_ptr), 0);

let bar_ptr: fn(i32) = not_bar_ptr; // force coercion to function pointer
assert_eq!(mem::size_of_val(&bar_ptr), mem::size_of::<usize>());

let footgun = &bar; // this is a shared reference to the zero-sized type identifying `bar`
```
 The last line shows that `&bar` is not a function pointer either. Rather, it is a reference to the function-specific ZST. `&bar` is basically never what you want when `bar` is a function.

 #### Casting to and from integers

 You cast function pointers directly to integers:

 
```
let fnptr: fn(i32) -> i32 = |x| x+2;
let fnptr_addr = fnptr as usize;
```
 However, a direct cast back is not possible. You need to use `transmute`:

 
```
let fnptr = fnptr_addr as *const ();
let fnptr: fn(i32) -> i32 = unsafe { std::mem::transmute(fnptr) };
assert_eq!(fnptr(40), 42);
```
 Crucially, we `as`-cast to a raw pointer before `transmute`ing to a function pointer. This avoids an integer-to-pointer `transmute`, which can be problematic. Transmuting between raw pointers and function pointers (i.e., two pointer types) is fine.

 Note that all of this is not portable to platforms where function pointers and data pointers have different sizes.

 #### Trait implementations

 In this documentation the shorthand `fn (T₁, T₂, …, Tₙ)` is used to represent non-variadic function pointers of varying length. Note that this is a convenience notation to avoid repetitive documentation, not valid Rust syntax.

 Due to a temporary restriction in Rust’s type system, these traits are only implemented on functions that take 12 arguments or less, with the `"Rust"` and `"C"` ABIs. In the future, this may change:

 * [`PartialEq`](cmp/trait.partialeq "trait std::cmp::PartialEq")
* [`Eq`](cmp/trait.eq "trait std::cmp::Eq")
* [`PartialOrd`](cmp/trait.partialord "trait std::cmp::PartialOrd")
* [`Ord`](cmp/trait.ord "trait std::cmp::Ord")
* [`Hash`](hash/trait.hash "trait std::hash::Hash")
* [`Pointer`](fmt/trait.pointer "trait std::fmt::Pointer")
* [`Debug`](fmt/derive.debug "derive std::fmt::Debug")

 The following traits are implemented for function pointers with any number of arguments and any ABI. These traits have implementations that are automatically generated by the compiler, so are not limited by missing language features:

 * [`Clone`](clone/trait.clone "trait std::clone::Clone")
* [`Copy`](marker/trait.copy "trait std::marker::Copy")
* [`Send`](marker/trait.send "trait std::marker::Send")
* [`Sync`](marker/trait.sync "trait std::marker::Sync")
* [`Unpin`](marker/trait.unpin "trait std::marker::Unpin")
* [`UnwindSafe`](panic/trait.unwindsafe "trait std::panic::UnwindSafe")
* [`RefUnwindSafe`](panic/trait.refunwindsafe "trait std::panic::RefUnwindSafe")

 In addition, all *safe* function pointers implement [`Fn`](ops/trait.fn "trait std::ops::Fn"), [`FnMut`](ops/trait.fnmut "trait std::ops::FnMut"), and [`FnOnce`](ops/trait.fnonce "trait std::ops::FnOnce"), because these traits are specially known to the compiler.

 Trait Implementations
---------------------



[source](https://doc.rust-lang.org/src/std/primitive_docs.rs.html#1580-1584)
```
impl<Ret, T> Clone for fn (T₁, T₂, …, Tₙ) -> Ret
```

This trait is implemented on function pointers with any number of arguments.

 

[source](https://doc.rust-lang.org/src/std/primitive_docs.rs.html#1581-1583)
```
fn clone(&self) -> Self
```
Returns a copy of the value. [Read more](clone/trait.clone#tymethod.clone)

[source](https://doc.rust-lang.org/src/core/clone.rs.html#129)
```
fn clone_from(&mut self, source: &Self)
```
Performs copy-assignment from `source`. [Read more](clone/trait.clone#method.clone_from)


[source](https://doc.rust-lang.org/src/std/primitive_docs.rs.html#1591-1593)
```
impl<Ret, T> Copy for fn (T₁, T₂, …, Tₙ) -> Ret
```

This trait is implemented on function pointers with any number of arguments.

 

Auto Trait Implementations
--------------------------




```
impl<Ret, T> RefUnwindSafe for fn (T₁, T₂, …, Tₙ) -> Ret
```

```
impl<Ret, T> Send for fn (T₁, T₂, …, Tₙ) -> Ret
```

```
impl<Ret, T> Sync for fn (T₁, T₂, …, Tₙ) -> Ret
```

```
impl<Ret, T> Unpin for fn (T₁, T₂, …, Tₙ) -> Ret
```

```
impl<Ret, T> UnwindSafe for fn (T₁, T₂, …, Tₙ) -> Ret
```


Blanket Implementations
-----------------------



[source](https://doc.rust-lang.org/src/core/any.rs.html#200)
```
impl<T> Any for T
where
    T: 'static + ?Sized,
```

[source](https://doc.rust-lang.org/src/core/any.rs.html#201)
```
fn type_id(&self) -> TypeId
```
Gets the `TypeId` of `self`. [Read more](any/trait.any#tymethod.type_id)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#208)
```
impl<T> Borrow<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#210)
```
fn borrow(&self) -> &T
```
Immutably borrows from an owned value. [Read more](borrow/trait.borrow#tymethod.borrow)


[source](https://doc.rust-lang.org/src/core/borrow.rs.html#216)
```
impl<T> BorrowMut<T> for T
where
    T: ?Sized,
```

[source](https://doc.rust-lang.org/src/core/borrow.rs.html#217)
```
fn borrow_mut(&mut self) -> &mut T
```
Mutably borrows from an owned value. [Read more](borrow/trait.borrowmut#tymethod.borrow_mut)


[source](https://doc.rust-lang.org/src/core/ptr/mod.rs.html#1935)
```
impl<F> Debug for F
where
    F: FnPtr,
```

[source](https://doc.rust-lang.org/src/core/ptr/mod.rs.html#1936)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter. [Read more](fmt/trait.debug#tymethod.fmt)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#723)
```
impl<T> From<T> for T
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#726)
```
fn from(t: T) -> T
```

Returns the argument unchanged.

 

[source](https://doc.rust-lang.org/src/core/ptr/mod.rs.html#1921)
```
impl<F> Hash for F
where
    F: FnPtr,
```

[source](https://doc.rust-lang.org/src/core/ptr/mod.rs.html#1922)
```
fn hash<HH>(&self, state: &mut HH)
where
    HH: Hasher,
```
Feeds this value into the given [`Hasher`](hash/trait.hasher "trait std::hash::Hasher"). [Read more](hash/trait.hash#tymethod.hash)

[source](https://doc.rust-lang.org/src/core/hash/mod.rs.html#237-239)1.3.0
```
fn hash_slice<H>(data: &[Self], state: &mut H)
where
    H: Hasher,
    Self: Sized,
```
Feeds a slice of this type into the given [`Hasher`](hash/trait.hasher "trait std::hash::Hasher"). [Read more](hash/trait.hash#method.hash_slice)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#707)
```
impl<T, U> Into<U> for T
where
    U: From<T>,
```

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#716)
```
fn into(self) -> U
```

Calls `U::from(self)`.

 That is, this conversion is whatever the implementation of `[From](convert/trait.from "trait std::convert::From")<T> for U` chooses to do.

 

[source](https://doc.rust-lang.org/src/core/ptr/mod.rs.html#1913)
```
impl<F> Ord for F
where
    F: FnPtr,
```

[source](https://doc.rust-lang.org/src/core/ptr/mod.rs.html#1915)
```
fn cmp(&self, other: &F) -> Ordering
```
This method returns an [`Ordering`](cmp/enum.ordering "enum std::cmp::Ordering") between `self` and `other`. [Read more](cmp/trait.ord#tymethod.cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#790-792)1.21.0
```
fn max(self, other: Self) -> Self
where
    Self: Sized,
```
Compares and returns the maximum of two values. [Read more](cmp/trait.ord#method.max)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#810-812)1.21.0
```
fn min(self, other: Self) -> Self
where
    Self: Sized,
```
Compares and returns the minimum of two values. [Read more](cmp/trait.ord#method.min)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#835-838)1.50.0
```
fn clamp(self, min: Self, max: Self) -> Self
where
    Self: Sized + PartialOrd<Self>,
```
Restrict a value to a certain interval. [Read more](cmp/trait.ord#method.clamp)


[source](https://doc.rust-lang.org/src/core/ptr/mod.rs.html#1896)
```
impl<F> PartialEq<F> for F
where
    F: FnPtr,
```

[source](https://doc.rust-lang.org/src/core/ptr/mod.rs.html#1898)
```
fn eq(&self, other: &F) -> bool
```
This method tests for `self` and `other` values to be equal, and is used by `==`.
[source](https://doc.rust-lang.org/src/core/cmp.rs.html#226)
```
fn ne(&self, other: &Rhs) -> bool
```
This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.

[source](https://doc.rust-lang.org/src/core/ptr/mod.rs.html#1906)
```
impl<F> PartialOrd<F> for F
where
    F: FnPtr,
```

[source](https://doc.rust-lang.org/src/core/ptr/mod.rs.html#1908)
```
fn partial_cmp(&self, other: &F) -> Option<Ordering>
```
This method returns an ordering between `self` and `other` values if one exists. [Read more](cmp/trait.partialord#tymethod.partial_cmp)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1067)
```
fn lt(&self, other: &Rhs) -> bool
```
This method tests less than (for `self` and `other`) and is used by the `<` operator. [Read more](cmp/trait.partialord#method.lt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1084)
```
fn le(&self, other: &Rhs) -> bool
```
This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. [Read more](cmp/trait.partialord#method.le)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1100)
```
fn gt(&self, other: &Rhs) -> bool
```
This method tests greater than (for `self` and `other`) and is used by the `>` operator. [Read more](cmp/trait.partialord#method.gt)

[source](https://doc.rust-lang.org/src/core/cmp.rs.html#1117)
```
fn ge(&self, other: &Rhs) -> bool
```
This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. [Read more](cmp/trait.partialord#method.ge)


[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#906)
```
impl<'a, F> Pattern<'a> for F
where
    F: FnMut(char) -> bool,
```


```
type Searcher = CharPredicateSearcher<'a, F>
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Associated searcher for this pattern
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#910)
```
fn into_searcher(self, haystack: &'a str) -> CharPredicateSearcher<'a, F>
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Constructs the associated searcher from `self` and the `haystack` to search in.
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#910)
```
fn is_contained_in(self, haystack: &'a str) -> bool
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Checks whether the pattern matches anywhere in the haystack
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#910)
```
fn is_prefix_of(self, haystack: &'a str) -> bool
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Checks whether the pattern matches at the front of the haystack
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#910)
```
fn strip_prefix_of(self, haystack: &'a str) -> Option<&'a str>
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Removes the pattern from the front of haystack, if it matches.
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#910)
```
fn is_suffix_of(self, haystack: &'a str) -> bool
where
    CharPredicateSearcher<'a, F>: ReverseSearcher<'a>,
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Checks whether the pattern matches at the back of the haystack
[source](https://doc.rust-lang.org/src/core/str/pattern.rs.html#910)
```
fn strip_suffix_of(self, haystack: &'a str) -> Option<&'a str>
where
    CharPredicateSearcher<'a, F>: ReverseSearcher<'a>,
```

🔬This is a nightly-only experimental API. (`pattern` [#27721](https://github.com/rust-lang/rust/issues/27721))
Removes the pattern from the back of haystack, if it matches.

[source](https://doc.rust-lang.org/src/core/ptr/mod.rs.html#1928)
```
impl<F> Pointer for F
where
    F: FnPtr,
```

[source](https://doc.rust-lang.org/src/core/ptr/mod.rs.html#1929)
```
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
```
Formats the value using the given formatter.

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#82)
```
impl<T> ToOwned for T
where
    T: Clone,
```


```
type Owned = T
```
The resulting type after obtaining ownership.
[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#87)
```
fn to_owned(&self) -> T
```
Creates owned data from borrowed data, usually by cloning. [Read more](borrow/trait.toowned#tymethod.to_owned)

[source](https://doc.rust-lang.org/src/alloc/borrow.rs.html#91)
```
fn clone_into(&self, target: &mut T)
```
Uses borrowed data to replace owned data, usually by cloning. [Read more](borrow/trait.toowned#method.clone_into)


[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#763)
```
impl<T, U> TryFrom<U> for T
where
    U: Into<T>,
```


```
type Error = Infallible
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#770)
```
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#748)
```
impl<T, U> TryInto<U> for T
where
    U: TryFrom<T>,
```


```
type Error = <U as TryFrom<T>>::Error
```
The type returned in the event of a conversion error.
[source](https://doc.rust-lang.org/src/core/convert/mod.rs.html#755)
```
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
```
Performs the conversion.

[source](https://doc.rust-lang.org/src/core/ptr/mod.rs.html#1903)
```
impl<F> Eq for F
where
    F: FnPtr,
```



 © 2010 The Rust Project Developers  
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.  

<https://doc.rust-lang.org/std/primitive.fn.html>

Primitive Type i8
=================


The 8-bit signed integer type.

 Implementations
---------------



[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#296)
```
impl i8
```

[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)1.43.0
```
pub const MIN: i8 = -128i8
```

The smallest value that can be represented by this integer type (−27).

 ##### Examples

 Basic usage:

 
```
assert_eq!(i8::MIN, -128);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)1.43.0
```
pub const MAX: i8 = 127i8
```

The largest value that can be represented by this integer type (27 − 1).

 ##### Examples

 Basic usage:

 
```
assert_eq!(i8::MAX, 127);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)1.53.0
```
pub const BITS: u32 = 8u32
```

The size of this integer type in bits.

 ##### Examples

 
```
assert_eq!(i8::BITS, 8);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)
```
pub fn from_str_radix(src: &str, radix: u32) -> Result<i8, ParseIntError>
```

Converts a string slice in a given base to an integer.

 The string is expected to be an optional `+` or `-` sign followed by digits. Leading and trailing whitespace represent an error. Digits are a subset of these characters, depending on `radix`:

 * `0-9`
* `a-z`
* `A-Z`

 ##### Panics

 This function panics if `radix` is not in the range from 2 to 36.

 ##### Examples

 Basic usage:

 
```
assert_eq!(i8::from_str_radix("A", 16), Ok(10));
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)const: 1.32.0
```
pub const fn count_ones(self) -> u32
```

Returns the number of ones in the binary representation of `self`.

 ##### Examples

 Basic usage:

 
```
let n = 0b100_0000i8;

assert_eq!(n.count_ones(), 1);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)const: 1.32.0
```
pub const fn count_zeros(self) -> u32
```

Returns the number of zeros in the binary representation of `self`.

 ##### Examples

 Basic usage:

 
```
assert_eq!(i8::MAX.count_zeros(), 1);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)const: 1.32.0
```
pub const fn leading_zeros(self) -> u32
```

Returns the number of leading zeros in the binary representation of `self`.

 Depending on what you’re doing with the value, you might also be interested in the [`ilog2`](primitive.i8#method.ilog2 "method i8::ilog2") function which returns a consistent number, even if the type widens.

 ##### Examples

 Basic usage:

 
```
let n = -1i8;

assert_eq!(n.leading_zeros(), 0);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)const: 1.32.0
```
pub const fn trailing_zeros(self) -> u32
```

Returns the number of trailing zeros in the binary representation of `self`.

 ##### Examples

 Basic usage:

 
```
let n = -4i8;

assert_eq!(n.trailing_zeros(), 2);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)1.46.0 (const: 1.46.0)
```
pub const fn leading_ones(self) -> u32
```

Returns the number of leading ones in the binary representation of `self`.

 ##### Examples

 Basic usage:

 
```
let n = -1i8;

assert_eq!(n.leading_ones(), 8);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)1.46.0 (const: 1.46.0)
```
pub const fn trailing_ones(self) -> u32
```

Returns the number of trailing ones in the binary representation of `self`.

 ##### Examples

 Basic usage:

 
```
let n = 3i8;

assert_eq!(n.trailing_ones(), 2);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)const: 1.32.0
```
pub const fn rotate_left(self, n: u32) -> i8
```

Shifts the bits to the left by a specified amount, `n`, wrapping the truncated bits to the end of the resulting integer.

 Please note this isn’t the same operation as the `<<` shifting operator!

 ##### Examples

 Basic usage:

 
```
let n = -0x7ei8;
let m = 0xa;

assert_eq!(n.rotate_left(2), m);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)const: 1.32.0
```
pub const fn rotate_right(self, n: u32) -> i8
```

Shifts the bits to the right by a specified amount, `n`, wrapping the truncated bits to the beginning of the resulting integer.

 Please note this isn’t the same operation as the `>>` shifting operator!

 ##### Examples

 Basic usage:

 
```
let n = 0xai8;
let m = -0x7e;

assert_eq!(n.rotate_right(2), m);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)const: 1.32.0
```
pub const fn swap_bytes(self) -> i8
```

Reverses the byte order of the integer.

 ##### Examples

 Basic usage:

 
```
let n = 0x12i8;

let m = n.swap_bytes();

assert_eq!(m, 0x12);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)1.37.0 (const: 1.37.0)
```
pub const fn reverse_bits(self) -> i8
```

Reverses the order of bits in the integer. The least significant bit becomes the most significant bit, second least-significant bit becomes second most-significant bit, etc.

 ##### Examples

 Basic usage:

 
```
let n = 0x12i8;
let m = n.reverse_bits();

assert_eq!(m, 0x48);
assert_eq!(0, 0i8.reverse_bits());
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)const: 1.32.0
```
pub const fn from_be(x: i8) -> i8
```

Converts an integer from big endian to the target’s endianness.

 On big endian this is a no-op. On little endian the bytes are swapped.

 ##### Examples

 Basic usage:

 
```
let n = 0x1Ai8;

if cfg!(target_endian = "big") {
    assert_eq!(i8::from_be(n), n)
} else {
    assert_eq!(i8::from_be(n), n.swap_bytes())
}
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)const: 1.32.0
```
pub const fn from_le(x: i8) -> i8
```

Converts an integer from little endian to the target’s endianness.

 On little endian this is a no-op. On big endian the bytes are swapped.

 ##### Examples

 Basic usage:

 
```
let n = 0x1Ai8;

if cfg!(target_endian = "little") {
    assert_eq!(i8::from_le(n), n)
} else {
    assert_eq!(i8::from_le(n), n.swap_bytes())
}
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)const: 1.32.0
```
pub const fn to_be(self) -> i8
```

Converts `self` to big endian from the target’s endianness.

 On big endian this is a no-op. On little endian the bytes are swapped.

 ##### Examples

 Basic usage:

 
```
let n = 0x1Ai8;

if cfg!(target_endian = "big") {
    assert_eq!(n.to_be(), n)
} else {
    assert_eq!(n.to_be(), n.swap_bytes())
}
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)const: 1.32.0
```
pub const fn to_le(self) -> i8
```

Converts `self` to little endian from the target’s endianness.

 On little endian this is a no-op. On big endian the bytes are swapped.

 ##### Examples

 Basic usage:

 
```
let n = 0x1Ai8;

if cfg!(target_endian = "little") {
    assert_eq!(n.to_le(), n)
} else {
    assert_eq!(n.to_le(), n.swap_bytes())
}
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)const: 1.47.0
```
pub const fn checked_add(self, rhs: i8) -> Option<i8>
```

Checked integer addition. Computes `self + rhs`, returning `None` if overflow occurred.

 ##### Examples

 Basic usage:

 
```
assert_eq!((i8::MAX - 2).checked_add(1), Some(i8::MAX - 1));
assert_eq!((i8::MAX - 2).checked_add(3), None);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)const: [unstable](https://github.com/rust-lang/rust/issues/85122 "Tracking issue for const_inherent_unchecked_arith")
```
pub unsafe fn unchecked_add(self, rhs: i8) -> i8
```

🔬This is a nightly-only experimental API. (`unchecked_math` [#85122](https://github.com/rust-lang/rust/issues/85122))

Unchecked integer addition. Computes `self + rhs`, assuming overflow cannot occur.

 ##### Safety

 This results in undefined behavior when `self + rhs > i8::MAX` or `self + rhs < i8::MIN`, i.e. when [`checked_add`](primitive.i8#method.checked_add "method i8::checked_add") would return `None`.

 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)1.66.0 (const: 1.66.0)
```
pub const fn checked_add_unsigned(self, rhs: u8) -> Option<i8>
```

Checked addition with an unsigned integer. Computes `self + rhs`, returning `None` if overflow occurred.

 ##### Examples

 Basic usage:

 
```
assert_eq!(1i8.checked_add_unsigned(2), Some(3));
assert_eq!((i8::MAX - 2).checked_add_unsigned(3), None);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)const: 1.47.0
```
pub const fn checked_sub(self, rhs: i8) -> Option<i8>
```

Checked integer subtraction. Computes `self - rhs`, returning `None` if overflow occurred.

 ##### Examples

 Basic usage:

 
```
assert_eq!((i8::MIN + 2).checked_sub(1), Some(i8::MIN + 1));
assert_eq!((i8::MIN + 2).checked_sub(3), None);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)const: [unstable](https://github.com/rust-lang/rust/issues/85122 "Tracking issue for const_inherent_unchecked_arith")
```
pub unsafe fn unchecked_sub(self, rhs: i8) -> i8
```

🔬This is a nightly-only experimental API. (`unchecked_math` [#85122](https://github.com/rust-lang/rust/issues/85122))

Unchecked integer subtraction. Computes `self - rhs`, assuming overflow cannot occur.

 ##### Safety

 This results in undefined behavior when `self - rhs > i8::MAX` or `self - rhs < i8::MIN`, i.e. when [`checked_sub`](primitive.i8#method.checked_sub "method i8::checked_sub") would return `None`.

 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)1.66.0 (const: 1.66.0)
```
pub const fn checked_sub_unsigned(self, rhs: u8) -> Option<i8>
```

Checked subtraction with an unsigned integer. Computes `self - rhs`, returning `None` if overflow occurred.

 ##### Examples

 Basic usage:

 
```
assert_eq!(1i8.checked_sub_unsigned(2), Some(-1));
assert_eq!((i8::MIN + 2).checked_sub_unsigned(3), None);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)const: 1.47.0
```
pub const fn checked_mul(self, rhs: i8) -> Option<i8>
```

Checked integer multiplication. Computes `self * rhs`, returning `None` if overflow occurred.

 ##### Examples

 Basic usage:

 
```
assert_eq!(i8::MAX.checked_mul(1), Some(i8::MAX));
assert_eq!(i8::MAX.checked_mul(2), None);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)const: [unstable](https://github.com/rust-lang/rust/issues/85122 "Tracking issue for const_inherent_unchecked_arith")
```
pub unsafe fn unchecked_mul(self, rhs: i8) -> i8
```

🔬This is a nightly-only experimental API. (`unchecked_math` [#85122](https://github.com/rust-lang/rust/issues/85122))

Unchecked integer multiplication. Computes `self * rhs`, assuming overflow cannot occur.

 ##### Safety

 This results in undefined behavior when `self * rhs > i8::MAX` or `self * rhs < i8::MIN`, i.e. when [`checked_mul`](primitive.i8#method.checked_mul "method i8::checked_mul") would return `None`.

 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)const: 1.52.0
```
pub const fn checked_div(self, rhs: i8) -> Option<i8>
```

Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0` or the division results in overflow.

 ##### Examples

 Basic usage:

 
```
assert_eq!((i8::MIN + 1).checked_div(-1), Some(127));
assert_eq!(i8::MIN.checked_div(-1), None);
assert_eq!((1i8).checked_div(0), None);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)1.38.0 (const: 1.52.0)
```
pub const fn checked_div_euclid(self, rhs: i8) -> Option<i8>
```

Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None` if `rhs == 0` or the division results in overflow.

 ##### Examples

 Basic usage:

 
```
assert_eq!((i8::MIN + 1).checked_div_euclid(-1), Some(127));
assert_eq!(i8::MIN.checked_div_euclid(-1), None);
assert_eq!((1i8).checked_div_euclid(0), None);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)1.7.0 (const: 1.52.0)
```
pub const fn checked_rem(self, rhs: i8) -> Option<i8>
```

Checked integer remainder. Computes `self % rhs`, returning `None` if `rhs == 0` or the division results in overflow.

 ##### Examples

 Basic usage:

 
```
assert_eq!(5i8.checked_rem(2), Some(1));
assert_eq!(5i8.checked_rem(0), None);
assert_eq!(i8::MIN.checked_rem(-1), None);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)1.38.0 (const: 1.52.0)
```
pub const fn checked_rem_euclid(self, rhs: i8) -> Option<i8>
```

Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None` if `rhs == 0` or the division results in overflow.

 ##### Examples

 Basic usage:

 
```
assert_eq!(5i8.checked_rem_euclid(2), Some(1));
assert_eq!(5i8.checked_rem_euclid(0), None);
assert_eq!(i8::MIN.checked_rem_euclid(-1), None);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)1.7.0 (const: 1.47.0)
```
pub const fn checked_neg(self) -> Option<i8>
```

Checked negation. Computes `-self`, returning `None` if `self == MIN`.

 ##### Examples

 Basic usage:

 
```
assert_eq!(5i8.checked_neg(), Some(-5));
assert_eq!(i8::MIN.checked_neg(), None);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)1.7.0 (const: 1.47.0)
```
pub const fn checked_shl(self, rhs: u32) -> Option<i8>
```

Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger than or equal to the number of bits in `self`.

 ##### Examples

 Basic usage:

 
```
assert_eq!(0x1i8.checked_shl(4), Some(0x10));
assert_eq!(0x1i8.checked_shl(129), None);
```
 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)const: [unstable](https://github.com/rust-lang/rust/issues/85122 "Tracking issue for const_inherent_unchecked_arith")
```
pub unsafe fn unchecked_shl(self, rhs: u32) -> i8
```

🔬This is a nightly-only experimental API. (`unchecked_math` [#85122](https://github.com/rust-lang/rust/issues/85122))

Unchecked shift left. Computes `self << rhs`, assuming that `rhs` is less than the number of bits in `self`.

 ##### Safety

 This results in undefined behavior if `rhs` is larger than or equal to the number of bits in `self`, i.e. when [`checked_shl`](primitive.i8#method.checked_shl "method i8::checked_shl") would return `None`.

 
[source](https://doc.rust-lang.org/src/core/num/mod.rs.html#297-316)1.7.0 (const: 1.47.0)
```
pub const fn checked_shr(self, rhs: u32) -> Option<i8>
```

Checked shift right. Computes `self >> rhs`, returning `Non
[cell cut: 22,491,609 characters, first 4,193,888 kept]