{"id": "async-book/intro.md#section-0", "text": "Asynchronous Programming in Rust\n\nNOTE: this guide is currently undergoing a rewrite after a long time without much work. It is work in progress, much is missing, and what exists is a bit rough.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Table of Contents", "chapter": "Introduction", "heading_path": [], "path": "intro.md", "url": "https://rust-lang.github.io/async-book/intro.html", "has_code": false, "code_tags": []}} {"id": "async-book/intro.md#introduction-1", "text": "Asynchronous Programming in Rust › Introduction\n\nThis book is a guide to asynchronous programming in Rust. It is designed to help you take your first steps and to discover more about advanced topics. We don't assume any experience with asynchronous programming (in Rust or another language), but we do assume you're familiar with Rust already. If you want to learn about Rust, you could start with The Rust Programming Language.\nThis book has two main parts: part one is a beginners guide, it is designed to be read in-order and to take you from total beginner to intermediate level. Part two is a collection of stand-alone chapters on more advanced topics. It should be useful once you've worked through part one or if you already have some experience with async Rust.\nYou can navigate this book in multiple ways:\n* You can read it front to back, in order. This is the recommend path for newcomers to async Rust, at least for part one of the book.\n* There is a summary contents on the left-hand side of the webpage.\n* If you want information about a broad topic, you could start with the topic index.\n* If you want to find all discussion about a specific topic, you could start with the detailed index.\n* You could see if your question is answered in the FAQs.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Table of Contents", "chapter": "Introduction", "heading_path": ["Introduction"], "path": "intro.md", "url": "https://rust-lang.github.io/async-book/intro.html#introduction", "has_code": false, "code_tags": []}} {"id": "async-book/intro.md#what-is-async-programming-and-why-would-you-do-it-2", "text": "Asynchronous Programming in Rust › Introduction › What is Async Programming and why would you do it?\n\nIn concurrent programming, the program does multiple things at the same time (or at least appears to). Programming with threads is one form of concurrent programming. Code within a thread is written in sequential style and the operating system executes threads concurrently. With async programming, concurrency happens entirely within your program (the operating system is not involved). An async runtime (which is just another crate in Rust) manages async tasks in conjunction with the programmer explicitly yielding control by using the `await` keyword.\nBecause the operating system is not involved, *context switching* in the async world is very fast. Furthermore, async tasks have much lower memory overhead than operating system threads. This makes async programming a good fit for systems which need to handle very many concurrent tasks and where those tasks spend a lot of time waiting (for example, for client responses or for IO). It also makes async programming a good fit for microcontrollers with very limited amounts of memory and no operating system that provides threads.\nAsync programming also offers the programmer fine-grained control over how tasks are executed (levels of parallelism and concurrency, control flow, scheduling, and so forth). This means that async programming can be expressive as well as ergonomic for many uses. In particular, async programming in Rust has a powerful concept of cancellation and supports many different flavours of concurrency (expressed using constructs including `spawn` and its variations, `join`, `select`, `for_each_concurrent`, etc.). These allow composable and reusable implementations of concepts like timeouts, pausing, and throttling.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Table of Contents", "chapter": "Introduction", "heading_path": ["Introduction", "What is Async Programming and why would you do it?"], "path": "intro.md", "url": "https://rust-lang.github.io/async-book/intro.html#what-is-async-programming-and-why-would-you-do-it", "has_code": false, "code_tags": []}} {"id": "async-book/intro.md#hello-world-3", "text": "Asynchronous Programming in Rust › Introduction › Hello, world!\n\nJust to give you a taste of what async Rust looks like, here is a 'hello, world' example. There is no concurrency, and it doesn't really take advantage of being async. It does define and use an async function, and it does print \"hello, world!\":\n```rust,edition2021\n// Define an async function.\nasync fn say_hello() {\n println!(\"hello, world!\");\n}\n\n#[tokio::main] // Boilerplate which lets us write `async fn main`, we'll explain it later.\nasync fn main() {\n // Call an async function and await its result.\n say_hello().await;\n}\n```\nWe'll explain everything in detail later. For now, note how we define an asynchronous function using `async fn` and call it using `.await` - an async function in Rust doesn't do anything unless it is `await`ed[^blocking].\nLike all examples in this book, if you want to see the full example (including `Cargo.toml`, for example) or to run it yourself locally, you can find them in the book's GitHub repo: e.g., examples/hello-world.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Table of Contents", "chapter": "Introduction", "heading_path": ["Introduction", "Hello, world!"], "path": "intro.md", "url": "https://rust-lang.github.io/async-book/intro.html#hello-world", "has_code": true, "code_tags": ["rust,edition2021"]}} {"id": "async-book/intro.md#development-of-async-rust-4", "text": "Asynchronous Programming in Rust › Introduction › Development of Async Rust\n\nThe async features of Rust have been in development for a while, but it is not a 'finished' part of the language. Async Rust (at least the parts available in the stable compiler and standard libraries) is reliable and performant. It is used in production in some of the most demanding situations at the largest tech companies. However, there are some missing parts and rough edges (rough in the sense of ergonomics rather than reliability). You are likely to stumble upon some of these parts during your journey with async Rust. For most missing parts, there are workarounds and these are covered in this book.\nCurrently, working with async iterators (also known as streams) is where most users find some rough parts. Some uses of async in traits are not yet well-supported. There is not a good solution for async destruction.\nAsync Rust is being actively worked on. If you want to follow development, you can check out the Async Working Group's home page which includes their roadmap. Or you could read the async project goal within the Rust Project.\nRust is an open source project. If you'd like to contribute to development of async Rust, start at the contributing docs in the main Rust repo.\n[^blocking]: This is actually a bad example because `println` is *blocking IO* and it is generally a bad idea to do blocking IO in async functions. We'll explain what blocking IO is in chapter TODO and why you shouldn't do blocking IO in an async function in chapter TODO.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Table of Contents", "chapter": "Introduction", "heading_path": ["Introduction", "Development of Async Rust"], "path": "intro.md", "url": "https://rust-lang.github.io/async-book/intro.html#development-of-async-rust", "has_code": false, "code_tags": []}} {"id": "async-book/navigation/intro.md#navigation-0", "text": "Asynchronous Programming in Rust › Navigation\n\nTODO Intro to navigation\n- By topic\n- FAQs\n- Index", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Table of Contents", "chapter": "Navigation", "heading_path": ["Navigation"], "path": "navigation/intro.md", "url": "https://rust-lang.github.io/async-book/navigation/intro.html#navigation", "has_code": false, "code_tags": []}} {"id": "async-book/navigation/topics.md#concurrency-and-parallelism-0", "text": "Asynchronous Programming in Rust › Topic index › Concurrency and parallelism\n\n- Introduction\n- Running async tasks in parallel using `spawn`\n- Running futures concurrently using `join` and `select`\n- Mixing sync and async concurrency", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Table of Contents", "chapter": "By topic", "heading_path": ["Topic index", "Concurrency and parallelism"], "path": "navigation/topics.md", "url": "https://rust-lang.github.io/async-book/navigation/topics.html#concurrency-and-parallelism", "has_code": false, "code_tags": []}} {"id": "async-book/navigation/topics.md#correctness-and-safety-1", "text": "Asynchronous Programming in Rust › Topic index › Correctness and safety\n\n- Cancellation\n - Introduction\n - In `select` and `try_join`", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Table of Contents", "chapter": "By topic", "heading_path": ["Topic index", "Correctness and safety"], "path": "navigation/topics.md", "url": "https://rust-lang.github.io/async-book/navigation/topics.html#correctness-and-safety", "has_code": false, "code_tags": []}} {"id": "async-book/navigation/topics.md#performance-2", "text": "Asynchronous Programming in Rust › Topic index › Performance\n\n- Blocking\n - Introduction\n - Blocking and non-blocking IO\n - CPU-intensive code", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Table of Contents", "chapter": "By topic", "heading_path": ["Topic index", "Performance"], "path": "navigation/topics.md", "url": "https://rust-lang.github.io/async-book/navigation/topics.html#performance", "has_code": false, "code_tags": []}} {"id": "async-book/navigation/topics.md#testing-3", "text": "Asynchronous Programming in Rust › Topic index › Testing\n\n- Unit test syntax", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Table of Contents", "chapter": "By topic", "heading_path": ["Topic index", "Testing"], "path": "navigation/topics.md", "url": "https://rust-lang.github.io/async-book/navigation/topics.html#testing", "has_code": false, "code_tags": []}} {"id": "async-book/navigation/index.md#index-0", "text": "Asynchronous Programming in Rust › Index\n\n- Async/`async`\n - blocks\n - closures\n - functions\n - traits\n - c.f., threads\n- `await`\n- Blocking\n - IO\n - CPU-intensive tasks\n- Cancellation\n - `CancellationToken`\n - In `select`\n- Concurrency\n - c.f., parallelism\n - Primitives (`join`, `select`, etc.)\n- Cooperative scheduling\n- Executor\n- Futures\n - `Future` trait\n- IO\n - Blocking", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Table of Contents", "chapter": "Index", "heading_path": ["Index"], "path": "navigation/index.md", "url": "https://rust-lang.github.io/async-book/navigation/index.html#index", "has_code": false, "code_tags": []}} {"id": "async-book/navigation/index.md#index-1", "text": "Asynchronous Programming in Rust › Index\n\n- `join`\n- Joining tasks\n- `JoinHandle`\n - `abort`\n- Multiple runtimes\n- Multitasking\n - Cooperative, yielding\n - Pre-emptive\n- Parallelism\n - c.f., concurrency\n- Pinning, `Pin`\n- `race`\n- Reactor\n- Runtimes\n- Scheduler\n- `select`\n- Spawning tasks", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Table of Contents", "chapter": "Index", "heading_path": ["Index"], "path": "navigation/index.md", "url": "https://rust-lang.github.io/async-book/navigation/index.html#index", "has_code": false, "code_tags": []}} {"id": "async-book/navigation/index.md#index-2", "text": "Asynchronous Programming in Rust › Index\n\n- Tasks\n - Spawning\n- Testing\n - Unit tests\n- Threads\n- Tokio\n- Traits\n - async\n - `Future`\n- `try_join`\n- `Unpin`\n- Waiting\n- Yielding\n- `yield_now`", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Table of Contents", "chapter": "Index", "heading_path": ["Index"], "path": "navigation/index.md", "url": "https://rust-lang.github.io/async-book/navigation/index.html#index", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/intro.md#part-1-a-guide-to-asynchronous-programming-in-rust-0", "text": "Asynchronous Programming in Rust › Part 1: A guide to asynchronous programming in Rust\n\nThis part of the book is a tutorial-style guide to async Rust. It is aimed at newcomers to async programming in Rust. It should be useful whether or not you've done async programming in other languages. If you have, you might skip the first section or skim it as a refresher. You might also want to read this comparison to async in other languages sooner rather than later.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Introduction", "heading_path": ["Part 1: A guide to asynchronous programming in Rust"], "path": "part-guide/intro.md", "url": "https://rust-lang.github.io/async-book/part-guide/intro.html#part-1-a-guide-to-asynchronous-programming-in-rust", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/intro.md#core-concepts-1", "text": "Asynchronous Programming in Rust › Part 1: A guide to asynchronous programming in Rust › Core concepts\n\nWe'll start by discussing different models of concurrent programming, using processes, threads, or async tasks. The first chapter will cover the essential parts of Rust's async model before we get into the nitty-gritty of async programming in the second chapter where we introduce the async and await programming paradigm. We cover some more async programming concepts in the following chapter.\nOne of the main motivations for async programming is more performant IO, which we cover in the next chapter. We also cover *blocking* in detail in the same chapter. Blocking is a major hazard in async programming where a thread is blocked from making progress by an operation (often IO) which synchronously waits.\nAnother motivation for async programming is that it facilitates new models for abstraction and composition of concurrent code. After covering that, we move on to synchronization between concurrent tasks.\nThere is a chapter on tools for async programming.\nThe last few chapters cover some more specialised topics, starting with async destruction and clean-up (which is a common requirement, but since there is currently not a good built-in solution, is a bit of a specialist topic).\nThe next two chapters in the guide go into detail on futures and runtimes, two fundamental building blocks for async programming.\nFinally, we cover timers and signal handling and async iterators (aka streams). The latter are how we program with sequences of async events (c.f., individual async events which are represented using futures or async functions). This is an area where the language is being actively developed and can be a little rough around the edges.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Introduction", "heading_path": ["Part 1: A guide to asynchronous programming in Rust", "Core concepts"], "path": "part-guide/intro.md", "url": "https://rust-lang.github.io/async-book/part-guide/intro.html#core-concepts", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/concurrency.md#concurrent-programming-0", "text": "Asynchronous Programming in Rust › Concurrent programming\n\nThe goal of this chapter is to give you a high-level idea of how async concurrency works and how it is different from concurrency with threads. I think it is important to have a good mental model of what is going on before getting in to the practicalities, but if you're the kind of person who likes to see some real code first, you might like to read the next chapter or two and then come back to this one.\nWe'll start with some motivation, then cover sequential programming, programming with threads or processes, and then async programming. The chapter finishes with a section on concurrency and parallelism.\nUsers want their computers to do multiple things. Sometimes users want to do those things at the same time (e.g., be listening to a music app at the same time as typing in their editor). Sometimes doing multiple tasks at the same time is more efficient (e.g., getting some work done in the editor while a large file downloads). Sometimes there are multiple users wanting to use a single computer at the same time (e.g., multiple clients connected to a server).", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Concurrent programming", "heading_path": ["Concurrent programming"], "path": "part-guide/concurrency.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency.html#concurrent-programming", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/concurrency.md#concurrent-programming-1", "text": "Asynchronous Programming in Rust › Concurrent programming\n\nTo give a lower-level example, a music program might need to keep playing music while the user interacts with the user interface (UI). To 'keep playing music', it might need to stream music data from the server, process that data from one format to another, and send the processed data to the computer's audio system via the operating system (OS). For the user, it might need to send and receive data or commands to the server in response to the user instructions, it might need to send signals to the subsystem playing music (e.g., if the user changes track or pauses), it might need to update the graphical display (e.g., highlighting a button or changing the track name), and it must keep the mouse cursor or text inputs responsive while doing all of the above.\nDoing multiple things at once (or appearing to do so) is called concurrency. Programs (in conjunction with the OS) must manage their concurrency and there are many ways to do that. We'll describe some of those ways in this chapter, but we'll start with purely sequential code, i.e., no concurrency at all.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Concurrent programming", "heading_path": ["Concurrent programming"], "path": "part-guide/concurrency.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency.html#concurrent-programming", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/concurrency.md#sequential-execution-2", "text": "Asynchronous Programming in Rust › Concurrent programming › Sequential execution\n\nThe default mode of execution in most programming languages (including Rust) is sequential execution.\n```\ndo_a_thing();\nprintln!(\"hello!\");\ndo_another_thing();\n```\nEach statement is completed before the next one starts[^obs1]. Nothing happens in between those statements[^obs2]. This might sound trivial but it is a really useful property for reasoning about our code. However, it also means we waste a lot of time. In the above example, while we're waiting for `println!(\"hello!\")` to happen, we could have executed `do_another_thing()`. Perhaps we could even have executed all three statements at the same time.\nWhenever IO[^io-def] happens (printing using `println!` is IO - it is outputting text to the console via a call to the OS), the program will wait for the IO to complete[^io-complete] before executing the next statement. Waiting for IO to complete before continuing with execution *blocks* the program from making other progress. Blocking IO is the easiest kind of IO to use, implement, and reason about, but it is also the least efficient - in a sequential world, the program can do nothing while it waits for the IO to complete.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Concurrent programming", "heading_path": ["Concurrent programming", "Sequential execution"], "path": "part-guide/concurrency.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency.html#sequential-execution", "has_code": true, "code_tags": ["(untagged)"]}} {"id": "async-book/part-guide/concurrency.md#sequential-execution-3", "text": "Asynchronous Programming in Rust › Concurrent programming › Sequential execution\n\n[^obs1]: This isn't really true: modern compilers and CPUs will reorganize your code and run it any order they like. Sequential statements are likely to overlap in many different ways. However, this should never be *observable* to the program itself or its users.\n[^obs2]: This isn't true either: even when one program is purely sequential, other programs might be running at the same time; more on this in the next section.\n[^io-def]: IO is an acronym of input/output. It means any communication from the program to the world outside the program. That might be reading or writing to disk or the network, writing to the terminal, getting user input from a keyboard or mouse, or communicating with the OS or another program running in the system. IO is interesting in the context of concurrency because it takes several orders of magnitude longer to happen than nearly any task a program might do internally. That typically means lots of waiting, and that waiting time is an opportunity to do other work.\n[^io-complete]: Exactly when IO is complete is actually rather complicated. From the program's perspective a single IO call is complete when control is returned from the OS. This usually indicates that data has been sent to some hardware or other program, but it doesn't necessarily mean that the data has actually been written to disk or displayed to the user, etc. That might require more work in the hardware or periodic flushing of caches, or for another program to read the data. Mostly we don't need to worry about this, but it's good to be aware of.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Concurrent programming", "heading_path": ["Concurrent programming", "Sequential execution"], "path": "part-guide/concurrency.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency.html#sequential-execution", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/concurrency.md#processes-and-threads-4", "text": "Asynchronous Programming in Rust › Concurrent programming › Processes and threads\n\nProcesses and threads are concepts which are provided by the operating system to provide concurrency. There is one process per executable, so supporting multiple processes means a computer can run multiple programs[^proc-program] concurrently; there can be multiple threads per process, which means there can also be concurrency *within* a process.\nThere are many small differences in the way that processes and threads are handled. The most important difference is that memory is shared between threads but not between processes[^shmem]. That means that communication between processes happens by some kind of message passing, similar to communicating between programs running on different computers. From a program's perspective, the single process is their whole world; creating new processes means running new programs. Creating new threads, however, is just part of the program's regular execution.\nBecause of these distinctions between processes and threads, they feel very different to a programmer. But from the OS's perspective they are very similar and we'll discuss their properties as if they were a single concept. We'll talk about threads, but unless we note otherwise, you should understand that to mean 'threads or processes'.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Concurrent programming", "heading_path": ["Concurrent programming", "Processes and threads"], "path": "part-guide/concurrency.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency.html#processes-and-threads", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/concurrency.md#processes-and-threads-5", "text": "Asynchronous Programming in Rust › Concurrent programming › Processes and threads\n\nThe OS is responsible for *scheduling* threads, which means it decides when threads run and for how long. Most modern computers have multiple cores, so they can run multiple threads at literally the same time. However, it is common to have many more threads than cores, so the OS will run each thread for a small amount of time and then pause it and run a different thread for some time[^sched]. When multiple threads are run on a single core in this fashion, it is called *interleaving* or *time-slicing*. Since the OS chooses when to pause a thread's execution, it is called *pre-emptive multitasking* (multitasking here just means running multiple threads at the same time); the OS *pre-empts* execution of a thread (or more verbosely, the OS pre-emptively pauses execution. It is pre-emptive because the OS is pausing the thread to make time for another thread, before the first thread would otherwise pause, to ensure that the second thread can execute before it becomes a problem that it can't).\nLet's look at IO again. What happens when a thread blocks waiting for IO? In a system with threads, then the OS will pause the thread (it's just going to be waiting in any case) and wake it up again when the IO is complete[^busywait]. Depending on the scheduling algorithm, it might take some time after the IO completes until the OS wakes up the thread waiting for IO, since the OS might wait for other threads to get some work done. So now things are much more efficient: while one thread waits for IO, another thread (or more likely, many threads due to multitasking) can make progress. But, from the perspective of the thread doing IO, things are still sequential - it waits for the IO to finish before starting the next operation.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Concurrent programming", "heading_path": ["Concurrent programming", "Processes and threads"], "path": "part-guide/concurrency.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency.html#processes-and-threads", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/concurrency.md#processes-and-threads-6", "text": "Asynchronous Programming in Rust › Concurrent programming › Processes and threads\n\nA thread can also choose to pause itself by calling a `sleep` function, usually with a timeout. In this case the OS pauses the thread at the threads own request. Similar to pausing due to pre-emption or IO, the OS will wake the thread up again later (after the timeout) to continue execution.\nWhen an OS pauses one thread and starts another (for any reason), it is called *context switching*. The context being switched includes the registers, operating system records, and the contents of many caches. That's a non-trivial amount of work. Together with the transfer of control to the OS and back to a thread, and the costs of working with stale caches, context switching is an expensive operation.\nFinally, note that some hardware or OSs do not support processes or threads, this is more likely in the embedded world.\n[^proc-program]: from the user's perspective, a single program may include multiple processes, but from the OS's perspective each process is a separate program.\n[^shmem]: Some OSs do support sharing memory between processes, but using it requires special treatment and most memory is not shared.\n[^sched]: Exactly how the OS chooses which thread to run and for how long (and on which core), is a key part of scheduling. There are many options, both high-level strategies and options to configure those strategies. Making good choices here is crucial for good performance, but it is complicated and we won't dig into it here.\n[^busywait]: There's another option which is that the thread can *busy wait* by just spinning in a loop until the IO is finished. This is not very efficient since other threads won't get to run and is uncommon in most modern systems. You may come across it in the implementations of locks or in very simple embedded systems.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Concurrent programming", "heading_path": ["Concurrent programming", "Processes and threads"], "path": "part-guide/concurrency.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency.html#processes-and-threads", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/concurrency.md#async-programming-7", "text": "Asynchronous Programming in Rust › Concurrent programming › Async programming\n\nAsync programming is a kind of concurrency with the same high-level goals as concurrency with threads (do many things at the same time), but a different implementation. The two big differences between async concurrency and concurrency with threads, is that async concurrency is managed entirely within the program with no help from the OS[^threads], and that multitasking is cooperative rather than pre-emptive[^other] (we'll explain that in a minute). There are many different models of async concurrency, we'll compare them later on in the guide, but for now we'll focus only on Rust's model.\nTo distinguish them from threads, we'll call a sequence of executions in async concurrency a task (they're also called *green threads*, but this sometimes has connotations of pre-emptive scheduling and implementation details like one stack per task). The way a task is executed, scheduled, and represented in memory is very different to a thread, but for a high-level intuition, it can be useful to think of tasks as just like threads, but managed entirely within the program, rather than by the OS.\nIn an async system, there is still a scheduler which decides which task to run next (it's part of the program, not part of the OS). However, the scheduler cannot pre-empt a task. Instead a task must voluntarily give up control and allow another task to be scheduled. Because tasks must cooperate (by giving up control), this is called cooperative multitasking.\nUsing cooperative rather than pre-emptive multitasking has many implications:\n* between points where control might be yielded, you can guarantee that code will be executed sequentially - you'll never be unexpectedly paused,\n* if a task takes a long time between yield points (e.g., by doing blocking IO or performing long-running computation), other tasks will not be able to make progress,\n* implementing a scheduler is much simpler and scheduling (and context switching) has fewer overheads.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Concurrent programming", "heading_path": ["Concurrent programming", "Async programming"], "path": "part-guide/concurrency.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency.html#async-programming", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/concurrency.md#async-programming-8", "text": "Asynchronous Programming in Rust › Concurrent programming › Async programming\n\nAsync concurrency is much more efficient than concurrency with threads. The memory overheads are much lower and context switching is a much cheaper operation - it doesn't require handing control to the OS and back to the program and there is much less data to switch. However, there can still be some cache effects - although the OS's caches such as the TLB don't need to be changed, tasks are likely to operate on different parts of memory, so data required by the newly scheduled task may not be in a memory cache.\nAsynchronous *IO* is an alternative to blocking IO (it's sometimes called non-blocking IO). Async IO is not directly tied to async concurrency, but the two are often used together. In async IO, a program initiates IO with one system call and then can either check or be notified when the IO completes. That means the program is free to get other work done while the IO takes place. In Rust, the mechanics of async IO are handled by the async runtime (the scheduler is also part of the runtime, we'll discuss runtimes in more detail later in this book, but essentially the runtime is just a library which takes care of some of the fundamental async stuff).", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Concurrent programming", "heading_path": ["Concurrent programming", "Async programming"], "path": "part-guide/concurrency.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency.html#async-programming", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/concurrency.md#async-programming-9", "text": "Asynchronous Programming in Rust › Concurrent programming › Async programming\n\nFrom the perspective of the whole system, blocking IO in a concurrent system with threads and non-blocking IO in an async concurrent system are similar. In both cases, IO takes time and other work gets done while the IO is happening:\n- With threads, the thread doing IO requests IO from the OS, the thread is paused by the OS, other threads get work done, and when the IO is done, the OS wakes up the thread so it can continue execution with the result of the IO.\n- With async, the task doing IO requests IO from the runtime, the runtime requests IO from the OS but the OS returns control to the runtime. The runtime pauses the IO task and schedules other tasks to get work done. When the IO is done, the runtime wakes up the IO task so it can continue execution with the result of the IO.\nThe advantage of using async IO, is that the overheads are much lower so a system can support orders of magnitude more tasks than threads. That makes async concurrency particularly well-suited for tasks with lots of users which spend a lot of time waiting for IO (if they don't spend a lot of time waiting and instead do lots of CPU-bound work, then there is not so much advantage to the low-overheads because the bottleneck will be CPU and memory resources).\nThreads and async are not mutually exclusive: many programs use both. Some programs have parts which are better implemented using threads and parts which are better implemented using async. For example, a database server may use async techniques to manage network communication with clients, but use OS threads for computation on data. Alternatively, a program may be written only using async concurrency, but the runtime will execute tasks on multiple threads. This is necessary for a program to make use of multiple CPU cores. We'll cover the intersection of threads and async tasks in a number of places later in the book.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Concurrent programming", "heading_path": ["Concurrent programming", "Async programming"], "path": "part-guide/concurrency.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency.html#async-programming", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/concurrency.md#async-programming-10", "text": "Asynchronous Programming in Rust › Concurrent programming › Async programming\n\n[^threads]: We'll start our explanation assuming a program only has a single thread, but expand on that later. There will probably be other processes running on the system, but they don't really affect how async concurrency works.\n[^other]: There are some programming languages (or even libraries) which have concurrency which is managed within the program (without the OS), but with a pre-emptive scheduler rather than relying on cooperation between threads. Go is a well-known example. These systems don't require `async` and `await` notation, but have other downsides including making interop with other languages or the OS much more difficult, and having a heavyweight runtime. Very early versions of Rust had such a system, but no traces of it remained by 1.0.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Concurrent programming", "heading_path": ["Concurrent programming", "Async programming"], "path": "part-guide/concurrency.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency.html#async-programming", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/concurrency.md#concurrency-and-parallelism-11", "text": "Asynchronous Programming in Rust › Concurrent programming › Concurrency and Parallelism\n\nSo far we've been talking about concurrency (doing, or appearing to do, many things at the same time), and we've hinted at parallelism (the presence of multiple CPU cores which facilitates literally doing many things at the same time). These terms are sometimes used interchangeably, but they are distinct concepts. In this section, we'll try to precisely define these terms and the difference between them. I'll use simple pseudo-code to illustrate things.\nImagine a single task broken into a bunch of sub-tasks:\n```\ntask1 {\n subTask1-1()\n subTask1-2()\n ...\n subTask1-100()\n}\n```\nLet's pretend to be a processor which executes such pseudocode. The obvious way to do so is to first do `subTask1-1` then do `subTask1-2` and so on until we've completed all sub-tasks. This is sequential execution.\nNow consider multiple tasks. How might we execute them? We might start one task, do all the sub-tasks until the whole task is complete, then start on the next. The two tasks are being executed sequentially (and the sub-tasks within each task are also being executed sequentially). Looking at just the sub-tasks, you'd execute them like this:\n```\nsubTask1-1()\nsubTask1-2()\n...\nsubTask1-100()\nsubTask2-1()\nsubTask2-2()\n...\nsubTask2-100()\n\n```\nAlternatively, you could do `subTask1`, then put `task1` aside (remembering how far you got) and pick up the next task and do the first sub-task from that one, then go back to `task1` to do a sub-task. The two tasks would be interleaved, we call this concurrent execution of the two tasks. It might look like:", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Concurrent programming", "heading_path": ["Concurrent programming", "Concurrency and Parallelism"], "path": "part-guide/concurrency.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency.html#concurrency-and-parallelism", "has_code": true, "code_tags": ["(untagged)"]}} {"id": "async-book/part-guide/concurrency.md#concurrency-and-parallelism-12", "text": "Asynchronous Programming in Rust › Concurrent programming › Concurrency and Parallelism\n\n```\nsubTask1-1()\nsubTask2-1()\nsubTask1-2()\nsubTask2-2()\n...\nsubTask1-100()\nsubTask2-100()\n\n```\nUnless one task can observe the results or side-effects of a different task, then from the task's perspective, the sub-tasks are still being executed sequentially.\nThere's no reason we have to limit ourselves to two tasks, we could interleave any number and do so in any order.\nNote that no matter how much concurrency we add, the whole job takes the same amount of time to complete (in fact it might take longer with more concurrency due to the overheads of context switching between them). However, for a given sub-task, we might get it finished earlier than in the purely sequential execution (for a user, this might feel more responsive).\nNow, imagine it's not just you processing the tasks, you've got some processor friends to help you out. You can work on tasks at the same time and get the work done faster! This is *parallel* execution (which is also concurrent). You might execute the sub-tasks like:\n```\nProcessor 1 Processor 2\n============== ==============\nsubTask1-1() subTask2-1()\nsubTask1-2() subTask2-2()\n... ...\nsubTask1-100() subTask2-100()\n```\nIf there are more than two processors, we can process even more tasks in parallel. We could also do some interleaving of tasks on each processor or sharing of tasks between processors.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Concurrent programming", "heading_path": ["Concurrent programming", "Concurrency and Parallelism"], "path": "part-guide/concurrency.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency.html#concurrency-and-parallelism", "has_code": true, "code_tags": ["(untagged)"]}} {"id": "async-book/part-guide/concurrency.md#concurrency-and-parallelism-13", "text": "Asynchronous Programming in Rust › Concurrent programming › Concurrency and Parallelism\n\nIn real code, things are a bit more complicated. Some sub-tasks (e.g., IO) don't require a processor to actively participate, they just need starting and some time later collecting the results. And some sub-tasks might require the results (or side-effects) of a sub-task from a different task in order to make progress (synchronization). Both these scenarios limit the effective ways that tasks can be concurrently executed and that, together with ensuring some concept of fairness, is why scheduling is important.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Concurrent programming", "heading_path": ["Concurrent programming", "Concurrency and Parallelism"], "path": "part-guide/concurrency.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency.html#concurrency-and-parallelism", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/concurrency.md#enough-silly-examples-lets-try-to-define-things-properly-14", "text": "Asynchronous Programming in Rust › Concurrent programming › Concurrency and Parallelism › Enough silly examples, let's try to define things properly\n\nConcurrency is about ordering of computations and parallelism is about the mode of execution.\nGiven two computations, we say they are sequential (i.e., not concurrent) if we can observe that one happens before the other, or that they are concurrent if we cannot observe (or alternatively, it does not matter) that one happens before the other.\nTwo computations happen in parallel if they are literally happening at the same time. We can think of parallelism as a resource: the more parallelism is available, the more computations can happen in a fixed period of time (assuming that computation happens at the same speed). Increasing the concurrency of a system without increasing parallelism can never make it faster (although it can make the system more responsive and it may make it feasible to implement optimizations which would otherwise be impractical).\nTo restate, two computations may happen one after the other (neither concurrent nor parallel), their execution may be interleaved on a single CPU core (concurrent, but not parallel), or they may be executed at the same time on two cores (concurrent and parallel)[^p-not-c].\nAnother useful framing[^turon] is that concurrency is a way of organizing code and parallelism is a resource. This is a powerful statement! That concurrency is about organising code rather than executing code is important because from the perspective of the processor, concurrency without parallelism simply doesn't exist. It's particularly relevant for async concurrency because that is implemented entirely in user-side code - not only is it 'just' about organizing code, but you can easily prove that to yourself by just reading the source code. That parallelism is a resource is also useful because it reminds us that for parallelism and performance, only the number of processor cores is important, not how the code is organized with respect to concurrency (e.g., how many threads there are).", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Concurrent programming", "heading_path": ["Concurrent programming", "Concurrency and Parallelism", "Enough silly examples, let's try to define things properly"], "path": "part-guide/concurrency.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency.html#enough-silly-examples-lets-try-to-define-things-properly", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/concurrency.md#enough-silly-examples-lets-try-to-define-things-properly-15", "text": "Asynchronous Programming in Rust › Concurrent programming › Concurrency and Parallelism › Enough silly examples, let's try to define things properly\n\nBoth threaded and async systems can offer both concurrency and parallelism. In both cases, concurrency is controlled by code (spawning threads or tasks) and parallelism is controlled by the scheduler, which is part of the OS for threads (configured by the OS's API), and part of the runtime library for async (configured by choice of runtime, how the runtime is implemented, and options that the runtime provides to client code). There is however, a practical difference due to convention and common defaults. In threaded systems, each concurrent thread is executed in parallel using as much parallelism as possible. In async systems, there is no strong default: a system may run all tasks in a single thread, it may assign multiple tasks to a single thread and lock that thread to a core (so groups of tasks execute in parallel, but within a group each task executes concurrently, but never in parallel with other tasks within the group), or tasks may be run in parallel with or without limits. For the first part of this guide, we will use the Tokio runtime which primarily supports the last model. I.e., the behavior regarding parallelism is similar to concurrency with threads. Furthermore, we'll see features in async Rust which explicitly support concurrency but not parallelism, independent of the runtime.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Concurrent programming", "heading_path": ["Concurrent programming", "Concurrency and Parallelism", "Enough silly examples, let's try to define things properly"], "path": "part-guide/concurrency.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency.html#enough-silly-examples-lets-try-to-define-things-properly", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/concurrency.md#enough-silly-examples-lets-try-to-define-things-properly-16", "text": "Asynchronous Programming in Rust › Concurrent programming › Concurrency and Parallelism › Enough silly examples, let's try to define things properly\n\n[^p-not-c]: Can computation be parallel but not concurrent? Sort of but not really. Imagine two tasks (a and b) which consist of one sub-task each (1 and 2 belonging to a and b, respectively). By the use of synchronisation, we can't start sub-task 2 until sub-task 1 is complete and task a has to wait for sub-task 2 to complete until it is complete. Now a and b run on different processors. If we look at the tasks as black boxes, we can say they are running in parallel, but in a sense they are not concurrent because their ordering is fully determined. However, if we look at the sub-tasks we can see that they are neither parallel or concurrent.\n[^turon]: Which I think is due to Aaron Turon and is reflected in some of the design of Rust's standard library, e.g., in the available_parallelism function.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Concurrent programming", "heading_path": ["Concurrent programming", "Concurrency and Parallelism", "Enough silly examples, let's try to define things properly"], "path": "part-guide/concurrency.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency.html#enough-silly-examples-lets-try-to-define-things-properly", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/concurrency.md#summary-17", "text": "Asynchronous Programming in Rust › Concurrent programming › Summary\n\n- There are many models of execution. We described sequential execution, threads and processes, and asynchronous programming.\n - Threads are an abstraction provided (and scheduled) by the OS. They usually involve pre-emptive multitasking, are parallel by default, and have fairly high overheads of management and context switching.\n - Asynchronous programming is managed by a user-space runtime. Multi-tasking is cooperative. It has lower overheads than threads, but feels a bit different to programming with threads since it uses different programming primitives (`async` and `await`, and futures, rather than first-class threads).\n- Concurrency and parallelism are different but closely related concepts.\n - Concurrency is about ordering of computation (operations are concurrent if their order of execution cannot be observed).\n - Parallelism is about computing on multiple processors (operations are parallel if they are literally happening at the same time).\n- Both OS threads and async programming provide concurrency and parallelism; async programming can also offer constructs for flexible or fine-grained concurrency which are not part of most operating systems' threads API.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Concurrent programming", "heading_path": ["Concurrent programming", "Summary"], "path": "part-guide/concurrency.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency.html#summary", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/async-await.md#async-and-await-0", "text": "Asynchronous Programming in Rust › Async and Await\n\nIn this chapter we'll get started doing some async programming in Rust and we'll introduce the `async` and `await` keywords.\n`async` is an annotation on functions (and other items, such as traits, which we'll get to later); `await` is an operator used in expressions. But before we jump into those keywords, we need to cover a few core concepts of async programming in Rust, this follows from the discussion in the previous chapter, here we'll relate things directly to Rust programming.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Async and await", "heading_path": ["Async and Await"], "path": "part-guide/async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/async-await.html#async-and-await", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/async-await.md#the-runtime-1", "text": "Asynchronous Programming in Rust › Async and Await › Rust async concepts › The runtime\n\nAsync tasks must be managed and scheduled. There are typically more tasks than cores available so they can't all be run at once. When one stops executing another must be picked to execute. If a task is waiting on IO or some other event, it should not be scheduled, but when that completes, it should be scheduled. That requires interacting with the OS and managing IO work.\nMany programming languages provide a runtime. Commonly, this runtime does a lot more than manage async tasks - it might manage memory (including garbage collection), have a role in exception handling, provide an abstraction layer over the OS, or even be a full virtual machine. Rust is a low-level language and strives towards minimal runtime overhead. The async runtime therefore has a much more limited scope than many other languages' runtimes. There are also many ways to design and implement an async runtime, so Rust lets you choose one depending on your requirements, rather than providing one. This does mean that getting started with async programming requires an extra step.\nAs well as running and scheduling tasks, a runtime must interact with the OS to manage async IO. It must also provide timer functionality to tasks (which intersects with IO management). There are no strong rules about how a runtime must be structured, but some terms and division of responsibilities are common:\n- *reactor* or *event loop* or *driver* (equivalent terms): dispatches IO and timer events, interacts with the OS, and does the lowest-level driving forward of execution,\n- *scheduler*: determines when tasks can execute and on which OS threads,\n- *executor* or *runtime*: combines the reactor and scheduler, and is the user-facing API for running async tasks; *runtime* is also used to mean the whole library of functionality (e.g., everything in the Tokio crate, not just the Tokio executor which is represented by the `Runtime` type).", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Async and await", "heading_path": ["Async and Await", "Rust async concepts", "The runtime"], "path": "part-guide/async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/async-await.html#the-runtime", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/async-await.md#the-runtime-2", "text": "Asynchronous Programming in Rust › Async and Await › Rust async concepts › The runtime\n\nAs well as the executor as described above, a runtime crate typically includes many utility traits and functions. These might include traits (e.g., `AsyncRead`) and implementations for IO, functionality for common IO tasks such as networking or accessing the file system, locks, channels, and other synchronisation primitives, utilities for timing, utilities for working with the OS (e.g., signal handling), utility functions for working with futures and streams (async iterators), or monitoring and observation tools. We'll cover many of those in this guide.\nThere are many async runtimes to choose from. Some have very different scheduling policies, or are optimised for a specific task or domain. For most of this guide we'll use the Tokio runtime. It's a general purpose runtime and is the most popular runtime in the ecosystem. It's a great choice for getting started and for production work. In some circumstances, you might get better performance or be able to write simpler code with a different runtime. Later in this guide we'll discuss some of the other available runtimes and why you might choose one or another, or even write your own.\nTo get up and running as quickly as possible, you need just a little boilerplate. You'll need to include the Tokio crate as a dependency in your Cargo.toml (just like any other crate):\n```\n[dependencies]\ntokio = { version = \"1\", features = [\"full\"] }\n```\nAnd you'll use the `tokio::main` annotation on your `main` function so that it can be an async function (which is otherwise not permitted in Rust):\n```rust,norun\n#[tokio::main]\nasync fn main() { ... }\n```\nThat's it! You're ready to write some asynchronous code!", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Async and await", "heading_path": ["Async and Await", "Rust async concepts", "The runtime"], "path": "part-guide/async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/async-await.html#the-runtime", "has_code": true, "code_tags": ["(untagged)", "rust,norun"]}} {"id": "async-book/part-guide/async-await.md#the-runtime-3", "text": "Asynchronous Programming in Rust › Async and Await › Rust async concepts › The runtime\n\nThe `#[tokio::main]` annotation initializes the Tokio runtime and starts an async task for running the code in `main`. Later in this guide we'll explain in more detail what that annotation is doing and how to use async code without it (which will give you more flexibility).", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Async and await", "heading_path": ["Async and Await", "Rust async concepts", "The runtime"], "path": "part-guide/async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/async-await.html#the-runtime", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/async-await.md#futures-rs-and-the-ecosystem-4", "text": "Asynchronous Programming in Rust › Async and Await › Rust async concepts › Futures-rs and the ecosystem\n\nTODO context and history, what futures-rs is for - was used a lot, probably don't need it now, overlap with Tokio and other runtimes (sometimes with subtle semantic differences), why you might need it (working with futures directly, esp writing your own, streams, some utils)\nOther ecosystem stuff - Yosh's crates, alt runtimes, experimental stuff, other?", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Async and await", "heading_path": ["Async and Await", "Rust async concepts", "Futures-rs and the ecosystem"], "path": "part-guide/async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/async-await.html#futures-rs-and-the-ecosystem", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/async-await.md#futures-and-tasks-5", "text": "Asynchronous Programming in Rust › Async and Await › Rust async concepts › Futures and tasks\n\nThe basic unit of async concurrency in Rust is the *future*. A future is just a regular old Rust object (a struct or enum, usually) which implements the 'Future' trait. A future represents a deferred computation. That is, a computation that will be ready at some point in the future.\nWe'll talk a lot about futures in this guide, but it's easiest to get started without worrying too much about them. We'll mention them quite a bit in the next few sections, but we won't really define them or use them directly until later. One important aspect of futures is that they can be combined to make new, 'bigger' futures (we'll talk a lot more about *how* they can be combined later).\nI've used the term 'async task' quite a bit in an informal way in the previous chapter and this one. I've used the term to mean a logical sequence of execution; analogous to a thread but managed within a program rather than externally by the OS. It is often useful to think in terms of tasks, however, Rust itself has no concept of a task and the term is used to mean different things! It is confusing! To make it worse, runtimes do have a concept of a task and different runtimes have slightly different concepts of tasks.\nFrom here on in, I'm going to try to be precise about the terminology around tasks. When I use just 'task' I mean the abstract concept of a sequence of computation that may occur concurrently with other tasks. I'll use 'async task' to mean exactly the same thing, but in contrast to a task which is implemented as an OS thread. I'll use 'runtime's task' to mean whatever kind of task a runtime imagines, and 'tokio task' (or some other specific runtime) to mean Tokio's idea of a task.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Async and await", "heading_path": ["Async and Await", "Rust async concepts", "Futures and tasks"], "path": "part-guide/async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/async-await.html#futures-and-tasks", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/async-await.md#futures-and-tasks-6", "text": "Asynchronous Programming in Rust › Async and Await › Rust async concepts › Futures and tasks\n\nAn async task in Rust is just a future (usually a 'big' future made by combining many others). In other words, a task is a future which is executed. However, there are times when a future is 'executed' without being a runtime's task. This kind of a future is intuitively a *task* but not a *runtime's task*. I'll spell this out more when we get to an example of it.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Async and await", "heading_path": ["Async and Await", "Rust async concepts", "Futures and tasks"], "path": "part-guide/async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/async-await.html#futures-and-tasks", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/async-await.md#async-functions-7", "text": "Asynchronous Programming in Rust › Async and Await › Async functions\n\nThe `async` keyword is a modifier on function declarations. E.g., we can write `pub async fn send_to_server(...)`. An async function is simply a function declared using the `async` keyword, and what that means is that it is a function which can be executed asynchronously, in other words the caller *can choose not to* wait for the function to complete before doing something else.\nIn more mechanical terms, when an async function is called, the body is not executed as it would be for a regular function. Instead the function body and its arguments are packaged into a future which is returned in lieu of a real result. The caller can then decide what to do with that future (if the caller wants the result 'straight away', then it will `await` the future, see the next section).\nWithin an async function, code is executed in the usual, sequential way[^preempt], being async makes no difference. You can call synchronous functions from async functions, and execution proceeds as usual. One extra thing you can do within an async function is use `await` to await other async functions (or futures), which *may* cause yielding of control so that another task can execute.\n[^preempt]: like any other thread, the thread the async function is running on may be pre-empted by the operating system and paused so another thread can get some work done. However, from the function's point of view this is not observable without inspecting data which may have been modified by other threads (and which could have been modified by another thread executing in parallel without the current thread being paused).", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Async and await", "heading_path": ["Async and Await", "Async functions"], "path": "part-guide/async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/async-await.html#async-functions", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/async-await.md#await-8", "text": "Asynchronous Programming in Rust › Async and Await › `await`\n\nWe stated above that a future is a computation that will be ready at some point in the future. To get the result of that computation, we use the `await` keyword. If the result is ready immediately or can be computed without waiting, then `await` simply does that computation to produce the result. However, if the result is not ready, then `await` hands control over to the scheduler so that another task can proceed (this is cooperative multitasking mentioned in the previous chapter).\nIn Rust, the syntax for using await is `some_future.await`, i.e., it is a postfix keyword used with the `.` operator. That means it can be used ergonomically in chains of method calls and field accesses. This is in contrast to languages like Python or JavaScript, where `await` is a prefix operator placed before an expression, such as `await some_function()`.\nTo see why postfix await is often more ergonomic, suppose you're calling an async function that makes a network request and want to access the status code of the response. With the prefix `await` syntax, you would need to prepend `await` to `fetch()`, then wrap the expression in parentheses to propagate errors with `?`, and then access the status code, like `(await fetch())?.status_code`. In postfix syntax, you can write `fetch().await?.status_code`. This becomes especially helpful in longer chains. E.g., an expression with two prefix awaits looks like `(await (await fetch())?.json())?.data`, whereas the postfix equivalent is `fetch().await?.json().await?.data`, which reads more naturally.\nNow let's look at how `async` and `await` in practice. Consider the following functions:", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Async and await", "heading_path": ["Async and Await", "`await`"], "path": "part-guide/async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/async-await.html#await", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/async-await.md#await-9", "text": "Asynchronous Programming in Rust › Async and Await › `await`\n\n```rust,norun\n// An async function, but it doesn't need to wait for anything.\nasync fn add(a: u32, b: u32) -> u32 {\n a + b\n}\n\nasync fn wait_to_add(a: u32, b: u32) -> u32 {\n sleep(1000).await;\n a + b\n}\n```\nIf we call `add(15, 3).await` then it will return immediately with the result `18`. If we call `wait_to_add(15, 3).await`, we will eventually get the same answer, but while we wait another task will get an opportunity to run.\nIn this silly example, the call to `sleep` is a stand-in for doing some long-running task where we have to wait for the result. This is usually an IO operation where the result is data read from an external source or confirmation that writing to an external destination succeeded. Reading looks something like `let data = read(...).await?`. In this case `await` will cause the current task to wait while the read happens. The task will resume once reading is completed (other tasks could get some work done while the reading task waits). The result of reading could be data successfully read or an error (handled by the `?`).\nNote that if we call `add` or `wait_to_add` or `read` without using `.await` we won't get any answer!\nWhat?\nCalling an async function returns a future, it doesn't immediately execute the code in the function. Furthermore, a future does not do any work until it is awaited[^poll]. This is in contrast to some other languages where an async function returns a future which begins executing immediately.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Async and await", "heading_path": ["Async and Await", "`await`"], "path": "part-guide/async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/async-await.html#await", "has_code": true, "code_tags": ["rust,norun"]}} {"id": "async-book/part-guide/async-await.md#await-10", "text": "Asynchronous Programming in Rust › Async and Await › `await`\n\nThis is an important point about async programming in Rust. After a while it will be second nature, but it often trips up beginners, especially those who have experience with async programming in other languages.\nAn important intuition about futures in Rust is that they are inert objects. To get any work done they must be driven forward by an external force (usually an async runtime).\nWe've described `await` quite operationally (it runs a future, producing a result), but we talked in the previous chapter about async tasks and concurrency, how does `await` fit into that mental model? First, let's consider pure sequential code: logically, calling a function simply executes the code in the function (with some assignment of variables). In other words, the current task continues executing the next 'chunk' of code which is defined by the function. Similarly, in an async context, calling a non-async function simply continues execution with that function. Calling an async function finds the code to run, but doesn't run it. `await` is an operator which continues execution of the current task, or if the current task can't continue right now, gives another task an opportunity to continue.\n`await` can only be used inside an async context, for now that means inside an async function (we'll see more kinds of async contexts later). To understand why, remember that `await` might hand over control to the runtime so that another task can execute. There is only a runtime to hand control to in an async context. For now, you can imagine the runtime like a global variable which is only accessible in async functions, we'll explain later how it really works.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Async and await", "heading_path": ["Async and Await", "`await`"], "path": "part-guide/async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/async-await.html#await", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/async-await.md#await-11", "text": "Asynchronous Programming in Rust › Async and Await › `await`\n\nFinally, for one more perspective on `await`: we mentioned earlier that futures can be combined together to make 'bigger' futures. `async` functions are one way to define a future, and `await` is one way to combine futures. Using `await` on a future combines that future into the future produced by the async function it's used inside. We'll talk in more detail about this perspective and other ways to combine futures later.\n[^poll]: Or polled, which is a lower-level operation than `await` and happens behind the scenes when using `await`. We'll talk about polling later when we talk about futures in detail.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Async and await", "heading_path": ["Async and Await", "`await`"], "path": "part-guide/async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/async-await.html#await", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/async-await.md#some-asyncawait-examples-12", "text": "Asynchronous Programming in Rust › Async and Await › Some async/await examples\n\nLet's start by revisiting our 'hello, world!' example:\n```rust,edition2021\n// Define an async function.\nasync fn say_hello() {\n println!(\"hello, world!\");\n}\n\n#[tokio::main] // Boilerplate which lets us write `async fn main`, we'll explain it later.\nasync fn main() {\n // Call an async function and await its result.\n say_hello().await;\n}\n```\nYou should now recognise the boilerplate around `main`. It's for initializing the Tokio runtime and creating an initial task to run the async `main` function.\n`say_hello` is an async function, when we call it, we have to follow the call with `.await` to run it as part of the current task. Note that if you remove the `.await`, then running the program does nothing! Calling `say_hello` returns a future, but it is never executed so `println` is never called (the compiler will warn you, at least).\nHere's a slightly more realistic example, taken from the Tokio tutorial.\n```rust,norun\n#[tokio::main]\nasync fn main() -> Result<()> {\n // Open a connection to the mini-redis address.\n let mut client = client::connect(\"127.0.0.1:6379\").await?;\n\n // Set the key \"hello\" with value \"world\"\n client.set(\"hello\", \"world\".into()).await?;\n\n // Get key \"hello\"\n let result = client.get(\"hello\").await?;\n\n println!(\"got value from the server; result={:?}\", result);\n\n Ok(())\n}\n```", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Async and await", "heading_path": ["Async and Await", "Some async/await examples"], "path": "part-guide/async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/async-await.html#some-asyncawait-examples", "has_code": true, "code_tags": ["rust,edition2021", "rust,norun"]}} {"id": "async-book/part-guide/async-await.md#some-asyncawait-examples-13", "text": "Asynchronous Programming in Rust › Async and Await › Some async/await examples\n\nThe code is a bit more interesting, but we're essentially doing the same thing - calling async functions and then awaiting to execute the result. This time we're using `?` for error handling - it works just like in synchronous Rust.\nFor all the talk so far about concurrency, parallelism, and asynchrony, both these examples are 100% sequential. Just calling and awaiting async functions does not introduce any concurrency unless there are other tasks to schedule while the awaiting task is waiting. To prove this to ourselves, lets look at another simple (but contrived) example:\n```rust,edition2021\nuse std::io::{stdout, Write};\nuse tokio::time::{sleep, Duration};\n\nasync fn say_hello() {\n print!(\"hello, \");\n // Flush stdout so we see the effect of the above `print` immediately.\n stdout().flush().unwrap();\n}\n\nasync fn say_world() {\n println!(\"world!\");\n}\n\n#[tokio::main]\nasync fn main() {\n say_hello().await;\n // An async sleep function, puts the current task to sleep for 1s.\n sleep(Duration::from_millis(1000)).await;\n say_world().await;\n}\n```\nBetween printing \"hello\" and \"world\", we put the current task to sleep[^async-sleep] for one second. Observe what happens when we run the program: it prints \"hello\", does nothing for one second, then prints \"world\". That is because executing a single task is purely sequential. If we had some concurrency, then that one second nap would be an excellent opportunity to get some other work done, like printing \"world\". We'll see how to do that in the next section.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Async and await", "heading_path": ["Async and Await", "Some async/await examples"], "path": "part-guide/async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/async-await.html#some-asyncawait-examples", "has_code": true, "code_tags": ["rust,edition2021"]}} {"id": "async-book/part-guide/async-await.md#some-asyncawait-examples-14", "text": "Asynchronous Programming in Rust › Async and Await › Some async/await examples\n\n[^async-sleep]: Note that we're using an async sleep function here, if we were to use `sleep` from std we'd put the whole thread to sleep. That wouldn't make any difference in this toy example but in a real program it would mean other tasks could not be scheduled on that thread during that time. That is very bad.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Async and await", "heading_path": ["Async and Await", "Some async/await examples"], "path": "part-guide/async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/async-await.html#some-asyncawait-examples", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/async-await.md#spawning-tasks-15", "text": "Asynchronous Programming in Rust › Async and Await › Spawning tasks\n\nWe've talked about async and await as a way to run code in an async task. And we've said that `await` can put the current task to sleep while it waits for IO or some other event. When that happens, another task can run, but how do those other tasks come about? Just like we use `std::thread::spawn` to spawn a new task, we can use `tokio::spawn` to spawn a new async task. Note that `spawn` is a function of Tokio, the runtime, not from Rust's standard library, because tasks are purely a runtime concept.\nHere's a tiny example of running an async function on a separate task by using `spawn`:\n```rust,edition2021\nuse tokio::{spawn, time::{sleep, Duration}};\n\nasync fn say_hello() {\n // Wait for a while before printing to make it a more interesting race.\n sleep(Duration::from_millis(100)).await;\n println!(\"hello\");\n}\n\nasync fn say_world() {\n sleep(Duration::from_millis(100)).await;\n println!(\"world!\");\n}\n\n#[tokio::main]\nasync fn main() {\n spawn(say_hello());\n spawn(say_world());\n // Wait for a while to give the tasks time to run.\n sleep(Duration::from_millis(1000)).await;\n}\n```\nSimilar to the last example, we have two functions printing \"hello\" and \"world!\". But this time we run them concurrently (and in parallel) rather than sequentially. If you run the program a few times you should see the strings printing in both orders - sometimes \"hello\" first, sometimes \"world!\" first. A classic concurrent race!", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Async and await", "heading_path": ["Async and Await", "Spawning tasks"], "path": "part-guide/async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/async-await.html#spawning-tasks", "has_code": true, "code_tags": ["rust,edition2021"]}} {"id": "async-book/part-guide/async-await.md#spawning-tasks-16", "text": "Asynchronous Programming in Rust › Async and Await › Spawning tasks\n\nLet's dive into what is happening here. There are three concepts in play: futures, tasks, and threads. The `spawn` function takes a future (which remember can be made up of many smaller futures) and runs it as a new Tokio task. Tasks are the concept which the Tokio runtime schedules and manages (not individual futures). Tokio (in its default configuration) is a multi-threaded runtime which means that when we spawn a new task, that task may be run on a different OS thread from the task it was spawned from (it may be run on the same thread, or it may start on one thread and then be moved to another later on).\nSo, when a future is spawned as a task it runs *concurrently* with the task it was spawned from and any other tasks. It may also run in parallel to those tasks if it is scheduled on a different thread.\nTo summarise, when we write two statements following each other in Rust, they are executed sequentially (whether in async code or not). When we write `await`, that does not change the concurrency of sequential statements. E.g., `foo(); bar();` is strictly sequential - `foo` is called and afterwards, `bar` is called. That is true whether `foo` and `bar` are async functions or not. `foo().await; bar().await;` is also strictly sequential, `foo` is fully evaluated and then `bar` is fully evaluated. In both cases another thread might be interleaved with the sequential execution and in the second case, another async task might be interleaved at the await points, but the two statements are executed sequentially *with respect to each other* in both cases.\nIf we use either `thread::spawn` or `tokio::spawn` we introduce concurrency and potentially parallelism, in the first case between threads and in the second between tasks.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Async and await", "heading_path": ["Async and Await", "Spawning tasks"], "path": "part-guide/async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/async-await.html#spawning-tasks", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/async-await.md#spawning-tasks-17", "text": "Asynchronous Programming in Rust › Async and Await › Spawning tasks\n\nLater in the guide we'll see cases where we execute futures concurrently, but never in parallel.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Async and await", "heading_path": ["Async and Await", "Spawning tasks"], "path": "part-guide/async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/async-await.html#spawning-tasks", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/async-await.md#joining-tasks-18", "text": "Asynchronous Programming in Rust › Async and Await › Spawning tasks › Joining tasks\n\nIf we want to get the result of executing a spawned task, then the spawning task can wait for it to finish and use the result, this is called *joining* the tasks (analogous to joining threads, and the APIs for joining are similar).\nWhen a task is spawned, the spawn function returns a `JoinHandle`. If you just want the task to do it's own thing executing, the `JoinHandle` can be discarded (dropping the `JoinHandle` does not affect the spawned task). But if you want the spawning task to wait for the spawned task to complete and then use the result, you can `await` the `JoinHandle` to do so.\nFor example, let's revisit our 'Hello, world!' example one more time:\n```rust,edition2021\nuse tokio::{spawn, time::{sleep, Duration}};\n\nasync fn say_hello() {\n // Wait for a while before printing to make it a more interesting race.\n sleep(Duration::from_millis(100)).await;\n println!(\"hello\");\n}\n\nasync fn say_world() {\n sleep(Duration::from_millis(100)).await;\n println!(\"world\");\n}\n\n#[tokio::main]\nasync fn main() {\n let handle1 = spawn(say_hello());\n let handle2 = spawn(say_world());\n \n let _ = handle1.await;\n let _ = handle2.await;\n\n println!(\"!\");\n}\n```\nThe code is similar to last time, but instead of just calling `spawn`, we save the returned `JoinHandle`s and later `await` them. Since we're waiting for those tasks to complete before we exit the `main` function, we no longer need the `sleep` in `main`.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Async and await", "heading_path": ["Async and Await", "Spawning tasks", "Joining tasks"], "path": "part-guide/async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/async-await.html#joining-tasks", "has_code": true, "code_tags": ["rust,edition2021"]}} {"id": "async-book/part-guide/async-await.md#joining-tasks-19", "text": "Asynchronous Programming in Rust › Async and Await › Spawning tasks › Joining tasks\n\nThe two spawned tasks are still executing concurrently. If you run the program a few times you should see both orderings. However, the `await`ed join handles are a limit on the concurrency: the final exclamation mark ('!') will *always* be printed last (you could experiment with moving `println!(\"!\");` relative to the `await`s. You'll probably need to change with the sleep times too to get observable effects).\nIf we immediately `await`ed the `JoinHandle` of the first `spawn` rather than saved it and later `await`ed (i.e., written `spawn(say_hello()).await;`), then we'd have spawned another task to run the 'hello' future, but the spawning task would have waited for it to finish before doing anything else. In other words, there is no possible concurrency! You almost never want to do this (because why bother with the spawn? Just write the sequential code).", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Async and await", "heading_path": ["Async and Await", "Spawning tasks", "Joining tasks"], "path": "part-guide/async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/async-await.html#joining-tasks", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/async-await.md#joinhandle-20", "text": "Asynchronous Programming in Rust › Async and Await › Spawning tasks › `JoinHandle`\n\nWe'll quickly look at `JoinHandle` in a little more depth. The fact that we can `await` a `JoinHandle` is a clue that a `JoinHandle` is itself a future. `spawn` is not an `async` function, it's a regular function that returns a future (`JoinHandle`). It does some work (to schedule the task) before returning the future (unlike an async future), which is why we don't *need* to `await` `spawn`. Awaiting a `JoinHandle` waits for the spawned task to complete and then returns the result. In the above example, there was no result, we just waited for the task to complete. `JoinHandle` is a generic type and it's type parameter is the type returned by the spawned task. In the above example, the type would be `JoinHandle<()>`, a future that results in a `String` would produce a `JoinHandle` with type `JoinHandle`.\n`await`ing a `JoinHandle` returns a `Result` (which is why we used `let _ = ...` in the above example, it avoids a warning about an unused `Result`). If the spawned task completed successfully, then the task's result will be in the `Ok` variant. If the task panicked or was aborted (a form of cancellation), then the result will be an `Err` containing a `JoinError` docs. If you are not using cancellation via `abort` in your project, then `unwrapping` the result of `JoinHandle.await` is a reasonable approach, since that is effectively propagating a panic from the spawned task to the spawning task.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Async and await", "heading_path": ["Async and Await", "Spawning tasks", "`JoinHandle`"], "path": "part-guide/async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/async-await.html#joinhandle", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/more-async-await.md#unit-tests-0", "text": "Asynchronous Programming in Rust › More async/await topics › Unit tests\n\nHow to unit test async code? The issue is that you can only await from inside an async context, and unit tests in Rust are not async. Luckily, most runtimes provide a convenience attribute for tests similar to the one for `async main`. Using Tokio, it looks like this:\n```rust,norun\n#[tokio::test]\nasync fn test_something() {\n // Write a test here, including all the `await`s you like.\n}\n```\nThere are many ways to configure the test, see the docs for details.\nThere are some more advanced topics in testing async code (e.g., testing for race conditions, deadlock, etc.), and we'll cover some of those later in this guide.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "More async/await topics", "heading_path": ["More async/await topics", "Unit tests"], "path": "part-guide/more-async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/more-async-await.html#unit-tests", "has_code": true, "code_tags": ["rust,norun"]}} {"id": "async-book/part-guide/more-async-await.md#blocking-and-cancellation-1", "text": "Asynchronous Programming in Rust › More async/await topics › Blocking and cancellation\n\nBlocking and cancellation are important to keep in mind when programming with async Rust. These concepts are not localised to any particular feature or function, but are ubiquitous properties of the system which you must understand to write correct code.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "More async/await topics", "heading_path": ["More async/await topics", "Blocking and cancellation"], "path": "part-guide/more-async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/more-async-await.html#blocking-and-cancellation", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/more-async-await.md#blocking-io-2", "text": "Asynchronous Programming in Rust › More async/await topics › Blocking and cancellation › Blocking IO\n\nWe say a thread (note we're talking about OS threads here, not async tasks) is blocked when it can't make any progress. That's usually because it is waiting for the OS to complete a task on its behalf (usually I/O). Importantly, while a thread is blocked, the OS knows not to schedule it so that other threads can make progress. This is fine in a multithreaded program because it lets other threads make progress while the blocked thread is waiting. However, in an async program, there are other tasks which should be scheduled on the same OS thread, but the OS doesn't know about those and keeps the whole thread waiting. This means that rather than the single task waiting for its I/O to complete (which is fine), many tasks have to wait (which is not fine).\nWe’ll talk soon about non-blocking/async I/O. For now, just know that non-blocking I/O is I/O that the async runtime is aware of, so only the current task waits; the thread itself is not blocked. It is very important to only use non-blocking I/O from an async task, never blocking I/O (which is the only kind provided in Rust's standard library).", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "More async/await topics", "heading_path": ["More async/await topics", "Blocking and cancellation", "Blocking IO"], "path": "part-guide/more-async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/more-async-await.html#blocking-io", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/more-async-await.md#blocking-computation-3", "text": "Asynchronous Programming in Rust › More async/await topics › Blocking and cancellation › Blocking computation\n\nYou can also block the thread by doing computation (this is not quite the same as blocking I/O, since the OS is not involved, but the effect is similar). If you have a long-running computation (with or without blocking I/O) without yielding control to the runtime, then that task will never give the runtime's scheduler a chance to schedule other tasks. Remember that async programming uses cooperative multitasking. Here a task is not cooperating, so other tasks won't get a chance to get work done. We'll discuss ways to mitigate this later.\nThere are many other ways to block a whole thread, and we'll come back to blocking several times in this guide.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "More async/await topics", "heading_path": ["More async/await topics", "Blocking and cancellation", "Blocking computation"], "path": "part-guide/more-async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/more-async-await.html#blocking-computation", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/more-async-await.md#cancellation-4", "text": "Asynchronous Programming in Rust › More async/await topics › Blocking and cancellation › Cancellation\n\nCancellation means stopping a future (or task) from executing. Since in Rust (and in contrast to many other async/await systems), futures must be driven forward by an external force (like the async runtime), if a future is no longer driven forward then it will not execute any more. If a future is dropped (remember, a future is just a plain old Rust object), then it can never make any more progress and is canceled.\nCancellation can be initiated in a few ways:\n- By simply dropping a future (if you own it).\n- Calling `abort` on a task's 'JoinHandle' (or an `AbortHandle`).\n- Via a `CancellationToken` (which requires the future being canceled to notice the token and cooperatively cancel itself).\n- Implicitly, by a function or macro like `select`.\nThe middle two are specific to Tokio, though most runtimes provide similar facilities. Using a `CancellationToken` requires cooperation of the future being canceled, but the others do not. In these other cases, the canceled future will get no notification of cancellation and no opportunity to clean up (besides its destructor). Note that even if a future has a cancellation token, it can still be canceled via the other methods which won't trigger the cancellation token.\nFrom the perspective of writing async code (in async functions, blocks, futures, etc.), the code might stop executing at any `await` (including hidden ones in macros) and never start again. In order for your code to be correct (specifically to be *cancellation safe*), it must work correctly whether it completes normally or whether it terminates at any await point[^cfThreads].", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "More async/await topics", "heading_path": ["More async/await topics", "Blocking and cancellation", "Cancellation"], "path": "part-guide/more-async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/more-async-await.html#cancellation", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/more-async-await.md#cancellation-5", "text": "Asynchronous Programming in Rust › More async/await topics › Blocking and cancellation › Cancellation\n\n```rust,norun\nasync fn some_function(input: Option) {\n let Some(input) = input else {\n return; // Might terminate here (`return`).\n };\n\n let x = foo(input)?; // Might terminate here (`?`).\n\n let y = bar(x).await; // Might terminate here (`await`).\n\n // ...\n\n // Might terminate here (implicit return).\n}\n```\nAn example of how this can go wrong is if an async function reads data into an internal buffer, then awaits the next datum. If reading the data is destructive (i.e., cannot be re-read from the original source) and the async function is canceled, then the internal buffer will be dropped, and the data in it will be lost. It is important to consider how a future and any data it touches will be impacted by canceling the future, restarting the future, or starting a new future which touches the same data.\nWe'll be coming back to cancellation and cancellation safety a few times in this guide, and there is a whole chapter on the topic in the reference section.\n[^cfThreads]: It is interesting to compare cancellation in async programming with canceling threads. Canceling a thread is possible (e.g., using `pthread_cancel` in C, there is no direct way to do this in Rust), but it is almost always a very, very bad idea since the thread being canceled can terminate anywhere. In contrast, canceling an async task can only happen at an await point. As a consequence, it is very rare to cancel an OS thread without terminating the whole process and so as a programmer, you generally don't worry about this happening. In async Rust however, cancellation is definitely something which *can* happen. We'll be discussing how to deal with that as we go along.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "More async/await topics", "heading_path": ["More async/await topics", "Blocking and cancellation", "Cancellation"], "path": "part-guide/more-async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/more-async-await.html#cancellation", "has_code": true, "code_tags": ["rust,norun"]}} {"id": "async-book/part-guide/more-async-await.md#async-blocks-6", "text": "Asynchronous Programming in Rust › More async/await topics › Async blocks\n\nA regular block (`{ ... }`) groups code together in the source and creates a scope of encapsulation for names. At runtime, the block is executed in order and evaluates to the value of its last expression (or the unit type (`()`) if there is no trailing expression).\nSimilarly to async functions, an async block is a deferred version of a regular block. An async block scopes code and names together, but at runtime it is not immediately executed and evaluates to a future. To execute the block and obtain the result, it must be `await`ed. E.g.:\n```rust,norun\nlet s1 = {\n let a = 42;\n format!(\"The answer is {a}\")\n};\n\nlet s2 = async {\n let q = question().await;\n format!(\"The question is {q}\")\n};\n```\nIf we were to execute this snippet, `s1` would be a string which could be printed, but `s2` would be a future; `question()` would not have been called. To print `s2`, we first have to `s2.await`.\nAn async block is the simplest way to start an async context and create a future. It is commonly used to create small futures which are only used in one place.\nUnfortunately, control flow with async blocks is a little quirky. Because an async block creates a future rather than straightforwardly executing, it behaves more like a function than a regular block with respect to control flow. `break` and `continue` cannot go 'through' an async block like they can with regular blocks; instead you have to use `return`:", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "More async/await topics", "heading_path": ["More async/await topics", "Async blocks"], "path": "part-guide/more-async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/more-async-await.html#async-blocks", "has_code": true, "code_tags": ["rust,norun"]}} {"id": "async-book/part-guide/more-async-await.md#async-blocks-7", "text": "Asynchronous Programming in Rust › More async/await topics › Async blocks\n\n```rust,norun\nloop {\n {\n if ... {\n // ok\n continue;\n }\n }\n\n async {\n if ... {\n // not ok\n // continue;\n\n // ok - continues with the next execution of the `loop`, though note that if there was\n // code in the loop after the async block that would be executed.\n return;\n }\n }.await\n}\n```\nTo implement `break` you would need to test the value of the block (a common idiom is to use `ControlFlow` for the value of the block, which also allows use of `?`).\nLikewise, `?` inside an async block will terminate execution of the future in the presence of an error, causing the `await`ed block to take the value of the error, but won't exit the surrounding function (like `?` in a regular block would). You'll need another `?` after `await` for that:\n```rust,norun\nasync {\n let x = foo()?; // This `?` only exits the async block, not the surrounding function.\n consume(x);\n Ok(())\n}.await?\n```\nAnnoyingly, this often confuses the compiler since (unlike functions) the 'return' type of an async block is not explicitly stated. You'll probably need to add some type annotations on variables or use turbofished types to make this work, e.g., `Ok::<_, MyError>(())` instead of `Ok(())` in the above example.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "More async/await topics", "heading_path": ["More async/await topics", "Async blocks"], "path": "part-guide/more-async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/more-async-await.html#async-blocks", "has_code": true, "code_tags": ["rust,norun"]}} {"id": "async-book/part-guide/more-async-await.md#async-blocks-8", "text": "Asynchronous Programming in Rust › More async/await topics › Async blocks\n\nA function which returns an async block is pretty similar to an async function. Writing `async fn foo() -> ... { ... }` is roughly equivalent to `fn foo() -> ... { async { ... } }`. In fact, from the caller's perspective they are equivalent, and changing from one form to the other is not a breaking change. Furthermore, you can override one with the other when implementing an async trait (see below). However, you do have to adjust the type, making the `Future` explicit in the async block version: `async fn foo() -> Foo` becomes `fn foo() -> impl Future` (you might also need to make other bounds explicit, e.g., `Send` and `'static`).\nYou would usually prefer the async function version since it is simpler and clearer. However, the async block version is more flexible since you can execute some code when the function is called (by writing it outside the async block) and some code when the result is awaited (the code inside the async block).", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "More async/await topics", "heading_path": ["More async/await topics", "Async blocks"], "path": "part-guide/more-async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/more-async-await.html#async-blocks", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/more-async-await.md#async-closures-9", "text": "Asynchronous Programming in Rust › More async/await topics › Async closures\n\n- closures\n - coming soon (https://github.com/rust-lang/rust/pull/132706, https://blog.rust-lang.org/inside-rust/2024/08/09/async-closures-call-for-testing.html)\n - async blocks in closures vs async closures", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "More async/await topics", "heading_path": ["More async/await topics", "Async closures"], "path": "part-guide/more-async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/more-async-await.html#async-closures", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/more-async-await.md#lifetimes-and-borrowing-10", "text": "Asynchronous Programming in Rust › More async/await topics › Lifetimes and borrowing\n\n- Mentioned the static lifetime above\n- Lifetime bounds on futures (`Future + '_`, etc.)\n- Borrowing across await points\n- I don't know, I'm sure there are more lifetime issues with async functions ...", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "More async/await topics", "heading_path": ["More async/await topics", "Lifetimes and borrowing"], "path": "part-guide/more-async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/more-async-await.html#lifetimes-and-borrowing", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/more-async-await.md#send--static-bounds-on-futures-11", "text": "Asynchronous Programming in Rust › More async/await topics › `Send + 'static` bounds on futures\n\n- Why they're there, multi-threaded runtimes\n- spawn local to avoid them\n- What makes an async fn `Send + 'static` and how to fix bugs with it", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "More async/await topics", "heading_path": ["More async/await topics", "`Send + 'static` bounds on futures"], "path": "part-guide/more-async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/more-async-await.html#send--static-bounds-on-futures", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/more-async-await.md#async-traits-12", "text": "Asynchronous Programming in Rust › More async/await topics › Async traits\n\n- syntax\n - The `Send + 'static` issue and working around it\n - trait_variant\n - explicit future\n - return type notation (https://blog.rust-lang.org/inside-rust/2024/09/26/rtn-call-for-testing.html)\n- overriding\n - future vs async notation for methods\n- object safety\n- capture rules (https://blog.rust-lang.org/2024/09/05/impl-trait-capture-rules.html)\n- history and async-trait crate", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "More async/await topics", "heading_path": ["More async/await topics", "Async traits"], "path": "part-guide/more-async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/more-async-await.html#async-traits", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/more-async-await.md#recursion-13", "text": "Asynchronous Programming in Rust › More async/await topics › Recursion\n\n- Allowed (relatively new), but requires some explicit boxing\n - forward reference to futures, pinning\n - https://rust-lang.github.io/async-book/07_workarounds/04_recursion.html\n - https://blog.rust-lang.org/2024/03/21/Rust-1.77.0.html#support-for-recursion-in-async-fn\n - async-recursion macro (https://docs.rs/async-recursion/latest/async_recursion/)", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "More async/await topics", "heading_path": ["More async/await topics", "Recursion"], "path": "part-guide/more-async-await.md", "url": "https://rust-lang.github.io/async-book/part-guide/more-async-await.html#recursion", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/io.md#io-and-issues-with-blocking-0", "text": "Asynchronous Programming in Rust › IO and issues with blocking\n\nEfficiently handling IO (input/output) is one of the primary motivators for async programming and most async programs do lots of IO. At it's root, the issue with IO is that it takes orders of magnitude more time than computation, therefore just waiting for IO to complete rather than getting on with other work is incredibly inefficient. Ideally, async programming lets a program get on with other work while waiting for IO.\nThis chapter is an introduction to IO in the async context. We'll cover the important difference between blocking and non-blocking IO, and why blocking IO and async programming don't mix (at least not without a bit of thought and effort). We'll cover how to use non-blocking IO, then look at some of the issues which can crop up with IO and async programming. We'll also look at how the OS handles IO and have a sneak peek at some alternative IO methods like io_uring.\nWe'll finish by covering some other ways of blocking an async task (which is bad) and how to properly mix async programming with blocking IO or long-running, CPU-intensive code.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "IO and issues with blocking", "heading_path": ["IO and issues with blocking"], "path": "part-guide/io.md", "url": "https://rust-lang.github.io/async-book/part-guide/io.html#io-and-issues-with-blocking", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/io.md#blocking-and-non-blocking-io-1", "text": "Asynchronous Programming in Rust › IO and issues with blocking › Blocking and non-blocking IO\n\nIO is implemented by the operating system; the work of IO takes place in separate processes and/or in dedicated hardware, in either case outside of the program's process. IO can be either synchronous or asynchronous (aka blocking and non-blocking, respectively). Synchronous IO means that the program (or at least the thread) waits (aka blocks) while the IO takes place and doesn't start processing until the IO is complete and the result is received from the OS. Asynchronous IO means that the program can continue to make progress while the IO takes place and can pick up the result later. There are many different OS APIs for both kinds of IO, though more variety in the asynchronous space.\nAsynchronous IO and asynchronous programming are not intrinsically linked. However, async programming facilitates ergonomic and performant async IO, and that is a major motivation for async programming. Blocking due to synchronous IO is a major source of performance issues with async programming, and we must be careful to avoid it (more on this below).\nRust's standard library includes functions and traits for blocking IO. For non-blocking IO, you must use specialized libraries, which are often part of the async runtime, e.g., Tokio's `io` module.\nLet's quickly look at an example (adapted from the Tokio docs):\n```rust\nuse tokio::{io::AsyncWriteExt, net::TcpStream};\n\nasync fn write_hello() -> Result<(), Box> {\n let mut stream = TcpStream::connect(\"127.0.0.1:8080\").await?;\n stream.write_all(b\"hello world!\").await?;\n\n Ok(())\n}\n```", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "IO and issues with blocking", "heading_path": ["IO and issues with blocking", "Blocking and non-blocking IO"], "path": "part-guide/io.md", "url": "https://rust-lang.github.io/async-book/part-guide/io.html#blocking-and-non-blocking-io", "has_code": true, "code_tags": ["rust"]}} {"id": "async-book/part-guide/io.md#blocking-and-non-blocking-io-2", "text": "Asynchronous Programming in Rust › IO and issues with blocking › Blocking and non-blocking IO\n\n`write_all` is an async IO method which writes data to `stream`. This might complete immediately, but more likely this will take some time to complete, so `stream.write_all(...).await` will cause the current task to be paused while it waits for the OS to handle the write. The scheduler will run other tasks and when the write is complete, it will wake up the task and schedule it to continue working.\nHowever, if we used a write function from the standard library, the async scheduler would not be involved and the OS would pause the whole thread while the IO completes, meaning that not only is the current task paused but no other task can be executed using that thread. If this happens to all threads in the runtime's thread pool (which in some circumstances can be just one thread), then the whole program stops and cannot make progress. This is called blocking the thread (or program) and is very bad for performance. It is important to never block threads in an async program, and thus you should avoid using blocking IO in an async task.\nBlocking a thread can be caused by long-running tasks or tasks waiting for locks, as well as by blocking IO. We'll discuss this more at the end of this chapter.\nIt is a common pattern to repeatedly read or write, and streams and sinks (aka async iterators) are a convenient mechanism for doing so. They're covered in a dedicated chapter.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "IO and issues with blocking", "heading_path": ["IO and issues with blocking", "Blocking and non-blocking IO"], "path": "part-guide/io.md", "url": "https://rust-lang.github.io/async-book/part-guide/io.html#blocking-and-non-blocking-io", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/io.md#reading-and-writing-3", "text": "Asynchronous Programming in Rust › IO and issues with blocking › Reading and writing\n\nTODO\n- async Read and Write traits\n - part of the runtime\n- how to use\n- specific implementations\n - network vs disk\n - tcp, udp\n - file system is not really async, but io_uring (ref to that chapter)\n - practical examples\n - stdout, etc.\n - pipe, fd, etc.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "IO and issues with blocking", "heading_path": ["IO and issues with blocking", "Reading and writing"], "path": "part-guide/io.md", "url": "https://rust-lang.github.io/async-book/part-guide/io.html#reading-and-writing", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/io.md#memory-management-4", "text": "Asynchronous Programming in Rust › IO and issues with blocking › Memory management\n\nWhen we read data we need to put it somewhere and when we write data it needs to be kept somewhere until the write completes. In either case, how that memory is mangaged is important.\nTODO\n- Issues with buffer management and async IO\n- Different solutions and pros and cons\n - zero-copy approach\n - shared buffer approach\n- Utility crates to help with this, Bytes, etc.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "IO and issues with blocking", "heading_path": ["IO and issues with blocking", "Memory management"], "path": "part-guide/io.md", "url": "https://rust-lang.github.io/async-book/part-guide/io.html#memory-management", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/io.md#advanced-topics-on-io-5", "text": "Asynchronous Programming in Rust › IO and issues with blocking › Advanced topics on IO\n\nTODO\n- buf read/write\n- Read + Write, split, join\n- copy\n- simplex and duplex\n- cancelation\n- what if we have to do sync IO? Spawn a thread or use spawn_blocking (see below)", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "IO and issues with blocking", "heading_path": ["IO and issues with blocking", "Advanced topics on IO"], "path": "part-guide/io.md", "url": "https://rust-lang.github.io/async-book/part-guide/io.html#advanced-topics-on-io", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/io.md#the-os-view-of-io-6", "text": "Asynchronous Programming in Rust › IO and issues with blocking › The OS view of IO\n\nTODO\n- Different kinds of IO and mechanisms, completion IO, reference to completion IO chapter in adv section\n - different runtimes can faciliate this\n - mio for low-level interface", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "IO and issues with blocking", "heading_path": ["IO and issues with blocking", "The OS view of IO"], "path": "part-guide/io.md", "url": "https://rust-lang.github.io/async-book/part-guide/io.html#the-os-view-of-io", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/io.md#other-blocking-operations-7", "text": "Asynchronous Programming in Rust › IO and issues with blocking › Other blocking operations\n\nAs mentioned at the start of the chapter, not blocking threads is crucial for the performance of async programs. Blocking IO of different kinds is a common way to block, but it is also possible to block by doing lots of computation or waiting in a way which the async scheduler isn't coordinating.\nWaiting is most often caused by using non-async aware synchronisation mechanisms, for example, using `std::sync::Mutex` rather than an async mutex, or waiting for a non-async channel. We'll discuss this issue in the chapter on Channels, locking, and synchronization. There are other ways that you might wait in a blocking way, and in general you need to find a non-blocking or otherwise async-friendly mechanism, e.g., using an async `sleep` function rather than the std one. Waiting could also be a busy wait (effectively just looping without doing any work, aka a spin lock), you should probably just avoid that.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "IO and issues with blocking", "heading_path": ["IO and issues with blocking", "Other blocking operations"], "path": "part-guide/io.md", "url": "https://rust-lang.github.io/async-book/part-guide/io.html#other-blocking-operations", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/io.md#cpu-intensive-work-8", "text": "Asynchronous Programming in Rust › IO and issues with blocking › Other blocking operations › CPU-intensive work\n\nDoing long-running (i.e., cpu-intensive or cpu-bound) work will prevent the scheduler from running other tasks. This *is* a kind of blocking, but it is not as bad as blocking on IO or waiting because at least your program is making some progress. However (without care and consideration), it is likely to be sub-optimal for performance by some measure (e.g., tail latency) and perhaps a correctness issue if the tasks that can't run needed to be run at a particular time. There is a meme that you should simply not use async Rust (or general purpose async runtimes like Tokio) for CPU-intensive work, but that is an over-simplification. What is correct is that you cannot mix IO- and CPU-bound (or more precisely, long-running and latency-sensitive) tasks without some special handling and expect to have a good time.\nFor the rest of this section, we'll assume you have a mix of latency-sensitive tasks and long-running, CPU-intensive tasks. If you don't have anything which is latency-sensitive, then things are a bit different (mostly easier).\nThere are essentially three solutions for running long-running or blocking tasks: use a runtime's built-in facilities, use a separate thread, or use a separate runtime.\nIn Tokio, you can use `spawn_blocking` to spawn a task which might block. This works like `spawn` for spawning a task, but runs the task in a separate thread pool which is optimized for tasks which might block (the task will likely run on it's own thread). Note that this runs regular synchronous code, not an async task. That means that the task can't be cancelled (even though its `JoinHandle` has an `abort` method). Other runtimes provide similar functionality.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "IO and issues with blocking", "heading_path": ["IO and issues with blocking", "Other blocking operations", "CPU-intensive work"], "path": "part-guide/io.md", "url": "https://rust-lang.github.io/async-book/part-guide/io.html#cpu-intensive-work", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/io.md#cpu-intensive-work-9", "text": "Asynchronous Programming in Rust › IO and issues with blocking › Other blocking operations › CPU-intensive work\n\nThis example uses `spawn_blocking` to perform blocking I/O by calling a synchronous filesystem function from the standard library. Note that `tokio::fs` also exists and provides asynchronous filesystem APIs; however, under the hood it too uses blocking operations wrapped in `spawn_blocking`.\n```rust,norun\nuse tokio;\n\n#[tokio::main]\nasync fn main() {\n let contents = tokio::task::spawn_blocking(|| {\n\t\tstd::fs::read_to_string(\"file.txt\").unwrap()\n })\n\t.await\n\t.unwrap();\n\n\t// do something with contents\n}\n```\nBecause tasks spawned with `spawn_blocking` cannot be aborted, it is intended for work that eventually completes. Tasks that may block indefinitely, such as a server listening for incoming requests, are better run on a dedicated thread so they do not occupy a thread from Tokio's blocking thread pool for an extended period. You can create one with `std::thread::spawn` or a similar API.\nIf you need to run a lot of tasks, you'll probably need some kind of thread pool or work scheduler. If you keep spawning threads and have many more than there are cores available, you'll end up sacrificing throughput. Rayon is a popular choice which makes it easy to run and manage parallel tasks. You might get better performance with something which is more specific to your workload and/or has some knowledge of the tasks being run.\nHere is an example of using Rayon together with Tokio. It utilizes `tokio::oneshot::channel` to communicate results between a task spawned by Rayon and the current task in Tokio.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "IO and issues with blocking", "heading_path": ["IO and issues with blocking", "Other blocking operations", "CPU-intensive work"], "path": "part-guide/io.md", "url": "https://rust-lang.github.io/async-book/part-guide/io.html#cpu-intensive-work", "has_code": true, "code_tags": ["rust,norun"]}} {"id": "async-book/part-guide/io.md#cpu-intensive-work-10", "text": "Asynchronous Programming in Rust › IO and issues with blocking › Other blocking operations › CPU-intensive work\n\n```rust,norun\nuse rayon::prelude::*;\n\n#[tokio::main]\nasync fn main() {\n let data = 1..=10;\n\n let (send, recv) = tokio::sync::oneshot::channel();\n // Spawn a task on rayon to avoid blocking the current task\n std::thread::spawn(move || {\n // Use rayon's parallel iterators to compute the results in parallel\n let results = data.into_par_iter().map(compute).collect::>();\n // Send the result back to Tokio.\n send.send(results).unwrap();\n });\n\n // Wait for the rayon task and get the results\n let results = recv.await.unwrap();\n println!(\"Results: {:?}\", results);\n}\n\nfn compute(input: u64) -> u64 {\n // Simulate a CPU-intensive computation by\n // summing up a large number of integers.\n let mut sum = 0u64;\n for i in 0..100_000_000 {\n sum = sum.wrapping_add(i * i);\n }\n sum % input\n}\n```\nYou can use a separate instance of the async runtime for latency-sensitive tasks and for long-running tasks. This is suitable for CPU-bound tasks, but you still shouldn't use blocking IO, even on the runtime for long-running tasks. For CPU-bound tasks, this is a good solution in that it is the only one which supports the long-running tasks be async tasks. It is also flexible (since the runtimes can be configured to be optimal for the kind of task they're running; indeed, it is necessary to put some effort into runtime configuration to get optimal performance) and lets you benefit from using mature, well-engineered sub-systems like Tokio. You can even use two different async runtimes. In any case, the runtimes must be run on different threads.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "IO and issues with blocking", "heading_path": ["IO and issues with blocking", "Other blocking operations", "CPU-intensive work"], "path": "part-guide/io.md", "url": "https://rust-lang.github.io/async-book/part-guide/io.html#cpu-intensive-work", "has_code": true, "code_tags": ["rust,norun"]}} {"id": "async-book/part-guide/io.md#cpu-intensive-work-11", "text": "Asynchronous Programming in Rust › IO and issues with blocking › Other blocking operations › CPU-intensive work\n\nOn the other hand, you do need to do a bit more thinking: you must ensure that you are running tasks on the right runtime (which can be harder than it sounds) and communication between tasks can be complicated. We'll discuss synchronisation between sync and async contexts next, but it can be even trickier between multiple async runtimes. Each runtime is it's own little universe of tasks and the schedulers are totally independent. Tokio channels and locks *can* be used from different runtimes (even non-Tokio ones), but other runtimes' primitives may not work in this way.\nSince the scheduler in each runtime is oblivious of other runtimes (and the OS is oblivious to any async schedulers), there is no coordination or shared prioritisation of scheduling and work cannot be stolen between runtimes. Therefore, scheduling of tasks can be sub-optimal (especially if the runtimes are not well-tuned to their workloads). Furthermore, since all scheduling is cooperative, long-running tasks can still be starved of resources and latency can suffer. See the next section for how long-running tasks can be made to be more cooperative.\nAs a pure scheduler, using Tokio for CPU work is likely to have slightly higher overheads than a dedicated, synchronous worker pool. This is not surprising when one considers the extra work required to support async programming. This is unlikely to be a problem in practice for most users, but might be worth considering if your code is extremely performance sensitive.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "IO and issues with blocking", "heading_path": ["IO and issues with blocking", "Other blocking operations", "CPU-intensive work"], "path": "part-guide/io.md", "url": "https://rust-lang.github.io/async-book/part-guide/io.html#cpu-intensive-work", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/io.md#cpu-intensive-work-12", "text": "Asynchronous Programming in Rust › IO and issues with blocking › Other blocking operations › CPU-intensive work\n\nFor any of the above solutions, you will have tasks running in different contexts (sync and async, or different async runtimes). If you need to communicate between tasks, then you need to take care that you are using the correct combinations of sync and async primitives (channels, mutexes, etc.) and the correct (blocking or non-blocking) methods on those primitives. For mutexes and similar locks, you should probably use the async versions if you need to hold the lock across an await point or protect an IO resource (it should be usable from sync contexts by using a blocking lock method), or a synchronous version to protect data or where the lock does not need to be held across an await point. Tokio's async channels can be used from sync context with blocking methods, but see these docs for some detail on when to use sync or async channels.\nSo, which of the above solutions should you use?\n- If you're doing blocking IO, you should probably use `spawn_blocking`. You cannot use a second runtime or other thread pool (at least if you need optimal performance).\n- If you have a thread that will run forever, you should use `std::thread::spawn` rather than use any kind of thread pool (since it will use up one of the pool's threads).\n- If you're doing *lots* of CPU work, then you should use a thread pool, either a specialised one or a second async runtime.\n- If you need to run long-running async code, then you should use a second runtime.\n- You might choose to use a dedicated thread or `spawn_blocking` because it is easy and has satisfactory performance, even though a more complex solution is more optimal.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "IO and issues with blocking", "heading_path": ["IO and issues with blocking", "Other blocking operations", "CPU-intensive work"], "path": "part-guide/io.md", "url": "https://rust-lang.github.io/async-book/part-guide/io.html#cpu-intensive-work", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/io.md#yielding-13", "text": "Asynchronous Programming in Rust › IO and issues with blocking › Other blocking operations › Yielding\n\nLong-running code is an issue because it doesn't give the scheduler an opportunity to schedule other tasks. Async concurrency is cooperative: the scheduler cannot pre-empt a task to run a different one. If a long-running task doesn't yield to the scheduler, then the scheduler cannot stop it. However, if the long-running code does yield to the scheduler, then other tasks can be scheduled and the fact that a task is long-running is not an issue. This can be used as an alternative to using another thread for CPU-intensive work or for CPU-intensive work on it's own runtime to (possibly) improve performance.\nYielding is easy, simply call the runtime's yield function. In Tokio that is `yield_now`. Note that this is different to both the standard library's `yield_now` and the `yield` keyword for yielding from a coroutine. Calling `yield_now` won't yield to the scheduler if the current future is being run inside a `select` or `join` (see the chapter on composing futures concurrently); that may or may not be what you want to happen.\nKnowing when you need to yield is a bit more tricky. First of all you need to know if your program is implicitly yielding. This can only happen at an `.await`, so if you're not `await`ing, then you're not yielding. But await doesn't automatically yield to the scheduler. That only happens if the leaf future being `await`ed is pending (not ready) or there is an explicit `yield` somewhere in the call stack. Tokio and most async runtimes will do this in their IO and synchronization functions, but in general you can't know whether an `await` will yield without debugging or inspecting the source code.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "IO and issues with blocking", "heading_path": ["IO and issues with blocking", "Other blocking operations", "Yielding"], "path": "part-guide/io.md", "url": "https://rust-lang.github.io/async-book/part-guide/io.html#yielding", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/io.md#yielding-14", "text": "Asynchronous Programming in Rust › IO and issues with blocking › Other blocking operations › Yielding\n\nA good rule of thumb is that code should not run for more than 10-100 microseconds without hitting a potential yield point.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "IO and issues with blocking", "heading_path": ["IO and issues with blocking", "Other blocking operations", "Yielding"], "path": "part-guide/io.md", "url": "https://rust-lang.github.io/async-book/part-guide/io.html#yielding", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/io.md#references-15", "text": "Asynchronous Programming in Rust › IO and issues with blocking › Other blocking operations › References\n\n- Tokio docs on CPU-bound tasks and blocking code\n- Blog post: What is Blocking?\n- Blog post: Using Rustlang’s Async Tokio Runtime for CPU-Bound Tasks", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "IO and issues with blocking", "heading_path": ["IO and issues with blocking", "Other blocking operations", "References"], "path": "part-guide/io.md", "url": "https://rust-lang.github.io/async-book/part-guide/io.html#references", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/concurrency-primitives.md#composing-futures-concurrently-0", "text": "Asynchronous Programming in Rust › Composing futures concurrently\n\nIn this chapter we're going to cover more ways in which futures can be composed. In particular, some new ways in which futures can be executed concurrently (but not in parallel). Superficially, the new functions/macros we introduce in this chapter are pretty simple. However, the underlying concepts can be pretty subtle. We'll start with a recap on futures, concurrency, and parallelism, but you might also want to revisit the earlier section comparing concurrency with parallelism.\nA futures is a deferred computation. A future can be progressed by using `await`, which hands over control to the runtime, causing the current task to wait for the result of the computation. If `a` and `b` are futures, then they can be sequentially composed (that is, combined to make a future which executes `a` to completion and then `b` to completion) by `await`ing one then the other: `async { a.await; b.await}`.\nWe have also seen parallel composition of futures using `spawn`: `async { let a = spawn(a); let b = spawn(b); (a.await, b.await)}` runs the two futures in parallel. Note that the `await`s in the tuple are not awaiting the futures themselves, but are awaiting `JoinHandle`s to get the results of the futures when they complete.\nIn this chapter we introduce two ways to compose futures concurrently without parallelism: `join` and `select`/`race`. In both cases, the futures run concurrently by time-slicing; each of the composed futures takes turns to execute then the next gets a turn. This is done *without involving the async runtime* (and therefore without multiple OS threads and without any potential for parallelism). The composing construct interleaves the futures locally. You can think of these constructs being like mini-executors which execute their component futures within a single async task.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Composing futures concurrently", "heading_path": ["Composing futures concurrently"], "path": "part-guide/concurrency-primitives.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency-primitives.html#composing-futures-concurrently", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/concurrency-primitives.md#composing-futures-concurrently-1", "text": "Asynchronous Programming in Rust › Composing futures concurrently\n\nThe fundamental difference between join and select/race is how they handle futures completing their work: a join finishes when all futures finish, a select/race finishes when one future finishes (all the others are cancelled). There are also variations of both for handling errors.\nThese constructs (or similar concepts) are often used with streams, we'll touch on this below, but we'll talk more about that in the streams chapter.\nIf you want parallelism (or you don't explicitly not want parallelism), spawning tasks is often a simpler alternative to these composition constructs. Spawning tasks is usually less error-prone, more general, and performance is more predictable. On the other hand, spawning is inherently less structured, which can make lifecycle and resource management harder to reason about.\nIt's worth considering the performance issue in a little more depth. The potential performance problem with concurrent composition is the fairness of time sharing. If you have 100 tasks in your program, then typically the optimal way to share resources is for each task to get 1% of the processor time (or if the tasks are all waiting, then for each to have the same chance of being woken up). If you spawn 100 tasks, then this is usually what happens (roughly). However, if you spawn two tasks and join 99 futures on one of those tasks, then the scheduler will only know about two tasks and one task will get 50% of the time and the 99 futures will each get 0.5%.\nUsually the distribution of tasks is not so biased, and very often we use join/select/etc. for things like timeouts where this behaviour is actually desirable. But it is worth considering to ensure that your program has the performance characteristics you want.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Composing futures concurrently", "heading_path": ["Composing futures concurrently"], "path": "part-guide/concurrency-primitives.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency-primitives.html#composing-futures-concurrently", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/concurrency-primitives.md#join-2", "text": "Asynchronous Programming in Rust › Composing futures concurrently › Join\n\nTokio's `join` macro takes a list of futures and runs them all to completion concurrently (returning all the results as a tuple). It returns when all the futures have completed. The futures are always executed on the same thread (concurrently and not in parallel).\nHere's a simple example:\n```rust,norun\nasync fn main() {\n let (result_1, result_2) = join!(do_a_thing(), do_a_thing());\n // Use `result_1` and `result_2`.\n}\n```\nHere, the two executions of `do_a_thing` happen concurrently, and the results are ready when they are both done. Notice that we don't `await` to get the results. `join!` implicitly awaits its futures and produces a value. It does not create a future. You do still need to use it within an async context (e.g., from within an async function).\nAlthough you can't see it in the example above, `join!` takes expressions which evaluate to futures[^into]. `join` does not create an async context in it's body and you shouldn't `await` the futures passed to `join` (otherwise they'll be evaluated before the joined futures).\nBecause all the futures are executed on the same thread, if any future blocks the thread, then none of them can make progress. If using a mutex or other lock, this can easily lead to deadlock if one future is waiting for a lock held by another future.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Composing futures concurrently", "heading_path": ["Composing futures concurrently", "Join"], "path": "part-guide/concurrency-primitives.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency-primitives.html#join", "has_code": true, "code_tags": ["rust,norun"]}} {"id": "async-book/part-guide/concurrency-primitives.md#join-3", "text": "Asynchronous Programming in Rust › Composing futures concurrently › Join\n\n`join` does not care about the result of the futures. In particular, if a future is cancelled or returns an error, it does not affect the others - they continue to execute. If you want 'fail fast' behaviour, use `try_join`. `try_join` works similarly to `join`, however, if any future returns an `Err`, then all the other futures are cancelled and `try_join` returns the error immediately.\nBack in the earlier chapter on async/await, we used the word 'join' to talk about joining spawned tasks. As the name suggests, joining futures and tasks is related: joining means we execute multiple futures concurrently and wait for the result before continuing. The syntax is different: using a `JoinHandle` vs the `join` macro, but the idea is similar. The key difference is that when joining tasks, the tasks execute concurrently and in parallel, whereas using `join!`, the futures execute concurrently but not in parallel. Furthermore, spawned tasks are scheduled on the runtime's scheduler, whereas with `join!` the futures are 'scheduled' locally (on the same task and within the temporal scope of the macro's execution). Another difference is that if a spawned task panics, the panic is caught by the runtime, but if a future in `join` panics, then the whole task panics.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Composing futures concurrently", "heading_path": ["Composing futures concurrently", "Join"], "path": "part-guide/concurrency-primitives.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency-primitives.html#join", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/concurrency-primitives.md#alternatives-4", "text": "Asynchronous Programming in Rust › Composing futures concurrently › Join › Alternatives\n\nRunning futures concurrently and collecting their results is a common requirement. You should probably use `spawn` and `JoinHandle`s unless you have a good reason not to (i.e., you explicitly do not want parallelism, and even then you might prefer to use `spawn_local`). The `JoinSet` abstraction manages such spawned tasks in a way similar to `join!`.\nMost runtimes (and futures.rs) have an equivalent to Tokio's `join` macro and they mostly behave the same way. There are also `join` functions, which are similar to the macro but a little less flexible. E.g., futures.rs has `join` for joining two futures, `join3`, `join4`, and `join5` for joining the obvious number of futures, and join_all for joining a collection of futures (as well as `try_` variations of each of these).", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Composing futures concurrently", "heading_path": ["Composing futures concurrently", "Join", "Alternatives"], "path": "part-guide/concurrency-primitives.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency-primitives.html#alternatives", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/concurrency-primitives.md#alternatives-5", "text": "Asynchronous Programming in Rust › Composing futures concurrently › Join › Alternatives\n\nFutures-concurrency also provides functionality for join (and try_join). In the futures-concurrency style, these operations are trait methods on groups of futures such as tuples, `Vec`s, or arrays. E.g., to join two futures, you would write `(fut1, fut2).join().await` (note that `await` is explicit here).\nIf the set of futures you wish to join together varies dynamically (e.g., new futures are created as input comes in over the network), or you want the results as they complete rather than when all the futures have completed, then you'll need to use streams and the `FuturesUnordered` or `FuturesOrdered` functionality. We'll cover these in the streams chapter.\n[^into]: The expressions must have a type which implements `IntoFuture`. The expression is evaluated and converted to a future by the macro. I.e., they don't actually have to evaluate to a future, but rather something which can be converted into a future, but this is a pretty minor distinction. The expressions themselves are evaluated sequentially before any of the resulting futures are executed.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Composing futures concurrently", "heading_path": ["Composing futures concurrently", "Join", "Alternatives"], "path": "part-guide/concurrency-primitives.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency-primitives.html#alternatives", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/concurrency-primitives.md#raceselect-6", "text": "Asynchronous Programming in Rust › Composing futures concurrently › Race/select\n\nThe counterpart to joining futures is racing them (aka selecting on them). With race/select the futures are executed concurrently, but rather than waiting for all the futures to complete, we only wait for the first one to complete and then cancel the others. Although this sounds similar to joining, it is significantly more interesting (and sometimes error-prone) because now we have to reason about cancellation.\nHere's an example using Tokio's `select` macro:\n```rust,norun\nasync fn main() {\n select! {\n result = do_a_thing() => {\n println!(\"computation completed and returned {result}\");\n }\n _ = timeout() => {\n println!(\"computation timed-out\");\n }\n }\n}\n```\nYou'll notice things are already more interesting than with the `join` macro because we handle the results of the futures within the `select` macro. It looks a bit like a `match` expression, but with `select`, all branches are run concurrently and the body of the branch which finishes first is executed with its result (the other branches are not executed and the futures are cancelled by `drop`ping). In the example, `do_a_thing` and `timeout` execute concurrently and the first to complete will have it's block executed (i.e., only one `println` will run), the other future will be cancelled. As with the `join` macro, awaiting the futures is implicit.\nTokio's `select` macro supports a bunch of features:", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Composing futures concurrently", "heading_path": ["Composing futures concurrently", "Race/select"], "path": "part-guide/concurrency-primitives.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency-primitives.html#raceselect", "has_code": true, "code_tags": ["rust,norun"]}} {"id": "async-book/part-guide/concurrency-primitives.md#raceselect-7", "text": "Asynchronous Programming in Rust › Composing futures concurrently › Race/select\n\n- pattern matching: the syntax on the left of `=` on each branch can be a pattern and the block is only executed if the result of the future matches the pattern. If the pattern does not match, then the future is no longer polled (but other futures are). This can be useful for futures which optionally return a value, e.g., `Some(x) = do_a_thing() => { ... }`.\n- `if` guards: each branch may have an `if` guard. When the `select` macro runs, after evaluating each expression to produce a future, the `if` guard is evaluated and the future is only polled if the guard is true. E.g., `x = = do_a_thing() if false => { ... }` will never be polled. Note that the `if` guard is not re-evaluated during polling, only when the macro is initialized.\n- `else` branch: `select` can have an `else` branch `else => { ... }`, this is executed if all the futures have stopped and none of the blocks have been executed. If this happens without an `else` branch, then `select` will panic.\nThe value of the `select!` macro is the value of the executed branch (just like `match`), so all branches must have the same type. E.g., if we wanted to use the result of the above example outside of the `select`, we'd write it like\n```rust,norun\nasync fn main() {\n let result = select! {\n result = do_a_thing() => {\n Some(result)\n }\n _ = timeout() => {\n None\n }\n };\n\n // Use `result`\n}\n```", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Composing futures concurrently", "heading_path": ["Composing futures concurrently", "Race/select"], "path": "part-guide/concurrency-primitives.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency-primitives.html#raceselect", "has_code": true, "code_tags": ["rust,norun"]}} {"id": "async-book/part-guide/concurrency-primitives.md#raceselect-8", "text": "Asynchronous Programming in Rust › Composing futures concurrently › Race/select\n\nAs with `join!`, `select!` does not treat `Result`s in any special way (other than the pattern matching mentioned previously) and if a branch completes with an error, then all other branches will be cancelled and the error will be used as the result of select (in the same way as if the branch has completed successfully).\nThe `select` macro intrinsically uses cancellation, so if you're trying to avoid cancellation in your program, you must avoid `select!`. In fact, `select` is often the primary source of cancellation in an async program. As discussed elsewhere, cancellation has many subtle issues which can lead to bugs. In particular, note that `select` cancels futures by simply dropping them. This will not notify the future being dropped or trigger any cancellation tokens, etc.\n`select!` is often used in a loop to handle streams or other sequences of futures. This adds an extra layer of complexity and opportunities for bugs. In the simple case that we create a new, independent future on each iteration of the loop, things are not much more complicated. However, this is rarely what is needed. Generally we want to preserve some state between iterations. It is common to use `select` in a loop with streams, where each iteration of the loop handles one result from the stream. E.g.:\n```rust,norun\nasync fn main() {\n let mut stream = ...;\n\n loop {\n select! {\n result = stream.next() => {\n match result {\n Some(x) => println!(\"received: {x}\"),\n None => break,\n }\n }\n _ = timeout() => {\n println!(\"time out!\");\n break;\n }\n }\n }\n}\n```", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Composing futures concurrently", "heading_path": ["Composing futures concurrently", "Race/select"], "path": "part-guide/concurrency-primitives.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency-primitives.html#raceselect", "has_code": true, "code_tags": ["rust,norun"]}} {"id": "async-book/part-guide/concurrency-primitives.md#raceselect-9", "text": "Asynchronous Programming in Rust › Composing futures concurrently › Race/select\n\nIn this example, we read values from `stream` and print them until there are none left or waiting for a result times out. What happens to any remaining data in the stream in the timeout case depends on the implementation of the stream (it might be lost! Or duplicated!). This is an example of why behaviour in the face of cancellation can be important (and tricky).\nWe may want to reuse a future, not just a stream, across iterations. For example, we may want to race against a timeout future where the timeout applies to all iterations rather than applying a new timeout for each iteration. This is possible by creating the future outside of the loop and referencing it:\n```rust,norun\nasync fn main() {\n let mut stream = ...;\n let mut timeout = timeout();\n\n loop {\n select! {\n result = stream.next() => {\n match result {\n Some(x) => println!(\"received: {x}\"),\n None => break,\n }\n }\n // Create a reference to `timeout` rather than moving it.\n _ = &mut timeout => {\n println!(\"time out!\");\n break;\n }\n }\n }\n}\n```\nThere are a couple of important details when using `select!` in a loop with futures or streams created outside of the `select!`. These are a fundamental consequence of how `select` works, so I'll introduce them by stepping through the details of `select`, using `timeout` in the last example as an example.\n- `timeout` is created outside of the loop and initialised with some time to count down.\n- On each iteration of the loop, `select` creates a reference to `timeout`, but does not change its state.\n- As `select` executes, it polls `timeout` which will return `Pending` while there is time left and `Ready` when the time elapses, at which point its block is executed.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Composing futures concurrently", "heading_path": ["Composing futures concurrently", "Race/select"], "path": "part-guide/concurrency-primitives.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency-primitives.html#raceselect", "has_code": true, "code_tags": ["rust,norun"]}} {"id": "async-book/part-guide/concurrency-primitives.md#raceselect-10", "text": "Asynchronous Programming in Rust › Composing futures concurrently › Race/select\n\nIn the above example, when `timeout` is ready, we `break` out of the loop. But what if we didn't do that? In that case, `select` would simply poll `timeout` again, which the `Future` docs say should not happen! `select` can't help this, it doesn't have any state (between iterations) to decide if `timeout` should be polled. Depending on how `timeout` is written, this might cause a panic, a logic error, or some kind of crash.\nYou can prevent this kind of bug in several ways:\n- Use a fused future or stream so that re-polling is safe.\n- Ensure that your code is structured so that futures are never re-polled, e.g., by breaking out of the loop (as in the previous example), or by using an `if` guard.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Composing futures concurrently", "heading_path": ["Composing futures concurrently", "Race/select"], "path": "part-guide/concurrency-primitives.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency-primitives.html#raceselect", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/concurrency-primitives.md#raceselect-11", "text": "Asynchronous Programming in Rust › Composing futures concurrently › Race/select\n\nNow, lets consider the type of `&mut timeout`. Lets assume that `timeout()` returns a type which implements `Future`, which might be an anonymous type from an async function, or it might be a named type like `Timeout`. Lets assume the latter because it makes the examples easier (but the logic applies in either case). Given that `Timeout` implents `Future`, will `&mut Timeout` implement `Future`? Not necessarily! There is a blanket `impl` which makes this true, but only if `Timeout` implements `Unpin`. That is not the case for all futures, so often you'll get a type error writing code like the last example. Such an error is easily fixed though by using the `pin` macro, e.g., `let mut timeout = pin!(timeout());`\nCancellation with `select` in a loop is a rich source of subtle bugs. These usually happen where a future contains some state involving some data but not the data itself. When the future is dropped by cancellation, that state is lost but the underlying data is not updated. This can lead to data being lost or processed multiple times.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Composing futures concurrently", "heading_path": ["Composing futures concurrently", "Race/select"], "path": "part-guide/concurrency-primitives.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency-primitives.html#raceselect", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/concurrency-primitives.md#alternatives-1-12", "text": "Asynchronous Programming in Rust › Composing futures concurrently › Race/select › Alternatives\n\nFutures.rs has its own `select` macro and futures-concurrency has a Race trait which are alternatives to Tokio's `select` macro. These both have the same core semantics of concurrently racing multiple futures, processing the result of the first and cancelling the others, but they have different syntax and vary in the details.\nFutures.rs' `select` is superficially similar to Tokio's; to summarize the differences, in the futures.rs version:\n- Futures must always be fused (enforced by type-checking).\n- `select` has `default` and `complete` branches, rather than an `else` branch.\n- `select` does not support `if` guards.\nFutures-concurrency's `Race` has a very different syntax, similar to it's version of `join`, e.g., `(future_a, future_b).race().await` (it works on `Vec`s and arrays as well as tuples). The syntax is less flexible than the macros, but fits in nicely with most async code. Note that if you use `race` within a loop, you can still have the same issues as with `select`.\nAs with `join`, spawning tasks and letting them execute in parallel is often a good alternative to using `select`. However, cancelling the remaining tasks after the first completes requires some extra work. This can be done using channels or a cancellation token. In either case, cancellation requires some action by the task being cancelled which means the task can do some tidying up or other graceful shutdown.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Composing futures concurrently", "heading_path": ["Composing futures concurrently", "Race/select", "Alternatives"], "path": "part-guide/concurrency-primitives.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency-primitives.html#alternatives-1", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/concurrency-primitives.md#alternatives-1-13", "text": "Asynchronous Programming in Rust › Composing futures concurrently › Race/select › Alternatives\n\nA common use for `select` (especially inside a loop) is working with streams. There are stream combinator methods which can replace some uses of select. For example, `merge` in futures-concurrency is a good alternative to merge multiple streams together.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Composing futures concurrently", "heading_path": ["Composing futures concurrently", "Race/select", "Alternatives"], "path": "part-guide/concurrency-primitives.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency-primitives.html#alternatives-1", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/concurrency-primitives.md#final-words-14", "text": "Asynchronous Programming in Rust › Composing futures concurrently › Final words\n\nIn this section we've talked about two ways to run groups of futures concurrently. Joining futures means waiting for them all to finish; selecting (aka racing) futures means waiting for the first to finish. In contrast to spawning tasks, these compositions make no use of parallelism.\nBoth `join` and `select` operate on sets of futures which are known in advance (often when writing the program, rather than at runtime). Sometimes, the futures to be composed are not known in advance - futures must be added to the set of composed futures as they are being executed. For this we need streams which have their own composition operations.\nIt's worth reiterating that although these composition operators are powerful and expressive, it is often easier and more appropriate to use tasks and spawning: parallelism is often desirable, you're less likely to have bugs around cancellation or blocking, and resource allocation is usually fairer (or at least simpler) and more predictable.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Composing futures concurrently", "heading_path": ["Composing futures concurrently", "Final words"], "path": "part-guide/concurrency-primitives.md", "url": "https://rust-lang.github.io/async-book/part-guide/concurrency-primitives.html#final-words", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/sync.md#channels-locking-and-synchronization-0", "text": "Asynchronous Programming in Rust › Channels, locking, and synchronization\n\nnote on runtime specificness of sync primitves\nWhy we need async primitives rather than use the sync ones", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Channels, locking, and synchronization", "heading_path": ["Channels, locking, and synchronization"], "path": "part-guide/sync.md", "url": "https://rust-lang.github.io/async-book/part-guide/sync.html#channels-locking-and-synchronization", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/sync.md#channels-1", "text": "Asynchronous Programming in Rust › Channels, locking, and synchronization › Channels\n\n- basically same as the std ones, but await\n - communicate between tasks (same thread or different)\n- one shot\n- mpsc\n- other channels\n- bounded and unbounded channels", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Channels, locking, and synchronization", "heading_path": ["Channels, locking, and synchronization", "Channels"], "path": "part-guide/sync.md", "url": "https://rust-lang.github.io/async-book/part-guide/sync.html#channels", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/sync.md#locks-2", "text": "Asynchronous Programming in Rust › Channels, locking, and synchronization › Locks\n\n- async Mutex\n - c.f., std::Mutex - can be held across await points (borrowing the mutex in the guard, guard is Send, scheduler-aware? or just because lock is async?), lock is async (will not block the thread waiting for lock to be available)\n - even a clippy lint for holding the guard across await (https://rust-lang.github.io/rust-clippy/master/index.html#await_holding_lock)\n - more expensive because it can be held across await\n - use std::Mutex if you can\n - can use try_lock or mutex is expected to not be under contention\n - lock is not magically dropped when yield (that's kind of the point of a lock!)\n - deadlock by holding mutex over await\n - tasks deadlocked, but other tasks can make progress so might not look like a deadlock in process stats/tools/OS\n - usual advice - limit scope, minimise locks, order locks, prefer alternatives\n - no mutex poisoning\n - lock_owned\n - blocking_lock\n - cannot use in async\n - applies to other locks (should the above be moved before discussion of mutex specifically? Probably yes)\n- RWLock\n- Semaphore\n- yielding", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Channels, locking, and synchronization", "heading_path": ["Channels, locking, and synchronization", "Locks"], "path": "part-guide/sync.md", "url": "https://rust-lang.github.io/async-book/part-guide/sync.html#locks", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/sync.md#other-synchronization-primitives-3", "text": "Asynchronous Programming in Rust › Channels, locking, and synchronization › Other synchronization primitives\n\n- notify, barrier\n- OnceCell\n- atomics", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Channels, locking, and synchronization", "heading_path": ["Channels, locking, and synchronization", "Other synchronization primitives"], "path": "part-guide/sync.md", "url": "https://rust-lang.github.io/async-book/part-guide/sync.html#other-synchronization-primitives", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/tools.md#tools-for-async-programming-0", "text": "Asynchronous Programming in Rust › Tools for async programming\n\n- Why we need specialist tools for async\n- Are there other tools to cover\n - loom", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Tools for async programming", "heading_path": ["Tools for async programming"], "path": "part-guide/tools.md", "url": "https://rust-lang.github.io/async-book/part-guide/tools.html#tools-for-async-programming", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/tools.md#monitoring-1", "text": "Asynchronous Programming in Rust › Tools for async programming › Monitoring\n\n- Tokio console", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Tools for async programming", "heading_path": ["Tools for async programming", "Monitoring"], "path": "part-guide/tools.md", "url": "https://rust-lang.github.io/async-book/part-guide/tools.html#monitoring", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/tools.md#tracing-and-logging-2", "text": "Asynchronous Programming in Rust › Tools for async programming › Tracing and logging\n\n- issues with async tracing\n- tracing crate (https://github.com/tokio-rs/tracing)", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Tools for async programming", "heading_path": ["Tools for async programming", "Tracing and logging"], "path": "part-guide/tools.md", "url": "https://rust-lang.github.io/async-book/part-guide/tools.html#tracing-and-logging", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/tools.md#debugging-3", "text": "Asynchronous Programming in Rust › Tools for async programming › Debugging\n\n- Understanding async backtraces (RUST_BACKTRACE and in a debugger)\n- Techniques for debugging async code\n- Using Tokio console for debugging\n- Debugger support (WinDbg?)", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Tools for async programming", "heading_path": ["Tools for async programming", "Debugging"], "path": "part-guide/tools.md", "url": "https://rust-lang.github.io/async-book/part-guide/tools.html#debugging", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/tools.md#profiling-4", "text": "Asynchronous Programming in Rust › Tools for async programming › Profiling\n\n- How async messes up flamegraphs\n- How to profile async IO\n- Getting insight into the runtime\n - Tokio metrics", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Tools for async programming", "heading_path": ["Tools for async programming", "Profiling"], "path": "part-guide/tools.md", "url": "https://rust-lang.github.io/async-book/part-guide/tools.html#profiling", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/dtors.md#destruction-and-clean-up-0", "text": "Asynchronous Programming in Rust › Destruction and clean-up\n\n- Object destruction and recap of Drop\n- General clean up requirements in software\n- Async issues\n - Might want to do stuff async during clean up, e.g., send a final message\n - Might need to clean up stuff which is still being used async-ly\n - Might want to clean up when an async task completes or cancels and there is no way to catch that\n - State of the runtime during clean-up phase (esp if we're panicking or whatever)\n - No async Drop\n - WIP\n - forward ref to completion io topic", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Destruction and clean-up", "heading_path": ["Destruction and clean-up"], "path": "part-guide/dtors.md", "url": "https://rust-lang.github.io/async-book/part-guide/dtors.html#destruction-and-clean-up", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/dtors.md#cancellation-1", "text": "Asynchronous Programming in Rust › Destruction and clean-up › Cancellation\n\n- How it happens (recap of more-async-await.md)\n - drop a future\n - cancellation token\n - abort functions\n- What we can do about 'catching' cancellation\n - logging or monitoring cancellation\n- How cancellation affects other futures tasks (forward ref to cancellation safety chapter, this should just be a heads-up)", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Destruction and clean-up", "heading_path": ["Destruction and clean-up", "Cancellation"], "path": "part-guide/dtors.md", "url": "https://rust-lang.github.io/async-book/part-guide/dtors.html#cancellation", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/dtors.md#panicking-and-async-2", "text": "Asynchronous Programming in Rust › Destruction and clean-up › Panicking and async\n\n- Propagation of panics across tasks (spawn result)\n- Panics leaving data inconsistent (tokio mutexes)\n- Calling async code when panicking (make sure you don't)", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Destruction and clean-up", "heading_path": ["Destruction and clean-up", "Panicking and async"], "path": "part-guide/dtors.md", "url": "https://rust-lang.github.io/async-book/part-guide/dtors.html#panicking-and-async", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/dtors.md#patterns-for-clean-up-3", "text": "Asynchronous Programming in Rust › Destruction and clean-up › Patterns for clean-up\n\n- Avoid needing clean up (abort/restart)\n- Don't use async for cleanup and don't worry too much\n- async clean up method + dtor bomb (i.e., separate clean-up from destruction)\n- centralise/out-source clean-up in a separate task or thread or supervisor object/process\n- https://tokio.rs/tokio/topics/shutdown", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Destruction and clean-up", "heading_path": ["Destruction and clean-up", "Patterns for clean-up"], "path": "part-guide/dtors.md", "url": "https://rust-lang.github.io/async-book/part-guide/dtors.html#patterns-for-clean-up", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/dtors.md#why-no-async-drop-yet-4", "text": "Asynchronous Programming in Rust › Destruction and clean-up › Why no async Drop (yet)\n\n- Note this is advanced section and not necessary to read\n- Why async Drop is hard\n- Possible solutions and there issues\n- Current status", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Destruction and clean-up", "heading_path": ["Destruction and clean-up", "Why no async Drop (yet)"], "path": "part-guide/dtors.md", "url": "https://rust-lang.github.io/async-book/part-guide/dtors.html#why-no-async-drop-yet", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/futures.md#futures-0", "text": "Asynchronous Programming in Rust › Futures\n\nWe've talked a lot about futures in the preceding chapters; they're a key part of Rust's async programming story! In this chapter we're going to get into some of the details of what futures are and how they work, and some libraries for working directly with futures.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Futures", "heading_path": ["Futures"], "path": "part-guide/futures.md", "url": "https://rust-lang.github.io/async-book/part-guide/futures.html#futures", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/futures.md#the-future-and-intofuture-traits-1", "text": "Asynchronous Programming in Rust › Futures › The `Future` and `IntoFuture` traits\n\n- Future\n - Output assoc type\n - No real detail here, polling is in the next section, reference adv sections on Pin, executors/wakers\n- IntoFuture\n - Usage - general, in await, async builder pattern (pros and cons in using)\n- Boxing futures, `Box` and how it used to be common and necessary but mostly isn't now, except for recursion, etc.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Futures", "heading_path": ["Futures", "The `Future` and `IntoFuture` traits"], "path": "part-guide/futures.md", "url": "https://rust-lang.github.io/async-book/part-guide/futures.html#the-future-and-intofuture-traits", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/futures.md#polling-2", "text": "Asynchronous Programming in Rust › Futures › Polling\n\n- what it is and who does it, Poll type\n - ready is final state\n- how it connects with await\n- drop = cancel\n - for futures and thus tasks\n - implications for async programming in general\n - reference to chapter on cancellation safety", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Futures", "heading_path": ["Futures", "Polling"], "path": "part-guide/futures.md", "url": "https://rust-lang.github.io/async-book/part-guide/futures.html#polling", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/futures.md#futures-rs-crate-3", "text": "Asynchronous Programming in Rust › Futures › futures-rs crate\n\n- History and purpose\n - see streams chapter\n - helpers for writing executors or other low-level futures stuff\n - pinning and boxing\n - executor as a partial runtime (see alternate runtimes in reference)\n- TryFuture\n- convenience futures: pending, ready, ok/err, etc.\n- combinator functions on FutureExt\n- alternative to Tokio stuff\n - functions\n - IO traits", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Futures", "heading_path": ["Futures", "futures-rs crate"], "path": "part-guide/futures.md", "url": "https://rust-lang.github.io/async-book/part-guide/futures.html#futures-rs-crate", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/futures.md#futures-concurrency-crate-4", "text": "Asynchronous Programming in Rust › Futures › futures-concurrency crate\n\nhttps://docs.rs/futures-concurrency/latest/futures_concurrency/", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Futures", "heading_path": ["Futures", "futures-concurrency crate"], "path": "part-guide/futures.md", "url": "https://rust-lang.github.io/async-book/part-guide/futures.html#futures-concurrency-crate", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/runtimes.md#running-async-code-0", "text": "Asynchronous Programming in Rust › Runtimes and runtime issues › Running async code\n\n- Explicit startup vs async main\n- tokio context concept\n- block_on\n- runtime as reflected in the code (Runtime, Handle)\n- runtime shutdown", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Runtimes", "heading_path": ["Runtimes and runtime issues", "Running async code"], "path": "part-guide/runtimes.md", "url": "https://rust-lang.github.io/async-book/part-guide/runtimes.html#running-async-code", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/runtimes.md#threads-and-tasks-1", "text": "Asynchronous Programming in Rust › Runtimes and runtime issues › Threads and tasks\n\n- default work stealing, multi-threaded\n - revisit Send + 'static bounds\n- yield\n- spawn-local\n- spawn-blocking (recap), block-in-place\n- tokio-specific stuff on yielding to other threads, local vs global queues, etc", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Runtimes", "heading_path": ["Runtimes and runtime issues", "Threads and tasks"], "path": "part-guide/runtimes.md", "url": "https://rust-lang.github.io/async-book/part-guide/runtimes.html#threads-and-tasks", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/runtimes.md#configuration-options-2", "text": "Asynchronous Programming in Rust › Runtimes and runtime issues › Configuration options\n\n- thread pool size\n- single threaded, thread per core etc.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Runtimes", "heading_path": ["Runtimes and runtime issues", "Configuration options"], "path": "part-guide/runtimes.md", "url": "https://rust-lang.github.io/async-book/part-guide/runtimes.html#configuration-options", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/runtimes.md#alternate-runtimes-3", "text": "Asynchronous Programming in Rust › Runtimes and runtime issues › Alternate runtimes\n\n- Why you'd want to use a different runtime or implement your own\n- What kind of variations exist in the high-level design\n- Forward ref to adv chapters", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Runtimes", "heading_path": ["Runtimes and runtime issues", "Alternate runtimes"], "path": "part-guide/runtimes.md", "url": "https://rust-lang.github.io/async-book/part-guide/runtimes.html#alternate-runtimes", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/timers-signals.md#time-and-timers-0", "text": "Asynchronous Programming in Rust › Timers and Signal handling › Time and Timers\n\n- runtime integration, don't use thread::sleep, etc.\n- std Instant and Duration\n- sleep\n- interval\n- timeout\n - special future vs select/race", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Timers and signal handling", "heading_path": ["Timers and Signal handling", "Time and Timers"], "path": "part-guide/timers-signals.md", "url": "https://rust-lang.github.io/async-book/part-guide/timers-signals.html#time-and-timers", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/timers-signals.md#signal-handling-1", "text": "Asynchronous Programming in Rust › Timers and Signal handling › Signal handling\n\n- what is signal handling and why is it an async issue?\n- very OS specific\n- see Tokio docs", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Timers and signal handling", "heading_path": ["Timers and Signal handling", "Signal handling"], "path": "part-guide/timers-signals.md", "url": "https://rust-lang.github.io/async-book/part-guide/timers-signals.html#signal-handling", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/streams.md#async-iterators-fka-streams-0", "text": "Asynchronous Programming in Rust › Async iterators (FKA streams)\n\n- Stream as an async iterator or as many futures\n- WIP\n - current status\n - futures and Tokio Stream traits\n - nightly trait\n- lazy like sync iterators\n- pinning and streams (forward ref to pinning chapter)\n- fused streams", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Async iterators (streams)", "heading_path": ["Async iterators (FKA streams)"], "path": "part-guide/streams.md", "url": "https://rust-lang.github.io/async-book/part-guide/streams.html#async-iterators-fka-streams", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/streams.md#consuming-an-async-iterator-1", "text": "Asynchronous Programming in Rust › Async iterators (FKA streams) › Consuming an async iterator\n\n- while let with async next\n- for_each, for_each_concurrent\n- collect\n- into_future, buffered", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Async iterators (streams)", "heading_path": ["Async iterators (FKA streams)", "Consuming an async iterator"], "path": "part-guide/streams.md", "url": "https://rust-lang.github.io/async-book/part-guide/streams.html#consuming-an-async-iterator", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/streams.md#stream-combinators-2", "text": "Asynchronous Programming in Rust › Async iterators (FKA streams) › Stream combinators\n\n- Taking a future instead of a closure\n- Some example combinators\n- unordered variations\n- StreamGroup", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Async iterators (streams)", "heading_path": ["Async iterators (FKA streams)", "Stream combinators"], "path": "part-guide/streams.md", "url": "https://rust-lang.github.io/async-book/part-guide/streams.html#stream-combinators", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/streams.md#joinselectrace-with-streams-3", "text": "Asynchronous Programming in Rust › Async iterators (FKA streams) › Stream combinators › join/select/race with streams\n\n- hazards with select in a loop\n- fusing\n- difference to just futures\n- alternatives to these\n - Stream::merge, etc.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Async iterators (streams)", "heading_path": ["Async iterators (FKA streams)", "Stream combinators", "join/select/race with streams"], "path": "part-guide/streams.md", "url": "https://rust-lang.github.io/async-book/part-guide/streams.html#joinselectrace-with-streams", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/streams.md#implementing-an-async-iterator-4", "text": "Asynchronous Programming in Rust › Async iterators (FKA streams) › Implementing an async iterator\n\n- Implementing the trait\n- Practicalities and util functions\n- async_iter stream macro", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Async iterators (streams)", "heading_path": ["Async iterators (FKA streams)", "Implementing an async iterator"], "path": "part-guide/streams.md", "url": "https://rust-lang.github.io/async-book/part-guide/streams.html#implementing-an-async-iterator", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/streams.md#sinks-5", "text": "Asynchronous Programming in Rust › Async iterators (FKA streams) › Sinks\n\n- https://docs.rs/futures/latest/futures/sink/index.html", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Async iterators (streams)", "heading_path": ["Async iterators (FKA streams)", "Sinks"], "path": "part-guide/streams.md", "url": "https://rust-lang.github.io/async-book/part-guide/streams.html#sinks", "has_code": false, "code_tags": []}} {"id": "async-book/part-guide/streams.md#future-work-6", "text": "Asynchronous Programming in Rust › Async iterators (FKA streams) › Future work\n\n- current status\n - https://rust-lang.github.io/rfcs/2996-async-iterator.html\n- async next vs poll\n- async iteration syntax\n- (async) generators\n- lending iterators", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 1: guide", "chapter": "Async iterators (streams)", "heading_path": ["Async iterators (FKA streams)", "Future work"], "path": "part-guide/streams.md", "url": "https://rust-lang.github.io/async-book/part-guide/streams.html#future-work", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/cancellation.md#cancellation-and-cancellation-safety-0", "text": "Asynchronous Programming in Rust › Cancellation and cancellation safety\n\nInternal vs external cancellation\nThreads vs futures\n drop = cancel\n only at await points\n useful feature\n still somewhat abrubt and surprising\nOther cancellation mechanisms\n abort\n cancellation tokens", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Cancellation and cancellation safety", "heading_path": ["Cancellation and cancellation safety"], "path": "part-reference/cancellation.md", "url": "https://rust-lang.github.io/async-book/part-reference/cancellation.html#cancellation-and-cancellation-safety", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/cancellation.md#cancellation-safety-1", "text": "Asynchronous Programming in Rust › Cancellation and cancellation safety › Cancellation safety\n\nNot a memory safety issue or race condition\n Data loss or other logic errors\nDifferent definitions/names\n tokio's definition\n general definition/halt safety\n applying a replicated future idea\nSimple data loss\nResumption\nIssue with select or similar in loops\nSplitting state between the future and the context as a root cause", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Cancellation and cancellation safety", "heading_path": ["Cancellation and cancellation safety", "Cancellation safety"], "path": "part-reference/cancellation.md", "url": "https://rust-lang.github.io/async-book/part-reference/cancellation.html#cancellation-safety", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/pinning.md#pinning-0", "text": "Asynchronous Programming in Rust › Pinning\n\nPinning is a notoriously difficult concept and has some subtle and confusing properties. This section will go over the topic in depth (arguably too much depth). Pinning is key to the implementation of async programming in Rust[^design], but it's possible to get far without ever encountering pinning and certainly without having to have a deep understanding.\nThe first section will give a summary of pinning, which hopefully is enough for most async programmers to know. The rest of this chapter is for implementers, others doing advanced or low-level async programming, and the curious.\nAfter the summary, this chapter will give some background on move semantics before getting into pinning. We'll cover the general idea, then the `Pin` and `Unpin` types, how pinning achieves it goals, and several topics about working with pinning in practice. There are then sections on pinning and async programming, and some alternatives and extensions to pinning (for the really curious). At the end of the chapter are some links to alternative explanations and reference material.\n[^design]: It's worth noting that pinning is a low-level building block designed specifically for the implementation of async Rust. Although it is not directly tied to async Rust and can be used for other purposes, it was not designed to be a general-purpose mechanism, and in particular is not an out-of-the-box solution for self-referential fields. Using pinning for anything other than async code generally only works if it is wrapped in thick layers of abstraction, since it will require lots of fiddly and hard to reason about unsafe code.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#pinning", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/pinning.md#tldr-1", "text": "Asynchronous Programming in Rust › Pinning › TL;DR\n\n`Pin` marks a pointer as pointing to an object which will not move until it is dropped. Pinning is not built-in to the language or compiler; it works by simply restricting access to mutable references to the pointee. It is easy enough to break pinning in unsafe code, but like all safety guarantees in unsafe code, it is the responsibility of the programmer not to do so.\nBy guaranteeing that an object won't move, pinning makes it safe to have references from one field of a struct to another (sometimes called self-references). This is required for the implementation of async functions (which are implemented as data structures where variables are stored as fields, since variables may reference each other, fields of a future implementing an async function must be able to reference each other). Mostly, programmers don't have to be aware of this detail, but when dealing with futures directly, you might need to be because the signature of `Future::poll` requires `self` to be pinned.\nIf you're using futures by reference, you might need to pin a reference using `pin!(...)` to ensure the reference still implements the `Future` trait (this often comes up with the `select` macro). Likewise, if you want to manually call `poll` on a future (usually because you are implementing another future), you will need a pinned reference to it (use `pin!` or ensure arguments have pinned types). If you're implementing a future or if you have a pinned reference for some other reason, and you want mutable access to the object's internals, you'll need to understand the section below on pinned fields to know how to do so and when it is safe.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "TL;DR"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#tldr", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/pinning.md#move-semantics-2", "text": "Asynchronous Programming in Rust › Pinning › Move semantics\n\nA useful concept for discussing pinning and related topics is the idea of *place*s. A place is a chunk of memory (with an address) where a value can live. A reference doesn't really point at a value, it points at a place. That is why `*ref = ...` makes sense: the dereference gives you the place, not a copy of the value. Places are well-known to language implementers but usually implicit in programming languages (they are implicit in Rust). Programmers usually have a good intuition for places, but may not think of them explicitly.\nAs well as references, variables and field accesses evaluate to places. In fact, anything that can appear on the left-hand side of an assignment must be a place at runtime (which is why places are called 'lvalue's in compiler jargon).\nIn Rust, mutability is a property of places, as is being 'frozen' as a result of borrowing (we might say the place is borrowed).\nAssignment in Rust *moves* data (mostly, some simple data has copy semantics, but that doesn't matter too much). When we write `let b = a;`, the data that was in memory at a place identified by `a` is moved to the place identified by `b`. That means that after the assignment, the data exists at `b` but no longer exists at `a`. Or in other words, the address of the object is changed by the assignment[^compiler].\nIf pointers existed to the place which was moved from, the pointers would be invalid since they no longer point to the object. This is why borrowed references prevent moving: `let r = &a; let b = a;` is illegal, the existence of `r` prevents `a` being moved.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "Move semantics"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#move-semantics", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/pinning.md#move-semantics-3", "text": "Asynchronous Programming in Rust › Pinning › Move semantics\n\nThe compiler only knows about references from outside an object into the object (such as the above example, or a reference to a field of an object). A reference entirely within an object would be invisible to the compiler. Imagine if we were allowed to write something like:\n```rust,norun\nstruct Bad {\n field: u64,\n r: &'self u64,\n}\n```\nWe could have an instance `b` of `Bad` where `b.r` points to `b.field`. In `let a = b;`, the internal reference `b.r` to `b.field` is invisible to the compiler, so it looks like there are no references to `b` and therefore the move to `a` would be ok. However if that happened, then after the move, `a.r` would not point to `a.field` as we'd like, but to invalid memory at the old location of `b.field`, violating Rust's safety guarantees.\nMoving data isn't limited to values. Data can also be moved out of a unique reference. Dereferencing a `Box` moves the data from the heap to the stack. `take`, `replace`, and `swap` (all in `std::mem`) move data out of a mutable reference (`&mut T`). Moving out of a `Box` leaves the pointed-to place invalid. Moving out of a mutable reference leaves the place valid, but containing different data.\n[^compiler]: We're conflating source code and runtime a bit here. To be absolutely clear, variables don't exist at runtime. The (compiled) snippet might be executed multiple times (e.g., if it's in a loop or in a function called multiple times). For each execution the variables in the source code will be represented by different addresses at runtime.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "Move semantics"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#move-semantics", "has_code": true, "code_tags": ["rust,norun"]}} {"id": "async-book/part-reference/pinning.md#move-semantics-4", "text": "Asynchronous Programming in Rust › Pinning › Move semantics\n\nAbstractly, a move is implemented by copying the bits from the origin to the destination and then erasing the origin bits. However, the compiler can optimise this is many ways.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "Move semantics"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#move-semantics", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/pinning.md#pinning-1-5", "text": "Asynchronous Programming in Rust › Pinning › Pinning\n\nImportant note: I'm going to start by discussing an abstract concept of pinning, which is not exactly what is expressed by any particular type. We'll make the concept more concrete as we go on, and end up with precise definitions of what different types mean, but none of these types mean exactly the same as the pinning concept we'll start with.\nAn object is pinned if it will not be moved or otherwise invalidated. As I explained above, this is not a new concept - borrowing an object prevents the object being moved for the duration of the borrow. Whether an object can be moved or not is not explicit in Rust's types, though it is known by the compiler (which is why you can get \"cannot move out of\" error messages). As opposed to borrowing (and the temporary restriction on moves caused by borrowing), being pinned is permanent. An object can change from being not pinned to being pinned, but once it is pinned then it must remain pinned until it is dropped[^inherent].\nJust as pointer types reflect the ownership and mutability of the pointee (e.g., `Box` vs `&`, `&mut` vs `&`), we want to reflect pinned-ness in pointer types too. This is not a property of the pointer - the pointer is not pinned or movable - it is a property of the pointed-to place: whether the pointee can be moved out of its place.\nRoughly, `Pin>` is a pointer to an owned, pinned object and `Pin<&mut T>` is a pointer to a uniquely borrowed, mutable, pinned object (c.f., `&mut T` which is a pointer to a uniquely borrowed, mutable, object which may or may not be pinned).", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "Pinning"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#pinning-1", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/pinning.md#pinning-1-6", "text": "Asynchronous Programming in Rust › Pinning › Pinning\n\nThe pinning concept was not added to Rust until after 1.0 and for reasons of backwards compatibility, there is no way to explicitly express whether an *object* is pinned or not. We can only express that a reference points to a pinned or not-pinned object.\nPinning is orthogonal to mutability. An object might be mutable and either pinned (`Pin<&mut T>`) or not (`&mut T`) (i.e., the object can be modified, and either it is pinned in place or can be moved), or immutable and either pinned (`Pin<&T>`) or not (`T`) (i.e., the object can't be modified, and either it can't be moved or can be moved but not modified). Note that `&T` cannot be mutated or moved, but is not pinned because its immovability is only temporary.\n[^inherent]: Permanence is not a fundamental aspect of pinning, it is part of the framing of pinning in Rust and the safety guarantees around it. It would be ok for pinning to be temporary if this could be safely expressed and the temporal scope of pinning could be relied upon by consumers of the pinning guarantees. However, that is not possible with Rust today or with any reasonable extension.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "Pinning"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#pinning-1", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/pinning.md#unpin-7", "text": "Asynchronous Programming in Rust › Pinning › Pinning › `Unpin`\n\nAlthough moving and not moving is how we introduced pinning and is somewhat suggested by the name, `Pin` does not actually tell you much about whether the pointee will actually move or not.\nWhat? Sigh.\nPinning is actually a contract about validity, not about moving. It guarantees that *if an object is address-sensitive, then* its address will not change (and thus addresses derived from it, such as the addresses of its fields, will not change either). Most data in Rust is not address-sensitive. It can be moved around and everything will be ok. `Pin` guarantees that the pointee will be valid with respect to it's address. If the pointee is address-sensitive, then it can't be moved; if it's not address-sensitive, then it doesn't matter whether it is moved.\n`Unpin` is a trait which expresses whether objects are address-sensitive. If an object implements `Unpin`, then it is *not* address-sensitive. If an object is `!Unpin` then it is address-sensitive. Alternatively, if we think of pinning as the act of holding an object in its place, then `Unpin` means it is safe to undo that action and allow the object to be moved.\n`Unpin` is an auto-trait and most types are `Unpin`. Only types which have an `!Unpin` field or which explicitly opt-out are not `Unpin`. You can opt-out by having a `PhantomPinned` field or (if you're using nightly) with `impl !Unpin for ... {}`.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "Pinning", "`Unpin`"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#unpin", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/pinning.md#unpin-8", "text": "Asynchronous Programming in Rust › Pinning › Pinning › `Unpin`\n\nFor types which implement `Unpin`, `Pin` essentially does nothing. `Pin>` and `Pin<&mut T>` can be used just like `Box` and `&mut T`. In fact, for `Unpin` types, the `Pin`ed and regular pointers can be freely-interconverted using `Pin::new` and `Pin::into_inner`. It's worth restating: `Pin<...>` does not guarantee that the pointee will not move, only that the pointee won't move if it is `!Unpin`.\nThe practical implication of the above is that working with `Unpin` types and pinning is much easier than with types which are not `Unpin`, in fact the `Pin` marker has basically no effect on `Unpin` types and pointers to `Unpin` types, and you can basically ignore all the pinning guarantees and requirements.\n`Unpin` should not be understood as a property of an object alone; the only thing `Unpin` changes is how an object interacts with `Pin`. Using an `Unpin` bound outside of the pinning context doesn't affect the compiler's behaviour or what can be done with the object. The only reason to use `Unpin` is in conjunction with pinning, or to propagate the bound to where it is used with pinning.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "Pinning", "`Unpin`"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#unpin", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/pinning.md#pin-9", "text": "Asynchronous Programming in Rust › Pinning › Pinning › `Pin`\n\n`Pin` is a marker type, it is important for type checking, but is compiled away and does not exist at runtime (`Pin` is guaranteed to have the same memory layout and ABI as `Ptr`). It is a wrapper of pointers (such as `Box`), so it behaves like a pointer type, but it does not add an indirection, `Box` and `Pin>` are the same when a program is run. It is better to think of `Pin` as a modifier to the pointer rather than a pointer itself.\n`Pin` means that the pointee of `Ptr` (not `Ptr` itself) is pinned. That is, `Pin` guarantees that the pointee (not the pointer) will remain valid with respect to its address until the pointee is dropped. If the pointee is address-sensitive (i.e., is `!Unpin`), then the pointee will not be moved.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "Pinning", "`Pin`"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#pin", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/pinning.md#pinning-values-10", "text": "Asynchronous Programming in Rust › Pinning › Pinning › Pinning values\n\nObjects are not created pinned. An object starts unpinned (and may be freely moved), it becomes pinned when a pinning pointer is created which points to the object. If the object is `Unpin`, then this is trivial using `Pin::new`, however, if the object is not `Unpin`, then pinning it must ensure that it cannot be moved or invalidated via an alias.\nTo pin an object on the heap, you can create a new pinning `Box` by using `Box::pin`, or convert an existing `Box` into a pinning `Box` using `Box::into_pin`. In either case, you'll end up with `Pin>`. Some other pointers (such as `Arc` and `Rc`) have similar mechanisms. For pointers which don't, or for your own pointer types, you'll need to use `Pin::new_unchecked` to create a pinned pointer[^box-pin]. This is an unsafe function and so the programmer must ensure that `Pin`'s invariants are maintained. That is, that the pointee will, under every circumstance, remain valid until it's destructor is called. There are some subtle details to ensuring this, refer to the function's docs or the below section how pinning works for more.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "Pinning", "Pinning values"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#pinning-values", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/pinning.md#pinning-values-11", "text": "Asynchronous Programming in Rust › Pinning › Pinning › Pinning values\n\n`Box::pin` pins an object to a place in the heap. To pin an object on the stack, you can use the `pin` macro to create and pin a mutable reference (`Pin<&mut T>`)[^not-stack].\nTokio also has a `pin` macro which does the same thing as the std macro and also supports assigning into a variable inside the macro. The futures-rs and pin-utils crates have a `pin_mut` macro which used to be commonly used, but is now deprecated in favor of the std macro.\nYou can also use `Pin::static_ref` and `Pin::static_mut` to pin a static reference.\n[^box-pin]: There is no special treatment for `Box` (or the other std pointers) either in the pinning implementation or the compiler. `Box` uses the unsafe functions in `Pin`'s API to implement `Box::pin`. The safety requirements of `Pin` are satisfied due to the safety guarantees of `Box`.\n[^not-stack]: This is only strictly pinning to the stack in non-async functions. In an async function, all locals are allocated in the async pseudo-stack, so the place being pinned is likely to be stored on the heap as part of the future underlying the async function.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "Pinning", "Pinning values"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#pinning-values", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/pinning.md#using-pinned-types-12", "text": "Asynchronous Programming in Rust › Pinning › Pinning › Using pinned types\n\nIn theory, using pinned pointers is just like using any other pointer type. However, because it is not the most intuitive abstraction, and because it has no language support, using pinned pointers tends to be pretty unergonomic. The most common case for using pinning is when dealing with futures and streams, we'll cover those specifics in more detail below.\nUsing a pinned pointer as an immutably borrowed reference is trivial because of `Pin`'s implementation of `Deref`. You can mostly just treat `Poll>` as `&T`, using an explicit `deref()` if necessary. Likewise, getting a `Pin<&T>` is pretty easy using `as_ref()`.\nThe most common way to work with pinned types is using `Pin<&mut T>` (e.g., in `Future::poll`), however, the easiest way to produce a pinned object is `Box::pin` which gives a `Pin>`. You can convert the latter to the former using `Pin::as_mut`. However, without the language support for reusing references (implicit reborrowing), you have to keep calling `as_mut` rather than reusing the result. E.g. (from the `as_mut` docs),\n```rust,norun\nimpl Type {\n fn method(self: Pin<&mut Self>) {\n // do something\n }\n\n fn call_method_twice(mut self: Pin<&mut Self>) {\n // `method` consumes `self`, so reborrow the `Pin<&mut Self>` via `as_mut`.\n self.as_mut().method();\n self.as_mut().method();\n }\n}\n```", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "Pinning", "Using pinned types"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#using-pinned-types", "has_code": true, "code_tags": ["rust,norun"]}} {"id": "async-book/part-reference/pinning.md#using-pinned-types-13", "text": "Asynchronous Programming in Rust › Pinning › Pinning › Using pinned types\n\nIf you need to access the pinned pointee in some other way, you can do so via `Pin::into_inner_unchecked`. However, this is unsafe and you must be *very* careful about ensuring the safety requirements of `Pin` are respected.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "Pinning", "Using pinned types"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#using-pinned-types", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/pinning.md#how-pinning-works-14", "text": "Asynchronous Programming in Rust › Pinning › Pinning › How pinning works\n\n`Pin` is a simple wrapper struct (aka, a newtype) for pointers. It is enforced to work only on pointers by requiring the `Deref` bound on it's generic parameter to do anything useful, however, this is just for expressing intention, rather than for preserving safety. As with most newtype wrappers, `Pin` exists to express an invariant at compile-time rather than for any runtime effect. Indeed, in most circumstances, `Pin` and the pinning machinery will completely disappear during compilation.\nTo be precise, the invariant expressed by `Pin` is about validity, not just movability. It is also a validity invariant which only applies once a pointer is pinned - before that `Pin` has no effect and makes no requirements on what happens before something is pinned. Once a pointer is pinned, `Pin` requires (and guarantees in safe code) that the pointed-to object will remain valid at the same address in memory until the object's destructor is called.\nFor immutable pointers (e.g., borrowed references), `Pin` has no effect - since the pointee cannot be mutated or replaced, there is no danger of it being invalidated.\nFor a pointer that allows mutation (e.g., `Box` or `&mut`), having direct access to that pointer or access to a mutable reference (`&mut`) to the pointee could allow for mutation or moving the pointee. `Pin` simply does not provide any (non-`unsafe`) way to get direct access to the pointer or a mutable reference. The usual way for a pointer to provide a mutable reference to its pointee is by implementing `DerefMut`, `Pin` only implements `DerefMut` if the pointee is `Unpin`.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "Pinning", "How pinning works"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#how-pinning-works", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/pinning.md#how-pinning-works-15", "text": "Asynchronous Programming in Rust › Pinning › Pinning › How pinning works\n\nThis implementation is incredibly simple! To summarize: `Pin` is a wrapper struct around a pointer which provides only immutable access to the pointee (and mutable access if the pointee is `Unpin`). Everything else is details (and subtle invariants for unsafe code). For convenience, `Pin` provides a facility to convert between `Pin` types (always safe since the pointer cannot escape a `Pin`), etc.\n`Pin` also provides unsafe functions for creating pinned pointers and accessing the underlying data. As with all `unsafe` functions, maintaining the safety invariants is the responsibility of the programmer rather than the compiler. Unfortunately, the safety invariants for pinning are somewhat scattered, in that they are enforced in different places and are hard to describe in a global, unified manner. I won't describe them in detail here and refer you to the docs, but I'll attempt to summarize (see the module docs for a detailed overview):", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "Pinning", "How pinning works"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#how-pinning-works", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/pinning.md#pinning-pointer-types-16", "text": "Asynchronous Programming in Rust › Pinning › Pinning › How pinning works › Pinning pointer types\n\n- Creating a new pinned pointer `new_unchecked`. The programmer must ensure that the pointee is pinned (that is, abides by the pinning invariants). This requirement may be satisfied by the pointer type alone (e.g., in the case of `Box`) or may require participation of the pointee type (e.g., in the case of `&mut`). This includes (but is not limited to):\n - Not moving out of `self` in `Deref` and `DerefMut`.\n - Properly implementing `Drop`, see the drop guarantee.\n - Opting out of `Unpin` (by using `PhantomPinned`) if you require the pinning guarantees.\n - The pointee may not be `#[repr(packed)]`.\n- Accessing the pinned value `into_inner_unchecked`, `get_unchecked_mut`, `map_unchecked`, and `map_unchecked_mut`. It becomes the programmer's responsibility to enforce the pinning guarantees (including not moving the data) from the moment data is accessed until it's destructor runs (note that this scope of responsibility extends beyond the unsafe call and applies whatever happens to the underlying data).\n- Not providing any other way to move data out of a pinned type (which would need an unsafe implementation).", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "Pinning", "How pinning works", "Pinning pointer types"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#pinning-pointer-types", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/pinning.md#pinning-pointer-types-17", "text": "Asynchronous Programming in Rust › Pinning › Pinning › How pinning works › Pinning pointer types\n\nWe said earlier that `Pin` wraps a pointer type. It is common to see `Pin>`, `Pin<&T>`, and `Pin<&mut T>`. Technically, the only requirement of the pinning pointer type is that it implements `Deref`. However, there are no ways to create a `Pin` for any other pointer types other than using unsafe code (via `new_unchecked`). Doing so has requirements on the pointer type to ensure the pinning contract:\n- The pointer's implementations of `Deref` and `DerefMut` must not move out of their pointee.\n- It must not be possible to obtain an `&mut` reference to the pointee at any time after the `Pin` is created, even after the `Pin` has been dropped (this is why you can't safely construct a `Pin<&mut T>` from an `&mut T`). This must remain true via multiple steps or via references (which prevents using `Rc` or `Arc`).\n- The pointer's implementation of `Drop` must not move (or otherwise invalidate) it's pointee. \nSee the `new_unchecked` docs for more detail.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "Pinning", "How pinning works", "Pinning pointer types"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#pinning-pointer-types", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/pinning.md#pinning-and-drop-18", "text": "Asynchronous Programming in Rust › Pinning › Pinning › Pinning and `Drop`\n\nThe pinning contract applies until the pinned object is dropped (technically, that means when its `drop` method returns, not when it is called). This is usually fairly straightforward since `drop` is called automatically when objects are destroyed. If you are doing things manually with an object's lifecycle, you might need to give it some extra thought. If you have an object which is (or might be) pinned and that object is not `Unpin`, then you must call it's `drop` method (using `drop_in_place`) before deallocating or reusing the object's memory or address. See the std docs for details.\nIf you are implementing an address-sensitive type (i.e., one that is `!Unpin`), then you must take extra care with the `Drop` implementation. Even though the self-type in `drop` is `&mut Self`, you must treat the self-type as `Pin<&mut Self>`. In other words, you must ensure the object remains valid until the `drop` function returns. One way to make this explicit in the source code is to follow the following idiom:\n```rust,norun\nimpl Drop for Type {\n fn drop(&mut self) {\n // `new_unchecked` is okay because we know this value is never used\n // again after being dropped.\n inner_drop(unsafe { Pin::new_unchecked(self)});\n\n fn inner_drop(this: Pin<&mut Self>) {\n // Actual drop code goes here.\n }\n }\n}\n```", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "Pinning", "Pinning and `Drop`"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#pinning-and-drop", "has_code": true, "code_tags": ["rust,norun"]}} {"id": "async-book/part-reference/pinning.md#pinning-and-drop-19", "text": "Asynchronous Programming in Rust › Pinning › Pinning › Pinning and `Drop`\n\nNote that the validity requirements will be dependent on the type being implemented. Precisely defining these requirements, especially concerning object destruction is recommended, especially if multiple objects could be involved (e.g., an intrusive linked list). Ensuring correctness here is likely to be interesting!", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "Pinning", "Pinning and `Drop`"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#pinning-and-drop", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/pinning.md#pinned-self-in-methods-20", "text": "Asynchronous Programming in Rust › Pinning › Pinning › Pinned self in methods\n\nCalling methods on pinned types leads to thinking about the self-type in these methods. If the method does not need to mutate `self`, then you can still use `&self` since `Pin<...>` can dereference to a borrowed reference. However, if you need to mutate `self` (and your type is not `Unpin`) then you need to choose between `&mut self` and `self: Pin<&mut Self>` (although pinned pointers can't be implicitly coerced to the latter type, they can be easily converted using `Pin::as_mut`).\nUsing `&mut self` makes the implementation easy, but means the method cannot be called on a pinned object. Using `self: Pin<&mut Self>` means considering pin projection (see the next section) and can only be called on a pinned object. Although this is all a bit confounding, it makes sense intuitively when you remember that pinning is a phased concept - objects start unpinned, and at some point undergo a phase change to become pinned. `&mut self` methods are ones which can be called in the first (unpinned) phase and `self: Pin<&mut Self>` methods are ones which can be called in the second (pinned) phase.\nNote that `drop` takes `&mut self` (even though it might be called in either phase). This is due to a limitation of the language and the desire for backwards compatibility. It requires special treatment in the compiler and comes with safety requirements.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "Pinning", "Pinned self in methods"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#pinned-self-in-methods", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/pinning.md#pinned-fields-structural-pinning-and-pin-projection-21", "text": "Asynchronous Programming in Rust › Pinning › Pinning › Pinned fields, structural pinning, and pin projection\n\nGiven that an object is pinned, what does that tell us about the 'pinned'-ness of its fields? The answer depends on choices made by the implementer of the datatype, there is no universal answer (indeed it can be different for different fields of the same object). \nIf the pinned-ness of an object propagates to a field, we say the field exhibits 'structural pinning' or that pinning is projected with the field. In this case there should be a projection method `fn get_field(self: Pin<&mut Self>) -> Pin<&mut Field>`. If the field is not structurally pinned, then a projection method should have signature `fn get_field(self: Pin<&mut Self>) -> &mut Field`. Implementing either method (or implementing similar code) requires `unsafe` code and either choice has safety implications. Pin-propagation must be consistent, a field must always be structurally pinned or not, it is nearly always unsound for a field to be structurally pinned at some times and not at others.\nPinning should project to a field if the field is an address-sensitive part of the aggregate datatype. That is, if the aggregate being pinned depends on the field being pinned, then pinning must project to that field. For example, if there is a reference from another part of the aggregate into the field, or if there is a self-reference within the field, then pinning must project to the field. On the other hand, for a generic collection, pinning does not need to project to it's contents since the collection does not rely on their behaviour (that's because the collection cannot rely on the implementation of the generic items it contains, so the collection itself cannot rely on the addresses of its items).", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "Pinning", "Pinned fields, structural pinning, and pin projection"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#pinned-fields-structural-pinning-and-pin-projection", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/pinning.md#macros-for-pin-projection-22", "text": "Asynchronous Programming in Rust › Pinning › Pinning › Pinned fields, structural pinning, and pin projection › Macros for pin projection\n\nWhen writing unsafe code, you can only assume that the pinning guarantees apply to the fields of an object which are structurally pinned. On the other hand, you can safely treat non-structurally pinned fields as moveable and not worry about the pinning requirements for them. In particular, a struct can be `Unpin` even if a field is not, as long as that field is always treated as not being structurally pinned.\nIf a field is structurally pinned, then the pinning requirements on the aggregate struct extend to the field. Under no circumstance can code move the contents of the field while the aggregate is pinned (this would always require unsafe code). Structurally pinned fields must be dropped before they are moved (including deallocation) even in the case of panicking, which means care must be taken within the aggregate's `Drop` impl. Furthermore, the aggregate struct cannot be `Unpin` unless all of its structurally-pinned fields are.\nThere are macros available for helping with pin projection.\nThe pin-project crate provides the `#[pin_project]` attribute macro (and the `#[pin]` helper attribute) which implements safe pin projection for you by creating a pinned version of the annotated type which can be accessed using the `project` method on the annotated type.\nPin-project-lite is an alternative using a declarative macro (`pin_project!`) which works in a very similar way to pin-project. Pin-project-lite is lightweight in the sense that it is not a procedural macro and therefore does not add dependences for implementing procedural macros to your project. However, it is less expressive than pin-project and does not give custom error messages. Pin-project-lite is recommended if you want to avoid adding the procedural macro dependencies, and pin-project is recommended otherwise.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "Pinning", "Pinned fields, structural pinning, and pin projection", "Macros for pin projection"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#macros-for-pin-projection", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/pinning.md#macros-for-pin-projection-23", "text": "Asynchronous Programming in Rust › Pinning › Pinning › Pinned fields, structural pinning, and pin projection › Macros for pin projection\n\nPin-utils provides the `unsafe_pinned` macro to help implement pin projection, but the whole crate is deprecated in favor of the above crates and functionality now in std.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "Pinning", "Pinned fields, structural pinning, and pin projection", "Macros for pin projection"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#macros-for-pin-projection", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/pinning.md#assigning-to-a-pinned-pointer-24", "text": "Asynchronous Programming in Rust › Pinning › Pinning › Assigning to a pinned pointer\n\nIt is generally safe to assign into a pinned pointer. Although this can't be done in the usual way (`*p = ...`), it can be done using `Pin::set`. More generally, you can use unsafe code to assign into fields of the pointee.\nUsing `Pin::set` is always safe since the previously pinned pointee will be dropped, fulfilling the pin requirements and the new pointee is not pinned until the move into the pinned place is complete. Assigning into individual fields does not automatically violate the pinning requirements, but care must be taken to ensure that the object as a whole remains valid. For example, if a field is assigned into, then any other fields which reference that field must still be valid with the new object (this is not part of the pinning requirements, but might be part of the object's other invariants).\nCopying one pinned object into another pinned place can only be done in unsafe code, how safety is maintained depends on the individual object. There is no general violation of the pinning requirements - the object being replaced is not moving and nor is the object being copied. However, the validity of the object being replaced may have safety requirements which are usually protected by pinning, but in this case must be established by the programmer. For example, if we have a struct with two fields `a` and `b` where `b` refers to `a`, that reference requires pinning to be remain valid. If such a struct is copied into another place, then the value of `b` must be updated to point to the new `a` rather than the old one.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "Pinning", "Assigning to a pinned pointer"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#assigning-to-a-pinned-pointer", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/pinning.md#pinning-and-async-programming-25", "text": "Asynchronous Programming in Rust › Pinning › Pinning and async programming\n\nHopefully, you can do all you ever want to do with async Rust and never worry about pinning. Sometimes you'll hit a corner case which requires using pinning and if you want to do implement futures, a runtime, or similar things, you'll need to know about pinning. In this section, I'll explain why.\nAsync functions are implemented as futures (see section TODO - this is a summary overview, make sure we explain more deeply and with examples elsewhere). At each await point execution of the function may be paused and during that time the values of live variables must be saved. They essentially become fields of a struct (which is part of an enum). Such variables may refer to other variables which are saved in the future, e.g., consider,\n```rust,norun\nasync fn foo() {\n let a = ...;\n let b = &a;\n bar().await;\n // use b\n}\n```\nThe generated future object here will be something like:\n```rust,norun\nstruct Foo {\n a: A,\n b: &'self A, // Invariant `self.b == &self.a`\n}\n```\n(I'm simplifying a bit, ignoring the state of execution, etc., but the important bit is the variables/fields).\nThis makes intuitive sense, unfortunately `'self` does not exist in Rust. And for good reason! Remember that Rust objects can be moved, so code like the following would be unsound:\n```rust,norun\nlet f1 = Foo { ... }; // f1.b == &f1.a\nlet f2 = f1; // f2.b == &f1.a, but f1 no longer exists since it moved to f2\n```\nNote that this is not just an issue of not being able to name the lifetime, even if we use raw pointers, such code would still be incorrect.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "Pinning and async programming"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#pinning-and-async-programming", "has_code": true, "code_tags": ["rust,norun"]}} {"id": "async-book/part-reference/pinning.md#pinning-and-async-programming-26", "text": "Asynchronous Programming in Rust › Pinning › Pinning and async programming\n\nHowever, if we know that once it is created, then an instance of `Foo` will never move, then everything Just Works. (The compiler has a concept similar to `'self` internally for such cases, as a programmer, we would have to use raw pointers and unsafe code). This concept of not moving is exactly what pinning describes.\nWe see this requirement in the signature of `Future::poll`, where the type of `self` (the future) is `Pin<&mut Self>`. Mostly, when using async/await, the compiler takes care of pinning and unpinning, and as a programmer you don't need to worry about it.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "Pinning and async programming"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#pinning-and-async-programming", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/pinning.md#manual-pinning-27", "text": "Asynchronous Programming in Rust › Pinning › Pinning and async programming › Manual pinning\n\nThere are some places where pinning leaks through the abstraction of async/await. At its root, this is due to the `Pin` in the signature of `Future::poll` and `Stream::poll_next`. When using futures and streams directly (rather than through async/await), we might need to consider pinning to make things work. Some common reasons to need pinned types are:\n- Polling a future or stream - either in application code or when implementing your own future.\n- Using boxed futures. If you're using boxed futures (or streams) and therefore writing out future types rather than using async functions, you'll likely see a lot of `Pin<...>` in those types and need to use `Box::pin` to create the futures.\n- Implementing a future - inside `poll`, `self` is pinned and therefore you need to work with pin projection and/or unsafe code to get mutable access to fields of `self`.\n- Combining futures or streams. This mostly just works, but if you need to take a reference to a future and then poll it (e.g., defining a future outside a loop and using it in `select!` inside the loop), then you will need to pin the reference to the future in order to use the reference like a future.\n- Working with streams - there is currently less abstraction in Rust around streams than futures, so you're more likely to use combinator methods (which don't technically require pinning, but seems to make issues around referencing or creating futures/streams more prevalent) or even `poll` manually than when working with futures.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "Pinning and async programming", "Manual pinning"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#manual-pinning", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/pinning.md#alternatives-and-extensions-28", "text": "Asynchronous Programming in Rust › Pinning › Alternatives and extensions\n\nThis section is for those with a curiosity about the language design around pinning. You absolutely don't need to read this section if you just want to read, understand, and write async programs.\nPinning is difficult to understand and can feel a bit clunky, so people often wonder if there is a better alternative or variation. I'll cover a few alternatives and show why they either don't work or are more complex than you might expect.\nHowever before that, it's important to understand the historical context for pinning. If you are designing a brand new language and want to support async/await, self-references, or immovable types there are certainly better ways to do so than Rust's pinning. However, async/await, futures, and pinning were added to Rust after it's 1.0 release and designed in the context of a strong backwards-compatibility guarantee. Beyond that hard requirement, there was a requirement of wanting to design and implement this feature in a reasonable time frame. Some solutions (e.g., those involving linear types) would require fundamental research, design, and implementation that would realistically be measured in decades when considering the resources and constraints of the Rust project.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "Alternatives and extensions"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#alternatives-and-extensions", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/pinning.md#alternatives-29", "text": "Asynchronous Programming in Rust › Pinning › Alternatives and extensions › Alternatives\n\nFirst, lets consider the class of solutions which make Rust types non-movable by default. Note that this is a significant change to the fundamental semantics of Rust; any solution in this class would likely need significant effort to achieve backwards-compatibility (I won't speculate on if that's even possible for specific solutions, but with techniques like auto-traits, derive attributes, editions, migration tooling, etc., it is possibly possible).\nOne proposal (really, a group of proposals since there are various ways to define the semantics) is to have a `Move` marker trait (similar to `Copy`) which marks objects as movable and all other types would be immovable. In contrast to `Pin`, this is a property of values, not of pointers, so the effect is much more far-reaching, e.g., `let a = b;` would be an error if `b` does not implement `Move`.\nThe fundamental problem with this approach is that pinning today is a phased concept (a place starts unpinned and becomes pinned) and types apply to the whole lifetime of values. (Pinning is also best understood as a property of places rather than values, but types apply to values, whether this is a fundamental problem for any trait-based approach, I don't know). This is explored in these two blog posts: Two Ways Not to Move and Ergonomic Self-Referential Types for Rust.\nFurthermore, any `Move` trait is likely to have problems with backwards-compatibility and lead to 'infectious bounds' (i.e., `Move` or `!Move` would be required in many, many places).", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "Alternatives and extensions", "Alternatives"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#alternatives", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/pinning.md#alternatives-30", "text": "Asynchronous Programming in Rust › Pinning › Alternatives and extensions › Alternatives\n\nAnother proposal is to support move constructors similar to C++. However, this breaks the fundamental invariant of Rust that objects can always be bit-wise moved. That would make Rust much less predictable and therefore make Rust programs more difficult to understand and debug. This is a backwards-incompatible change of the worst kind because it would silently break unsafe code because it changes a fundamental assumption that authors of the code may have made. Furthermore, the design and implementation effort required for such a fundamental change would be huge. On top of those practical issues, it's unclear if it would even work: move constructors could be used to fix-up references in the object being moved, but there might be references to the object being moved from outside the object which could not be fixed up.\nA potential solution of a different kind is the idea of offset references. This is a reference which is relative rather than absolute, i.e., a field which is an offset reference to another field would always point within the same object, even if the object is moved in memory. The issue with offset pointers is that a field must be either an offset pointer or an absolute pointer. But references in async function become fields which sometimes reference memory internal to the future object and sometimes reference memory outside it.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "Alternatives and extensions", "Alternatives"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#alternatives", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/pinning.md#extensions-31", "text": "Asynchronous Programming in Rust › Pinning › Alternatives and extensions › Extensions\n\nThere are multiple proposals for making pinning more powerful and/or easier to work with. These are mostly proposals to make pinning a more first-class part of the language in various ways, rather than a purely library concept (they often include extensions to std as well as the language). I'll cover a few of the more developed ideas, they are related to each other and all have the general goal of improving pinning ergonomics by making creating and using pinned places easier, in particular around structural pinning and `drop`.\nPinned places runs with the idea that pinning is property of places rather than values or types, and adds a `pin`/`pinned` modifier to references similar to `mut`. This integrates with reborrowing and method resolution to improve the ergonomics of method calls with pinned `self`.\n`UnpinCell` extends the pinned places idea to support native pin projection of fields. MinPin is a more minimal (and backwards-compatible) proposal for native pin projection and better `drop` support.\nThe `Overwrite` trait is a proposed trait which makes explicit the distinction between permission to modify a part of an object (`foo.f = ...`) and permission to overwrite the whole object (`*foo = ...`), both of which are currently allowed for all mutable references. The proposal also includes immutable fields. `Overwrite` is a sort-of-replacement for `Unpin` which (together with some of the ideas from pinned places) could improve working with pinning. Unfortunately, although it could be adopted backwards-compatibly, the transition would be a lot more work than for the other extensions.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "Alternatives and extensions", "Extensions"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#extensions", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/pinning.md#references-32", "text": "Asynchronous Programming in Rust › Pinning › References\n\n- std docs source of truth for behaviour and guarantees of `Pin`, etc. Good docs.\n - `Pin`, `Unpin`, `pin` macro\n- RFC 2349 the RFC which proposed pinning. The stabilized API is a bit different from the one proposed here, but there is a good explanation of the core concept and rationale in the RFC.\n- Some blog posts or other resources explaining pinning:\n - Pin by WithoutBoats (the primary designer of pinning) on the history, context, and rationale of pinning, and why it is a difficult concept.\n - Why is std::pin::Pin so weird? deep dive into the rationale of the pinning design and using pinning in practice.\n - Pin, Unpin, and why Rust needs them\n - Pinning section of async/await\n - Pin and suffering thorough blog post in a very conversational style about understanding async code and pinning with lots of examples.\n - The book *Rust for Rustaceans* by Jon Gjengset has an excellent description of why pinning is necessary for the implementation of async/await and how pinning works.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Pinning", "heading_path": ["Pinning", "References"], "path": "part-reference/pinning.md", "url": "https://rust-lang.github.io/async-book/part-reference/pinning.html#references", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/structured.md#structured-concurrency-0", "text": "Asynchronous Programming in Rust › Structured Concurrency\n\nAuthors note (TODO): we might want to discuss some parts of this chapter much earlier in the book, in particularly as design principles (first intro is in guide/intro). However, in the interests of better understanding the topic and getting something written down, I'm starting with a separate chapter. It's also still a bit rough.\n(Note: the first few sections are talking about the abstract concept of structured concurrency and is not specific to Rust or async programming (c.f., synchronous concurrent programming with threads). I use 'task' to mean any thread or async task or other similar concurrency primitive).\nStructured concurrency is a philosophy for designing concurrent programs. For programs to fully adhere to the principals of structured concurrency requires certain language features and libraries, but many of the benefits are available by following the philosophy without such features. Structured concurrency is independent of language and concurrency primitives (threads vs async, etc.). Many people have found the ideas from structured concurrency to be useful when programming with async Rust.\nThe essential idea of structured concurrency is that tasks are organised into a tree. Child tasks start after their parents and always finish before them. This allows results and errors to always be passed back to parent tasks, and requires that cancellation of parents is always propagated to child tasks. Primarily, temporal scope follows lexical scope, which means that a task should not outlive the function or block where it is created. However, this is not a requirement of structured concurrency as long as longer-lived tasks are reified in the program in some way (typically by using an object to represent the temporal scope of a child task within its parent task).\nTODO diagram\nStructured concurrency is named by analogy to structured programming, which is the idea that control flow should be structured using functions, loops, etc., rather than arbitrary jumps (`goto`).", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Structured concurrency", "heading_path": ["Structured Concurrency"], "path": "part-reference/structured.md", "url": "https://rust-lang.github.io/async-book/part-reference/structured.html#structured-concurrency", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/structured.md#structured-concurrency-1", "text": "Asynchronous Programming in Rust › Structured Concurrency\n\nBefore we consider structured concurrency, it's helpful to reflect on the sense in which common concurrent designs are unstructured. A typical pattern is that a task is started using some kind of spawning statement. That task then runs to completion concurrently with other tasks in the system (including the task which spawned it). There is no constraint on which task finishes first. The program is essentially just a bag of tasks which live independently and might terminate at any time. Any communication or synchronization of the tasks is ad hoc, and the programmer cannot assume that any other task will still be running.\nThe practical downsides of unstructured concurrency are that returning results from a task must happen in an extra-linguistic fashion with no language-level guarantees around when or how this happens. Errors may go uncaught because languages' error handling mechanisms cannot be applied to the unconstrained control flow of unstructured concurrency. We also have no guarantees about the relative state of tasks - any task may be running, terminated successfully or with an error, or externally cancelled, independent of the state of any others[^join]. All this makes concurrent programs difficult to understand and maintain. This lack of structure is one reason why concurrent programming is considered categorically more difficult than sequential programming.\nIt's worth noting that structured concurrency is a programming discipline which imposes restrictions on your program. Just like functions and loops are less flexible than goto, structured concurrency is less flexible than just spawning tasks. However, as with structured programming the costs of structured concurrency in flexibility are outweighed by the gains in predictability.\n[^join]: Using join handles mitigates these downsides somewhat, but is an ad hoc mechanism with no reliable guarantees. To get the full benefits of structured concurrency you have to be meticulous about always using them, as well as handling cancellation and errors properly. This is difficult without language or library support; we'll discuss this a bit more below.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Structured concurrency", "heading_path": ["Structured Concurrency"], "path": "part-reference/structured.md", "url": "https://rust-lang.github.io/async-book/part-reference/structured.html#structured-concurrency", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/structured.md#principles-of-structured-concurrency-2", "text": "Asynchronous Programming in Rust › Structured Concurrency › Principles of structured concurrency\n\nThe key idea of structured concurrency is that all tasks (or threads or whatever) are organized as a tree. I.e., each task (except the main task which is the root) has a single parent and there are no cycles of parents. A child task is started by its parent[^start-parent] and must *always* finish executing before its parent. There are no constraints between siblings. The parent of a task may not change.\nWhen reasoning about programs which implement structured concurrency, the key new fact is that if a task is live, then all of its ancestor tasks must also be live. This doesn't guarantee they are in a good state - they might be in the process of shutting down or handling an error, but they must be running in some form. This means that for any task (except the root task), there is always a live task to send results or errors to. Indeed, the ideal approach is that the language's error handling is extended so that errors are always propagated to the parent task. In Rust, this should apply to both returning `Result::Err` and to panicking.\nFurthermore, the lifetime of child tasks can be represented in the parent task. In the common case, the lifetime of a task (its temporal scope) is tied to the lexical scope in which it is started. For example, all tasks started within a function should complete before the function returns. This is an extremely powerful reasoning tool. Of course, this is too restrictive for all cases, and so the temporal scope of tasks can extend beyond a lexical scope by using an object in the program (often called a 'scope' or 'nursery'). Such an object can be passed or stored, and thus have an arbitrary lifetime. We still have an important reasoning tool: the tasks tied to that object cannot outlive it (in Rust this property lets us integrate tasks with the lifetime system).", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Structured concurrency", "heading_path": ["Structured Concurrency", "Principles of structured concurrency"], "path": "part-reference/structured.md", "url": "https://rust-lang.github.io/async-book/part-reference/structured.html#principles-of-structured-concurrency", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/structured.md#principles-of-structured-concurrency-3", "text": "Asynchronous Programming in Rust › Structured Concurrency › Principles of structured concurrency\n\nThe above leads to another benefit of structured concurrency: it lets us reason about resource management across multiple tasks. Cleanup code is called when a resource will no longer be used (e.g., closing a file handle). In sequential code, the problem of when to call cleanup code is solved by ensuring destructors are called when an object goes out of scope. However, in concurrent code, an object might still be in use by another task and so when to clean up is unclear (reference counting or garbage collection are solutions in many cases, but make reasoning about the lifetimes of objects difficult which can lead to errors, and also has runtime overheads).\nThe principle of a parent task outliving it's children has an important implication for cancellation: if a task is cancelled, then all its child tasks must be cancelled, and their cancellation must complete before the parent's cancellation completes. That in turn has implications for how cancellation can be implemented in a structurally concurrent system.\nIf a task completes early due to an error (in Rust, this might mean a panic, as well as an early return), then before returning the task must wait for all its child tasks to complete. In practice, an early return must trigger cancellation of child tasks. This is analogous to panicking in Rust: panicking triggers destructors in the current scope before walking up the stack, calling destructors in each scope until the program terminates or the panic is caught. Under structural concurrency, an early return must trigger cancellation of child tasks (and thus cleanup of objects in those tasks) and walks down the tree of tasks cancelling all (transitive) children.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Structured concurrency", "heading_path": ["Structured Concurrency", "Principles of structured concurrency"], "path": "part-reference/structured.md", "url": "https://rust-lang.github.io/async-book/part-reference/structured.html#principles-of-structured-concurrency", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/structured.md#principles-of-structured-concurrency-4", "text": "Asynchronous Programming in Rust › Structured Concurrency › Principles of structured concurrency\n\nSome designs work very naturally under structured concurrency (e.g., worker tasks with a single job to complete), while others don't fit so well. Generally these patterns are ones where not being tied to a specific task is a feature, e.g., worker pools or background threads. Even using these patterns, the tasks usually shouldn't outlive the whole program and so there is always one task which can be the parent.\n[^start-parent]: This is not actually a hard requirement for structured concurrency. If the temporal scope of a task can be represented in the program and passed between tasks, then a child task can be started by one task but have another as its parent.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Structured concurrency", "heading_path": ["Structured Concurrency", "Principles of structured concurrency"], "path": "part-reference/structured.md", "url": "https://rust-lang.github.io/async-book/part-reference/structured.html#principles-of-structured-concurrency", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/structured.md#implementing-structured-concurrency-5", "text": "Asynchronous Programming in Rust › Structured Concurrency › Principles of structured concurrency › Implementing structured concurrency\n\nThe exemplar implementation of structured concurrency is the Python Trio library. Trio is a general purpose library for async programming and IO designed around the concepts of structured concurrency. Trio programs use the `async with` construct to define a lexical scope for spawning tasks. Spawned tasks are associated with a nursery object (which is somewhat like a Scope in Rust). The lifetime of a task is tied to the dynamic temporal scope of its nursery, and in the common case, the lexical scope of an `async with` block. This enforces the parent/child relationship between tasks and thus the tree-invariant of structured concurrency.\nError handling uses Python exceptions which are automatically propagated to parent tasks.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Structured concurrency", "heading_path": ["Structured Concurrency", "Principles of structured concurrency", "Implementing structured concurrency"], "path": "part-reference/structured.md", "url": "https://rust-lang.github.io/async-book/part-reference/structured.html#implementing-structured-concurrency", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/structured.md#partially-structured-concurrency-6", "text": "Asynchronous Programming in Rust › Structured Concurrency › Principles of structured concurrency › Partially structured concurrency\n\nLike many programming techniques, the full benefits of structured concurrency come from *only* using it. If all concurrency is structured, then it makes it much easier to reason about the behaviour of the whole program. However, that has requirements on a language which are not easily met; it is easy enough to do unstructured concurrency in Rust, for example. However, even applying the principles of structured concurrency selectively, or thinking in terms of structured concurrency can be useful.\nOne can use structured concurrency as a design discipline. When designing a program, always consider and document the parent-child relationships between tasks and ensure that a child task terminates before it's parent. This is usually fairly easy under normal execution, but can be difficult in the face of cancellation and panics.\nAnother element of structured concurrency which is fairly easy to adopt is to always propagate errors to the parent task. Just like regular error handling, the best thing to do might be to ignore the error, but this should be explicit in the code of the parent task.\nAnother programming discipline to learn from structured concurrency is to cancel all child tasks in the event of cancelling a parent task. This makes the structural concurrency guarantees much more reliable and makes cancellation in general easier to reason about.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Structured concurrency", "heading_path": ["Structured Concurrency", "Principles of structured concurrency", "Partially structured concurrency"], "path": "part-reference/structured.md", "url": "https://rust-lang.github.io/async-book/part-reference/structured.html#partially-structured-concurrency", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/structured.md#practical-structured-concurrency-with-async-rust-7", "text": "Asynchronous Programming in Rust › Structured Concurrency › Practical structured concurrency with async Rust\n\nConcurrency in Rust (whether async or using threads) is inherently unstructured. Tasks can be arbitrarily spawned, errors and panics on other tasks can be ignored, and cancellation is usually instantaneous and does not propagate to other tasks (see below for why these issues can't be easily solved). However, there are several ways you can get some of the benefits of structured concurrency in your programs:\n- Design your programs at a high level in accordance with structured concurrency.\n- Stick to structured concurrency idioms where possible (and avoid unstructured idioms).\n- Use crates to make structured concurrency more ergonomic and reliable.\nOne of the trickiest issues with using structured concurrency with Rust is propagating cancellation to child futures/tasks. If you're using futures and composing them concurrently, then this happens naturally if abruptly (dropping a future drops any futures it owns, cancelling them). However, when a task is dropped, there is no opportunity to send a signal to tasks it has spawned (at least not with Tokio[^join_handle]).\nThe implication of this is that you can only assume a weaker invariant than with 'real' structured concurrency: rather than being able to assume that a parent task is always alive, you can only assume that the parent is always alive unless it has been cancelled or it has panicked. While this is sub-optimal, it can still simplify programming because you never have to handle the case of having no parent to handle some result *under normal execution*.\nTODO\n- ownership/lifetimes naturally leading to sc\n- reasoning about resources\n[^join_handle]: The semantics of Tokio's `JoinHandle` is that if the handle is dropped, then the underlying task is 'released' (c.f., dropped), i.e., the result of the child task is not handled by any other task.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Structured concurrency", "heading_path": ["Structured Concurrency", "Practical structured concurrency with async Rust"], "path": "part-reference/structured.md", "url": "https://rust-lang.github.io/async-book/part-reference/structured.html#practical-structured-concurrency-with-async-rust", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/structured.md#applying-structured-concurrency-to-the-design-of-async-programs-8", "text": "Asynchronous Programming in Rust › Structured Concurrency › Practical structured concurrency with async Rust › Applying structured concurrency to the design of async programs\n\nIn terms of designing programs, applying structured concurrency has a few implications:\n- Organising the concurrency of a program in a tree structure, i.e., thinking in terms of parent and child tasks.\n- Temporal scope should follow lexical scope where possible, or in concrete terms a function shouldn't return (including early returns and panics) until any tasks launched in the function are complete.\n- Data generally flows from child tasks to parent tasks. Of course, some data will flow from parents to children or in other ways, but primarily, tasks pass the results of their work to their parent tasks for further processing. This includes errors, so parent tasks should handle the errors of their children.\nIf you're writing a library and want to use structured concurrency (or you want the library to be usable in a concurrent-structured program), then it is important that encapsulation of the library component includes temporal encapsulation. I.e., it doesn't start tasks which keep running beyond the API functions returning.\nSince Rust can't enforce the rules of structured concurrency, it's important to be aware of, and to document, in which ways the program (or component) is structured and where it violates the structured concurrency discipline.\nOne useful compromise pattern is to only allow unstructured concurrency at the highest level of abstraction, and only for tasks spawned from the outer-most functions of the main task (ideally only from the `main` function, but programs often have some setup or configuration code which means that the logical 'top level' of a program is actually a few functions deep). Under such a pattern, a bunch of tasks are spawned from `main`, usually with distinct responsibilities and limited interaction between each other. These tasks might be restarted, new tasks started by any other task, or have a limited lifetime tied to clients or similar, i.e., they are concurrent-unstructured. Within each of these tasks, structured concurrency is rigorously applied.\nTODO why is this useful?", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Structured concurrency", "heading_path": ["Structured Concurrency", "Practical structured concurrency with async Rust", "Applying structured concurrency to the design of async programs"], "path": "part-reference/structured.md", "url": "https://rust-lang.github.io/async-book/part-reference/structured.html#applying-structured-concurrency-to-the-design-of-async-programs", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/structured.md#applying-structured-concurrency-to-the-design-of-async-programs-9", "text": "Asynchronous Programming in Rust › Structured Concurrency › Practical structured concurrency with async Rust › Applying structured concurrency to the design of async programs\n\nTODO would be great to have a case study here.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Structured concurrency", "heading_path": ["Structured Concurrency", "Practical structured concurrency with async Rust", "Applying structured concurrency to the design of async programs"], "path": "part-reference/structured.md", "url": "https://rust-lang.github.io/async-book/part-reference/structured.html#applying-structured-concurrency-to-the-design-of-async-programs", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/structured.md#structured-and-unstructured-idioms-10", "text": "Asynchronous Programming in Rust › Structured Concurrency › Practical structured concurrency with async Rust › Structured and unstructured idioms\n\nThis subsection covers a grab-bag of idioms which work well with a structured approach to concurrency, and a few which make structuring concurrency more difficult.\nThe easiest way to follow structured concurrency is to use futures and concurrent composition rather than tasks and spawning. If you need tasks for parallelism, then you will need to use `JoinHandle`s or `JoinSet`s. You must take care that child tasks can clean up properly if the parent task panics or is cancelled. Handles must be checked for errors to ensure errors in child tasks are properly handled.\nOne way to work around the lack of cancellation propagation is to avoid abruptly cancelling (dropping) any task which may have children. Instead use a signal (e.g., a cancellation token) so that the task can cancel it's children before terminating. Unfortunately this is incompatible with `select`.\nTo handle shutting down a program (or component), use an explicit shutdown method rather than dropping the component, so that the shutdown function can wait for child tasks to terminate or cancel them (since `drop` cannot be async).\nA few idioms do not play well with structured concurrency:\n- Spawning tasks without awaiting their completion via a join handle, or dropping those join handles.\n- Select or race macros/functions. These are not inherently structured, but since they abruptly cancel futures, it's a common source of unstructured cancellation.\n- Worker tasks or pools. For async tasks the overheads of starting/shutting down tasks is so low that there is likely to be very little benefit of using a pool of tasks rather than a pool of 'data', e.g., a connection pool.\n- Data with no clear ownership structure - this isn't necessarily in contradiction with structured concurrency, but often leads to design issues.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Structured concurrency", "heading_path": ["Structured Concurrency", "Practical structured concurrency with async Rust", "Structured and unstructured idioms"], "path": "part-reference/structured.md", "url": "https://rust-lang.github.io/async-book/part-reference/structured.html#structured-and-unstructured-idioms", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/structured.md#crates-for-structured-concurrency-11", "text": "Asynchronous Programming in Rust › Structured Concurrency › Practical structured concurrency with async Rust › Crates for structured concurrency\n\nTODO\n- crates: moro, async-nursery\n- futures-concurrency", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Structured concurrency", "heading_path": ["Structured Concurrency", "Practical structured concurrency with async Rust", "Crates for structured concurrency"], "path": "part-reference/structured.md", "url": "https://rust-lang.github.io/async-book/part-reference/structured.html#crates-for-structured-concurrency", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/structured.md#related-topics-12", "text": "Asynchronous Programming in Rust › Structured Concurrency › Related topics\n\nThis section is not necessary to know to use structured concurrency with async Rust, but is useful context included for the curious.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Structured concurrency", "heading_path": ["Structured Concurrency", "Related topics"], "path": "part-reference/structured.md", "url": "https://rust-lang.github.io/async-book/part-reference/structured.html#related-topics", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/structured.md#scoped-threads-13", "text": "Asynchronous Programming in Rust › Structured Concurrency › Related topics › Scoped threads\n\nStructured concurrency with Rust threads works pretty well. Although you can't prevent spawning threads with unscoped lifetime, this is easy to avoid. Instead, restrict yourself to using scoped threads, see the `scope` function docs for how. Using scoped threads limits child lifetimes and automatically propagates panics back to the parent thread. The parent thread must check the results of child threads to handle errors though. You can even pass around the `Scope` object like a Trio nursery. Cancellation is not usually an issue for Rust threads, but if you do make use of thread cancellation, you'll have to integrate that with scoped threads manually.\nSpecific to Rust, scoped threads allow child threads to borrow data from the parent thread, something not possible with concurrent-unstructured threads. This can be very useful and shows how well structured concurrency and Rust-ownership-style resource management can work together.", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Structured concurrency", "heading_path": ["Structured Concurrency", "Related topics", "Scoped threads"], "path": "part-reference/structured.md", "url": "https://rust-lang.github.io/async-book/part-reference/structured.html#scoped-threads", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/structured.md#async-drop-and-scoped-tasks-14", "text": "Asynchronous Programming in Rust › Structured Concurrency › Related topics › Async drop and scoped tasks\n\nIn Rust, destructors (`drop`) are used to ensure resources are cleaned up when an object's lifetime ends. Since futures are just objects, their destructor would be an obvious place to ensure cancellation of child futures. However, in an async program it is very often desirable for cleanup actions to be asynchronous (not doing so can block other tasks). Unfortunately Rust does not currently support asynchronous destructors (async drop). There is ongoing work to support them, but it is difficult for a number of reasons, including that an object with an async destructor might be dropped from non-async context, and that since calling `drop` is implicit, there is nowhere to write an explicit `await`.\nGiven how useful scoped threads are (both in general and for structured concurrency), another good question is why there is no similar construct for async programming ('scoped tasks')? TODO answer this", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Structured concurrency", "heading_path": ["Structured Concurrency", "Related topics", "Async drop and scoped tasks"], "path": "part-reference/structured.md", "url": "https://rust-lang.github.io/async-book/part-reference/structured.html#async-drop-and-scoped-tasks", "has_code": false, "code_tags": []}} {"id": "async-book/part-reference/structured.md#references-15", "text": "Asynchronous Programming in Rust › Structured Concurrency › Related topics › References\n\nIf you're interested, here are some good blog posts for further reading:\n- Structured Concurrency\n- Tree-structured concurrency", "metadata": {"book": "async-book", "book_title": "Asynchronous Programming in Rust", "part": "Part 2: reference", "chapter": "Structured concurrency", "heading_path": ["Structured Concurrency", "Related topics", "References"], "path": "part-reference/structured.md", "url": "https://rust-lang.github.io/async-book/part-reference/structured.html#references", "has_code": false, "code_tags": []}} {"id": "book/title-page.md#the-rust-programming-language-0", "text": "The Rust Programming Language › The Rust Programming Language\n\n_by Steve Klabnik, Carol Nichols, and Chris Krycho, with contributions from the\nRust Community_\nThis version of the text assumes you’re using Rust 1.97.0 (released 2026-07-09)\nor later with `edition = \"2024\"` in the *Cargo.toml* file of all projects to\nconfigure them to use Rust 2024 Edition idioms. See the “Installation” section\nof Chapter 1 for instructions on installing or\nupdating Rust, and see Appendix E for information\non editions.\nThe HTML format is available online at\nhttps://doc.rust-lang.org/stable/book/\nand offline with installations of Rust made with `rustup`; run `rustup doc\n--book` to open.\nSeveral community [translations] are also available.\nThis text is available in paperback and ebook format from No Starch\nPress.\n**🚨 Want a more interactive learning experience? Try out a different version\nof the Rust Book, featuring: quizzes, highlighting, visualizations, and\nmore**: ", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "The Rust Programming Language", "heading_path": ["The Rust Programming Language"], "path": "title-page.md", "url": "https://doc.rust-lang.org/book/title-page.html#the-rust-programming-language", "has_code": false, "code_tags": []}} {"id": "book/foreword.md#foreword-0", "text": "The Rust Programming Language › Foreword\n\nThe Rust programming language has come a long way in a few short years, from\nits creation and incubation by a small and nascent community of enthusiasts, to\nbecoming one of the most loved and in-demand programming languages in the\nworld. Looking back, it was inevitable that the power and promise of Rust would\nturn heads and gain a foothold in systems programming. What was not inevitable\nwas the global growth in interest and innovation that permeated through open\nsource communities and catalyzed wide-scale adoption across industries.\nAt this point in time, it is easy to point to the wonderful features that Rust\nhas to offer to explain this explosion in interest and adoption. Who doesn’t\nwant memory safety, *and* fast performance, *and* a friendly compiler, *and*\ngreat tooling, among a host of other wonderful features? The Rust language you\nsee today combines years of research in systems programming with the practical\nwisdom of a vibrant and passionate community. This language was designed with\npurpose and crafted with care, offering developers a tool that makes it easier\nto write safe, fast, and reliable code.\nBut what makes Rust truly special is its roots in empowering you, the user, to\nachieve your goals. This is a language that wants you to succeed, and the\nprinciple of empowerment runs through the core of the community that builds,\nmaintains, and advocates for this language. Since the previous edition of this\ndefinitive text, Rust has further developed into a truly global and trusted\nlanguage. The Rust Project is now robustly supported by the Rust Foundation,\nwhich also invests in key initiatives to ensure that Rust is secure, stable,\nand sustainable.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Foreword", "heading_path": ["Foreword"], "path": "foreword.md", "url": "https://doc.rust-lang.org/book/foreword.html#foreword", "has_code": false, "code_tags": []}} {"id": "book/foreword.md#foreword-1", "text": "The Rust Programming Language › Foreword\n\nThis edition of *The Rust Programming Language* is a comprehensive update,\nreflecting the language’s evolution over the years and providing valuable new\ninformation. But it is not just a guide to syntax and libraries—it’s an\ninvitation to join a community that values quality, performance, and thoughtful\ndesign. Whether you’re a seasoned developer looking to explore Rust for the\nfirst time or an experienced Rustacean looking to refine your skills, this\nedition offers something for everyone.\nThe Rust journey has been one of collaboration, learning, and iteration. The\ngrowth of the language and its ecosystem is a direct reflection of the vibrant,\ndiverse community behind it. The contributions of thousands of developers, from\ncore language designers to casual contributors, are what make Rust such a\nunique and powerful tool. By picking up this book, you’re not just learning a\nnew programming language—you’re joining a movement to make software better,\nsafer, and more enjoyable to work with.\nWelcome to the Rust community!\n- Bec Rumbul, Executive Director of the Rust Foundation", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Foreword", "heading_path": ["Foreword"], "path": "foreword.md", "url": "https://doc.rust-lang.org/book/foreword.html#foreword", "has_code": false, "code_tags": []}} {"id": "book/ch00-00-introduction.md#introduction-0", "text": "The Rust Programming Language › Introduction\n\nNote: This edition of the book is the same as The Rust Programming\nLanguage available in print and ebook format from No Starch\nPress.\nWelcome to _The Rust Programming Language_, an introductory book about Rust.\nThe Rust programming language helps you write faster, more reliable software.\nHigh-level ergonomics and low-level control are often at odds in programming\nlanguage design; Rust challenges that conflict. Through balancing powerful\ntechnical capacity and a great developer experience, Rust gives you the option\nto control low-level details (such as memory usage) without all the hassle\ntraditionally associated with such control.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Introduction", "heading_path": ["Introduction"], "path": "ch00-00-introduction.md", "url": "https://doc.rust-lang.org/book/ch00-00-introduction.html#introduction", "has_code": false, "code_tags": []}} {"id": "book/ch00-00-introduction.md#who-rust-is-for-1", "text": "The Rust Programming Language › Introduction › Who Rust Is For\n\nRust is ideal for many people for a variety of reasons. Let’s look at a few of\nthe most important groups.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Introduction", "heading_path": ["Introduction", "Who Rust Is For"], "path": "ch00-00-introduction.md", "url": "https://doc.rust-lang.org/book/ch00-00-introduction.html#who-rust-is-for", "has_code": false, "code_tags": []}} {"id": "book/ch00-00-introduction.md#teams-of-developers-2", "text": "The Rust Programming Language › Introduction › Who Rust Is For › Teams of Developers\n\nRust is proving to be a productive tool for collaborating among large teams of\ndevelopers with varying levels of systems programming knowledge. Low-level code\nis prone to various subtle bugs, which in most other languages can only be\ncaught through extensive testing and careful code review by experienced\ndevelopers. In Rust, the compiler plays a gatekeeper role by refusing to\ncompile code with these elusive bugs, including concurrency bugs. By working\nalongside the compiler, the team can spend its time focusing on the program’s\nlogic rather than chasing down bugs.\nRust also brings contemporary developer tools to the systems programming world:\n- Cargo, the included dependency manager and build tool, makes adding,\n compiling, and managing dependencies painless and consistent across the Rust\n ecosystem.\n- The `rustfmt` formatting tool ensures a consistent coding style across\n developers.\n- The Rust Language Server powers integrated development environment (IDE)\n integration for code completion and inline error messages.\nBy using these and other tools in the Rust ecosystem, developers can be\nproductive while writing systems-level code.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Introduction", "heading_path": ["Introduction", "Who Rust Is For", "Teams of Developers"], "path": "ch00-00-introduction.md", "url": "https://doc.rust-lang.org/book/ch00-00-introduction.html#teams-of-developers", "has_code": false, "code_tags": []}} {"id": "book/ch00-00-introduction.md#students-3", "text": "The Rust Programming Language › Introduction › Who Rust Is For › Students\n\nRust is for students and those who are interested in learning about systems\nconcepts. Using Rust, many people have learned about topics like operating\nsystems development. The community is very welcoming and happy to answer\nstudents’ questions. Through efforts such as this book, the Rust teams want to\nmake systems concepts more accessible to more people, especially those new to\nprogramming.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Introduction", "heading_path": ["Introduction", "Who Rust Is For", "Students"], "path": "ch00-00-introduction.md", "url": "https://doc.rust-lang.org/book/ch00-00-introduction.html#students", "has_code": false, "code_tags": []}} {"id": "book/ch00-00-introduction.md#companies-4", "text": "The Rust Programming Language › Introduction › Who Rust Is For › Companies\n\nHundreds of companies, large and small, use Rust in production for a variety of\ntasks, including command line tools, web services, DevOps tooling, embedded\ndevices, audio and video analysis and transcoding, cryptocurrencies,\nbioinformatics, search engines, Internet of Things applications, machine\nlearning, and even major parts of the Firefox web browser.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Introduction", "heading_path": ["Introduction", "Who Rust Is For", "Companies"], "path": "ch00-00-introduction.md", "url": "https://doc.rust-lang.org/book/ch00-00-introduction.html#companies", "has_code": false, "code_tags": []}} {"id": "book/ch00-00-introduction.md#open-source-developers-5", "text": "The Rust Programming Language › Introduction › Who Rust Is For › Open Source Developers\n\nRust is for people who want to build the Rust programming language, community,\ndeveloper tools, and libraries. We’d love to have you contribute to the Rust\nlanguage.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Introduction", "heading_path": ["Introduction", "Who Rust Is For", "Open Source Developers"], "path": "ch00-00-introduction.md", "url": "https://doc.rust-lang.org/book/ch00-00-introduction.html#open-source-developers", "has_code": false, "code_tags": []}} {"id": "book/ch00-00-introduction.md#people-who-value-speed-and-stability-6", "text": "The Rust Programming Language › Introduction › Who Rust Is For › People Who Value Speed and Stability\n\nRust is for people who crave speed and stability in a language. By speed, we\nmean both how quickly Rust code can run and the speed at which Rust lets you\nwrite programs. The Rust compiler’s checks ensure stability through feature\nadditions and refactoring. This is in contrast to the brittle legacy code in\nlanguages without these checks, which developers are often afraid to modify. By\nstriving for zero-cost abstractions—higher-level features that compile to\nlower-level code as fast as code written manually—Rust endeavors to make safe\ncode be fast code as well.\nThe Rust language hopes to support many other users as well; those mentioned\nhere are merely some of the biggest stakeholders. Overall, Rust’s greatest\nambition is to eliminate the trade-offs that programmers have accepted for\ndecades by providing safety _and_ productivity, speed _and_ ergonomics. Give\nRust a try, and see if its choices work for you.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Introduction", "heading_path": ["Introduction", "Who Rust Is For", "People Who Value Speed and Stability"], "path": "ch00-00-introduction.md", "url": "https://doc.rust-lang.org/book/ch00-00-introduction.html#people-who-value-speed-and-stability", "has_code": false, "code_tags": []}} {"id": "book/ch00-00-introduction.md#who-this-book-is-for-7", "text": "The Rust Programming Language › Introduction › Who This Book Is For\n\nThis book assumes that you’ve written code in another programming language, but\nit doesn’t make any assumptions about which one. We’ve tried to make the\nmaterial broadly accessible to those from a wide variety of programming\nbackgrounds. We don’t spend a lot of time talking about what programming _is_\nor how to think about it. If you’re entirely new to programming, you would be\nbetter served by reading a book that specifically provides an introduction to\nprogramming.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Introduction", "heading_path": ["Introduction", "Who This Book Is For"], "path": "ch00-00-introduction.md", "url": "https://doc.rust-lang.org/book/ch00-00-introduction.html#who-this-book-is-for", "has_code": false, "code_tags": []}} {"id": "book/ch00-00-introduction.md#how-to-use-this-book-8", "text": "The Rust Programming Language › Introduction › How to Use This Book\n\nIn general, this book assumes that you’re reading it in sequence from front to\nback. Later chapters build on concepts in earlier chapters, and earlier\nchapters might not delve into details on a particular topic but will revisit\nthe topic in a later chapter.\nYou’ll find two kinds of chapters in this book: concept chapters and project\nchapters. In concept chapters, you’ll learn about an aspect of Rust. In project\nchapters, we’ll build small programs together, applying what you’ve learned so\nfar. Chapter 2, Chapter 12, and Chapter 21 are project chapters; the rest are\nconcept chapters.\n**Chapter 1** explains how to install Rust, how to write a “Hello, world!”\nprogram, and how to use Cargo, Rust’s package manager and build tool. **Chapter\n2** is a hands-on introduction to writing a program in Rust, having you build\nup a number-guessing game. Here, we cover concepts at a high level, and later\nchapters will provide additional detail. If you want to get your hands dirty\nright away, Chapter 2 is the place for that. If you’re a particularly\nmeticulous learner who prefers to learn every detail before moving on to the\nnext, you might want to skip Chapter 2 and go straight to **Chapter 3**, which\ncovers Rust features that are similar to those of other programming languages;\nthen, you can return to Chapter 2 when you’d like to work on a project applying\nthe details you’ve learned.\nIn **Chapter 4**, you’ll learn about Rust’s ownership system. **Chapter 5**\ndiscusses structs and methods. **Chapter 6** covers enums, `match` expressions,\nand the `if let` and `let...else` control flow constructs. You’ll use structs\nand enums to make custom types.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Introduction", "heading_path": ["Introduction", "How to Use This Book"], "path": "ch00-00-introduction.md", "url": "https://doc.rust-lang.org/book/ch00-00-introduction.html#how-to-use-this-book", "has_code": false, "code_tags": []}} {"id": "book/ch00-00-introduction.md#how-to-use-this-book-9", "text": "The Rust Programming Language › Introduction › How to Use This Book\n\nIn **Chapter 7**, you’ll learn about Rust’s module system and about privacy\nrules for organizing your code and its public application programming interface\n(API). **Chapter 8** discusses some common collection data structures that the\nstandard library provides: vectors, strings, and hash maps. **Chapter 9**\nexplores Rust’s error-handling philosophy and techniques.\n**Chapter 10** digs into generics, traits, and lifetimes, which give you the\npower to define code that applies to multiple types. **Chapter 11** is all\nabout testing, which even with Rust’s safety guarantees is necessary to ensure\nthat your program’s logic is correct. In **Chapter 12**, we’ll build our own\nimplementation of a subset of functionality from the `grep` command line tool\nthat searches for text within files. For this, we’ll use many of the concepts\nwe discussed in the previous chapters.\n**Chapter 13** explores closures and iterators: features of Rust that come from\nfunctional programming languages. In **Chapter 14**, we’ll examine Cargo in\nmore depth and talk about best practices for sharing your libraries with\nothers. **Chapter 15** discusses smart pointers that the standard library\nprovides and the traits that enable their functionality.\nIn **Chapter 16**, we’ll walk through different models of concurrent\nprogramming and talk about how Rust helps you program in multiple threads\nfearlessly. In **Chapter 17**, we build on that by exploring Rust’s async and\nawait syntax, along with tasks, futures, and streams, and the lightweight\nconcurrency model they enable.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Introduction", "heading_path": ["Introduction", "How to Use This Book"], "path": "ch00-00-introduction.md", "url": "https://doc.rust-lang.org/book/ch00-00-introduction.html#how-to-use-this-book", "has_code": false, "code_tags": []}} {"id": "book/ch00-00-introduction.md#how-to-use-this-book-10", "text": "The Rust Programming Language › Introduction › How to Use This Book\n\n**Chapter 18** looks at how Rust idioms compare to object-oriented programming\nprinciples you might be familiar with. **Chapter 19** is a reference on\npatterns and pattern matching, which are powerful ways of expressing ideas\nthroughout Rust programs. **Chapter 20** contains a smorgasbord of advanced\ntopics of interest, including unsafe Rust, macros, and more about lifetimes,\ntraits, types, functions, and closures.\nIn **Chapter 21**, we’ll complete a project in which we’ll implement a\nlow-level multithreaded web server!\nFinally, some appendixes contain useful information about the language in a\nmore reference-like format. **Appendix A** covers Rust’s keywords, **Appendix\nB** covers Rust’s operators and symbols, **Appendix C** covers derivable traits\nprovided by the standard library, **Appendix D** covers some useful development\ntools, and **Appendix E** explains Rust editions. In **Appendix F**, you can\nfind translations of the book, and in **Appendix G** we’ll cover how Rust is\nmade and what nightly Rust is.\nThere is no wrong way to read this book: If you want to skip ahead, go for it!\nYou might have to jump back to earlier chapters if you experience any\nconfusion. But do whatever works for you.\n", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Introduction", "heading_path": ["Introduction", "How to Use This Book"], "path": "ch00-00-introduction.md", "url": "https://doc.rust-lang.org/book/ch00-00-introduction.html#how-to-use-this-book", "has_code": false, "code_tags": []}} {"id": "book/ch00-00-introduction.md#how-to-use-this-book-11", "text": "The Rust Programming Language › Introduction › How to Use This Book\n\nAn important part of the process of learning Rust is learning how to read the\nerror messages the compiler displays: These will guide you toward working code.\nAs such, we’ll provide many examples that don’t compile along with the error\nmessage the compiler will show you in each situation. Know that if you enter\nand run a random example, it may not compile! Make sure you read the\nsurrounding text to see whether the example you’re trying to run is meant to\nerror. In most situations, we’ll lead you to the correct version of any code\nthat doesn’t compile. Ferris will also help you distinguish code that isn’t\nmeant to work:\n| Ferris | Meaning |\n| ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ |\n| \"Ferris | This code does not compile! |\n| \"Ferris | This code panics! |\n| \"Ferris | This code does not produce the desired behavior. |\nIn most situations, we’ll lead you to the correct version of any code that\ndoesn’t compile.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Introduction", "heading_path": ["Introduction", "How to Use This Book"], "path": "ch00-00-introduction.md", "url": "https://doc.rust-lang.org/book/ch00-00-introduction.html#how-to-use-this-book", "has_code": false, "code_tags": []}} {"id": "book/ch00-00-introduction.md#source-code-12", "text": "The Rust Programming Language › Introduction › Source Code\n\nThe source files from which this book is generated can be found on\nGitHub.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Introduction", "heading_path": ["Introduction", "Source Code"], "path": "ch00-00-introduction.md", "url": "https://doc.rust-lang.org/book/ch00-00-introduction.html#source-code", "has_code": false, "code_tags": []}} {"id": "book/ch01-00-getting-started.md#getting-started-0", "text": "The Rust Programming Language › Getting Started\n\nLet’s start your Rust journey! There’s a lot to learn, but every journey starts\nsomewhere. In this chapter, we’ll discuss:\n- Installing Rust on Linux, macOS, and Windows\n- Writing a program that prints `Hello, world!`\n- Using `cargo`, Rust’s package manager and build system", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Getting Started", "heading_path": ["Getting Started"], "path": "ch01-00-getting-started.md", "url": "https://doc.rust-lang.org/book/ch01-00-getting-started.html#getting-started", "has_code": false, "code_tags": []}} {"id": "book/ch01-01-installation.md#installation-0", "text": "The Rust Programming Language › Installation\n\nThe first step is to install Rust. We’ll download Rust through `rustup`, a\ncommand line tool for managing Rust versions and associated tools. You’ll need\nan internet connection for the download.\nNote: If you prefer not to use `rustup` for some reason, please see the\nOther Rust Installation Methods page for more options.\nThe following steps install the latest stable version of the Rust compiler.\nRust’s stability guarantees ensure that all the examples in the book that\ncompile will continue to compile with newer Rust versions. The output might\ndiffer slightly between versions because Rust often improves error messages and\nwarnings. In other words, any newer, stable version of Rust you install using\nthese steps should work as expected with the content of this book.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Installation", "heading_path": ["Installation"], "path": "ch01-01-installation.md", "url": "https://doc.rust-lang.org/book/ch01-01-installation.html#installation", "has_code": false, "code_tags": []}} {"id": "book/ch01-01-installation.md#command-line-notation-1", "text": "The Rust Programming Language › Installation › Command Line Notation\n\nIn this chapter and throughout the book, we’ll show some commands used in the\nterminal. Lines that you should enter in a terminal all start with `$`. You\ndon’t need to type the `$` character; it’s the command line prompt shown to\nindicate the start of each command. Lines that don’t start with `$` typically\nshow the output of the previous command. Additionally, PowerShell-specific\nexamples will use `>` rather than `$`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Installation", "heading_path": ["Installation", "Command Line Notation"], "path": "ch01-01-installation.md", "url": "https://doc.rust-lang.org/book/ch01-01-installation.html#command-line-notation", "has_code": false, "code_tags": []}} {"id": "book/ch01-01-installation.md#installing-rustup-on-linux-or-macos-2", "text": "The Rust Programming Language › Installation › Installing `rustup` on Linux or macOS\n\nIf you’re using Linux or macOS, open a terminal and enter the following command:\n```console\n$ curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh\n```\nThe command downloads a script and starts the installation of the `rustup`\ntool, which installs the latest stable version of Rust. You might be prompted\nfor your password. If the install is successful, the following line will appear:\n```text\nRust is installed now. Great!\n```\nYou will also need a _linker_, which is a program that Rust uses to join its\ncompiled outputs into one file. It is likely you already have one. If you get\nlinker errors, you should install a C compiler, which will typically include a\nlinker. A C compiler is also useful because some common Rust packages depend on\nC code and will need a C compiler.\nOn macOS, you can get a C compiler by running:\n```console\n$ xcode-select --install\n```\nLinux users should generally install GCC or Clang, according to their\ndistribution’s documentation. For example, if you use Ubuntu, you can install\nthe `build-essential` package.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Installation", "heading_path": ["Installation", "Installing `rustup` on Linux or macOS"], "path": "ch01-01-installation.md", "url": "https://doc.rust-lang.org/book/ch01-01-installation.html#installing-rustup-on-linux-or-macos", "has_code": true, "code_tags": ["console", "text"]}} {"id": "book/ch01-01-installation.md#installing-rustup-on-windows-3", "text": "The Rust Programming Language › Installation › Installing `rustup` on Windows\n\nOn Windows, go to https://www.rust-lang.org/tools/install\n and follow the instructions for installing Rust. At some point in the\ninstallation, you’ll be prompted to install Visual Studio. This provides a\nlinker and the native libraries needed to compile programs. If you need more\nhelp with this step, see\nhttps://rust-lang.github.io/rustup/installation/windows-msvc.html\n.\nThe rest of this book uses commands that work in both _cmd.exe_ and PowerShell.\nIf there are specific differences, we’ll explain which to use.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Installation", "heading_path": ["Installation", "Installing `rustup` on Windows"], "path": "ch01-01-installation.md", "url": "https://doc.rust-lang.org/book/ch01-01-installation.html#installing-rustup-on-windows", "has_code": false, "code_tags": []}} {"id": "book/ch01-01-installation.md#troubleshooting-4", "text": "The Rust Programming Language › Installation › Troubleshooting\n\nTo check whether you have Rust installed correctly, open a shell and enter this\nline:\n```console\n$ rustc --version\n```\nYou should see the version number, commit hash, and commit date for the latest\nstable version that has been released, in the following format:\n```text\nrustc x.y.z (abcabcabc yyyy-mm-dd)\n```\nIf you see this information, you have installed Rust successfully! If you don’t\nsee this information, check that Rust is in your `%PATH%` system variable as\nfollows.\nIn Windows CMD, use:\n```console\necho %PATH%\n```\nIn PowerShell, use:\n```powershell\necho $env:Path\n```\nIn Linux and macOS, use:\n```console\n$ echo $PATH\n```\nIf that’s all correct and Rust still isn’t working, there are a number of\nplaces you can get help. Find out how to get in touch with other Rustaceans (a\nsilly nickname we call ourselves) on the community page.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Installation", "heading_path": ["Installation", "Troubleshooting"], "path": "ch01-01-installation.md", "url": "https://doc.rust-lang.org/book/ch01-01-installation.html#troubleshooting", "has_code": true, "code_tags": ["console", "powershell", "text"]}} {"id": "book/ch01-01-installation.md#updating-and-uninstalling-5", "text": "The Rust Programming Language › Installation › Updating and Uninstalling\n\nOnce Rust is installed via `rustup`, updating to a newly released version is\neasy. From your shell, run the following update script:\n```console\n$ rustup update\n```\nTo uninstall Rust and `rustup`, run the following uninstall script from your\nshell:\n```console\n$ rustup self uninstall\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Installation", "heading_path": ["Installation", "Updating and Uninstalling"], "path": "ch01-01-installation.md", "url": "https://doc.rust-lang.org/book/ch01-01-installation.html#updating-and-uninstalling", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch01-01-installation.md#reading-the-local-documentation-6", "text": "The Rust Programming Language › Installation › Reading the Local Documentation\n\nThe installation of Rust also includes a local copy of the documentation so\nthat you can read it offline. Run `rustup doc` to open the local documentation\nin your browser.\nAny time a type or function is provided by the standard library and you’re not\nsure what it does or how to use it, use the application programming interface\n(API) documentation to find out!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Installation", "heading_path": ["Installation", "Reading the Local Documentation"], "path": "ch01-01-installation.md", "url": "https://doc.rust-lang.org/book/ch01-01-installation.html#reading-the-local-documentation", "has_code": false, "code_tags": []}} {"id": "book/ch01-01-installation.md#using-text-editors-and-ides-7", "text": "The Rust Programming Language › Installation › Using Text Editors and IDEs\n\nThis book makes no assumptions about what tools you use to author Rust code.\nJust about any text editor will get the job done! However, many text editors and\nintegrated development environments (IDEs) have built-in support for Rust. You\ncan always find a fairly current list of many editors and IDEs on the tools\npage on the Rust website.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Installation", "heading_path": ["Installation", "Using Text Editors and IDEs"], "path": "ch01-01-installation.md", "url": "https://doc.rust-lang.org/book/ch01-01-installation.html#using-text-editors-and-ides", "has_code": false, "code_tags": []}} {"id": "book/ch01-01-installation.md#working-offline-with-this-book-8", "text": "The Rust Programming Language › Installation › Working Offline with This Book\n\nIn several examples, we will use Rust packages beyond the standard library. To\nwork through those examples, you will either need to have an internet connection\nor to have downloaded those dependencies ahead of time. To download the\ndependencies ahead of time, you can run the following commands. (We’ll explain\nwhat `cargo` is and what each of these commands does in detail later.)\n```console\n$ cargo new get-dependencies\n$ cd get-dependencies\n$ cargo add rand@0.10.1 trpl@0.2.0\n```\nThis will cache the downloads for these packages so you will not need to\ndownload them later. Once you have run this command, you do not need to keep the\n`get-dependencies` folder. If you have run this command, you can use the\n`--offline` flag with all `cargo` commands in the rest of the book to use these\ncached versions instead of attempting to use the network.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Installation", "heading_path": ["Installation", "Working Offline with This Book"], "path": "ch01-01-installation.md", "url": "https://doc.rust-lang.org/book/ch01-01-installation.html#working-offline-with-this-book", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch01-02-hello-world.md#hello-world-0", "text": "The Rust Programming Language › Hello, World!\n\nNow that you’ve installed Rust, it’s time to write your first Rust program.\nIt’s traditional when learning a new language to write a little program that\nprints the text `Hello, world!` to the screen, so we’ll do the same here!\nNote: This book assumes basic familiarity with the command line. Rust makes\nno specific demands about your editing or tooling or where your code lives, so\nif you prefer to use an IDE instead of the command line, feel free to use your\nfavorite IDE. Many IDEs now have some degree of Rust support; check the IDE’s\ndocumentation for details. The Rust team has been focusing on enabling great\nIDE support via `rust-analyzer`. See Appendix D\nfor more details.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Hello, World!", "heading_path": ["Hello, World!"], "path": "ch01-02-hello-world.md", "url": "https://doc.rust-lang.org/book/ch01-02-hello-world.html#hello-world", "has_code": false, "code_tags": []}} {"id": "book/ch01-02-hello-world.md#project-directory-setup-1", "text": "The Rust Programming Language › Hello, World! › Project Directory Setup\n\nYou’ll start by making a directory to store your Rust code. It doesn’t matter\nto Rust where your code lives, but for the exercises and projects in this book,\nwe suggest making a _projects_ directory in your home directory and keeping all\nyour projects there.\nOpen a terminal and enter the following commands to make a _projects_ directory\nand a directory for the “Hello, world!” project within the _projects_ directory.\nFor Linux, macOS, and PowerShell on Windows, enter this:\n```console\n$ mkdir ~/projects\n$ cd ~/projects\n$ mkdir hello_world\n$ cd hello_world\n```\nFor Windows CMD, enter this:\n```cmd\nmkdir \"%USERPROFILE%\\projects\"\ncd /d \"%USERPROFILE%\\projects\"\nmkdir hello_world\ncd hello_world\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Hello, World!", "heading_path": ["Hello, World!", "Project Directory Setup"], "path": "ch01-02-hello-world.md", "url": "https://doc.rust-lang.org/book/ch01-02-hello-world.html#project-directory-setup", "has_code": true, "code_tags": ["cmd", "console"]}} {"id": "book/ch01-02-hello-world.md#rust-program-basics-2", "text": "The Rust Programming Language › Hello, World! › Rust Program Basics\n\nNext, make a new source file and call it _main.rs_. Rust files always end with\nthe _.rs_ extension. If you’re using more than one word in your filename, the\nconvention is to use an underscore to separate them. For example, use\n_hello_world.rs_ rather than _helloworld.rs_.\nNow open the _main.rs_ file you just created and enter the code in Listing 1-1.\nListing 1-1: A program that prints `Hello, world!` (main.rs)\n```rust\nfn main() {\n println!(\"Hello, world!\");\n}\n```\nSave the file and go back to your terminal window in the\n_~/projects/hello_world_ directory. On Linux or macOS, enter the following\ncommands to compile and run the file:\n```console\n$ rustc main.rs\n$ ./main\nHello, world!\n```\nOn Windows, enter the command `.\\main` instead of `./main`:\n```powershell\nrustc main.rs\n.\\main\nHello, world!\n```\nRegardless of your operating system, the string `Hello, world!` should print to\nthe terminal. If you don’t see this output, refer back to the\n“Troubleshooting” part of the Installation\nsection for ways to get help.\nIf `Hello, world!` did print, congratulations! You’ve officially written a Rust\nprogram. That makes you a Rust programmer—welcome!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Hello, World!", "heading_path": ["Hello, World!", "Rust Program Basics"], "path": "ch01-02-hello-world.md", "url": "https://doc.rust-lang.org/book/ch01-02-hello-world.html#rust-program-basics", "has_code": true, "code_tags": ["console", "powershell", "rust"]}} {"id": "book/ch01-02-hello-world.md#the-anatomy-of-a-rust-program-3", "text": "The Rust Programming Language › Hello, World! › The Anatomy of a Rust Program\n\nLet’s review this “Hello, world!” program in detail. Here’s the first piece of\nthe puzzle:\n```rust\nfn main() {\n\n}\n```\nThese lines define a function named `main`. The `main` function is special: It\nis always the first code that runs in every executable Rust program. Here, the\nfirst line declares a function named `main` that has no parameters and returns\nnothing. If there were parameters, they would go inside the parentheses (`()`).\nThe function body is wrapped in `{}`. Rust requires curly brackets around all\nfunction bodies. It’s good style to place the opening curly bracket on the same\nline as the function declaration, adding one space in between.\nNote: If you want to stick to a standard style across Rust projects, you can\nuse an automatic formatter tool called `rustfmt` to format your code in a\nparticular style (more on `rustfmt` in\nAppendix D). The Rust team has included this tool\nwith the standard Rust distribution, as `rustc` is, so it should already be\ninstalled on your computer!\nThe body of the `main` function holds the following code:\n```rust\nprintln!(\"Hello, world!\");\n```\nThis line does all the work in this little program: It prints text to the\nscreen. There are three important details to notice here.\nFirst, `println!` calls a Rust macro. If it had called a function instead, it\nwould be entered as `println` (without the `!`). Rust macros are a way to write\ncode that generates code to extend Rust syntax, and we’ll discuss them in more\ndetail in Chapter 20. For now, you just need to\nknow that using a `!` means that you’re calling a macro instead of a normal\nfunction and that macros don’t always follow the same rules as functions.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Hello, World!", "heading_path": ["Hello, World!", "The Anatomy of a Rust Program"], "path": "ch01-02-hello-world.md", "url": "https://doc.rust-lang.org/book/ch01-02-hello-world.html#the-anatomy-of-a-rust-program", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch01-02-hello-world.md#the-anatomy-of-a-rust-program-4", "text": "The Rust Programming Language › Hello, World! › The Anatomy of a Rust Program\n\nSecond, you see the `\"Hello, world!\"` string. We pass this string as an argument\nto `println!`, and the string is printed to the screen.\nThird, we end the line with a semicolon (`;`), which indicates that this\nexpression is over, and the next one is ready to begin. Most lines of Rust code\nend with a semicolon.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Hello, World!", "heading_path": ["Hello, World!", "The Anatomy of a Rust Program"], "path": "ch01-02-hello-world.md", "url": "https://doc.rust-lang.org/book/ch01-02-hello-world.html#the-anatomy-of-a-rust-program", "has_code": false, "code_tags": []}} {"id": "book/ch01-02-hello-world.md#compilation-and-execution-5", "text": "The Rust Programming Language › Hello, World! › Compilation and Execution\n\nYou’ve just run a newly created program, so let’s examine each step in the\nprocess.\nBefore running a Rust program, you must compile it using the Rust compiler by\nentering the `rustc` command and passing it the name of your source file, like\nthis:\n```console\n$ rustc main.rs\n```\nIf you have a C or C++ background, you’ll notice that this is similar to `gcc`\nor `clang`. After compiling successfully, Rust outputs a binary executable.\nOn Linux, macOS, and PowerShell on Windows, you can see the executable by\nentering the `ls` command in your shell:\n```console\n$ ls\nmain main.rs\n```\nOn Linux and macOS, you’ll see two files. With PowerShell on Windows, you’ll\nsee the same three files that you would see using CMD. With CMD on Windows, you\nwould enter the following:\n```cmd\ndir /B %= the /B option says to only show the file names =%\nmain.exe\nmain.pdb\nmain.rs\n```\nThis shows the source code file with the _.rs_ extension, the executable file\n(_main.exe_ on Windows, but _main_ on all other platforms), and, when using\nWindows, a file containing debugging information with the _.pdb_ extension.\nFrom here, you run the _main_ or _main.exe_ file, like this:\n```console\n$ ./main # or .\\main on Windows\n```\nIf your _main.rs_ is your “Hello, world!” program, this line prints `Hello,\nworld!` to your terminal.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Hello, World!", "heading_path": ["Hello, World!", "Compilation and Execution"], "path": "ch01-02-hello-world.md", "url": "https://doc.rust-lang.org/book/ch01-02-hello-world.html#compilation-and-execution", "has_code": true, "code_tags": ["cmd", "console"]}} {"id": "book/ch01-02-hello-world.md#compilation-and-execution-6", "text": "The Rust Programming Language › Hello, World! › Compilation and Execution\n\nIf you’re more familiar with a dynamic language, such as Ruby, Python, or\nJavaScript, you might not be used to compiling and running a program as\nseparate steps. Rust is an _ahead-of-time compiled_ language, meaning you can\ncompile a program and give the executable to someone else, and they can run it\neven without having Rust installed. If you give someone a _.rb_, _.py_, or\n_.js_ file, they need to have a Ruby, Python, or JavaScript implementation\ninstalled (respectively). But in those languages, you only need one command to\ncompile and run your program. Everything is a trade-off in language design.\nJust compiling with `rustc` is fine for simple programs, but as your project\ngrows, you’ll want to manage all the options and make it easy to share your\ncode. Next, we’ll introduce you to the Cargo tool, which will help you write\nreal-world Rust programs.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Hello, World!", "heading_path": ["Hello, World!", "Compilation and Execution"], "path": "ch01-02-hello-world.md", "url": "https://doc.rust-lang.org/book/ch01-02-hello-world.html#compilation-and-execution", "has_code": false, "code_tags": []}} {"id": "book/ch01-03-hello-cargo.md#hello-cargo-0", "text": "The Rust Programming Language › Hello, Cargo!\n\nCargo is Rust’s build system and package manager. Most Rustaceans use this tool\nto manage their Rust projects because Cargo handles a lot of tasks for you,\nsuch as building your code, downloading the libraries your code depends on, and\nbuilding those libraries. (We call the libraries that your code needs\n_dependencies_.)\nThe simplest Rust programs, like the one we’ve written so far, don’t have any\ndependencies. If we had built the “Hello, world!” project with Cargo, it would\nonly use the part of Cargo that handles building your code. As you write more\ncomplex Rust programs, you’ll add dependencies, and if you start a project\nusing Cargo, adding dependencies will be much easier to do.\nBecause the vast majority of Rust projects use Cargo, the rest of this book\nassumes that you’re using Cargo too. Cargo comes installed with Rust if you\nused the official installers discussed in the\n“Installation” section. If you installed Rust\nthrough some other means, check whether Cargo is installed by entering the\nfollowing in your terminal:\n```console\n$ cargo --version\n```\nIf you see a version number, you have it! If you see an error, such as `command\nnot found`, look at the documentation for your method of installation to\ndetermine how to install Cargo separately.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Hello, Cargo!", "heading_path": ["Hello, Cargo!"], "path": "ch01-03-hello-cargo.md", "url": "https://doc.rust-lang.org/book/ch01-03-hello-cargo.html#hello-cargo", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch01-03-hello-cargo.md#creating-a-project-with-cargo-1", "text": "The Rust Programming Language › Hello, Cargo! › Creating a Project with Cargo\n\nLet’s create a new project using Cargo and look at how it differs from our\noriginal “Hello, world!” project. Navigate back to your _projects_ directory\n(or wherever you decided to store your code). Then, on any operating system,\nrun the following:\n```console\n$ cargo new hello_cargo\n$ cd hello_cargo\n```\nThe first command creates a new directory and project called _hello_cargo_.\nWe’ve named our project _hello_cargo_, and Cargo creates its files in a\ndirectory of the same name.\nGo into the _hello_cargo_ directory and list the files. You’ll see that Cargo\nhas generated two files and one directory for us: a _Cargo.toml_ file and a\n_src_ directory with a _main.rs_ file inside.\nIt has also initialized a new Git repository along with a _.gitignore_ file.\nGit files won’t be generated if you run `cargo new` within an existing Git\nrepository; you can override this behavior by using `cargo new --vcs=git`.\nNote: Git is a common version control system. You can change `cargo new` to\nuse a different version control system or no version control system by using\nthe `--vcs` flag. Run `cargo new --help` to see the available options.\nOpen _Cargo.toml_ in your text editor of choice. It should look similar to the\ncode in Listing 1-2.\nListing 1-2: Contents of *Cargo.toml* generated by `cargo new` (Cargo.toml)\n```toml\n[package]\nname = \"hello_cargo\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n[dependencies]\n```\nThis file is in the _TOML_ (_Tom’s Obvious, Minimal\nLanguage_) format, which is Cargo’s configuration format.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Hello, Cargo!", "heading_path": ["Hello, Cargo!", "Creating a Project with Cargo"], "path": "ch01-03-hello-cargo.md", "url": "https://doc.rust-lang.org/book/ch01-03-hello-cargo.html#creating-a-project-with-cargo", "has_code": true, "code_tags": ["console", "toml"]}} {"id": "book/ch01-03-hello-cargo.md#creating-a-project-with-cargo-2", "text": "The Rust Programming Language › Hello, Cargo! › Creating a Project with Cargo\n\nThe first line, `[package]`, is a section heading that indicates that the\nfollowing statements are configuring a package. As we add more information to\nthis file, we’ll add other sections.\nThe next three lines set the configuration information Cargo needs to compile\nyour program: the name, the version, and the edition of Rust to use. We’ll talk\nabout the `edition` key in Appendix E.\nThe last line, `[dependencies]`, is the start of a section for you to list any\nof your project’s dependencies. In Rust, packages of code are referred to as\n_crates_. We won’t need any other crates for this project, but we will in the\nfirst project in Chapter 2, so we’ll use this dependencies section then.\nNow open _src/main.rs_ and take a look:\nFilename: src/main.rs\n```rust\nfn main() {\n println!(\"Hello, world!\");\n}\n```\nCargo has generated a “Hello, world!” program for you, just like the one we\nwrote in Listing 1-1! So far, the differences between our project and the\nproject Cargo generated are that Cargo placed the code in the _src_ directory,\nand we have a _Cargo.toml_ configuration file in the top directory.\nCargo expects your source files to live inside the _src_ directory. The\ntop-level project directory is just for README files, license information,\nconfiguration files, and anything else not related to your code. Using Cargo\nhelps you organize your projects. There’s a place for everything, and\neverything is in its place.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Hello, Cargo!", "heading_path": ["Hello, Cargo!", "Creating a Project with Cargo"], "path": "ch01-03-hello-cargo.md", "url": "https://doc.rust-lang.org/book/ch01-03-hello-cargo.html#creating-a-project-with-cargo", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch01-03-hello-cargo.md#creating-a-project-with-cargo-3", "text": "The Rust Programming Language › Hello, Cargo! › Creating a Project with Cargo\n\nIf you started a project that doesn’t use Cargo, as we did with the “Hello,\nworld!” project, you can convert it to a project that does use Cargo. Move the\nproject code into the _src_ directory and create an appropriate _Cargo.toml_\nfile. One easy way to get that _Cargo.toml_ file is to run `cargo init`, which\nwill create it for you automatically.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Hello, Cargo!", "heading_path": ["Hello, Cargo!", "Creating a Project with Cargo"], "path": "ch01-03-hello-cargo.md", "url": "https://doc.rust-lang.org/book/ch01-03-hello-cargo.html#creating-a-project-with-cargo", "has_code": false, "code_tags": []}} {"id": "book/ch01-03-hello-cargo.md#building-and-running-a-cargo-project-4", "text": "The Rust Programming Language › Hello, Cargo! › Building and Running a Cargo Project\n\nNow let’s look at what’s different when we build and run the “Hello, world!”\nprogram with Cargo! From your _hello_cargo_ directory, build your project by\nentering the following command:\n```console\n$ cargo build\n Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo)\n Finished dev [unoptimized + debuginfo] target(s) in 2.85 secs\n```\nThis command creates an executable file in _target/debug/hello_cargo_ (or\n_target\\debug\\hello_cargo.exe_ on Windows) rather than in your current\ndirectory. Because the default build is a debug build, Cargo puts the binary in\na directory named _debug_. You can run the executable with this command:\n```console\n$ ./target/debug/hello_cargo # or .\\target\\debug\\hello_cargo.exe on Windows\nHello, world!\n```\nIf all goes well, `Hello, world!` should print to the terminal. Running `cargo\nbuild` for the first time also causes Cargo to create a new file at the top\nlevel: _Cargo.lock_. This file keeps track of the exact versions of\ndependencies in your project. This project doesn’t have dependencies, so the\nfile is a bit sparse. You won’t ever need to change this file manually; Cargo\nmanages its contents for you.\nWe just built a project with `cargo build` and ran it with\n`./target/debug/hello_cargo`, but we can also use `cargo run` to compile the\ncode and then run the resultant executable all in one command:\n```console\n$ cargo run\n Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs\n Running `target/debug/hello_cargo`\nHello, world!\n```\nUsing `cargo run` is more convenient than having to remember to run `cargo\nbuild` and then use the whole path to the binary, so most developers use `cargo\nrun`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Hello, Cargo!", "heading_path": ["Hello, Cargo!", "Building and Running a Cargo Project"], "path": "ch01-03-hello-cargo.md", "url": "https://doc.rust-lang.org/book/ch01-03-hello-cargo.html#building-and-running-a-cargo-project", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch01-03-hello-cargo.md#building-and-running-a-cargo-project-5", "text": "The Rust Programming Language › Hello, Cargo! › Building and Running a Cargo Project\n\nNotice that this time we didn’t see output indicating that Cargo was compiling\n`hello_cargo`. Cargo figured out that the files hadn’t changed, so it didn’t\nrebuild but just ran the binary. If you had modified your source code, Cargo\nwould have rebuilt the project before running it, and you would have seen this\noutput:\n```console\n$ cargo run\n Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo)\n Finished dev [unoptimized + debuginfo] target(s) in 0.33 secs\n Running `target/debug/hello_cargo`\nHello, world!\n```\nCargo also provides a command called `cargo check`. This command quickly checks\nyour code to make sure it compiles but doesn’t produce an executable:\n```console\n$ cargo check\n Checking hello_cargo v0.1.0 (file:///projects/hello_cargo)\n Finished dev [unoptimized + debuginfo] target(s) in 0.32 secs\n```\nWhy would you not want an executable? Often, `cargo check` is much faster than\n`cargo build` because it skips the step of producing an executable. If you’re\ncontinually checking your work while writing the code, using `cargo check` will\nspeed up the process of letting you know if your project is still compiling! As\nsuch, many Rustaceans run `cargo check` periodically as they write their\nprogram to make sure it compiles. Then, they run `cargo build` when they’re\nready to use the executable.\nLet’s recap what we’ve learned so far about Cargo:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Hello, Cargo!", "heading_path": ["Hello, Cargo!", "Building and Running a Cargo Project"], "path": "ch01-03-hello-cargo.md", "url": "https://doc.rust-lang.org/book/ch01-03-hello-cargo.html#building-and-running-a-cargo-project", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch01-03-hello-cargo.md#building-and-running-a-cargo-project-6", "text": "The Rust Programming Language › Hello, Cargo! › Building and Running a Cargo Project\n\n- We can create a project using `cargo new`.\n- We can build a project using `cargo build`.\n- We can build and run a project in one step using `cargo run`.\n- We can build a project without producing a binary to check for errors using\n `cargo check`.\n- Instead of saving the result of the build in the same directory as our code,\n Cargo stores it in the _target/debug_ directory.\nAn additional advantage of using Cargo is that the commands are the same no\nmatter which operating system you’re working on. So, at this point, we’ll no\nlonger provide specific instructions for Linux and macOS versus Windows.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Hello, Cargo!", "heading_path": ["Hello, Cargo!", "Building and Running a Cargo Project"], "path": "ch01-03-hello-cargo.md", "url": "https://doc.rust-lang.org/book/ch01-03-hello-cargo.html#building-and-running-a-cargo-project", "has_code": false, "code_tags": []}} {"id": "book/ch01-03-hello-cargo.md#building-for-release-7", "text": "The Rust Programming Language › Hello, Cargo! › Building for Release\n\nWhen your project is finally ready for release, you can use `cargo build\n--release` to compile it with optimizations. This command will create an\nexecutable in _target/release_ instead of _target/debug_. The optimizations\nmake your Rust code run faster, but turning them on lengthens the time it takes\nfor your program to compile. This is why there are two different profiles: one\nfor development, when you want to rebuild quickly and often, and another for\nbuilding the final program you’ll give to a user that won’t be rebuilt\nrepeatedly and that will run as fast as possible. If you’re benchmarking your\ncode’s running time, be sure to run `cargo build --release` and benchmark with\nthe executable in _target/release_.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Hello, Cargo!", "heading_path": ["Hello, Cargo!", "Building for Release"], "path": "ch01-03-hello-cargo.md", "url": "https://doc.rust-lang.org/book/ch01-03-hello-cargo.html#building-for-release", "has_code": false, "code_tags": []}} {"id": "book/ch01-03-hello-cargo.md#leveraging-cargos-conventions-8", "text": "The Rust Programming Language › Hello, Cargo! › Leveraging Cargo’s Conventions\n\nWith simple projects, Cargo doesn’t provide a lot of value over just using\n`rustc`, but it will prove its worth as your programs become more intricate.\nOnce programs grow to multiple files or need a dependency, it’s much easier to\nlet Cargo coordinate the build.\nEven though the `hello_cargo` project is simple, it now uses much of the real\ntooling you’ll use in the rest of your Rust career. In fact, to work on any\nexisting projects, you can use the following commands to check out the code\nusing Git, change to that project’s directory, and build:\n```console\n$ git clone example.org/someproject\n$ cd someproject\n$ cargo build\n```\nFor more information about Cargo, check out its documentation.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Hello, Cargo!", "heading_path": ["Hello, Cargo!", "Leveraging Cargo’s Conventions"], "path": "ch01-03-hello-cargo.md", "url": "https://doc.rust-lang.org/book/ch01-03-hello-cargo.html#leveraging-cargos-conventions", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch01-03-hello-cargo.md#summary-9", "text": "The Rust Programming Language › Summary\n\nYou’re already off to a great start on your Rust journey! In this chapter, you\nlearned how to:\n- Install the latest stable version of Rust using `rustup`.\n- Update to a newer Rust version.\n- Open locally installed documentation.\n- Write and run a “Hello, world!” program using `rustc` directly.\n- Create and run a new project using the conventions of Cargo.\nThis is a great time to build a more substantial program to get used to reading\nand writing Rust code. So, in Chapter 2, we’ll build a guessing game program.\nIf you would rather start by learning how common programming concepts work in\nRust, see Chapter 3 and then return to Chapter 2.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Hello, Cargo!", "heading_path": ["Summary"], "path": "ch01-03-hello-cargo.md", "url": "https://doc.rust-lang.org/book/ch01-03-hello-cargo.html#summary", "has_code": false, "code_tags": []}} {"id": "book/ch02-00-guessing-game-tutorial.md#programming-a-guessing-game-0", "text": "The Rust Programming Language › Programming a Guessing Game\n\nLet’s jump into Rust by working through a hands-on project together! This\nchapter introduces you to a few common Rust concepts by showing you how to use\nthem in a real program. You’ll learn about `let`, `match`, methods, associated\nfunctions, external crates, and more! In the following chapters, we’ll explore\nthese ideas in more detail. In this chapter, you’ll just practice the\nfundamentals.\nWe’ll implement a classic beginner programming problem: a guessing game. Here’s\nhow it works: The program will generate a random integer between 1 and 100. It\nwill then prompt the player to enter a guess. After a guess is entered, the\nprogram will indicate whether the guess is too low or too high. If the guess is\ncorrect, the game will print a congratulatory message and exit.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#programming-a-guessing-game", "has_code": false, "code_tags": []}} {"id": "book/ch02-00-guessing-game-tutorial.md#setting-up-a-new-project-1", "text": "The Rust Programming Language › Programming a Guessing Game › Setting Up a New Project\n\nTo set up a new project, go to the _projects_ directory that you created in\nChapter 1 and make a new project using Cargo, like so:\n```console\n$ cargo new guessing_game\n$ cd guessing_game\n```\nThe first command, `cargo new`, takes the name of the project (`guessing_game`)\nas the first argument. The second command changes to the new project’s\ndirectory.\nLook at the generated _Cargo.toml_ file:\nFilename: Cargo.toml\n```toml\n[package]\nname = \"guessing_game\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n[dependencies]\n```\nAs you saw in Chapter 1, `cargo new` generates a “Hello, world!” program for\nyou. Check out the _src/main.rs_ file:\nFilename: src/main.rs\n```rust\nfn main() {\n println!(\"Hello, world!\");\n}\n```\nNow let’s compile this “Hello, world!” program and run it in the same step\nusing the `cargo run` command:\n```console\n$ cargo run\n Compiling guessing_game v0.1.0 (file:///projects/guessing_game)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.08s\n Running `target/debug/guessing_game`\nHello, world!\n```\nThe `run` command comes in handy when you need to rapidly iterate on a project,\nas we’ll do in this game, quickly testing each iteration before moving on to\nthe next one.\nReopen the _src/main.rs_ file. You’ll be writing all the code in this file.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Setting Up a New Project"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#setting-up-a-new-project", "has_code": true, "code_tags": ["console", "rust", "toml"]}} {"id": "book/ch02-00-guessing-game-tutorial.md#processing-a-guess-2", "text": "The Rust Programming Language › Programming a Guessing Game › Processing a Guess\n\nThe first part of the guessing game program will ask for user input, process\nthat input, and check that the input is in the expected form. To start, we’ll\nallow the player to input a guess. Enter the code in Listing 2-1 into\n_src/main.rs_.\nListing 2-1: Code that gets a guess from the user and prints it (src/main.rs)\n```rust,ignore\nuse std::io;\n\nfn main() {\n println!(\"Guess the number!\");\n\n println!(\"Please input your guess.\");\n\n let mut guess = String::new();\n\n io::stdin()\n .read_line(&mut guess)\n .expect(\"Failed to read line\");\n\n println!(\"You guessed: {guess}\");\n}\n```\nThis code contains a lot of information, so let’s go over it line by line. To\nobtain user input and then print the result as output, we need to bring the\n`io` input/output library into scope. The `io` library comes from the standard\nlibrary, known as `std`:\n```rust,ignore\nuse std::io;\n```\nBy default, Rust has a set of items defined in the standard library that it\nbrings into the scope of every program. This set is called the _prelude_, and\nyou can see everything in it in the standard library documentation.\nIf a type you want to use isn’t in the prelude, you have to bring that type\ninto scope explicitly with a `use` statement. Using the `std::io` library\nprovides you with a number of useful features, including the ability to accept\nuser input.\nAs you saw in Chapter 1, the `main` function is the entry point into the\nprogram:\n```rust,ignore\nfn main() {\n```\nThe `fn` syntax declares a new function; the parentheses, `()`, indicate there\nare no parameters; and the curly bracket, `{`, starts the body of the function.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Processing a Guess"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#processing-a-guess", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch02-00-guessing-game-tutorial.md#processing-a-guess-3", "text": "The Rust Programming Language › Programming a Guessing Game › Processing a Guess\n\nAs you also learned in Chapter 1, `println!` is a macro that prints a string to\nthe screen:\n```rust,ignore\n println!(\"Guess the number!\");\n\n println!(\"Please input your guess.\");\n```\nThis code is printing a prompt stating what the game is and requesting input\nfrom the user.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Processing a Guess"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#processing-a-guess", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch02-00-guessing-game-tutorial.md#storing-values-with-variables-4", "text": "The Rust Programming Language › Programming a Guessing Game › Processing a Guess › Storing Values with Variables\n\nNext, we’ll create a _variable_ to store the user input, like this:\n```rust,ignore\n let mut guess = String::new();\n```\nNow the program is getting interesting! There’s a lot going on in this little\nline. We use the `let` statement to create the variable. Here’s another example:\n```rust,ignore\nlet apples = 5;\n```\nThis line creates a new variable named `apples` and binds it to the value `5`.\nIn Rust, variables are immutable by default, meaning once we give the variable\na value, the value won’t change. We’ll be discussing this concept in detail in\nthe “Variables and Mutability”\nsection in Chapter 3. To make a variable mutable, we add `mut` before the\nvariable name:\n```rust,ignore\nlet apples = 5; // immutable\nlet mut bananas = 5; // mutable\n```\nNote: The `//` syntax starts a comment that continues until the end of the\nline. Rust ignores everything in comments. We’ll discuss comments in more\ndetail in Chapter 3.\nReturning to the guessing game program, you now know that `let mut guess` will\nintroduce a mutable variable named `guess`. The equal sign (`=`) tells Rust we\nwant to bind something to the variable now. On the right of the equal sign is\nthe value that `guess` is bound to, which is the result of calling\n`String::new`, a function that returns a new instance of a `String`.\n`String` is a string type provided by the standard\nlibrary that is a growable, UTF-8 encoded bit of text.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Processing a Guess", "Storing Values with Variables"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#storing-values-with-variables", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch02-00-guessing-game-tutorial.md#storing-values-with-variables-5", "text": "The Rust Programming Language › Programming a Guessing Game › Processing a Guess › Storing Values with Variables\n\nThe `::` syntax in the `::new` line indicates that `new` is an associated\nfunction of the `String` type. An _associated function_ is a function that’s\nimplemented on a type, in this case `String`. This `new` function creates a\nnew, empty string. You’ll find a `new` function on many types because it’s a\ncommon name for a function that makes a new value of some kind.\nIn full, the `let mut guess = String::new();` line has created a mutable\nvariable that is currently bound to a new, empty instance of a `String`. Whew!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Processing a Guess", "Storing Values with Variables"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#storing-values-with-variables", "has_code": false, "code_tags": []}} {"id": "book/ch02-00-guessing-game-tutorial.md#receiving-user-input-6", "text": "The Rust Programming Language › Programming a Guessing Game › Processing a Guess › Receiving User Input\n\nRecall that we included the input/output functionality from the standard\nlibrary with `use std::io;` on the first line of the program. Now we’ll call\nthe `stdin` function from the `io` module, which will allow us to handle user\ninput:\n```rust,ignore\n io::stdin()\n .read_line(&mut guess)\n```\nIf we hadn’t imported the `io` module with `use std::io;` at the beginning of\nthe program, we could still use the function by writing this function call as\n`std::io::stdin`. The `stdin` function returns an instance of\n`std::io::Stdin`, which is a type that represents a\nhandle to the standard input for your terminal.\nNext, the line `.read_line(&mut guess)` calls the `read_line`\n method on the standard input handle to get input from the user.\nWe’re also passing `&mut guess` as the argument to `read_line` to tell it what\nstring to store the user input in. The full job of `read_line` is to take\nwhatever the user types into standard input and append that into a string\n(without overwriting its contents), so we therefore pass that string as an\nargument. The string argument needs to be mutable so that the method can change\nthe string’s content.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Processing a Guess", "Receiving User Input"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#receiving-user-input", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch02-00-guessing-game-tutorial.md#receiving-user-input-7", "text": "The Rust Programming Language › Programming a Guessing Game › Processing a Guess › Receiving User Input\n\nThe `&` indicates that this argument is a _reference_, which gives you a way to\nlet multiple parts of your code access one piece of data without needing to\ncopy that data into memory multiple times. References are a complex feature,\nand one of Rust’s major advantages is how safe and easy it is to use\nreferences. You don’t need to know a lot of those details to finish this\nprogram. For now, all you need to know is that, like variables, references are\nimmutable by default. Hence, you need to write `&mut guess` rather than\n`&guess` to make it mutable. (Chapter 4 will explain references more\nthoroughly.)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Processing a Guess", "Receiving User Input"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#receiving-user-input", "has_code": false, "code_tags": []}} {"id": "book/ch02-00-guessing-game-tutorial.md#handling-potential-failure-with-result-8", "text": "The Rust Programming Language › Programming a Guessing Game › Processing a Guess › Handling Potential Failure with `Result`\n\nWe’re still working on this line of code. We’re now discussing a third line of\ntext, but note that it’s still part of a single logical line of code. The next\npart is this method:\n```rust,ignore\n .expect(\"Failed to read line\");\n```\nWe could have written this code as:\n```rust,ignore\nio::stdin().read_line(&mut guess).expect(\"Failed to read line\");\n```\nHowever, one long line is difficult to read, so it’s best to divide it. It’s\noften wise to introduce a newline and other whitespace to help break up long\nlines when you call a method with the `.method_name()` syntax. Now let’s\ndiscuss what this line does.\nAs mentioned earlier, `read_line` puts whatever the user enters into the string\nwe pass to it, but it also returns a `Result` value. `Result`\n is an _enumeration_, often called an _enum_,\nwhich is a type that can be in one of multiple possible states. We call each\npossible state a _variant_.\nChapter 6 will cover enums in more detail. The purpose\nof these `Result` types is to encode error-handling information.\n`Result`’s variants are `Ok` and `Err`. The `Ok` variant indicates the\noperation was successful, and it contains the successfully generated value.\nThe `Err` variant means the operation failed, and it contains information\nabout how or why the operation failed.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Processing a Guess", "Handling Potential Failure with `Result`"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#handling-potential-failure-with-result", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch02-00-guessing-game-tutorial.md#handling-potential-failure-with-result-9", "text": "The Rust Programming Language › Programming a Guessing Game › Processing a Guess › Handling Potential Failure with `Result`\n\nValues of the `Result` type, like values of any type, have methods defined on\nthem. An instance of `Result` has an `expect` method\nthat you can call. If this instance of `Result` is an `Err` value, `expect`\nwill cause the program to crash and display the message that you passed as an\nargument to `expect`. If the `read_line` method returns an `Err`, it would\nlikely be the result of an error coming from the underlying operating system.\nIf this instance of `Result` is an `Ok` value, `expect` will take the return\nvalue that `Ok` is holding and return just that value to you so that you can\nuse it. In this case, that value is the number of bytes in the user’s input.\nIf you don’t call `expect`, the program will compile, but you’ll get a warning:\n```console\n$ cargo build\n Compiling guessing_game v0.1.0 (file:///projects/guessing_game)\nwarning: unused `Result` that must be used\n --> src/main.rs:10:5\n |\n10 | io::stdin().read_line(&mut guess);\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n |\n = note: this `Result` may be an `Err` variant, which should be handled\n = note: `#[warn(unused_must_use)]` (part of `#[warn(unused)]`) on by default\nhelp: use `let _ = ...` to ignore the resulting value\n |\n10 | let _ = io::stdin().read_line(&mut guess);\n | +++++++\n\nwarning: `guessing_game` (bin \"guessing_game\") generated 1 warning\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.59s\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Processing a Guess", "Handling Potential Failure with `Result`"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#handling-potential-failure-with-result", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch02-00-guessing-game-tutorial.md#handling-potential-failure-with-result-10", "text": "The Rust Programming Language › Programming a Guessing Game › Processing a Guess › Handling Potential Failure with `Result`\n\nRust warns that you haven’t used the `Result` value returned from `read_line`,\nindicating that the program hasn’t handled a possible error.\nThe right way to suppress the warning is to actually write error-handling code,\nbut in our case we just want to crash this program when a problem occurs, so we\ncan use `expect`. You’ll learn about recovering from errors in Chapter\n9.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Processing a Guess", "Handling Potential Failure with `Result`"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#handling-potential-failure-with-result", "has_code": false, "code_tags": []}} {"id": "book/ch02-00-guessing-game-tutorial.md#printing-values-with-println-placeholders-11", "text": "The Rust Programming Language › Programming a Guessing Game › Processing a Guess › Printing Values with `println!` Placeholders\n\nAside from the closing curly bracket, there’s only one more line to discuss in\nthe code so far:\n```rust,ignore\n println!(\"You guessed: {guess}\");\n```\nThis line prints the string that now contains the user’s input. The `{}` set of\ncurly brackets is a placeholder: Think of `{}` as little crab pincers that hold\na value in place. When printing the value of a variable, the variable name can\ngo inside the curly brackets. When printing the result of evaluating an\nexpression, place empty curly brackets in the format string, then follow the\nformat string with a comma-separated list of expressions to print in each empty\ncurly bracket placeholder in the same order. Printing a variable and the result\nof an expression in one call to `println!` would look like this:\n```rust\nlet x = 5;\nlet y = 10;\n\nprintln!(\"x = {x} and y + 2 = {}\", y + 2);\n```\nThis code would print `x = 5 and y + 2 = 12`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Processing a Guess", "Printing Values with `println!` Placeholders"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#printing-values-with-println-placeholders", "has_code": true, "code_tags": ["rust", "rust,ignore"]}} {"id": "book/ch02-00-guessing-game-tutorial.md#testing-the-first-part-12", "text": "The Rust Programming Language › Programming a Guessing Game › Processing a Guess › Testing the First Part\n\nLet’s test the first part of the guessing game. Run it using `cargo run`:\n```console\n$ cargo run\n Compiling guessing_game v0.1.0 (file:///projects/guessing_game)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 6.44s\n Running `target/debug/guessing_game`\nGuess the number!\nPlease input your guess.\n6\nYou guessed: 6\n```\nAt this point, the first part of the game is done: We’re getting input from the\nkeyboard and then printing it.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Processing a Guess", "Testing the First Part"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#testing-the-first-part", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch02-00-guessing-game-tutorial.md#generating-a-secret-number-13", "text": "The Rust Programming Language › Programming a Guessing Game › Generating a Secret Number\n\nNext, we need to generate a secret number that the user will try to guess. The\nsecret number should be different every time so that the game is fun to play\nmore than once. We’ll use a random number between 1 and 100 so that the game\nisn’t too difficult. Rust doesn’t yet include random number functionality in\nits standard library. However, the Rust team does provide a `rand`\ncrate with said functionality.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Generating a Secret Number"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#generating-a-secret-number", "has_code": false, "code_tags": []}} {"id": "book/ch02-00-guessing-game-tutorial.md#increasing-functionality-with-a-crate-14", "text": "The Rust Programming Language › Programming a Guessing Game › Generating a Secret Number › Increasing Functionality with a Crate\n\nRemember that a crate is a collection of Rust source code files. The project\nwe’ve been building is a binary crate, which is an executable. The `rand` crate\nis a library crate, which contains code that is intended to be used in other\nprograms and can’t be executed on its own.\nCargo’s coordination of external crates is where Cargo really shines. Before we\ncan write code that uses `rand`, we need to modify the _Cargo.toml_ file to\ninclude the `rand` crate as a dependency. Open that file now and add the\nfollowing line to the bottom, beneath the `[dependencies]` section header that\nCargo created for you. Be sure to specify `rand` exactly as we have here, with\nthis version number, or the code examples in this tutorial may not work:\nFilename: Cargo.toml\n```toml\n[dependencies]\nrand = \"0.10.1\"\n```\nIn the _Cargo.toml_ file, everything that follows a header is part of that\nsection that continues until another section starts. In `[dependencies]`, you\ntell Cargo which external crates your project depends on and which versions of\nthose crates you require. In this case, we specify the `rand` crate with the\nsemantic version specifier `0.10.1`. Cargo understands Semantic\nVersioning (sometimes called _SemVer_), which is a\nstandard for writing version numbers. The specifier `0.10.1` is actually\nshorthand for `^0.10.1`, which means any version that is at least 0.10.1 but\nbelow 0.11.0.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Generating a Secret Number", "Increasing Functionality with a Crate"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#increasing-functionality-with-a-crate", "has_code": true, "code_tags": ["toml"]}} {"id": "book/ch02-00-guessing-game-tutorial.md#increasing-functionality-with-a-crate-15", "text": "The Rust Programming Language › Programming a Guessing Game › Generating a Secret Number › Increasing Functionality with a Crate\n\nCargo considers these versions to have public APIs compatible with version\n0.10.1, and this specification ensures that you’ll get the latest patch release\nthat will still compile with the code in this chapter. Any version 0.11.0 or\ngreater is not guaranteed to have the same API as what the following examples\nuse.\nNow, without changing any of the code, let’s build the project, as shown in\nListing 2-2.\nListing 2-2: The output from running `cargo build` after adding the `rand` crate as a dependency\n```console\n$ cargo build\n Updating crates.io index\n Locking 8 packages to latest Rust 1.96.0 compatible versions\n Downloaded rand_core v0.10.1\n Downloaded chacha20 v0.10.1\n Downloaded rand v0.10.1\n Downloaded 3 crates (162.9KiB) in 0.59s\n Compiling libc v0.2.186\n Compiling rand_core v0.10.1\n Compiling getrandom v0.4.3\n Compiling cfg-if v1.0.4\n Compiling chacha20 v0.10.1\n Compiling rand v0.10.1\n Compiling guessing_game v0.1.0 (file:///projects/guessing_game)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 2.03s\n```\nYou may see different version numbers (but they will all be compatible with the\ncode, thanks to SemVer!) and different lines (depending on the operating\nsystem), and the lines may be in a different order.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Generating a Secret Number", "Increasing Functionality with a Crate"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#increasing-functionality-with-a-crate", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch02-00-guessing-game-tutorial.md#ensuring-reproducible-builds-16", "text": "The Rust Programming Language › Programming a Guessing Game › Generating a Secret Number › Increasing Functionality with a Crate › Ensuring Reproducible Builds\n\nWhen we include an external dependency, Cargo fetches the latest versions of\neverything that dependency needs from the _registry_, which is a copy of data\nfrom Crates.io. Crates.io is where people in the Rust ecosystem\npost their open source Rust projects for others to use.\nAfter updating the registry, Cargo checks the `[dependencies]` section and\ndownloads any crates listed that aren’t already downloaded. In this case,\nalthough we only listed `rand` as a dependency, Cargo also grabbed other crates\nthat `rand` depends on to work. After downloading the crates, Rust compiles\nthem and then compiles the project with the dependencies available.\nIf you immediately run `cargo build` again without making any changes, you\nwon’t get any output aside from the `Finished` line. Cargo knows it has already\ndownloaded and compiled the dependencies, and you haven’t changed anything\nabout them in your _Cargo.toml_ file. Cargo also knows that you haven’t changed\nanything about your code, so it doesn’t recompile that either. With nothing to\ndo, it simply exits.\nIf you open the _src/main.rs_ file, make a trivial change, and then save it and\nbuild again, you’ll only see two lines of output:\n```console\n$ cargo build\n Compiling guessing_game v0.1.0 (file:///projects/guessing_game)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.13s\n```\nThese lines show that Cargo only updates the build with your tiny change to the\n_src/main.rs_ file. Your dependencies haven’t changed, so Cargo knows it can\nreuse what it has already downloaded and compiled for those.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Generating a Secret Number", "Increasing Functionality with a Crate", "Ensuring Reproducible Builds"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#ensuring-reproducible-builds", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch02-00-guessing-game-tutorial.md#updating-a-crate-to-get-a-new-version-17", "text": "The Rust Programming Language › Programming a Guessing Game › Generating a Secret Number › Increasing Functionality with a Crate › Updating a Crate to Get a New Version\n\nCargo has a mechanism that ensures that you can rebuild the same artifact every\ntime you or anyone else builds your code: Cargo will use only the versions of\nthe dependencies you specified until you indicate otherwise. For example, say\nthat next week version 0.10.2 of the `rand` crate comes out, and that version\ncontains an important bug fix, but it also contains a regression that will\nbreak your code. To handle this, Rust creates the _Cargo.lock_ file the first\ntime you run `cargo build`, so we now have this in the _guessing_game_\ndirectory.\nWhen you build a project for the first time, Cargo figures out all the versions\nof the dependencies that fit the criteria and then writes them to the\n_Cargo.lock_ file. When you build your project in the future, Cargo will see\nthat the _Cargo.lock_ file exists and will use the versions specified there\nrather than doing all the work of figuring out versions again. This lets you\nhave a reproducible build automatically. In other words, your project will\nremain at 0.10.1 until you explicitly upgrade, thanks to the _Cargo.lock_ file.\nBecause the _Cargo.lock_ file is important for reproducible builds, it’s often\nchecked into source control with the rest of the code in your project.\nWhen you _do_ want to update a crate, Cargo provides the command `update`,\nwhich will ignore the _Cargo.lock_ file and figure out all the latest versions\nthat fit your specifications in _Cargo.toml_. Cargo will then write those\nversions to the _Cargo.lock_ file. Otherwise, by default, Cargo will only look\nfor versions greater than 0.10.1 and less than 0.11.0. If the `rand` crate has\nreleased the two new versions 0.10.2 and 0.999.0, you would see the following if\nyou ran `cargo update`:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Generating a Secret Number", "Increasing Functionality with a Crate", "Updating a Crate to Get a New Version"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#updating-a-crate-to-get-a-new-version", "has_code": false, "code_tags": []}} {"id": "book/ch02-00-guessing-game-tutorial.md#updating-a-crate-to-get-a-new-version-18", "text": "The Rust Programming Language › Programming a Guessing Game › Generating a Secret Number › Increasing Functionality with a Crate › Updating a Crate to Get a New Version\n\n```console\n$ cargo update\n Updating crates.io index\n Locking 1 package to latest Rust 1.96.0 compatible version\n Updating rand v0.10.1 -> v0.10.2 (available: v0.999.0)\n```\nCargo ignores the 0.999.0 release. At this point, you would also notice a\nchange in your _Cargo.lock_ file noting that the version of the `rand` crate\nyou are now using is 0.10.2. To use `rand` version 0.999.0 or any version in the\n0.999._x_ series, you’d have to update the _Cargo.toml_ file to look like this\ninstead (don’t actually make this change because the following examples assume\nyou’re using `rand` 0.10):\n```toml\n[dependencies]\nrand = \"0.999.0\"\n```\nThe next time you run `cargo build`, Cargo will update the registry of crates\navailable and reevaluate your `rand` requirements according to the new version\nyou have specified.\nThere’s a lot more to say about Cargo and its\necosystem, which we’ll discuss in Chapter 14, but\nfor now, that’s all you need to know. Cargo makes it very easy to reuse\nlibraries, so Rustaceans are able to write smaller projects that are assembled\nfrom a number of packages.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Generating a Secret Number", "Increasing Functionality with a Crate", "Updating a Crate to Get a New Version"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#updating-a-crate-to-get-a-new-version", "has_code": true, "code_tags": ["console", "toml"]}} {"id": "book/ch02-00-guessing-game-tutorial.md#generating-a-random-number-19", "text": "The Rust Programming Language › Programming a Guessing Game › Generating a Secret Number › Generating a Random Number\n\nLet’s start using `rand` to generate a number to guess. The next step is to\nupdate _src/main.rs_, as shown in Listing 2-3.\nListing 2-3: Adding code to generate a random number (src/main.rs)\n```rust,ignore\nuse std::io;\n\nuse rand::prelude::*;\n\nfn main() {\n println!(\"Guess the number!\");\n\n let secret_number = rand::rng().random_range(1..=100);\n\n println!(\"The secret number is: {secret_number}\");\n\n println!(\"Please input your guess.\");\n\n let mut guess = String::new();\n\n io::stdin()\n .read_line(&mut guess)\n .expect(\"Failed to read line\");\n\n println!(\"You guessed: {guess}\");\n}\n```\nFirst, we add the line `use rand::prelude::*;`. The `prelude` module contains\nthe most commonly used parts of the `rand` crate, and `use` makes those items\navailable in our program's scope.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Generating a Secret Number", "Generating a Random Number"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#generating-a-random-number", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch02-00-guessing-game-tutorial.md#generating-a-random-number-20", "text": "The Rust Programming Language › Programming a Guessing Game › Generating a Secret Number › Generating a Random Number\n\nNext, we’re adding two lines in the middle. In the first line, we call the\n`rand::rng` function that gives us the particular random number generator we’re\ngoing to use: one that is local to the current thread of execution and is\nseeded by the operating system. Then, we call the `random_range` method on the\nrandom number generator. This method is defined by the `RngExt` trait that is\npart of the `rand::prelude` module that we brought into scope with the `use\nrand::prelude::*;` statement. The `random_range` method takes a range\nexpression as an argument and generates a random number in the range. The kind\nof range expression we’re using here takes the form `start..=end` and is\ninclusive on the lower and upper bounds, so we need to specify `1..=100` to\nrequest a number between 1 and 100.\nNote: You won’t just know what to bring into scope and which methods and\nfunctions to call from a crate, so each crate has documentation with\ninstructions for using it. Another neat feature of Cargo is that running the\n`cargo doc --open` command will build documentation provided by all your\ndependencies locally and open it in your browser. If you’re interested in\nother functionality in the `rand` crate, for example, run `cargo doc --open`\nand click `rand` in the sidebar on the left.\nThe second new line prints the secret number. This is useful while we’re\ndeveloping the program to be able to test it, but we’ll delete it from the\nfinal version. It’s not much of a game if the program prints the answer as soon\nas it starts!\nTry running the program a few times:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Generating a Secret Number", "Generating a Random Number"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#generating-a-random-number", "has_code": false, "code_tags": []}} {"id": "book/ch02-00-guessing-game-tutorial.md#generating-a-random-number-21", "text": "The Rust Programming Language › Programming a Guessing Game › Generating a Secret Number › Generating a Random Number\n\n```console\n$ cargo run\n Compiling guessing_game v0.1.0 (file:///projects/guessing_game)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.02s\n Running `target/debug/guessing_game`\nGuess the number!\nThe secret number is: 7\nPlease input your guess.\n4\nYou guessed: 4\n\n$ cargo run\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.02s\n Running `target/debug/guessing_game`\nGuess the number!\nThe secret number is: 83\nPlease input your guess.\n5\nYou guessed: 5\n```\nYou should get different random numbers, and they should all be numbers between\n1 and 100. If you get warnings, they are safe to ignore. If you get errors,\nplease check that you have `rand = \"0.10.1\"` in your *Cargo.toml* as future\nversions of `rand` may have a different API, but any version in the `0.10`\nseries should work with the code in this chapter.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Generating a Secret Number", "Generating a Random Number"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#generating-a-random-number", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch02-00-guessing-game-tutorial.md#comparing-the-guess-to-the-secret-number-22", "text": "The Rust Programming Language › Programming a Guessing Game › Comparing the Guess to the Secret Number\n\nNow that we have user input and a random number, we can compare them. That step\nis shown in Listing 2-4. Note that this code won’t compile just yet, as we will\nexplain.\nListing 2-4: Handling the possible return values of comparing two numbers (src/main.rs)\n```rust,ignore,does_not_compile\nuse std::cmp::Ordering;\nuse std::io;\n\nuse rand::prelude::*;\n\nfn main() {\n // --snip--\n\n println!(\"You guessed: {guess}\");\n\n match guess.cmp(&secret_number) {\n Ordering::Less => println!(\"Too small!\"),\n Ordering::Greater => println!(\"Too big!\"),\n Ordering::Equal => println!(\"You win!\"),\n }\n}\n```\nFirst, we add another `use` statement, bringing a type called\n`std::cmp::Ordering` into scope from the standard library. The `Ordering` type\nis another enum and has the variants `Less`, `Greater`, and `Equal`. These are\nthe three outcomes that are possible when you compare two values.\nThen, we add five new lines at the bottom that use the `Ordering` type. The\n`cmp` method compares two values and can be called on anything that can be\ncompared. It takes a reference to whatever you want to compare with: Here, it’s\ncomparing `guess` to `secret_number`. Then, it returns a variant of the\n`Ordering` enum we brought into scope with the `use` statement. We use a\n`match` expression to decide what to do next based on\nwhich variant of `Ordering` was returned from the call to `cmp` with the values\nin `guess` and `secret_number`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Comparing the Guess to the Secret Number"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#comparing-the-guess-to-the-secret-number", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch02-00-guessing-game-tutorial.md#comparing-the-guess-to-the-secret-number-23", "text": "The Rust Programming Language › Programming a Guessing Game › Comparing the Guess to the Secret Number\n\nA `match` expression is made up of _arms_. An arm consists of a _pattern_ to\nmatch against, and the code that should be run if the value given to `match`\nfits that arm’s pattern. Rust takes the value given to `match` and looks\nthrough each arm’s pattern in turn. Patterns and the `match` construct are\npowerful Rust features: They let you express a variety of situations your code\nmight encounter, and they make sure you handle them all. These features will be\ncovered in detail in Chapter 6 and Chapter 19, respectively.\nLet’s walk through an example with the `match` expression we use here. Say that\nthe user has guessed 50 and the randomly generated secret number this time is\n38.\nWhen the code compares 50 to 38, the `cmp` method will return\n`Ordering::Greater` because 50 is greater than 38. The `match` expression gets\nthe `Ordering::Greater` value and starts checking each arm’s pattern. It looks\nat the first arm’s pattern, `Ordering::Less`, and sees that the value\n`Ordering::Greater` does not match `Ordering::Less`, so it ignores the code in\nthat arm and moves to the next arm. The next arm’s pattern is\n`Ordering::Greater`, which _does_ match `Ordering::Greater`! The associated\ncode in that arm will execute and print `Too big!` to the screen. The `match`\nexpression ends after the first successful match, so it won’t look at the last\narm in this scenario.\nHowever, the code in Listing 2-4 won’t compile yet. Let’s try it:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Comparing the Guess to the Secret Number"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#comparing-the-guess-to-the-secret-number", "has_code": false, "code_tags": []}} {"id": "book/ch02-00-guessing-game-tutorial.md#comparing-the-guess-to-the-secret-number-24", "text": "The Rust Programming Language › Programming a Guessing Game › Comparing the Guess to the Secret Number\n\n```console\n$ cargo build\n Compiling libc v0.2.186\n Compiling rand_core v0.10.1\n Compiling getrandom v0.4.3\n Compiling cfg-if v1.0.0\n Compiling chacha20 v0.10.1\n Compiling rand v0.10.1\n Compiling guessing_game v0.1.0 (file:///projects/guessing_game)\nerror[E0308]: mismatched types\n --> src/main.rs:23:21\n |\n23 | match guess.cmp(&secret_number) {\n | --- ^^^^^^^^^^^^^^ expected `&String`, found `&{integer}`\n | |\n | arguments to this method are incorrect\n |\n = note: expected reference `&String`\n found reference `&{integer}`\nnote: method defined here\n --> /rustc/2d8144b7880597b6e6d3dfd63a9a9efae3f533d3/library/core/src/cmp.rs:1000:7\n\nFor more information about this error, try `rustc --explain E0308`.\nerror: could not compile `guessing_game` (bin \"guessing_game\") due to 1 previous error\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Comparing the Guess to the Secret Number"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#comparing-the-guess-to-the-secret-number", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch02-00-guessing-game-tutorial.md#comparing-the-guess-to-the-secret-number-25", "text": "The Rust Programming Language › Programming a Guessing Game › Comparing the Guess to the Secret Number\n\nThe core of the error states that there are _mismatched types_. Rust has a\nstrong, static type system. However, it also has type inference. When we wrote\n`let mut guess = String::new()`, Rust was able to infer that `guess` should be\na `String` and didn’t make us write the type. The `secret_number`, on the other\nhand, is a number type. A few of Rust’s number types can have a value between 1\nand 100: `i32`, a 32-bit number; `u32`, an unsigned 32-bit number; `i64`, a\n64-bit number; as well as others. Unless otherwise specified, Rust defaults to\nan `i32`, which is the type of `secret_number` unless you add type information\nelsewhere that would cause Rust to infer a different numerical type. The reason\nfor the error is that Rust cannot compare a string and a number type.\nUltimately, we want to convert the `String` the program reads as input into a\nnumber type so that we can compare it numerically to the secret number. We do\nso by adding this line to the `main` function body:\nFilename: src/main.rs\n```rust,ignore\n // --snip--\n\n let mut guess = String::new();\n\n io::stdin()\n .read_line(&mut guess)\n .expect(\"Failed to read line\");\n\n let guess: u32 = guess.trim().parse().expect(\"Please type a number!\");\n\n println!(\"You guessed: {guess}\");\n\n match guess.cmp(&secret_number) {\n Ordering::Less => println!(\"Too small!\"),\n Ordering::Greater => println!(\"Too big!\"),\n Ordering::Equal => println!(\"You win!\"),\n }\n```\nThe line is:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Comparing the Guess to the Secret Number"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#comparing-the-guess-to-the-secret-number", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch02-00-guessing-game-tutorial.md#comparing-the-guess-to-the-secret-number-26", "text": "The Rust Programming Language › Programming a Guessing Game › Comparing the Guess to the Secret Number\n\n```rust,ignore\nlet guess: u32 = guess.trim().parse().expect(\"Please type a number!\");\n```\nWe create a variable named `guess`. But wait, doesn’t the program already have\na variable named `guess`? It does, but helpfully Rust allows us to shadow the\nprevious value of `guess` with a new one. _Shadowing_ lets us reuse the `guess`\nvariable name rather than forcing us to create two unique variables, such as\n`guess_str` and `guess`, for example. We’ll cover this in more detail in\nChapter 3, but for now, know that this feature is\noften used when you want to convert a value from one type to another type.\nWe bind this new variable to the expression `guess.trim().parse()`. The `guess`\nin the expression refers to the original `guess` variable that contained the\ninput as a string. The `trim` method on a `String` instance will eliminate any\nwhitespace at the beginning and end, which we must do before we can convert the\nstring to a `u32`, which can only contain numerical data. The user must press\nenter to satisfy `read_line` and input their guess, which adds a\nnewline character to the string. For example, if the user types 5 and\npresses enter, `guess` looks like this: `5\\n`. The `\\n` represents\n“newline.” (On Windows, pressing enter results in a carriage return\nand a newline, `\\r\\n`.) The `trim` method eliminates `\\n` or `\\r\\n`, resulting\nin just `5`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Comparing the Guess to the Secret Number"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#comparing-the-guess-to-the-secret-number", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch02-00-guessing-game-tutorial.md#comparing-the-guess-to-the-secret-number-27", "text": "The Rust Programming Language › Programming a Guessing Game › Comparing the Guess to the Secret Number\n\nThe `parse` method on strings converts a string to\nanother type. Here, we use it to convert from a string to a number. We need to\ntell Rust the exact number type we want by using `let guess: u32`. The colon\n(`:`) after `guess` tells Rust we’ll annotate the variable’s type. Rust has a\nfew built-in number types; the `u32` seen here is an unsigned, 32-bit integer.\nIt’s a good default choice for a small positive number. You’ll learn about\nother number types in Chapter 3.\nAdditionally, the `u32` annotation in this example program and the comparison\nwith `secret_number` means Rust will infer that `secret_number` should be a\n`u32` as well. So, now the comparison will be between two values of the same\ntype!\nThe `parse` method will only work on characters that can logically be converted\ninto numbers and so can easily cause errors. If, for example, the string\ncontained `A👍%`, there would be no way to convert that to a number. Because it\nmight fail, the `parse` method returns a `Result` type, much as the `read_line`\nmethod does (discussed earlier in “Handling Potential Failure with\n`Result`”). We’ll treat\nthis `Result` the same way by using the `expect` method again. If `parse`\nreturns an `Err` `Result` variant because it couldn’t create a number from the\nstring, the `expect` call will crash the game and print the message we give it.\nIf `parse` can successfully convert the string to a number, it will return the\n`Ok` variant of `Result`, and `expect` will return the number that we want from\nthe `Ok` value.\nLet’s run the program now:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Comparing the Guess to the Secret Number"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#comparing-the-guess-to-the-secret-number", "has_code": false, "code_tags": []}} {"id": "book/ch02-00-guessing-game-tutorial.md#comparing-the-guess-to-the-secret-number-28", "text": "The Rust Programming Language › Programming a Guessing Game › Comparing the Guess to the Secret Number\n\n```console\n$ cargo run\n Compiling guessing_game v0.1.0 (file:///projects/guessing_game)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.26s\n Running `target/debug/guessing_game`\nGuess the number!\nThe secret number is: 58\nPlease input your guess.\n 76\nYou guessed: 76\nToo big!\n```\nNice! Even though spaces were added before the guess, the program still figured\nout that the user guessed 76. Run the program a few times to verify the\ndifferent behavior with different kinds of input: Guess the number correctly,\nguess a number that is too high, and guess a number that is too low.\nWe have most of the game working now, but the user can make only one guess.\nLet’s change that by adding a loop!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Comparing the Guess to the Secret Number"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#comparing-the-guess-to-the-secret-number", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch02-00-guessing-game-tutorial.md#allowing-multiple-guesses-with-looping-29", "text": "The Rust Programming Language › Programming a Guessing Game › Allowing Multiple Guesses with Looping\n\nThe `loop` keyword creates an infinite loop. We’ll add a loop to give users\nmore chances at guessing the number:\nFilename: src/main.rs\n```rust,ignore\n // --snip--\n\n println!(\"The secret number is: {secret_number}\");\n\n loop {\n println!(\"Please input your guess.\");\n\n // --snip--\n\n match guess.cmp(&secret_number) {\n Ordering::Less => println!(\"Too small!\"),\n Ordering::Greater => println!(\"Too big!\"),\n Ordering::Equal => println!(\"You win!\"),\n }\n }\n}\n```\nAs you can see, we’ve moved everything from the guess input prompt onward into\na loop. Be sure to indent the lines inside the loop another four spaces each\nand run the program again. The program will now ask for another guess forever,\nwhich actually introduces a new problem. It doesn’t seem like the user can quit!\nThe user could always interrupt the program by using the keyboard shortcut\nctrl-C. But there’s another way to escape this insatiable\nmonster, as mentioned in the `parse` discussion in “Comparing the Guess to the\nSecret Number”: If\nthe user enters a non-number answer, the program will crash. We can take\nadvantage of that to allow the user to quit, as shown here:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Allowing Multiple Guesses with Looping"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#allowing-multiple-guesses-with-looping", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch02-00-guessing-game-tutorial.md#allowing-multiple-guesses-with-looping-30", "text": "The Rust Programming Language › Programming a Guessing Game › Allowing Multiple Guesses with Looping\n\n```console\n$ cargo run\n Compiling guessing_game v0.1.0 (file:///projects/guessing_game)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.23s\n Running `target/debug/guessing_game`\nGuess the number!\nThe secret number is: 59\nPlease input your guess.\n45\nYou guessed: 45\nToo small!\nPlease input your guess.\n60\nYou guessed: 60\nToo big!\nPlease input your guess.\n59\nYou guessed: 59\nYou win!\nPlease input your guess.\nquit\n\nthread 'main' (6694925) panicked at src/main.rs:28:47:\nPlease type a number!: ParseIntError { kind: InvalidDigit }\nnote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n```\nTyping `quit` will quit the game, but as you’ll notice, so will entering any\nother non-number input. This is suboptimal, to say the least; we want the game\nto also stop when the correct number is guessed.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Allowing Multiple Guesses with Looping"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#allowing-multiple-guesses-with-looping", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch02-00-guessing-game-tutorial.md#quitting-after-a-correct-guess-31", "text": "The Rust Programming Language › Programming a Guessing Game › Allowing Multiple Guesses with Looping › Quitting After a Correct Guess\n\nLet’s program the game to quit when the user wins by adding a `break` statement:\nFilename: src/main.rs\n```rust,ignore\n // --snip--\n\n match guess.cmp(&secret_number) {\n Ordering::Less => println!(\"Too small!\"),\n Ordering::Greater => println!(\"Too big!\"),\n Ordering::Equal => {\n println!(\"You win!\");\n break;\n }\n }\n }\n}\n```\nAdding the `break` line after `You win!` makes the program exit the loop when\nthe user guesses the secret number correctly. Exiting the loop also means\nexiting the program, because the loop is the last part of `main`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Allowing Multiple Guesses with Looping", "Quitting After a Correct Guess"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#quitting-after-a-correct-guess", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch02-00-guessing-game-tutorial.md#handling-invalid-input-32", "text": "The Rust Programming Language › Programming a Guessing Game › Allowing Multiple Guesses with Looping › Handling Invalid Input\n\nTo further refine the game’s behavior, rather than crashing the program when\nthe user inputs a non-number, let’s make the game ignore a non-number so that\nthe user can continue guessing. We can do that by altering the line where\n`guess` is converted from a `String` to a `u32`, as shown in Listing 2-5.\nListing 2-5: Ignoring a non-number guess and asking for another guess instead of crashing the program (src/main.rs)\n```rust,ignore\n // --snip--\n\n io::stdin()\n .read_line(&mut guess)\n .expect(\"Failed to read line\");\n\n let guess: u32 = match guess.trim().parse() {\n Ok(num) => num,\n Err(_) => continue,\n };\n\n println!(\"You guessed: {guess}\");\n\n // --snip--\n```\nWe switch from an `expect` call to a `match` expression to move from crashing\non an error to handling the error. Remember that `parse` returns a `Result`\ntype and `Result` is an enum that has the variants `Ok` and `Err`. We’re using\na `match` expression here, as we did with the `Ordering` result of the `cmp`\nmethod.\nIf `parse` is able to successfully turn the string into a number, it will\nreturn an `Ok` value that contains the resultant number. That `Ok` value will\nmatch the first arm’s pattern, and the `match` expression will just return the\n`num` value that `parse` produced and put inside the `Ok` value. That number\nwill end up right where we want it in the new `guess` variable we’re creating.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Allowing Multiple Guesses with Looping", "Handling Invalid Input"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#handling-invalid-input", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch02-00-guessing-game-tutorial.md#handling-invalid-input-33", "text": "The Rust Programming Language › Programming a Guessing Game › Allowing Multiple Guesses with Looping › Handling Invalid Input\n\nIf `parse` is _not_ able to turn the string into a number, it will return an\n`Err` value that contains more information about the error. The `Err` value\ndoes not match the `Ok(num)` pattern in the first `match` arm, but it does\nmatch the `Err(_)` pattern in the second arm. The underscore, `_`, is a\ncatch-all value; in this example, we’re saying we want to match all `Err`\nvalues, no matter what information they have inside them. So, the program will\nexecute the second arm’s code, `continue`, which tells the program to go to the\nnext iteration of the `loop` and ask for another guess. So, effectively, the\nprogram ignores all errors that `parse` might encounter!\nNow everything in the program should work as expected. Let’s try it:\n```console\n$ cargo run\n Compiling guessing_game v0.1.0 (file:///projects/guessing_game)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.13s\n Running `target/debug/guessing_game`\nGuess the number!\nThe secret number is: 61\nPlease input your guess.\n10\nYou guessed: 10\nToo small!\nPlease input your guess.\n99\nYou guessed: 99\nToo big!\nPlease input your guess.\nfoo\nPlease input your guess.\n61\nYou guessed: 61\nYou win!\n```\nAwesome! With one tiny final tweak, we will finish the guessing game. Recall\nthat the program is still printing the secret number. That worked well for\ntesting, but it ruins the game. Let’s delete the `println!` that outputs the\nsecret number. Listing 2-6 shows the final code.\nListing 2-6: Complete guessing game code (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Allowing Multiple Guesses with Looping", "Handling Invalid Input"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#handling-invalid-input", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch02-00-guessing-game-tutorial.md#handling-invalid-input-34", "text": "The Rust Programming Language › Programming a Guessing Game › Allowing Multiple Guesses with Looping › Handling Invalid Input\n\n```rust,ignore\nuse std::cmp::Ordering;\nuse std::io;\n\nuse rand::prelude::*;\n\nfn main() {\n println!(\"Guess the number!\");\n\n let secret_number = rand::rng().random_range(1..=100);\n\n loop {\n println!(\"Please input your guess.\");\n\n let mut guess = String::new();\n\n io::stdin()\n .read_line(&mut guess)\n .expect(\"Failed to read line\");\n\n let guess: u32 = match guess.trim().parse() {\n Ok(num) => num,\n Err(_) => continue,\n };\n\n println!(\"You guessed: {guess}\");\n\n match guess.cmp(&secret_number) {\n Ordering::Less => println!(\"Too small!\"),\n Ordering::Greater => println!(\"Too big!\"),\n Ordering::Equal => {\n println!(\"You win!\");\n break;\n }\n }\n }\n}\n```\nAt this point, you’ve successfully built the guessing game. Congratulations!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Allowing Multiple Guesses with Looping", "Handling Invalid Input"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#handling-invalid-input", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch02-00-guessing-game-tutorial.md#summary-35", "text": "The Rust Programming Language › Programming a Guessing Game › Summary\n\nThis project was a hands-on way to introduce you to many new Rust concepts:\n`let`, `match`, functions, the use of external crates, and more. In the next\nfew chapters, you’ll learn about these concepts in more detail. Chapter 3\ncovers concepts that most programming languages have, such as variables, data\ntypes, and functions, and shows how to use them in Rust. Chapter 4 explores\nownership, a feature that makes Rust different from other languages. Chapter 5\ndiscusses structs and method syntax, and Chapter 6 explains how enums work.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Programming a Guessing Game", "heading_path": ["Programming a Guessing Game", "Summary"], "path": "ch02-00-guessing-game-tutorial.md", "url": "https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#summary", "has_code": false, "code_tags": []}} {"id": "book/ch03-00-common-programming-concepts.md#keywords-0", "text": "The Rust Programming Language › Common Programming Concepts › Keywords\n\nThis chapter covers concepts that appear in almost every programming language\nand how they work in Rust. Many programming languages have much in common at\ntheir core. None of the concepts presented in this chapter are unique to Rust,\nbut we’ll discuss them in the context of Rust and explain the conventions\naround using them.\nSpecifically, you’ll learn about variables, basic types, functions, comments,\nand control flow. These foundations will be in every Rust program, and learning\nthem early will give you a strong core to start from.\nThe Rust language has a set of _keywords_ that are reserved for use by the\nlanguage only, much as in other languages. Keep in mind that you cannot use\nthese words as names of variables or functions. Most of the keywords have\nspecial meanings, and you’ll be using them to do various tasks in your Rust\nprograms; a few have no current functionality associated with them but have\nbeen reserved for functionality that might be added to Rust in the future. You\ncan find the list of the keywords in Appendix A.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Common Programming Concepts", "heading_path": ["Common Programming Concepts", "Keywords"], "path": "ch03-00-common-programming-concepts.md", "url": "https://doc.rust-lang.org/book/ch03-00-common-programming-concepts.html#keywords", "has_code": false, "code_tags": []}} {"id": "book/ch03-01-variables-and-mutability.md#variables-and-mutability-0", "text": "The Rust Programming Language › Variables and Mutability\n\nAs mentioned in the “Storing Values with\nVariables” section, by default,\nvariables are immutable. This is one of many nudges Rust gives you to write\nyour code in a way that takes advantage of the safety and easy concurrency that\nRust offers. However, you still have the option to make your variables mutable.\nLet’s explore how and why Rust encourages you to favor immutability and why\nsometimes you might want to opt out.\nWhen a variable is immutable, once a value is bound to a name, you can’t change\nthat value. To illustrate this, generate a new project called _variables_ in\nyour _projects_ directory by using `cargo new variables`.\nThen, in your new _variables_ directory, open _src/main.rs_ and replace its\ncode with the following code, which won’t compile just yet:\nFilename: src/main.rs\n```rust,ignore,does_not_compile\nfn main() {\n let x = 5;\n println!(\"The value of x is: {x}\");\n x = 6;\n println!(\"The value of x is: {x}\");\n}\n```\nSave and run the program using `cargo run`. You should receive an error message\nregarding an immutability error, as shown in this output:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Variables and Mutability", "heading_path": ["Variables and Mutability"], "path": "ch03-01-variables-and-mutability.md", "url": "https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html#variables-and-mutability", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch03-01-variables-and-mutability.md#variables-and-mutability-1", "text": "The Rust Programming Language › Variables and Mutability\n\n```console\n$ cargo run\n Compiling variables v0.1.0 (file:///projects/variables)\nerror[E0384]: cannot assign twice to immutable variable `x`\n --> src/main.rs:4:5\n |\n2 | let x = 5;\n | - first assignment to `x`\n3 | println!(\"The value of x is: {x}\");\n4 | x = 6;\n | ^^^^^ cannot assign twice to immutable variable\n |\nhelp: consider making this binding mutable\n |\n2 | let mut x = 5;\n | +++\n\nFor more information about this error, try `rustc --explain E0384`.\nerror: could not compile `variables` (bin \"variables\") due to 1 previous error\n```\nThis example shows how the compiler helps you find errors in your programs.\nCompiler errors can be frustrating, but really they only mean your program\nisn’t safely doing what you want it to do yet; they do _not_ mean that you’re\nnot a good programmer! Experienced Rustaceans still get compiler errors.\nYou received the error message `` cannot assign twice to immutable variable `x` `` because you tried to assign a second value to the immutable `x` variable.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Variables and Mutability", "heading_path": ["Variables and Mutability"], "path": "ch03-01-variables-and-mutability.md", "url": "https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html#variables-and-mutability", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch03-01-variables-and-mutability.md#variables-and-mutability-2", "text": "The Rust Programming Language › Variables and Mutability\n\nIt’s important that we get compile-time errors when we attempt to change a\nvalue that’s designated as immutable, because this very situation can lead to\nbugs. If one part of our code operates on the assumption that a value will\nnever change and another part of our code changes that value, it’s possible\nthat the first part of the code won’t do what it was designed to do. The cause\nof this kind of bug can be difficult to track down after the fact, especially\nwhen the second piece of code changes the value only _sometimes_. The Rust\ncompiler guarantees that when you state that a value won’t change, it really\nwon’t change, so you don’t have to keep track of it yourself. Your code is thus\neasier to reason through.\nBut mutability can be very useful and can make code more convenient to write.\nAlthough variables are immutable by default, you can make them mutable by\nadding `mut` in front of the variable name as you did in Chapter\n2. Adding `mut` also conveys\nintent to future readers of the code by indicating that other parts of the code\nwill be changing this variable’s value.\nFor example, let’s change _src/main.rs_ to the following:\nFilename: src/main.rs\n```rust\nfn main() {\n let mut x = 5;\n println!(\"The value of x is: {x}\");\n x = 6;\n println!(\"The value of x is: {x}\");\n}\n```\nWhen we run the program now, we get this:\n```console\n$ cargo run\n Compiling variables v0.1.0 (file:///projects/variables)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.30s\n Running `target/debug/variables`\nThe value of x is: 5\nThe value of x is: 6\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Variables and Mutability", "heading_path": ["Variables and Mutability"], "path": "ch03-01-variables-and-mutability.md", "url": "https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html#variables-and-mutability", "has_code": true, "code_tags": ["console", "rust"]}} {"id": "book/ch03-01-variables-and-mutability.md#variables-and-mutability-3", "text": "The Rust Programming Language › Variables and Mutability\n\nWe’re allowed to change the value bound to `x` from `5` to `6` when `mut` is\nused. Ultimately, deciding whether to use mutability or not is up to you and\ndepends on what you think is clearest in that particular situation.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Variables and Mutability", "heading_path": ["Variables and Mutability"], "path": "ch03-01-variables-and-mutability.md", "url": "https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html#variables-and-mutability", "has_code": false, "code_tags": []}} {"id": "book/ch03-01-variables-and-mutability.md#declaring-constants-4", "text": "The Rust Programming Language › Variables and Mutability › Declaring Constants\n\nLike immutable variables, _constants_ are values that are bound to a name and\nare not allowed to change, but there are a few differences between constants\nand variables.\nFirst, you aren’t allowed to use `mut` with constants. Constants aren’t just\nimmutable by default—they’re always immutable. You declare constants using the\n`const` keyword instead of the `let` keyword, and the type of the value _must_\nbe annotated. We’ll cover types and type annotations in the next section,\n“Data Types”, so don’t worry about the details\nright now. Just know that you must always annotate the type.\nConstants can be declared in any scope, including the global scope, which makes\nthem useful for values that many parts of code need to know about.\nThe last difference is that constants may be set only to a constant expression,\nnot the result of a value that could only be computed at runtime.\nHere’s an example of a constant declaration:\n```rust\nconst THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;\n```\nThe constant’s name is `THREE_HOURS_IN_SECONDS`, and its value is set to the\nresult of multiplying 60 (the number of seconds in a minute) by 60 (the number\nof minutes in an hour) by 3 (the number of hours we want to count in this\nprogram). Rust’s naming convention for constants is to use all uppercase with\nunderscores between words. The compiler is able to evaluate a limited set of\noperations at compile time, which lets us choose to write out this value in a\nway that’s easier to understand and verify, rather than setting this constant\nto the value 10,800. See the Rust Reference’s section on constant\nevaluation for more information on what operations can be used\nwhen declaring constants.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Variables and Mutability", "heading_path": ["Variables and Mutability", "Declaring Constants"], "path": "ch03-01-variables-and-mutability.md", "url": "https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html#declaring-constants", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch03-01-variables-and-mutability.md#declaring-constants-5", "text": "The Rust Programming Language › Variables and Mutability › Declaring Constants\n\nConstants are valid for the entire time a program runs, within the scope in\nwhich they were declared. This property makes constants useful for values in\nyour application domain that multiple parts of the program might need to know\nabout, such as the maximum number of points any player of a game is allowed to\nearn, or the speed of light.\nNaming hardcoded values used throughout your program as constants is useful in\nconveying the meaning of that value to future maintainers of the code. It also\nhelps to have only one place in your code that you would need to change if the\nhardcoded value needed to be updated in the future.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Variables and Mutability", "heading_path": ["Variables and Mutability", "Declaring Constants"], "path": "ch03-01-variables-and-mutability.md", "url": "https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html#declaring-constants", "has_code": false, "code_tags": []}} {"id": "book/ch03-01-variables-and-mutability.md#shadowing-6", "text": "The Rust Programming Language › Variables and Mutability › Shadowing\n\nAs you saw in the guessing game tutorial in Chapter\n2, you can declare a\nnew variable with the same name as a previous variable. Rustaceans say that the\nfirst variable is _shadowed_ by the second, which means that the second\nvariable is what the compiler will see when you use the name of the variable.\nIn effect, the second variable overshadows the first, taking any uses of the\nvariable name to itself until either it itself is shadowed or the scope ends.\nWe can shadow a variable by using the same variable’s name and repeating the\nuse of the `let` keyword as follows:\nFilename: src/main.rs\n```rust\nfn main() {\n let x = 5;\n\n let x = x + 1;\n\n {\n let x = x * 2;\n println!(\"The value of x in the inner scope is: {x}\");\n }\n\n println!(\"The value of x is: {x}\");\n}\n```\nThis program first binds `x` to a value of `5`. Then, it creates a new variable\n`x` by repeating `let x =`, taking the original value and adding `1` so that\nthe value of `x` is `6`. Then, within an inner scope created with the curly\nbrackets, the third `let` statement also shadows `x` and creates a new\nvariable, multiplying the previous value by `2` to give `x` a value of `12`.\nWhen that scope is over, the inner shadowing ends and `x` returns to being `6`.\nWhen we run this program, it will output the following:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Variables and Mutability", "heading_path": ["Variables and Mutability", "Shadowing"], "path": "ch03-01-variables-and-mutability.md", "url": "https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html#shadowing", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch03-01-variables-and-mutability.md#shadowing-7", "text": "The Rust Programming Language › Variables and Mutability › Shadowing\n\n```console\n$ cargo run\n Compiling variables v0.1.0 (file:///projects/variables)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.31s\n Running `target/debug/variables`\nThe value of x in the inner scope is: 12\nThe value of x is: 6\n```\nShadowing is different from marking a variable as `mut` because we’ll get a\ncompile-time error if we accidentally try to reassign to this variable without\nusing the `let` keyword. By using `let`, we can perform a few transformations\non a value but have the variable be immutable after those transformations have\ncompleted.\nThe other difference between `mut` and shadowing is that because we’re\neffectively creating a new variable when we use the `let` keyword again, we can\nchange the type of the value but reuse the same name. For example, say our\nprogram asks a user to show how many spaces they want between some text by\ninputting space characters, and then we want to store that input as a number:\n```rust\n let spaces = \" \";\n let spaces = spaces.len();\n```\nThe first `spaces` variable is a string type, and the second `spaces` variable\nis a number type. Shadowing thus spares us from having to come up with\ndifferent names, such as `spaces_str` and `spaces_num`; instead, we can reuse\nthe simpler `spaces` name. However, if we try to use `mut` for this, as shown\nhere, we’ll get a compile-time error:\n```rust,ignore,does_not_compile\n let mut spaces = \" \";\n spaces = spaces.len();\n```\nThe error says we’re not allowed to mutate a variable’s type:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Variables and Mutability", "heading_path": ["Variables and Mutability", "Shadowing"], "path": "ch03-01-variables-and-mutability.md", "url": "https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html#shadowing", "has_code": true, "code_tags": ["console", "rust", "rust,ignore,does_not_compile"]}} {"id": "book/ch03-01-variables-and-mutability.md#shadowing-8", "text": "The Rust Programming Language › Variables and Mutability › Shadowing\n\n```console\n$ cargo run\n Compiling variables v0.1.0 (file:///projects/variables)\nerror[E0308]: mismatched types\n --> src/main.rs:3:14\n |\n2 | let mut spaces = \" \";\n | ----- expected due to this value\n3 | spaces = spaces.len();\n | ^^^^^^^^^^^^ expected `&str`, found `usize`\n\nFor more information about this error, try `rustc --explain E0308`.\nerror: could not compile `variables` (bin \"variables\") due to 1 previous error\n```\nNow that we’ve explored how variables work, let’s look at more data types they\ncan have.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Variables and Mutability", "heading_path": ["Variables and Mutability", "Shadowing"], "path": "ch03-01-variables-and-mutability.md", "url": "https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html#shadowing", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch03-02-data-types.md#data-types-0", "text": "The Rust Programming Language › Data Types\n\nEvery value in Rust is of a certain _data type_, which tells Rust what kind of\ndata is being specified so that it knows how to work with that data. We’ll look\nat two data type subsets: scalar and compound.\nKeep in mind that Rust is a _statically typed_ language, which means that it\nmust know the types of all variables at compile time. The compiler can usually\ninfer what type we want to use based on the value and how we use it. In cases\nwhen many types are possible, such as when we converted a `String` to a numeric\ntype using `parse` in the “Comparing the Guess to the Secret\nNumber” section in\nChapter 2, we must add a type annotation, like this:\n```rust\nlet guess: u32 = \"42\".parse().expect(\"Not a number!\");\n```\nIf we don’t add the `: u32` type annotation shown in the preceding code, Rust\nwill display the following error, which means the compiler needs more\ninformation from us to know which type we want to use:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Data Types", "heading_path": ["Data Types"], "path": "ch03-02-data-types.md", "url": "https://doc.rust-lang.org/book/ch03-02-data-types.html#data-types", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch03-02-data-types.md#data-types-1", "text": "The Rust Programming Language › Data Types\n\n```console\n$ cargo build\n Compiling no_type_annotations v0.1.0 (file:///projects/no_type_annotations)\nerror[E0284]: type annotations needed\n --> src/main.rs:2:9\n |\n2 | let guess = \"42\".parse().expect(\"Not a number!\");\n | ^^^^^ ----- type must be known at this point\n |\n = note: cannot satisfy `<_ as FromStr>::Err == _`\nhelp: consider giving `guess` an explicit type\n |\n2 | let guess: /* Type */ = \"42\".parse().expect(\"Not a number!\");\n | ++++++++++++\n\nFor more information about this error, try `rustc --explain E0284`.\nerror: could not compile `no_type_annotations` (bin \"no_type_annotations\") due to 1 previous error\n```\nYou’ll see different type annotations for other data types.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Data Types", "heading_path": ["Data Types"], "path": "ch03-02-data-types.md", "url": "https://doc.rust-lang.org/book/ch03-02-data-types.html#data-types", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch03-02-data-types.md#integer-types-2", "text": "The Rust Programming Language › Data Types › Scalar Types › Integer Types\n\nA _scalar_ type represents a single value. Rust has four primary scalar types:\nintegers, floating-point numbers, Booleans, and characters. You may recognize\nthese from other programming languages. Let’s jump into how they work in Rust.\nAn _integer_ is a number without a fractional component. We used one integer\ntype in Chapter 2, the `u32` type. This type declaration indicates that the\nvalue it’s associated with should be an unsigned integer (signed integer types\nstart with `i` instead of `u`) that takes up 32 bits of space. Table 3-1 shows\nthe built-in integer types in Rust. We can use any of these variants to declare\nthe type of an integer value.\nTable 3-1: Integer Types in Rust\n| Length | Signed | Unsigned |\n| ------- | ------- | -------- |\n| 8-bit | `i8` | `u8` |\n| 16-bit | `i16` | `u16` |\n| 32-bit | `i32` | `u32` |\n| 64-bit | `i64` | `u64` |\n| 128-bit | `i128` | `u128` |\n| Architecture-dependent | `isize` | `usize` |", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Data Types", "heading_path": ["Data Types", "Scalar Types", "Integer Types"], "path": "ch03-02-data-types.md", "url": "https://doc.rust-lang.org/book/ch03-02-data-types.html#integer-types", "has_code": false, "code_tags": []}} {"id": "book/ch03-02-data-types.md#integer-types-3", "text": "The Rust Programming Language › Data Types › Scalar Types › Integer Types\n\nEach variant can be either signed or unsigned and has an explicit size.\n_Signed_ and _unsigned_ refer to whether it’s possible for the number to be\nnegative—in other words, whether the number needs to have a sign with it\n(signed) or whether it will only ever be positive and can therefore be\nrepresented without a sign (unsigned). It’s like writing numbers on paper: When\nthe sign matters, a number is shown with a plus sign or a minus sign; however,\nwhen it’s safe to assume the number is positive, it’s shown with no sign.\nSigned numbers are stored using two’s complement\n representation.\nEach signed variant can store numbers from −(2n − 1) to 2n −\n1 − 1 inclusive, where _n_ is the number of bits that variant uses. So, an\n`i8` can store numbers from −(27) to 27 − 1, which equals\n−128 to 127. Unsigned variants can store numbers from 0 to 2n − 1,\nso a `u8` can store numbers from 0 to 28 − 1, which equals 0 to 255.\nAdditionally, the `isize` and `usize` types depend on the architecture of the\ncomputer your program is running on: 64 bits if you’re on a 64-bit architecture\nand 32 bits if you’re on a 32-bit architecture.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Data Types", "heading_path": ["Data Types", "Scalar Types", "Integer Types"], "path": "ch03-02-data-types.md", "url": "https://doc.rust-lang.org/book/ch03-02-data-types.html#integer-types", "has_code": false, "code_tags": []}} {"id": "book/ch03-02-data-types.md#integer-overflow-4", "text": "The Rust Programming Language › Data Types › Scalar Types › Integer Types › Integer Overflow\n\nYou can write integer literals in any of the forms shown in Table 3-2. Note\nthat number literals that can be multiple numeric types allow a type suffix,\nsuch as `57u8`, to designate the type. Number literals can also use `_` as a\nvisual separator to make the number easier to read, such as `1_000`, which will\nhave the same value as if you had specified `1000`.\nTable 3-2: Integer Literals in Rust\n| Number literals | Example |\n| ---------------- | ------------- |\n| Decimal | `98_222` |\n| Hex | `0xff` |\n| Octal | `0o77` |\n| Binary | `0b1111_0000` |\n| Byte (`u8` only) | `b'A'` |\nSo how do you know which type of integer to use? If you’re unsure, Rust’s\ndefaults are generally good places to start: Integer types default to `i32`.\nThe primary situation in which you’d use `isize` or `usize` is when indexing\nsome sort of collection.\nLet’s say you have a variable of type `u8` that can hold values between 0 and\n255. If you try to change the variable to a value outside that range, such as\n256, _integer overflow_ will occur, which can result in one of two behaviors.\nWhen you’re compiling in debug mode, Rust includes checks for integer overflow\nthat cause your program to _panic_ at runtime if this behavior occurs. Rust\nuses the term _panicking_ when a program exits with an error; we’ll discuss\npanics in more depth in the “Unrecoverable Errors with\n`panic!`” section in Chapter\n9.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Data Types", "heading_path": ["Data Types", "Scalar Types", "Integer Types", "Integer Overflow"], "path": "ch03-02-data-types.md", "url": "https://doc.rust-lang.org/book/ch03-02-data-types.html#integer-overflow", "has_code": false, "code_tags": []}} {"id": "book/ch03-02-data-types.md#floating-point-types-5", "text": "The Rust Programming Language › Data Types › Scalar Types › Floating-Point Types\n\nWhen you’re compiling in release mode with the `--release` flag, Rust does\n_not_ include checks for integer overflow that cause panics. Instead, if\noverflow occurs, Rust performs _two’s complement wrapping_. In short, values\ngreater than the maximum value the type can hold “wrap around” to the minimum\nof the values the type can hold. In the case of a `u8`, the value 256 becomes\n0, the value 257 becomes 1, and so on. The program won’t panic, but the\nvariable will have a value that probably isn’t what you were expecting it to\nhave. Relying on integer overflow’s wrapping behavior is considered an error.\nTo explicitly handle the possibility of overflow, you can use these families\nof methods provided by the standard library for primitive numeric types:\n- Wrap in all compilation modes with the `wrapping_*` methods, such as \n `wrapping_add`.\n- Return the `None` value if there is overflow with the `checked_*` methods.\n- Return the value and a Boolean indicating whether there was overflow with\n the `overflowing_*` methods.\n- Saturate at the value’s minimum or maximum values with the `saturating_*`\n methods.\nRust also has two primitive types for _floating-point numbers_, which are\nnumbers with decimal points. Rust’s floating-point types are `f32` and `f64`,\nwhich are 32 bits and 64 bits in size, respectively. The default type is `f64`\nbecause on modern CPUs, it’s roughly the same speed as `f32` but is capable of\nmore precision. All floating-point types are signed.\nHere’s an example that shows floating-point numbers in action:\nFilename: src/main.rs", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Data Types", "heading_path": ["Data Types", "Scalar Types", "Floating-Point Types"], "path": "ch03-02-data-types.md", "url": "https://doc.rust-lang.org/book/ch03-02-data-types.html#floating-point-types", "has_code": false, "code_tags": []}} {"id": "book/ch03-02-data-types.md#the-character-type-6", "text": "The Rust Programming Language › Data Types › Scalar Types › The Character Type\n\n```rust\nfn main() {\n let x = 2.0; // f64\n\n let y: f32 = 3.0; // f32\n}\n```\nFloating-point numbers are represented according to the IEEE-754 standard.\nRust supports the basic mathematical operations you’d expect for all the number\ntypes: addition, subtraction, multiplication, division, and remainder. Integer\ndivision truncates toward zero to the nearest integer. The following code shows\nhow you’d use each numeric operation in a `let` statement:\nFilename: src/main.rs\n```rust\nfn main() {\n // addition\n let sum = 5 + 10;\n\n // subtraction\n let difference = 95.5 - 4.3;\n\n // multiplication\n let product = 4 * 30;\n\n // division\n let quotient = 56.7 / 32.2;\n let truncated = -5 / 3; // Results in -1\n\n // remainder\n let remainder = 43 % 5;\n}\n```\nEach expression in these statements uses a mathematical operator and evaluates\nto a single value, which is then bound to a variable. Appendix\nB contains a list of all operators that Rust\nprovides.\nAs in most other programming languages, a Boolean type in Rust has two possible\nvalues: `true` and `false`. Booleans are one byte in size. The Boolean type in\nRust is specified using `bool`. For example:\nFilename: src/main.rs\n```rust\nfn main() {\n let t = true;\n\n let f: bool = false; // with explicit type annotation\n}\n```\nThe main way to use Boolean values is through conditionals, such as an `if`\nexpression. We’ll cover how `if` expressions work in Rust in the “Control\nFlow” section.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Data Types", "heading_path": ["Data Types", "Scalar Types", "The Character Type"], "path": "ch03-02-data-types.md", "url": "https://doc.rust-lang.org/book/ch03-02-data-types.html#the-character-type", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch03-02-data-types.md#the-character-type-7", "text": "The Rust Programming Language › Data Types › Scalar Types › The Character Type\n\nRust’s `char` type is the language’s most primitive alphabetic type. Here are\nsome examples of declaring `char` values:\nFilename: src/main.rs\n```rust\nfn main() {\n let c = 'z';\n let z: char = 'ℤ'; // with explicit type annotation\n let heart_eyed_cat = '😻';\n}\n```\nNote that we specify `char` literals with single quotation marks, as opposed to\nstring literals, which use double quotation marks. Rust’s `char` type is 4\nbytes in size and represents a Unicode scalar value, which means it can\nrepresent a lot more than just ASCII. Accented letters; Chinese, Japanese, and\nKorean characters; emojis; and zero-width spaces are all valid `char` values in\nRust. Unicode scalar values range from `U+0000` to `U+D7FF` and `U+E000` to\n`U+10FFFF` inclusive. However, a “character” isn’t really a concept in Unicode,\nso your human intuition for what a “character” is may not match up with what a\n`char` is in Rust. We’ll discuss this topic in detail in “Storing UTF-8\nEncoded Text with Strings” in Chapter 8.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Data Types", "heading_path": ["Data Types", "Scalar Types", "The Character Type"], "path": "ch03-02-data-types.md", "url": "https://doc.rust-lang.org/book/ch03-02-data-types.html#the-character-type", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch03-02-data-types.md#the-tuple-type-8", "text": "The Rust Programming Language › Data Types › Compound Types › The Tuple Type\n\n_Compound types_ can group multiple values into one type. Rust has two\nprimitive compound types: tuples and arrays.\nA _tuple_ is a general way of grouping together a number of values with a\nvariety of types into one compound type. Tuples have a fixed length: Once\ndeclared, they cannot grow or shrink in size.\nWe create a tuple by writing a comma-separated list of values inside\nparentheses. Each position in the tuple has a type, and the types of the\ndifferent values in the tuple don’t have to be the same. We’ve added optional\ntype annotations in this example:\nFilename: src/main.rs\n```rust\nfn main() {\n let tup: (i32, f64, u8) = (500, 6.4, 1);\n}\n```\nThe variable `tup` binds to the entire tuple because a tuple is considered a\nsingle compound element. To get the individual values out of a tuple, we can\nuse pattern matching to destructure a tuple value, like this:\nFilename: src/main.rs\n```rust\nfn main() {\n let tup = (500, 6.4, 1);\n\n let (x, y, z) = tup;\n\n println!(\"The value of y is: {y}\");\n}\n```\nThis program first creates a tuple and binds it to the variable `tup`. It then\nuses a pattern with `let` to take `tup` and turn it into three separate\nvariables, `x`, `y`, and `z`. This is called _destructuring_ because it breaks\nthe single tuple into three parts. Finally, the program prints the value of\n`y`, which is `6.4`.\nWe can also access a tuple element directly by using a period (`.`) followed by\nthe index of the value we want to access. For example:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Data Types", "heading_path": ["Data Types", "Compound Types", "The Tuple Type"], "path": "ch03-02-data-types.md", "url": "https://doc.rust-lang.org/book/ch03-02-data-types.html#the-tuple-type", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch03-02-data-types.md#the-array-type-9", "text": "The Rust Programming Language › Data Types › Compound Types › The Array Type\n\nFilename: src/main.rs\n```rust\nfn main() {\n let x: (i32, f64, u8) = (500, 6.4, 1);\n\n let five_hundred = x.0;\n\n let six_point_four = x.1;\n\n let one = x.2;\n}\n```\nThis program creates the tuple `x` and then accesses each element of the tuple\nusing their respective indices. As with most programming languages, the first\nindex in a tuple is 0.\nThe tuple without any values has a special name, _unit_. This value and its\ncorresponding type are both written `()` and represent an empty value or an\nempty return type. Expressions implicitly return the unit value if they don’t\nreturn any other value.\nAnother way to have a collection of multiple values is with an _array_. Unlike\na tuple, every element of an array must have the same type. Unlike arrays in\nsome other languages, arrays in Rust have a fixed length.\nWe write the values in an array as a comma-separated list inside square\nbrackets:\nFilename: src/main.rs\n```rust\nfn main() {\n let a = [1, 2, 3, 4, 5];\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Data Types", "heading_path": ["Data Types", "Compound Types", "The Array Type"], "path": "ch03-02-data-types.md", "url": "https://doc.rust-lang.org/book/ch03-02-data-types.html#the-array-type", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch03-02-data-types.md#the-array-type-10", "text": "The Rust Programming Language › Data Types › Compound Types › The Array Type\n\nArrays are useful when you want your data allocated on the stack, the same as\nthe other types we have seen so far, rather than the heap (we will discuss the\nstack and the heap more in Chapter 4) or when\nyou want to ensure that you always have a fixed number of elements. An array\nisn’t as flexible as the vector type, though. A vector is a similar collection\ntype provided by the standard library that _is_ allowed to grow or shrink in\nsize because its contents live on the heap. If you’re unsure whether to use an\narray or a vector, chances are you should use a vector. Chapter\n8 discusses vectors in more detail.\nHowever, arrays are more useful when you know the number of elements will not\nneed to change. For example, if you were using the names of the month in a\nprogram, you would probably use an array rather than a vector because you know\nit will always contain 12 elements:\n```rust\nlet months = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\",\n \"August\", \"September\", \"October\", \"November\", \"December\"];\n```\nYou write an array’s type using square brackets with the type of each element,\na semicolon, and then the number of elements in the array, like so:\n```rust\nlet a: [i32; 5] = [1, 2, 3, 4, 5];\n```\nHere, `i32` is the type of each element. After the semicolon, the number `5`\nindicates the array contains five elements.\nYou can also initialize an array to contain the same value for each element by\nspecifying the initial value, followed by a semicolon, and then the length of\nthe array in square brackets, as shown here:\n```rust\nlet a = [3; 5];\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Data Types", "heading_path": ["Data Types", "Compound Types", "The Array Type"], "path": "ch03-02-data-types.md", "url": "https://doc.rust-lang.org/book/ch03-02-data-types.html#the-array-type", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch03-02-data-types.md#invalid-array-element-access-11", "text": "The Rust Programming Language › Data Types › Compound Types › Invalid Array Element Access\n\nThe array named `a` will contain `5` elements that will all be set to the value\n`3` initially. This is the same as writing `let a = [3, 3, 3, 3, 3];` but in a\nmore concise way.\nAn array is a single chunk of memory of a known, fixed size that can be\nallocated on the stack. You can access elements of an array using indexing,\nlike this:\nFilename: src/main.rs\n```rust\nfn main() {\n let a = [1, 2, 3, 4, 5];\n\n let first = a[0];\n let second = a[1];\n}\n```\nIn this example, the variable named `first` will get the value `1` because that\nis the value at index `[0]` in the array. The variable named `second` will get\nthe value `2` from index `[1]` in the array.\nLet’s see what happens if you try to access an element of an array that is past\nthe end of the array. Say you run this code, similar to the guessing game in\nChapter 2, to get an array index from the user:\nFilename: src/main.rs\n```rust,ignore,panics\nuse std::io;\n\nfn main() {\n let a = [1, 2, 3, 4, 5];\n\n println!(\"Please enter an array index.\");\n\n let mut index = String::new();\n\n io::stdin()\n .read_line(&mut index)\n .expect(\"Failed to read line\");\n\n let index: usize = index\n .trim()\n .parse()\n .expect(\"Index entered was not a number\");\n\n let element = a[index];\n\n println!(\"The value of the element at index {index} is: {element}\");\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Data Types", "heading_path": ["Data Types", "Compound Types", "Invalid Array Element Access"], "path": "ch03-02-data-types.md", "url": "https://doc.rust-lang.org/book/ch03-02-data-types.html#invalid-array-element-access", "has_code": true, "code_tags": ["rust", "rust,ignore,panics"]}} {"id": "book/ch03-02-data-types.md#invalid-array-element-access-12", "text": "The Rust Programming Language › Data Types › Compound Types › Invalid Array Element Access\n\nThis code compiles successfully. If you run this code using `cargo run` and\nenter `0`, `1`, `2`, `3`, or `4`, the program will print out the corresponding\nvalue at that index in the array. If you instead enter a number past the end of\nthe array, such as `10`, you’ll see output like this:\n```console\nthread 'main' panicked at src/main.rs:19:19:\nindex out of bounds: the len is 5 but the index is 10\nnote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n```\nThe program resulted in a runtime error at the point of using an invalid\nvalue in the indexing operation. The program exited with an error message and\ndidn’t execute the final `println!` statement. When you attempt to access an\nelement using indexing, Rust will check that the index you’ve specified is less\nthan the array length. If the index is greater than or equal to the length,\nRust will panic. This check has to happen at runtime, especially in this case,\nbecause the compiler can’t possibly know what value a user will enter when they\nrun the code later.\nThis is an example of Rust’s memory safety principles in action. In many\nlow-level languages, this kind of check is not done, and when you provide an\nincorrect index, invalid memory can be accessed. Rust protects you against this\nkind of error by immediately exiting instead of allowing the memory access and\ncontinuing. Chapter 9 discusses more of Rust’s error handling and how you can\nwrite readable, safe code that neither panics nor allows invalid memory access.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Data Types", "heading_path": ["Data Types", "Compound Types", "Invalid Array Element Access"], "path": "ch03-02-data-types.md", "url": "https://doc.rust-lang.org/book/ch03-02-data-types.html#invalid-array-element-access", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch03-03-how-functions-work.md#functions-0", "text": "The Rust Programming Language › Functions\n\nFunctions are prevalent in Rust code. You’ve already seen one of the most\nimportant functions in the language: the `main` function, which is the entry\npoint of many programs. You’ve also seen the `fn` keyword, which allows you to\ndeclare new functions.\nRust code uses _snake case_ as the conventional style for function and variable\nnames, in which all letters are lowercase and underscores separate words.\nHere’s a program that contains an example function definition:\nFilename: src/main.rs\n```rust\nfn main() {\n println!(\"Hello, world!\");\n\n another_function();\n}\n\nfn another_function() {\n println!(\"Another function.\");\n}\n```\nWe define a function in Rust by entering `fn` followed by a function name and a\nset of parentheses. The curly brackets tell the compiler where the function\nbody begins and ends.\nWe can call any function we’ve defined by entering its name followed by a set\nof parentheses. Because `another_function` is defined in the program, it can be\ncalled from inside the `main` function. Note that we defined `another_function`\n_after_ the `main` function in the source code; we could have defined it before\nas well. Rust doesn’t care where you define your functions, only that they’re\ndefined somewhere in a scope that can be seen by the caller.\nLet’s start a new binary project named _functions_ to explore functions\nfurther. Place the `another_function` example in _src/main.rs_ and run it. You\nshould see the following output:\n```console\n$ cargo run\n Compiling functions v0.1.0 (file:///projects/functions)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.28s\n Running `target/debug/functions`\nHello, world!\nAnother function.\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Functions", "heading_path": ["Functions"], "path": "ch03-03-how-functions-work.md", "url": "https://doc.rust-lang.org/book/ch03-03-how-functions-work.html#functions", "has_code": true, "code_tags": ["console", "rust"]}} {"id": "book/ch03-03-how-functions-work.md#functions-1", "text": "The Rust Programming Language › Functions\n\nThe lines execute in the order in which they appear in the `main` function.\nFirst the “Hello, world!” message prints, and then `another_function` is called\nand its message is printed.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Functions", "heading_path": ["Functions"], "path": "ch03-03-how-functions-work.md", "url": "https://doc.rust-lang.org/book/ch03-03-how-functions-work.html#functions", "has_code": false, "code_tags": []}} {"id": "book/ch03-03-how-functions-work.md#parameters-2", "text": "The Rust Programming Language › Functions › Parameters\n\nWe can define functions to have _parameters_, which are special variables that\nare part of a function’s signature. When a function has parameters, you can\nprovide it with concrete values for those parameters. Technically, the concrete\nvalues are called _arguments_, but in casual conversation, people tend to use\nthe words _parameter_ and _argument_ interchangeably for either the variables\nin a function’s definition or the concrete values passed in when you call a\nfunction.\nIn this version of `another_function` we add a parameter:\nFilename: src/main.rs\n```rust\nfn main() {\n another_function(5);\n}\n\nfn another_function(x: i32) {\n println!(\"The value of x is: {x}\");\n}\n```\nTry running this program; you should get the following output:\n```console\n$ cargo run\n Compiling functions v0.1.0 (file:///projects/functions)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.21s\n Running `target/debug/functions`\nThe value of x is: 5\n```\nThe declaration of `another_function` has one parameter named `x`. The type of\n`x` is specified as `i32`. When we pass `5` in to `another_function`, the\n`println!` macro puts `5` where the pair of curly brackets containing `x` was\nin the format string.\nIn function signatures, you _must_ declare the type of each parameter. This is\na deliberate decision in Rust’s design: Requiring type annotations in function\ndefinitions means the compiler almost never needs you to use them elsewhere in\nthe code to figure out what type you mean. The compiler is also able to give\nmore-helpful error messages if it knows what types the function expects.\nWhen defining multiple parameters, separate the parameter declarations with\ncommas, like this:\nFilename: src/main.rs", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Functions", "heading_path": ["Functions", "Parameters"], "path": "ch03-03-how-functions-work.md", "url": "https://doc.rust-lang.org/book/ch03-03-how-functions-work.html#parameters", "has_code": true, "code_tags": ["console", "rust"]}} {"id": "book/ch03-03-how-functions-work.md#parameters-3", "text": "The Rust Programming Language › Functions › Parameters\n\n```rust\nfn main() {\n print_labeled_measurement(5, 'h');\n}\n\nfn print_labeled_measurement(value: i32, unit_label: char) {\n println!(\"The measurement is: {value}{unit_label}\");\n}\n```\nThis example creates a function named `print_labeled_measurement` with two\nparameters. The first parameter is named `value` and is an `i32`. The second is\nnamed `unit_label` and is type `char`. The function then prints text containing\nboth the `value` and the `unit_label`.\nLet’s try running this code. Replace the program currently in your _functions_\nproject’s _src/main.rs_ file with the preceding example and run it using `cargo\nrun`:\n```console\n$ cargo run\n Compiling functions v0.1.0 (file:///projects/functions)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.31s\n Running `target/debug/functions`\nThe measurement is: 5h\n```\nBecause we called the function with `5` as the value for `value` and `'h'` as\nthe value for `unit_label`, the program output contains those values.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Functions", "heading_path": ["Functions", "Parameters"], "path": "ch03-03-how-functions-work.md", "url": "https://doc.rust-lang.org/book/ch03-03-how-functions-work.html#parameters", "has_code": true, "code_tags": ["console", "rust"]}} {"id": "book/ch03-03-how-functions-work.md#statements-and-expressions-4", "text": "The Rust Programming Language › Functions › Statements and Expressions\n\nFunction bodies are made up of a series of statements optionally ending in an\nexpression. So far, the functions we’ve covered haven’t included an ending\nexpression, but you have seen an expression as part of a statement. Because\nRust is an expression-based language, this is an important distinction to\nunderstand. Other languages don’t have the same distinctions, so let’s look at\nwhat statements and expressions are and how their differences affect the bodies\nof functions.\n- _Statements_ are instructions that perform some action and do not return\n a value.\n- _Expressions_ evaluate to a resultant value.\nLet’s look at some examples.\nWe’ve actually already used statements and expressions. Creating a variable and\nassigning a value to it with the `let` keyword is a statement. In Listing 3-1,\n`let y = 6;` is a statement.\nListing 3-1: A `main` function declaration containing one statement (src/main.rs)\n```rust\nfn main() {\n let y = 6;\n}\n```\nFunction definitions are also statements; the entire preceding example is a\nstatement in itself. (As we’ll see shortly, calling a function is not a\nstatement, though.)\nStatements do not return values. Therefore, you can’t assign a `let` statement\nto another variable, as the following code tries to do; you’ll get an error:\nFilename: src/main.rs\n```rust,ignore,does_not_compile\nfn main() {\n let x = (let y = 6);\n}\n```\nWhen you run this program, the error you’ll get looks like this:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Functions", "heading_path": ["Functions", "Statements and Expressions"], "path": "ch03-03-how-functions-work.md", "url": "https://doc.rust-lang.org/book/ch03-03-how-functions-work.html#statements-and-expressions", "has_code": true, "code_tags": ["rust", "rust,ignore,does_not_compile"]}} {"id": "book/ch03-03-how-functions-work.md#statements-and-expressions-5", "text": "The Rust Programming Language › Functions › Statements and Expressions\n\n```console\n$ cargo run\n Compiling functions v0.1.0 (file:///projects/functions)\nerror: expected expression, found `let` statement\n --> src/main.rs:2:14\n |\n2 | let x = (let y = 6);\n | ^^^\n |\n = note: only supported directly in conditions of `if` and `while` expressions\n\nwarning: unnecessary parentheses around assigned value\n --> src/main.rs:2:13\n |\n2 | let x = (let y = 6);\n | ^ ^\n |\n = note: `#[warn(unused_parens)]` (part of `#[warn(unused)]`) on by default\nhelp: remove these parentheses\n |\n2 - let x = (let y = 6);\n2 + let x = let y = 6 ;\n |\n\nwarning: `functions` (bin \"functions\") generated 1 warning\nerror: could not compile `functions` (bin \"functions\") due to 1 previous error; 1 warning emitted\n```\nThe `let y = 6` statement does not return a value, so there isn’t anything for\n`x` to bind to. This is different from what happens in other languages, such as\nC and Ruby, where the assignment returns the value of the assignment. In those\nlanguages, you can write `x = y = 6` and have both `x` and `y` have the value\n`6`; that is not the case in Rust.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Functions", "heading_path": ["Functions", "Statements and Expressions"], "path": "ch03-03-how-functions-work.md", "url": "https://doc.rust-lang.org/book/ch03-03-how-functions-work.html#statements-and-expressions", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch03-03-how-functions-work.md#statements-and-expressions-6", "text": "The Rust Programming Language › Functions › Statements and Expressions\n\nExpressions evaluate to a value and make up most of the rest of the code that\nyou’ll write in Rust. Consider a math operation, such as `5 + 6`, which is an\nexpression that evaluates to the value `11`. Expressions can be part of\nstatements: In Listing 3-1, the `6` in the statement `let y = 6;` is an\nexpression that evaluates to the value `6`. Calling a function is an\nexpression. Calling a macro is an expression. A new scope block created with\ncurly brackets is an expression, for example:\nFilename: src/main.rs\n```rust\nfn main() {\n let y = {\n let x = 3;\n x + 1\n };\n\n println!(\"The value of y is: {y}\");\n}\n```\nThis expression:\n```rust,ignore\n{\n let x = 3;\n x + 1\n}\n```\nis a block that, in this case, evaluates to `4`. That value gets bound to `y`\nas part of the `let` statement. Note the `x + 1` line without a semicolon at\nthe end, which is unlike most of the lines you’ve seen so far. Expressions do\nnot include ending semicolons. If you add a semicolon to the end of an\nexpression, you turn it into a statement, and it will then not return a value.\nKeep this in mind as you explore function return values and expressions next.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Functions", "heading_path": ["Functions", "Statements and Expressions"], "path": "ch03-03-how-functions-work.md", "url": "https://doc.rust-lang.org/book/ch03-03-how-functions-work.html#statements-and-expressions", "has_code": true, "code_tags": ["rust", "rust,ignore"]}} {"id": "book/ch03-03-how-functions-work.md#functions-with-return-values-7", "text": "The Rust Programming Language › Functions › Functions with Return Values\n\nFunctions can return values to the code that calls them. We don’t name return\nvalues, but we must declare their type after an arrow (`->`). In Rust, the\nreturn value of the function is synonymous with the value of the final\nexpression in the block of the body of a function. You can return early from a\nfunction by using the `return` keyword and specifying a value, but most\nfunctions return the last expression implicitly. Here’s an example of a\nfunction that returns a value:\nFilename: src/main.rs\n```rust\nfn five() -> i32 {\n 5\n}\n\nfn main() {\n let x = five();\n\n println!(\"The value of x is: {x}\");\n}\n```\nThere are no function calls, macros, or even `let` statements in the `five`\nfunction—just the number `5` by itself. That’s a perfectly valid function in\nRust. Note that the function’s return type is specified too, as `-> i32`. Try\nrunning this code; the output should look like this:\n```console\n$ cargo run\n Compiling functions v0.1.0 (file:///projects/functions)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.30s\n Running `target/debug/functions`\nThe value of x is: 5\n```\nThe `5` in `five` is the function’s return value, which is why the return type\nis `i32`. Let’s examine this in more detail. There are two important bits:\nFirst, the line `let x = five();` shows that we’re using the return value of a\nfunction to initialize a variable. Because the function `five` returns a `5`,\nthat line is the same as the following:\n```rust\nlet x = 5;\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Functions", "heading_path": ["Functions", "Functions with Return Values"], "path": "ch03-03-how-functions-work.md", "url": "https://doc.rust-lang.org/book/ch03-03-how-functions-work.html#functions-with-return-values", "has_code": true, "code_tags": ["console", "rust"]}} {"id": "book/ch03-03-how-functions-work.md#functions-with-return-values-8", "text": "The Rust Programming Language › Functions › Functions with Return Values\n\nSecond, the `five` function has no parameters and defines the type of the\nreturn value, but the body of the function is a lonely `5` with no semicolon\nbecause it’s an expression whose value we want to return.\nLet’s look at another example:\nFilename: src/main.rs\n```rust\nfn main() {\n let x = plus_one(5);\n\n println!(\"The value of x is: {x}\");\n}\n\nfn plus_one(x: i32) -> i32 {\n x + 1\n}\n```\nRunning this code will print `The value of x is: 6`. But what happens if we\nplace a semicolon at the end of the line containing `x + 1`, changing it from\nan expression to a statement?\nFilename: src/main.rs\n```rust,ignore,does_not_compile\nfn main() {\n let x = plus_one(5);\n\n println!(\"The value of x is: {x}\");\n}\n\nfn plus_one(x: i32) -> i32 {\n x + 1;\n}\n```\nCompiling this code will produce an error, as follows:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Functions", "heading_path": ["Functions", "Functions with Return Values"], "path": "ch03-03-how-functions-work.md", "url": "https://doc.rust-lang.org/book/ch03-03-how-functions-work.html#functions-with-return-values", "has_code": true, "code_tags": ["rust", "rust,ignore,does_not_compile"]}} {"id": "book/ch03-03-how-functions-work.md#functions-with-return-values-9", "text": "The Rust Programming Language › Functions › Functions with Return Values\n\n```console\n$ cargo run\n Compiling functions v0.1.0 (file:///projects/functions)\nerror[E0308]: mismatched types\n --> src/main.rs:7:24\n |\n7 | fn plus_one(x: i32) -> i32 {\n | -------- ^^^ expected `i32`, found `()`\n | |\n | implicitly returns `()` as its body has no tail or `return` expression\n8 | x + 1;\n | - help: remove this semicolon to return this value\n\nFor more information about this error, try `rustc --explain E0308`.\nerror: could not compile `functions` (bin \"functions\") due to 1 previous error\n```\nThe main error message, `mismatched types`, reveals the core issue with this\ncode. The definition of the function `plus_one` says that it will return an\n`i32`, but statements don’t evaluate to a value, which is expressed by `()`,\nthe unit type. Therefore, nothing is returned, which contradicts the function\ndefinition and results in an error. In this output, Rust provides a message to\npossibly help rectify this issue: It suggests removing the semicolon, which\nwould fix the error.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Functions", "heading_path": ["Functions", "Functions with Return Values"], "path": "ch03-03-how-functions-work.md", "url": "https://doc.rust-lang.org/book/ch03-03-how-functions-work.html#functions-with-return-values", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch03-04-comments.md#comments-0", "text": "The Rust Programming Language › Comments\n\nAll programmers strive to make their code easy to understand, but sometimes\nextra explanation is warranted. In these cases, programmers leave _comments_ in\ntheir source code that the compiler will ignore but that people reading the\nsource code may find useful.\nHere’s a simple comment:\n```rust\n// hello, world\n```\nIn Rust, the idiomatic comment style starts a comment with two slashes, and the\ncomment continues until the end of the line. For comments that extend beyond a\nsingle line, you’ll need to include `//` on each line, like this:\n```rust\n// So we're doing something complicated here, long enough that we need\n// multiple lines of comments to do it! Whew! Hopefully, this comment will\n// explain what's going on.\n```\nComments can also be placed at the end of lines containing code:\nFilename: src/main.rs\n```rust\nfn main() {\n let lucky_number = 7; // I'm feeling lucky today\n}\n```\nBut you’ll more often see them used in this format, with the comment on a\nseparate line above the code it’s annotating:\nFilename: src/main.rs\n```rust\nfn main() {\n // I'm feeling lucky today\n let lucky_number = 7;\n}\n```\nRust also has another kind of comment, documentation comments, which we’ll\ndiscuss in the “Publishing a Crate to Crates.io”\nsection of Chapter 14.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Comments", "heading_path": ["Comments"], "path": "ch03-04-comments.md", "url": "https://doc.rust-lang.org/book/ch03-04-comments.html#comments", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch03-05-control-flow.md#control-flow-0", "text": "The Rust Programming Language › Control Flow\n\nThe ability to run some code depending on whether a condition is `true` and the\nability to run some code repeatedly while a condition is `true` are basic\nbuilding blocks in most programming languages. The most common constructs that\nlet you control the flow of execution of Rust code are `if` expressions and\nloops.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Control Flow", "heading_path": ["Control Flow"], "path": "ch03-05-control-flow.md", "url": "https://doc.rust-lang.org/book/ch03-05-control-flow.html#control-flow", "has_code": false, "code_tags": []}} {"id": "book/ch03-05-control-flow.md#if-expressions-1", "text": "The Rust Programming Language › Control Flow › `if` Expressions\n\nAn `if` expression allows you to branch your code depending on conditions. You\nprovide a condition and then state, “If this condition is met, run this block\nof code. If the condition is not met, do not run this block of code.”\nCreate a new project called _branches_ in your _projects_ directory to explore\nthe `if` expression. In the _src/main.rs_ file, input the following:\nFilename: src/main.rs\n```rust\nfn main() {\n let number = 3;\n\n if number < 5 {\n println!(\"condition was true\");\n } else {\n println!(\"condition was false\");\n }\n}\n```\nAll `if` expressions start with the keyword `if`, followed by a condition. In\nthis case, the condition checks whether or not the variable `number` has a\nvalue less than 5. We place the block of code to execute if the condition is\n`true` immediately after the condition inside curly brackets. Blocks of code\nassociated with the conditions in `if` expressions are sometimes called _arms_,\njust like the arms in `match` expressions that we discussed in the “Comparing\nthe Guess to the Secret Number”\n section of Chapter 2.\nOptionally, we can also include an `else` expression, which we chose to do\nhere, to give the program an alternative block of code to execute should the\ncondition evaluate to `false`. If you don’t provide an `else` expression and\nthe condition is `false`, the program will just skip the `if` block and move on\nto the next bit of code.\nTry running this code; you should see the following output:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Control Flow", "heading_path": ["Control Flow", "`if` Expressions"], "path": "ch03-05-control-flow.md", "url": "https://doc.rust-lang.org/book/ch03-05-control-flow.html#if-expressions", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch03-05-control-flow.md#if-expressions-2", "text": "The Rust Programming Language › Control Flow › `if` Expressions\n\n```console\n$ cargo run\n Compiling branches v0.1.0 (file:///projects/branches)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.31s\n Running `target/debug/branches`\ncondition was true\n```\nLet’s try changing the value of `number` to a value that makes the condition\n`false` to see what happens:\n```rust,ignore\n let number = 7;\n```\nRun the program again, and look at the output:\n```console\n$ cargo run\n Compiling branches v0.1.0 (file:///projects/branches)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.31s\n Running `target/debug/branches`\ncondition was false\n```\nIt’s also worth noting that the condition in this code _must_ be a `bool`. If\nthe condition isn’t a `bool`, we’ll get an error. For example, try running the\nfollowing code:\nFilename: src/main.rs\n```rust,ignore,does_not_compile\nfn main() {\n let number = 3;\n\n if number {\n println!(\"number was three\");\n }\n}\n```\nThe `if` condition evaluates to a value of `3` this time, and Rust throws an\nerror:\n```console\n$ cargo run\n Compiling branches v0.1.0 (file:///projects/branches)\nerror[E0308]: mismatched types\n --> src/main.rs:4:8\n |\n4 | if number {\n | ^^^^^^ expected `bool`, found integer\n\nFor more information about this error, try `rustc --explain E0308`.\nerror: could not compile `branches` (bin \"branches\") due to 1 previous error\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Control Flow", "heading_path": ["Control Flow", "`if` Expressions"], "path": "ch03-05-control-flow.md", "url": "https://doc.rust-lang.org/book/ch03-05-control-flow.html#if-expressions", "has_code": true, "code_tags": ["console", "rust,ignore", "rust,ignore,does_not_compile"]}} {"id": "book/ch03-05-control-flow.md#handling-multiple-conditions-with-else-if-3", "text": "The Rust Programming Language › Control Flow › `if` Expressions › Handling Multiple Conditions with `else if`\n\nThe error indicates that Rust expected a `bool` but got an integer. Unlike\nlanguages such as Ruby and JavaScript, Rust will not automatically try to\nconvert non-Boolean types to a Boolean. You must be explicit and always provide\n`if` with a Boolean as its condition. If we want the `if` code block to run\nonly when a number is not equal to `0`, for example, we can change the `if`\nexpression to the following:\nFilename: src/main.rs\n```rust\nfn main() {\n let number = 3;\n\n if number != 0 {\n println!(\"number was something other than zero\");\n }\n}\n```\nRunning this code will print `number was something other than zero`.\nYou can use multiple conditions by combining `if` and `else` in an `else if`\nexpression. For example:\nFilename: src/main.rs\n```rust\nfn main() {\n let number = 6;\n\n if number % 4 == 0 {\n println!(\"number is divisible by 4\");\n } else if number % 3 == 0 {\n println!(\"number is divisible by 3\");\n } else if number % 2 == 0 {\n println!(\"number is divisible by 2\");\n } else {\n println!(\"number is not divisible by 4, 3, or 2\");\n }\n}\n```\nThis program has four possible paths it can take. After running it, you should\nsee the following output:\n```console\n$ cargo run\n Compiling branches v0.1.0 (file:///projects/branches)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.31s\n Running `target/debug/branches`\nnumber is divisible by 3\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Control Flow", "heading_path": ["Control Flow", "`if` Expressions", "Handling Multiple Conditions with `else if`"], "path": "ch03-05-control-flow.md", "url": "https://doc.rust-lang.org/book/ch03-05-control-flow.html#handling-multiple-conditions-with-else-if", "has_code": true, "code_tags": ["console", "rust"]}} {"id": "book/ch03-05-control-flow.md#using-if-in-a-let-statement-4", "text": "The Rust Programming Language › Control Flow › `if` Expressions › Using `if` in a `let` Statement\n\nWhen this program executes, it checks each `if` expression in turn and executes\nthe first body for which the condition evaluates to `true`. Note that even\nthough 6 is divisible by 2, we don’t see the output `number is divisible by 2`,\nnor do we see the `number is not divisible by 4, 3, or 2` text from the `else`\nblock. That’s because Rust only executes the block for the first `true`\ncondition, and once it finds one, it doesn’t even check the rest.\nUsing too many `else if` expressions can clutter your code, so if you have more\nthan one, you might want to refactor your code. Chapter 6 describes a powerful\nRust branching construct called `match` for these cases.\nBecause `if` is an expression, we can use it on the right side of a `let`\nstatement to assign the outcome to a variable, as in Listing 3-2.\nListing 3-2: Assigning the result of an `if` expression to a variable (src/main.rs)\n```rust\nfn main() {\n let condition = true;\n let number = if condition { 5 } else { 6 };\n\n println!(\"The value of number is: {number}\");\n}\n```\nThe `number` variable will be bound to a value based on the outcome of the `if`\nexpression. Run this code to see what happens:\n```console\n$ cargo run\n Compiling branches v0.1.0 (file:///projects/branches)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.30s\n Running `target/debug/branches`\nThe value of number is: 5\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Control Flow", "heading_path": ["Control Flow", "`if` Expressions", "Using `if` in a `let` Statement"], "path": "ch03-05-control-flow.md", "url": "https://doc.rust-lang.org/book/ch03-05-control-flow.html#using-if-in-a-let-statement", "has_code": true, "code_tags": ["console", "rust"]}} {"id": "book/ch03-05-control-flow.md#using-if-in-a-let-statement-5", "text": "The Rust Programming Language › Control Flow › `if` Expressions › Using `if` in a `let` Statement\n\nRemember that blocks of code evaluate to the last expression in them, and\nnumbers by themselves are also expressions. In this case, the value of the\nwhole `if` expression depends on which block of code executes. This means the\nvalues that have the potential to be results from each arm of the `if` must be\nthe same type; in Listing 3-2, the results of both the `if` arm and the `else`\narm were `i32` integers. If the types are mismatched, as in the following\nexample, we’ll get an error:\nFilename: src/main.rs\n```rust,ignore,does_not_compile\nfn main() {\n let condition = true;\n\n let number = if condition { 5 } else { \"six\" };\n\n println!(\"The value of number is: {number}\");\n}\n```\nWhen we try to compile this code, we’ll get an error. The `if` and `else` arms\nhave value types that are incompatible, and Rust indicates exactly where to\nfind the problem in the program:\n```console\n$ cargo run\n Compiling branches v0.1.0 (file:///projects/branches)\nerror[E0308]: `if` and `else` have incompatible types\n --> src/main.rs:4:44\n |\n4 | let number = if condition { 5 } else { \"six\" };\n | - ^^^^^ expected integer, found `&str`\n | |\n | expected because of this\n\nFor more information about this error, try `rustc --explain E0308`.\nerror: could not compile `branches` (bin \"branches\") due to 1 previous error\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Control Flow", "heading_path": ["Control Flow", "`if` Expressions", "Using `if` in a `let` Statement"], "path": "ch03-05-control-flow.md", "url": "https://doc.rust-lang.org/book/ch03-05-control-flow.html#using-if-in-a-let-statement", "has_code": true, "code_tags": ["console", "rust,ignore,does_not_compile"]}} {"id": "book/ch03-05-control-flow.md#using-if-in-a-let-statement-6", "text": "The Rust Programming Language › Control Flow › `if` Expressions › Using `if` in a `let` Statement\n\nThe expression in the `if` block evaluates to an integer, and the expression in\nthe `else` block evaluates to a string. This won’t work, because variables must\nhave a single type, and Rust needs to know definitively at compile time what\ntype the `number` variable is. Knowing the type of `number` lets the compiler\nverify the type is valid everywhere we use `number`. Rust wouldn’t be able to\ndo that if the type of `number` was only determined at runtime; the compiler\nwould be more complex and would make fewer guarantees about the code if it had\nto keep track of multiple hypothetical types for any variable.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Control Flow", "heading_path": ["Control Flow", "`if` Expressions", "Using `if` in a `let` Statement"], "path": "ch03-05-control-flow.md", "url": "https://doc.rust-lang.org/book/ch03-05-control-flow.html#using-if-in-a-let-statement", "has_code": false, "code_tags": []}} {"id": "book/ch03-05-control-flow.md#repeating-code-with-loop-7", "text": "The Rust Programming Language › Control Flow › Repetition with Loops › Repeating Code with `loop`\n\nIt’s often useful to execute a block of code more than once. For this task,\nRust provides several _loops_, which will run through the code inside the loop\nbody to the end and then start immediately back at the beginning. To experiment\nwith loops, let’s make a new project called _loops_.\nRust has three kinds of loops: `loop`, `while`, and `for`. Let’s try each one.\nThe `loop` keyword tells Rust to execute a block of code over and over again\neither forever or until you explicitly tell it to stop.\nAs an example, change the _src/main.rs_ file in your _loops_ directory to look\nlike this:\nFilename: src/main.rs\n```rust,ignore\nfn main() {\n loop {\n println!(\"again!\");\n }\n}\n```\nWhen we run this program, we’ll see `again!` printed over and over continuously\nuntil we stop the program manually. Most terminals support the keyboard shortcut\nctrl-C to interrupt a program that is stuck in a continual\nloop. Give it a try:\n```console\n$ cargo run\n Compiling loops v0.1.0 (file:///projects/loops)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.08s\n Running `target/debug/loops`\nagain!\nagain!\nagain!\nagain!\n^Cagain!\n```\nThe symbol `^C` represents where you pressed ctrl-C.\nYou may or may not see the word `again!` printed after the `^C`, depending on\nwhere the code was in the loop when it received the interrupt signal.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Control Flow", "heading_path": ["Control Flow", "Repetition with Loops", "Repeating Code with `loop`"], "path": "ch03-05-control-flow.md", "url": "https://doc.rust-lang.org/book/ch03-05-control-flow.html#repeating-code-with-loop", "has_code": true, "code_tags": ["console", "rust,ignore"]}} {"id": "book/ch03-05-control-flow.md#returning-values-from-loops-8", "text": "The Rust Programming Language › Control Flow › Repetition with Loops › Returning Values from Loops\n\nFortunately, Rust also provides a way to break out of a loop using code. You\ncan place the `break` keyword within the loop to tell the program when to stop\nexecuting the loop. Recall that we did this in the guessing game in the\n“Quitting After a Correct Guess”\n section of Chapter 2 to exit the program when the user won the game by\nguessing the correct number.\nWe also used `continue` in the guessing game, which in a loop tells the program\nto skip over any remaining code in this iteration of the loop and go to the\nnext iteration.\nOne of the uses of a `loop` is to retry an operation you know might fail, such\nas checking whether a thread has completed its job. You might also need to pass\nthe result of that operation out of the loop to the rest of your code. To do\nthis, you can add the value you want returned after the `break` expression you\nuse to stop the loop; that value will be returned out of the loop so that you\ncan use it, as shown here:\n```rust\nfn main() {\n let mut counter = 0;\n\n let result = loop {\n counter += 1;\n\n if counter == 10 {\n break counter * 2;\n }\n };\n\n println!(\"The result is {result}\");\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Control Flow", "heading_path": ["Control Flow", "Repetition with Loops", "Returning Values from Loops"], "path": "ch03-05-control-flow.md", "url": "https://doc.rust-lang.org/book/ch03-05-control-flow.html#returning-values-from-loops", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch03-05-control-flow.md#disambiguating-with-loop-labels-9", "text": "The Rust Programming Language › Control Flow › Repetition with Loops › Disambiguating with Loop Labels\n\nBefore the loop, we declare a variable named `counter` and initialize it to\n`0`. Then, we declare a variable named `result` to hold the value returned from\nthe loop. On every iteration of the loop, we add `1` to the `counter` variable,\nand then check whether the `counter` is equal to `10`. When it is, we use the\n`break` keyword with the value `counter * 2`. After the loop, we use a\nsemicolon to end the statement that assigns the value to `result`. Finally, we\nprint the value in `result`, which in this case is `20`.\nYou can also `return` from inside a loop. While `break` only exits the current\nloop, `return` always exits the current function.\nIf you have loops within loops, `break` and `continue` apply to the innermost\nloop at that point. You can optionally specify a _loop label_ on a loop that\nyou can then use with `break` or `continue` to specify that those keywords\napply to the labeled loop instead of the innermost loop. Loop labels must begin\nwith a single quote. Here’s an example with two nested loops:\n```rust\nfn main() {\n let mut count = 0;\n 'counting_up: loop {\n println!(\"count = {count}\");\n let mut remaining = 10;\n\n loop {\n println!(\"remaining = {remaining}\");\n if remaining == 9 {\n break;\n }\n if count == 2 {\n break 'counting_up;\n }\n remaining -= 1;\n }\n\n count += 1;\n }\n println!(\"End count = {count}\");\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Control Flow", "heading_path": ["Control Flow", "Repetition with Loops", "Disambiguating with Loop Labels"], "path": "ch03-05-control-flow.md", "url": "https://doc.rust-lang.org/book/ch03-05-control-flow.html#disambiguating-with-loop-labels", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch03-05-control-flow.md#streamlining-conditional-loops-with-while-10", "text": "The Rust Programming Language › Control Flow › Repetition with Loops › Streamlining Conditional Loops with while\n\nThe outer loop has the label `'counting_up`, and it will count up from 0 to 2.\nThe inner loop without a label counts down from 10 to 9. The first `break` that\ndoesn’t specify a label will exit the inner loop only. The `break\n'counting_up;` statement will exit the outer loop. This code prints:\n```console\n$ cargo run\n Compiling loops v0.1.0 (file:///projects/loops)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.58s\n Running `target/debug/loops`\ncount = 0\nremaining = 10\nremaining = 9\ncount = 1\nremaining = 10\nremaining = 9\ncount = 2\nremaining = 10\nEnd count = 2\n```\nA program will often need to evaluate a condition within a loop. While the\ncondition is `true`, the loop runs. When the condition ceases to be `true`, the\nprogram calls `break`, stopping the loop. It’s possible to implement behavior\nlike this using a combination of `loop`, `if`, `else`, and `break`; you could\ntry that now in a program, if you’d like. However, this pattern is so common\nthat Rust has a built-in language construct for it, called a `while` loop. In\nListing 3-3, we use `while` to loop the program three times, counting down each\ntime, and then, after the loop, to print a message and exit.\nListing 3-3: Using a `while` loop to run code while a condition evaluates to `true` (src/main.rs)\n```rust\nfn main() {\n let mut number = 3;\n\n while number != 0 {\n println!(\"{number}!\");\n\n number -= 1;\n }\n\n println!(\"LIFTOFF!!!\");\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Control Flow", "heading_path": ["Control Flow", "Repetition with Loops", "Streamlining Conditional Loops with while"], "path": "ch03-05-control-flow.md", "url": "https://doc.rust-lang.org/book/ch03-05-control-flow.html#streamlining-conditional-loops-with-while", "has_code": true, "code_tags": ["console", "rust"]}} {"id": "book/ch03-05-control-flow.md#looping-through-a-collection-with-for-11", "text": "The Rust Programming Language › Control Flow › Repetition with Loops › Looping Through a Collection with `for`\n\nThis construct eliminates a lot of nesting that would be necessary if you used\n`loop`, `if`, `else`, and `break`, and it’s clearer. While a condition\nevaluates to `true`, the code runs; otherwise, it exits the loop.\nYou can choose to use the `while` construct to loop over the elements of a\ncollection, such as an array. For example, the loop in Listing 3-4 prints each\nelement in the array `a`.\nListing 3-4: Looping through each element of a collection using a `while` loop (src/main.rs)\n```rust\nfn main() {\n let a = [10, 20, 30, 40, 50];\n let mut index = 0;\n\n while index < 5 {\n println!(\"the value is: {}\", a[index]);\n\n index += 1;\n }\n}\n```\nHere, the code counts up through the elements in the array. It starts at index\n`0` and then loops until it reaches the final index in the array (that is,\nwhen `index < 5` is no longer `true`). Running this code will print every\nelement in the array:\n```console\n$ cargo run\n Compiling loops v0.1.0 (file:///projects/loops)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.32s\n Running `target/debug/loops`\nthe value is: 10\nthe value is: 20\nthe value is: 30\nthe value is: 40\nthe value is: 50\n```\nAll five array values appear in the terminal, as expected. Even though `index`\nwill reach a value of `5` at some point, the loop stops executing before trying\nto fetch a sixth value from the array.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Control Flow", "heading_path": ["Control Flow", "Repetition with Loops", "Looping Through a Collection with `for`"], "path": "ch03-05-control-flow.md", "url": "https://doc.rust-lang.org/book/ch03-05-control-flow.html#looping-through-a-collection-with-for", "has_code": true, "code_tags": ["console", "rust"]}} {"id": "book/ch03-05-control-flow.md#looping-through-a-collection-with-for-12", "text": "The Rust Programming Language › Control Flow › Repetition with Loops › Looping Through a Collection with `for`\n\nHowever, this approach is error-prone; we could cause the program to panic if\nthe index value or test condition is incorrect. For example, if you changed the\ndefinition of the `a` array to have four elements but forgot to update the\ncondition to `while index < 4`, the code would panic. It’s also slow, because\nthe compiler adds runtime code to perform the conditional check of whether the\nindex is within the bounds of the array on every iteration through the loop.\nAs a more concise alternative, you can use a `for` loop and execute some code\nfor each item in a collection. A `for` loop looks like the code in Listing 3-5.\nListing 3-5: Looping through each element of a collection using a `for` loop (src/main.rs)\n```rust\nfn main() {\n let a = [10, 20, 30, 40, 50];\n\n for element in a {\n println!(\"the value is: {element}\");\n }\n}\n```\nWhen we run this code, we’ll see the same output as in Listing 3-4. More\nimportantly, we’ve now increased the safety of the code and eliminated the\nchance of bugs that might result from going beyond the end of the array or not\ngoing far enough and missing some items. Machine code generated from `for`\nloops can be more efficient as well because the index doesn’t need to be\ncompared to the length of the array at every iteration.\nUsing the `for` loop, you wouldn’t need to remember to change any other code if\nyou changed the number of values in the array, as you would with the method\nused in Listing 3-4.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Control Flow", "heading_path": ["Control Flow", "Repetition with Loops", "Looping Through a Collection with `for`"], "path": "ch03-05-control-flow.md", "url": "https://doc.rust-lang.org/book/ch03-05-control-flow.html#looping-through-a-collection-with-for", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch03-05-control-flow.md#looping-through-a-collection-with-for-13", "text": "The Rust Programming Language › Control Flow › Repetition with Loops › Looping Through a Collection with `for`\n\nThe safety and conciseness of `for` loops make them the most commonly used loop\nconstruct in Rust. Even in situations in which you want to run some code a\ncertain number of times, as in the countdown example that used a `while` loop\nin Listing 3-3, most Rustaceans would use a `for` loop. The way to do that\nwould be to use a `Range`, provided by the standard library, which generates\nall numbers in sequence starting from one number and ending before another\nnumber.\nHere’s what the countdown would look like using a `for` loop and another method\nwe’ve not yet talked about, `rev`, to reverse the range:\nFilename: src/main.rs\n```rust\nfn main() {\n for number in (1..4).rev() {\n println!(\"{number}!\");\n }\n println!(\"LIFTOFF!!!\");\n}\n```\nThis code is a bit nicer, isn’t it?", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Control Flow", "heading_path": ["Control Flow", "Repetition with Loops", "Looping Through a Collection with `for`"], "path": "ch03-05-control-flow.md", "url": "https://doc.rust-lang.org/book/ch03-05-control-flow.html#looping-through-a-collection-with-for", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch03-05-control-flow.md#summary-14", "text": "The Rust Programming Language › Summary\n\nYou made it! This was a sizable chapter: You learned about variables, scalar\nand compound data types, functions, comments, `if` expressions, and loops! To\npractice with the concepts discussed in this chapter, try building programs to\ndo the following:\n- Convert temperatures between Fahrenheit and Celsius.\n- Generate the *n*th Fibonacci number.\n- Print the lyrics to the Christmas carol “The Twelve Days of Christmas,”\n taking advantage of the repetition in the song.\nWhen you’re ready to move on, we’ll talk about a concept in Rust that _doesn’t_\ncommonly exist in other programming languages: ownership.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Control Flow", "heading_path": ["Summary"], "path": "ch03-05-control-flow.md", "url": "https://doc.rust-lang.org/book/ch03-05-control-flow.html#summary", "has_code": false, "code_tags": []}} {"id": "book/ch04-00-understanding-ownership.md#understanding-ownership-0", "text": "The Rust Programming Language › Understanding Ownership\n\nOwnership is Rust’s most unique feature and has deep implications for the rest\nof the language. It enables Rust to make memory safety guarantees without\nneeding a garbage collector, so it’s important to understand how ownership\nworks. In this chapter, we’ll talk about ownership as well as several related\nfeatures: borrowing, slices, and how Rust lays data out in memory.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Understanding Ownership", "heading_path": ["Understanding Ownership"], "path": "ch04-00-understanding-ownership.md", "url": "https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html#understanding-ownership", "has_code": false, "code_tags": []}} {"id": "book/ch04-01-what-is-ownership.md#what-is-ownership-0", "text": "The Rust Programming Language › What Is Ownership?\n\n_Ownership_ is a set of rules that govern how a Rust program manages memory.\nAll programs have to manage the way they use a computer’s memory while running.\nSome languages have garbage collection that regularly looks for no-longer-used\nmemory as the program runs; in other languages, the programmer must explicitly\nallocate and free the memory. Rust uses a third approach: Memory is managed\nthrough a system of ownership with a set of rules that the compiler checks. If\nany of the rules are violated, the program won’t compile. None of the features\nof ownership will slow down your program while it’s running.\nBecause ownership is a new concept for many programmers, it does take some time\nto get used to. The good news is that the more experienced you become with Rust\nand the rules of the ownership system, the easier you’ll find it to naturally\ndevelop code that is safe and efficient. Keep at it!\nWhen you understand ownership, you’ll have a solid foundation for understanding\nthe features that make Rust unique. In this chapter, you’ll learn ownership by\nworking through some examples that focus on a very common data structure:\nstrings.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "What is Ownership?", "heading_path": ["What Is Ownership?"], "path": "ch04-01-what-is-ownership.md", "url": "https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html#what-is-ownership", "has_code": false, "code_tags": []}} {"id": "book/ch04-01-what-is-ownership.md#the-stack-and-the-heap-1", "text": "The Rust Programming Language › What Is Ownership? › The Stack and the Heap\n\nMany programming languages don’t require you to think about the stack and the\nheap very often. But in a systems programming language like Rust, whether a\nvalue is on the stack or the heap affects how the language behaves and why\nyou have to make certain decisions. Parts of ownership will be described in\nrelation to the stack and the heap later in this chapter, so here is a brief\nexplanation in preparation.\nBoth the stack and the heap are parts of memory available to your code to use\nat runtime, but they are structured in different ways. The stack stores\nvalues in the order it gets them and removes the values in the opposite\norder. This is referred to as _last in, first out (LIFO)_. Think of a stack of\nplates: When you add more plates, you put them on top of the pile, and when\nyou need a plate, you take one off the top. Adding or removing plates from\nthe middle or bottom wouldn’t work as well! Adding data is called _pushing\nonto the stack_, and removing data is called _popping off the stack_. All\ndata stored on the stack must have a known, fixed size. Data with an unknown\nsize at compile time or a size that might change must be stored on the heap\ninstead.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "What is Ownership?", "heading_path": ["What Is Ownership?", "The Stack and the Heap"], "path": "ch04-01-what-is-ownership.md", "url": "https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html#the-stack-and-the-heap", "has_code": false, "code_tags": []}} {"id": "book/ch04-01-what-is-ownership.md#the-stack-and-the-heap-2", "text": "The Rust Programming Language › What Is Ownership? › The Stack and the Heap\n\nThe heap is less organized: When you put data on the heap, you request a\ncertain amount of space. The memory allocator finds an empty spot in the heap\nthat is big enough, marks it as being in use, and returns a _pointer_, which\nis the address of that location. This process is called _allocating on the\nheap_ and is sometimes abbreviated as just _allocating_ (pushing values onto\nthe stack is not considered allocating). Because the pointer to the heap is a\nknown, fixed size, you can store the pointer on the stack, but when you want\nthe actual data, you must follow the pointer. Think of being seated at a\nrestaurant. When you enter, you state the number of people in your group, and\nthe host finds an empty table that fits everyone and leads you there. If\nsomeone in your group comes late, they can ask where you’ve been seated to\nfind you.\nPushing to the stack is faster than allocating on the heap because the\nallocator never has to search for a place to store new data; that location is\nalways at the top of the stack. Comparatively, allocating space on the heap\nrequires more work because the allocator must first find a big enough space\nto hold the data and then perform bookkeeping to prepare for the next\nallocation.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "What is Ownership?", "heading_path": ["What Is Ownership?", "The Stack and the Heap"], "path": "ch04-01-what-is-ownership.md", "url": "https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html#the-stack-and-the-heap", "has_code": false, "code_tags": []}} {"id": "book/ch04-01-what-is-ownership.md#the-stack-and-the-heap-3", "text": "The Rust Programming Language › What Is Ownership? › The Stack and the Heap\n\nAccessing data in the heap is generally slower than accessing data on the\nstack because you have to follow a pointer to get there. Contemporary\nprocessors are faster if they jump around less in memory. Continuing the\nanalogy, consider a server at a restaurant taking orders from many tables.\nIt’s most efficient to get all the orders at one table before moving on to\nthe next table. Taking an order from table A, then an order from table B,\nthen one from A again, and then one from B again would be a much slower\nprocess. By the same token, a processor can usually do its job better if it\nworks on data that’s close to other data (as it is on the stack) rather than\nfarther away (as it can be on the heap).\nWhen your code calls a function, the values passed into the function\n(including, potentially, pointers to data on the heap) and the function’s\nlocal variables get pushed onto the stack. When the function is over, those\nvalues get popped off the stack.\nKeeping track of what parts of code are using what data on the heap,\nminimizing the amount of duplicate data on the heap, and cleaning up unused\ndata on the heap so that you don’t run out of space are all problems that\nownership addresses. Once you understand ownership, you won’t need to think\nabout the stack and the heap very often. But knowing that the main purpose of\nownership is to manage heap data can help explain why it works the way it\ndoes.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "What is Ownership?", "heading_path": ["What Is Ownership?", "The Stack and the Heap"], "path": "ch04-01-what-is-ownership.md", "url": "https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html#the-stack-and-the-heap", "has_code": false, "code_tags": []}} {"id": "book/ch04-01-what-is-ownership.md#ownership-rules-4", "text": "The Rust Programming Language › What Is Ownership? › Ownership Rules\n\nFirst, let’s take a look at the ownership rules. Keep these rules in mind as we\nwork through the examples that illustrate them:\n- Each value in Rust has an _owner_.\n- There can only be one owner at a time.\n- When the owner goes out of scope, the value will be dropped.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "What is Ownership?", "heading_path": ["What Is Ownership?", "Ownership Rules"], "path": "ch04-01-what-is-ownership.md", "url": "https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html#ownership-rules", "has_code": false, "code_tags": []}} {"id": "book/ch04-01-what-is-ownership.md#variable-scope-5", "text": "The Rust Programming Language › What Is Ownership? › Variable Scope\n\nNow that we’re past basic Rust syntax, we won’t include all the `fn main() {`\ncode in the examples, so if you’re following along, make sure to put the\nfollowing examples inside a `main` function manually. As a result, our examples\nwill be a bit more concise, letting us focus on the actual details rather than\nboilerplate code.\nAs a first example of ownership, we’ll look at the scope of some variables. A\n_scope_ is the range within a program for which an item is valid. Take the\nfollowing variable:\n```rust\nlet s = \"hello\";\n```\nThe variable `s` refers to a string literal, where the value of the string is\nhardcoded into the text of our program. The variable is valid from the point at\nwhich it’s declared until the end of the current scope. Listing 4-1 shows a\nprogram with comments annotating where the variable `s` would be valid.\nListing 4-1: A variable and the scope in which it is valid\n```rust\n { // s is not valid here, since it's not yet declared\n let s = \"hello\"; // s is valid from this point forward\n\n // do stuff with s\n } // this scope is now over, and s is no longer valid\n```\nIn other words, there are two important points in time here:\n- When `s` comes _into_ scope, it is valid.\n- It remains valid until it goes _out of_ scope.\nAt this point, the relationship between scopes and when variables are valid is\nsimilar to that in other programming languages. Now we’ll build on top of this\nunderstanding by introducing the `String` type.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "What is Ownership?", "heading_path": ["What Is Ownership?", "Variable Scope"], "path": "ch04-01-what-is-ownership.md", "url": "https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html#variable-scope", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch04-01-what-is-ownership.md#the-string-type-6", "text": "The Rust Programming Language › What Is Ownership? › The `String` Type\n\nTo illustrate the rules of ownership, we need a data type that is more complex\nthan those we covered in the “Data Types” section\nof Chapter 3. The types covered previously are of a known size, can be stored\non the stack and popped off the stack when their scope is over, and can be\nquickly and trivially copied to make a new, independent instance if another\npart of code needs to use the same value in a different scope. But we want to\nlook at data that is stored on the heap and explore how Rust knows when to\nclean up that data, and the `String` type is a great example.\nWe’ll concentrate on the parts of `String` that relate to ownership. These\naspects also apply to other complex data types, whether they are provided by\nthe standard library or created by you. We’ll discuss non-ownership aspects of\n`String` in Chapter 8.\nWe’ve already seen string literals, where a string value is hardcoded into our\nprogram. String literals are convenient, but they aren’t suitable for every\nsituation in which we may want to use text. One reason is that they’re\nimmutable. Another is that not every string value can be known when we write\nour code: For example, what if we want to take user input and store it? It is\nfor these situations that Rust has the `String` type. This type manages\ndata allocated on the heap and as such is able to store an amount of text that\nis unknown to us at compile time. You can create a `String` from a string\nliteral using the `from` function, like so:\n```rust\nlet s = String::from(\"hello\");\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "What is Ownership?", "heading_path": ["What Is Ownership?", "The `String` Type"], "path": "ch04-01-what-is-ownership.md", "url": "https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html#the-string-type", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch04-01-what-is-ownership.md#the-string-type-7", "text": "The Rust Programming Language › What Is Ownership? › The `String` Type\n\nThe double colon `::` operator allows us to namespace this particular `from`\nfunction under the `String` type rather than using some sort of name like\n`string_from`. We’ll discuss this syntax more in the “Methods”\n section of Chapter 5, and when we talk about namespacing with\nmodules in “Paths for Referring to an Item in the Module\nTree” in Chapter 7.\nThis kind of string _can_ be mutated:\n```rust\n let mut s = String::from(\"hello\");\n\n s.push_str(\", world!\"); // push_str() appends a literal to a String\n\n println!(\"{s}\"); // this will print `hello, world!`\n```\nSo, what’s the difference here? Why can `String` be mutated but literals\ncannot? The difference is in how these two types deal with memory.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "What is Ownership?", "heading_path": ["What Is Ownership?", "The `String` Type"], "path": "ch04-01-what-is-ownership.md", "url": "https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html#the-string-type", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch04-01-what-is-ownership.md#memory-and-allocation-8", "text": "The Rust Programming Language › What Is Ownership? › Memory and Allocation\n\nIn the case of a string literal, we know the contents at compile time, so the\ntext is hardcoded directly into the final executable. This is why string\nliterals are fast and efficient. But these properties only come from the string\nliteral’s immutability. Unfortunately, we can’t put a blob of memory into the\nbinary for each piece of text whose size is unknown at compile time and whose\nsize might change while running the program.\nWith the `String` type, in order to support a mutable, growable piece of text,\nwe need to allocate an amount of memory on the heap, unknown at compile time,\nto hold the contents. This means:\n- The memory must be requested from the memory allocator at runtime.\n- We need a way of returning this memory to the allocator when we’re done with\n our `String`.\nThat first part is done by us: When we call `String::from`, its implementation\nrequests the memory it needs. This is pretty much universal in programming\nlanguages.\nHowever, the second part is different. In languages with a _garbage collector\n(GC)_, the GC keeps track of and cleans up memory that isn’t being used\nanymore, and we don’t need to think about it. In most languages without a GC,\nit’s our responsibility to identify when memory is no longer being used and to\ncall code to explicitly free it, just as we did to request it. Doing this\ncorrectly has historically been a difficult programming problem. If we forget,\nwe’ll waste memory. If we do it too early, we’ll have an invalid variable. If\nwe do it twice, that’s a bug too. We need to pair exactly one `allocate` with\nexactly one `free`.\nRust takes a different path: The memory is automatically returned once the\nvariable that owns it goes out of scope. Here’s a version of our scope example\nfrom Listing 4-1 using a `String` instead of a string literal:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "What is Ownership?", "heading_path": ["What Is Ownership?", "Memory and Allocation"], "path": "ch04-01-what-is-ownership.md", "url": "https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html#memory-and-allocation", "has_code": false, "code_tags": []}} {"id": "book/ch04-01-what-is-ownership.md#variables-and-data-interacting-with-move-9", "text": "The Rust Programming Language › What Is Ownership? › Memory and Allocation › Variables and Data Interacting with Move\n\n```rust\n {\n let s = String::from(\"hello\"); // s is valid from this point forward\n\n // do stuff with s\n } // this scope is now over, and s is no\n // longer valid\n```\nThere is a natural point at which we can return the memory our `String` needs\nto the allocator: when `s` goes out of scope. When a variable goes out of\nscope, Rust calls a special function for us. This function is called\n`drop`, and it’s where the author of `String` can put\nthe code to return the memory. Rust calls `drop` automatically at the closing\ncurly bracket.\nNote: In C++, this pattern of deallocating resources at the end of an item’s\nlifetime is sometimes called _Resource Acquisition Is Initialization (RAII)_.\nThe `drop` function in Rust will be familiar to you if you’ve used RAII\npatterns.\nThis pattern has a profound impact on the way Rust code is written. It may seem\nsimple right now, but the behavior of code can be unexpected in more\ncomplicated situations when we want to have multiple variables use the data\nwe’ve allocated on the heap. Let’s explore some of those situations now.\nMultiple variables can interact with the same data in different ways in Rust.\nListing 4-2 shows an example using an integer.\nListing 4-2: Assigning the integer value of variable `x` to `y`\n```rust\n let x = 5;\n let y = x;\n```\nWe can probably guess what this is doing: “Bind the value `5` to `x`; then, make\na copy of the value in `x` and bind it to `y`.” We now have two variables, `x`\nand `y`, and both equal `5`. This is indeed what is happening, because integers\nare simple values with a known, fixed size, and these two `5` values are pushed\nonto the stack.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "What is Ownership?", "heading_path": ["What Is Ownership?", "Memory and Allocation", "Variables and Data Interacting with Move"], "path": "ch04-01-what-is-ownership.md", "url": "https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html#variables-and-data-interacting-with-move", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch04-01-what-is-ownership.md#variables-and-data-interacting-with-move-10", "text": "The Rust Programming Language › What Is Ownership? › Memory and Allocation › Variables and Data Interacting with Move\n\nNow let’s look at the `String` version:\n```rust\n let s1 = String::from(\"hello\");\n let s2 = s1;\n```\nThis looks very similar, so we might assume that the way it works would be the\nsame: That is, the second line would make a copy of the value in `s1` and bind\nit to `s2`. But this isn’t quite what happens.\nTake a look at Figure 4-1 to see what is happening to `String` under the\ncovers. A `String` is made up of three parts, shown on the left: a pointer to\nthe memory that holds the contents of the string, a length, and a capacity.\nThis group of data is stored on the stack. On the right is the memory on the\nheap that holds the contents.\n\"Two\nFigure 4-1: The representation in memory of a `String`\nholding the value `\"hello\"` bound to `s1`\nThe length is how much memory, in bytes, the contents of the `String` are\ncurrently using. The capacity is the total amount of memory, in bytes, that the\n`String` has received from the allocator. The difference between length and\ncapacity matters, but not in this context, so for now, it’s fine to ignore the\ncapacity.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "What is Ownership?", "heading_path": ["What Is Ownership?", "Memory and Allocation", "Variables and Data Interacting with Move"], "path": "ch04-01-what-is-ownership.md", "url": "https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html#variables-and-data-interacting-with-move", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch04-01-what-is-ownership.md#variables-and-data-interacting-with-move-11", "text": "The Rust Programming Language › What Is Ownership? › Memory and Allocation › Variables and Data Interacting with Move\n\nWhen we assign `s1` to `s2`, the `String` data is copied, meaning we copy the\npointer, the length, and the capacity that are on the stack. We do not copy the\ndata on the heap that the pointer refers to. In other words, the data\nrepresentation in memory looks like Figure 4-2.\n\"Three\nFigure 4-2: The representation in memory of the variable\n`s2` that has a copy of the pointer, length, and capacity of `s1`\nThe representation does _not_ look like Figure 4-3, which is what memory would\nlook like if Rust instead copied the heap data as well. If Rust did this, the\noperation `s2 = s1` could be very expensive in terms of runtime performance if\nthe data on the heap were large.\n\"Four\nFigure 4-3: Another possibility for what `s2 = s1` might\ndo if Rust copied the heap data as well", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "What is Ownership?", "heading_path": ["What Is Ownership?", "Memory and Allocation", "Variables and Data Interacting with Move"], "path": "ch04-01-what-is-ownership.md", "url": "https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html#variables-and-data-interacting-with-move", "has_code": false, "code_tags": []}} {"id": "book/ch04-01-what-is-ownership.md#variables-and-data-interacting-with-move-12", "text": "The Rust Programming Language › What Is Ownership? › Memory and Allocation › Variables and Data Interacting with Move\n\nEarlier, we said that when a variable goes out of scope, Rust automatically\ncalls the `drop` function and cleans up the heap memory for that variable. But\nFigure 4-2 shows both data pointers pointing to the same location. This is a\nproblem: When `s2` and `s1` go out of scope, they will both try to free the\nsame memory. This is known as a _double free_ error and is one of the memory\nsafety bugs we mentioned previously. Freeing memory twice can lead to memory\ncorruption, which can potentially lead to security vulnerabilities.\nTo ensure memory safety, after the line `let s2 = s1;`, Rust considers `s1` as\nno longer valid. Therefore, Rust doesn’t need to free anything when `s1` goes\nout of scope. Check out what happens when you try to use `s1` after `s2` is\ncreated; it won’t work:\n```rust,ignore,does_not_compile\n let s1 = String::from(\"hello\");\n let s2 = s1;\n\n println!(\"{s1}, world!\");\n```\nYou’ll get an error like this because Rust prevents you from using the\ninvalidated reference:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "What is Ownership?", "heading_path": ["What Is Ownership?", "Memory and Allocation", "Variables and Data Interacting with Move"], "path": "ch04-01-what-is-ownership.md", "url": "https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html#variables-and-data-interacting-with-move", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch04-01-what-is-ownership.md#variables-and-data-interacting-with-move-13", "text": "The Rust Programming Language › What Is Ownership? › Memory and Allocation › Variables and Data Interacting with Move\n\n```console\n$ cargo run\n Compiling ownership v0.1.0 (file:///projects/ownership)\nerror[E0382]: borrow of moved value: `s1`\n --> src/main.rs:5:16\n |\n2 | let s1 = String::from(\"hello\");\n | -- move occurs because `s1` has type `String`, which does not implement the `Copy` trait\n3 | let s2 = s1;\n | -- value moved here\n4 |\n5 | println!(\"{s1}, world!\");\n | ^^ value borrowed here after move\n |\nhelp: consider cloning the value if the performance cost is acceptable\n |\n3 | let s2 = s1.clone();\n | ++++++++\n\nFor more information about this error, try `rustc --explain E0382`.\nerror: could not compile `ownership` (bin \"ownership\") due to 1 previous error\n```\nIf you’ve heard the terms _shallow copy_ and _deep copy_ while working with\nother languages, the concept of copying the pointer, length, and capacity\nwithout copying the data probably sounds like making a shallow copy. But\nbecause Rust also invalidates the first variable, instead of being called a\nshallow copy, it’s known as a _move_. In this example, we would say that `s1`\nwas _moved_ into `s2`. So, what actually happens is shown in Figure 4-4.\n\"Three", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "What is Ownership?", "heading_path": ["What Is Ownership?", "Memory and Allocation", "Variables and Data Interacting with Move"], "path": "ch04-01-what-is-ownership.md", "url": "https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html#variables-and-data-interacting-with-move", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch04-01-what-is-ownership.md#scope-and-assignment-14", "text": "The Rust Programming Language › What Is Ownership? › Memory and Allocation › Scope and Assignment\n\nFigure 4-4: The representation in memory after `s1` has\nbeen invalidated\nThat solves our problem! With only `s2` valid, when it goes out of scope it\nalone will free the memory, and we’re done.\nIn addition, there’s a design choice that’s implied by this: Rust will never\nautomatically create “deep” copies of your data. Therefore, any _automatic_\ncopying can be assumed to be inexpensive in terms of runtime performance.\nThe inverse of this is true for the relationship between scoping, ownership, and\nmemory being freed via the `drop` function as well. When you assign a completely\nnew value to an existing variable, Rust will call `drop` and free the original\nvalue’s memory immediately. Consider this code, for example:\n```rust\n let mut s = String::from(\"hello\");\n s = String::from(\"ahoy\");\n\n println!(\"{s}, world!\");\n```\nWe initially declare a variable `s` and bind it to a `String` with the value\n`\"hello\"`. Then, we immediately create a new `String` with the value `\"ahoy\"`\nand assign it to `s`. At this point, nothing is referring to the original value\non the heap at all. Figure 4-5 illustrates the stack and heap data now:\n\"One\nFigure 4-5: The representation in memory after the initial\nvalue has been replaced in its entirety", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "What is Ownership?", "heading_path": ["What Is Ownership?", "Memory and Allocation", "Scope and Assignment"], "path": "ch04-01-what-is-ownership.md", "url": "https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html#scope-and-assignment", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch04-01-what-is-ownership.md#stack-only-data-copy-15", "text": "The Rust Programming Language › What Is Ownership? › Memory and Allocation › Stack-Only Data: Copy\n\nThe original string thus immediately goes out of scope. Rust will run the `drop`\nfunction on it and its memory will be freed right away. When we print the value\nat the end, it will be `\"ahoy, world!\"`.\nIf we _do_ want to deeply copy the heap data of the `String`, not just the\nstack data, we can use a common method called `clone`. We’ll discuss method\nsyntax in Chapter 5, but because methods are a common feature in many\nprogramming languages, you’ve probably seen them before.\nHere’s an example of the `clone` method in action:\n```rust\n let s1 = String::from(\"hello\");\n let s2 = s1.clone();\n\n println!(\"s1 = {s1}, s2 = {s2}\");\n```\nThis works just fine and explicitly produces the behavior shown in Figure 4-3,\nwhere the heap data _does_ get copied.\nWhen you see a call to `clone`, you know that some arbitrary code is being\nexecuted and that code may be expensive. It’s a visual indicator that something\ndifferent is going on.\nThere’s another wrinkle we haven’t talked about yet. This code using\nintegers—part of which was shown in Listing 4-2—works and is valid:\n```rust\n let x = 5;\n let y = x;\n\n println!(\"x = {x}, y = {y}\");\n```\nBut this code seems to contradict what we just learned: We don’t have a call to\n`clone`, but `x` is still valid and wasn’t moved into `y`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "What is Ownership?", "heading_path": ["What Is Ownership?", "Memory and Allocation", "Stack-Only Data: Copy"], "path": "ch04-01-what-is-ownership.md", "url": "https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html#stack-only-data-copy", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch04-01-what-is-ownership.md#stack-only-data-copy-16", "text": "The Rust Programming Language › What Is Ownership? › Memory and Allocation › Stack-Only Data: Copy\n\nThe reason is that types such as integers that have a known size at compile\ntime are stored entirely on the stack, so copies of the actual values are quick\nto make. That means there’s no reason we would want to prevent `x` from being\nvalid after we create the variable `y`. In other words, there’s no difference\nbetween deep and shallow copying here, so calling `clone` wouldn’t do anything\ndifferent from the usual shallow copying, and we can leave it out.\nRust has a special annotation called the `Copy` trait that we can place on\ntypes that are stored on the stack, as integers are (we’ll talk more about\ntraits in Chapter 10). If a type implements the `Copy`\ntrait, variables that use it do not move, but rather are trivially copied,\nmaking them still valid after assignment to another variable.\nRust won’t let us annotate a type with `Copy` if the type, or any of its parts,\nhas implemented the `Drop` trait. If the type needs something special to happen\nwhen the value goes out of scope and we add the `Copy` annotation to that type,\nwe’ll get a compile-time error. To learn about how to add the `Copy` annotation\nto your type to implement the trait, see “Derivable\nTraits” in Appendix C.\nSo, what types implement the `Copy` trait? You can check the documentation for\nthe given type to be sure, but as a general rule, any group of simple scalar\nvalues can implement `Copy`, and nothing that requires allocation or is some\nform of resource can implement `Copy`. Here are some of the types that\nimplement `Copy`:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "What is Ownership?", "heading_path": ["What Is Ownership?", "Memory and Allocation", "Stack-Only Data: Copy"], "path": "ch04-01-what-is-ownership.md", "url": "https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html#stack-only-data-copy", "has_code": false, "code_tags": []}} {"id": "book/ch04-01-what-is-ownership.md#stack-only-data-copy-17", "text": "The Rust Programming Language › What Is Ownership? › Memory and Allocation › Stack-Only Data: Copy\n\n- All the integer types, such as `u32`.\n- The Boolean type, `bool`, with values `true` and `false`.\n- All the floating-point types, such as `f64`.\n- The character type, `char`.\n- Tuples, if they only contain types that also implement `Copy`. For example,\n `(i32, i32)` implements `Copy`, but `(i32, String)` does not.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "What is Ownership?", "heading_path": ["What Is Ownership?", "Memory and Allocation", "Stack-Only Data: Copy"], "path": "ch04-01-what-is-ownership.md", "url": "https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html#stack-only-data-copy", "has_code": false, "code_tags": []}} {"id": "book/ch04-01-what-is-ownership.md#ownership-and-functions-18", "text": "The Rust Programming Language › What Is Ownership? › Ownership and Functions\n\nThe mechanics of passing a value to a function are similar to those when\nassigning a value to a variable. Passing a variable to a function will move or\ncopy, just as assignment does. Listing 4-3 has an example with some annotations\nshowing where variables go into and out of scope.\nListing 4-3: Functions with ownership and scope annotated (src/main.rs)\n```rust\nfn main() {\n let s = String::from(\"hello\"); // s comes into scope\n\n takes_ownership(s); // s's value moves into the function...\n // ... and so is no longer valid here\n\n let x = 5; // x comes into scope\n\n makes_copy(x); // Because i32 implements the Copy trait,\n // x does NOT move into the function,\n // so it's okay to use x afterward.\n\n} // Here, x goes out of scope, then s. However, because s's value was moved,\n // nothing special happens.\n\nfn takes_ownership(some_string: String) { // some_string comes into scope\n println!(\"{some_string}\");\n} // Here, some_string goes out of scope and `drop` is called. The backing\n // memory is freed.\n\nfn makes_copy(some_integer: i32) { // some_integer comes into scope\n println!(\"{some_integer}\");\n} // Here, some_integer goes out of scope. Nothing special happens.\n```\nIf we tried to use `s` after the call to `takes_ownership`, Rust would throw a\ncompile-time error. These static checks protect us from mistakes. Try adding\ncode to `main` that uses `s` and `x` to see where you can use them and where\nthe ownership rules prevent you from doing so.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "What is Ownership?", "heading_path": ["What Is Ownership?", "Ownership and Functions"], "path": "ch04-01-what-is-ownership.md", "url": "https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html#ownership-and-functions", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch04-01-what-is-ownership.md#return-values-and-scope-19", "text": "The Rust Programming Language › What Is Ownership? › Return Values and Scope\n\nReturning values can also transfer ownership. Listing 4-4 shows an example of a\nfunction that returns some value, with similar annotations as those in Listing\n4-3.\nListing 4-4: Transferring ownership of return values (src/main.rs)\n```rust\nfn main() {\n let s1 = gives_ownership(); // gives_ownership moves its return\n // value into s1\n\n let s2 = String::from(\"hello\"); // s2 comes into scope\n\n let s3 = takes_and_gives_back(s2); // s2 is moved into\n // takes_and_gives_back, which also\n // moves its return value into s3\n} // Here, s3 goes out of scope and is dropped. s2 was moved, so nothing\n // happens. s1 goes out of scope and is dropped.\n\nfn gives_ownership() -> String { // gives_ownership will move its\n // return value into the function\n // that calls it\n\n let some_string = String::from(\"yours\"); // some_string comes into scope\n\n some_string // some_string is returned and\n // moves out to the calling\n // function\n}\n\n// This function takes a String and returns a String.\nfn takes_and_gives_back(a_string: String) -> String {\n // a_string comes into\n // scope\n\n a_string // a_string is returned and moves out to the calling function\n}\n```\nThe ownership of a variable follows the same pattern every time: Assigning a\nvalue to another variable moves it. When a variable that includes data on the\nheap goes out of scope, the value will be cleaned up by `drop` unless ownership\nof the data has been moved to another variable.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "What is Ownership?", "heading_path": ["What Is Ownership?", "Return Values and Scope"], "path": "ch04-01-what-is-ownership.md", "url": "https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html#return-values-and-scope", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch04-01-what-is-ownership.md#return-values-and-scope-20", "text": "The Rust Programming Language › What Is Ownership? › Return Values and Scope\n\nWhile this works, taking ownership and then returning ownership with every\nfunction is a bit tedious. What if we want to let a function use a value but\nnot take ownership? It’s quite annoying that anything we pass in also needs to\nbe passed back if we want to use it again, in addition to any data resulting\nfrom the body of the function that we might want to return as well.\nRust does let us return multiple values using a tuple, as shown in Listing 4-5.\nListing 4-5: Returning ownership of parameters (src/main.rs)\n```rust\nfn main() {\n let s1 = String::from(\"hello\");\n\n let (s2, len) = calculate_length(s1);\n\n println!(\"The length of '{s2}' is {len}.\");\n}\n\nfn calculate_length(s: String) -> (String, usize) {\n let length = s.len(); // len() returns the length of a String\n\n (s, length)\n}\n```\nBut this is too much ceremony and a lot of work for a concept that should be\ncommon. Luckily for us, Rust has a feature for using a value without\ntransferring ownership: references.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "What is Ownership?", "heading_path": ["What Is Ownership?", "Return Values and Scope"], "path": "ch04-01-what-is-ownership.md", "url": "https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html#return-values-and-scope", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch04-02-references-and-borrowing.md#references-and-borrowing-0", "text": "The Rust Programming Language › References and Borrowing\n\nThe issue with the tuple code in Listing 4-5 is that we have to return the\n`String` to the calling function so that we can still use the `String` after\nthe call to `calculate_length`, because the `String` was moved into\n`calculate_length`. Instead, we can provide a reference to the `String` value.\nA reference is like a pointer in that it’s an address we can follow to access\nthe data stored at that address; that data is owned by some other variable.\nUnlike a pointer, a reference is guaranteed to point to a valid value of a\nparticular type for the life of that reference.\nHere is how you would define and use a `calculate_length` function that has a\nreference to an object as a parameter instead of taking ownership of the value:\nListing (src/main.rs)\n```rust\nfn main() {\n let s1 = String::from(\"hello\");\n\n let len = calculate_length(&s1);\n\n println!(\"The length of '{s1}' is {len}.\");\n}\n\nfn calculate_length(s: &String) -> usize {\n s.len()\n}\n```\nFirst, notice that all the tuple code in the variable declaration and the\nfunction return value is gone. Second, note that we pass `&s1` into\n`calculate_length` and, in its definition, we take `&String` rather than\n`String`. These ampersands represent references, and they allow you to refer to\nsome value without taking ownership of it. Figure 4-6 depicts this concept.\n\"Three", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "References and Borrowing", "heading_path": ["References and Borrowing"], "path": "ch04-02-references-and-borrowing.md", "url": "https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html#references-and-borrowing", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch04-02-references-and-borrowing.md#references-and-borrowing-1", "text": "The Rust Programming Language › References and Borrowing\n\nFigure 4-6: A diagram of `&String` `s` pointing at\n`String` `s1`\nNote: The opposite of referencing by using `&` is _dereferencing_, which is\naccomplished with the dereference operator, `*`. We’ll see some uses of the\ndereference operator in Chapter 8 and discuss details of dereferencing in\nChapter 15.\nLet’s take a closer look at the function call here:\n```rust\n let s1 = String::from(\"hello\");\n\n let len = calculate_length(&s1);\n```\nThe `&s1` syntax lets us create a reference that _refers_ to the value of `s1`\nbut does not own it. Because the reference does not own it, the value it points\nto will not be dropped when the reference stops being used.\nLikewise, the signature of the function uses `&` to indicate that the type of\nthe parameter `s` is a reference. Let’s add some explanatory annotations:\n```rust\nfn calculate_length(s: &String) -> usize { // s is a reference to a String\n s.len()\n} // Here, s goes out of scope. But because s does not have ownership of what\n // it refers to, the String is not dropped.\n```\nThe scope in which the variable `s` is valid is the same as any function\nparameter’s scope, but the value pointed to by the reference is not dropped\nwhen `s` stops being used, because `s` doesn’t have ownership. When functions\nhave references as parameters instead of the actual values, we won’t need to\nreturn the values in order to give back ownership, because we never had\nownership.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "References and Borrowing", "heading_path": ["References and Borrowing"], "path": "ch04-02-references-and-borrowing.md", "url": "https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html#references-and-borrowing", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch04-02-references-and-borrowing.md#references-and-borrowing-2", "text": "The Rust Programming Language › References and Borrowing\n\nWe call the action of creating a reference _borrowing_. As in real life, if a\nperson owns something, you can borrow it from them. When you’re done, you have\nto give it back. You don’t own it.\nSo, what happens if we try to modify something we’re borrowing? Try the code in\nListing 4-6. Spoiler alert: It doesn’t work!\nListing 4-6: Attempting to modify a borrowed value (src/main.rs)\n```rust,ignore,does_not_compile\nfn main() {\n let s = String::from(\"hello\");\n\n change(&s);\n}\n\nfn change(some_string: &String) {\n some_string.push_str(\", world\");\n}\n```\nHere’s the error:\n```console\n$ cargo run\n Compiling ownership v0.1.0 (file:///projects/ownership)\nerror[E0596]: cannot borrow `*some_string` as mutable, as it is behind a `&` reference\n --> src/main.rs:8:5\n |\n8 | some_string.push_str(\", world\");\n | ^^^^^^^^^^^ `some_string` is a `&` reference, so it cannot be borrowed as mutable\n |\nhelp: consider changing this to be a mutable reference\n |\n7 | fn change(some_string: &mut String) {\n | +++\n\nFor more information about this error, try `rustc --explain E0596`.\nerror: could not compile `ownership` (bin \"ownership\") due to 1 previous error\n```\nJust as variables are immutable by default, so are references. We’re not\nallowed to modify something we have a reference to.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "References and Borrowing", "heading_path": ["References and Borrowing"], "path": "ch04-02-references-and-borrowing.md", "url": "https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html#references-and-borrowing", "has_code": true, "code_tags": ["console", "rust,ignore,does_not_compile"]}} {"id": "book/ch04-02-references-and-borrowing.md#mutable-references-3", "text": "The Rust Programming Language › References and Borrowing › Mutable References\n\nWe can fix the code from Listing 4-6 to allow us to modify a borrowed value\nwith just a few small tweaks that use, instead, a _mutable reference_:\nListing (src/main.rs)\n```rust\nfn main() {\n let mut s = String::from(\"hello\");\n\n change(&mut s);\n}\n\nfn change(some_string: &mut String) {\n some_string.push_str(\", world\");\n}\n```\nFirst, we change `s` to be `mut`. Then, we create a mutable reference with\n`&mut s` where we call the `change` function and update the function signature\nto accept a mutable reference with `some_string: &mut String`. This makes it\nvery clear that the `change` function will mutate the value it borrows.\nMutable references have one big restriction: If you have a mutable reference to\na value, you can have no other references to that value. This code that\nattempts to create two mutable references to `s` will fail:\nListing (src/main.rs)\n```rust,ignore,does_not_compile\n let mut s = String::from(\"hello\");\n\n let r1 = &mut s;\n let r2 = &mut s;\n\n println!(\"{r1}, {r2}\");\n```\nHere’s the error:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "References and Borrowing", "heading_path": ["References and Borrowing", "Mutable References"], "path": "ch04-02-references-and-borrowing.md", "url": "https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html#mutable-references", "has_code": true, "code_tags": ["rust", "rust,ignore,does_not_compile"]}} {"id": "book/ch04-02-references-and-borrowing.md#mutable-references-4", "text": "The Rust Programming Language › References and Borrowing › Mutable References\n\n```console\n$ cargo run\n Compiling ownership v0.1.0 (file:///projects/ownership)\nerror[E0499]: cannot borrow `s` as mutable more than once at a time\n --> src/main.rs:5:14\n |\n4 | let r1 = &mut s;\n | ------ first mutable borrow occurs here\n5 | let r2 = &mut s;\n | ^^^^^^ second mutable borrow occurs here\n6 |\n7 | println!(\"{r1}, {r2}\");\n | -- first borrow later used here\n\nFor more information about this error, try `rustc --explain E0499`.\nerror: could not compile `ownership` (bin \"ownership\") due to 1 previous error\n```\nThis error says that this code is invalid because we cannot borrow `s` as\nmutable more than once at a time. The first mutable borrow is in `r1` and must\nlast until it’s used in the `println!`, but between the creation of that\nmutable reference and its usage, we tried to create another mutable reference\nin `r2` that borrows the same data as `r1`.\nThe restriction preventing multiple mutable references to the same data at the\nsame time allows for mutation but in a very controlled fashion. It’s something\nthat new Rustaceans struggle with because most languages let you mutate\nwhenever you’d like. The benefit of having this restriction is that Rust can\nprevent data races at compile time. A _data race_ is similar to a race\ncondition and happens when these three behaviors occur:\n- Two or more pointers access the same data at the same time.\n- At least one of the pointers is being used to write to the data.\n- There’s no mechanism being used to synchronize access to the data.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "References and Borrowing", "heading_path": ["References and Borrowing", "Mutable References"], "path": "ch04-02-references-and-borrowing.md", "url": "https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html#mutable-references", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch04-02-references-and-borrowing.md#mutable-references-5", "text": "The Rust Programming Language › References and Borrowing › Mutable References\n\nData races cause undefined behavior and can be difficult to diagnose and fix\nwhen you’re trying to track them down at runtime; Rust prevents this problem by\nrefusing to compile code with data races!\nAs always, we can use curly brackets to create a new scope, allowing for\nmultiple mutable references, just not _simultaneous_ ones:\n```rust\n let mut s = String::from(\"hello\");\n\n {\n let r1 = &mut s;\n } // r1 goes out of scope here, so we can make a new reference with no problems.\n\n let r2 = &mut s;\n```\nRust enforces a similar rule for combining mutable and immutable references.\nThis code results in an error:\n```rust,ignore,does_not_compile\n let mut s = String::from(\"hello\");\n\n let r1 = &s; // no problem\n let r2 = &s; // no problem\n let r3 = &mut s; // BIG PROBLEM\n\n println!(\"{r1}, {r2}, and {r3}\");\n```\nHere’s the error:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "References and Borrowing", "heading_path": ["References and Borrowing", "Mutable References"], "path": "ch04-02-references-and-borrowing.md", "url": "https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html#mutable-references", "has_code": true, "code_tags": ["rust", "rust,ignore,does_not_compile"]}} {"id": "book/ch04-02-references-and-borrowing.md#mutable-references-6", "text": "The Rust Programming Language › References and Borrowing › Mutable References\n\n```console\n$ cargo run\n Compiling ownership v0.1.0 (file:///projects/ownership)\nerror[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable\n --> src/main.rs:6:14\n |\n4 | let r1 = &s; // no problem\n | -- immutable borrow occurs here\n5 | let r2 = &s; // no problem\n6 | let r3 = &mut s; // BIG PROBLEM\n | ^^^^^^ mutable borrow occurs here\n7 |\n8 | println!(\"{r1}, {r2}, and {r3}\");\n | -- immutable borrow later used here\n\nFor more information about this error, try `rustc --explain E0502`.\nerror: could not compile `ownership` (bin \"ownership\") due to 1 previous error\n```\nWhew! We _also_ cannot have a mutable reference while we have an immutable one\nto the same value.\nUsers of an immutable reference don’t expect the value to suddenly change out\nfrom under them! However, multiple immutable references are allowed because no\none who is just reading the data has the ability to affect anyone else’s\nreading of the data.\nNote that a reference’s scope starts from where it is introduced and continues\nthrough the last time that reference is used. For instance, this code will\ncompile because the last usage of the immutable references is in the `println!`,\nbefore the mutable reference is introduced:\n```rust\n let mut s = String::from(\"hello\");\n\n let r1 = &s; // no problem\n let r2 = &s; // no problem\n println!(\"{r1} and {r2}\");\n // Variables r1 and r2 will not be used after this point.\n\n let r3 = &mut s; // no problem\n println!(\"{r3}\");\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "References and Borrowing", "heading_path": ["References and Borrowing", "Mutable References"], "path": "ch04-02-references-and-borrowing.md", "url": "https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html#mutable-references", "has_code": true, "code_tags": ["console", "rust"]}} {"id": "book/ch04-02-references-and-borrowing.md#mutable-references-7", "text": "The Rust Programming Language › References and Borrowing › Mutable References\n\nThe scopes of the immutable references `r1` and `r2` end after the `println!`\nwhere they are last used, which is before the mutable reference `r3` is\ncreated. These scopes don’t overlap, so this code is allowed: The compiler can\ntell that the reference is no longer being used at a point before the end of\nthe scope.\nEven though borrowing errors may be frustrating at times, remember that it’s\nthe Rust compiler pointing out a potential bug early (at compile time rather\nthan at runtime) and showing you exactly where the problem is. Then, you don’t\nhave to track down why your data isn’t what you thought it was.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "References and Borrowing", "heading_path": ["References and Borrowing", "Mutable References"], "path": "ch04-02-references-and-borrowing.md", "url": "https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html#mutable-references", "has_code": false, "code_tags": []}} {"id": "book/ch04-02-references-and-borrowing.md#dangling-references-8", "text": "The Rust Programming Language › References and Borrowing › Dangling References\n\nIn languages with pointers, it’s easy to erroneously create a _dangling\npointer_—a pointer that references a location in memory that may have been\ngiven to someone else—by freeing some memory while preserving a pointer to that\nmemory. In Rust, by contrast, the compiler guarantees that references will\nnever be dangling references: If you have a reference to some data, the\ncompiler will ensure that the data will not go out of scope before the\nreference to the data does.\nLet’s try to create a dangling reference to see how Rust prevents them with a\ncompile-time error:\nListing (src/main.rs)\n```rust,ignore,does_not_compile\nfn main() {\n let reference_to_nothing = dangle();\n}\n\nfn dangle() -> &String {\n let s = String::from(\"hello\");\n\n &s\n}\n```\nHere’s the error:\n```console\n$ cargo run\n Compiling ownership v0.1.0 (file:///projects/ownership)\nerror[E0106]: missing lifetime specifier\n --> src/main.rs:5:16\n |\n5 | fn dangle() -> &String {\n | ^ expected named lifetime parameter\n |\n = help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from\nhelp: consider using the `'static` lifetime, but this is uncommon unless you're returning a borrowed value from a `const` or a `static`\n |\n5 | fn dangle() -> &'static String {\n | +++++++\nhelp: instead, you are more likely to want to return an owned value\n |\n5 - fn dangle() -> &String {\n5 + fn dangle() -> String {\n |\n\nFor more information about this error, try `rustc --explain E0106`.\nerror: could not compile `ownership` (bin \"ownership\") due to 1 previous error\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "References and Borrowing", "heading_path": ["References and Borrowing", "Dangling References"], "path": "ch04-02-references-and-borrowing.md", "url": "https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html#dangling-references", "has_code": true, "code_tags": ["console", "rust,ignore,does_not_compile"]}} {"id": "book/ch04-02-references-and-borrowing.md#dangling-references-9", "text": "The Rust Programming Language › References and Borrowing › Dangling References\n\nThis error message refers to a feature we haven’t covered yet: lifetimes. We’ll\ndiscuss lifetimes in detail in Chapter 10. But, if you disregard the parts\nabout lifetimes, the message does contain the key to why this code is a problem:\n```text\nthis function's return type contains a borrowed value, but there is no value\nfor it to be borrowed from\n```\nLet’s take a closer look at exactly what’s happening at each stage of our\n`dangle` code:\nListing (src/main.rs)\n```rust,ignore,does_not_compile\nfn dangle() -> &String { // dangle returns a reference to a String\n\n let s = String::from(\"hello\"); // s is a new String\n\n &s // we return a reference to the String, s\n} // Here, s goes out of scope and is dropped, so its memory goes away.\n // Danger!\n```\nBecause `s` is created inside `dangle`, when the code of `dangle` is finished,\n`s` will be deallocated. But we tried to return a reference to it. That means\nthis reference would be pointing to an invalid `String`. That’s no good! Rust\nwon’t let us do this.\nThe solution here is to return the `String` directly:\n```rust\nfn no_dangle() -> String {\n let s = String::from(\"hello\");\n\n s\n}\n```\nThis works without any problems. Ownership is moved out, and nothing is\ndeallocated.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "References and Borrowing", "heading_path": ["References and Borrowing", "Dangling References"], "path": "ch04-02-references-and-borrowing.md", "url": "https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html#dangling-references", "has_code": true, "code_tags": ["rust", "rust,ignore,does_not_compile", "text"]}} {"id": "book/ch04-02-references-and-borrowing.md#the-rules-of-references-10", "text": "The Rust Programming Language › References and Borrowing › The Rules of References\n\nLet’s recap what we’ve discussed about references:\n- At any given time, you can have _either_ one mutable reference _or_ any\n number of immutable references.\n- References must always be valid.\nNext, we’ll look at a different kind of reference: slices.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "References and Borrowing", "heading_path": ["References and Borrowing", "The Rules of References"], "path": "ch04-02-references-and-borrowing.md", "url": "https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html#the-rules-of-references", "has_code": false, "code_tags": []}} {"id": "book/ch04-03-slices.md#the-slice-type-0", "text": "The Rust Programming Language › The Slice Type\n\n_Slices_ let you reference a contiguous sequence of elements in a\ncollection. A slice is a kind\nof reference, so it does not have ownership.\nHere’s a small programming problem: Write a function that takes a string of\nwords separated by spaces and returns the first word it finds in that string.\nIf the function doesn’t find a space in the string, the whole string must be\none word, so the entire string should be returned.\nNote: For the purposes of introducing slices, we are assuming ASCII only in\nthis section; a more thorough discussion of UTF-8 handling is in the\n“Storing UTF-8 Encoded Text with Strings” section\nof Chapter 8.\nLet’s work through how we’d write the signature of this function without using\nslices, to understand the problem that slices will solve:\n```rust,ignore\nfn first_word(s: &String) -> ?\n```\nThe `first_word` function has a parameter of type `&String`. We don’t need\nownership, so this is fine. (In idiomatic Rust, functions do not take ownership\nof their arguments unless they need to, and the reasons for that will become\nclear as we keep going.) But what should we return? We don’t really have a way\nto talk about *part* of a string. However, we could return the index of the end\nof the word, indicated by a space. Let’s try that, as shown in Listing 4-7.\nListing 4-7: The `first_word` function that returns a byte index value into the `String` parameter (src/main.rs)\n```rust\nfn first_word(s: &String) -> usize {\n let bytes = s.as_bytes();\n\n for (i, &item) in bytes.iter().enumerate() {\n if item == b' ' {\n return i;\n }\n }\n\n s.len()\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "The Slice Type", "heading_path": ["The Slice Type"], "path": "ch04-03-slices.md", "url": "https://doc.rust-lang.org/book/ch04-03-slices.html#the-slice-type", "has_code": true, "code_tags": ["rust", "rust,ignore"]}} {"id": "book/ch04-03-slices.md#the-slice-type-1", "text": "The Rust Programming Language › The Slice Type\n\nBecause we need to go through the `String` element by element and check whether\na value is a space, we’ll convert our `String` to an array of bytes using the\n`as_bytes` method.\n```rust,ignore\n let bytes = s.as_bytes();\n```\nNext, we create an iterator over the array of bytes using the `iter` method:\n```rust,ignore\n for (i, &item) in bytes.iter().enumerate() {\n```\nWe’ll discuss iterators in more detail in Chapter 13.\nFor now, know that `iter` is a method that returns each element in a collection\nand that `enumerate` wraps the result of `iter` and returns each element as\npart of a tuple instead. The first element of the tuple returned from\n`enumerate` is the index, and the second element is a reference to the element.\nThis is a bit more convenient than calculating the index ourselves.\nBecause the `enumerate` method returns a tuple, we can use patterns to\ndestructure that tuple. We’ll be discussing patterns more in Chapter\n6. In the `for` loop, we specify a pattern that has `i`\nfor the index in the tuple and `&item` for the single byte in the tuple.\nBecause we get a reference to the element from `.iter().enumerate()`, we use\n`&` in the pattern.\nInside the `for` loop, we search for the byte that represents the space by\nusing the byte literal syntax. If we find a space, we return the position.\nOtherwise, we return the length of the string by using `s.len()`.\n```rust,ignore\n if item == b' ' {\n return i;\n }\n }\n\n s.len()\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "The Slice Type", "heading_path": ["The Slice Type"], "path": "ch04-03-slices.md", "url": "https://doc.rust-lang.org/book/ch04-03-slices.html#the-slice-type", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch04-03-slices.md#the-slice-type-2", "text": "The Rust Programming Language › The Slice Type\n\nWe now have a way to find out the index of the end of the first word in the\nstring, but there’s a problem. We’re returning a `usize` on its own, but it’s\nonly a meaningful number in the context of the `&String`. In other words,\nbecause it’s a separate value from the `String`, there’s no guarantee that it\nwill still be valid in the future. Consider the program in Listing 4-8 that\nuses the `first_word` function from Listing 4-7.\nListing 4-8: Storing the result from calling the `first_word` function and then changing the `String` contents (src/main.rs)\n```rust\nfn main() {\n let mut s = String::from(\"hello world\");\n\n let word = first_word(&s); // word will get the value 5\n\n s.clear(); // this empties the String, making it equal to \"\"\n\n // word still has the value 5 here, but s no longer has any content that we\n // could meaningfully use with the value 5, so word is now totally invalid!\n}\n```\nThis program compiles without any errors and would also do so if we used `word`\nafter calling `s.clear()`. Because `word` isn’t connected to the state of `s`\nat all, `word` still contains the value `5`. We could use that value `5` with\nthe variable `s` to try to extract the first word out, but this would be a bug\nbecause the contents of `s` have changed since we saved `5` in `word`.\nHaving to worry about the index in `word` getting out of sync with the data in\n`s` is tedious and error-prone! Managing these indices is even more brittle if\nwe write a `second_word` function. Its signature would have to look like this:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "The Slice Type", "heading_path": ["The Slice Type"], "path": "ch04-03-slices.md", "url": "https://doc.rust-lang.org/book/ch04-03-slices.html#the-slice-type", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch04-03-slices.md#the-slice-type-3", "text": "The Rust Programming Language › The Slice Type\n\n```rust,ignore\nfn second_word(s: &String) -> (usize, usize) {\n```\nNow we’re tracking a starting _and_ an ending index, and we have even more\nvalues that were calculated from data in a particular state but aren’t tied to\nthat state at all. We have three unrelated variables floating around that need\nto be kept in sync.\nLuckily, Rust has a solution to this problem: string slices.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "The Slice Type", "heading_path": ["The Slice Type"], "path": "ch04-03-slices.md", "url": "https://doc.rust-lang.org/book/ch04-03-slices.html#the-slice-type", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch04-03-slices.md#string-slices-4", "text": "The Rust Programming Language › The Slice Type › String Slices\n\nA _string slice_ is a reference to a contiguous sequence of the elements of a\n`String`, and it looks like this:\n```rust\n let s = String::from(\"hello world\");\n\n let hello = &s[0..5];\n let world = &s[6..11];\n```\nRather than a reference to the entire `String`, `hello` is a reference to a\nportion of the `String`, specified in the extra `[0..5]` bit. We create slices\nusing a range within square brackets by specifying\n`[starting_index..ending_index]`, where _`starting_index`_ is the first\nposition in the slice and _`ending_index`_ is one more than the last position\nin the slice. Internally, the slice data structure stores the starting position\nand the length of the slice, which corresponds to _`ending_index`_ minus\n_`starting_index`_. So, in the case of `let world = &s[6..11];`, `world` would\nbe a slice that contains a pointer to the byte at index 6 of `s` with a length\nvalue of `5`.\nFigure 4-7 shows this in a diagram.\n\"Three\nFigure 4-7: A string slice referring to part of a\n`String`", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "The Slice Type", "heading_path": ["The Slice Type", "String Slices"], "path": "ch04-03-slices.md", "url": "https://doc.rust-lang.org/book/ch04-03-slices.html#string-slices", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch04-03-slices.md#string-slices-5", "text": "The Rust Programming Language › The Slice Type › String Slices\n\nWith Rust’s `..` range syntax, if you want to start at index 0, you can drop\nthe value before the two periods. In other words, these are equal:\n```rust\nlet s = String::from(\"hello\");\n\nlet slice = &s[0..2];\nlet slice = &s[..2];\n```\nBy the same token, if your slice includes the last byte of the `String`, you\ncan drop the trailing number. That means these are equal:\n```rust\nlet s = String::from(\"hello\");\n\nlet len = s.len();\n\nlet slice = &s[3..len];\nlet slice = &s[3..];\n```\nYou can also drop both values to take a slice of the entire string. So, these\nare equal:\n```rust\nlet s = String::from(\"hello\");\n\nlet len = s.len();\n\nlet slice = &s[0..len];\nlet slice = &s[..];\n```\nNote: String slice range indices must occur at valid UTF-8 character\nboundaries. If you attempt to create a string slice in the middle of a\nmultibyte character, your program will exit with an error.\nWith all this information in mind, let’s rewrite `first_word` to return a\nslice. The type that signifies “string slice” is written as `&str`:\nListing (src/main.rs)\n```rust\nfn first_word(s: &String) -> &str {\n let bytes = s.as_bytes();\n\n for (i, &item) in bytes.iter().enumerate() {\n if item == b' ' {\n return &s[0..i];\n }\n }\n\n &s[..]\n}\n```\nWe get the index for the end of the word the same way we did in Listing 4-7, by\nlooking for the first occurrence of a space. When we find a space, we return a\nstring slice using the start of the string and the index of the space as the\nstarting and ending indices.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "The Slice Type", "heading_path": ["The Slice Type", "String Slices"], "path": "ch04-03-slices.md", "url": "https://doc.rust-lang.org/book/ch04-03-slices.html#string-slices", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch04-03-slices.md#string-slices-6", "text": "The Rust Programming Language › The Slice Type › String Slices\n\nNow when we call `first_word`, we get back a single value that is tied to the\nunderlying data. The value is made up of a reference to the starting point of\nthe slice and the number of elements in the slice.\nReturning a slice would also work for a `second_word` function:\n```rust,ignore\nfn second_word(s: &String) -> &str {\n```\nWe now have a straightforward API that’s much harder to mess up because the\ncompiler will ensure that the references into the `String` remain valid.\nRemember the bug in the program in Listing 4-8, when we got the index to the\nend of the first word but then cleared the string so our index was invalid?\nThat code was logically incorrect but didn’t show any immediate errors. The\nproblems would show up later if we kept trying to use the first word index with\nan emptied string. Slices make this bug impossible and let us know much sooner\nthat we have a problem with our code. Using the slice version of `first_word`\nwill throw a compile-time error:\nListing (src/main.rs)\n```rust,ignore,does_not_compile\nfn main() {\n let mut s = String::from(\"hello world\");\n\n let word = first_word(&s);\n\n s.clear(); // error!\n\n println!(\"the first word is: {word}\");\n}\n```\nHere’s the compiler error:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "The Slice Type", "heading_path": ["The Slice Type", "String Slices"], "path": "ch04-03-slices.md", "url": "https://doc.rust-lang.org/book/ch04-03-slices.html#string-slices", "has_code": true, "code_tags": ["rust,ignore", "rust,ignore,does_not_compile"]}} {"id": "book/ch04-03-slices.md#string-slices-as-parameters-7", "text": "The Rust Programming Language › The Slice Type › String Slices › String Slices as Parameters\n\n```console\n$ cargo run\n Compiling ownership v0.1.0 (file:///projects/ownership)\nerror[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable\n --> src/main.rs:18:5\n |\n16 | let word = first_word(&s);\n | -- immutable borrow occurs here\n17 |\n18 | s.clear(); // error!\n | ^^^^^^^^^ mutable borrow occurs here\n19 |\n20 | println!(\"the first word is: {word}\");\n | ---- immutable borrow later used here\n\nFor more information about this error, try `rustc --explain E0502`.\nerror: could not compile `ownership` (bin \"ownership\") due to 1 previous error\n```\nRecall from the borrowing rules that if we have an immutable reference to\nsomething, we cannot also take a mutable reference. Because `clear` needs to\ntruncate the `String`, it needs to get a mutable reference. The `println!`\nafter the call to `clear` uses the reference in `word`, so the immutable\nreference must still be active at that point. Rust disallows the mutable\nreference in `clear` and the immutable reference in `word` from existing at the\nsame time, and compilation fails. Not only has Rust made our API easier to use,\nbut it has also eliminated an entire class of errors at compile time!\nRecall that we talked about string literals being stored inside the binary. Now\nthat we know about slices, we can properly understand string literals:\n```rust\nlet s = \"Hello, world!\";\n```\nThe type of `s` here is `&str`: It’s a slice pointing to that specific point of\nthe binary. This is also why string literals are immutable; `&str` is an\nimmutable reference.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "The Slice Type", "heading_path": ["The Slice Type", "String Slices", "String Slices as Parameters"], "path": "ch04-03-slices.md", "url": "https://doc.rust-lang.org/book/ch04-03-slices.html#string-slices-as-parameters", "has_code": true, "code_tags": ["console", "rust"]}} {"id": "book/ch04-03-slices.md#string-slices-as-parameters-8", "text": "The Rust Programming Language › The Slice Type › String Slices › String Slices as Parameters\n\nKnowing that you can take slices of literals and `String` values leads us to\none more improvement on `first_word`, and that’s its signature:\n```rust,ignore\nfn first_word(s: &String) -> &str {\n```\nA more experienced Rustacean would write the signature shown in Listing 4-9\ninstead because it allows us to use the same function on both `&String` values\nand `&str` values.\nListing 4-9: Improving the `first_word` function by using a string slice for the type of the `s` parameter\n```rust,ignore\nfn first_word(s: &str) -> &str {\n```\nIf we have a string slice, we can pass that directly. If we have a `String`, we\ncan pass a slice of the `String` or a reference to the `String`. This\nflexibility takes advantage of deref coercions, a feature we will cover in\nthe “Using Deref Coercions in Functions and Methods”\n section of Chapter 15.\nDefining a function to take a string slice instead of a reference to a `String`\nmakes our API more general and useful without losing any functionality:\nListing (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "The Slice Type", "heading_path": ["The Slice Type", "String Slices", "String Slices as Parameters"], "path": "ch04-03-slices.md", "url": "https://doc.rust-lang.org/book/ch04-03-slices.html#string-slices-as-parameters", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch04-03-slices.md#string-slices-as-parameters-9", "text": "The Rust Programming Language › The Slice Type › String Slices › String Slices as Parameters\n\n```rust\nfn main() {\n let my_string = String::from(\"hello world\");\n\n // `first_word` works on slices of `String`s, whether partial or whole.\n let word = first_word(&my_string[0..6]);\n let word = first_word(&my_string[..]);\n // `first_word` also works on references to `String`s, which are equivalent\n // to whole slices of `String`s.\n let word = first_word(&my_string);\n\n let my_string_literal = \"hello world\";\n\n // `first_word` works on slices of string literals, whether partial or\n // whole.\n let word = first_word(&my_string_literal[0..6]);\n let word = first_word(&my_string_literal[..]);\n\n // Because string literals *are* string slices already,\n // this works too, without the slice syntax!\n let word = first_word(my_string_literal);\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "The Slice Type", "heading_path": ["The Slice Type", "String Slices", "String Slices as Parameters"], "path": "ch04-03-slices.md", "url": "https://doc.rust-lang.org/book/ch04-03-slices.html#string-slices-as-parameters", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch04-03-slices.md#other-slices-10", "text": "The Rust Programming Language › The Slice Type › Other Slices\n\nString slices, as you might imagine, are specific to strings. But there’s a\nmore general slice type too. Consider this array:\n```rust\nlet a = [1, 2, 3, 4, 5];\n```\nJust as we might want to refer to part of a string, we might want to refer to\npart of an array. We’d do so like this:\n```rust\nlet a = [1, 2, 3, 4, 5];\n\nlet slice = &a[1..3];\n\nassert_eq!(slice, &[2, 3]);\n```\nThis slice has the type `&[i32]`. It works the same way as string slices do, by\nstoring a reference to the first element and a length. You’ll use this kind of\nslice for all sorts of other collections. We’ll discuss these collections in\ndetail when we talk about vectors in Chapter 8.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "The Slice Type", "heading_path": ["The Slice Type", "Other Slices"], "path": "ch04-03-slices.md", "url": "https://doc.rust-lang.org/book/ch04-03-slices.html#other-slices", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch04-03-slices.md#summary-11", "text": "The Rust Programming Language › Summary\n\nThe concepts of ownership, borrowing, and slices ensure memory safety in Rust\nprograms at compile time. The Rust language gives you control over your memory\nusage in the same way as other systems programming languages. But having the\nowner of data automatically clean up that data when the owner goes out of scope\nmeans you don’t have to write and debug extra code to get this control.\nOwnership affects how lots of other parts of Rust work, so we’ll talk about\nthese concepts further throughout the rest of the book. Let’s move on to\nChapter 5 and look at grouping pieces of data together in a `struct`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "The Slice Type", "heading_path": ["Summary"], "path": "ch04-03-slices.md", "url": "https://doc.rust-lang.org/book/ch04-03-slices.html#summary", "has_code": false, "code_tags": []}} {"id": "book/ch05-00-structs.md#using-structs-to-structure-related-data-0", "text": "The Rust Programming Language › Using Structs to Structure Related Data\n\nA _struct_, or _structure_, is a custom data type that lets you package\ntogether and name multiple related values that make up a meaningful group. If\nyou’re familiar with an object-oriented language, a struct is like an object’s\ndata attributes. In this chapter, we’ll compare and contrast tuples with\nstructs to build on what you already know and demonstrate when structs are a\nbetter way to group data.\nWe’ll demonstrate how to define and instantiate structs. We’ll discuss how to\ndefine associated functions, especially the kind of associated functions called\n_methods_, to specify behavior associated with a struct type. Structs and enums\n(discussed in Chapter 6) are the building blocks for creating new types in your\nprogram’s domain to take full advantage of Rust’s compile-time type checking.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using Structs to Structure Related Data", "heading_path": ["Using Structs to Structure Related Data"], "path": "ch05-00-structs.md", "url": "https://doc.rust-lang.org/book/ch05-00-structs.html#using-structs-to-structure-related-data", "has_code": false, "code_tags": []}} {"id": "book/ch05-01-defining-structs.md#defining-and-instantiating-structs-0", "text": "The Rust Programming Language › Defining and Instantiating Structs\n\nStructs are similar to tuples, discussed in “The Tuple Type”\n section, in that both hold multiple related values. Like tuples, the\npieces of a struct can be different types. Unlike with tuples, in a struct\nyou’ll name each piece of data so it’s clear what the values mean. Adding these\nnames means that structs are more flexible than tuples: You don’t have to rely\non the order of the data to specify or access the values of an instance.\nTo define a struct, we enter the keyword `struct` and name the entire struct. A\nstruct’s name should describe the significance of the pieces of data being\ngrouped together. Then, inside curly brackets, we define the names and types of\nthe pieces of data, which we call _fields_. For example, Listing 5-1 shows a\nstruct that stores information about a user account.\nListing 5-1: A `User` struct definition (src/main.rs)\n```rust\nstruct User {\n active: bool,\n username: String,\n email: String,\n sign_in_count: u64,\n}\n```\nTo use a struct after we’ve defined it, we create an _instance_ of that struct\nby specifying concrete values for each of the fields. We create an instance by\nstating the name of the struct and then add curly brackets containing _`key:\nvalue`_ pairs, where the keys are the names of the fields and the values are the\ndata we want to store in those fields. We don’t have to specify the fields in\nthe same order in which we declared them in the struct. In other words, the\nstruct definition is like a general template for the type, and instances fill\nin that template with particular data to create values of the type. For\nexample, we can declare a particular user as shown in Listing 5-2.\nListing 5-2: Creating an instance of the `User` struct (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining and Instantiating Structs", "heading_path": ["Defining and Instantiating Structs"], "path": "ch05-01-defining-structs.md", "url": "https://doc.rust-lang.org/book/ch05-01-defining-structs.html#defining-and-instantiating-structs", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch05-01-defining-structs.md#defining-and-instantiating-structs-1", "text": "The Rust Programming Language › Defining and Instantiating Structs\n\n```rust\nfn main() {\n let user1 = User {\n active: true,\n username: String::from(\"someusername123\"),\n email: String::from(\"someone@example.com\"),\n sign_in_count: 1,\n };\n}\n```\nTo get a specific value from a struct, we use dot notation. For example, to\naccess this user’s email address, we use `user1.email`. If the instance is\nmutable, we can change a value by using the dot notation and assigning into a\nparticular field. Listing 5-3 shows how to change the value in the `email`\nfield of a mutable `User` instance.\nListing 5-3: Changing the value in the `email` field of a `User` instance (src/main.rs)\n```rust\nfn main() {\n let mut user1 = User {\n active: true,\n username: String::from(\"someusername123\"),\n email: String::from(\"someone@example.com\"),\n sign_in_count: 1,\n };\n\n user1.email = String::from(\"anotheremail@example.com\");\n}\n```\nNote that the entire instance must be mutable; Rust doesn’t allow us to mark\nonly certain fields as mutable. As with any expression, we can construct a new\ninstance of the struct as the last expression in the function body to\nimplicitly return that new instance.\nListing 5-4 shows a `build_user` function that returns a `User` instance with\nthe given email and username. The `active` field gets the value `true`, and the\n`sign_in_count` gets a value of `1`.\nListing 5-4: A `build_user` function that takes an email and username and returns a `User` instance (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining and Instantiating Structs", "heading_path": ["Defining and Instantiating Structs"], "path": "ch05-01-defining-structs.md", "url": "https://doc.rust-lang.org/book/ch05-01-defining-structs.html#defining-and-instantiating-structs", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch05-01-defining-structs.md#defining-and-instantiating-structs-2", "text": "The Rust Programming Language › Defining and Instantiating Structs\n\n```rust\nfn build_user(email: String, username: String) -> User {\n User {\n active: true,\n username: username,\n email: email,\n sign_in_count: 1,\n }\n}\n```\nIt makes sense to name the function parameters with the same name as the struct\nfields, but having to repeat the `email` and `username` field names and\nvariables is a bit tedious. If the struct had more fields, repeating each name\nwould get even more annoying. Luckily, there’s a convenient shorthand!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining and Instantiating Structs", "heading_path": ["Defining and Instantiating Structs"], "path": "ch05-01-defining-structs.md", "url": "https://doc.rust-lang.org/book/ch05-01-defining-structs.html#defining-and-instantiating-structs", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch05-01-defining-structs.md#using-the-field-init-shorthand-3", "text": "The Rust Programming Language › Defining and Instantiating Structs › Using the Field Init Shorthand\n\nBecause the parameter names and the struct field names are exactly the same in\nListing 5-4, we can use the _field init shorthand_ syntax to rewrite\n`build_user` so that it behaves exactly the same but doesn’t have the\nrepetition of `username` and `email`, as shown in Listing 5-5.\nListing 5-5: A `build_user` function that uses field init shorthand because the `username` and `email` parameters have the same name as struct fields (src/main.rs)\n```rust\nfn build_user(email: String, username: String) -> User {\n User {\n active: true,\n username,\n email,\n sign_in_count: 1,\n }\n}\n```\nHere, we’re creating a new instance of the `User` struct, which has a field\nnamed `email`. We want to set the `email` field’s value to the value in the\n`email` parameter of the `build_user` function. Because the `email` field and\nthe `email` parameter have the same name, we only need to write `email` rather\nthan `email: email`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining and Instantiating Structs", "heading_path": ["Defining and Instantiating Structs", "Using the Field Init Shorthand"], "path": "ch05-01-defining-structs.md", "url": "https://doc.rust-lang.org/book/ch05-01-defining-structs.html#using-the-field-init-shorthand", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch05-01-defining-structs.md#creating-instances-with-struct-update-syntax-4", "text": "The Rust Programming Language › Defining and Instantiating Structs › Creating Instances with Struct Update Syntax\n\nIt’s often useful to create a new instance of a struct that includes most of\nthe values from another instance of the same type, but changes some of them.\nYou can do this using struct update syntax.\nFirst, in Listing 5-6 we show how to create a new `User` instance in `user2` in\nthe regular way, without the update syntax. We set a new value for `email` but\notherwise use the same values from `user1` that we created in Listing 5-2.\nListing 5-6: Creating a new `User` instance using all but one of the values from `user1` (src/main.rs)\n```rust\nfn main() {\n // --snip--\n\n let user2 = User {\n active: user1.active,\n username: user1.username,\n email: String::from(\"another@example.com\"),\n sign_in_count: user1.sign_in_count,\n };\n}\n```\nUsing struct update syntax, we can achieve the same effect with less code, as\nshown in Listing 5-7. The syntax `..` specifies that the remaining fields not\nexplicitly set should have the same value as the fields in the given instance.\nListing 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` (src/main.rs)\n```rust\nfn main() {\n // --snip--\n\n let user2 = User {\n email: String::from(\"another@example.com\"),\n ..user1\n };\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining and Instantiating Structs", "heading_path": ["Defining and Instantiating Structs", "Creating Instances with Struct Update Syntax"], "path": "ch05-01-defining-structs.md", "url": "https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-with-struct-update-syntax", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch05-01-defining-structs.md#creating-instances-with-struct-update-syntax-5", "text": "The Rust Programming Language › Defining and Instantiating Structs › Creating Instances with Struct Update Syntax\n\nThe code in Listing 5-7 also creates an instance in `user2` that has a\ndifferent value for `email` but has the same values for the `username`,\n`active`, and `sign_in_count` fields from `user1`. The `..user1` must come last\nto specify that any remaining fields should get their values from the\ncorresponding fields in `user1`, but we can choose to specify values for as\nmany fields as we want in any order, regardless of the order of the fields in\nthe struct’s definition.\nNote that the struct update syntax uses `=` like an assignment; this is because\nit moves the data, just as we saw in the “Variables and Data Interacting with\nMove” section. In this example, we can no longer use\n`user1` after creating `user2` because the `String` in the `username` field of\n`user1` was moved into `user2`. If we had given `user2` new `String` values for\nboth `email` and `username`, and thus only used the `active` and `sign_in_count`\nvalues from `user1`, then `user1` would still be valid after creating `user2`.\nBoth `active` and `sign_in_count` are types that implement the `Copy` trait, so\nthe behavior we discussed in the “Stack-Only Data: Copy”\nsection would apply. We can also still use `user1.email` in this example,\nbecause its value was not moved out of `user1`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining and Instantiating Structs", "heading_path": ["Defining and Instantiating Structs", "Creating Instances with Struct Update Syntax"], "path": "ch05-01-defining-structs.md", "url": "https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-with-struct-update-syntax", "has_code": false, "code_tags": []}} {"id": "book/ch05-01-defining-structs.md#creating-different-types-with-tuple-structs-6", "text": "The Rust Programming Language › Defining and Instantiating Structs › Creating Different Types with Tuple Structs\n\nRust also supports structs that look similar to tuples, called _tuple structs_.\nTuple structs have the added meaning the struct name provides but don’t have\nnames associated with their fields; rather, they just have the types of the\nfields. Tuple structs are useful when you want to give the whole tuple a name\nand make the tuple a different type from other tuples, and when naming each\nfield as in a regular struct would be verbose or redundant.\nTo define a tuple struct, start with the `struct` keyword and the struct name\nfollowed by the types in the tuple. For example, here we define and use two\ntuple structs named `Color` and `Point`:\nListing (src/main.rs)\n```rust\nstruct Color(i32, i32, i32);\nstruct Point(i32, i32, i32);\n\nfn main() {\n let black = Color(0, 0, 0);\n let origin = Point(0, 0, 0);\n}\n```\nNote that the `black` and `origin` values are different types because they’re\ninstances of different tuple structs. Each struct you define is its own type,\neven though the fields within the struct might have the same types. For\nexample, a function that takes a parameter of type `Color` cannot take a\n`Point` as an argument, even though both types are made up of three `i32`\nvalues. Otherwise, tuple struct instances are similar to tuples in that you can\ndestructure them into their individual pieces, and you can use a `.` followed\nby the index to access an individual value. Unlike tuples, tuple structs\nrequire you to name the type of the struct when you destructure them. For\nexample, we would write `let Point(x, y, z) = origin;` to destructure the\nvalues in the `origin` point into variables named `x`, `y`, and `z`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining and Instantiating Structs", "heading_path": ["Defining and Instantiating Structs", "Creating Different Types with Tuple Structs"], "path": "ch05-01-defining-structs.md", "url": "https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-different-types-with-tuple-structs", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch05-01-defining-structs.md#defining-unit-like-structs-7", "text": "The Rust Programming Language › Defining and Instantiating Structs › Defining Unit-Like Structs\n\nYou can also define structs that don’t have any fields! These are called\n_unit-like structs_ because they behave similarly to `()`, the unit type that\nwe mentioned in “The Tuple Type” section. Unit-like\nstructs can be useful when you need to implement a trait on some type but don’t\nhave any data that you want to store in the type itself. We’ll discuss traits\nin Chapter 10. Here’s an example of declaring and instantiating a unit struct\nnamed `AlwaysEqual`:\nListing (src/main.rs)\n```rust\nstruct AlwaysEqual;\n\nfn main() {\n let subject = AlwaysEqual;\n}\n```\nTo define `AlwaysEqual`, we use the `struct` keyword, the name we want, and\nthen a semicolon. No need for curly brackets or parentheses! Then, we can get\nan instance of `AlwaysEqual` in the `subject` variable in a similar way: using\nthe name we defined, without any curly brackets or parentheses. Imagine that\nlater we’ll implement behavior for this type such that every instance of\n`AlwaysEqual` is always equal to every instance of any other type, perhaps to\nhave a known result for testing purposes. We wouldn’t need any data to\nimplement that behavior! You’ll see in Chapter 10 how to define traits and\nimplement them on any type, including unit-like structs.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining and Instantiating Structs", "heading_path": ["Defining and Instantiating Structs", "Defining Unit-Like Structs"], "path": "ch05-01-defining-structs.md", "url": "https://doc.rust-lang.org/book/ch05-01-defining-structs.html#defining-unit-like-structs", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch05-01-defining-structs.md#ownership-of-struct-data-8", "text": "The Rust Programming Language › Defining and Instantiating Structs › Ownership of Struct Data\n\nIn the `User` struct definition in Listing 5-1, we used the owned `String`\ntype rather than the `&str` string slice type. This is a deliberate choice\nbecause we want each instance of this struct to own all of its data and for\nthat data to be valid for as long as the entire struct is valid.\nIt’s also possible for structs to store references to data owned by something\nelse, but to do so requires the use of _lifetimes_, a Rust feature that we’ll\ndiscuss in Chapter 10. Lifetimes ensure that the data referenced by a struct\nis valid for as long as the struct is. Let’s say you try to store a reference\nin a struct without specifying lifetimes, like the following in\n*src/main.rs*; this won’t work:\nListing (src/main.rs)\n```rust,ignore,does_not_compile\nstruct User {\n active: bool,\n username: &str,\n email: &str,\n sign_in_count: u64,\n}\n\nfn main() {\n let user1 = User {\n active: true,\n username: \"someusername123\",\n email: \"someone@example.com\",\n sign_in_count: 1,\n };\n}\n```\nThe compiler will complain that it needs lifetime specifiers:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining and Instantiating Structs", "heading_path": ["Defining and Instantiating Structs", "Ownership of Struct Data"], "path": "ch05-01-defining-structs.md", "url": "https://doc.rust-lang.org/book/ch05-01-defining-structs.html#ownership-of-struct-data", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch05-01-defining-structs.md#ownership-of-struct-data-9", "text": "The Rust Programming Language › Defining and Instantiating Structs › Ownership of Struct Data\n\n```console\n$ cargo run\n Compiling structs v0.1.0 (file:///projects/structs)\nerror[E0106]: missing lifetime specifier\n --> src/main.rs:3:15\n |\n3 | username: &str,\n | ^ expected named lifetime parameter\n |\nhelp: consider introducing a named lifetime parameter\n |\n1 ~ struct User<'a> {\n2 | active: bool,\n3 ~ username: &'a str,\n |\n\nerror[E0106]: missing lifetime specifier\n --> src/main.rs:4:12\n |\n4 | email: &str,\n | ^ expected named lifetime parameter\n |\nhelp: consider introducing a named lifetime parameter\n |\n1 ~ struct User<'a> {\n2 | active: bool,\n3 | username: &str,\n4 ~ email: &'a str,\n |\n\nFor more information about this error, try `rustc --explain E0106`.\nerror: could not compile `structs` (bin \"structs\") due to 2 previous errors\n```\nIn Chapter 10, we’ll discuss how to fix these errors so that you can store\nreferences in structs, but for now, we’ll fix errors like these using owned\ntypes like `String` instead of references like `&str`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining and Instantiating Structs", "heading_path": ["Defining and Instantiating Structs", "Ownership of Struct Data"], "path": "ch05-01-defining-structs.md", "url": "https://doc.rust-lang.org/book/ch05-01-defining-structs.html#ownership-of-struct-data", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch05-02-example-structs.md#an-example-program-using-structs-0", "text": "The Rust Programming Language › An Example Program Using Structs\n\nTo understand when we might want to use structs, let’s write a program that\ncalculates the area of a rectangle. We’ll start by using single variables and\nthen refactor the program until we’re using structs instead.\nLet’s make a new binary project with Cargo called _rectangles_ that will take\nthe width and height of a rectangle specified in pixels and calculate the area\nof the rectangle. Listing 5-8 shows a short program with one way of doing\nexactly that in our project’s _src/main.rs_.\nListing 5-8: Calculating the area of a rectangle specified by separate width and height variables (src/main.rs)\n```rust\nfn main() {\n let width1 = 30;\n let height1 = 50;\n\n println!(\n \"The area of the rectangle is {} square pixels.\",\n area(width1, height1)\n );\n}\n\nfn area(width: u32, height: u32) -> u32 {\n width * height\n}\n```\nNow, run this program using `cargo run`:\n```console\n$ cargo run\n Compiling rectangles v0.1.0 (file:///projects/rectangles)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.42s\n Running `target/debug/rectangles`\nThe area of the rectangle is 1500 square pixels.\n```\nThis code succeeds in figuring out the area of the rectangle by calling the\n`area` function with each dimension, but we can do more to make this code clear\nand readable.\nThe issue with this code is evident in the signature of `area`:\n```rust,ignore\nfn area(width: u32, height: u32) -> u32 {\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "An Example Program Using Structs", "heading_path": ["An Example Program Using Structs"], "path": "ch05-02-example-structs.md", "url": "https://doc.rust-lang.org/book/ch05-02-example-structs.html#an-example-program-using-structs", "has_code": true, "code_tags": ["console", "rust", "rust,ignore"]}} {"id": "book/ch05-02-example-structs.md#an-example-program-using-structs-1", "text": "The Rust Programming Language › An Example Program Using Structs\n\nThe `area` function is supposed to calculate the area of one rectangle, but the\nfunction we wrote has two parameters, and it’s not clear anywhere in our\nprogram that the parameters are related. It would be more readable and more\nmanageable to group width and height together. We’ve already discussed one way\nwe might do that in “The Tuple Type” section\nof Chapter 3: by using tuples.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "An Example Program Using Structs", "heading_path": ["An Example Program Using Structs"], "path": "ch05-02-example-structs.md", "url": "https://doc.rust-lang.org/book/ch05-02-example-structs.html#an-example-program-using-structs", "has_code": false, "code_tags": []}} {"id": "book/ch05-02-example-structs.md#refactoring-with-tuples-2", "text": "The Rust Programming Language › An Example Program Using Structs › Refactoring with Tuples\n\nListing 5-9 shows another version of our program that uses tuples.\nListing 5-9: Specifying the width and height of the rectangle with a tuple (src/main.rs)\n```rust\nfn main() {\n let rect1 = (30, 50);\n\n println!(\n \"The area of the rectangle is {} square pixels.\",\n area(rect1)\n );\n}\n\nfn area(dimensions: (u32, u32)) -> u32 {\n dimensions.0 * dimensions.1\n}\n```\nIn one way, this program is better. Tuples let us add a bit of structure, and\nwe’re now passing just one argument. But in another way, this version is less\nclear: Tuples don’t name their elements, so we have to index into the parts of\nthe tuple, making our calculation less obvious.\nMixing up the width and height wouldn’t matter for the area calculation, but if\nwe want to draw the rectangle on the screen, it would matter! We would have to\nkeep in mind that `width` is the tuple index `0` and `height` is the tuple\nindex `1`. This would be even harder for someone else to figure out and keep in\nmind if they were to use our code. Because we haven’t conveyed the meaning of\nour data in our code, it’s now easier to introduce errors.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "An Example Program Using Structs", "heading_path": ["An Example Program Using Structs", "Refactoring with Tuples"], "path": "ch05-02-example-structs.md", "url": "https://doc.rust-lang.org/book/ch05-02-example-structs.html#refactoring-with-tuples", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch05-02-example-structs.md#refactoring-with-structs-3", "text": "The Rust Programming Language › An Example Program Using Structs › Refactoring with Structs\n\nWe use structs to add meaning by labeling the data. We can transform the tuple\nwe’re using into a struct with a name for the whole as well as names for the\nparts, as shown in Listing 5-10.\nListing 5-10: Defining a `Rectangle` struct (src/main.rs)\n```rust\nstruct Rectangle {\n width: u32,\n height: u32,\n}\n\nfn main() {\n let rect1 = Rectangle {\n width: 30,\n height: 50,\n };\n\n println!(\n \"The area of the rectangle is {} square pixels.\",\n area(&rect1)\n );\n}\n\nfn area(rectangle: &Rectangle) -> u32 {\n rectangle.width * rectangle.height\n}\n```\nHere, we’ve defined a struct and named it `Rectangle`. Inside the curly\nbrackets, we defined the fields as `width` and `height`, both of which have\ntype `u32`. Then, in `main`, we created a particular instance of `Rectangle`\nthat has a width of `30` and a height of `50`.\nOur `area` function is now defined with one parameter, which we’ve named\n`rectangle`, whose type is an immutable borrow of a struct `Rectangle`\ninstance. As mentioned in Chapter 4, we want to borrow the struct rather than\ntake ownership of it. This way, `main` retains its ownership and can continue\nusing `rect1`, which is the reason we use the `&` in the function signature and\nwhere we call the function.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "An Example Program Using Structs", "heading_path": ["An Example Program Using Structs", "Refactoring with Structs"], "path": "ch05-02-example-structs.md", "url": "https://doc.rust-lang.org/book/ch05-02-example-structs.html#refactoring-with-structs", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch05-02-example-structs.md#refactoring-with-structs-4", "text": "The Rust Programming Language › An Example Program Using Structs › Refactoring with Structs\n\nThe `area` function accesses the `width` and `height` fields of the `Rectangle`\ninstance (note that accessing fields of a borrowed struct instance does not\nmove the field values, which is why you often see borrows of structs). Our\nfunction signature for `area` now says exactly what we mean: Calculate the area\nof `Rectangle`, using its `width` and `height` fields. This conveys that the\nwidth and height are related to each other, and it gives descriptive names to\nthe values rather than using the tuple index values of `0` and `1`. This is a\nwin for clarity.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "An Example Program Using Structs", "heading_path": ["An Example Program Using Structs", "Refactoring with Structs"], "path": "ch05-02-example-structs.md", "url": "https://doc.rust-lang.org/book/ch05-02-example-structs.html#refactoring-with-structs", "has_code": false, "code_tags": []}} {"id": "book/ch05-02-example-structs.md#adding-functionality-with-derived-traits-5", "text": "The Rust Programming Language › An Example Program Using Structs › Adding Functionality with Derived Traits\n\nIt’d be useful to be able to print an instance of `Rectangle` while we’re\ndebugging our program and see the values for all its fields. Listing 5-11 tries\nusing the `println!` macro as we have used in\nprevious chapters. This won’t work, however.\nListing 5-11: Attempting to print a `Rectangle` instance (src/main.rs)\n```rust,ignore,does_not_compile\nstruct Rectangle {\n width: u32,\n height: u32,\n}\n\nfn main() {\n let rect1 = Rectangle {\n width: 30,\n height: 50,\n };\n\n println!(\"rect1 is {rect1}\");\n}\n```\nWhen we compile this code, we get an error with this core message:\n```text\nerror[E0277]: `Rectangle` doesn't implement `std::fmt::Display`\n```\nThe `println!` macro can do many kinds of formatting, and by default, the curly\nbrackets tell `println!` to use formatting known as `Display`: output intended\nfor direct end user consumption. The primitive types we’ve seen so far\nimplement `Display` by default because there’s only one way you’d want to show\na `1` or any other primitive type to a user. But with structs, the way\n`println!` should format the output is less clear because there are more\ndisplay possibilities: Do you want commas or not? Do you want to print the\ncurly brackets? Should all the fields be shown? Due to this ambiguity, Rust\ndoesn’t try to guess what we want, and structs don’t have a provided\nimplementation of `Display` to use with `println!` and the `{}` placeholder.\nIf we continue reading the errors, we’ll find this helpful note:\n```text\nhelp: the trait `std::fmt::Display` is not implemented for `Rectangle`\n --> src/main.rs:1:1\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "An Example Program Using Structs", "heading_path": ["An Example Program Using Structs", "Adding Functionality with Derived Traits"], "path": "ch05-02-example-structs.md", "url": "https://doc.rust-lang.org/book/ch05-02-example-structs.html#adding-functionality-with-derived-traits", "has_code": true, "code_tags": ["rust,ignore,does_not_compile", "text"]}} {"id": "book/ch05-02-example-structs.md#adding-functionality-with-derived-traits-6", "text": "The Rust Programming Language › An Example Program Using Structs › Adding Functionality with Derived Traits\n\nLet’s try it! The `println!` macro call will now look like `println!(\"rect1 is\n{rect1:?}\");`. Putting the specifier `:?` inside the curly brackets tells\n`println!` we want to use an output format called `Debug`. The `Debug` trait\nenables us to print our struct in a way that is useful for developers so that\nwe can see its value while we’re debugging our code.\nCompile the code with this change. Drat! We still get an error:\n```text\nerror[E0277]: `Rectangle` doesn't implement `Debug`\n```\nBut again, the compiler gives us a helpful note:\n```text\n | required by this formatting parameter\n |\n```\nRust _does_ include functionality to print out debugging information, but we\nhave to explicitly opt in to make that functionality available for our struct.\nTo do that, we add the outer attribute `#[derive(Debug)]` just before the\nstruct definition, as shown in Listing 5-12.\nListing 5-12: Adding the attribute to derive the `Debug` trait and printing the `Rectangle` instance using debug formatting (src/main.rs)\n```rust\n#[derive(Debug)]\nstruct Rectangle {\n width: u32,\n height: u32,\n}\n\nfn main() {\n let rect1 = Rectangle {\n width: 30,\n height: 50,\n };\n\n println!(\"rect1 is {rect1:?}\");\n}\n```\nNow when we run the program, we won’t get any errors, and we’ll see the\nfollowing output:\n```console\n$ cargo run\n Compiling rectangles v0.1.0 (file:///projects/rectangles)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.48s\n Running `target/debug/rectangles`\nrect1 is Rectangle { width: 30, height: 50 }\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "An Example Program Using Structs", "heading_path": ["An Example Program Using Structs", "Adding Functionality with Derived Traits"], "path": "ch05-02-example-structs.md", "url": "https://doc.rust-lang.org/book/ch05-02-example-structs.html#adding-functionality-with-derived-traits", "has_code": true, "code_tags": ["console", "rust", "text"]}} {"id": "book/ch05-02-example-structs.md#adding-functionality-with-derived-traits-7", "text": "The Rust Programming Language › An Example Program Using Structs › Adding Functionality with Derived Traits\n\nNice! It’s not the prettiest output, but it shows the values of all the fields\nfor this instance, which would definitely help during debugging. When we have\nlarger structs, it’s useful to have output that’s a bit easier to read; in\nthose cases, we can use `{:#?}` instead of `{:?}` in the `println!` string. In\nthis example, using the `{:#?}` style will output the following:\n```console\n$ cargo run\n Compiling rectangles v0.1.0 (file:///projects/rectangles)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.48s\n Running `target/debug/rectangles`\nrect1 is Rectangle {\n width: 30,\n height: 50,\n}\n```\nAnother way to print out a value using the `Debug` format is to use the `dbg!`\nmacro, which takes ownership of an expression (as opposed\nto `println!`, which takes a reference), prints the file and line number of\nwhere that `dbg!` macro call occurs in your code along with the resultant value\nof that expression, and returns ownership of the value.\nNote: Calling the `dbg!` macro prints to the standard error console stream\n(`stderr`), as opposed to `println!`, which prints to the standard output\nconsole stream (`stdout`). We’ll talk more about `stderr` and `stdout` in the\n“Redirecting Errors to Standard Error” section in Chapter\n12.\nHere’s an example where we’re interested in the value that gets assigned to the\n`width` field, as well as the value of the whole struct in `rect1`:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "An Example Program Using Structs", "heading_path": ["An Example Program Using Structs", "Adding Functionality with Derived Traits"], "path": "ch05-02-example-structs.md", "url": "https://doc.rust-lang.org/book/ch05-02-example-structs.html#adding-functionality-with-derived-traits", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch05-02-example-structs.md#adding-functionality-with-derived-traits-8", "text": "The Rust Programming Language › An Example Program Using Structs › Adding Functionality with Derived Traits\n\n```rust\n#[derive(Debug)]\nstruct Rectangle {\n width: u32,\n height: u32,\n}\n\nfn main() {\n let scale = 2;\n let rect1 = Rectangle {\n width: dbg!(30 * scale),\n height: 50,\n };\n\n dbg!(&rect1);\n}\n```\nWe can put `dbg!` around the expression `30 * scale` and, because `dbg!`\nreturns ownership of the expression’s value, the `width` field will get the\nsame value as if we didn’t have the `dbg!` call there. We don’t want `dbg!` to\ntake ownership of `rect1`, so we use a reference to `rect1` in the next call.\nHere’s what the output of this example looks like:\n```console\n$ cargo run\n Compiling rectangles v0.1.0 (file:///projects/rectangles)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.61s\n Running `target/debug/rectangles`\n[src/main.rs:10:16] 30 * scale = 60\n[src/main.rs:14:5] &rect1 = Rectangle {\n width: 60,\n height: 50,\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "An Example Program Using Structs", "heading_path": ["An Example Program Using Structs", "Adding Functionality with Derived Traits"], "path": "ch05-02-example-structs.md", "url": "https://doc.rust-lang.org/book/ch05-02-example-structs.html#adding-functionality-with-derived-traits", "has_code": true, "code_tags": ["console", "rust"]}} {"id": "book/ch05-02-example-structs.md#adding-functionality-with-derived-traits-9", "text": "The Rust Programming Language › An Example Program Using Structs › Adding Functionality with Derived Traits\n\nWe can see the first bit of output came from _src/main.rs_ line 10 where we’re\ndebugging the expression `30 * scale`, and its resultant value is `60` (the\n`Debug` formatting implemented for integers is to print only their value). The\n`dbg!` call on line 14 of _src/main.rs_ outputs the value of `&rect1`, which is\nthe `Rectangle` struct. This output uses the pretty `Debug` formatting of the\n`Rectangle` type. The `dbg!` macro can be really helpful when you’re trying to\nfigure out what your code is doing!\nIn addition to the `Debug` trait, Rust has provided a number of traits for us\nto use with the `derive` attribute that can add useful behavior to our custom\ntypes. Those traits and their behaviors are listed in Appendix C\n. We’ll cover how to implement these traits with custom behavior as\nwell as how to create your own traits in Chapter 10. There are also many\nattributes other than `derive`; for more information, see the “Attributes”\nsection of the Rust Reference.\nOur `area` function is very specific: It only computes the area of rectangles.\nIt would be helpful to tie this behavior more closely to our `Rectangle` struct\nbecause it won’t work with any other type. Let’s look at how we can continue to\nrefactor this code by turning the `area` function into an `area` method\ndefined on our `Rectangle` type.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "An Example Program Using Structs", "heading_path": ["An Example Program Using Structs", "Adding Functionality with Derived Traits"], "path": "ch05-02-example-structs.md", "url": "https://doc.rust-lang.org/book/ch05-02-example-structs.html#adding-functionality-with-derived-traits", "has_code": false, "code_tags": []}} {"id": "book/ch05-03-method-syntax.md#methods-0", "text": "The Rust Programming Language › Methods\n\nMethods are similar to functions: We declare them with the `fn` keyword and a\nname, they can have parameters and a return value, and they contain some code\nthat’s run when the method is called from somewhere else. Unlike functions,\nmethods are defined within the context of a struct (or an enum or a trait\nobject, which we cover in Chapter 6 and Chapter\n18, respectively), and their first parameter is\nalways `self`, which represents the instance of the struct the method is being\ncalled on.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Methods", "heading_path": ["Methods"], "path": "ch05-03-method-syntax.md", "url": "https://doc.rust-lang.org/book/ch05-03-method-syntax.html#methods", "has_code": false, "code_tags": []}} {"id": "book/ch05-03-method-syntax.md#method-syntax-1", "text": "The Rust Programming Language › Methods › Method Syntax\n\nLet’s change the `area` function that has a `Rectangle` instance as a parameter\nand instead make an `area` method defined on the `Rectangle` struct, as shown\nin Listing 5-13.\nListing 5-13: Defining an `area` method on the `Rectangle` struct (src/main.rs)\n```rust\n#[derive(Debug)]\nstruct Rectangle {\n width: u32,\n height: u32,\n}\n\nimpl Rectangle {\n fn area(&self) -> u32 {\n self.width * self.height\n }\n}\n\nfn main() {\n let rect1 = Rectangle {\n width: 30,\n height: 50,\n };\n\n println!(\n \"The area of the rectangle is {} square pixels.\",\n rect1.area()\n );\n}\n```\nTo define the function within the context of `Rectangle`, we start an `impl`\n(implementation) block for `Rectangle`. Everything within this `impl` block\nwill be associated with the `Rectangle` type. Then, we move the `area` function\nwithin the `impl` curly brackets and change the first (and in this case, only)\nparameter to be `self` in the signature and everywhere within the body. In\n`main`, where we called the `area` function and passed `rect1` as an argument,\nwe can instead use _method syntax_ to call the `area` method on our `Rectangle`\ninstance. The method syntax goes after an instance: We add a dot followed by\nthe method name, parentheses, and any arguments.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Methods", "heading_path": ["Methods", "Method Syntax"], "path": "ch05-03-method-syntax.md", "url": "https://doc.rust-lang.org/book/ch05-03-method-syntax.html#method-syntax", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch05-03-method-syntax.md#method-syntax-2", "text": "The Rust Programming Language › Methods › Method Syntax\n\nIn the signature for `area`, we use `&self` instead of `rectangle: &Rectangle`.\nThe `&self` is actually short for `self: &Self`. Within an `impl` block, the\ntype `Self` is an alias for the type that the `impl` block is for. Methods must\nhave a parameter named `self` of type `Self` for their first parameter, so Rust\nlets you abbreviate this with only the name `self` in the first parameter spot.\nNote that we still need to use the `&` in front of the `self` shorthand to\nindicate that this method borrows the `Self` instance, just as we did in\n`rectangle: &Rectangle`. Methods can take ownership of `self`, borrow `self`\nimmutably, as we’ve done here, or borrow `self` mutably, just as they can any\nother parameter.\nWe chose `&self` here for the same reason we used `&Rectangle` in the function\nversion: We don’t want to take ownership, and we just want to read the data in\nthe struct, not write to it. If we wanted to change the instance that we’ve\ncalled the method on as part of what the method does, we’d use `&mut self` as\nthe first parameter. Having a method that takes ownership of the instance by\nusing just `self` as the first parameter is rare; this technique is usually\nused when the method transforms `self` into something else and you want to\nprevent the caller from using the original instance after the transformation.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Methods", "heading_path": ["Methods", "Method Syntax"], "path": "ch05-03-method-syntax.md", "url": "https://doc.rust-lang.org/book/ch05-03-method-syntax.html#method-syntax", "has_code": false, "code_tags": []}} {"id": "book/ch05-03-method-syntax.md#method-syntax-3", "text": "The Rust Programming Language › Methods › Method Syntax\n\nThe main reason for using methods instead of functions, in addition to\nproviding method syntax and not having to repeat the type of `self` in every\nmethod’s signature, is for organization. We’ve put all the things we can do\nwith an instance of a type in one `impl` block rather than making future users\nof our code search for capabilities of `Rectangle` in various places in the\nlibrary we provide.\nNote that we can choose to give a method the same name as one of the struct’s\nfields. For example, we can define a method on `Rectangle` that is also named\n`width`:\nListing (src/main.rs)\n```rust\nimpl Rectangle {\n fn width(&self) -> bool {\n self.width > 0\n }\n}\n\nfn main() {\n let rect1 = Rectangle {\n width: 30,\n height: 50,\n };\n\n if rect1.width() {\n println!(\"The rectangle has a nonzero width; it is {}\", rect1.width);\n }\n}\n```\nHere, we’re choosing to make the `width` method return `true` if the value in\nthe instance’s `width` field is greater than `0` and `false` if the value is\n`0`: We can use a field within a method of the same name for any purpose. In\n`main`, when we follow `rect1.width` with parentheses, Rust knows we mean the\nmethod `width`. When we don’t use parentheses, Rust knows we mean the field\n`width`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Methods", "heading_path": ["Methods", "Method Syntax"], "path": "ch05-03-method-syntax.md", "url": "https://doc.rust-lang.org/book/ch05-03-method-syntax.html#method-syntax", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch05-03-method-syntax.md#method-syntax-4", "text": "The Rust Programming Language › Methods › Method Syntax\n\nOften, but not always, when we give a method the same name as a field we want\nit to only return the value in the field and do nothing else. Methods like this\nare called _getters_, and Rust does not implement them automatically for struct\nfields as some other languages do. Getters are useful because you can make the\nfield private but the method public and thus enable read-only access to that\nfield as part of the type’s public API. We will discuss what public and private\nare and how to designate a field or method as public or private in Chapter\n7.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Methods", "heading_path": ["Methods", "Method Syntax"], "path": "ch05-03-method-syntax.md", "url": "https://doc.rust-lang.org/book/ch05-03-method-syntax.html#method-syntax", "has_code": false, "code_tags": []}} {"id": "book/ch05-03-method-syntax.md#wheres-the---operator-5", "text": "The Rust Programming Language › Methods › Where’s the `->` Operator?\n\nIn C and C++, two different operators are used for calling methods: You use\n`.` if you’re calling a method on the object directly and `->` if you’re\ncalling the method on a pointer to the object and need to dereference the\npointer first. In other words, if `object` is a pointer,\n`object->something()` is similar to `(*object).something()`.\nRust doesn’t have an equivalent to the `->` operator; instead, Rust has a\nfeature called _automatic referencing and dereferencing_. Calling methods is\none of the few places in Rust with this behavior.\nHere’s how it works: When you call a method with `object.something()`, Rust\nautomatically adds in `&`, `&mut`, or `*` so that `object` matches the\nsignature of the method. In other words, the following are the same:\n```rust\np1.distance(&p2);\n(&p1).distance(&p2);\n```\nThe first one looks much cleaner. This automatic referencing behavior works\nbecause methods have a clear receiver—the type of `self`. Given the receiver\nand name of a method, Rust can figure out definitively whether the method is\nreading (`&self`), mutating (`&mut self`), or consuming (`self`). The fact\nthat Rust makes borrowing implicit for method receivers is a big part of\nmaking ownership ergonomic in practice.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Methods", "heading_path": ["Methods", "Where’s the `->` Operator?"], "path": "ch05-03-method-syntax.md", "url": "https://doc.rust-lang.org/book/ch05-03-method-syntax.html#wheres-the---operator", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch05-03-method-syntax.md#methods-with-more-parameters-6", "text": "The Rust Programming Language › Methods › Methods with More Parameters\n\nLet’s practice using methods by implementing a second method on the `Rectangle`\nstruct. This time we want an instance of `Rectangle` to take another instance\nof `Rectangle` and return `true` if the second `Rectangle` can fit completely\nwithin `self` (the first `Rectangle`); otherwise, it should return `false`.\nThat is, once we’ve defined the `can_hold` method, we want to be able to write\nthe program shown in Listing 5-14.\nListing 5-14: Using the as-yet-unwritten `can_hold` method (src/main.rs)\n```rust,ignore\nfn main() {\n let rect1 = Rectangle {\n width: 30,\n height: 50,\n };\n let rect2 = Rectangle {\n width: 10,\n height: 40,\n };\n let rect3 = Rectangle {\n width: 60,\n height: 45,\n };\n\n println!(\"Can rect1 hold rect2? {}\", rect1.can_hold(&rect2));\n println!(\"Can rect1 hold rect3? {}\", rect1.can_hold(&rect3));\n}\n```\nThe expected output would look like the following because both dimensions of\n`rect2` are smaller than the dimensions of `rect1`, but `rect3` is wider than\n`rect1`:\n```text\nCan rect1 hold rect2? true\nCan rect1 hold rect3? false\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Methods", "heading_path": ["Methods", "Methods with More Parameters"], "path": "ch05-03-method-syntax.md", "url": "https://doc.rust-lang.org/book/ch05-03-method-syntax.html#methods-with-more-parameters", "has_code": true, "code_tags": ["rust,ignore", "text"]}} {"id": "book/ch05-03-method-syntax.md#methods-with-more-parameters-7", "text": "The Rust Programming Language › Methods › Methods with More Parameters\n\nWe know we want to define a method, so it will be within the `impl Rectangle`\nblock. The method name will be `can_hold`, and it will take an immutable borrow\nof another `Rectangle` as a parameter. We can tell what the type of the\nparameter will be by looking at the code that calls the method:\n`rect1.can_hold(&rect2)` passes in `&rect2`, which is an immutable borrow to\n`rect2`, an instance of `Rectangle`. This makes sense because we only need to\nread `rect2` (rather than write, which would mean we’d need a mutable borrow),\nand we want `main` to retain ownership of `rect2` so that we can use it again\nafter calling the `can_hold` method. The return value of `can_hold` will be a\nBoolean, and the implementation will check whether the width and height of\n`self` are greater than the width and height of the other `Rectangle`,\nrespectively. Let’s add the new `can_hold` method to the `impl` block from\nListing 5-13, shown in Listing 5-15.\nListing 5-15: Implementing the `can_hold` method on `Rectangle` that takes another `Rectangle` instance as a parameter (src/main.rs)\n```rust\nimpl Rectangle {\n fn area(&self) -> u32 {\n self.width * self.height\n }\n\n fn can_hold(&self, other: &Rectangle) -> bool {\n self.width > other.width && self.height > other.height\n }\n}\n```\nWhen we run this code with the `main` function in Listing 5-14, we’ll get our\ndesired output. Methods can take multiple parameters that we add to the\nsignature after the `self` parameter, and those parameters work just like\nparameters in functions.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Methods", "heading_path": ["Methods", "Methods with More Parameters"], "path": "ch05-03-method-syntax.md", "url": "https://doc.rust-lang.org/book/ch05-03-method-syntax.html#methods-with-more-parameters", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch05-03-method-syntax.md#associated-functions-8", "text": "The Rust Programming Language › Methods › Associated Functions\n\nAll functions defined within an `impl` block are called _associated functions_\nbecause they’re associated with the type named after the `impl`. We can define\nassociated functions that don’t have `self` as their first parameter (and thus\nare not methods) because they don’t need an instance of the type to work with.\nWe’ve already used one function like this: the `String::from` function that’s\ndefined on the `String` type.\nAssociated functions that aren’t methods are often used for constructors that\nwill return a new instance of the struct. These are often called `new`, but\n`new` isn’t a special name and isn’t built into the language. For example, we\ncould choose to provide an associated function named `square` that would have\none dimension parameter and use that as both width and height, thus making it\neasier to create a square `Rectangle` rather than having to specify the same\nvalue twice:\nFilename: src/main.rs\n```rust\nimpl Rectangle {\n fn square(size: u32) -> Self {\n Self {\n width: size,\n height: size,\n }\n }\n}\n```\nThe `Self` keywords in the return type and in the body of the function are\naliases for the type that appears after the `impl` keyword, which in this case\nis `Rectangle`.\nTo call this associated function, we use the `::` syntax with the struct name;\n`let sq = Rectangle::square(3);` is an example. This function is namespaced by\nthe struct: The `::` syntax is used for both associated functions and\nnamespaces created by modules. We’ll discuss modules in Chapter\n7.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Methods", "heading_path": ["Methods", "Associated Functions"], "path": "ch05-03-method-syntax.md", "url": "https://doc.rust-lang.org/book/ch05-03-method-syntax.html#associated-functions", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch05-03-method-syntax.md#multiple-impl-blocks-9", "text": "The Rust Programming Language › Methods › Multiple `impl` Blocks\n\nEach struct is allowed to have multiple `impl` blocks. For example, Listing\n5-15 is equivalent to the code shown in Listing 5-16, which has each method in\nits own `impl` block.\nListing 5-16: Rewriting Listing 5-15 using multiple `impl` blocks\n```rust\nimpl Rectangle {\n fn area(&self) -> u32 {\n self.width * self.height\n }\n}\n\nimpl Rectangle {\n fn can_hold(&self, other: &Rectangle) -> bool {\n self.width > other.width && self.height > other.height\n }\n}\n```\nThere’s no reason to separate these methods into multiple `impl` blocks here,\nbut this is valid syntax. We’ll see a case in which multiple `impl` blocks are\nuseful in Chapter 10, where we discuss generic types and traits.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Methods", "heading_path": ["Methods", "Multiple `impl` Blocks"], "path": "ch05-03-method-syntax.md", "url": "https://doc.rust-lang.org/book/ch05-03-method-syntax.html#multiple-impl-blocks", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch05-03-method-syntax.md#summary-10", "text": "The Rust Programming Language › Summary\n\nStructs let you create custom types that are meaningful for your domain. By\nusing structs, you can keep associated pieces of data connected to each other\nand name each piece to make your code clear. In `impl` blocks, you can define\nfunctions that are associated with your type, and methods are a kind of\nassociated function that let you specify the behavior that instances of your\nstructs have.\nBut structs aren’t the only way you can create custom types: Let’s turn to\nRust’s enum feature to add another tool to your toolbox.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Methods", "heading_path": ["Summary"], "path": "ch05-03-method-syntax.md", "url": "https://doc.rust-lang.org/book/ch05-03-method-syntax.html#summary", "has_code": false, "code_tags": []}} {"id": "book/ch06-00-enums.md#enums-and-pattern-matching-0", "text": "The Rust Programming Language › Enums and Pattern Matching\n\nIn this chapter, we’ll look at enumerations, also referred to as _enums_.\nEnums allow you to define a type by enumerating its possible variants. First\nwe’ll define and use an enum to show how an enum can encode meaning along with\ndata. Next, we’ll explore a particularly useful enum, called `Option`, which\nexpresses that a value can be either something or nothing. Then, we’ll look at\nhow pattern matching in the `match` expression makes it easy to run different\ncode for different values of an enum. Finally, we’ll cover how the `if let`\nconstruct is another convenient and concise idiom available to handle enums in\nyour code.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Enums and Pattern Matching", "heading_path": ["Enums and Pattern Matching"], "path": "ch06-00-enums.md", "url": "https://doc.rust-lang.org/book/ch06-00-enums.html#enums-and-pattern-matching", "has_code": false, "code_tags": []}} {"id": "book/ch06-01-defining-an-enum.md#defining-an-enum-0", "text": "The Rust Programming Language › Defining an Enum\n\nWhere structs give you a way of grouping together related fields and data, like\na `Rectangle` with its `width` and `height`, enums give you a way of saying a\nvalue is one of a possible set of values. For example, we may want to say that\n`Rectangle` is one of a set of possible shapes that also includes `Circle` and\n`Triangle`. To do this, Rust allows us to encode these possibilities as an enum.\nLet’s look at a situation we might want to express in code and see why enums\nare useful and more appropriate than structs in this case. Say we need to work\nwith IP addresses. Currently, two major standards are used for IP addresses:\nversion four and version six. Because these are the only possibilities for an\nIP address that our program will come across, we can _enumerate_ all possible\nvariants, which is where enumeration gets its name.\nAny IP address can be either a version four or a version six address, but not\nboth at the same time. That property of IP addresses makes the enum data\nstructure appropriate because an enum value can only be one of its variants.\nBoth version four and version six addresses are still fundamentally IP\naddresses, so they should be treated as the same type when the code is handling\nsituations that apply to any kind of IP address.\nWe can express this concept in code by defining an `IpAddrKind` enumeration and\nlisting the possible kinds an IP address can be, `V4` and `V6`. These are the\nvariants of the enum:\n```rust\nenum IpAddrKind {\n V4,\n V6,\n}\n```\n`IpAddrKind` is now a custom data type that we can use elsewhere in our code.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining an Enum", "heading_path": ["Defining an Enum"], "path": "ch06-01-defining-an-enum.md", "url": "https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html#defining-an-enum", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch06-01-defining-an-enum.md#enum-values-1", "text": "The Rust Programming Language › Defining an Enum › Enum Values\n\nWe can create instances of each of the two variants of `IpAddrKind` like this:\n```rust\n let four = IpAddrKind::V4;\n let six = IpAddrKind::V6;\n```\nNote that the variants of the enum are namespaced under its identifier, and we\nuse a double colon to separate the two. This is useful because now both values\n`IpAddrKind::V4` and `IpAddrKind::V6` are of the same type: `IpAddrKind`. We\ncan then, for instance, define a function that takes any `IpAddrKind`:\n```rust\nfn route(ip_kind: IpAddrKind) {}\n```\nAnd we can call this function with either variant:\n```rust\n route(IpAddrKind::V4);\n route(IpAddrKind::V6);\n```\nUsing enums has even more advantages. Thinking more about our IP address type,\nat the moment we don’t have a way to store the actual IP address _data_; we\nonly know what _kind_ it is. Given that you just learned about structs in\nChapter 5, you might be tempted to tackle this problem with structs as shown in\nListing 6-1.\nListing 6-1: Storing the data and `IpAddrKind` variant of an IP address using a `struct`\n```rust\n enum IpAddrKind {\n V4,\n V6,\n }\n\n struct IpAddr {\n kind: IpAddrKind,\n address: String,\n }\n\n let home = IpAddr {\n kind: IpAddrKind::V4,\n address: String::from(\"127.0.0.1\"),\n };\n\n let loopback = IpAddr {\n kind: IpAddrKind::V6,\n address: String::from(\"::1\"),\n };\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining an Enum", "heading_path": ["Defining an Enum", "Enum Values"], "path": "ch06-01-defining-an-enum.md", "url": "https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html#enum-values", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch06-01-defining-an-enum.md#enum-values-2", "text": "The Rust Programming Language › Defining an Enum › Enum Values\n\nHere, we’ve defined a struct `IpAddr` that has two fields: a `kind` field that\nis of type `IpAddrKind` (the enum we defined previously) and an `address` field\nof type `String`. We have two instances of this struct. The first is `home`,\nand it has the value `IpAddrKind::V4` as its `kind` with associated address\ndata of `127.0.0.1`. The second instance is `loopback`. It has the other\nvariant of `IpAddrKind` as its `kind` value, `V6`, and has address `::1`\nassociated with it. We’ve used a struct to bundle the `kind` and `address`\nvalues together, so now the variant is associated with the value.\nHowever, representing the same concept using just an enum is more concise:\nRather than an enum inside a struct, we can put data directly into each enum\nvariant. This new definition of the `IpAddr` enum says that both `V4` and `V6`\nvariants will have associated `String` values:\n```rust\n enum IpAddr {\n V4(String),\n V6(String),\n }\n\n let home = IpAddr::V4(String::from(\"127.0.0.1\"));\n\n let loopback = IpAddr::V6(String::from(\"::1\"));\n```\nWe attach data to each variant of the enum directly, so there is no need for an\nextra struct. Here, it’s also easier to see another detail of how enums work:\nThe name of each enum variant that we define also becomes a function that\nconstructs an instance of the enum. That is, `IpAddr::V4()` is a function call\nthat takes a `String` argument and returns an instance of the `IpAddr` type. We\nautomatically get this constructor function defined as a result of defining the\nenum.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining an Enum", "heading_path": ["Defining an Enum", "Enum Values"], "path": "ch06-01-defining-an-enum.md", "url": "https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html#enum-values", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch06-01-defining-an-enum.md#enum-values-3", "text": "The Rust Programming Language › Defining an Enum › Enum Values\n\nThere’s another advantage to using an enum rather than a struct: Each variant\ncan have different types and amounts of associated data. Version four IP\naddresses will always have four numeric components that will have values\nbetween 0 and 255. If we wanted to store `V4` addresses as four `u8` values but\nstill express `V6` addresses as one `String` value, we wouldn’t be able to with\na struct. Enums handle this case with ease:\n```rust\n enum IpAddr {\n V4(u8, u8, u8, u8),\n V6(String),\n }\n\n let home = IpAddr::V4(127, 0, 0, 1);\n\n let loopback = IpAddr::V6(String::from(\"::1\"));\n```\nWe’ve shown several different ways to define data structures to store version\nfour and version six IP addresses. However, as it turns out, wanting to store\nIP addresses and encode which kind they are is so common that the standard\nlibrary has a definition we can use! Let’s look at how\nthe standard library defines `IpAddr`. It has the exact enum and variants that\nwe’ve defined and used, but it embeds the address data inside the variants in\nthe form of two different structs, which are defined differently for each\nvariant:\n```rust\nstruct Ipv4Addr {\n // --snip--\n}\n\nstruct Ipv6Addr {\n // --snip--\n}\n\nenum IpAddr {\n V4(Ipv4Addr),\n V6(Ipv6Addr),\n}\n```\nThis code illustrates that you can put any kind of data inside an enum variant:\nstrings, numeric types, or structs, for example. You can even include another\nenum! Also, standard library types are often not much more complicated than\nwhat you might come up with.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining an Enum", "heading_path": ["Defining an Enum", "Enum Values"], "path": "ch06-01-defining-an-enum.md", "url": "https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html#enum-values", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch06-01-defining-an-enum.md#enum-values-4", "text": "The Rust Programming Language › Defining an Enum › Enum Values\n\nNote that even though the standard library contains a definition for `IpAddr`,\nwe can still create and use our own definition without conflict because we\nhaven’t brought the standard library’s definition into our scope. We’ll talk\nmore about bringing types into scope in Chapter 7.\nLet’s look at another example of an enum in Listing 6-2: This one has a wide\nvariety of types embedded in its variants.\nListing 6-2: A `Message` enum whose variants each store different amounts and types of values\n```rust\nenum Message {\n Quit,\n Move { x: i32, y: i32 },\n Write(String),\n ChangeColor(i32, i32, i32),\n}\n```\nThis enum has four variants with different types:\n- `Quit`: Has no data associated with it at all\n- `Move`: Has named fields, like a struct does\n- `Write`: Includes a single `String`\n- `ChangeColor`: Includes three `i32` values\nDefining an enum with variants such as the ones in Listing 6-2 is similar to\ndefining different kinds of struct definitions, except the enum doesn’t use the\n`struct` keyword and all the variants are grouped together under the `Message`\ntype. The following structs could hold the same data that the preceding enum\nvariants hold:\n```rust\nstruct QuitMessage; // unit struct\nstruct MoveMessage {\n x: i32,\n y: i32,\n}\nstruct WriteMessage(String); // tuple struct\nstruct ChangeColorMessage(i32, i32, i32); // tuple struct\n```\nBut if we used the different structs, each of which has its own type, we\ncouldn’t as easily define a function to take any of these kinds of messages as\nwe could with the `Message` enum defined in Listing 6-2, which is a single type.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining an Enum", "heading_path": ["Defining an Enum", "Enum Values"], "path": "ch06-01-defining-an-enum.md", "url": "https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html#enum-values", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch06-01-defining-an-enum.md#enum-values-5", "text": "The Rust Programming Language › Defining an Enum › Enum Values\n\nThere is one more similarity between enums and structs: Just as we’re able to\ndefine methods on structs using `impl`, we’re also able to define methods on\nenums. Here’s a method named `call` that we could define on our `Message` enum:\n```rust\n impl Message {\n fn call(&self) {\n // method body would be defined here\n }\n }\n\n let m = Message::Write(String::from(\"hello\"));\n m.call();\n```\nThe body of the method would use `self` to get the value that we called the\nmethod on. In this example, we’ve created a variable `m` that has the value\n`Message::Write(String::from(\"hello\"))`, and that is what `self` will be in the\nbody of the `call` method when `m.call()` runs.\nLet’s look at another enum in the standard library that is very common and\nuseful: `Option`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining an Enum", "heading_path": ["Defining an Enum", "Enum Values"], "path": "ch06-01-defining-an-enum.md", "url": "https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html#enum-values", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch06-01-defining-an-enum.md#the-option-enum-6", "text": "The Rust Programming Language › Defining an Enum › The `Option` Enum\n\nThis section explores a case study of `Option`, which is another enum defined\nby the standard library. The `Option` type encodes the very common scenario in\nwhich a value could be something, or it could be nothing.\nFor example, if you request the first item in a non-empty list, you would get\na value. If you request the first item in an empty list, you would get nothing.\nExpressing this concept in terms of the type system means the compiler can\ncheck whether you’ve handled all the cases you should be handling; this\nfunctionality can prevent bugs that are extremely common in other programming\nlanguages.\nProgramming language design is often thought of in terms of which features you\ninclude, but the features you exclude are important too. Rust doesn’t have the\nnull feature that many other languages have. _Null_ is a value that means there\nis no value there. In languages with null, variables can always be in one of\ntwo states: null or not-null.\nIn his 2009 presentation “Null References: The Billion Dollar Mistake,” Tony\nHoare, the inventor of null, had this to say:\nI call it my billion-dollar mistake. At that time, I was designing the first\ncomprehensive type system for references in an object-oriented language. My\ngoal was to ensure that all use of references should be absolutely safe, with\nchecking performed automatically by the compiler. But I couldn’t resist the\ntemptation to put in a null reference, simply because it was so easy to\nimplement. This has led to innumerable errors, vulnerabilities, and system\ncrashes, which have probably caused a billion dollars of pain and damage in\nthe last forty years.\nThe problem with null values is that if you try to use a null value as a\nnot-null value, you’ll get an error of some kind. Because this null or not-null\nproperty is pervasive, it’s extremely easy to make this kind of error.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining an Enum", "heading_path": ["Defining an Enum", "The `Option` Enum"], "path": "ch06-01-defining-an-enum.md", "url": "https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html#the-option-enum", "has_code": false, "code_tags": []}} {"id": "book/ch06-01-defining-an-enum.md#the-option-enum-7", "text": "The Rust Programming Language › Defining an Enum › The `Option` Enum\n\nHowever, the concept that null is trying to express is still a useful one: A\nnull is a value that is currently invalid or absent for some reason.\nThe problem isn’t really with the concept but with the particular\nimplementation. As such, Rust does not have nulls, but it does have an enum\nthat can encode the concept of a value being present or absent. This enum is\n`Option`, and it is defined by the standard library\nas follows:\n```rust\nenum Option {\n None,\n Some(T),\n}\n```\nThe `Option` enum is so useful that it’s even included in the prelude; you\ndon’t need to bring it into scope explicitly. Its variants are also included in\nthe prelude: You can use `Some` and `None` directly without the `Option::`\nprefix. The `Option` enum is still just a regular enum, and `Some(T)` and\n`None` are still variants of type `Option`.\nThe `` syntax is a feature of Rust we haven’t talked about yet. It’s a\ngeneric type parameter, and we’ll cover generics in more detail in Chapter 10.\nFor now, all you need to know is that `` means that the `Some` variant of\nthe `Option` enum can hold one piece of data of any type, and that each\nconcrete type that gets used in place of `T` makes the overall `Option` type\na different type. Here are some examples of using `Option` values to hold\nnumber types and char types:\n```rust\n let some_number = Some(5);\n let some_char = Some('e');\n\n let absent_number: Option = None;\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining an Enum", "heading_path": ["Defining an Enum", "The `Option` Enum"], "path": "ch06-01-defining-an-enum.md", "url": "https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html#the-option-enum", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch06-01-defining-an-enum.md#the-option-enum-8", "text": "The Rust Programming Language › Defining an Enum › The `Option` Enum\n\nThe type of `some_number` is `Option`. The type of `some_char` is\n`Option`, which is a different type. Rust can infer these types because\nwe’ve specified a value inside the `Some` variant. For `absent_number`, Rust\nrequires us to annotate the overall `Option` type: The compiler can’t infer the\ntype that the corresponding `Some` variant will hold by looking only at a\n`None` value. Here, we tell Rust that we mean for `absent_number` to be of type\n`Option`.\nWhen we have a `Some` value, we know that a value is present, and the value is\nheld within the `Some`. When we have a `None` value, in some sense it means the\nsame thing as null: We don’t have a valid value. So, why is having `Option`\nany better than having null?\nIn short, because `Option` and `T` (where `T` can be any type) are different\ntypes, the compiler won’t let us use an `Option` value as if it were\ndefinitely a valid value. For example, this code won’t compile, because it’s\ntrying to add an `i8` to an `Option`:\n```rust,ignore,does_not_compile\n let x: i8 = 5;\n let y: Option = Some(5);\n\n let sum = x + y;\n```\nIf we run this code, we get an error message like this one:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining an Enum", "heading_path": ["Defining an Enum", "The `Option` Enum"], "path": "ch06-01-defining-an-enum.md", "url": "https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html#the-option-enum", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch06-01-defining-an-enum.md#the-option-enum-9", "text": "The Rust Programming Language › Defining an Enum › The `Option` Enum\n\n```console\n$ cargo run\n Compiling enums v0.1.0 (file:///projects/enums)\nerror[E0277]: cannot add `Option` to `i8`\n --> src/main.rs:5:17\n |\n5 | let sum = x + y;\n | ^ no implementation for `i8 + Option`\n |\n = help: the trait `Add>` is not implemented for `i8`\nhelp: the following other types implement trait `Add`\n --> /rustc/2d8144b7880597b6e6d3dfd63a9a9efae3f533d3/library/core/src/ops/arith.rs:98:8\n |\n = note: `i8` implements `Add`\n ::: /rustc/2d8144b7880597b6e6d3dfd63a9a9efae3f533d3/library/core/src/ops/arith.rs:113:0\n |\n = note: in this macro invocation\n --> /rustc/2d8144b7880597b6e6d3dfd63a9a9efae3f533d3/library/core/src/internal_macros.rs:22:8\n |\n = note: `&i8` implements `Add`\n ::: /rustc/2d8144b7880597b6e6d3dfd63a9a9efae3f533d3/library/core/src/internal_macros.rs:33:8\n |\n = note: `i8` implements `Add<&i8>`\n ::: /rustc/2d8144b7880597b6e6d3dfd63a9a9efae3f533d3/library/core/src/internal_macros.rs:44:8\n |\n = note: `&i8` implements `Add`\n = note: this error originates in the macro `add_impl` (in Nightly builds, run with -Z macro-backtrace for more info)\n\nFor more information about this error, try `rustc --explain E0277`.\nerror: could not compile `enums` (bin \"enums\") due to 1 previous error\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining an Enum", "heading_path": ["Defining an Enum", "The `Option` Enum"], "path": "ch06-01-defining-an-enum.md", "url": "https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html#the-option-enum", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch06-01-defining-an-enum.md#the-option-enum-10", "text": "The Rust Programming Language › Defining an Enum › The `Option` Enum\n\nIntense! In effect, this error message means that Rust doesn’t understand how\nto add an `i8` and an `Option`, because they’re different types. When we\nhave a value of a type like `i8` in Rust, the compiler will ensure that we\nalways have a valid value. We can proceed confidently without having to check\nfor null before using that value. Only when we have an `Option` (or\nwhatever type of value we’re working with) do we have to worry about possibly\nnot having a value, and the compiler will make sure we handle that case before\nusing the value.\nIn other words, you have to convert an `Option` to a `T` before you can\nperform `T` operations with it. Generally, this helps catch one of the most\ncommon issues with null: assuming that something isn’t null when it actually is.\nEliminating the risk of incorrectly assuming a not-null value helps you be more\nconfident in your code. In order to have a value that can possibly be null, you\nmust explicitly opt in by making the type of that value `Option`. Then, when\nyou use that value, you are required to explicitly handle the case when the\nvalue is null. Everywhere that a value has a type that isn’t an `Option`,\nyou _can_ safely assume that the value isn’t null. This was a deliberate design\ndecision for Rust to limit null’s pervasiveness and increase the safety of Rust\ncode.\nSo how do you get the `T` value out of a `Some` variant when you have a value\nof type `Option` so that you can use that value? The `Option` enum has a\nlarge number of methods that are useful in a variety of situations; you can\ncheck them out in its documentation. Becoming familiar\nwith the methods on `Option` will be extremely useful in your journey with\nRust.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining an Enum", "heading_path": ["Defining an Enum", "The `Option` Enum"], "path": "ch06-01-defining-an-enum.md", "url": "https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html#the-option-enum", "has_code": false, "code_tags": []}} {"id": "book/ch06-01-defining-an-enum.md#the-option-enum-11", "text": "The Rust Programming Language › Defining an Enum › The `Option` Enum\n\nIn general, in order to use an `Option` value, you want to have code that\nwill handle each variant. You want some code that will run only when you have a\n`Some(T)` value, and this code is allowed to use the inner `T`. You want some\nother code to run only if you have a `None` value, and that code doesn’t have a\n`T` value available. The `match` expression is a control flow construct that\ndoes just this when used with enums: It will run different code depending on\nwhich variant of the enum it has, and that code can use the data inside the\nmatching value.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining an Enum", "heading_path": ["Defining an Enum", "The `Option` Enum"], "path": "ch06-01-defining-an-enum.md", "url": "https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html#the-option-enum", "has_code": false, "code_tags": []}} {"id": "book/ch06-02-match.md#the-match-control-flow-construct-0", "text": "The Rust Programming Language › The `match` Control Flow Construct\n\nRust has an extremely powerful control flow construct called `match` that\nallows you to compare a value against a series of patterns and then execute\ncode based on which pattern matches. Patterns can be made up of literal values,\nvariable names, wildcards, and many other things; Chapter\n19 covers all the different kinds of patterns\nand what they do. The power of `match` comes from the expressiveness of the\npatterns and the fact that the compiler confirms that all possible cases are\nhandled.\nThink of a `match` expression as being like a coin-sorting machine: Coins slide\ndown a track with variously sized holes along it, and each coin falls through\nthe first hole it encounters that it fits into. In the same way, values go\nthrough each pattern in a `match`, and at the first pattern the value “fits,”\nthe value falls into the associated code block to be used during execution.\nSpeaking of coins, let’s use them as an example using `match`! We can write a\nfunction that takes an unknown US coin and, in a similar way as the counting\nmachine, determines which coin it is and returns its value in cents, as shown\nin Listing 6-3.\nListing 6-3: An enum and a `match` expression that has the variants of the enum as its patterns\n```rust\nenum Coin {\n Penny,\n Nickel,\n Dime,\n Quarter,\n}\n\nfn value_in_cents(coin: Coin) -> u8 {\n match coin {\n Coin::Penny => 1,\n Coin::Nickel => 5,\n Coin::Dime => 10,\n Coin::Quarter => 25,\n }\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "The `match` Control Flow Construct", "heading_path": ["The `match` Control Flow Construct"], "path": "ch06-02-match.md", "url": "https://doc.rust-lang.org/book/ch06-02-match.html#the-match-control-flow-construct", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch06-02-match.md#the-match-control-flow-construct-1", "text": "The Rust Programming Language › The `match` Control Flow Construct\n\nLet’s break down the `match` in the `value_in_cents` function. First, we list\nthe `match` keyword followed by an expression, which in this case is the value\n`coin`. This seems very similar to a conditional expression used with `if`, but\nthere’s a big difference: With `if`, the condition needs to evaluate to a\nBoolean value, but here it can be any type. The type of `coin` in this example\nis the `Coin` enum that we defined on the first line.\nNext are the `match` arms. An arm has two parts: a pattern and some code. The\nfirst arm here has a pattern that is the value `Coin::Penny` and then the `=>`\noperator that separates the pattern and the code to run. The code in this case\nis just the value `1`. Each arm is separated from the next with a comma.\nWhen the `match` expression executes, it compares the resultant value against\nthe pattern of each arm, in order. If a pattern matches the value, the code\nassociated with that pattern is executed. If that pattern doesn’t match the\nvalue, execution continues to the next arm, much as in a coin-sorting machine.\nWe can have as many arms as we need: In Listing 6-3, our `match` has four arms.\nThe code associated with each arm is an expression, and the resultant value of\nthe expression in the matching arm is the value that gets returned for the\nentire `match` expression.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "The `match` Control Flow Construct", "heading_path": ["The `match` Control Flow Construct"], "path": "ch06-02-match.md", "url": "https://doc.rust-lang.org/book/ch06-02-match.html#the-match-control-flow-construct", "has_code": false, "code_tags": []}} {"id": "book/ch06-02-match.md#the-match-control-flow-construct-2", "text": "The Rust Programming Language › The `match` Control Flow Construct\n\nWe don’t typically use curly brackets if the match arm code is short, as it is\nin Listing 6-3 where each arm just returns a value. If you want to run multiple\nlines of code in a match arm, you must use curly brackets, and the comma\nfollowing the arm is then optional. For example, the following code prints\n“Lucky penny!” every time the method is called with a `Coin::Penny`, but it\nstill returns the last value of the block, `1`:\n```rust\nfn value_in_cents(coin: Coin) -> u8 {\n match coin {\n Coin::Penny => {\n println!(\"Lucky penny!\");\n 1\n }\n Coin::Nickel => 5,\n Coin::Dime => 10,\n Coin::Quarter => 25,\n }\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "The `match` Control Flow Construct", "heading_path": ["The `match` Control Flow Construct"], "path": "ch06-02-match.md", "url": "https://doc.rust-lang.org/book/ch06-02-match.html#the-match-control-flow-construct", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch06-02-match.md#patterns-that-bind-to-values-3", "text": "The Rust Programming Language › The `match` Control Flow Construct › Patterns That Bind to Values\n\nAnother useful feature of match arms is that they can bind to the parts of the\nvalues that match the pattern. This is how we can extract values out of enum\nvariants.\nAs an example, let’s change one of our enum variants to hold data inside it.\nFrom 1999 through 2008, the United States minted quarters with different\ndesigns for each of the 50 states on one side. No other coins got state\ndesigns, so only quarters have this extra value. We can add this information to\nour `enum` by changing the `Quarter` variant to include a `UsState` value\nstored inside it, which we’ve done in Listing 6-4.\nListing 6-4: A `Coin` enum in which the `Quarter` variant also holds a `UsState` value\n```rust\n#[derive(Debug)] // so we can inspect the state in a minute\nenum UsState {\n Alabama,\n Alaska,\n // --snip--\n}\n\nenum Coin {\n Penny,\n Nickel,\n Dime,\n Quarter(UsState),\n}\n```\nLet’s imagine that a friend is trying to collect all 50 state quarters. While\nwe sort our loose change by coin type, we’ll also call out the name of the\nstate associated with each quarter so that if it’s one our friend doesn’t have,\nthey can add it to their collection.\nIn the match expression for this code, we add a variable called `state` to the\npattern that matches values of the variant `Coin::Quarter`. When a\n`Coin::Quarter` matches, the `state` variable will bind to the value of that\nquarter’s state. Then, we can use `state` in the code for that arm, like so:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "The `match` Control Flow Construct", "heading_path": ["The `match` Control Flow Construct", "Patterns That Bind to Values"], "path": "ch06-02-match.md", "url": "https://doc.rust-lang.org/book/ch06-02-match.html#patterns-that-bind-to-values", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch06-02-match.md#patterns-that-bind-to-values-4", "text": "The Rust Programming Language › The `match` Control Flow Construct › Patterns That Bind to Values\n\n```rust\nfn value_in_cents(coin: Coin) -> u8 {\n match coin {\n Coin::Penny => 1,\n Coin::Nickel => 5,\n Coin::Dime => 10,\n Coin::Quarter(state) => {\n println!(\"State quarter from {state:?}!\");\n 25\n }\n }\n}\n```\nIf we were to call `value_in_cents(Coin::Quarter(UsState::Alaska))`, `coin`\nwould be `Coin::Quarter(UsState::Alaska)`. When we compare that value with each\nof the match arms, none of them match until we reach `Coin::Quarter(state)`. At\nthat point, the binding for `state` will be the value `UsState::Alaska`. We can\nthen use that binding in the `println!` expression, thus getting the inner\nstate value out of the `Coin` enum variant for `Quarter`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "The `match` Control Flow Construct", "heading_path": ["The `match` Control Flow Construct", "Patterns That Bind to Values"], "path": "ch06-02-match.md", "url": "https://doc.rust-lang.org/book/ch06-02-match.html#patterns-that-bind-to-values", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch06-02-match.md#the-optiont-match-pattern-5", "text": "The Rust Programming Language › The `match` Control Flow Construct › The `Option` `match` Pattern\n\nIn the previous section, we wanted to get the inner `T` value out of the `Some`\ncase when using `Option`; we can also handle `Option` using `match`, as\nwe did with the `Coin` enum! Instead of comparing coins, we’ll compare the\nvariants of `Option`, but the way the `match` expression works remains the\nsame.\nLet’s say we want to write a function that takes an `Option` and, if\nthere’s a value inside, adds 1 to that value. If there isn’t a value inside,\nthe function should return the `None` value and not attempt to perform any\noperations.\nThis function is very easy to write, thanks to `match`, and will look like\nListing 6-5.\nListing 6-5\n```rust\n fn plus_one(x: Option) -> Option {\n match x {\n None => None,\n Some(i) => Some(i + 1),\n }\n }\n\n let five = Some(5);\n let six = plus_one(five);\n let none = plus_one(None);\n```\nLet’s examine the first execution of `plus_one` in more detail. When we call\n`plus_one(five)`, the variable `x` in the body of `plus_one` will have the\nvalue `Some(5)`. We then compare that against each match arm:\n```rust,ignore\n None => None,\n```\nThe `Some(5)` value doesn’t match the pattern `None`, so we continue to the\nnext arm:\n```rust,ignore\n Some(i) => Some(i + 1),\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "The `match` Control Flow Construct", "heading_path": ["The `match` Control Flow Construct", "The `Option` `match` Pattern"], "path": "ch06-02-match.md", "url": "https://doc.rust-lang.org/book/ch06-02-match.html#the-optiont-match-pattern", "has_code": true, "code_tags": ["rust", "rust,ignore"]}} {"id": "book/ch06-02-match.md#the-optiont-match-pattern-6", "text": "The Rust Programming Language › The `match` Control Flow Construct › The `Option` `match` Pattern\n\nDoes `Some(5)` match `Some(i)`? It does! We have the same variant. The `i`\nbinds to the value contained in `Some`, so `i` takes the value `5`. The code in\nthe match arm is then executed, so we add 1 to the value of `i` and create a\nnew `Some` value with our total `6` inside.\nNow let’s consider the second call of `plus_one` in Listing 6-5, where `x` is\n`None`. We enter the `match` and compare to the first arm:\n```rust,ignore\n None => None,\n```\nIt matches! There’s no value to add to, so the program stops and returns the\n`None` value on the right side of `=>`. Because the first arm matched, no other\narms are compared.\nCombining `match` and enums is useful in many situations. You’ll see this\npattern a lot in Rust code: `match` against an enum, bind a variable to the\ndata inside, and then execute code based on it. It’s a bit tricky at first, but\nonce you get used to it, you’ll wish you had it in all languages. It’s\nconsistently a user favorite.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "The `match` Control Flow Construct", "heading_path": ["The `match` Control Flow Construct", "The `Option` `match` Pattern"], "path": "ch06-02-match.md", "url": "https://doc.rust-lang.org/book/ch06-02-match.html#the-optiont-match-pattern", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch06-02-match.md#matches-are-exhaustive-7", "text": "The Rust Programming Language › The `match` Control Flow Construct › Matches Are Exhaustive\n\nThere’s one other aspect of `match` we need to discuss: The arms’ patterns must\ncover all possibilities. Consider this version of our `plus_one` function,\nwhich has a bug and won’t compile:\n```rust,ignore,does_not_compile\n fn plus_one(x: Option) -> Option {\n match x {\n Some(i) => Some(i + 1),\n }\n }\n```\nWe didn’t handle the `None` case, so this code will cause a bug. Luckily, it’s\na bug Rust knows how to catch. If we try to compile this code, we’ll get this\nerror:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "The `match` Control Flow Construct", "heading_path": ["The `match` Control Flow Construct", "Matches Are Exhaustive"], "path": "ch06-02-match.md", "url": "https://doc.rust-lang.org/book/ch06-02-match.html#matches-are-exhaustive", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch06-02-match.md#matches-are-exhaustive-8", "text": "The Rust Programming Language › The `match` Control Flow Construct › Matches Are Exhaustive\n\n```console\n$ cargo run\n Compiling enums v0.1.0 (file:///projects/enums)\nerror[E0004]: non-exhaustive patterns: `None` not covered\n --> src/main.rs:3:15\n |\n3 | match x {\n | ^ pattern `None` not covered\n |\nnote: `Option` defined here\n --> /rustc/2d8144b7880597b6e6d3dfd63a9a9efae3f533d3/library/core/src/option.rs:597:0\n ::: /rustc/2d8144b7880597b6e6d3dfd63a9a9efae3f533d3/library/core/src/option.rs:601:4\n |\n = note: not covered\n = note: the matched value is of type `Option`\nhelp: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown\n |\n4 ~ Some(i) => Some(i + 1),\n5 ~ None => todo!(),\n |\n\nFor more information about this error, try `rustc --explain E0004`.\nerror: could not compile `enums` (bin \"enums\") due to 1 previous error\n```\nRust knows that we didn’t cover every possible case and even knows which\npattern we forgot! Matches in Rust are _exhaustive_: We must exhaust every last\npossibility in order for the code to be valid. Especially in the case of\n`Option`, when Rust prevents us from forgetting to explicitly handle the\n`None` case, it protects us from assuming that we have a value when we might\nhave null, thus making the billion-dollar mistake discussed earlier impossible.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "The `match` Control Flow Construct", "heading_path": ["The `match` Control Flow Construct", "Matches Are Exhaustive"], "path": "ch06-02-match.md", "url": "https://doc.rust-lang.org/book/ch06-02-match.html#matches-are-exhaustive", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch06-02-match.md#catch-all-patterns-and-the-_-placeholder-9", "text": "The Rust Programming Language › The `match` Control Flow Construct › Catch-All Patterns and the `_` Placeholder\n\nUsing enums, we can also take special actions for a few particular values, but\nfor all other values take one default action. Imagine we’re implementing a game\nwhere, if you roll a 3 on a dice roll, your player doesn’t move but instead\ngets a fancy new hat. If you roll a 7, your player loses a fancy hat. For all\nother values, your player moves that number of spaces on the game board. Here’s\na `match` that implements that logic, with the result of the dice roll\nhardcoded rather than a random value, and all other logic represented by\nfunctions without bodies because actually implementing them is out of scope for\nthis example:\n```rust\n let dice_roll = 9;\n match dice_roll {\n 3 => add_fancy_hat(),\n 7 => remove_fancy_hat(),\n other => move_player(other),\n }\n\n fn add_fancy_hat() {}\n fn remove_fancy_hat() {}\n fn move_player(num_spaces: u8) {}\n```\nFor the first two arms, the patterns are the literal values `3` and `7`. For\nthe last arm that covers every other possible value, the pattern is the\nvariable we’ve chosen to name `other`. The code that runs for the `other` arm\nuses the variable by passing it to the `move_player` function.\nThis code compiles, even though we haven’t listed all the possible values a\n`u8` can have, because the last pattern will match all values not specifically\nlisted. This catch-all pattern meets the requirement that `match` must be\nexhaustive. Note that we have to put the catch-all arm last because the\npatterns are evaluated in order. If we had put the catch-all arm earlier, the\nother arms would never run, so Rust will warn us if we add arms after a\ncatch-all!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "The `match` Control Flow Construct", "heading_path": ["The `match` Control Flow Construct", "Catch-All Patterns and the `_` Placeholder"], "path": "ch06-02-match.md", "url": "https://doc.rust-lang.org/book/ch06-02-match.html#catch-all-patterns-and-the-_-placeholder", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch06-02-match.md#catch-all-patterns-and-the-_-placeholder-10", "text": "The Rust Programming Language › The `match` Control Flow Construct › Catch-All Patterns and the `_` Placeholder\n\nRust also has a pattern we can use when we want a catch-all but don’t want to\n_use_ the value in the catch-all pattern: `_` is a special pattern that matches\nany value and does not bind to that value. This tells Rust we aren’t going to\nuse the value, so Rust won’t warn us about an unused variable.\nLet’s change the rules of the game: Now, if you roll anything other than a 3 or\na 7, you must roll again. We no longer need to use the catch-all value, so we\ncan change our code to use `_` instead of the variable named `other`:\n```rust\n let dice_roll = 9;\n match dice_roll {\n 3 => add_fancy_hat(),\n 7 => remove_fancy_hat(),\n _ => reroll(),\n }\n\n fn add_fancy_hat() {}\n fn remove_fancy_hat() {}\n fn reroll() {}\n```\nThis example also meets the exhaustiveness requirement because we’re explicitly\nignoring all other values in the last arm; we haven’t forgotten anything.\nFinally, we’ll change the rules of the game one more time so that nothing else\nhappens on your turn if you roll anything other than a 3 or a 7. We can express\nthat by using the unit value (the empty tuple type we mentioned in “The Tuple\nType” section) as the code that goes with the `_` arm:\n```rust\n let dice_roll = 9;\n match dice_roll {\n 3 => add_fancy_hat(),\n 7 => remove_fancy_hat(),\n _ => (),\n }\n\n fn add_fancy_hat() {}\n fn remove_fancy_hat() {}\n```\nHere, we’re telling Rust explicitly that we aren’t going to use any other value\nthat doesn’t match a pattern in an earlier arm, and we don’t want to run any\ncode in this case.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "The `match` Control Flow Construct", "heading_path": ["The `match` Control Flow Construct", "Catch-All Patterns and the `_` Placeholder"], "path": "ch06-02-match.md", "url": "https://doc.rust-lang.org/book/ch06-02-match.html#catch-all-patterns-and-the-_-placeholder", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch06-02-match.md#catch-all-patterns-and-the-_-placeholder-11", "text": "The Rust Programming Language › The `match` Control Flow Construct › Catch-All Patterns and the `_` Placeholder\n\nThere’s more about patterns and matching that we’ll cover in Chapter\n19. For now, we’re going to move on to the\n`if let` syntax, which can be useful in situations where the `match` expression\nis a bit wordy.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "The `match` Control Flow Construct", "heading_path": ["The `match` Control Flow Construct", "Catch-All Patterns and the `_` Placeholder"], "path": "ch06-02-match.md", "url": "https://doc.rust-lang.org/book/ch06-02-match.html#catch-all-patterns-and-the-_-placeholder", "has_code": false, "code_tags": []}} {"id": "book/ch06-03-if-let.md#concise-control-flow-with-if-let-and-letelse-0", "text": "The Rust Programming Language › Concise Control Flow with `if let` and `let...else`\n\nThe `if let` syntax lets you combine `if` and `let` into a less verbose way to\nhandle values that match one pattern while ignoring the rest. Consider the\nprogram in Listing 6-6 that matches on an `Option` value in the\n`config_max` variable but only wants to execute code if the value is the `Some`\nvariant.\nListing 6-6: A `match` that only cares about executing code when the value is `Some`\n```rust\n let config_max = Some(3u8);\n match config_max {\n Some(max) => println!(\"The maximum is configured to be {max}\"),\n _ => (),\n }\n```\nIf the value is `Some`, we print out the value in the `Some` variant by binding\nthe value to the variable `max` in the pattern. We don’t want to do anything\nwith the `None` value. To satisfy the `match` expression, we have to add `_ =>\n()` after processing just one variant, which is annoying boilerplate code to\nadd.\nInstead, we could write this in a shorter way using `if let`. The following\ncode behaves the same as the `match` in Listing 6-6:\n```rust\n let config_max = Some(3u8);\n if let Some(max) = config_max {\n println!(\"The maximum is configured to be {max}\");\n }\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Concise Control Flow with `if let` and `let...else`", "heading_path": ["Concise Control Flow with `if let` and `let...else`"], "path": "ch06-03-if-let.md", "url": "https://doc.rust-lang.org/book/ch06-03-if-let.html#concise-control-flow-with-if-let-and-letelse", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch06-03-if-let.md#concise-control-flow-with-if-let-and-letelse-1", "text": "The Rust Programming Language › Concise Control Flow with `if let` and `let...else`\n\nThe syntax `if let` takes a pattern and an expression separated by an equal\nsign. It works the same way as a `match`, where the expression is given to the\n`match` and the pattern is its first arm. In this case, the pattern is\n`Some(max)`, and the `max` binds to the value inside the `Some`. We can then\nuse `max` in the body of the `if let` block in the same way we used `max` in\nthe corresponding `match` arm. The code in the `if let` block only runs if the\nvalue matches the pattern.\nUsing `if let` means less typing, less indentation, and less boilerplate code.\nHowever, you lose the exhaustive checking `match` enforces that ensures that\nyou aren’t forgetting to handle any cases. Choosing between `match` and `if\nlet` depends on what you’re doing in your particular situation and whether\ngaining conciseness is an appropriate trade-off for losing exhaustive checking.\nIn other words, you can think of `if let` as syntax sugar for a `match` that\nruns code when the value matches one pattern and then ignores all other values.\nWe can include an `else` with an `if let`. The block of code that goes with the\n`else` is the same as the block of code that would go with the `_` case in the\n`match` expression that is equivalent to the `if let` and `else`. Recall the\n`Coin` enum definition in Listing 6-4, where the `Quarter` variant also held a\n`UsState` value. If we wanted to count all non-quarter coins we see while also\nannouncing the state of the quarters, we could do that with a `match`\nexpression, like this:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Concise Control Flow with `if let` and `let...else`", "heading_path": ["Concise Control Flow with `if let` and `let...else`"], "path": "ch06-03-if-let.md", "url": "https://doc.rust-lang.org/book/ch06-03-if-let.html#concise-control-flow-with-if-let-and-letelse", "has_code": false, "code_tags": []}} {"id": "book/ch06-03-if-let.md#concise-control-flow-with-if-let-and-letelse-2", "text": "The Rust Programming Language › Concise Control Flow with `if let` and `let...else`\n\n```rust\n let mut count = 0;\n match coin {\n Coin::Quarter(state) => println!(\"State quarter from {state:?}!\"),\n _ => count += 1,\n }\n```\nOr we could use an `if let` and `else` expression, like this:\n```rust\n let mut count = 0;\n if let Coin::Quarter(state) = coin {\n println!(\"State quarter from {state:?}!\");\n } else {\n count += 1;\n }\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Concise Control Flow with `if let` and `let...else`", "heading_path": ["Concise Control Flow with `if let` and `let...else`"], "path": "ch06-03-if-let.md", "url": "https://doc.rust-lang.org/book/ch06-03-if-let.html#concise-control-flow-with-if-let-and-letelse", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch06-03-if-let.md#staying-on-the-happy-path-with-letelse-3", "text": "The Rust Programming Language › Staying on the “Happy Path” with `let...else`\n\nThe common pattern is to perform some computation when a value is present and\nreturn a default value otherwise. Continuing with our example of coins with a\n`UsState` value, if we wanted to say something funny depending on how old the\nstate on the quarter was, we might introduce a method on `UsState` to check the\nage of a state, like so:\n```rust\nimpl UsState {\n fn existed_in(&self, year: u16) -> bool {\n match self {\n UsState::Alabama => year >= 1819,\n UsState::Alaska => year >= 1959,\n // -- snip --\n }\n }\n}\n```\nThen, we might use `if let` to match on the type of coin, introducing a `state`\nvariable within the body of the condition, as in Listing 6-7.\nListing 6-7: Checking whether a state existed in 1900 by using conditionals nested inside an `if let`\n```rust\nfn describe_state_quarter(coin: Coin) -> Option {\n if let Coin::Quarter(state) = coin {\n if state.existed_in(1900) {\n Some(format!(\"{state:?} is pretty old, for America!\"))\n } else {\n Some(format!(\"{state:?} is relatively new.\"))\n }\n } else {\n None\n }\n}\n```\nThat gets the job done, but it has pushed the work into the body of the `if\nlet` statement, and if the work to be done is more complicated, it might be\nhard to follow exactly how the top-level branches relate. We could also take\nadvantage of the fact that expressions produce a value either to produce the\n`state` from the `if let` or to return early, as in Listing 6-8. (You could do\nsomething similar with a `match`, too.)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Concise Control Flow with `if let` and `let...else`", "heading_path": ["Staying on the “Happy Path” with `let...else`"], "path": "ch06-03-if-let.md", "url": "https://doc.rust-lang.org/book/ch06-03-if-let.html#staying-on-the-happy-path-with-letelse", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch06-03-if-let.md#staying-on-the-happy-path-with-letelse-4", "text": "The Rust Programming Language › Staying on the “Happy Path” with `let...else`\n\nListing 6-8: Using `if let` to produce a value or return early\n```rust\nfn describe_state_quarter(coin: Coin) -> Option {\n let state = if let Coin::Quarter(state) = coin {\n state\n } else {\n return None;\n };\n\n if state.existed_in(1900) {\n Some(format!(\"{state:?} is pretty old, for America!\"))\n } else {\n Some(format!(\"{state:?} is relatively new.\"))\n }\n}\n```\nThis is a bit annoying to follow in its own way, though! One branch of the `if\nlet` produces a value, and the other one returns from the function entirely.\nTo make this common pattern nicer to express, Rust has `let...else`. The\n`let...else` syntax takes a pattern on the left side and an expression on the\nright, very similar to `if let`, but it does not have an `if` branch, only an\n`else` branch. If the pattern matches, it will bind the value from the pattern\nin the outer scope. If the pattern does _not_ match, the program will flow into\nthe `else` arm, which must return from the function.\nIn Listing 6-9, you can see how Listing 6-8 looks when using `let...else` in\nplace of `if let`.\nListing 6-9: Using `let...else` to clarify the flow through the function\n```rust\nfn describe_state_quarter(coin: Coin) -> Option {\n let Coin::Quarter(state) = coin else {\n return None;\n };\n\n if state.existed_in(1900) {\n Some(format!(\"{state:?} is pretty old, for America!\"))\n } else {\n Some(format!(\"{state:?} is relatively new.\"))\n }\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Concise Control Flow with `if let` and `let...else`", "heading_path": ["Staying on the “Happy Path” with `let...else`"], "path": "ch06-03-if-let.md", "url": "https://doc.rust-lang.org/book/ch06-03-if-let.html#staying-on-the-happy-path-with-letelse", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch06-03-if-let.md#staying-on-the-happy-path-with-letelse-5", "text": "The Rust Programming Language › Staying on the “Happy Path” with `let...else`\n\nNotice that it stays on the “happy path” in the main body of the function this\nway, without having significantly different control flow for two branches the\nway the `if let` did.\nIf you have a situation in which your program has logic that is too verbose to\nexpress using a `match`, remember that `if let` and `let...else` are in your\nRust toolbox as well.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Concise Control Flow with `if let` and `let...else`", "heading_path": ["Staying on the “Happy Path” with `let...else`"], "path": "ch06-03-if-let.md", "url": "https://doc.rust-lang.org/book/ch06-03-if-let.html#staying-on-the-happy-path-with-letelse", "has_code": false, "code_tags": []}} {"id": "book/ch06-03-if-let.md#summary-6", "text": "The Rust Programming Language › Summary\n\nWe’ve now covered how to use enums to create custom types that can be one of a\nset of enumerated values. We’ve shown how the standard library’s `Option`\ntype helps you use the type system to prevent errors. When enum values have\ndata inside them, you can use `match` or `if let` to extract and use those\nvalues, depending on how many cases you need to handle.\nYour Rust programs can now express concepts in your domain using structs and\nenums. Creating custom types to use in your API ensures type safety: The\ncompiler will make certain your functions only get values of the type each\nfunction expects.\nIn order to provide a well-organized API to your users that is straightforward\nto use and only exposes exactly what your users will need, let’s now turn to\nRust’s modules.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Concise Control Flow with `if let` and `let...else`", "heading_path": ["Summary"], "path": "ch06-03-if-let.md", "url": "https://doc.rust-lang.org/book/ch06-03-if-let.html#summary", "has_code": false, "code_tags": []}} {"id": "book/ch07-00-managing-growing-projects-with-packages-crates-and-modules.md#packages-crates-and-modules-0", "text": "The Rust Programming Language › Packages, Crates, and Modules\n\nAs you write large programs, organizing your code will become increasingly\nimportant. By grouping related functionality and separating code with distinct\nfeatures, you’ll clarify where to find code that implements a particular\nfeature and where to go to change how a feature works.\nThe programs we’ve written so far have been in one module in one file. As a\nproject grows, you should organize code by splitting it into multiple modules\nand then multiple files. A package can contain multiple binary crates and\noptionally one library crate. As a package grows, you can extract parts into\nseparate crates that become external dependencies. This chapter covers all\nthese techniques. For very large projects comprising a set of interrelated\npackages that evolve together, Cargo provides workspaces, which we’ll cover in\n“Cargo Workspaces” in Chapter 14.\nWe’ll also discuss encapsulating implementation details, which lets you reuse\ncode at a higher level: Once you’ve implemented an operation, other code can\ncall your code via its public interface without having to know how the\nimplementation works. The way you write code defines which parts are public for\nother code to use and which parts are private implementation details that you\nreserve the right to change. This is another way to limit the amount of detail\nyou have to keep in your head.\nA related concept is scope: The nested context in which code is written has a\nset of names that are defined as “in scope.” When reading, writing, and\ncompiling code, programmers and compilers need to know whether a particular\nname at a particular spot refers to a variable, function, struct, enum, module,\nconstant, or other item and what that item means. You can create scopes and\nchange which names are in or out of scope. You can’t have two items with the\nsame name in the same scope; tools are available to resolve name conflicts.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Packages, Crates, and Modules", "heading_path": ["Packages, Crates, and Modules"], "path": "ch07-00-managing-growing-projects-with-packages-crates-and-modules.md", "url": "https://doc.rust-lang.org/book/ch07-00-managing-growing-projects-with-packages-crates-and-modules.html#packages-crates-and-modules", "has_code": false, "code_tags": []}} {"id": "book/ch07-00-managing-growing-projects-with-packages-crates-and-modules.md#packages-crates-and-modules-1", "text": "The Rust Programming Language › Packages, Crates, and Modules\n\nRust has a number of features that allow you to manage your code’s\norganization, including which details are exposed, which details are private,\nand what names are in each scope in your programs. These features, sometimes\ncollectively referred to as the _module system_, include:\n* **Packages**: A Cargo feature that lets you build, test, and share crates\n* **Crates**: A tree of modules that produces a library or executable\n* **Modules and use**: Let you control the organization, scope, and privacy of\npaths\n* **Paths**: A way of naming an item, such as a struct, function, or module\nIn this chapter, we’ll cover all these features, discuss how they interact, and\nexplain how to use them to manage scope. By the end, you should have a solid\nunderstanding of the module system and be able to work with scopes like a pro!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Packages, Crates, and Modules", "heading_path": ["Packages, Crates, and Modules"], "path": "ch07-00-managing-growing-projects-with-packages-crates-and-modules.md", "url": "https://doc.rust-lang.org/book/ch07-00-managing-growing-projects-with-packages-crates-and-modules.html#packages-crates-and-modules", "has_code": false, "code_tags": []}} {"id": "book/ch07-01-packages-and-crates.md#packages-and-crates-0", "text": "The Rust Programming Language › Packages and Crates\n\nThe first parts of the module system we’ll cover are packages and crates.\nA _crate_ is the smallest amount of code that the Rust compiler considers at a\ntime. Even if you run `rustc` rather than `cargo` and pass a single source code\nfile (as we did all the way back in “Rust Program Basics”\n in Chapter 1), the compiler considers that file to be a crate. Crates can\ncontain modules, and the modules may be defined in other files that get\ncompiled with the crate, as we’ll see in the coming sections.\nA crate can come in one of two forms: a binary crate or a library crate.\n_Binary crates_ are programs you can compile to an executable that you can run,\nsuch as a command line program or a server. Each must have a function called\n`main` that defines what happens when the executable runs. All the crates we’ve\ncreated so far have been binary crates.\n_Library crates_ don’t have a `main` function, and they don’t compile to an\nexecutable. Instead, they define functionality intended to be shared with\nmultiple projects. For example, the `rand` crate we used in Chapter\n2 provides functionality that generates random numbers.\nMost of the time when Rustaceans say “crate,” they mean library crate, and they\nuse “crate” interchangeably with the general programming concept of a “library.”\nThe _crate root_ is a source file that the Rust compiler starts from and makes\nup the root module of your crate (we’ll explain modules in depth in “Control\nScope and Privacy with Modules”).", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Packages and Crates", "heading_path": ["Packages and Crates"], "path": "ch07-01-packages-and-crates.md", "url": "https://doc.rust-lang.org/book/ch07-01-packages-and-crates.html#packages-and-crates", "has_code": false, "code_tags": []}} {"id": "book/ch07-01-packages-and-crates.md#packages-and-crates-1", "text": "The Rust Programming Language › Packages and Crates\n\nA _package_ is a bundle of one or more crates that provides a set of\nfunctionality. A package contains a _Cargo.toml_ file that describes how to\nbuild those crates. Cargo is actually a package that contains the binary crate\nfor the command line tool you’ve been using to build your code. The Cargo\npackage also contains a library crate that the binary crate depends on. Other\nprojects can depend on the Cargo library crate to use the same logic the Cargo\ncommand line tool uses.\nA package can contain as many binary crates as you like, but at most only one\nlibrary crate. A package must contain at least one crate, whether that’s a\nlibrary or binary crate.\nLet’s walk through what happens when we create a package. First, we enter the\ncommand `cargo new my-project`:\n```console\n$ cargo new my-project\n Created binary (application) `my-project` package\n$ ls my-project\nCargo.toml\nsrc\n$ ls my-project/src\nmain.rs\n```\nAfter we run `cargo new my-project`, we use `ls` to see what Cargo creates. In\nthe _my-project_ directory, there’s a _Cargo.toml_ file, giving us a package.\nThere’s also a _src_ directory that contains _main.rs_. Open _Cargo.toml_ in\nyour text editor and note that there’s no mention of _src/main.rs_. Cargo\nfollows a convention that _src/main.rs_ is the crate root of a binary crate\nwith the same name as the package. Likewise, Cargo knows that if the package\ndirectory contains _src/lib.rs_, the package contains a library crate with the\nsame name as the package, and _src/lib.rs_ is its crate root. Cargo passes the\ncrate root files to `rustc` to build the library or binary.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Packages and Crates", "heading_path": ["Packages and Crates"], "path": "ch07-01-packages-and-crates.md", "url": "https://doc.rust-lang.org/book/ch07-01-packages-and-crates.html#packages-and-crates", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch07-01-packages-and-crates.md#packages-and-crates-2", "text": "The Rust Programming Language › Packages and Crates\n\nHere, we have a package that only contains _src/main.rs_, meaning it only\ncontains a binary crate named `my-project`. If a package contains _src/main.rs_\nand _src/lib.rs_, it has two crates: a binary and a library, both with the same\nname as the package. A package can have multiple binary crates by placing files\nin the _src/bin_ directory: Each file will be a separate binary crate.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Packages and Crates", "heading_path": ["Packages and Crates"], "path": "ch07-01-packages-and-crates.md", "url": "https://doc.rust-lang.org/book/ch07-01-packages-and-crates.html#packages-and-crates", "has_code": false, "code_tags": []}} {"id": "book/ch07-02-defining-modules-to-control-scope-and-privacy.md#control-scope-and-privacy-with-modules-0", "text": "The Rust Programming Language › Control Scope and Privacy with Modules\n\nIn this section, we’ll talk about modules and other parts of the module system,\nnamely _paths_, which allow you to name items; the `use` keyword that brings a\npath into scope; and the `pub` keyword to make items public. We’ll also discuss\nthe `as` keyword, external packages, and the glob operator.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Control Scope and Privacy with Modules", "heading_path": ["Control Scope and Privacy with Modules"], "path": "ch07-02-defining-modules-to-control-scope-and-privacy.md", "url": "https://doc.rust-lang.org/book/ch07-02-defining-modules-to-control-scope-and-privacy.html#control-scope-and-privacy-with-modules", "has_code": false, "code_tags": []}} {"id": "book/ch07-02-defining-modules-to-control-scope-and-privacy.md#modules-cheat-sheet-1", "text": "The Rust Programming Language › Control Scope and Privacy with Modules › Modules Cheat Sheet\n\nBefore we get to the details of modules and paths, here we provide a quick\nreference on how modules, paths, the `use` keyword, and the `pub` keyword work\nin the compiler, and how most developers organize their code. We’ll be going\nthrough examples of each of these rules throughout this chapter, but this is a\ngreat place to refer to as a reminder of how modules work.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Control Scope and Privacy with Modules", "heading_path": ["Control Scope and Privacy with Modules", "Modules Cheat Sheet"], "path": "ch07-02-defining-modules-to-control-scope-and-privacy.md", "url": "https://doc.rust-lang.org/book/ch07-02-defining-modules-to-control-scope-and-privacy.html#modules-cheat-sheet", "has_code": false, "code_tags": []}} {"id": "book/ch07-02-defining-modules-to-control-scope-and-privacy.md#modules-cheat-sheet-2", "text": "The Rust Programming Language › Control Scope and Privacy with Modules › Modules Cheat Sheet\n\n- **Start from the crate root**: When compiling a crate, the compiler first\n looks in the crate root file (usually _src/lib.rs_ for a library crate and\n _src/main.rs_ for a binary crate) for code to compile.\n- **Declaring modules**: In the crate root file, you can declare new modules;\n say you declare a “garden” module with `mod garden;`. The compiler will look\n for the module’s code in these places:\n - Inline, within curly brackets that replace the semicolon following `mod\n garden`\n - In the file _src/garden.rs_\n - In the file _src/garden/mod.rs_\n- **Declaring submodules**: In any file other than the crate root, you can\n declare submodules. For example, you might declare `mod vegetables;` in\n _src/garden.rs_. The compiler will look for the submodule’s code within the\n directory named for the parent module in these places:\n - Inline, directly following `mod vegetables`, within curly brackets instead\n of the semicolon\n - In the file _src/garden/vegetables.rs_\n - In the file _src/garden/vegetables/mod.rs_\n- **Paths to code in modules**: Once a module is part of your crate, you can\n refer to code in that module from anywhere else in that same crate, as long\n as the privacy rules allow, using the path to the code. For example, an\n `Asparagus` type in the garden vegetables module would be found at\n `crate::garden::vegetables::Asparagus`.\n- **Private vs. public**: Code within a module is private from its parent\n modules by default. To make a module public, declare it with `pub mod`\n instead of `mod`. To make items within a public module public as well, use\n `pub` before their declarations.\n- **The `use` keyword**: Within a scope, the `use` keyword creates shortcuts to\n items to reduce repetition of long paths. In any scope that can refer to\n `crate::garden::vegetables::Asparagus`, you can create a shortcut with `use\n crate::garden::vegetables::Asparagus;`, and from then on you only need to\n write `Asparagus` to make use of that type in the scope.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Control Scope and Privacy with Modules", "heading_path": ["Control Scope and Privacy with Modules", "Modules Cheat Sheet"], "path": "ch07-02-defining-modules-to-control-scope-and-privacy.md", "url": "https://doc.rust-lang.org/book/ch07-02-defining-modules-to-control-scope-and-privacy.html#modules-cheat-sheet", "has_code": false, "code_tags": []}} {"id": "book/ch07-02-defining-modules-to-control-scope-and-privacy.md#modules-cheat-sheet-3", "text": "The Rust Programming Language › Control Scope and Privacy with Modules › Modules Cheat Sheet\n\nHere, we create a binary crate named `backyard` that illustrates these rules.\nThe crate’s directory, also named _backyard_, contains these files and\ndirectories:\n```text\nbackyard\n├── Cargo.lock\n├── Cargo.toml\n└── src\n ├── garden\n │   └── vegetables.rs\n ├── garden.rs\n └── main.rs\n```\nThe crate root file in this case is _src/main.rs_, and it contains:\nListing (src/main.rs)\n```rust,noplayground,ignore\nuse crate::garden::vegetables::Asparagus;\n\npub mod garden;\n\nfn main() {\n let plant = Asparagus {};\n println!(\"I'm growing {plant:?}!\");\n}\n```\nThe `pub mod garden;` line tells the compiler to include the code it finds in\n_src/garden.rs_, which is:\nListing (src/garden.rs)\n```rust,noplayground,ignore\npub mod vegetables;\n```\nHere, `pub mod vegetables;` means the code in _src/garden/vegetables.rs_ is\nincluded too. That code is:\n```rust,noplayground,ignore\n#[derive(Debug)]\npub struct Asparagus {}\n```\nNow let’s get into the details of these rules and demonstrate them in action!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Control Scope and Privacy with Modules", "heading_path": ["Control Scope and Privacy with Modules", "Modules Cheat Sheet"], "path": "ch07-02-defining-modules-to-control-scope-and-privacy.md", "url": "https://doc.rust-lang.org/book/ch07-02-defining-modules-to-control-scope-and-privacy.html#modules-cheat-sheet", "has_code": true, "code_tags": ["rust,noplayground,ignore", "text"]}} {"id": "book/ch07-02-defining-modules-to-control-scope-and-privacy.md#grouping-related-code-in-modules-4", "text": "The Rust Programming Language › Control Scope and Privacy with Modules › Grouping Related Code in Modules\n\n_Modules_ let us organize code within a crate for readability and easy reuse.\nModules also allow us to control the _privacy_ of items because code within a\nmodule is private by default. Private items are internal implementation details\nnot available for outside use. We can choose to make modules and the items\nwithin them public, which exposes them to allow external code to use and depend\non them.\nAs an example, let’s write a library crate that provides the functionality of a\nrestaurant. We’ll define the signatures of functions but leave their bodies\nempty to concentrate on the organization of the code rather than the\nimplementation of a restaurant.\nIn the restaurant industry, some parts of a restaurant are referred to as front\nof house and others as back of house. _Front of house_ is where customers are;\nthis encompasses where the hosts seat customers, servers take orders and\npayment, and bartenders make drinks. _Back of house_ is where the chefs and\ncooks work in the kitchen, dishwashers clean up, and managers do administrative\nwork.\nTo structure our crate in this way, we can organize its functions into nested\nmodules. Create a new library named `restaurant` by running `cargo new\nrestaurant --lib`. Then, enter the code in Listing 7-1 into _src/lib.rs_ to\ndefine some modules and function signatures; this code is the front of house\nsection.\nListing 7-1: A `front_of_house` module containing other modules that then contain functions (src/lib.rs)\n```rust,noplayground\nmod front_of_house {\n mod hosting {\n fn add_to_waitlist() {}\n\n fn seat_at_table() {}\n }\n\n mod serving {\n fn take_order() {}\n\n fn serve_order() {}\n\n fn take_payment() {}\n }\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Control Scope and Privacy with Modules", "heading_path": ["Control Scope and Privacy with Modules", "Grouping Related Code in Modules"], "path": "ch07-02-defining-modules-to-control-scope-and-privacy.md", "url": "https://doc.rust-lang.org/book/ch07-02-defining-modules-to-control-scope-and-privacy.html#grouping-related-code-in-modules", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch07-02-defining-modules-to-control-scope-and-privacy.md#grouping-related-code-in-modules-5", "text": "The Rust Programming Language › Control Scope and Privacy with Modules › Grouping Related Code in Modules\n\nWe define a module with the `mod` keyword followed by the name of the module\n(in this case, `front_of_house`). The body of the module then goes inside curly\nbrackets. Inside modules, we can place other modules, as in this case with the\nmodules `hosting` and `serving`. Modules can also hold definitions for other\nitems, such as structs, enums, constants, traits, and as in Listing 7-1,\nfunctions.\nBy using modules, we can group related definitions together and name why\nthey’re related. Programmers using this code can navigate the code based on the\ngroups rather than having to read through all the definitions, making it easier\nto find the definitions relevant to them. Programmers adding new functionality\nto this code would know where to place the code to keep the program organized.\nEarlier, we mentioned that _src/main.rs_ and _src/lib.rs_ are called _crate\nroots_. The reason for their name is that the contents of either of these two\nfiles form a module named `crate` at the root of the crate’s module structure,\nknown as the _module tree_.\nListing 7-2 shows the module tree for the structure in Listing 7-1.\nListing 7-2: The module tree for the code in Listing 7-1\n```text\ncrate\n └── front_of_house\n ├── hosting\n │ ├── add_to_waitlist\n │ └── seat_at_table\n └── serving\n ├── take_order\n ├── serve_order\n └── take_payment\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Control Scope and Privacy with Modules", "heading_path": ["Control Scope and Privacy with Modules", "Grouping Related Code in Modules"], "path": "ch07-02-defining-modules-to-control-scope-and-privacy.md", "url": "https://doc.rust-lang.org/book/ch07-02-defining-modules-to-control-scope-and-privacy.html#grouping-related-code-in-modules", "has_code": true, "code_tags": ["text"]}} {"id": "book/ch07-02-defining-modules-to-control-scope-and-privacy.md#grouping-related-code-in-modules-6", "text": "The Rust Programming Language › Control Scope and Privacy with Modules › Grouping Related Code in Modules\n\nThis tree shows how some of the modules nest inside other modules; for example,\n`hosting` nests inside `front_of_house`. The tree also shows that some modules\nare _siblings_, meaning they’re defined in the same module; `hosting` and\n`serving` are siblings defined within `front_of_house`. If module A is\ncontained inside module B, we say that module A is the _child_ of module B and\nthat module B is the _parent_ of module A. Notice that the entire module tree\nis rooted under the implicit module named `crate`.\nThe module tree might remind you of the filesystem’s directory tree on your\ncomputer; this is a very apt comparison! Just like directories in a filesystem,\nyou use modules to organize your code. And just like files in a directory, we\nneed a way to find our modules.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Control Scope and Privacy with Modules", "heading_path": ["Control Scope and Privacy with Modules", "Grouping Related Code in Modules"], "path": "ch07-02-defining-modules-to-control-scope-and-privacy.md", "url": "https://doc.rust-lang.org/book/ch07-02-defining-modules-to-control-scope-and-privacy.html#grouping-related-code-in-modules", "has_code": false, "code_tags": []}} {"id": "book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md#paths-for-referring-to-an-item-in-the-module-tree-0", "text": "The Rust Programming Language › Paths for Referring to an Item in the Module Tree\n\nTo show Rust where to find an item in a module tree, we use a path in the same\nway we use a path when navigating a filesystem. To call a function, we need to\nknow its path.\nA path can take two forms:\n- An _absolute path_ is the full path starting from a crate root; for code\n from an external crate, the absolute path begins with the crate name, and for\n code from the current crate, it starts with the literal `crate`.\n- A _relative path_ starts from the current module and uses `self`, `super`, or\n an identifier in the current module.\nBoth absolute and relative paths are followed by one or more identifiers\nseparated by double colons (`::`).\nReturning to Listing 7-1, say we want to call the `add_to_waitlist` function.\nThis is the same as asking: What’s the path of the `add_to_waitlist` function?\nListing 7-3 contains Listing 7-1 with some of the modules and functions removed.\nWe’ll show two ways to call the `add_to_waitlist` function from a new function,\n`eat_at_restaurant`, defined in the crate root. These paths are correct, but\nthere’s another problem remaining that will prevent this example from compiling\nas is. We’ll explain why in a bit.\nThe `eat_at_restaurant` function is part of our library crate’s public API, so\nwe mark it with the `pub` keyword. In the “Exposing Paths with the `pub`\nKeyword” section, we’ll go into more detail about `pub`.\nListing 7-3: Calling the `add_to_waitlist` function using absolute and relative paths (src/lib.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Paths for Referring to an Item in the Module Tree", "heading_path": ["Paths for Referring to an Item in the Module Tree"], "path": "ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md", "url": "https://doc.rust-lang.org/book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html#paths-for-referring-to-an-item-in-the-module-tree", "has_code": false, "code_tags": []}} {"id": "book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md#paths-for-referring-to-an-item-in-the-module-tree-1", "text": "The Rust Programming Language › Paths for Referring to an Item in the Module Tree\n\n```rust,ignore,does_not_compile\nmod front_of_house {\n mod hosting {\n fn add_to_waitlist() {}\n }\n}\n\npub fn eat_at_restaurant() {\n // Absolute path\n crate::front_of_house::hosting::add_to_waitlist();\n\n // Relative path\n front_of_house::hosting::add_to_waitlist();\n}\n```\nThe first time we call the `add_to_waitlist` function in `eat_at_restaurant`,\nwe use an absolute path. The `add_to_waitlist` function is defined in the same\ncrate as `eat_at_restaurant`, which means we can use the `crate` keyword to\nstart an absolute path. We then include each of the successive modules until we\nmake our way to `add_to_waitlist`. You can imagine a filesystem with the same\nstructure: We’d specify the path `/front_of_house/hosting/add_to_waitlist` to\nrun the `add_to_waitlist` program; using the `crate` name to start from the\ncrate root is like using `/` to start from the filesystem root in your shell.\nThe second time we call `add_to_waitlist` in `eat_at_restaurant`, we use a\nrelative path. The path starts with `front_of_house`, the name of the module\ndefined at the same level of the module tree as `eat_at_restaurant`. Here the\nfilesystem equivalent would be using the path\n`front_of_house/hosting/add_to_waitlist`. Starting with a module name means\nthat the path is relative.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Paths for Referring to an Item in the Module Tree", "heading_path": ["Paths for Referring to an Item in the Module Tree"], "path": "ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md", "url": "https://doc.rust-lang.org/book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html#paths-for-referring-to-an-item-in-the-module-tree", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md#paths-for-referring-to-an-item-in-the-module-tree-2", "text": "The Rust Programming Language › Paths for Referring to an Item in the Module Tree\n\nChoosing whether to use a relative or absolute path is a decision you’ll make\nbased on your project, and it depends on whether you’re more likely to move\nitem definition code separately from or together with the code that uses the\nitem. For example, if we moved the `front_of_house` module and the\n`eat_at_restaurant` function into a module named `customer_experience`, we’d\nneed to update the absolute path to `add_to_waitlist`, but the relative path\nwould still be valid. However, if we moved the `eat_at_restaurant` function\nseparately into a module named `dining`, the absolute path to the\n`add_to_waitlist` call would stay the same, but the relative path would need to\nbe updated. Our preference in general is to specify absolute paths because it’s\nmore likely we’ll want to move code definitions and item calls independently of\neach other.\nLet’s try to compile Listing 7-3 and find out why it won’t compile yet! The\nerrors we get are shown in Listing 7-4.\nListing 7-4: Compiler errors from building the code in Listing 7-3", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Paths for Referring to an Item in the Module Tree", "heading_path": ["Paths for Referring to an Item in the Module Tree"], "path": "ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md", "url": "https://doc.rust-lang.org/book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html#paths-for-referring-to-an-item-in-the-module-tree", "has_code": false, "code_tags": []}} {"id": "book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md#paths-for-referring-to-an-item-in-the-module-tree-3", "text": "The Rust Programming Language › Paths for Referring to an Item in the Module Tree\n\n```console\n$ cargo build\n Compiling restaurant v0.1.0 (file:///projects/restaurant)\nerror[E0603]: module `hosting` is private\n --> src/lib.rs:9:28\n |\n9 | crate::front_of_house::hosting::add_to_waitlist();\n | ^^^^^^^ --------------- function `add_to_waitlist` is not publicly re-exported\n | |\n | private module\n |\nnote: the module `hosting` is defined here\n --> src/lib.rs:2:5\n |\n2 | mod hosting {\n | ^^^^^^^^^^^\n\nerror[E0603]: module `hosting` is private\n --> src/lib.rs:12:21\n |\n12 | front_of_house::hosting::add_to_waitlist();\n | ^^^^^^^ --------------- function `add_to_waitlist` is not publicly re-exported\n | |\n | private module\n |\nnote: the module `hosting` is defined here\n --> src/lib.rs:2:5\n |\n 2 | mod hosting {\n | ^^^^^^^^^^^\n\nFor more information about this error, try `rustc --explain E0603`.\nerror: could not compile `restaurant` (lib) due to 2 previous errors\n```\nThe error messages say that module `hosting` is private. In other words, we\nhave the correct paths for the `hosting` module and the `add_to_waitlist`\nfunction, but Rust won’t let us use them because it doesn’t have access to the\nprivate sections. In Rust, all items (functions, methods, structs, enums,\nmodules, and constants) are private to parent modules by default. If you want\nto make an item like a function or struct private, you put it in a module.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Paths for Referring to an Item in the Module Tree", "heading_path": ["Paths for Referring to an Item in the Module Tree"], "path": "ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md", "url": "https://doc.rust-lang.org/book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html#paths-for-referring-to-an-item-in-the-module-tree", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md#paths-for-referring-to-an-item-in-the-module-tree-4", "text": "The Rust Programming Language › Paths for Referring to an Item in the Module Tree\n\nItems in a parent module can’t use the private items inside child modules, but\nitems in child modules can use the items in their ancestor modules. This is\nbecause child modules wrap and hide their implementation details, but the child\nmodules can see the context in which they’re defined. To continue with our\nmetaphor, think of the privacy rules as being like the back office of a\nrestaurant: What goes on in there is private to restaurant customers, but\noffice managers can see and do everything in the restaurant they operate.\nRust chose to have the module system function this way so that hiding inner\nimplementation details is the default. That way, you know which parts of the\ninner code you can change without breaking the outer code. However, Rust does\ngive you the option to expose inner parts of child modules’ code to outer\nancestor modules by using the `pub` keyword to make an item public.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Paths for Referring to an Item in the Module Tree", "heading_path": ["Paths for Referring to an Item in the Module Tree"], "path": "ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md", "url": "https://doc.rust-lang.org/book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html#paths-for-referring-to-an-item-in-the-module-tree", "has_code": false, "code_tags": []}} {"id": "book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md#exposing-paths-with-the-pub-keyword-5", "text": "The Rust Programming Language › Paths for Referring to an Item in the Module Tree › Exposing Paths with the `pub` Keyword\n\nLet’s return to the error in Listing 7-4 that told us the `hosting` module is\nprivate. We want the `eat_at_restaurant` function in the parent module to have\naccess to the `add_to_waitlist` function in the child module, so we mark the\n`hosting` module with the `pub` keyword, as shown in Listing 7-5.\nListing 7-5: Declaring the `hosting` module as `pub` to use it from `eat_at_restaurant` (src/lib.rs)\n```rust,ignore,does_not_compile\nmod front_of_house {\n pub mod hosting {\n fn add_to_waitlist() {}\n }\n}\n\n// -- snip --\n```\nUnfortunately, the code in Listing 7-5 still results in compiler errors, as\nshown in Listing 7-6.\nListing 7-6: Compiler errors from building the code in Listing 7-5", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Paths for Referring to an Item in the Module Tree", "heading_path": ["Paths for Referring to an Item in the Module Tree", "Exposing Paths with the `pub` Keyword"], "path": "ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md", "url": "https://doc.rust-lang.org/book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html#exposing-paths-with-the-pub-keyword", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md#exposing-paths-with-the-pub-keyword-6", "text": "The Rust Programming Language › Paths for Referring to an Item in the Module Tree › Exposing Paths with the `pub` Keyword\n\n```console\n$ cargo build\n Compiling restaurant v0.1.0 (file:///projects/restaurant)\nerror[E0603]: function `add_to_waitlist` is private\n --> src/lib.rs:10:37\n |\n10 | crate::front_of_house::hosting::add_to_waitlist();\n | ^^^^^^^^^^^^^^^ private function\n |\nnote: the function `add_to_waitlist` is defined here\n --> src/lib.rs:3:9\n |\n 3 | fn add_to_waitlist() {}\n | ^^^^^^^^^^^^^^^^^^^^\n\nerror[E0603]: function `add_to_waitlist` is private\n --> src/lib.rs:13:30\n |\n13 | front_of_house::hosting::add_to_waitlist();\n | ^^^^^^^^^^^^^^^ private function\n |\nnote: the function `add_to_waitlist` is defined here\n --> src/lib.rs:3:9\n |\n 3 | fn add_to_waitlist() {}\n | ^^^^^^^^^^^^^^^^^^^^\n\nFor more information about this error, try `rustc --explain E0603`.\nerror: could not compile `restaurant` (lib) due to 2 previous errors\n```\nWhat happened? Adding the `pub` keyword in front of `mod hosting` makes the\nmodule public. With this change, if we can access `front_of_house`, we can\naccess `hosting`. But the _contents_ of `hosting` are still private; making the\nmodule public doesn’t make its contents public. The `pub` keyword on a module\nonly lets code in its ancestor modules refer to it, not access its inner code.\nBecause modules are containers, there’s not much we can do by only making the\nmodule public; we need to go further and choose to make one or more of the\nitems within the module public as well.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Paths for Referring to an Item in the Module Tree", "heading_path": ["Paths for Referring to an Item in the Module Tree", "Exposing Paths with the `pub` Keyword"], "path": "ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md", "url": "https://doc.rust-lang.org/book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html#exposing-paths-with-the-pub-keyword", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md#exposing-paths-with-the-pub-keyword-7", "text": "The Rust Programming Language › Paths for Referring to an Item in the Module Tree › Exposing Paths with the `pub` Keyword\n\nThe errors in Listing 7-6 say that the `add_to_waitlist` function is private.\nThe privacy rules apply to structs, enums, functions, and methods as well as\nmodules.\nLet’s also make the `add_to_waitlist` function public by adding the `pub`\nkeyword before its definition, as in Listing 7-7.\nListing 7-7: Adding the `pub` keyword to `mod hosting` and `fn add_to_waitlist` lets us call the function from `eat_at_restaurant`. (src/lib.rs)\n```rust,noplayground,test_harness\nmod front_of_house {\n pub mod hosting {\n pub fn add_to_waitlist() {}\n }\n}\n\n// -- snip --\n```\nNow the code will compile! To see why adding the `pub` keyword lets us use\nthese paths in `eat_at_restaurant` with respect to the privacy rules, let’s\nlook at the absolute and the relative paths.\nIn the absolute path, we start with `crate`, the root of our crate’s module\ntree. The `front_of_house` module is defined in the crate root. While\n`front_of_house` isn’t public, because the `eat_at_restaurant` function is\ndefined in the same module as `front_of_house` (that is, `eat_at_restaurant`\nand `front_of_house` are siblings), we can refer to `front_of_house` from\n`eat_at_restaurant`. Next is the `hosting` module marked with `pub`. We can\naccess the parent module of `hosting`, so we can access `hosting`. Finally, the\n`add_to_waitlist` function is marked with `pub`, and we can access its parent\nmodule, so this function call works!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Paths for Referring to an Item in the Module Tree", "heading_path": ["Paths for Referring to an Item in the Module Tree", "Exposing Paths with the `pub` Keyword"], "path": "ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md", "url": "https://doc.rust-lang.org/book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html#exposing-paths-with-the-pub-keyword", "has_code": true, "code_tags": ["rust,noplayground,test_harness"]}} {"id": "book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md#best-practices-for-packages-with-a-binary-and-a-library-8", "text": "The Rust Programming Language › Paths for Referring to an Item in the Module Tree › Exposing Paths with the `pub` Keyword › Best Practices for Packages with a Binary and a Library\n\nIn the relative path, the logic is the same as the absolute path except for the\nfirst step: Rather than starting from the crate root, the path starts from\n`front_of_house`. The `front_of_house` module is defined within the same module\nas `eat_at_restaurant`, so the relative path starting from the module in which\n`eat_at_restaurant` is defined works. Then, because `hosting` and\n`add_to_waitlist` are marked with `pub`, the rest of the path works, and this\nfunction call is valid!\nIf you plan to share your library crate so that other projects can use your\ncode, your public API is your contract with users of your crate that determines\nhow they can interact with your code. There are many considerations around\nmanaging changes to your public API to make it easier for people to depend on\nyour crate. These considerations are beyond the scope of this book; if you’re\ninterested in this topic, see the Rust API Guidelines.\nWe mentioned that a package can contain both a _src/main.rs_ binary crate\nroot as well as a _src/lib.rs_ library crate root, and both crates will have\nthe package name by default. Typically, packages with this pattern of\ncontaining both a library and a binary crate will have just enough code in the\nbinary crate to start an executable that calls code defined in the library\ncrate. This lets other projects benefit from the most functionality that the\npackage provides because the library crate’s code can be shared.\nThe module tree should be defined in _src/lib.rs_. Then, any public items can\nbe used in the binary crate by starting paths with the name of the package.\nThe binary crate becomes a user of the library crate just like a completely\nexternal crate would use the library crate: It can only use the public API.\nThis helps you design a good API; not only are you the author, but you’re\nalso a client!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Paths for Referring to an Item in the Module Tree", "heading_path": ["Paths for Referring to an Item in the Module Tree", "Exposing Paths with the `pub` Keyword", "Best Practices for Packages with a Binary and a Library"], "path": "ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md", "url": "https://doc.rust-lang.org/book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html#best-practices-for-packages-with-a-binary-and-a-library", "has_code": false, "code_tags": []}} {"id": "book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md#best-practices-for-packages-with-a-binary-and-a-library-9", "text": "The Rust Programming Language › Paths for Referring to an Item in the Module Tree › Exposing Paths with the `pub` Keyword › Best Practices for Packages with a Binary and a Library\n\nIn Chapter 12, we’ll demonstrate this organizational\npractice with a command line program that will contain both a binary crate\nand a library crate.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Paths for Referring to an Item in the Module Tree", "heading_path": ["Paths for Referring to an Item in the Module Tree", "Exposing Paths with the `pub` Keyword", "Best Practices for Packages with a Binary and a Library"], "path": "ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md", "url": "https://doc.rust-lang.org/book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html#best-practices-for-packages-with-a-binary-and-a-library", "has_code": false, "code_tags": []}} {"id": "book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md#starting-relative-paths-with-super-10", "text": "The Rust Programming Language › Paths for Referring to an Item in the Module Tree › Starting Relative Paths with `super`\n\nWe can construct relative paths that begin in the parent module, rather than\nthe current module or the crate root, by using `super` at the start of the\npath. This is like starting a filesystem path with the `..` syntax that means\nto go to the parent directory. Using `super` allows us to reference an item\nthat we know is in the parent module, which can make rearranging the module\ntree easier when the module is closely related to the parent but the parent\nmight be moved elsewhere in the module tree someday.\nConsider the code in Listing 7-8 that models the situation in which a chef\nfixes an incorrect order and personally brings it out to the customer. The\nfunction `fix_incorrect_order` defined in the `back_of_house` module calls the\nfunction `deliver_order` defined in the parent module by specifying the path to\n`deliver_order`, starting with `super`.\nListing 7-8: Calling a function using a relative path starting with `super` (src/lib.rs)\n```rust,noplayground,test_harness\nfn deliver_order() {}\n\nmod back_of_house {\n fn fix_incorrect_order() {\n cook_order();\n super::deliver_order();\n }\n\n fn cook_order() {}\n}\n```\nThe `fix_incorrect_order` function is in the `back_of_house` module, so we can\nuse `super` to go to the parent module of `back_of_house`, which in this case\nis `crate`, the root. From there, we look for `deliver_order` and find it.\nSuccess! We think the `back_of_house` module and the `deliver_order` function\nare likely to stay in the same relationship to each other and get moved\ntogether should we decide to reorganize the crate’s module tree. Therefore, we\nused `super` so that we’ll have fewer places to update code in the future if\nthis code gets moved to a different module.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Paths for Referring to an Item in the Module Tree", "heading_path": ["Paths for Referring to an Item in the Module Tree", "Starting Relative Paths with `super`"], "path": "ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md", "url": "https://doc.rust-lang.org/book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html#starting-relative-paths-with-super", "has_code": true, "code_tags": ["rust,noplayground,test_harness"]}} {"id": "book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md#making-structs-and-enums-public-11", "text": "The Rust Programming Language › Paths for Referring to an Item in the Module Tree › Making Structs and Enums Public\n\nWe can also use `pub` to designate structs and enums as public, but there are a\nfew extra details to the usage of `pub` with structs and enums. If we use `pub`\nbefore a struct definition, we make the struct public, but the struct’s fields\nwill still be private. We can make each field public or not on a case-by-case\nbasis. In Listing 7-9, we’ve defined a public `back_of_house::Breakfast` struct\nwith a public `toast` field but a private `seasonal_fruit` field. This models\nthe case in a restaurant where the customer can pick the type of bread that\ncomes with a meal, but the chef decides which fruit accompanies the meal based\non what’s in season and in stock. The available fruit changes quickly, so\ncustomers can’t choose the fruit or even see which fruit they’ll get.\nListing 7-9: A struct with some public fields and some private fields (src/lib.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Paths for Referring to an Item in the Module Tree", "heading_path": ["Paths for Referring to an Item in the Module Tree", "Making Structs and Enums Public"], "path": "ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md", "url": "https://doc.rust-lang.org/book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html#making-structs-and-enums-public", "has_code": false, "code_tags": []}} {"id": "book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md#making-structs-and-enums-public-12", "text": "The Rust Programming Language › Paths for Referring to an Item in the Module Tree › Making Structs and Enums Public\n\n```rust,noplayground\nmod back_of_house {\n pub struct Breakfast {\n pub toast: String,\n seasonal_fruit: String,\n }\n\n impl Breakfast {\n pub fn summer(toast: &str) -> Breakfast {\n Breakfast {\n toast: String::from(toast),\n seasonal_fruit: String::from(\"peaches\"),\n }\n }\n }\n}\n\npub fn eat_at_restaurant() {\n // Order a breakfast in the summer with Rye toast.\n let mut meal = back_of_house::Breakfast::summer(\"Rye\");\n // Change our mind about what bread we'd like.\n meal.toast = String::from(\"Wheat\");\n println!(\"I'd like {} toast please\", meal.toast);\n\n // The next line won't compile if we uncomment it; we're not allowed\n // to see or modify the seasonal fruit that comes with the meal.\n // meal.seasonal_fruit = String::from(\"blueberries\");\n}\n```\nBecause the `toast` field in the `back_of_house::Breakfast` struct is public,\nin `eat_at_restaurant` we can write and read to the `toast` field using dot\nnotation. Notice that we can’t use the `seasonal_fruit` field in\n`eat_at_restaurant`, because `seasonal_fruit` is private. Try uncommenting the\nline modifying the `seasonal_fruit` field value to see what error you get!\nAlso, note that because `back_of_house::Breakfast` has a private field, the\nstruct needs to provide a public associated function that constructs an\ninstance of `Breakfast` (we’ve named it `summer` here). If `Breakfast` didn’t\nhave such a function, we couldn’t create an instance of `Breakfast` in\n`eat_at_restaurant`, because we couldn’t set the value of the private\n`seasonal_fruit` field in `eat_at_restaurant`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Paths for Referring to an Item in the Module Tree", "heading_path": ["Paths for Referring to an Item in the Module Tree", "Making Structs and Enums Public"], "path": "ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md", "url": "https://doc.rust-lang.org/book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html#making-structs-and-enums-public", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md#making-structs-and-enums-public-13", "text": "The Rust Programming Language › Paths for Referring to an Item in the Module Tree › Making Structs and Enums Public\n\nIn contrast, if we make an enum public, all of its variants are then public. We\nonly need the `pub` before the `enum` keyword, as shown in Listing 7-10.\nListing 7-10: Designating an enum as public makes all its variants public. (src/lib.rs)\n```rust,noplayground\nmod back_of_house {\n pub enum Appetizer {\n Soup,\n Salad,\n }\n}\n\npub fn eat_at_restaurant() {\n let order1 = back_of_house::Appetizer::Soup;\n let order2 = back_of_house::Appetizer::Salad;\n}\n```\nBecause we made the `Appetizer` enum public, we can use the `Soup` and `Salad`\nvariants in `eat_at_restaurant`.\nEnums aren’t very useful unless their variants are public; it would be annoying\nto have to annotate all enum variants with `pub` in every case, so the default\nfor enum variants is to be public. Structs are often useful without their\nfields being public, so struct fields follow the general rule of everything\nbeing private by default unless annotated with `pub`.\nThere’s one more situation involving `pub` that we haven’t covered, and that is\nour last module system feature: the `use` keyword. We’ll cover `use` by itself\nfirst, and then we’ll show how to combine `pub` and `use`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Paths for Referring to an Item in the Module Tree", "heading_path": ["Paths for Referring to an Item in the Module Tree", "Making Structs and Enums Public"], "path": "ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md", "url": "https://doc.rust-lang.org/book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html#making-structs-and-enums-public", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.md#bringing-paths-into-scope-with-the-use-keyword-0", "text": "The Rust Programming Language › Bringing Paths into Scope with the `use` Keyword\n\nHaving to write out the paths to call functions can feel inconvenient and\nrepetitive. In Listing 7-7, whether we chose the absolute or relative path to\nthe `add_to_waitlist` function, every time we wanted to call `add_to_waitlist`\nwe had to specify `front_of_house` and `hosting` too. Fortunately, there’s a\nway to simplify this process: We can create a shortcut to a path with the `use`\nkeyword once and then use the shorter name everywhere else in the scope.\nIn Listing 7-11, we bring the `crate::front_of_house::hosting` module into the\nscope of the `eat_at_restaurant` function so that we only have to specify\n`hosting::add_to_waitlist` to call the `add_to_waitlist` function in\n`eat_at_restaurant`.\nListing 7-11: Bringing a module into scope with `use` (src/lib.rs)\n```rust,noplayground,test_harness\nmod front_of_house {\n pub mod hosting {\n pub fn add_to_waitlist() {}\n }\n}\n\nuse crate::front_of_house::hosting;\n\npub fn eat_at_restaurant() {\n hosting::add_to_waitlist();\n}\n```\nAdding `use` and a path in a scope is similar to creating a symbolic link in\nthe filesystem. By adding `use crate::front_of_house::hosting` in the crate\nroot, `hosting` is now a valid name in that scope, just as though the `hosting`\nmodule had been defined in the crate root. Paths brought into scope with `use`\nalso check privacy, like any other paths.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Bringing Paths Into Scope with the `use` Keyword", "heading_path": ["Bringing Paths into Scope with the `use` Keyword"], "path": "ch07-04-bringing-paths-into-scope-with-the-use-keyword.md", "url": "https://doc.rust-lang.org/book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.html#bringing-paths-into-scope-with-the-use-keyword", "has_code": true, "code_tags": ["rust,noplayground,test_harness"]}} {"id": "book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.md#bringing-paths-into-scope-with-the-use-keyword-1", "text": "The Rust Programming Language › Bringing Paths into Scope with the `use` Keyword\n\nNote that `use` only creates the shortcut for the particular scope in which the\n`use` occurs. Listing 7-12 moves the `eat_at_restaurant` function into a new\nchild module named `customer`, which is then a different scope than the `use`\nstatement, so the function body won’t compile.\nListing 7-12: A `use` statement only applies in the scope it’s in. (src/lib.rs)\n```rust,noplayground,test_harness,does_not_compile,ignore\nmod front_of_house {\n pub mod hosting {\n pub fn add_to_waitlist() {}\n }\n}\n\nuse crate::front_of_house::hosting;\n\nmod customer {\n pub fn eat_at_restaurant() {\n hosting::add_to_waitlist();\n }\n}\n```\nThe compiler error shows that the shortcut no longer applies within the\n`customer` module:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Bringing Paths Into Scope with the `use` Keyword", "heading_path": ["Bringing Paths into Scope with the `use` Keyword"], "path": "ch07-04-bringing-paths-into-scope-with-the-use-keyword.md", "url": "https://doc.rust-lang.org/book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.html#bringing-paths-into-scope-with-the-use-keyword", "has_code": true, "code_tags": ["rust,noplayground,test_harness,does_not_compile,ignore"]}} {"id": "book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.md#bringing-paths-into-scope-with-the-use-keyword-2", "text": "The Rust Programming Language › Bringing Paths into Scope with the `use` Keyword\n\n```console\n$ cargo build\n Compiling restaurant v0.1.0 (file:///projects/restaurant)\nerror[E0433]: cannot find module or crate `hosting` in this scope\n --> src/lib.rs:11:9\n |\n11 | hosting::add_to_waitlist();\n | ^^^^^^^ use of unresolved module or unlinked crate `hosting`\n |\n = help: if you wanted to use a crate named `hosting`, use `cargo add hosting` to add it to your `Cargo.toml`\nhelp: consider importing this module through its public re-export\n |\n10 + use crate::hosting;\n |\n\nwarning: unused import: `crate::front_of_house::hosting`\n --> src/lib.rs:7:5\n |\n7 | use crate::front_of_house::hosting;\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n |\n = note: `#[warn(unused_imports)]` (part of `#[warn(unused)]`) on by default\n\nFor more information about this error, try `rustc --explain E0433`.\nwarning: `restaurant` (lib) generated 1 warning\nerror: could not compile `restaurant` (lib) due to 1 previous error; 1 warning emitted\n```\nNotice there’s also a warning that the `use` is no longer used in its scope! To\nfix this problem, move the `use` within the `customer` module too, or reference\nthe shortcut in the parent module with `super::hosting` within the child\n`customer` module.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Bringing Paths Into Scope with the `use` Keyword", "heading_path": ["Bringing Paths into Scope with the `use` Keyword"], "path": "ch07-04-bringing-paths-into-scope-with-the-use-keyword.md", "url": "https://doc.rust-lang.org/book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.html#bringing-paths-into-scope-with-the-use-keyword", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.md#creating-idiomatic-use-paths-3", "text": "The Rust Programming Language › Bringing Paths into Scope with the `use` Keyword › Creating Idiomatic `use` Paths\n\nIn Listing 7-11, you might have wondered why we specified `use\ncrate::front_of_house::hosting` and then called `hosting::add_to_waitlist` in\n`eat_at_restaurant`, rather than specifying the `use` path all the way out to\nthe `add_to_waitlist` function to achieve the same result, as in Listing 7-13.\nListing 7-13: Bringing the `add_to_waitlist` function into scope with `use`, which is unidiomatic (src/lib.rs)\n```rust,noplayground,test_harness\nmod front_of_house {\n pub mod hosting {\n pub fn add_to_waitlist() {}\n }\n}\n\nuse crate::front_of_house::hosting::add_to_waitlist;\n\npub fn eat_at_restaurant() {\n add_to_waitlist();\n}\n```\nAlthough both Listing 7-11 and Listing 7-13 accomplish the same task, Listing\n7-11 is the idiomatic way to bring a function into scope with `use`. Bringing\nthe function’s parent module into scope with `use` means we have to specify the\nparent module when calling the function. Specifying the parent module when\ncalling the function makes it clear that the function isn’t locally defined\nwhile still minimizing repetition of the full path. The code in Listing 7-13 is\nunclear as to where `add_to_waitlist` is defined.\nOn the other hand, when bringing in structs, enums, and other items with `use`,\nit’s idiomatic to specify the full path. Listing 7-14 shows the idiomatic way\nto bring the standard library’s `HashMap` struct into the scope of a binary\ncrate.\nListing 7-14: Bringing `HashMap` into scope in an idiomatic way (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Bringing Paths Into Scope with the `use` Keyword", "heading_path": ["Bringing Paths into Scope with the `use` Keyword", "Creating Idiomatic `use` Paths"], "path": "ch07-04-bringing-paths-into-scope-with-the-use-keyword.md", "url": "https://doc.rust-lang.org/book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.html#creating-idiomatic-use-paths", "has_code": true, "code_tags": ["rust,noplayground,test_harness"]}} {"id": "book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.md#creating-idiomatic-use-paths-4", "text": "The Rust Programming Language › Bringing Paths into Scope with the `use` Keyword › Creating Idiomatic `use` Paths\n\n```rust\nuse std::collections::HashMap;\n\nfn main() {\n let mut map = HashMap::new();\n map.insert(1, 2);\n}\n```\nThere’s no strong reason behind this idiom: It’s just the convention that has\nemerged, and folks have gotten used to reading and writing Rust code this way.\nThe exception to this idiom is if we’re bringing two items with the same name\ninto scope with `use` statements, because Rust doesn’t allow that. Listing 7-15\nshows how to bring two `Result` types into scope that have the same name but\ndifferent parent modules, and how to refer to them.\nListing 7-15: Bringing two types with the same name into the same scope requires using their parent modules. (src/lib.rs)\n```rust,noplayground\nuse std::fmt;\nuse std::io;\n\nfn function1() -> fmt::Result {\n // --snip--\n}\n\nfn function2() -> io::Result<()> {\n // --snip--\n}\n```\nAs you can see, using the parent modules distinguishes the two `Result` types.\nIf instead we specified `use std::fmt::Result` and `use std::io::Result`, we’d\nhave two `Result` types in the same scope, and Rust wouldn’t know which one we\nmeant when we used `Result`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Bringing Paths Into Scope with the `use` Keyword", "heading_path": ["Bringing Paths into Scope with the `use` Keyword", "Creating Idiomatic `use` Paths"], "path": "ch07-04-bringing-paths-into-scope-with-the-use-keyword.md", "url": "https://doc.rust-lang.org/book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.html#creating-idiomatic-use-paths", "has_code": true, "code_tags": ["rust", "rust,noplayground"]}} {"id": "book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.md#providing-new-names-with-the-as-keyword-5", "text": "The Rust Programming Language › Bringing Paths into Scope with the `use` Keyword › Providing New Names with the `as` Keyword\n\nThere’s another solution to the problem of bringing two types of the same name\ninto the same scope with `use`: After the path, we can specify `as` and a new\nlocal name, or _alias_, for the type. Listing 7-16 shows another way to write\nthe code in Listing 7-15 by renaming one of the two `Result` types using `as`.\nListing 7-16: Renaming a type when it’s brought into scope with the `as` keyword (src/lib.rs)\n```rust,noplayground\nuse std::fmt::Result;\nuse std::io::Result as IoResult;\n\nfn function1() -> Result {\n // --snip--\n}\n\nfn function2() -> IoResult<()> {\n // --snip--\n}\n```\nIn the second `use` statement, we chose the new name `IoResult` for the\n`std::io::Result` type, which won’t conflict with the `Result` from `std::fmt`\nthat we’ve also brought into scope. Listing 7-15 and Listing 7-16 are\nconsidered idiomatic, so the choice is up to you!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Bringing Paths Into Scope with the `use` Keyword", "heading_path": ["Bringing Paths into Scope with the `use` Keyword", "Providing New Names with the `as` Keyword"], "path": "ch07-04-bringing-paths-into-scope-with-the-use-keyword.md", "url": "https://doc.rust-lang.org/book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.html#providing-new-names-with-the-as-keyword", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.md#re-exporting-names-with-pub-use-6", "text": "The Rust Programming Language › Bringing Paths into Scope with the `use` Keyword › Re-exporting Names with `pub use`\n\nWhen we bring a name into scope with the `use` keyword, the name is private to\nthe scope into which we imported it. To enable code outside that scope to refer\nto that name as if it had been defined in that scope, we can combine `pub` and\n`use`. This technique is called _re-exporting_ because we’re bringing an item\ninto scope but also making that item available for others to bring into their\nscope.\nListing 7-17 shows the code in Listing 7-11 with `use` in the root module\nchanged to `pub use`.\nListing 7-17: Making a name available for any code to use from a new scope with `pub use` (src/lib.rs)\n```rust,noplayground,test_harness\nmod front_of_house {\n pub mod hosting {\n pub fn add_to_waitlist() {}\n }\n}\n\npub use crate::front_of_house::hosting;\n\npub fn eat_at_restaurant() {\n hosting::add_to_waitlist();\n}\n```\nBefore this change, external code would have to call the `add_to_waitlist`\nfunction by using the path\n`restaurant::front_of_house::hosting::add_to_waitlist()`, which also would have\nrequired the `front_of_house` module to be marked as `pub`. Now that this `pub\nuse` has re-exported the `hosting` module from the root module, external code\ncan use the path `restaurant::hosting::add_to_waitlist()` instead.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Bringing Paths Into Scope with the `use` Keyword", "heading_path": ["Bringing Paths into Scope with the `use` Keyword", "Re-exporting Names with `pub use`"], "path": "ch07-04-bringing-paths-into-scope-with-the-use-keyword.md", "url": "https://doc.rust-lang.org/book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.html#re-exporting-names-with-pub-use", "has_code": true, "code_tags": ["rust,noplayground,test_harness"]}} {"id": "book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.md#re-exporting-names-with-pub-use-7", "text": "The Rust Programming Language › Bringing Paths into Scope with the `use` Keyword › Re-exporting Names with `pub use`\n\nRe-exporting is useful when the internal structure of your code is different\nfrom how programmers calling your code would think about the domain. For\nexample, in this restaurant metaphor, the people running the restaurant think\nabout “front of house” and “back of house.” But customers visiting a restaurant\nprobably won’t think about the parts of the restaurant in those terms. With `pub\nuse`, we can write our code with one structure but expose a different structure.\nDoing so makes our library well organized for programmers working on the library\nand programmers calling the library. We’ll look at another example of `pub use`\nand how it affects your crate’s documentation in “Exporting a Convenient Public\nAPI” in Chapter 14.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Bringing Paths Into Scope with the `use` Keyword", "heading_path": ["Bringing Paths into Scope with the `use` Keyword", "Re-exporting Names with `pub use`"], "path": "ch07-04-bringing-paths-into-scope-with-the-use-keyword.md", "url": "https://doc.rust-lang.org/book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.html#re-exporting-names-with-pub-use", "has_code": false, "code_tags": []}} {"id": "book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.md#using-external-packages-8", "text": "The Rust Programming Language › Bringing Paths into Scope with the `use` Keyword › Using External Packages\n\nIn Chapter 2, we programmed a guessing game project that used an external\npackage called `rand` to get random numbers. To use `rand` in our project, we\nadded this line to _Cargo.toml_:\nListing (Cargo.toml)\n```toml\nrand = \"0.10.1\"\n```\nAdding `rand` as a dependency in _Cargo.toml_ tells Cargo to download the\n`rand` package and any dependencies from crates.io and\nmake `rand` available to our project.\nThen, to bring `rand` definitions into the scope of our package, we added a\n`use` line starting with the name of the crate, `rand`, and listed the items we\nwanted to bring into scope. Recall that in “Generating a Random\nNumber” in Chapter 2, we brought items in the\n`rand::prelude` module into scope and called the `rand::rng` function:\n```rust,ignore\nuse rand::prelude::*;\n\nfn main() {\n let secret_number = rand::rng().random_range(1..=100);\n}\n```\nMembers of the Rust community have made many packages available at\ncrates.io, and pulling any of them into your package\ninvolves these same steps: listing them in your package’s _Cargo.toml_ file and\nusing `use` to bring items from their crates into scope.\nNote that the standard `std` library is also a crate that’s external to our\npackage. Because the standard library is shipped with the Rust language, we\ndon’t need to change _Cargo.toml_ to include `std`. But we do need to refer to\nit with `use` to bring items from there into our package’s scope. For example,\nwith `HashMap` we would use this line:\n```rust\nuse std::collections::HashMap;\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Bringing Paths Into Scope with the `use` Keyword", "heading_path": ["Bringing Paths into Scope with the `use` Keyword", "Using External Packages"], "path": "ch07-04-bringing-paths-into-scope-with-the-use-keyword.md", "url": "https://doc.rust-lang.org/book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.html#using-external-packages", "has_code": true, "code_tags": ["rust", "rust,ignore", "toml"]}} {"id": "book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.md#using-external-packages-9", "text": "The Rust Programming Language › Bringing Paths into Scope with the `use` Keyword › Using External Packages\n\nThis is an absolute path starting with `std`, the name of the standard library\ncrate.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Bringing Paths Into Scope with the `use` Keyword", "heading_path": ["Bringing Paths into Scope with the `use` Keyword", "Using External Packages"], "path": "ch07-04-bringing-paths-into-scope-with-the-use-keyword.md", "url": "https://doc.rust-lang.org/book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.html#using-external-packages", "has_code": false, "code_tags": []}} {"id": "book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.md#using-nested-paths-to-clean-up-use-lists-10", "text": "The Rust Programming Language › Bringing Paths into Scope with the `use` Keyword › Using Nested Paths to Clean Up `use` Lists\n\nIf we’re using multiple items defined in the same crate or same module, listing\neach item on its own line can take up a lot of vertical space in our files. For\nexample, these two `use` statements we had in the guessing game in Listing 2-4\nbring items from `std` into scope:\nListing (src/main.rs)\n```rust,ignore\n// --snip--\nuse std::cmp::Ordering;\nuse std::io;\n// --snip--\n```\nInstead, we can use nested paths to bring the same items into scope in one\nline. We do this by specifying the common part of the path, followed by two\ncolons, and then curly brackets around a list of the parts of the paths that\ndiffer, as shown in Listing 7-18.\nListing 7-18: Specifying a nested path to bring multiple items with the same prefix into scope (src/main.rs)\n```rust,ignore\n// --snip--\nuse std::{cmp::Ordering, io};\n// --snip--\n```\nIn bigger programs, bringing many items into scope from the same crate or\nmodule using nested paths can reduce the number of separate `use` statements\nneeded by a lot!\nWe can use a nested path at any level in a path, which is useful when combining\ntwo `use` statements that share a subpath. For example, Listing 7-19 shows two\n`use` statements: one that brings `std::io` into scope and one that brings\n`std::io::Write` into scope.\nListing 7-19: Two `use` statements where one is a subpath of the other (src/lib.rs)\n```rust,noplayground\nuse std::io;\nuse std::io::Write;\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Bringing Paths Into Scope with the `use` Keyword", "heading_path": ["Bringing Paths into Scope with the `use` Keyword", "Using Nested Paths to Clean Up `use` Lists"], "path": "ch07-04-bringing-paths-into-scope-with-the-use-keyword.md", "url": "https://doc.rust-lang.org/book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.html#using-nested-paths-to-clean-up-use-lists", "has_code": true, "code_tags": ["rust,ignore", "rust,noplayground"]}} {"id": "book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.md#using-nested-paths-to-clean-up-use-lists-11", "text": "The Rust Programming Language › Bringing Paths into Scope with the `use` Keyword › Using Nested Paths to Clean Up `use` Lists\n\nThe common part of these two paths is `std::io`, and that’s the complete first\npath. To merge these two paths into one `use` statement, we can use `self` in\nthe nested path, as shown in Listing 7-20.\nListing 7-20: Combining the paths in Listing 7-19 into one `use` statement (src/lib.rs)\n```rust,noplayground\nuse std::io::{self, Write};\n```\nThis line brings `std::io` and `std::io::Write` into scope.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Bringing Paths Into Scope with the `use` Keyword", "heading_path": ["Bringing Paths into Scope with the `use` Keyword", "Using Nested Paths to Clean Up `use` Lists"], "path": "ch07-04-bringing-paths-into-scope-with-the-use-keyword.md", "url": "https://doc.rust-lang.org/book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.html#using-nested-paths-to-clean-up-use-lists", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.md#importing-items-with-the-glob-operator-12", "text": "The Rust Programming Language › Bringing Paths into Scope with the `use` Keyword › Importing Items with the Glob Operator\n\nIf we want to bring _all_ public items defined in a path into scope, we can\nspecify that path followed by the `*` glob operator:\n```rust\nuse std::collections::*;\n```\nThis `use` statement brings all public items defined in `std::collections` into\nthe current scope. Be careful when using the glob operator! Glob can make it\nharder to tell what names are in scope and where a name used in your program\nwas defined. Additionally, if the dependency changes its definitions, what\nyou’ve imported changes as well, which may lead to compiler errors when you\nupgrade the dependency if the dependency adds a definition with the same name\nas a definition of yours in the same scope, for example.\nThe glob operator is often used when testing to bring everything under test into\nthe `tests` module; we’ll talk about that in “How to Write\nTests” in Chapter 11. The glob operator is also\nsometimes used as part of the prelude pattern: See the standard library\ndocumentation for more\ninformation on that pattern.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Bringing Paths Into Scope with the `use` Keyword", "heading_path": ["Bringing Paths into Scope with the `use` Keyword", "Importing Items with the Glob Operator"], "path": "ch07-04-bringing-paths-into-scope-with-the-use-keyword.md", "url": "https://doc.rust-lang.org/book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.html#importing-items-with-the-glob-operator", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch07-05-separating-modules-into-different-files.md#separating-modules-into-different-files-0", "text": "The Rust Programming Language › Separating Modules into Different Files\n\nSo far, all the examples in this chapter defined multiple modules in one file.\nWhen modules get large, you might want to move their definitions to a separate\nfile to make the code easier to navigate.\nFor example, let’s start from the code in Listing 7-17 that had multiple\nrestaurant modules. We’ll extract modules into files instead of having all the\nmodules defined in the crate root file. In this case, the crate root file is\n_src/lib.rs_, but this procedure also works with binary crates whose crate root\nfile is _src/main.rs_.\nFirst, we’ll extract the `front_of_house` module to its own file. Remove the\ncode inside the curly brackets for the `front_of_house` module, leaving only\nthe `mod front_of_house;` declaration, so that _src/lib.rs_ contains the code\nshown in Listing 7-21. Note that this won’t compile until we create the\n_src/front_of_house.rs_ file in Listing 7-22.\nListing 7-21: Declaring the `front_of_house` module whose body will be in *src/front_of_house.rs* (src/lib.rs)\n```rust,ignore,does_not_compile\nmod front_of_house;\n\npub use crate::front_of_house::hosting;\n\npub fn eat_at_restaurant() {\n hosting::add_to_waitlist();\n}\n```\nNext, place the code that was in the curly brackets into a new file named\n_src/front_of_house.rs_, as shown in Listing 7-22. The compiler knows to look\nin this file because it came across the module declaration in the crate root\nwith the name `front_of_house`.\nListing 7-22: Definitions inside the `front_of_house` module in *src/front_of_house.rs* (src/front_of_house.rs)\n```rust,ignore\npub mod hosting {\n pub fn add_to_waitlist() {}\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Separating Modules into Different Files", "heading_path": ["Separating Modules into Different Files"], "path": "ch07-05-separating-modules-into-different-files.md", "url": "https://doc.rust-lang.org/book/ch07-05-separating-modules-into-different-files.html#separating-modules-into-different-files", "has_code": true, "code_tags": ["rust,ignore", "rust,ignore,does_not_compile"]}} {"id": "book/ch07-05-separating-modules-into-different-files.md#separating-modules-into-different-files-1", "text": "The Rust Programming Language › Separating Modules into Different Files\n\nNote that you only need to load a file using a `mod` declaration _once_ in your\nmodule tree. Once the compiler knows the file is part of the project (and knows\nwhere in the module tree the code resides because of where you’ve put the `mod`\nstatement), other files in your project should refer to the loaded file’s code\nusing a path to where it was declared, as covered in the “Paths for Referring\nto an Item in the Module Tree” section. In other words,\n`mod` is _not_ an “include” operation that you may have seen in other\nprogramming languages.\nNext, we’ll extract the `hosting` module to its own file. The process is a bit\ndifferent because `hosting` is a child module of `front_of_house`, not of the\nroot module. We’ll place the file for `hosting` in a new directory that will be\nnamed for its ancestors in the module tree, in this case _src/front_of_house_.\nTo start moving `hosting`, we change _src/front_of_house.rs_ to contain only\nthe declaration of the `hosting` module:\nListing (src/front_of_house.rs)\n```rust,ignore\npub mod hosting;\n```\nThen, we create a _src/front_of_house_ directory and a _hosting.rs_ file to\ncontain the definitions made in the `hosting` module:\nListing (src/front_of_house/hosting.rs)\n```rust,ignore\npub fn add_to_waitlist() {}\n```\nIf we instead put _hosting.rs_ in the _src_ directory, the compiler would\nexpect the _hosting.rs_ code to be in a `hosting` module declared in the crate\nroot and not declared as a child of the `front_of_house` module. The\ncompiler’s rules for which files to check for which modules’ code mean the\ndirectories and files more closely match the module tree.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Separating Modules into Different Files", "heading_path": ["Separating Modules into Different Files"], "path": "ch07-05-separating-modules-into-different-files.md", "url": "https://doc.rust-lang.org/book/ch07-05-separating-modules-into-different-files.html#separating-modules-into-different-files", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch07-05-separating-modules-into-different-files.md#alternate-file-paths-2", "text": "The Rust Programming Language › Separating Modules into Different Files › Alternate File Paths\n\nSo far we’ve covered the most idiomatic file paths the Rust compiler uses,\nbut Rust also supports an older style of file path. For a module named\n`front_of_house` declared in the crate root, the compiler will look for the\nmodule’s code in:\n- _src/front_of_house.rs_ (what we covered)\n- _src/front_of_house/mod.rs_ (older style, still supported path)\nFor a module named `hosting` that is a submodule of `front_of_house`, the\ncompiler will look for the module’s code in:\n- _src/front_of_house/hosting.rs_ (what we covered)\n- _src/front_of_house/hosting/mod.rs_ (older style, still supported path)\nIf you use both styles for the same module, you’ll get a compiler error.\nUsing a mix of both styles for different modules in the same project is\nallowed but might be confusing for people navigating your project.\nThe main downside to the style that uses files named _mod.rs_ is that your\nproject can end up with many files named _mod.rs_, which can get confusing\nwhen you have them open in your editor at the same time.\nWe’ve moved each module’s code to a separate file, and the module tree remains\nthe same. The function calls in `eat_at_restaurant` will work without any\nmodification, even though the definitions live in different files. This\ntechnique lets you move modules to new files as they grow in size.\nNote that the `pub use crate::front_of_house::hosting` statement in\n_src/lib.rs_ also hasn’t changed, nor does `use` have any impact on what files\nare compiled as part of the crate. The `mod` keyword declares modules, and Rust\nlooks in a file with the same name as the module for the code that goes into\nthat module.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Separating Modules into Different Files", "heading_path": ["Separating Modules into Different Files", "Alternate File Paths"], "path": "ch07-05-separating-modules-into-different-files.md", "url": "https://doc.rust-lang.org/book/ch07-05-separating-modules-into-different-files.html#alternate-file-paths", "has_code": false, "code_tags": []}} {"id": "book/ch07-05-separating-modules-into-different-files.md#summary-3", "text": "The Rust Programming Language › Summary\n\nRust lets you split a package into multiple crates and a crate into modules so\nthat you can refer to items defined in one module from another module. You can\ndo this by specifying absolute or relative paths. These paths can be brought\ninto scope with a `use` statement so that you can use a shorter path for\nmultiple uses of the item in that scope. Module code is private by default, but\nyou can make definitions public by adding the `pub` keyword.\nIn the next chapter, we’ll look at some collection data structures in the\nstandard library that you can use in your neatly organized code.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Separating Modules into Different Files", "heading_path": ["Summary"], "path": "ch07-05-separating-modules-into-different-files.md", "url": "https://doc.rust-lang.org/book/ch07-05-separating-modules-into-different-files.html#summary", "has_code": false, "code_tags": []}} {"id": "book/ch08-00-common-collections.md#common-collections-0", "text": "The Rust Programming Language › Common Collections\n\nRust’s standard library includes a number of very useful data structures called\n_collections_. Most other data types represent one specific value, but\ncollections can contain multiple values. Unlike the built-in array and tuple\ntypes, the data that these collections point to is stored on the heap, which\nmeans the amount of data does not need to be known at compile time and can grow\nor shrink as the program runs. Each kind of collection has different\ncapabilities and costs, and choosing an appropriate one for your current\nsituation is a skill you’ll develop over time. In this chapter, we’ll discuss\nthree collections that are used very often in Rust programs:\n- A _vector_ allows you to store a variable number of values next to each other.\n- A _string_ is a collection of characters. We’ve mentioned the `String` type\n previously, but in this chapter, we’ll talk about it in depth.\n- A _hash map_ allows you to associate a value with a specific key. It’s a\n particular implementation of the more general data structure called a _map_.\nTo learn about the other kinds of collections provided by the standard library,\nsee the documentation.\nWe’ll discuss how to create and update vectors, strings, and hash maps, as well\nas what makes each special.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Common Collections", "heading_path": ["Common Collections"], "path": "ch08-00-common-collections.md", "url": "https://doc.rust-lang.org/book/ch08-00-common-collections.html#common-collections", "has_code": false, "code_tags": []}} {"id": "book/ch08-01-vectors.md#storing-lists-of-values-with-vectors-0", "text": "The Rust Programming Language › Storing Lists of Values with Vectors\n\nThe first collection type we’ll look at is `Vec`, also known as a vector.\nVectors allow you to store more than one value in a single data structure that\nputs all the values next to each other in memory. Vectors can only store values\nof the same type. They are useful when you have a list of items, such as the\nlines of text in a file or the prices of items in a shopping cart.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing Lists of Values with Vectors", "heading_path": ["Storing Lists of Values with Vectors"], "path": "ch08-01-vectors.md", "url": "https://doc.rust-lang.org/book/ch08-01-vectors.html#storing-lists-of-values-with-vectors", "has_code": false, "code_tags": []}} {"id": "book/ch08-01-vectors.md#creating-a-new-vector-1", "text": "The Rust Programming Language › Storing Lists of Values with Vectors › Creating a New Vector\n\nTo create a new, empty vector, we call the `Vec::new` function, as shown in\nListing 8-1.\nListing 8-1: Creating a new, empty vector to hold values of type `i32`\n```rust\n let v: Vec = Vec::new();\n```\nNote that we added a type annotation here. Because we aren’t inserting any\nvalues into this vector, Rust doesn’t know what kind of elements we intend to\nstore. This is an important point. Vectors are implemented using generics;\nwe’ll cover how to use generics with your own types in Chapter 10. For now,\nknow that the `Vec` type provided by the standard library can hold any type.\nWhen we create a vector to hold a specific type, we can specify the type within\nangle brackets. In Listing 8-1, we’ve told Rust that the `Vec` in `v` will\nhold elements of the `i32` type.\nMore often, you’ll create a `Vec` with initial values, and Rust will infer\nthe type of value you want to store, so you rarely need to do this type\nannotation. Rust conveniently provides the `vec!` macro, which will create a\nnew vector that holds the values you give it. Listing 8-2 creates a new\n`Vec` that holds the values `1`, `2`, and `3`. The integer type is `i32`\nbecause that’s the default integer type, as we discussed in the “Data\nTypes” section of Chapter 3.\nListing 8-2: Creating a new vector containing values\n```rust\n let v = vec![1, 2, 3];\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing Lists of Values with Vectors", "heading_path": ["Storing Lists of Values with Vectors", "Creating a New Vector"], "path": "ch08-01-vectors.md", "url": "https://doc.rust-lang.org/book/ch08-01-vectors.html#creating-a-new-vector", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch08-01-vectors.md#creating-a-new-vector-2", "text": "The Rust Programming Language › Storing Lists of Values with Vectors › Creating a New Vector\n\nBecause we’ve given initial `i32` values, Rust can infer that the type of `v`\nis `Vec`, and the type annotation isn’t necessary. Next, we’ll look at how\nto modify a vector.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing Lists of Values with Vectors", "heading_path": ["Storing Lists of Values with Vectors", "Creating a New Vector"], "path": "ch08-01-vectors.md", "url": "https://doc.rust-lang.org/book/ch08-01-vectors.html#creating-a-new-vector", "has_code": false, "code_tags": []}} {"id": "book/ch08-01-vectors.md#updating-a-vector-3", "text": "The Rust Programming Language › Storing Lists of Values with Vectors › Updating a Vector\n\nTo create a vector and then add elements to it, we can use the `push` method,\nas shown in Listing 8-3.\nListing 8-3: Using the `push` method to add values to a vector\n```rust\n let mut v = Vec::new();\n\n v.push(5);\n v.push(6);\n v.push(7);\n v.push(8);\n```\nAs with any variable, if we want to be able to change its value, we need to\nmake it mutable using the `mut` keyword, as discussed in Chapter 3. The numbers\nwe place inside are all of type `i32`, and Rust infers this from the data, so\nwe don’t need the `Vec` annotation.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing Lists of Values with Vectors", "heading_path": ["Storing Lists of Values with Vectors", "Updating a Vector"], "path": "ch08-01-vectors.md", "url": "https://doc.rust-lang.org/book/ch08-01-vectors.html#updating-a-vector", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch08-01-vectors.md#reading-elements-of-vectors-4", "text": "The Rust Programming Language › Storing Lists of Values with Vectors › Reading Elements of Vectors\n\nThere are two ways to reference a value stored in a vector: via indexing or by\nusing the `get` method. In the following examples, we’ve annotated the types of\nthe values that are returned from these functions for extra clarity.\nListing 8-4 shows both methods of accessing a value in a vector, with indexing\nsyntax and the `get` method.\nListing 8-4: Using indexing syntax and using the `get` method to access an item in a vector\n```rust\n let v = vec![1, 2, 3, 4, 5];\n\n let third: &i32 = &v[2];\n println!(\"The third element is {third}\");\n\n let third: Option<&i32> = v.get(2);\n match third {\n Some(third) => println!(\"The third element is {third}\"),\n None => println!(\"There is no third element.\"),\n }\n```\nNote a few details here. We use the index value of `2` to get the third element\nbecause vectors are indexed by number, starting at zero. Using `&` and `[]`\ngives us a reference to the element at the index value. When we use the `get`\nmethod with the index passed as an argument, we get an `Option<&T>` that we can\nuse with `match`.\nRust provides these two ways to reference an element so that you can choose how\nthe program behaves when you try to use an index value outside the range of\nexisting elements. As an example, let’s see what happens when we have a vector\nof five elements and then we try to access an element at index 100 with each\ntechnique, as shown in Listing 8-5.\nListing 8-5: Attempting to access the element at index 100 in a vector containing five elements", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing Lists of Values with Vectors", "heading_path": ["Storing Lists of Values with Vectors", "Reading Elements of Vectors"], "path": "ch08-01-vectors.md", "url": "https://doc.rust-lang.org/book/ch08-01-vectors.html#reading-elements-of-vectors", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch08-01-vectors.md#reading-elements-of-vectors-5", "text": "The Rust Programming Language › Storing Lists of Values with Vectors › Reading Elements of Vectors\n\n```rust,should_panic,panics\n let v = vec![1, 2, 3, 4, 5];\n\n let does_not_exist = &v[100];\n let does_not_exist = v.get(100);\n```\nWhen we run this code, the first `[]` method will cause the program to panic\nbecause it references a nonexistent element. This method is best used when you\nwant your program to crash if there’s an attempt to access an element past the\nend of the vector.\nWhen the `get` method is passed an index that is outside the vector, it returns\n`None` without panicking. You would use this method if accessing an element\nbeyond the range of the vector may happen occasionally under normal\ncircumstances. Your code will then have logic to handle having either\n`Some(&element)` or `None`, as discussed in Chapter 6. For example, the index\ncould be coming from a person entering a number. If they accidentally enter a\nnumber that’s too large and the program gets a `None` value, you could tell the\nuser how many items are in the current vector and give them another chance to\nenter a valid value. That would be more user-friendly than crashing the program\ndue to a typo!\nWhen the program has a valid reference, the borrow checker enforces the\nownership and borrowing rules (covered in Chapter 4) to ensure that this\nreference and any other references to the contents of the vector remain valid.\nRecall the rule that states you can’t have mutable and immutable references in\nthe same scope. That rule applies in Listing 8-6, where we hold an immutable\nreference to the first element in a vector and try to add an element to the\nend. This program won’t work if we also try to refer to that element later in\nthe function.\nListing 8-6: Attempting to add an element to a vector while holding a reference to an item", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing Lists of Values with Vectors", "heading_path": ["Storing Lists of Values with Vectors", "Reading Elements of Vectors"], "path": "ch08-01-vectors.md", "url": "https://doc.rust-lang.org/book/ch08-01-vectors.html#reading-elements-of-vectors", "has_code": true, "code_tags": ["rust,should_panic,panics"]}} {"id": "book/ch08-01-vectors.md#reading-elements-of-vectors-6", "text": "The Rust Programming Language › Storing Lists of Values with Vectors › Reading Elements of Vectors\n\n```rust,ignore,does_not_compile\n let mut v = vec![1, 2, 3, 4, 5];\n\n let first = &v[0];\n\n v.push(6);\n\n println!(\"The first element is: {first}\");\n```\nCompiling this code will result in this error:\n```console\n$ cargo run\n Compiling collections v0.1.0 (file:///projects/collections)\nerror[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable\n --> src/main.rs:6:5\n |\n4 | let first = &v[0];\n | - immutable borrow occurs here\n5 |\n6 | v.push(6);\n | ^^^^^^^^^ mutable borrow occurs here\n7 |\n8 | println!(\"The first element is: {first}\");\n | ----- immutable borrow later used here\n\nFor more information about this error, try `rustc --explain E0502`.\nerror: could not compile `collections` (bin \"collections\") due to 1 previous error\n```\nThe code in Listing 8-6 might look like it should work: Why should a reference\nto the first element care about changes at the end of the vector? This error is\ndue to the way vectors work: Because vectors put the values next to each other\nin memory, adding a new element onto the end of the vector might require\nallocating new memory and copying the old elements to the new space, if there\nisn’t enough room to put all the elements next to each other where the vector\nis currently stored. In that case, the reference to the first element would be\npointing to deallocated memory. The borrowing rules prevent programs from\nending up in that situation.\nNote: For more on the implementation details of the `Vec` type, see “The\nRustonomicon”.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing Lists of Values with Vectors", "heading_path": ["Storing Lists of Values with Vectors", "Reading Elements of Vectors"], "path": "ch08-01-vectors.md", "url": "https://doc.rust-lang.org/book/ch08-01-vectors.html#reading-elements-of-vectors", "has_code": true, "code_tags": ["console", "rust,ignore,does_not_compile"]}} {"id": "book/ch08-01-vectors.md#iterating-over-the-values-in-a-vector-7", "text": "The Rust Programming Language › Storing Lists of Values with Vectors › Iterating Over the Values in a Vector\n\nTo access each element in a vector in turn, we would iterate through all of the\nelements rather than use indices to access one at a time. Listing 8-7 shows how\nto use a `for` loop to get immutable references to each element in a vector of\n`i32` values and print them.\nListing 8-7: Printing each element in a vector by iterating over the elements using a `for` loop\n```rust\n let v = vec![100, 32, 57];\n for i in &v {\n println!(\"{i}\");\n }\n```\nWe can also iterate over mutable references to each element in a mutable vector\nin order to make changes to all the elements. The `for` loop in Listing 8-8\nwill add `50` to each element.\nListing 8-8: Iterating over mutable references to elements in a vector\n```rust\n let mut v = vec![100, 32, 57];\n for i in &mut v {\n *i += 50;\n }\n```\nTo change the value that the mutable reference refers to, we have to use the\n`*` dereference operator to get to the value in `i` before we can use the `+=`\noperator. We’ll talk more about the dereference operator in the “Following the\nReference to the Value” section of Chapter 15.\nIterating over a vector, whether immutably or mutably, is safe because of the\nborrow checker’s rules. If we attempted to insert or remove items in the `for`\nloop bodies in Listing 8-7 and Listing 8-8, we would get a compiler error\nsimilar to the one we got with the code in Listing 8-6. The reference to the\nvector that the `for` loop holds prevents simultaneous modification of the\nwhole vector.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing Lists of Values with Vectors", "heading_path": ["Storing Lists of Values with Vectors", "Iterating Over the Values in a Vector"], "path": "ch08-01-vectors.md", "url": "https://doc.rust-lang.org/book/ch08-01-vectors.html#iterating-over-the-values-in-a-vector", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch08-01-vectors.md#using-an-enum-to-store-multiple-types-8", "text": "The Rust Programming Language › Storing Lists of Values with Vectors › Using an Enum to Store Multiple Types\n\nVectors can only store values that are of the same type. This can be\ninconvenient; there are definitely use cases for needing to store a list of\nitems of different types. Fortunately, the variants of an enum are defined\nunder the same enum type, so when we need one type to represent elements of\ndifferent types, we can define and use an enum!\nFor example, say we want to get values from a row in a spreadsheet in which\nsome of the columns in the row contain integers, some floating-point numbers,\nand some strings. We can define an enum whose variants will hold the different\nvalue types, and all the enum variants will be considered the same type: that\nof the enum. Then, we can create a vector to hold that enum and so, ultimately,\nhold different types. We’ve demonstrated this in Listing 8-9.\nListing 8-9: Defining an enum to store values of different types in one vector\n```rust\n enum SpreadsheetCell {\n Int(i32),\n Float(f64),\n Text(String),\n }\n\n let row = vec![\n SpreadsheetCell::Int(3),\n SpreadsheetCell::Text(String::from(\"blue\")),\n SpreadsheetCell::Float(10.12),\n ];\n```\nRust needs to know what types will be in the vector at compile time so that it\nknows exactly how much memory on the heap will be needed to store each element.\nWe must also be explicit about what types are allowed in this vector. If Rust\nallowed a vector to hold any type, there would be a chance that one or more of\nthe types would cause errors with the operations performed on the elements of\nthe vector. Using an enum plus a `match` expression means that Rust will ensure\nat compile time that every possible case is handled, as discussed in Chapter 6.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing Lists of Values with Vectors", "heading_path": ["Storing Lists of Values with Vectors", "Using an Enum to Store Multiple Types"], "path": "ch08-01-vectors.md", "url": "https://doc.rust-lang.org/book/ch08-01-vectors.html#using-an-enum-to-store-multiple-types", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch08-01-vectors.md#using-an-enum-to-store-multiple-types-9", "text": "The Rust Programming Language › Storing Lists of Values with Vectors › Using an Enum to Store Multiple Types\n\nIf you don’t know the exhaustive set of types a program will get at runtime to\nstore in a vector, the enum technique won’t work. Instead, you can use a trait\nobject, which we’ll cover in Chapter 18.\nNow that we’ve discussed some of the most common ways to use vectors, be sure\nto review the API documentation for all of the many\nuseful methods defined on `Vec` by the standard library. For example, in\naddition to `push`, a `pop` method removes and returns the last element.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing Lists of Values with Vectors", "heading_path": ["Storing Lists of Values with Vectors", "Using an Enum to Store Multiple Types"], "path": "ch08-01-vectors.md", "url": "https://doc.rust-lang.org/book/ch08-01-vectors.html#using-an-enum-to-store-multiple-types", "has_code": false, "code_tags": []}} {"id": "book/ch08-01-vectors.md#dropping-a-vector-drops-its-elements-10", "text": "The Rust Programming Language › Storing Lists of Values with Vectors › Dropping a Vector Drops Its Elements\n\nLike any other `struct`, a vector is freed when it goes out of scope, as\nannotated in Listing 8-10.\nListing 8-10: Showing where the vector and its elements are dropped\n```rust\n {\n let v = vec![1, 2, 3, 4];\n\n // do stuff with v\n } // <- v goes out of scope and is freed here\n```\nWhen the vector gets dropped, all of its contents are also dropped, meaning the\nintegers it holds will be cleaned up. The borrow checker ensures that any\nreferences to contents of a vector are only used while the vector itself is\nvalid.\nLet’s move on to the next collection type: `String`!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing Lists of Values with Vectors", "heading_path": ["Storing Lists of Values with Vectors", "Dropping a Vector Drops Its Elements"], "path": "ch08-01-vectors.md", "url": "https://doc.rust-lang.org/book/ch08-01-vectors.html#dropping-a-vector-drops-its-elements", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch08-02-strings.md#storing-utf-8-encoded-text-with-strings-0", "text": "The Rust Programming Language › Storing UTF-8 Encoded Text with Strings\n\nWe talked about strings in Chapter 4, but we’ll look at them in more depth now.\nNew Rustaceans commonly get stuck on strings for a combination of three\nreasons: Rust’s propensity for exposing possible errors, strings being a more\ncomplicated data structure than many programmers give them credit for, and\nUTF-8. These factors combine in a way that can seem difficult when you’re\ncoming from other programming languages.\nWe discuss strings in the context of collections because strings are\nimplemented as a collection of bytes, plus some methods to provide useful\nfunctionality when those bytes are interpreted as text. In this section, we’ll\ntalk about the operations on `String` that every collection type has, such as\ncreating, updating, and reading. We’ll also discuss the ways in which `String`\nis different from the other collections, namely, how indexing into a `String` is\ncomplicated by the differences between how people and computers interpret\n`String` data.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing UTF-8 Encoded Text with Strings", "heading_path": ["Storing UTF-8 Encoded Text with Strings"], "path": "ch08-02-strings.md", "url": "https://doc.rust-lang.org/book/ch08-02-strings.html#storing-utf-8-encoded-text-with-strings", "has_code": false, "code_tags": []}} {"id": "book/ch08-02-strings.md#defining-strings-1", "text": "The Rust Programming Language › Storing UTF-8 Encoded Text with Strings › Defining Strings\n\nWe’ll first define what we mean by the term _string_. Rust has only one string\ntype in the core language, which is the string slice `str` that is usually seen\nin its borrowed form, `&str`. In Chapter 4, we talked about string slices,\nwhich are references to some UTF-8 encoded string data stored elsewhere. String\nliterals, for example, are stored in the program’s binary and are therefore\nstring slices.\nThe `String` type, which is provided by Rust’s standard library rather than\ncoded into the core language, is a growable, mutable, owned, UTF-8 encoded\nstring type. When Rustaceans refer to “strings” in Rust, they might be\nreferring to either the `String` or the string slice `&str` types, not just one\nof those types. Although this section is largely about `String`, both types are\nused heavily in Rust’s standard library, and both `String` and string slices\nare UTF-8 encoded.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing UTF-8 Encoded Text with Strings", "heading_path": ["Storing UTF-8 Encoded Text with Strings", "Defining Strings"], "path": "ch08-02-strings.md", "url": "https://doc.rust-lang.org/book/ch08-02-strings.html#defining-strings", "has_code": false, "code_tags": []}} {"id": "book/ch08-02-strings.md#creating-a-new-string-2", "text": "The Rust Programming Language › Storing UTF-8 Encoded Text with Strings › Creating a New String\n\nMany of the same operations available with `Vec` are available with `String`\nas well because `String` is actually implemented as a wrapper around a vector\nof bytes with some extra guarantees, restrictions, and capabilities. An example\nof a function that works the same way with `Vec` and `String` is the `new`\nfunction to create an instance, shown in Listing 8-11.\nListing 8-11: Creating a new, empty `String`\n```rust\n let mut s = String::new();\n```\nThis line creates a new, empty string called `s`, into which we can then load\ndata. Often, we’ll have some initial data with which we want to start the\nstring. For that, we use the `to_string` method, which is available on any type\nthat implements the `Display` trait, as string literals do. Listing 8-12 shows\ntwo examples.\nListing 8-12: Using the `to_string` method to create a `String` from a string literal\n```rust\n let data = \"initial contents\";\n\n let s = data.to_string();\n\n // The method also works on a literal directly:\n let s = \"initial contents\".to_string();\n```\nThis code creates a string containing `initial contents`.\nWe can also use the function `String::from` to create a `String` from a string\nliteral. The code in Listing 8-13 is equivalent to the code in Listing 8-12\nthat uses `to_string`.\nListing 8-13: Using the `String::from` function to create a `String` from a string literal\n```rust\n let s = String::from(\"initial contents\");\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing UTF-8 Encoded Text with Strings", "heading_path": ["Storing UTF-8 Encoded Text with Strings", "Creating a New String"], "path": "ch08-02-strings.md", "url": "https://doc.rust-lang.org/book/ch08-02-strings.html#creating-a-new-string", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch08-02-strings.md#creating-a-new-string-3", "text": "The Rust Programming Language › Storing UTF-8 Encoded Text with Strings › Creating a New String\n\nBecause strings are used for so many things, we can use many different generic\nAPIs for strings, providing us with a lot of options. Some of them can seem\nredundant, but they all have their place! In this case, `String::from` and\n`to_string` do the same thing, so which one you choose is a matter of style and\nreadability.\nRemember that strings are UTF-8 encoded, so we can include any properly encoded\ndata in them, as shown in Listing 8-14.\nListing 8-14: Storing greetings in different languages in strings\n```rust\n let hello = String::from(\"السلام عليكم\");\n let hello = String::from(\"Dobrý den\");\n let hello = String::from(\"Hello\");\n let hello = String::from(\"שלום\");\n let hello = String::from(\"नमस्ते\");\n let hello = String::from(\"こんにちは\");\n let hello = String::from(\"안녕하세요\");\n let hello = String::from(\"你好\");\n let hello = String::from(\"Olá\");\n let hello = String::from(\"Здравствуйте\");\n let hello = String::from(\"Hola\");\n```\nAll of these are valid `String` values.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing UTF-8 Encoded Text with Strings", "heading_path": ["Storing UTF-8 Encoded Text with Strings", "Creating a New String"], "path": "ch08-02-strings.md", "url": "https://doc.rust-lang.org/book/ch08-02-strings.html#creating-a-new-string", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch08-02-strings.md#concatenating-with--or-format-4", "text": "The Rust Programming Language › Storing UTF-8 Encoded Text with Strings › Updating a String › Concatenating with `+` or `format!`\n\nA `String` can grow in size and its contents can change, just like the contents\nof a `Vec`, if you push more data into it. In addition, you can conveniently\nuse the `+` operator or the `format!` macro to concatenate `String` values.\nWe can grow a `String` by using the `push_str` method to append a string slice,\nas shown in Listing 8-15.\nListing 8-15: Appending a string slice to a `String` using the `push_str` method\n```rust\n let mut s = String::from(\"foo\");\n s.push_str(\"bar\");\n```\nAfter these two lines, `s` will contain `foobar`. The `push_str` method takes a\nstring slice because we don’t necessarily want to take ownership of the\nparameter. For example, in the code in Listing 8-16, we want to be able to use\n`s2` after appending its contents to `s1`.\nListing 8-16: Using a string slice after appending its contents to a `String`\n```rust\n let mut s1 = String::from(\"foo\");\n let s2 = \"bar\";\n s1.push_str(s2);\n println!(\"s2 is {s2}\");\n```\nIf the `push_str` method took ownership of `s2`, we wouldn’t be able to print\nits value on the last line. However, this code works as we’d expect!\nThe `push` method takes a single character as a parameter and adds it to the\n`String`. Listing 8-17 adds the letter _l_ to a `String` using the `push`\nmethod.\nListing 8-17: Adding one character to a `String` value using `push`\n```rust\n let mut s = String::from(\"lo\");\n s.push('l');\n```\nAs a result, `s` will contain `lol`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing UTF-8 Encoded Text with Strings", "heading_path": ["Storing UTF-8 Encoded Text with Strings", "Updating a String", "Concatenating with `+` or `format!`"], "path": "ch08-02-strings.md", "url": "https://doc.rust-lang.org/book/ch08-02-strings.html#concatenating-with--or-format", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch08-02-strings.md#concatenating-with--or-format-5", "text": "The Rust Programming Language › Storing UTF-8 Encoded Text with Strings › Updating a String › Concatenating with `+` or `format!`\n\nOften, you’ll want to combine two existing strings. One way to do so is to use\nthe `+` operator, as shown in Listing 8-18.\nListing 8-18: Using the `+` operator to combine two `String` values into a new `String` value\n```rust\n let s1 = String::from(\"Hello, \");\n let s2 = String::from(\"world!\");\n let s3 = s1 + &s2; // note s1 has been moved here and can no longer be used\n```\nThe string `s3` will contain `Hello, world!`. The reason `s1` is no longer\nvalid after the addition, and the reason we used a reference to `s2`, has to do\nwith the signature of the method that’s called when we use the `+` operator.\nThe `+` operator uses the `add` method, whose signature looks something like\nthis:\n```rust,ignore\nfn add(self, s: &str) -> String {\n```\nIn the standard library, you’ll see `add` defined using generics and associated\ntypes. Here, we’ve substituted in concrete types, which is what happens when we\ncall this method with `String` values. We’ll discuss generics in Chapter 10.\nThis signature gives us the clues we need in order to understand the tricky\nbits of the `+` operator.\nFirst, `s2` has an `&`, meaning that we’re adding a reference of the second\nstring to the first string. This is because of the `s` parameter in the `add`\nfunction: We can only add a string slice to a `String`; we can’t add two\n`String` values together. But wait—the type of `&s2` is `&String`, not `&str`,\nas specified in the second parameter to `add`. So, why does Listing 8-18\ncompile?", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing UTF-8 Encoded Text with Strings", "heading_path": ["Storing UTF-8 Encoded Text with Strings", "Updating a String", "Concatenating with `+` or `format!`"], "path": "ch08-02-strings.md", "url": "https://doc.rust-lang.org/book/ch08-02-strings.html#concatenating-with--or-format", "has_code": true, "code_tags": ["rust", "rust,ignore"]}} {"id": "book/ch08-02-strings.md#concatenating-with--or-format-6", "text": "The Rust Programming Language › Storing UTF-8 Encoded Text with Strings › Updating a String › Concatenating with `+` or `format!`\n\nThe reason we’re able to use `&s2` in the call to `add` is that the compiler\ncan coerce the `&String` argument into a `&str`. When we call the `add` method,\nRust uses a deref coercion, which here turns `&s2` into `&s2[..]`. We’ll\ndiscuss deref coercion in more depth in Chapter 15. Because `add` does not take\nownership of the `s` parameter, `s2` will still be a valid `String` after this\noperation.\nSecond, we can see in the signature that `add` takes ownership of `self`\nbecause `self` does _not_ have an `&`. This means `s1` in Listing 8-18 will be\nmoved into the `add` call and will no longer be valid after that. So, although\n`let s3 = s1 + &s2;` looks like it will copy both strings and create a new one,\nthis statement actually takes ownership of `s1`, appends a copy of the contents\nof `s2`, and then returns ownership of the result. In other words, it looks\nlike it’s making a lot of copies, but it isn’t; the implementation is more\nefficient than copying.\nIf we need to concatenate multiple strings, the behavior of the `+` operator\ngets unwieldy:\n```rust\n let s1 = String::from(\"tic\");\n let s2 = String::from(\"tac\");\n let s3 = String::from(\"toe\");\n\n let s = s1 + \"-\" + &s2 + \"-\" + &s3;\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing UTF-8 Encoded Text with Strings", "heading_path": ["Storing UTF-8 Encoded Text with Strings", "Updating a String", "Concatenating with `+` or `format!`"], "path": "ch08-02-strings.md", "url": "https://doc.rust-lang.org/book/ch08-02-strings.html#concatenating-with--or-format", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch08-02-strings.md#concatenating-with--or-format-7", "text": "The Rust Programming Language › Storing UTF-8 Encoded Text with Strings › Updating a String › Concatenating with `+` or `format!`\n\nAt this point, `s` will be `tic-tac-toe`. With all of the `+` and `\"`\ncharacters, it’s difficult to see what’s going on. For combining strings in\nmore complicated ways, we can instead use the `format!` macro:\n```rust\n let s1 = String::from(\"tic\");\n let s2 = String::from(\"tac\");\n let s3 = String::from(\"toe\");\n\n let s = format!(\"{s1}-{s2}-{s3}\");\n```\nThis code also sets `s` to `tic-tac-toe`. The `format!` macro works like\n`println!`, but instead of printing the output to the screen, it returns a\n`String` with the contents. The version of the code using `format!` is much\neasier to read, and the code generated by the `format!` macro uses references\nso that this call doesn’t take ownership of any of its parameters.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing UTF-8 Encoded Text with Strings", "heading_path": ["Storing UTF-8 Encoded Text with Strings", "Updating a String", "Concatenating with `+` or `format!`"], "path": "ch08-02-strings.md", "url": "https://doc.rust-lang.org/book/ch08-02-strings.html#concatenating-with--or-format", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch08-02-strings.md#indexing-into-strings-8", "text": "The Rust Programming Language › Storing UTF-8 Encoded Text with Strings › Indexing into Strings\n\nIn many other programming languages, accessing individual characters in a\nstring by referencing them by index is a valid and common operation. However,\nif you try to access parts of a `String` using indexing syntax in Rust, you’ll\nget an error. Consider the invalid code in Listing 8-19.\nListing 8-19: Attempting to use indexing syntax with a `String`\n```rust,ignore,does_not_compile\n let s1 = String::from(\"hi\");\n let h = s1[0];\n```\nThis code will result in the following error:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing UTF-8 Encoded Text with Strings", "heading_path": ["Storing UTF-8 Encoded Text with Strings", "Indexing into Strings"], "path": "ch08-02-strings.md", "url": "https://doc.rust-lang.org/book/ch08-02-strings.html#indexing-into-strings", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch08-02-strings.md#internal-representation-9", "text": "The Rust Programming Language › Storing UTF-8 Encoded Text with Strings › Indexing into Strings › Internal Representation\n\n```console\n$ cargo run\n Compiling collections v0.1.0 (file:///projects/collections)\nerror[E0277]: the type `str` cannot be indexed by `{integer}`\n --> src/main.rs:3:16\n |\n3 | let h = s1[0];\n | ^ string indices are ranges of `usize`\n |\n = help: the trait `SliceIndex` is not implemented for `{integer}`\n = note: you can use `.chars().nth()` or `.bytes().nth()`\n for more information, see chapter 8 in The Book: \nhelp: `usize` implements trait `SliceIndex`\n --> /rustc/2d8144b7880597b6e6d3dfd63a9a9efae3f533d3/library/core/src/slice/index.rs:214:0\n |\n = note: `SliceIndex<[T]>`\n --> /rustc/2d8144b7880597b6e6d3dfd63a9a9efae3f533d3/library/core/src/bstr/traits.rs:197:0\n |\n = note: `SliceIndex`\n = note: required for `String` to implement `Index<{integer}>`\n\nFor more information about this error, try `rustc --explain E0277`.\nerror: could not compile `collections` (bin \"collections\") due to 1 previous error\n```\nThe error tells the story: Rust strings don’t support indexing. But why not? To\nanswer that question, we need to discuss how Rust stores strings in memory.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing UTF-8 Encoded Text with Strings", "heading_path": ["Storing UTF-8 Encoded Text with Strings", "Indexing into Strings", "Internal Representation"], "path": "ch08-02-strings.md", "url": "https://doc.rust-lang.org/book/ch08-02-strings.html#internal-representation", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch08-02-strings.md#internal-representation-10", "text": "The Rust Programming Language › Storing UTF-8 Encoded Text with Strings › Indexing into Strings › Internal Representation\n\nA `String` is a wrapper over a `Vec`. Let’s look at some of our properly\nencoded UTF-8 example strings from Listing 8-14. First, this one:\n```rust\n let hello = String::from(\"Hola\");\n```\nIn this case, `len` will be `4`, which means the vector storing the string\n`\"Hola\"` is 4 bytes long. Each of these letters takes 1 byte when encoded in\nUTF-8. The following line, however, may surprise you (note that this string\nbegins with the capital Cyrillic letter _Ze_, not the number 3):\n```rust\n let hello = String::from(\"Здравствуйте\");\n```\nIf you were asked how long the string is, you might say 12. In fact, Rust’s\nanswer is 24: That’s the number of bytes it takes to encode “Здравствуйте” in\nUTF-8, because each Unicode scalar value in that string takes 2 bytes of\nstorage. Therefore, an index into the string’s bytes will not always correlate\nto a valid Unicode scalar value. To demonstrate, consider this invalid Rust\ncode:\n```rust,ignore,does_not_compile\nlet hello = \"Здравствуйте\";\nlet answer = &hello[0];\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing UTF-8 Encoded Text with Strings", "heading_path": ["Storing UTF-8 Encoded Text with Strings", "Indexing into Strings", "Internal Representation"], "path": "ch08-02-strings.md", "url": "https://doc.rust-lang.org/book/ch08-02-strings.html#internal-representation", "has_code": true, "code_tags": ["rust", "rust,ignore,does_not_compile"]}} {"id": "book/ch08-02-strings.md#bytes-scalar-values-and-grapheme-clusters-11", "text": "The Rust Programming Language › Storing UTF-8 Encoded Text with Strings › Indexing into Strings › Bytes, Scalar Values, and Grapheme Clusters\n\nYou already know that `answer` will not be `З`, the first letter. When encoded\nin UTF-8, the first byte of `З` is `208` and the second is `151`, so it would\nseem that `answer` should in fact be `208`, but `208` is not a valid character\non its own. Returning `208` is likely not what a user would want if they asked\nfor the first letter of this string; however, that’s the only data that Rust\nhas at byte index 0. Users generally don’t want the byte value returned, even\nif the string contains only Latin letters: If `&\"hi\"[0]` were valid code that\nreturned the byte value, it would return `104`, not `h`.\nThe answer, then, is that to avoid returning an unexpected value and causing\nbugs that might not be discovered immediately, Rust doesn’t compile this code\nat all and prevents misunderstandings early in the development process.\nAnother point about UTF-8 is that there are actually three relevant ways to\nlook at strings from Rust’s perspective: as bytes, scalar values, and grapheme\nclusters (the closest thing to what we would call _letters_).\nIf we look at the Hindi word “नमस्ते” written in the Devanagari script, it is\nstored as a vector of `u8` values that looks like this:\n```text\n[224, 164, 168, 224, 164, 174, 224, 164, 184, 224, 165, 141, 224, 164, 164,\n224, 165, 135]\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing UTF-8 Encoded Text with Strings", "heading_path": ["Storing UTF-8 Encoded Text with Strings", "Indexing into Strings", "Bytes, Scalar Values, and Grapheme Clusters"], "path": "ch08-02-strings.md", "url": "https://doc.rust-lang.org/book/ch08-02-strings.html#bytes-scalar-values-and-grapheme-clusters", "has_code": true, "code_tags": ["text"]}} {"id": "book/ch08-02-strings.md#bytes-scalar-values-and-grapheme-clusters-12", "text": "The Rust Programming Language › Storing UTF-8 Encoded Text with Strings › Indexing into Strings › Bytes, Scalar Values, and Grapheme Clusters\n\nThat’s 18 bytes and is how computers ultimately store this data. If we look at\nthem as Unicode scalar values, which are what Rust’s `char` type is, those\nbytes look like this:\n```text\n['न', 'म', 'स', '्', 'त', 'े']\n```\nThere are six `char` values here, but the fourth and sixth are not letters:\nThey’re diacritics that don’t make sense on their own. Finally, if we look at\nthem as grapheme clusters, we’d get what a person would call the four letters\nthat make up the Hindi word:\n```text\n[\"न\", \"म\", \"स्\", \"ते\"]\n```\nRust provides different ways of interpreting the raw string data that computers\nstore so that each program can choose the interpretation it needs, no matter\nwhat human language the data is in.\nA final reason Rust doesn’t allow us to index into a `String` to get a\ncharacter is that indexing operations are expected to always take constant time\n(O(1)). But it isn’t possible to guarantee that performance with a `String`,\nbecause Rust would have to walk through the contents from the beginning to the\nindex to determine how many valid characters there were.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing UTF-8 Encoded Text with Strings", "heading_path": ["Storing UTF-8 Encoded Text with Strings", "Indexing into Strings", "Bytes, Scalar Values, and Grapheme Clusters"], "path": "ch08-02-strings.md", "url": "https://doc.rust-lang.org/book/ch08-02-strings.html#bytes-scalar-values-and-grapheme-clusters", "has_code": true, "code_tags": ["text"]}} {"id": "book/ch08-02-strings.md#slicing-strings-13", "text": "The Rust Programming Language › Storing UTF-8 Encoded Text with Strings › Slicing Strings\n\nIndexing into a string is often a bad idea because it’s not clear what the\nreturn type of the string-indexing operation should be: a byte value, a\ncharacter, a grapheme cluster, or a string slice. If you really need to use\nindices to create string slices, therefore, Rust asks you to be more specific.\nRather than indexing using `[]` with a single number, you can use `[]` with a\nrange to create a string slice containing particular bytes:\n```rust\nlet hello = \"Здравствуйте\";\n\nlet s = &hello[0..4];\n```\nHere, `s` will be a `&str` that contains the first 4 bytes of the string.\nEarlier, we mentioned that each of these characters was 2 bytes, which means\n`s` will be `Зд`.\nIf we were to try to slice only part of a character’s bytes with something like\n`&hello[0..1]`, Rust would panic at runtime in the same way as if an invalid\nindex were accessed in a vector:\n```console\n$ cargo run\n Compiling collections v0.1.0 (file:///projects/collections)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.43s\n Running `target/debug/collections`\n\nthread 'main' (6017738) panicked at src/main.rs:4:19:\nend byte index 1 is not a char boundary; it is inside 'З' (bytes 0..2 of string)\nnote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n```\nYou should use caution when creating string slices with ranges, because doing\nso can crash your program.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing UTF-8 Encoded Text with Strings", "heading_path": ["Storing UTF-8 Encoded Text with Strings", "Slicing Strings"], "path": "ch08-02-strings.md", "url": "https://doc.rust-lang.org/book/ch08-02-strings.html#slicing-strings", "has_code": true, "code_tags": ["console", "rust"]}} {"id": "book/ch08-02-strings.md#iterating-over-strings-14", "text": "The Rust Programming Language › Storing UTF-8 Encoded Text with Strings › Iterating Over Strings\n\nThe best way to operate on pieces of strings is to be explicit about whether\nyou want characters or bytes. For individual Unicode scalar values, use the\n`chars` method. Calling `chars` on “Зд” separates out and returns two values of\ntype `char`, and you can iterate over the result to access each element:\n```rust\nfor c in \"Зд\".chars() {\n println!(\"{c}\");\n}\n```\nThis code will print the following:\n```text\nЗ\nд\n```\nAlternatively, the `bytes` method returns each raw byte, which might be\nappropriate for your domain:\n```rust\nfor b in \"Зд\".bytes() {\n println!(\"{b}\");\n}\n```\nThis code will print the 4 bytes that make up this string:\n```text\n208\n151\n208\n180\n```\nBut be sure to remember that valid Unicode scalar values may be made up of more\nthan 1 byte.\nGetting grapheme clusters from strings, as with the Devanagari script, is\ncomplex, so this functionality is not provided by the standard library. Crates\nare available on crates.io if this is the\nfunctionality you need.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing UTF-8 Encoded Text with Strings", "heading_path": ["Storing UTF-8 Encoded Text with Strings", "Iterating Over Strings"], "path": "ch08-02-strings.md", "url": "https://doc.rust-lang.org/book/ch08-02-strings.html#iterating-over-strings", "has_code": true, "code_tags": ["rust", "text"]}} {"id": "book/ch08-02-strings.md#handling-the-complexities-of-strings-15", "text": "The Rust Programming Language › Storing UTF-8 Encoded Text with Strings › Handling the Complexities of Strings\n\nTo summarize, strings are complicated. Different programming languages make\ndifferent choices about how to present this complexity to the programmer. Rust\nhas chosen to make the correct handling of `String` data the default behavior\nfor all Rust programs, which means programmers have to put more thought into\nhandling UTF-8 data up front. This trade-off exposes more of the complexity of\nstrings than is apparent in other programming languages, but it prevents you\nfrom having to handle errors involving non-ASCII characters later in your\ndevelopment life cycle.\nThe good news is that the standard library offers a lot of functionality built\noff the `String` and `&str` types to help handle these complex situations\ncorrectly. Be sure to check out the documentation for useful methods like\n`contains` for searching in a string and `replace` for substituting parts of a\nstring with another string.\nLet’s switch to something a bit less complex: hash maps!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing UTF-8 Encoded Text with Strings", "heading_path": ["Storing UTF-8 Encoded Text with Strings", "Handling the Complexities of Strings"], "path": "ch08-02-strings.md", "url": "https://doc.rust-lang.org/book/ch08-02-strings.html#handling-the-complexities-of-strings", "has_code": false, "code_tags": []}} {"id": "book/ch08-03-hash-maps.md#storing-keys-with-associated-values-in-hash-maps-0", "text": "The Rust Programming Language › Storing Keys with Associated Values in Hash Maps\n\nThe last of our common collections is the hash map. The type `HashMap`\nstores a mapping of keys of type `K` to values of type `V` using a _hashing\nfunction_, which determines how it places these keys and values into memory.\nMany programming languages support this kind of data structure, but they often\nuse a different name, such as _hash_, _map_, _object_, _hash table_,\n_dictionary_, or _associative array_, just to name a few.\nHash maps are useful when you want to look up data not by using an index, as\nyou can with vectors, but by using a key that can be of any type. For example,\nin a game, you could keep track of each team’s score in a hash map in which\neach key is a team’s name and the values are each team’s score. Given a team\nname, you can retrieve its score.\nWe’ll go over the basic API of hash maps in this section, but many more goodies\nare hiding in the functions defined on `HashMap` by the standard library.\nAs always, check the standard library documentation for more information.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing Keys with Associated Values in Hash Maps", "heading_path": ["Storing Keys with Associated Values in Hash Maps"], "path": "ch08-03-hash-maps.md", "url": "https://doc.rust-lang.org/book/ch08-03-hash-maps.html#storing-keys-with-associated-values-in-hash-maps", "has_code": false, "code_tags": []}} {"id": "book/ch08-03-hash-maps.md#creating-a-new-hash-map-1", "text": "The Rust Programming Language › Storing Keys with Associated Values in Hash Maps › Creating a New Hash Map\n\nOne way to create an empty hash map is to use `new` and to add elements with\n`insert`. In Listing 8-20, we’re keeping track of the scores of two teams whose\nnames are _Blue_ and _Yellow_. The Blue team starts with 10 points, and the\nYellow team starts with 50.\nListing 8-20: Creating a new hash map and inserting some keys and values\n```rust\n use std::collections::HashMap;\n\n let mut scores = HashMap::new();\n\n scores.insert(String::from(\"Blue\"), 10);\n scores.insert(String::from(\"Yellow\"), 50);\n```\nNote that we need to first `use` the `HashMap` from the collections portion of\nthe standard library. Of our three common collections, this one is the least\noften used, so it’s not included in the features brought into scope\nautomatically in the prelude. Hash maps also have less support from the\nstandard library; there’s no built-in macro to construct them, for example.\nJust like vectors, hash maps store their data on the heap. This `HashMap` has\nkeys of type `String` and values of type `i32`. Like vectors, hash maps are\nhomogeneous: All of the keys must have the same type, and all of the values\nmust have the same type.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing Keys with Associated Values in Hash Maps", "heading_path": ["Storing Keys with Associated Values in Hash Maps", "Creating a New Hash Map"], "path": "ch08-03-hash-maps.md", "url": "https://doc.rust-lang.org/book/ch08-03-hash-maps.html#creating-a-new-hash-map", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch08-03-hash-maps.md#accessing-values-in-a-hash-map-2", "text": "The Rust Programming Language › Storing Keys with Associated Values in Hash Maps › Accessing Values in a Hash Map\n\nWe can get a value out of the hash map by providing its key to the `get`\nmethod, as shown in Listing 8-21.\nListing 8-21: Accessing the score for the Blue team stored in the hash map\n```rust\n use std::collections::HashMap;\n\n let mut scores = HashMap::new();\n\n scores.insert(String::from(\"Blue\"), 10);\n scores.insert(String::from(\"Yellow\"), 50);\n\n let team_name = String::from(\"Blue\");\n let score = scores.get(&team_name).copied().unwrap_or(0);\n```\nHere, `score` will have the value that’s associated with the Blue team, and the\nresult will be `10`. The `get` method returns an `Option<&V>`; if there’s no\nvalue for that key in the hash map, `get` will return `None`. This program\nhandles the `Option` by calling `copied` to get an `Option` rather than an\n`Option<&i32>`, then `unwrap_or` to set `score` to zero if `scores` doesn’t\nhave an entry for the key.\nWe can iterate over each key-value pair in a hash map in a similar manner as we\ndo with vectors, using a `for` loop:\n```rust\n use std::collections::HashMap;\n\n let mut scores = HashMap::new();\n\n scores.insert(String::from(\"Blue\"), 10);\n scores.insert(String::from(\"Yellow\"), 50);\n\n for (key, value) in &scores {\n println!(\"{key}: {value}\");\n }\n```\nThis code will print each pair in an arbitrary order:\n```text\nYellow: 50\nBlue: 10\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing Keys with Associated Values in Hash Maps", "heading_path": ["Storing Keys with Associated Values in Hash Maps", "Accessing Values in a Hash Map"], "path": "ch08-03-hash-maps.md", "url": "https://doc.rust-lang.org/book/ch08-03-hash-maps.html#accessing-values-in-a-hash-map", "has_code": true, "code_tags": ["rust", "text"]}} {"id": "book/ch08-03-hash-maps.md#managing-ownership-in-hash-maps-3", "text": "The Rust Programming Language › Storing Keys with Associated Values in Hash Maps › Managing Ownership in Hash Maps\n\nFor types that implement the `Copy` trait, like `i32`, the values are copied\ninto the hash map. For owned values like `String`, the values will be moved and\nthe hash map will be the owner of those values, as demonstrated in Listing 8-22.\nListing 8-22: Showing that keys and values are owned by the hash map once they’re inserted\n```rust\n use std::collections::HashMap;\n\n let field_name = String::from(\"Favorite color\");\n let field_value = String::from(\"Blue\");\n\n let mut map = HashMap::new();\n map.insert(field_name, field_value);\n // field_name and field_value are invalid at this point, try using them and\n // see what compiler error you get!\n```\nWe aren’t able to use the variables `field_name` and `field_value` after\nthey’ve been moved into the hash map with the call to `insert`.\nIf we insert references to values into the hash map, the values won’t be moved\ninto the hash map. The values that the references point to must be valid for at\nleast as long as the hash map is valid. We’ll talk more about these issues in\n“Validating References with\nLifetimes” in Chapter 10.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing Keys with Associated Values in Hash Maps", "heading_path": ["Storing Keys with Associated Values in Hash Maps", "Managing Ownership in Hash Maps"], "path": "ch08-03-hash-maps.md", "url": "https://doc.rust-lang.org/book/ch08-03-hash-maps.html#managing-ownership-in-hash-maps", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch08-03-hash-maps.md#adding-a-key-and-value-only-if-a-key-isnt-present-4", "text": "The Rust Programming Language › Storing Keys with Associated Values in Hash Maps › Updating a Hash Map › Adding a Key and Value Only If a Key Isn’t Present\n\nAlthough the number of key and value pairs is growable, each unique key can\nonly have one value associated with it at a time (but not vice versa: For\nexample, both the Blue team and the Yellow team could have the value `10`\nstored in the `scores` hash map).\nWhen you want to change the data in a hash map, you have to decide how to\nhandle the case when a key already has a value assigned. You could replace the\nold value with the new value, completely disregarding the old value. You could\nkeep the old value and ignore the new value, only adding the new value if the\nkey _doesn’t_ already have a value. Or you could combine the old value and the\nnew value. Let’s look at how to do each of these!\nIf we insert a key and a value into a hash map and then insert that same key\nwith a different value, the value associated with that key will be replaced.\nEven though the code in Listing 8-23 calls `insert` twice, the hash map will\nonly contain one key-value pair because we’re inserting the value for the Blue\nteam’s key both times.\nListing 8-23: Replacing a value stored with a particular key\n```rust\n use std::collections::HashMap;\n\n let mut scores = HashMap::new();\n\n scores.insert(String::from(\"Blue\"), 10);\n scores.insert(String::from(\"Blue\"), 25);\n\n println!(\"{scores:?}\");\n```\nThis code will print `{\"Blue\": 25}`. The original value of `10` has been\noverwritten.\nIt’s common to check whether a particular key already exists in the hash map\nwith a value and then to take the following actions: If the key does exist in\nthe hash map, the existing value should remain the way it is; if the key\ndoesn’t exist, insert it and a value for it.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing Keys with Associated Values in Hash Maps", "heading_path": ["Storing Keys with Associated Values in Hash Maps", "Updating a Hash Map", "Adding a Key and Value Only If a Key Isn’t Present"], "path": "ch08-03-hash-maps.md", "url": "https://doc.rust-lang.org/book/ch08-03-hash-maps.html#adding-a-key-and-value-only-if-a-key-isnt-present", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch08-03-hash-maps.md#updating-a-value-based-on-the-old-value-5", "text": "The Rust Programming Language › Storing Keys with Associated Values in Hash Maps › Updating a Hash Map › Updating a Value Based on the Old Value\n\nHash maps have a special API for this called `entry` that takes the key you\nwant to check as a parameter. The return value of the `entry` method is an enum\ncalled `Entry` that represents a value that might or might not exist. Let’s say\nwe want to check whether the key for the Yellow team has a value associated\nwith it. If it doesn’t, we want to insert the value `50`, and the same for the\nBlue team. Using the `entry` API, the code looks like Listing 8-24.\nListing 8-24: Using the `entry` method to only insert if the key does not already have a value\n```rust\n use std::collections::HashMap;\n\n let mut scores = HashMap::new();\n scores.insert(String::from(\"Blue\"), 10);\n\n scores.entry(String::from(\"Yellow\")).or_insert(50);\n scores.entry(String::from(\"Blue\")).or_insert(50);\n\n println!(\"{scores:?}\");\n```\nThe `or_insert` method on `Entry` is defined to return a mutable reference to\nthe value for the corresponding `Entry` key if that key exists, and if not, it\ninserts the parameter as the new value for this key and returns a mutable\nreference to the new value. This technique is much cleaner than writing the\nlogic ourselves and, in addition, plays more nicely with the borrow checker.\nRunning the code in Listing 8-24 will print `{\"Yellow\": 50, \"Blue\": 10}`. The\nfirst call to `entry` will insert the key for the Yellow team with the value\n`50` because the Yellow team doesn’t have a value already. The second call to\n`entry` will not change the hash map, because the Blue team already has the\nvalue `10`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing Keys with Associated Values in Hash Maps", "heading_path": ["Storing Keys with Associated Values in Hash Maps", "Updating a Hash Map", "Updating a Value Based on the Old Value"], "path": "ch08-03-hash-maps.md", "url": "https://doc.rust-lang.org/book/ch08-03-hash-maps.html#updating-a-value-based-on-the-old-value", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch08-03-hash-maps.md#updating-a-value-based-on-the-old-value-6", "text": "The Rust Programming Language › Storing Keys with Associated Values in Hash Maps › Updating a Hash Map › Updating a Value Based on the Old Value\n\nAnother common use case for hash maps is to look up a key’s value and then\nupdate it based on the old value. For instance, Listing 8-25 shows code that\ncounts how many times each word appears in some text. We use a hash map with\nthe words as keys and increment the value to keep track of how many times we’ve\nseen that word. If it’s the first time we’ve seen a word, we’ll first insert\nthe value `0`.\nListing 8-25: Counting occurrences of words using a hash map that stores words and counts\n```rust\n use std::collections::HashMap;\n\n let text = \"hello world wonderful world\";\n\n let mut map = HashMap::new();\n\n for word in text.split_whitespace() {\n let count = map.entry(word).or_insert(0);\n *count += 1;\n }\n\n println!(\"{map:?}\");\n```\nThis code will print `{\"world\": 2, \"hello\": 1, \"wonderful\": 1}`. You might see\nthe same key-value pairs printed in a different order: Recall from “Accessing\nValues in a Hash Map” that iterating over a hash map\nhappens in an arbitrary order.\nThe `split_whitespace` method returns an iterator over subslices, separated by\nwhitespace, of the value in `text`. The `or_insert` method returns a mutable\nreference (`&mut V`) to the value for the specified key. Here, we store that\nmutable reference in the `count` variable, so in order to assign to that value,\nwe must first dereference `count` using the asterisk (`*`). The mutable\nreference goes out of scope at the end of the `for` loop, so all of these\nchanges are safe and allowed by the borrowing rules.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing Keys with Associated Values in Hash Maps", "heading_path": ["Storing Keys with Associated Values in Hash Maps", "Updating a Hash Map", "Updating a Value Based on the Old Value"], "path": "ch08-03-hash-maps.md", "url": "https://doc.rust-lang.org/book/ch08-03-hash-maps.html#updating-a-value-based-on-the-old-value", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch08-03-hash-maps.md#hashing-functions-7", "text": "The Rust Programming Language › Storing Keys with Associated Values in Hash Maps › Hashing Functions\n\nBy default, `HashMap` uses a hashing function called _SipHash_ that can provide\nresistance to denial-of-service (DoS) attacks involving hash\ntables[^siphash]. This is not the fastest hashing algorithm\navailable, but the trade-off for better security that comes with the drop in\nperformance is worth it. If you profile your code and find that the default\nhash function is too slow for your purposes, you can switch to another function\nby specifying a different hasher. A _hasher_ is a type that implements the\n`BuildHasher` trait. We’ll talk about traits and how to implement them in\nChapter 10. You don’t necessarily have to implement\nyour own hasher from scratch; crates.io\nhas libraries shared by other Rust users that provide hashers implementing many\ncommon hashing algorithms.\n[^siphash]: https://en.wikipedia.org/wiki/SipHash", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing Keys with Associated Values in Hash Maps", "heading_path": ["Storing Keys with Associated Values in Hash Maps", "Hashing Functions"], "path": "ch08-03-hash-maps.md", "url": "https://doc.rust-lang.org/book/ch08-03-hash-maps.html#hashing-functions", "has_code": false, "code_tags": []}} {"id": "book/ch08-03-hash-maps.md#summary-8", "text": "The Rust Programming Language › Summary\n\nVectors, strings, and hash maps will provide a large amount of functionality\nnecessary in programs when you need to store, access, and modify data. Here are\nsome exercises you should now be equipped to solve:\n1. Given a list of integers, use a vector and return the median (when sorted,\n the value in the middle position) and mode (the value that occurs most\n often; a hash map will be helpful here) of the list.\n1. Convert strings to Pig Latin. The first consonant of each word is moved to\n the end of the word and _ay_ is added, so _first_ becomes _irst-fay_. Words\n that start with a vowel have _hay_ added to the end instead (_apple_ becomes\n _apple-hay_). Keep in mind the details about UTF-8 encoding!\n1. Using a hash map and vectors, create a text interface to allow a user to add\n employee names to a department in a company; for example, “Add Sally to\n Engineering” or “Add Amir to Sales.” Then, let the user retrieve a list of\n all people in a department or all people in the company by department, sorted\n alphabetically.\nThe standard library API documentation describes methods that vectors, strings,\nand hash maps have that will be helpful for these exercises!\nWe’re getting into more complex programs in which operations can fail, so it’s\na perfect time to discuss error handling. We’ll do that next!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Storing Keys with Associated Values in Hash Maps", "heading_path": ["Summary"], "path": "ch08-03-hash-maps.md", "url": "https://doc.rust-lang.org/book/ch08-03-hash-maps.html#summary", "has_code": false, "code_tags": []}} {"id": "book/ch09-00-error-handling.md#error-handling-0", "text": "The Rust Programming Language › Error Handling\n\nErrors are a fact of life in software, so Rust has a number of features for\nhandling situations in which something goes wrong. In many cases, Rust requires\nyou to acknowledge the possibility of an error and take some action before your\ncode will compile. This requirement makes your program more robust by ensuring\nthat you’ll discover errors and handle them appropriately before deploying your\ncode to production!\nRust groups errors into two major categories: recoverable and unrecoverable\nerrors. For a _recoverable error_, such as a _file not found_ error, we most\nlikely just want to report the problem to the user and retry the operation.\n_Unrecoverable errors_ are always symptoms of bugs, such as trying to access a\nlocation beyond the end of an array, and so we want to immediately stop the\nprogram.\nMost languages don’t distinguish between these two kinds of errors and handle\nboth in the same way, using mechanisms such as exceptions. Rust doesn’t have\nexceptions. Instead, it has the type `Result` for recoverable errors and\nthe `panic!` macro that stops execution when the program encounters an\nunrecoverable error. This chapter covers calling `panic!` first and then talks\nabout returning `Result` values. Additionally, we’ll explore\nconsiderations when deciding whether to try to recover from an error or to stop\nexecution.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Error Handling", "heading_path": ["Error Handling"], "path": "ch09-00-error-handling.md", "url": "https://doc.rust-lang.org/book/ch09-00-error-handling.html#error-handling", "has_code": false, "code_tags": []}} {"id": "book/ch09-01-unrecoverable-errors-with-panic.md#unrecoverable-errors-with-panic-0", "text": "The Rust Programming Language › Unrecoverable Errors with `panic!`\n\nSometimes bad things happen in your code, and there’s nothing you can do about\nit. In these cases, Rust has the `panic!` macro. There are two ways to cause a\npanic in practice: by taking an action that causes our code to panic (such as\naccessing an array past the end) or by explicitly calling the `panic!` macro.\nIn both cases, we cause a panic in our program. By default, these panics will\nprint a failure message, unwind, clean up the stack, and quit. Via an\nenvironment variable, you can also have Rust display the call stack when a\npanic occurs to make it easier to track down the source of the panic.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unrecoverable Errors with `panic!`", "heading_path": ["Unrecoverable Errors with `panic!`"], "path": "ch09-01-unrecoverable-errors-with-panic.md", "url": "https://doc.rust-lang.org/book/ch09-01-unrecoverable-errors-with-panic.html#unrecoverable-errors-with-panic", "has_code": false, "code_tags": []}} {"id": "book/ch09-01-unrecoverable-errors-with-panic.md#unwinding-the-stack-or-aborting-in-response-to-a-panic-1", "text": "The Rust Programming Language › Unrecoverable Errors with `panic!` › Unwinding the Stack or Aborting in Response to a Panic\n\nBy default, when a panic occurs, the program starts _unwinding_, which means\nRust walks back up the stack and cleans up the data from each function it\nencounters. However, walking back and cleaning up is a lot of work. Rust\ntherefore allows you to choose the alternative of immediately _aborting_,\nwhich ends the program without cleaning up.\nMemory that the program was using will then need to be cleaned up by the\noperating system. If in your project you need to make the resultant binary as\nsmall as possible, you can switch from unwinding to aborting upon a panic by\nadding `panic = 'abort'` to the appropriate `[profile]` sections in your\n_Cargo.toml_ file. For example, if you want to abort on panic in release mode,\nadd this:\n```toml\n[profile.release]\npanic = 'abort'\n```\nLet’s try calling `panic!` in a simple program:\nListing (src/main.rs)\n```rust,should_panic,panics\nfn main() {\n panic!(\"crash and burn\");\n}\n```\nWhen you run the program, you’ll see something like this:\n```console\n$ cargo run\n Compiling panic v0.1.0 (file:///projects/panic)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.25s\n Running `target/debug/panic`\n\nthread 'main' (6018279) panicked at src/main.rs:2:5:\ncrash and burn\nnote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n```\nThe call to `panic!` causes the error message contained in the last two lines.\nThe first line shows our panic message and the place in our source code where\nthe panic occurred: _src/main.rs:2:5_ indicates that it’s the second line,\nfifth character of our _src/main.rs_ file.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unrecoverable Errors with `panic!`", "heading_path": ["Unrecoverable Errors with `panic!`", "Unwinding the Stack or Aborting in Response to a Panic"], "path": "ch09-01-unrecoverable-errors-with-panic.md", "url": "https://doc.rust-lang.org/book/ch09-01-unrecoverable-errors-with-panic.html#unwinding-the-stack-or-aborting-in-response-to-a-panic", "has_code": true, "code_tags": ["console", "rust,should_panic,panics", "toml"]}} {"id": "book/ch09-01-unrecoverable-errors-with-panic.md#unwinding-the-stack-or-aborting-in-response-to-a-panic-2", "text": "The Rust Programming Language › Unrecoverable Errors with `panic!` › Unwinding the Stack or Aborting in Response to a Panic\n\nIn this case, the line indicated is part of our code, and if we go to that\nline, we see the `panic!` macro call. In other cases, the `panic!` call might\nbe in code that our code calls, and the filename and line number reported by\nthe error message will be someone else’s code where the `panic!` macro is\ncalled, not the line of our code that eventually led to the `panic!` call.\nWe can use the backtrace of the functions the `panic!` call came from to figure\nout the part of our code that is causing the problem. To understand how to use\na `panic!` backtrace, let’s look at another example and see what it’s like when\na `panic!` call comes from a library because of a bug in our code instead of\nfrom our code calling the macro directly. Listing 9-1 has some code that\nattempts to access an index in a vector beyond the range of valid indexes.\nListing 9-1: Attempting to access an element beyond the end of a vector, which will cause a call to `panic!` (src/main.rs)\n```rust,should_panic,panics\nfn main() {\n let v = vec![1, 2, 3];\n\n v[99];\n}\n```\nHere, we’re attempting to access the 100th element of our vector (which is at\nindex 99 because indexing starts at zero), but the vector has only three\nelements. In this situation, Rust will panic. Using `[]` is supposed to return\nan element, but if you pass an invalid index, there’s no element that Rust\ncould return here that would be correct.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unrecoverable Errors with `panic!`", "heading_path": ["Unrecoverable Errors with `panic!`", "Unwinding the Stack or Aborting in Response to a Panic"], "path": "ch09-01-unrecoverable-errors-with-panic.md", "url": "https://doc.rust-lang.org/book/ch09-01-unrecoverable-errors-with-panic.html#unwinding-the-stack-or-aborting-in-response-to-a-panic", "has_code": true, "code_tags": ["rust,should_panic,panics"]}} {"id": "book/ch09-01-unrecoverable-errors-with-panic.md#unwinding-the-stack-or-aborting-in-response-to-a-panic-3", "text": "The Rust Programming Language › Unrecoverable Errors with `panic!` › Unwinding the Stack or Aborting in Response to a Panic\n\nIn C, attempting to read beyond the end of a data structure is undefined\nbehavior. You might get whatever is at the location in memory that would\ncorrespond to that element in the data structure, even though the memory\ndoesn’t belong to that structure. This is called a _buffer overread_ and can\nlead to security vulnerabilities if an attacker is able to manipulate the index\nin such a way as to read data they shouldn’t be allowed to that is stored after\nthe data structure.\nTo protect your program from this sort of vulnerability, if you try to read an\nelement at an index that doesn’t exist, Rust will stop execution and refuse to\ncontinue. Let’s try it and see:\n```console\n$ cargo run\n Compiling panic v0.1.0 (file:///projects/panic)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.27s\n Running `target/debug/panic`\n\nthread 'main' (6017887) panicked at src/main.rs:4:6:\nindex out of bounds: the len is 3 but the index is 99\nnote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n```\nThis error points at line 4 of our _main.rs_ where we attempt to access index\n99 of the vector in `v`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unrecoverable Errors with `panic!`", "heading_path": ["Unrecoverable Errors with `panic!`", "Unwinding the Stack or Aborting in Response to a Panic"], "path": "ch09-01-unrecoverable-errors-with-panic.md", "url": "https://doc.rust-lang.org/book/ch09-01-unrecoverable-errors-with-panic.html#unwinding-the-stack-or-aborting-in-response-to-a-panic", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch09-01-unrecoverable-errors-with-panic.md#unwinding-the-stack-or-aborting-in-response-to-a-panic-4", "text": "The Rust Programming Language › Unrecoverable Errors with `panic!` › Unwinding the Stack or Aborting in Response to a Panic\n\nThe `note:` line tells us that we can set the `RUST_BACKTRACE` environment\nvariable to get a backtrace of exactly what happened to cause the error. A\n_backtrace_ is a list of all the functions that have been called to get to this\npoint. Backtraces in Rust work as they do in other languages: The key to\nreading the backtrace is to start from the top and read until you see files you\nwrote. That’s the spot where the problem originated. The lines above that spot\nare code that your code has called; the lines below are code that called your\ncode. These before-and-after lines might include core Rust code, standard\nlibrary code, or crates that you’re using. Let’s try to get a backtrace by\nsetting the `RUST_BACKTRACE` environment variable to any value except `0`.\nListing 9-2 shows output similar to what you’ll see.\nListing 9-2: The backtrace generated by a call to `panic!` displayed when the environment variable `RUST_BACKTRACE` is set", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unrecoverable Errors with `panic!`", "heading_path": ["Unrecoverable Errors with `panic!`", "Unwinding the Stack or Aborting in Response to a Panic"], "path": "ch09-01-unrecoverable-errors-with-panic.md", "url": "https://doc.rust-lang.org/book/ch09-01-unrecoverable-errors-with-panic.html#unwinding-the-stack-or-aborting-in-response-to-a-panic", "has_code": false, "code_tags": []}} {"id": "book/ch09-01-unrecoverable-errors-with-panic.md#unwinding-the-stack-or-aborting-in-response-to-a-panic-5", "text": "The Rust Programming Language › Unrecoverable Errors with `panic!` › Unwinding the Stack or Aborting in Response to a Panic\n\n```console\n$ RUST_BACKTRACE=1 cargo run\nthread 'main' panicked at src/main.rs:4:6:\nindex out of bounds: the len is 3 but the index is 99\nstack backtrace:\n 0: rust_begin_unwind\n at /rustc/4d91de4e48198da2e33413efdcd9cd2cc0c46688/library/std/src/panicking.rs:692:5\n 1: core::panicking::panic_fmt\n at /rustc/4d91de4e48198da2e33413efdcd9cd2cc0c46688/library/core/src/panicking.rs:75:14\n 2: core::panicking::panic_bounds_check\n at /rustc/4d91de4e48198da2e33413efdcd9cd2cc0c46688/library/core/src/panicking.rs:273:5\n 3: >::index\n at file:///home/.rustup/toolchains/1.85/lib/rustlib/src/rust/library/core/src/slice/index.rs:274:10\n 4: core::slice::index:: for [T]>::index\n at file:///home/.rustup/toolchains/1.85/lib/rustlib/src/rust/library/core/src/slice/index.rs:16:9\n 5: as core::ops::index::Index>::index\n at file:///home/.rustup/toolchains/1.85/lib/rustlib/src/rust/library/alloc/src/vec/mod.rs:3361:9\n 6: panic::main\n at ./src/main.rs:4:6\n 7: core::ops::function::FnOnce::call_once\n at file:///home/.rustup/toolchains/1.85/lib/rustlib/src/rust/library/core/src/ops/function.rs:250:5\nnote: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unrecoverable Errors with `panic!`", "heading_path": ["Unrecoverable Errors with `panic!`", "Unwinding the Stack or Aborting in Response to a Panic"], "path": "ch09-01-unrecoverable-errors-with-panic.md", "url": "https://doc.rust-lang.org/book/ch09-01-unrecoverable-errors-with-panic.html#unwinding-the-stack-or-aborting-in-response-to-a-panic", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch09-01-unrecoverable-errors-with-panic.md#unwinding-the-stack-or-aborting-in-response-to-a-panic-6", "text": "The Rust Programming Language › Unrecoverable Errors with `panic!` › Unwinding the Stack or Aborting in Response to a Panic\n\nThat’s a lot of output! The exact output you see might be different depending\non your operating system and Rust version. In order to get backtraces with this\ninformation, debug symbols must be enabled. Debug symbols are enabled by\ndefault when using `cargo build` or `cargo run` without the `--release` flag,\nas we have here.\nIn the output in Listing 9-2, line 6 of the backtrace points to the line in our\nproject that’s causing the problem: line 4 of _src/main.rs_. If we don’t want\nour program to panic, we should start our investigation at the location pointed\nto by the first line mentioning a file we wrote. In Listing 9-1, where we\ndeliberately wrote code that would panic, the way to fix the panic is to not\nrequest an element beyond the range of the vector indexes. When your code\npanics in the future, you’ll need to figure out what action the code is taking\nwith what values to cause the panic and what the code should do instead.\nWe’ll come back to `panic!` and when we should and should not use `panic!` to\nhandle error conditions in the “To `panic!` or Not to\n`panic!`” section later in this\nchapter. Next, we’ll look at how to recover from an error using `Result`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unrecoverable Errors with `panic!`", "heading_path": ["Unrecoverable Errors with `panic!`", "Unwinding the Stack or Aborting in Response to a Panic"], "path": "ch09-01-unrecoverable-errors-with-panic.md", "url": "https://doc.rust-lang.org/book/ch09-01-unrecoverable-errors-with-panic.html#unwinding-the-stack-or-aborting-in-response-to-a-panic", "has_code": false, "code_tags": []}} {"id": "book/ch09-02-recoverable-errors-with-result.md#recoverable-errors-with-result-0", "text": "The Rust Programming Language › Recoverable Errors with `Result`\n\nMost errors aren’t serious enough to require the program to stop entirely.\nSometimes when a function fails, it’s for a reason that you can easily interpret\nand respond to. For example, if you try to open a file and that operation fails\nbecause the file doesn’t exist, you might want to create the file instead of\nterminating the process.\nRecall from “Handling Potential Failure with `Result`”\n in Chapter 2 that the `Result` enum is defined as having two\nvariants, `Ok` and `Err`, as follows:\n```rust\nenum Result {\n Ok(T),\n Err(E),\n}\n```\nThe `T` and `E` are generic type parameters: We’ll discuss generics in more\ndetail in Chapter 10. What you need to know right now is that `T` represents\nthe type of the value that will be returned in a success case within the `Ok`\nvariant, and `E` represents the type of the error that will be returned in a\nfailure case within the `Err` variant. Because `Result` has these generic type\nparameters, we can use the `Result` type and the functions defined on it in\nmany different situations where the success value and error value we want to\nreturn may differ.\nLet’s call a function that returns a `Result` value because the function could\nfail. In Listing 9-3, we try to open a file.\nListing 9-3: Opening a file (src/main.rs)\n```rust\nuse std::fs::File;\n\nfn main() {\n let greeting_file_result = File::open(\"hello.txt\");\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Recoverable Errors with `Result`", "heading_path": ["Recoverable Errors with `Result`"], "path": "ch09-02-recoverable-errors-with-result.md", "url": "https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#recoverable-errors-with-result", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch09-02-recoverable-errors-with-result.md#recoverable-errors-with-result-1", "text": "The Rust Programming Language › Recoverable Errors with `Result`\n\nThe return type of `File::open` is a `Result`. The generic parameter `T`\nhas been filled in by the implementation of `File::open` with the type of the\nsuccess value, `std::fs::File`, which is a file handle. The type of `E` used in\nthe error value is `std::io::Error`. This return type means the call to\n`File::open` might succeed and return a file handle that we can read from or\nwrite to. The function call also might fail: For example, the file might not\nexist, or we might not have permission to access the file. The `File::open`\nfunction needs to have a way to tell us whether it succeeded or failed and at\nthe same time give us either the file handle or error information. This\ninformation is exactly what the `Result` enum conveys.\nIn the case where `File::open` succeeds, the value in the variable\n`greeting_file_result` will be an instance of `Ok` that contains a file handle.\nIn the case where it fails, the value in `greeting_file_result` will be an\ninstance of `Err` that contains more information about the kind of error that\noccurred.\nWe need to add to the code in Listing 9-3 to take different actions depending\non the value `File::open` returns. Listing 9-4 shows one way to handle the\n`Result` using a basic tool, the `match` expression that we discussed in\nChapter 6.\nListing 9-4: Using a `match` expression to handle the `Result` variants that might be returned (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Recoverable Errors with `Result`", "heading_path": ["Recoverable Errors with `Result`"], "path": "ch09-02-recoverable-errors-with-result.md", "url": "https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#recoverable-errors-with-result", "has_code": false, "code_tags": []}} {"id": "book/ch09-02-recoverable-errors-with-result.md#recoverable-errors-with-result-2", "text": "The Rust Programming Language › Recoverable Errors with `Result`\n\n```rust,should_panic\nuse std::fs::File;\n\nfn main() {\n let greeting_file_result = File::open(\"hello.txt\");\n\n let greeting_file = match greeting_file_result {\n Ok(file) => file,\n Err(error) => panic!(\"Problem opening the file: {error:?}\"),\n };\n}\n```\nNote that, like the `Option` enum, the `Result` enum and its variants have been\nbrought into scope by the prelude, so we don’t need to specify `Result::`\nbefore the `Ok` and `Err` variants in the `match` arms.\nWhen the result is `Ok`, this code will return the inner `file` value out of\nthe `Ok` variant, and we then assign that file handle value to the variable\n`greeting_file`. After the `match`, we can use the file handle for reading or\nwriting.\nThe other arm of the `match` handles the case where we get an `Err` value from\n`File::open`. In this example, we’ve chosen to call the `panic!` macro. If\nthere’s no file named _hello.txt_ in our current directory and we run this\ncode, we’ll see the following output from the `panic!` macro:\n```console\n$ cargo run\n Compiling error-handling v0.1.0 (file:///projects/error-handling)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.73s\n Running `target/debug/error-handling`\n\nthread 'main' (6018048) panicked at src/main.rs:8:23:\nProblem opening the file: Os { code: 2, kind: NotFound, message: \"No such file or directory\" }\nnote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n```\nAs usual, this output tells us exactly what has gone wrong.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Recoverable Errors with `Result`", "heading_path": ["Recoverable Errors with `Result`"], "path": "ch09-02-recoverable-errors-with-result.md", "url": "https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#recoverable-errors-with-result", "has_code": true, "code_tags": ["console", "rust,should_panic"]}} {"id": "book/ch09-02-recoverable-errors-with-result.md#matching-on-different-errors-3", "text": "The Rust Programming Language › Recoverable Errors with `Result` › Matching on Different Errors\n\nThe code in Listing 9-4 will `panic!` no matter why `File::open` failed.\nHowever, we want to take different actions for different failure reasons. If\n`File::open` failed because the file doesn’t exist, we want to create the file\nand return the handle to the new file. If `File::open` failed for any other\nreason—for example, because we didn’t have permission to open the file—we still\nwant the code to `panic!` in the same way it did in Listing 9-4. For this, we\nadd an inner `match` expression, shown in Listing 9-5.\nListing 9-5: Handling different kinds of errors in different ways (src/main.rs)\n```rust,ignore\nuse std::fs::File;\nuse std::io::ErrorKind;\n\nfn main() {\n let greeting_file_result = File::open(\"hello.txt\");\n\n let greeting_file = match greeting_file_result {\n Ok(file) => file,\n Err(error) => match error.kind() {\n ErrorKind::NotFound => match File::create(\"hello.txt\") {\n Ok(fc) => fc,\n Err(e) => panic!(\"Problem creating the file: {e:?}\"),\n },\n _ => {\n panic!(\"Problem opening the file: {error:?}\");\n }\n },\n };\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Recoverable Errors with `Result`", "heading_path": ["Recoverable Errors with `Result`", "Matching on Different Errors"], "path": "ch09-02-recoverable-errors-with-result.md", "url": "https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#matching-on-different-errors", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch09-02-recoverable-errors-with-result.md#alternatives-to-using-match-with-resultt-e-4", "text": "The Rust Programming Language › Recoverable Errors with `Result` › Matching on Different Errors › Alternatives to Using `match` with `Result`\n\nThe type of the value that `File::open` returns inside the `Err` variant is\n`io::Error`, which is a struct provided by the standard library. This struct\nhas a method, `kind`, that we can call to get an `io::ErrorKind` value. The\nenum `io::ErrorKind` is provided by the standard library and has variants\nrepresenting the different kinds of errors that might result from an `io`\noperation. The variant we want to use is `ErrorKind::NotFound`, which indicates\nthe file we’re trying to open doesn’t exist yet. So, we match on\n`greeting_file_result`, but we also have an inner match on `error.kind()`.\nThe condition we want to check in the inner match is whether the value returned\nby `error.kind()` is the `NotFound` variant of the `ErrorKind` enum. If it is,\nwe try to create the file with `File::create`. However, because `File::create`\ncould also fail, we need a second arm in the inner `match` expression. When the\nfile can’t be created, a different error message is printed. The second arm of\nthe outer `match` stays the same, so the program panics on any error besides\nthe missing file error.\nThat’s a lot of `match`! The `match` expression is very useful but also very\nmuch a primitive. In Chapter 13, you’ll learn about closures, which are used\nwith many of the methods defined on `Result`. These methods can be more\nconcise than using `match` when handling `Result` values in your code.\nFor example, here’s another way to write the same logic as shown in Listing\n9-5, this time using closures and the `unwrap_or_else` method:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Recoverable Errors with `Result`", "heading_path": ["Recoverable Errors with `Result`", "Matching on Different Errors", "Alternatives to Using `match` with `Result`"], "path": "ch09-02-recoverable-errors-with-result.md", "url": "https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#alternatives-to-using-match-with-resultt-e", "has_code": false, "code_tags": []}} {"id": "book/ch09-02-recoverable-errors-with-result.md#shortcuts-for-panic-on-error-5", "text": "The Rust Programming Language › Recoverable Errors with `Result` › Matching on Different Errors › Shortcuts for Panic on Error\n\n```rust,ignore\nuse std::fs::File;\nuse std::io::ErrorKind;\n\nfn main() {\n let greeting_file = File::open(\"hello.txt\").unwrap_or_else(|error| {\n if error.kind() == ErrorKind::NotFound {\n File::create(\"hello.txt\").unwrap_or_else(|error| {\n panic!(\"Problem creating the file: {error:?}\");\n })\n } else {\n panic!(\"Problem opening the file: {error:?}\");\n }\n });\n}\n```\nAlthough this code has the same behavior as Listing 9-5, it doesn’t contain\nany `match` expressions and is cleaner to read. Come back to this example\nafter you’ve read Chapter 13 and look up the `unwrap_or_else` method in the\nstandard library documentation. Many more of these methods can clean up huge,\nnested `match` expressions when you’re dealing with errors.\nUsing `match` works well enough, but it can be a bit verbose and doesn’t always\ncommunicate intent well. The `Result` type has many helper methods\ndefined on it to do various, more specific tasks. The `unwrap` method is a\nshortcut method implemented just like the `match` expression we wrote in\nListing 9-4. If the `Result` value is the `Ok` variant, `unwrap` will return\nthe value inside the `Ok`. If the `Result` is the `Err` variant, `unwrap` will\ncall the `panic!` macro for us. Here is an example of `unwrap` in action:\nListing (src/main.rs)\n```rust,should_panic\nuse std::fs::File;\n\nfn main() {\n let greeting_file = File::open(\"hello.txt\").unwrap();\n}\n```\nIf we run this code without a _hello.txt_ file, we’ll see an error message from\nthe `panic!` call that the `unwrap` method makes:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Recoverable Errors with `Result`", "heading_path": ["Recoverable Errors with `Result`", "Matching on Different Errors", "Shortcuts for Panic on Error"], "path": "ch09-02-recoverable-errors-with-result.md", "url": "https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#shortcuts-for-panic-on-error", "has_code": true, "code_tags": ["rust,ignore", "rust,should_panic"]}} {"id": "book/ch09-02-recoverable-errors-with-result.md#shortcuts-for-panic-on-error-6", "text": "The Rust Programming Language › Recoverable Errors with `Result` › Matching on Different Errors › Shortcuts for Panic on Error\n\n```text\nthread 'main' panicked at src/main.rs:4:49:\ncalled `Result::unwrap()` on an `Err` value: Os { code: 2, kind: NotFound, message: \"No such file or directory\" }\n```\nSimilarly, the `expect` method lets us also choose the `panic!` error message.\nUsing `expect` instead of `unwrap` and providing good error messages can convey\nyour intent and make tracking down the source of a panic easier. The syntax of\n`expect` looks like this:\nListing (src/main.rs)\n```rust,should_panic\nuse std::fs::File;\n\nfn main() {\n let greeting_file = File::open(\"hello.txt\")\n .expect(\"hello.txt should be included in this project\");\n}\n```\nWe use `expect` in the same way as `unwrap`: to return the file handle or call\nthe `panic!` macro. The error message used by `expect` in its call to `panic!`\nwill be the parameter that we pass to `expect`, rather than the default\n`panic!` message that `unwrap` uses. Here’s what it looks like:\n```text\nthread 'main' panicked at src/main.rs:5:10:\nhello.txt should be included in this project: Os { code: 2, kind: NotFound, message: \"No such file or directory\" }\n```\nIn production-quality code, most Rustaceans choose `expect` rather than\n`unwrap` and give more context about why the operation is expected to always\nsucceed. That way, if your assumptions are ever proven wrong, you have more\ninformation to use in debugging.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Recoverable Errors with `Result`", "heading_path": ["Recoverable Errors with `Result`", "Matching on Different Errors", "Shortcuts for Panic on Error"], "path": "ch09-02-recoverable-errors-with-result.md", "url": "https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#shortcuts-for-panic-on-error", "has_code": true, "code_tags": ["rust,should_panic", "text"]}} {"id": "book/ch09-02-recoverable-errors-with-result.md#propagating-errors-7", "text": "The Rust Programming Language › Recoverable Errors with `Result` › Propagating Errors\n\nWhen a function’s implementation calls something that might fail, instead of\nhandling the error within the function itself, you can return the error to the\ncalling code so that it can decide what to do. This is known as _propagating_\nthe error and gives more control to the calling code, where there might be more\ninformation or logic that dictates how the error should be handled than what\nyou have available in the context of your code.\nFor example, Listing 9-6 shows a function that reads a username from a file. If\nthe file doesn’t exist or can’t be read, this function will return those errors\nto the code that called the function.\nListing 9-6: A function that returns errors to the calling code using `match` (src/main.rs)\n```rust\nuse std::fs::File;\nuse std::io::{self, Read};\n\nfn read_username_from_file() -> Result {\n let username_file_result = File::open(\"hello.txt\");\n\n let mut username_file = match username_file_result {\n Ok(file) => file,\n Err(e) => return Err(e),\n };\n\n let mut username = String::new();\n\n match username_file.read_to_string(&mut username) {\n Ok(_) => Ok(username),\n Err(e) => Err(e),\n }\n}\n```\nThis function can be written in a much shorter way, but we’re going to start by\ndoing a lot of it manually in order to explore error handling; at the end,\nwe’ll show the shorter way. Let’s look at the return type of the function\nfirst: `Result`. This means the function is returning a\nvalue of the type `Result`, where the generic parameter `T` has been\nfilled in with the concrete type `String` and the generic type `E` has been\nfilled in with the concrete type `io::Error`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Recoverable Errors with `Result`", "heading_path": ["Recoverable Errors with `Result`", "Propagating Errors"], "path": "ch09-02-recoverable-errors-with-result.md", "url": "https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#propagating-errors", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch09-02-recoverable-errors-with-result.md#propagating-errors-8", "text": "The Rust Programming Language › Recoverable Errors with `Result` › Propagating Errors\n\nIf this function succeeds without any problems, the code that calls this\nfunction will receive an `Ok` value that holds a `String`—the `username` that\nthis function read from the file. If this function encounters any problems, the\ncalling code will receive an `Err` value that holds an instance of `io::Error`\nthat contains more information about what the problems were. We chose\n`io::Error` as the return type of this function because that happens to be the\ntype of the error value returned from both of the operations we’re calling in\nthis function’s body that might fail: the `File::open` function and the\n`read_to_string` method.\nThe body of the function starts by calling the `File::open` function. Then, we\nhandle the `Result` value with a `match` similar to the `match` in Listing 9-4.\nIf `File::open` succeeds, the file handle in the pattern variable `file`\nbecomes the value in the mutable variable `username_file` and the function\ncontinues. In the `Err` case, instead of calling `panic!`, we use the `return`\nkeyword to return early out of the function entirely and pass the error value\nfrom `File::open`, now in the pattern variable `e`, back to the calling code as\nthis function’s error value.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Recoverable Errors with `Result`", "heading_path": ["Recoverable Errors with `Result`", "Propagating Errors"], "path": "ch09-02-recoverable-errors-with-result.md", "url": "https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#propagating-errors", "has_code": false, "code_tags": []}} {"id": "book/ch09-02-recoverable-errors-with-result.md#the--operator-shortcut-9", "text": "The Rust Programming Language › Recoverable Errors with `Result` › Propagating Errors › The `?` Operator Shortcut\n\nSo, if we have a file handle in `username_file`, the function then creates a\nnew `String` in variable `username` and calls the `read_to_string` method on\nthe file handle in `username_file` to read the contents of the file into\n`username`. The `read_to_string` method also returns a `Result` because it\nmight fail, even though `File::open` succeeded. So, we need another `match` to\nhandle that `Result`: If `read_to_string` succeeds, then our function has\nsucceeded, and we return the username from the file that’s now in `username`\nwrapped in an `Ok`. If `read_to_string` fails, we return the error value in the\nsame way that we returned the error value in the `match` that handled the\nreturn value of `File::open`. However, we don’t need to explicitly say\n`return`, because this is the last expression in the function.\nThe code that calls this code will then handle getting either an `Ok` value\nthat contains a username or an `Err` value that contains an `io::Error`. It’s\nup to the calling code to decide what to do with those values. If the calling\ncode gets an `Err` value, it could call `panic!` and crash the program, use a\ndefault username, or look up the username from somewhere other than a file, for\nexample. We don’t have enough information on what the calling code is actually\ntrying to do, so we propagate all the success or error information upward for\nit to handle appropriately.\nThis pattern of propagating errors is so common in Rust that Rust provides the\nquestion mark operator `?` to make this easier.\nListing 9-7 shows an implementation of `read_username_from_file` that has the\nsame functionality as in Listing 9-6, but this implementation uses the `?`\noperator.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Recoverable Errors with `Result`", "heading_path": ["Recoverable Errors with `Result`", "Propagating Errors", "The `?` Operator Shortcut"], "path": "ch09-02-recoverable-errors-with-result.md", "url": "https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#the--operator-shortcut", "has_code": false, "code_tags": []}} {"id": "book/ch09-02-recoverable-errors-with-result.md#the--operator-shortcut-10", "text": "The Rust Programming Language › Recoverable Errors with `Result` › Propagating Errors › The `?` Operator Shortcut\n\nListing 9-7: A function that returns errors to the calling code using the `?` operator (src/main.rs)\n```rust\nuse std::fs::File;\nuse std::io::{self, Read};\n\nfn read_username_from_file() -> Result {\n let mut username_file = File::open(\"hello.txt\")?;\n let mut username = String::new();\n username_file.read_to_string(&mut username)?;\n Ok(username)\n}\n```\nThe `?` placed after a `Result` value is defined to work in almost the same way\nas the `match` expressions that we defined to handle the `Result` values in\nListing 9-6. If the value of the `Result` is an `Ok`, the value inside the `Ok`\nwill get returned from this expression, and the program will continue. If the\nvalue is an `Err`, the `Err` will be returned from the whole function as if we\nhad used the `return` keyword so that the error value gets propagated to the\ncalling code.\nThere is a difference between what the `match` expression from Listing 9-6 does\nand what the `?` operator does: Error values that have the `?` operator called\non them go through the `from` function, defined in the `From` trait in the\nstandard library, which is used to convert values from one type into another.\nWhen the `?` operator calls the `from` function, the error type received is\nconverted into the error type defined in the return type of the current\nfunction. This is useful when a function returns one error type to represent\nall the ways a function might fail, even if parts might fail for many different\nreasons.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Recoverable Errors with `Result`", "heading_path": ["Recoverable Errors with `Result`", "Propagating Errors", "The `?` Operator Shortcut"], "path": "ch09-02-recoverable-errors-with-result.md", "url": "https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#the--operator-shortcut", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch09-02-recoverable-errors-with-result.md#the--operator-shortcut-11", "text": "The Rust Programming Language › Recoverable Errors with `Result` › Propagating Errors › The `?` Operator Shortcut\n\nFor example, we could change the `read_username_from_file` function in Listing\n9-7 to return a custom error type named `OurError` that we define. If we also\ndefine `impl From for OurError` to construct an instance of\n`OurError` from an `io::Error`, then the `?` operator calls in the body of\n`read_username_from_file` will call `from` and convert the error types without\nneeding to add any more code to the function.\nIn the context of Listing 9-7, the `?` at the end of the `File::open` call will\nreturn the value inside an `Ok` to the variable `username_file`. If an error\noccurs, the `?` operator will return early out of the whole function and give\nany `Err` value to the calling code. The same thing applies to the `?` at the\nend of the `read_to_string` call.\nThe `?` operator eliminates a lot of boilerplate and makes this function’s\nimplementation simpler. We could even shorten this code further by chaining\nmethod calls immediately after the `?`, as shown in Listing 9-8.\nListing 9-8: Chaining method calls after the `?` operator (src/main.rs)\n```rust\nuse std::fs::File;\nuse std::io::{self, Read};\n\nfn read_username_from_file() -> Result {\n let mut username = String::new();\n\n File::open(\"hello.txt\")?.read_to_string(&mut username)?;\n\n Ok(username)\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Recoverable Errors with `Result`", "heading_path": ["Recoverable Errors with `Result`", "Propagating Errors", "The `?` Operator Shortcut"], "path": "ch09-02-recoverable-errors-with-result.md", "url": "https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#the--operator-shortcut", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch09-02-recoverable-errors-with-result.md#where-to-use-the--operator-12", "text": "The Rust Programming Language › Recoverable Errors with `Result` › Propagating Errors › Where to Use the `?` Operator\n\nWe’ve moved the creation of the new `String` in `username` to the beginning of\nthe function; that part hasn’t changed. Instead of creating a variable\n`username_file`, we’ve chained the call to `read_to_string` directly onto the\nresult of `File::open(\"hello.txt\")?`. We still have a `?` at the end of the\n`read_to_string` call, and we still return an `Ok` value containing `username`\nwhen both `File::open` and `read_to_string` succeed rather than returning\nerrors. The functionality is again the same as in Listing 9-6 and Listing 9-7;\nthis is just a different, more ergonomic way to write it.\nListing 9-9 shows a way to make this even shorter using `fs::read_to_string`.\nListing 9-9: Using `fs::read_to_string` instead of opening and then reading the file (src/main.rs)\n```rust\nuse std::fs;\nuse std::io;\n\nfn read_username_from_file() -> Result {\n fs::read_to_string(\"hello.txt\")\n}\n```\nReading a file into a string is a fairly common operation, so the standard\nlibrary provides the convenient `fs::read_to_string` function that opens the\nfile, creates a new `String`, reads the contents of the file, puts the contents\ninto that `String`, and returns it. Of course, using `fs::read_to_string`\ndoesn’t give us the opportunity to explain all the error handling, so we did it\nthe longer way first.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Recoverable Errors with `Result`", "heading_path": ["Recoverable Errors with `Result`", "Propagating Errors", "Where to Use the `?` Operator"], "path": "ch09-02-recoverable-errors-with-result.md", "url": "https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#where-to-use-the--operator", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch09-02-recoverable-errors-with-result.md#where-to-use-the--operator-13", "text": "The Rust Programming Language › Recoverable Errors with `Result` › Propagating Errors › Where to Use the `?` Operator\n\nThe `?` operator can only be used in functions whose return type is compatible\nwith the value the `?` is used on. This is because the `?` operator is defined\nto perform an early return of a value out of the function, in the same manner\nas the `match` expression we defined in Listing 9-6. In Listing 9-6, the\n`match` was using a `Result` value, and the early return arm returned an\n`Err(e)` value. The return type of the function has to be a `Result` so that\nit’s compatible with this `return`.\nIn Listing 9-10, let’s look at the error we’ll get if we use the `?` operator\nin a `main` function with a return type that is incompatible with the type of\nthe value we use `?` on.\nListing 9-10: Attempting to use the `?` in the `main` function that returns `()` won’t compile. (src/main.rs)\n```rust,ignore,does_not_compile\nuse std::fs::File;\n\nfn main() {\n let greeting_file = File::open(\"hello.txt\")?;\n}\n```\nThis code opens a file, which might fail. The `?` operator follows the `Result`\nvalue returned by `File::open`, but this `main` function has the return type of\n`()`, not `Result`. When we compile this code, we get the following error\nmessage:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Recoverable Errors with `Result`", "heading_path": ["Recoverable Errors with `Result`", "Propagating Errors", "Where to Use the `?` Operator"], "path": "ch09-02-recoverable-errors-with-result.md", "url": "https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#where-to-use-the--operator", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch09-02-recoverable-errors-with-result.md#where-to-use-the--operator-14", "text": "The Rust Programming Language › Recoverable Errors with `Result` › Propagating Errors › Where to Use the `?` Operator\n\n```console\n$ cargo run\n Compiling error-handling v0.1.0 (file:///projects/error-handling)\nerror[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)\n --> src/main.rs:4:48\n |\n3 | fn main() {\n | --------- this function should return `Result` or `Option` to accept `?`\n4 | let greeting_file = File::open(\"hello.txt\")?;\n | ^ cannot use the `?` operator in a function that returns `()`\n |\nhelp: consider adding return type\n |\n3 ~ fn main() -> Result<(), Box> {\n4 | let greeting_file = File::open(\"hello.txt\")?;\n5 + Ok(())\n |\n\nFor more information about this error, try `rustc --explain E0277`.\nerror: could not compile `error-handling` (bin \"error-handling\") due to 1 previous error\n```\nThis error points out that we’re only allowed to use the `?` operator in a\nfunction that returns `Result`, `Option`, or another type that implements\n`FromResidual`.\nTo fix the error, you have two choices. One choice is to change the return type\nof your function to be compatible with the value you’re using the `?` operator\non as long as you have no restrictions preventing that. The other choice is to\nuse a `match` or one of the `Result` methods to handle the `Result`\nin whatever way is appropriate.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Recoverable Errors with `Result`", "heading_path": ["Recoverable Errors with `Result`", "Propagating Errors", "Where to Use the `?` Operator"], "path": "ch09-02-recoverable-errors-with-result.md", "url": "https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#where-to-use-the--operator", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch09-02-recoverable-errors-with-result.md#where-to-use-the--operator-15", "text": "The Rust Programming Language › Recoverable Errors with `Result` › Propagating Errors › Where to Use the `?` Operator\n\nThe error message also mentioned that `?` can be used with `Option` values\nas well. As with using `?` on `Result`, you can only use `?` on `Option` in a\nfunction that returns an `Option`. The behavior of the `?` operator when called\non an `Option` is similar to its behavior when called on a `Result`:\nIf the value is `None`, the `None` will be returned early from the function at\nthat point. If the value is `Some`, the value inside the `Some` is the\nresultant value of the expression, and the function continues. Listing 9-11 has\nan example of a function that finds the last character of the first line in the\ngiven text.\nListing 9-11\n```rust\nfn last_char_of_first_line(text: &str) -> Option {\n text.lines().next()?.chars().last()\n}\n```\nThis function returns `Option` because it’s possible that there is a\ncharacter there, but it’s also possible that there isn’t. This code takes the\n`text` string slice argument and calls the `lines` method on it, which returns\nan iterator over the lines in the string. Because this function wants to\nexamine the first line, it calls `next` on the iterator to get the first value\nfrom the iterator. If `text` is the empty string, this call to `next` will\nreturn `None`, in which case we use `?` to stop and return `None` from\n`last_char_of_first_line`. If `text` is not the empty string, `next` will\nreturn a `Some` value containing a string slice of the first line in `text`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Recoverable Errors with `Result`", "heading_path": ["Recoverable Errors with `Result`", "Propagating Errors", "Where to Use the `?` Operator"], "path": "ch09-02-recoverable-errors-with-result.md", "url": "https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#where-to-use-the--operator", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch09-02-recoverable-errors-with-result.md#where-to-use-the--operator-16", "text": "The Rust Programming Language › Recoverable Errors with `Result` › Propagating Errors › Where to Use the `?` Operator\n\nThe `?` extracts the string slice, and we can call `chars` on that string slice\nto get an iterator of its characters. We’re interested in the last character in\nthis first line, so we call `last` to return the last item in the iterator.\nThis is an `Option` because it’s possible that the first line is the empty\nstring; for example, if `text` starts with a blank line but has characters on\nother lines, as in `\"\\nhi\"`. However, if there is a last character on the first\nline, it will be returned in the `Some` variant. The `?` operator in the middle\ngives us a concise way to express this logic, allowing us to implement the\nfunction in one line. If we couldn’t use the `?` operator on `Option`, we’d\nhave to implement this logic using more method calls or a `match` expression.\nNote that you can use the `?` operator on a `Result` in a function that returns\n`Result`, and you can use the `?` operator on an `Option` in a function that\nreturns `Option`, but you can’t mix and match. The `?` operator won’t\nautomatically convert a `Result` to an `Option` or vice versa; in those cases,\nyou can use methods like the `ok` method on `Result` or the `ok_or` method on\n`Option` to do the conversion explicitly.\nSo far, all the `main` functions we’ve used return `()`. The `main` function is\nspecial because it’s the entry point and exit point of an executable program,\nand there are restrictions on what its return type can be for the program to\nbehave as expected.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Recoverable Errors with `Result`", "heading_path": ["Recoverable Errors with `Result`", "Propagating Errors", "Where to Use the `?` Operator"], "path": "ch09-02-recoverable-errors-with-result.md", "url": "https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#where-to-use-the--operator", "has_code": false, "code_tags": []}} {"id": "book/ch09-02-recoverable-errors-with-result.md#where-to-use-the--operator-17", "text": "The Rust Programming Language › Recoverable Errors with `Result` › Propagating Errors › Where to Use the `?` Operator\n\nLuckily, `main` can also return a `Result<(), E>`. Listing 9-12 has the code\nfrom Listing 9-10, but we’ve changed the return type of `main` to be\n`Result<(), Box>` and added a return value `Ok(())` to the end. This\ncode will now compile.\nListing 9-12 (src/main.rs)\n```rust,ignore\nuse std::error::Error;\nuse std::fs::File;\n\nfn main() -> Result<(), Box> {\n let greeting_file = File::open(\"hello.txt\")?;\n\n Ok(())\n}\n```\nThe `Box` type is a trait object, which we’ll talk about in “Using\nTrait Objects to Abstract over Shared Behavior”\nin Chapter 18. For now, you can read `Box` to mean “any kind of\nerror.” Using `?` on a `Result` value in a `main` function with the error type\n`Box` is allowed because it allows any `Err` value to be returned\nearly. Even though the body of this `main` function will only ever return\nerrors of type `std::io::Error`, by specifying `Box`, this signature\nwill continue to be correct even if more code that returns other errors is\nadded to the body of `main`.\nWhen a `main` function returns a `Result<(), E>`, the executable will exit with\na value of `0` if `main` returns `Ok(())` and will exit with a nonzero value if\n`main` returns an `Err` value. Executables written in C return integers when\nthey exit: Programs that exit successfully return the integer `0`, and programs\nthat error return some integer other than `0`. Rust also returns integers from\nexecutables to be compatible with this convention.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Recoverable Errors with `Result`", "heading_path": ["Recoverable Errors with `Result`", "Propagating Errors", "Where to Use the `?` Operator"], "path": "ch09-02-recoverable-errors-with-result.md", "url": "https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#where-to-use-the--operator", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch09-02-recoverable-errors-with-result.md#where-to-use-the--operator-18", "text": "The Rust Programming Language › Recoverable Errors with `Result` › Propagating Errors › Where to Use the `?` Operator\n\nThe `main` function may return any types that implement the\n`std::process::Termination` trait, which contains\na function `report` that returns an `ExitCode`. Consult the standard library\ndocumentation for more information on implementing the `Termination` trait for\nyour own types.\nNow that we’ve discussed the details of calling `panic!` or returning `Result`,\nlet’s return to the topic of how to decide which is appropriate to use in which\ncases.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Recoverable Errors with `Result`", "heading_path": ["Recoverable Errors with `Result`", "Propagating Errors", "Where to Use the `?` Operator"], "path": "ch09-02-recoverable-errors-with-result.md", "url": "https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#where-to-use-the--operator", "has_code": false, "code_tags": []}} {"id": "book/ch09-03-to-panic-or-not-to-panic.md#to-panic-or-not-to-panic-0", "text": "The Rust Programming Language › To `panic!` or Not to `panic!`\n\nSo, how do you decide when you should call `panic!` and when you should return\n`Result`? When code panics, there’s no way to recover. You could call `panic!`\nfor any error situation, whether there’s a possible way to recover or not, but\nthen you’re making the decision that a situation is unrecoverable on behalf of\nthe calling code. When you choose to return a `Result` value, you give the\ncalling code options. The calling code could choose to attempt to recover in a\nway that’s appropriate for its situation, or it could decide that an `Err`\nvalue in this case is unrecoverable, so it can call `panic!` and turn your\nrecoverable error into an unrecoverable one. Therefore, returning `Result` is a\ngood default choice when you’re defining a function that might fail.\nIn situations such as examples, prototype code, and tests, it’s more\nappropriate to write code that panics instead of returning a `Result`. Let’s\nexplore why, then discuss situations in which the compiler can’t tell that\nfailure is impossible, but you as a human can. The chapter will conclude with\nsome general guidelines on how to decide whether to panic in library code.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "To `panic!` or Not to `panic!`", "heading_path": ["To `panic!` or Not to `panic!`"], "path": "ch09-03-to-panic-or-not-to-panic.md", "url": "https://doc.rust-lang.org/book/ch09-03-to-panic-or-not-to-panic.html#to-panic-or-not-to-panic", "has_code": false, "code_tags": []}} {"id": "book/ch09-03-to-panic-or-not-to-panic.md#examples-prototype-code-and-tests-1", "text": "The Rust Programming Language › To `panic!` or Not to `panic!` › Examples, Prototype Code, and Tests\n\nWhen you’re writing an example to illustrate some concept, also including\nrobust error-handling code can make the example less clear. In examples, it’s\nunderstood that a call to a method like `unwrap` that could panic is meant as a\nplaceholder for the way you’d want your application to handle errors, which can\ndiffer based on what the rest of your code is doing.\nSimilarly, the `unwrap` and `expect` methods are very handy when you’re\nprototyping and you’re not yet ready to decide how to handle errors. They leave\nclear markers in your code for when you’re ready to make your program more\nrobust.\nIf a method call fails in a test, you’d want the whole test to fail, even if\nthat method isn’t the functionality under test. Because `panic!` is how a test\nis marked as a failure, calling `unwrap` or `expect` is exactly what should\nhappen.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "To `panic!` or Not to `panic!`", "heading_path": ["To `panic!` or Not to `panic!`", "Examples, Prototype Code, and Tests"], "path": "ch09-03-to-panic-or-not-to-panic.md", "url": "https://doc.rust-lang.org/book/ch09-03-to-panic-or-not-to-panic.html#examples-prototype-code-and-tests", "has_code": false, "code_tags": []}} {"id": "book/ch09-03-to-panic-or-not-to-panic.md#when-you-have-more-information-than-the-compiler-2", "text": "The Rust Programming Language › To `panic!` or Not to `panic!` › When You Have More Information Than the Compiler\n\nIt would also be appropriate to call `expect` when you have some other logic\nthat ensures that the `Result` will have an `Ok` value, but the logic isn’t\nsomething the compiler understands. You’ll still have a `Result` value that you\nneed to handle: Whatever operation you’re calling still has the possibility of\nfailing in general, even though it’s logically impossible in your particular\nsituation. If you can ensure by manually inspecting the code that you’ll never\nhave an `Err` variant, it’s perfectly acceptable to call `expect` and document\nthe reason you think you’ll never have an `Err` variant in the argument text.\nHere’s an example:\n```rust\n use std::net::IpAddr;\n\n let home: IpAddr = \"127.0.0.1\"\n .parse()\n .expect(\"Hardcoded IP address should be valid\");\n```\nWe’re creating an `IpAddr` instance by parsing a hardcoded string. We can see\nthat `127.0.0.1` is a valid IP address, so it’s acceptable to use `expect`\nhere. However, having a hardcoded, valid string doesn’t change the return type\nof the `parse` method: We still get a `Result` value, and the compiler will\nstill make us handle the `Result` as if the `Err` variant is a possibility\nbecause the compiler isn’t smart enough to see that this string is always a\nvalid IP address. If the IP address string came from a user rather than being\nhardcoded into the program and therefore _did_ have a possibility of failure,\nwe’d definitely want to handle the `Result` in a more robust way instead.\nMentioning the assumption that this IP address is hardcoded will prompt us to\nchange `expect` to better error-handling code if, in the future, we need to get\nthe IP address from some other source instead.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "To `panic!` or Not to `panic!`", "heading_path": ["To `panic!` or Not to `panic!`", "When You Have More Information Than the Compiler"], "path": "ch09-03-to-panic-or-not-to-panic.md", "url": "https://doc.rust-lang.org/book/ch09-03-to-panic-or-not-to-panic.html#when-you-have-more-information-than-the-compiler", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch09-03-to-panic-or-not-to-panic.md#guidelines-for-error-handling-3", "text": "The Rust Programming Language › To `panic!` or Not to `panic!` › Guidelines for Error Handling\n\nIt’s advisable to have your code panic when it’s possible that your code could\nend up in a bad state. In this context, a _bad state_ is when some assumption,\nguarantee, contract, or invariant has been broken, such as when invalid values,\ncontradictory values, or missing values are passed to your code—plus one or\nmore of the following:\n- The bad state is something that is unexpected, as opposed to something that\n will likely happen occasionally, like a user entering data in the wrong\n format.\n- Your code after this point needs to rely on not being in this bad state,\n rather than checking for the problem at every step.\n- There’s not a good way to encode this information in the types you use. We’ll\n work through an example of what we mean in “Encoding States and Behavior as\n Types” in Chapter 18.\nIf someone calls your code and passes in values that don’t make sense, it’s\nbest to return an error if you can so that the user of the library can decide\nwhat they want to do in that case. However, in cases where continuing could be\ninsecure or harmful, the best choice might be to call `panic!` and alert the\nperson using your library to the bug in their code so that they can fix it\nduring development. Similarly, `panic!` is often appropriate if you’re calling\nexternal code that is out of your control and returns an invalid state that you\nhave no way of fixing.\nHowever, when failure is expected, it’s more appropriate to return a `Result`\nthan to make a `panic!` call. Examples include a parser being given malformed\ndata or an HTTP request returning a status that indicates you have hit a rate\nlimit. In these cases, returning a `Result` indicates that failure is an\nexpected possibility that the calling code must decide how to handle.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "To `panic!` or Not to `panic!`", "heading_path": ["To `panic!` or Not to `panic!`", "Guidelines for Error Handling"], "path": "ch09-03-to-panic-or-not-to-panic.md", "url": "https://doc.rust-lang.org/book/ch09-03-to-panic-or-not-to-panic.html#guidelines-for-error-handling", "has_code": false, "code_tags": []}} {"id": "book/ch09-03-to-panic-or-not-to-panic.md#guidelines-for-error-handling-4", "text": "The Rust Programming Language › To `panic!` or Not to `panic!` › Guidelines for Error Handling\n\nWhen your code performs an operation that could put a user at risk if it’s\ncalled using invalid values, your code should verify the values are valid first\nand panic if the values aren’t valid. This is mostly for safety reasons:\nAttempting to operate on invalid data can expose your code to vulnerabilities.\nThis is the main reason the standard library will call `panic!` if you attempt\nan out-of-bounds memory access: Trying to access memory that doesn’t belong to\nthe current data structure is a common security problem. Functions often have\n_contracts_: Their behavior is only guaranteed if the inputs meet particular\nrequirements. Panicking when the contract is violated makes sense because a\ncontract violation always indicates a caller-side bug, and it’s not a kind of\nerror you want the calling code to have to explicitly handle. In fact, there’s\nno reasonable way for calling code to recover; the calling _programmers_ need\nto fix the code. Contracts for a function, especially when a violation will\ncause a panic, should be explained in the API documentation for the function.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "To `panic!` or Not to `panic!`", "heading_path": ["To `panic!` or Not to `panic!`", "Guidelines for Error Handling"], "path": "ch09-03-to-panic-or-not-to-panic.md", "url": "https://doc.rust-lang.org/book/ch09-03-to-panic-or-not-to-panic.html#guidelines-for-error-handling", "has_code": false, "code_tags": []}} {"id": "book/ch09-03-to-panic-or-not-to-panic.md#guidelines-for-error-handling-5", "text": "The Rust Programming Language › To `panic!` or Not to `panic!` › Guidelines for Error Handling\n\nHowever, having lots of error checks in all of your functions would be verbose\nand annoying. Fortunately, you can use Rust’s type system (and thus the type\nchecking done by the compiler) to do many of the checks for you. If your\nfunction has a particular type as a parameter, you can proceed with your code’s\nlogic knowing that the compiler has already ensured that you have a valid\nvalue. For example, if you have a type rather than an `Option`, your program\nexpects to have _something_ rather than _nothing_. Your code then doesn’t have\nto handle two cases for the `Some` and `None` variants: It will only have one\ncase for definitely having a value. Code trying to pass nothing to your\nfunction won’t even compile, so your function doesn’t have to check for that\ncase at runtime. Another example is using an unsigned integer type such as\n`u32`, which ensures that the parameter is never negative.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "To `panic!` or Not to `panic!`", "heading_path": ["To `panic!` or Not to `panic!`", "Guidelines for Error Handling"], "path": "ch09-03-to-panic-or-not-to-panic.md", "url": "https://doc.rust-lang.org/book/ch09-03-to-panic-or-not-to-panic.html#guidelines-for-error-handling", "has_code": false, "code_tags": []}} {"id": "book/ch09-03-to-panic-or-not-to-panic.md#custom-types-for-validation-6", "text": "The Rust Programming Language › To `panic!` or Not to `panic!` › Custom Types for Validation\n\nLet’s take the idea of using Rust’s type system to ensure that we have a valid\nvalue one step further and look at creating a custom type for validation.\nRecall the guessing game in Chapter 2 in which our code asked the user to guess\na number between 1 and 100. We never validated that the user’s guess was\nbetween those numbers before checking it against our secret number; we only\nvalidated that the guess was positive. In this case, the consequences were not\nvery dire: Our output of “Too high” or “Too low” would still be correct. But it\nwould be a useful enhancement to guide the user toward valid guesses and have\ndifferent behavior when the user guesses a number that’s out of range versus\nwhen the user types, for example, letters instead.\nOne way to do this would be to parse the guess as an `i32` instead of only a\n`u32` to allow potentially negative numbers, and then add a check for the\nnumber being in range, like so:\nListing (src/main.rs)\n```rust,ignore\n loop {\n // --snip--\n\n let guess: i32 = match guess.trim().parse() {\n Ok(num) => num,\n Err(_) => continue,\n };\n\n if guess < 1 || guess > 100 {\n println!(\"The secret number will be between 1 and 100.\");\n continue;\n }\n\n match guess.cmp(&secret_number) {\n // --snip--\n }\n```\nThe `if` expression checks whether our value is out of range, tells the user\nabout the problem, and calls `continue` to start the next iteration of the loop\nand ask for another guess. After the `if` expression, we can proceed with the\ncomparisons between `guess` and the secret number knowing that `guess` is\nbetween 1 and 100.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "To `panic!` or Not to `panic!`", "heading_path": ["To `panic!` or Not to `panic!`", "Custom Types for Validation"], "path": "ch09-03-to-panic-or-not-to-panic.md", "url": "https://doc.rust-lang.org/book/ch09-03-to-panic-or-not-to-panic.html#custom-types-for-validation", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch09-03-to-panic-or-not-to-panic.md#custom-types-for-validation-7", "text": "The Rust Programming Language › To `panic!` or Not to `panic!` › Custom Types for Validation\n\nHowever, this is not an ideal solution: If it were absolutely critical that the\nprogram only operated on values between 1 and 100, and it had many functions\nwith this requirement, having a check like this in every function would be\ntedious (and might impact performance).\nInstead, we can make a new type in a dedicated module and put the validations\nin a function to create an instance of the type rather than repeating the\nvalidations everywhere. That way, it’s safe for functions to use the new type\nin their signatures and confidently use the values they receive. Listing 9-13\nshows one way to define a `Guess` type that will only create an instance of\n`Guess` if the `new` function receives a value between 1 and 100.\nListing 9-13: A `Guess` type that will only continue with values between 1 and 100 (src/guessing_game.rs)\n```rust\npub struct Guess {\n value: i32,\n}\n\nimpl Guess {\n pub fn new(value: i32) -> Guess {\n if value < 1 || value > 100 {\n panic!(\"Guess value must be between 1 and 100, got {value}.\");\n }\n\n Guess { value }\n }\n\n pub fn value(&self) -> i32 {\n self.value\n }\n}\n```\nNote that this code in *src/guessing_game.rs* depends on adding a module\ndeclaration `mod guessing_game;` in *src/lib.rs* that we haven’t shown here.\nWithin this new module’s file, we define a struct named `Guess` that has a\nfield named `value` that holds an `i32`. This is where the number will be\nstored.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "To `panic!` or Not to `panic!`", "heading_path": ["To `panic!` or Not to `panic!`", "Custom Types for Validation"], "path": "ch09-03-to-panic-or-not-to-panic.md", "url": "https://doc.rust-lang.org/book/ch09-03-to-panic-or-not-to-panic.html#custom-types-for-validation", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch09-03-to-panic-or-not-to-panic.md#custom-types-for-validation-8", "text": "The Rust Programming Language › To `panic!` or Not to `panic!` › Custom Types for Validation\n\nThen, we implement an associated function named `new` on `Guess` that creates\ninstances of `Guess` values. The `new` function is defined to have one\nparameter named `value` of type `i32` and to return a `Guess`. The code in the\nbody of the `new` function tests `value` to make sure it’s between 1 and 100.\nIf `value` doesn’t pass this test, we make a `panic!` call, which will alert\nthe programmer who is writing the calling code that they have a bug they need\nto fix, because creating a `Guess` with a `value` outside this range would\nviolate the contract that `Guess::new` is relying on. The conditions in which\n`Guess::new` might panic should be discussed in its public-facing API\ndocumentation; we’ll cover documentation conventions indicating the possibility\nof a `panic!` in the API documentation that you create in Chapter 14. If\n`value` does pass the test, we create a new `Guess` with its `value` field set\nto the `value` parameter and return the `Guess`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "To `panic!` or Not to `panic!`", "heading_path": ["To `panic!` or Not to `panic!`", "Custom Types for Validation"], "path": "ch09-03-to-panic-or-not-to-panic.md", "url": "https://doc.rust-lang.org/book/ch09-03-to-panic-or-not-to-panic.html#custom-types-for-validation", "has_code": false, "code_tags": []}} {"id": "book/ch09-03-to-panic-or-not-to-panic.md#custom-types-for-validation-9", "text": "The Rust Programming Language › To `panic!` or Not to `panic!` › Custom Types for Validation\n\nNext, we implement a method named `value` that borrows `self`, doesn’t have any\nother parameters, and returns an `i32`. This kind of method is sometimes called\na _getter_ because its purpose is to get some data from its fields and return\nit. This public method is necessary because the `value` field of the `Guess`\nstruct is private. It’s important that the `value` field be private so that\ncode using the `Guess` struct is not allowed to set `value` directly: Code\noutside the `guessing_game` module _must_ use the `Guess::new` function to\ncreate an instance of `Guess`, thereby ensuring that there’s no way for a\n`Guess` to have a `value` that hasn’t been checked by the conditions in the\n`Guess::new` function.\nA function that has a parameter or returns only numbers between 1 and 100 could\nthen declare in its signature that it takes or returns a `Guess` rather than an\n`i32` and wouldn’t need to do any additional checks in its body.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "To `panic!` or Not to `panic!`", "heading_path": ["To `panic!` or Not to `panic!`", "Custom Types for Validation"], "path": "ch09-03-to-panic-or-not-to-panic.md", "url": "https://doc.rust-lang.org/book/ch09-03-to-panic-or-not-to-panic.html#custom-types-for-validation", "has_code": false, "code_tags": []}} {"id": "book/ch09-03-to-panic-or-not-to-panic.md#summary-10", "text": "The Rust Programming Language › Summary\n\nRust’s error-handling features are designed to help you write more robust code.\nThe `panic!` macro signals that your program is in a state it can’t handle and\nlets you tell the process to stop instead of trying to proceed with invalid or\nincorrect values. The `Result` enum uses Rust’s type system to indicate that\noperations might fail in a way that your code could recover from. You can use\n`Result` to tell code that calls your code that it needs to handle potential\nsuccess or failure as well. Using `panic!` and `Result` in the appropriate\nsituations will make your code more reliable in the face of inevitable problems.\nNow that you’ve seen useful ways that the standard library uses generics with\nthe `Option` and `Result` enums, we’ll talk about how generics work and how you\ncan use them in your code.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "To `panic!` or Not to `panic!`", "heading_path": ["Summary"], "path": "ch09-03-to-panic-or-not-to-panic.md", "url": "https://doc.rust-lang.org/book/ch09-03-to-panic-or-not-to-panic.html#summary", "has_code": false, "code_tags": []}} {"id": "book/ch10-00-generics.md#generic-types-traits-and-lifetimes-0", "text": "The Rust Programming Language › Generic Types, Traits, and Lifetimes\n\nEvery programming language has tools for effectively handling the duplication\nof concepts. In Rust, one such tool is _generics_: abstract stand-ins for\nconcrete types or other properties. We can express the behavior of generics or\nhow they relate to other generics without knowing what will be in their place\nwhen compiling and running the code.\nFunctions can take parameters of some generic type, instead of a concrete type\nlike `i32` or `String`, in the same way they take parameters with unknown\nvalues to run the same code on multiple concrete values. In fact, we already\nused generics in Chapter 6 with `Option`, in Chapter 8 with `Vec` and\n`HashMap`, and in Chapter 9 with `Result`. In this chapter, you’ll\nexplore how to define your own types, functions, and methods with generics!\nFirst, we’ll review how to extract a function to reduce code duplication. We’ll\nthen use the same technique to make a generic function from two functions that\ndiffer only in the types of their parameters. We’ll also explain how to use\ngeneric types in struct and enum definitions.\nThen, you’ll learn how to use traits to define behavior in a generic way. You\ncan combine traits with generic types to constrain a generic type to accept\nonly those types that have a particular behavior, as opposed to just any type.\nFinally, we’ll discuss _lifetimes_: a variety of generics that give the\ncompiler information about how references relate to each other. Lifetimes allow\nus to give the compiler enough information about borrowed values so that it can\nensure that references will be valid in more situations than it could without\nour help.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Generic Types, Traits, and Lifetimes", "heading_path": ["Generic Types, Traits, and Lifetimes"], "path": "ch10-00-generics.md", "url": "https://doc.rust-lang.org/book/ch10-00-generics.html#generic-types-traits-and-lifetimes", "has_code": false, "code_tags": []}} {"id": "book/ch10-00-generics.md#removing-duplication-by-extracting-a-function-1", "text": "The Rust Programming Language › Generic Types, Traits, and Lifetimes › Removing Duplication by Extracting a Function\n\nGenerics allow us to replace specific types with a placeholder that represents\nmultiple types to remove code duplication. Before diving into generics syntax,\nlet’s first look at how to remove duplication in a way that doesn’t involve\ngeneric types by extracting a function that replaces specific values with a\nplaceholder that represents multiple values. Then, we’ll apply the same\ntechnique to extract a generic function! By looking at how to recognize\nduplicated code you can extract into a function, you’ll start to recognize\nduplicated code that can use generics.\nWe’ll begin with the short program in Listing 10-1 that finds the largest\nnumber in a list.\nListing 10-1: Finding the largest number in a list of numbers (src/main.rs)\n```rust\nfn main() {\n let number_list = vec![34, 50, 25, 100, 65];\n\n let mut largest = &number_list[0];\n\n for number in &number_list {\n if number > largest {\n largest = number;\n }\n }\n\n println!(\"The largest number is {largest}\");\n}\n```\nWe store a list of integers in the variable `number_list` and place a reference\nto the first number in the list in a variable named `largest`. We then iterate\nthrough all the numbers in the list, and if the current number is greater than\nthe number stored in `largest`, we replace the reference in that variable.\nHowever, if the current number is less than or equal to the largest number seen\nso far, the variable doesn’t change, and the code moves on to the next number\nin the list. After considering all the numbers in the list, `largest` should\nrefer to the largest number, which in this case is 100.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Generic Types, Traits, and Lifetimes", "heading_path": ["Generic Types, Traits, and Lifetimes", "Removing Duplication by Extracting a Function"], "path": "ch10-00-generics.md", "url": "https://doc.rust-lang.org/book/ch10-00-generics.html#removing-duplication-by-extracting-a-function", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch10-00-generics.md#removing-duplication-by-extracting-a-function-2", "text": "The Rust Programming Language › Generic Types, Traits, and Lifetimes › Removing Duplication by Extracting a Function\n\nWe’ve now been tasked with finding the largest number in two different lists of\nnumbers. To do so, we can choose to duplicate the code in Listing 10-1 and use\nthe same logic at two different places in the program, as shown in Listing 10-2.\nListing 10-2: Code to find the largest number in *two* lists of numbers (src/main.rs)\n```rust\nfn main() {\n let number_list = vec![34, 50, 25, 100, 65];\n\n let mut largest = &number_list[0];\n\n for number in &number_list {\n if number > largest {\n largest = number;\n }\n }\n\n println!(\"The largest number is {largest}\");\n\n let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8];\n\n let mut largest = &number_list[0];\n\n for number in &number_list {\n if number > largest {\n largest = number;\n }\n }\n\n println!(\"The largest number is {largest}\");\n}\n```\nAlthough this code works, duplicating code is tedious and error-prone. We also\nhave to remember to update the code in multiple places when we want to change\nit.\nTo eliminate this duplication, we’ll create an abstraction by defining a\nfunction that operates on any list of integers passed in as a parameter. This\nsolution makes our code clearer and lets us express the concept of finding the\nlargest number in a list abstractly.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Generic Types, Traits, and Lifetimes", "heading_path": ["Generic Types, Traits, and Lifetimes", "Removing Duplication by Extracting a Function"], "path": "ch10-00-generics.md", "url": "https://doc.rust-lang.org/book/ch10-00-generics.html#removing-duplication-by-extracting-a-function", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch10-00-generics.md#removing-duplication-by-extracting-a-function-3", "text": "The Rust Programming Language › Generic Types, Traits, and Lifetimes › Removing Duplication by Extracting a Function\n\nIn Listing 10-3, we extract the code that finds the largest number into a\nfunction named `largest`. Then, we call the function to find the largest number\nin the two lists from Listing 10-2. We could also use the function on any other\nlist of `i32` values we might have in the future.\nListing 10-3: Abstracted code to find the largest number in two lists (src/main.rs)\n```rust\nfn largest(list: &[i32]) -> &i32 {\n let mut largest = &list[0];\n\n for item in list {\n if item > largest {\n largest = item;\n }\n }\n\n largest\n}\n\nfn main() {\n let number_list = vec![34, 50, 25, 100, 65];\n\n let result = largest(&number_list);\n println!(\"The largest number is {result}\");\n\n let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8];\n\n let result = largest(&number_list);\n println!(\"The largest number is {result}\");\n}\n```\nThe `largest` function has a parameter called `list`, which represents any\nconcrete slice of `i32` values we might pass into the function. As a result,\nwhen we call the function, the code runs on the specific values that we pass\nin.\nIn summary, here are the steps we took to change the code from Listing 10-2 to\nListing 10-3:\n1. Identify duplicate code.\n1. Extract the duplicate code into the body of the function, and specify the\n inputs and return values of that code in the function signature.\n1. Update the two instances of duplicated code to call the function instead.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Generic Types, Traits, and Lifetimes", "heading_path": ["Generic Types, Traits, and Lifetimes", "Removing Duplication by Extracting a Function"], "path": "ch10-00-generics.md", "url": "https://doc.rust-lang.org/book/ch10-00-generics.html#removing-duplication-by-extracting-a-function", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch10-00-generics.md#removing-duplication-by-extracting-a-function-4", "text": "The Rust Programming Language › Generic Types, Traits, and Lifetimes › Removing Duplication by Extracting a Function\n\nNext, we’ll use these same steps with generics to reduce code duplication. In\nthe same way that the function body can operate on an abstract `list` instead\nof specific values, generics allow code to operate on abstract types.\nFor example, say we had two functions: one that finds the largest item in a\nslice of `i32` values and one that finds the largest item in a slice of `char`\nvalues. How would we eliminate that duplication? Let’s find out!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Generic Types, Traits, and Lifetimes", "heading_path": ["Generic Types, Traits, and Lifetimes", "Removing Duplication by Extracting a Function"], "path": "ch10-00-generics.md", "url": "https://doc.rust-lang.org/book/ch10-00-generics.html#removing-duplication-by-extracting-a-function", "has_code": false, "code_tags": []}} {"id": "book/ch10-01-syntax.md#generic-data-types-0", "text": "The Rust Programming Language › Generic Data Types\n\nWe use generics to create definitions for items like function signatures or\nstructs, which we can then use with many different concrete data types. Let’s\nfirst look at how to define functions, structs, enums, and methods using\ngenerics. Then, we’ll discuss how generics affect code performance.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Generic Data Types", "heading_path": ["Generic Data Types"], "path": "ch10-01-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-01-syntax.html#generic-data-types", "has_code": false, "code_tags": []}} {"id": "book/ch10-01-syntax.md#in-function-definitions-1", "text": "The Rust Programming Language › Generic Data Types › In Function Definitions\n\nWhen defining a function that uses generics, we place the generics in the\nsignature of the function where we would usually specify the data types of the\nparameters and return value. Doing so makes our code more flexible and provides\nmore functionality to callers of our function while preventing code duplication.\nContinuing with our `largest` function, Listing 10-4 shows two functions that\nboth find the largest value in a slice. We’ll then combine these into a single\nfunction that uses generics.\nListing 10-4: Two functions that differ only in their names and in the types in their signatures (src/main.rs)\n```rust\nfn largest_i32(list: &[i32]) -> &i32 {\n let mut largest = &list[0];\n\n for item in list {\n if item > largest {\n largest = item;\n }\n }\n\n largest\n}\n\nfn largest_char(list: &[char]) -> &char {\n let mut largest = &list[0];\n\n for item in list {\n if item > largest {\n largest = item;\n }\n }\n\n largest\n}\n\nfn main() {\n let number_list = vec![34, 50, 25, 100, 65];\n\n let result = largest_i32(&number_list);\n println!(\"The largest number is {result}\");\n\n let char_list = vec!['y', 'm', 'a', 'q'];\n\n let result = largest_char(&char_list);\n println!(\"The largest char is {result}\");\n}\n```\nThe `largest_i32` function is the one we extracted in Listing 10-3 that finds\nthe largest `i32` in a slice. The `largest_char` function finds the largest\n`char` in a slice. The function bodies have the same code, so let’s eliminate\nthe duplication by introducing a generic type parameter in a single function.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Generic Data Types", "heading_path": ["Generic Data Types", "In Function Definitions"], "path": "ch10-01-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-01-syntax.html#in-function-definitions", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch10-01-syntax.md#in-function-definitions-2", "text": "The Rust Programming Language › Generic Data Types › In Function Definitions\n\nTo parameterize the types in a new single function, we need to name the type\nparameter, just as we do for the value parameters to a function. You can use\nany identifier as a type parameter name. But we’ll use `T` because, by\nconvention, type parameter names in Rust are short, often just one letter, and\nRust’s type-naming convention is UpperCamelCase. Short for _type_, `T` is the\ndefault choice of most Rust programmers.\nWhen we use a parameter in the body of the function, we have to declare the\nparameter name in the signature so that the compiler knows what that name\nmeans. Similarly, when we use a type parameter name in a function signature, we\nhave to declare the type parameter name before we use it. To define the generic\n`largest` function, we place type name declarations inside angle brackets,\n`<>`, between the name of the function and the parameter list, like this:\n```rust,ignore\nfn largest(list: &[T]) -> &T {\n```\nWe read this definition as “The function `largest` is generic over some type\n`T`.” This function has one parameter named `list`, which is a slice of values\nof type `T`. The `largest` function will return a reference to a value of the\nsame type `T`.\nListing 10-5 shows the combined `largest` function definition using the generic\ndata type in its signature. The listing also shows how we can call the function\nwith either a slice of `i32` values or `char` values. Note that this code won’t\ncompile yet.\nListing 10-5: The `largest` function using generic type parameters; this doesn’t compile yet (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Generic Data Types", "heading_path": ["Generic Data Types", "In Function Definitions"], "path": "ch10-01-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-01-syntax.html#in-function-definitions", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch10-01-syntax.md#in-function-definitions-3", "text": "The Rust Programming Language › Generic Data Types › In Function Definitions\n\n```rust,ignore,does_not_compile\nfn largest(list: &[T]) -> &T {\n let mut largest = &list[0];\n\n for item in list {\n if item > largest {\n largest = item;\n }\n }\n\n largest\n}\n\nfn main() {\n let number_list = vec![34, 50, 25, 100, 65];\n\n let result = largest(&number_list);\n println!(\"The largest number is {result}\");\n\n let char_list = vec!['y', 'm', 'a', 'q'];\n\n let result = largest(&char_list);\n println!(\"The largest char is {result}\");\n}\n```\nIf we compile this code right now, we’ll get this error:\n```console\n$ cargo run\n Compiling chapter10 v0.1.0 (file:///projects/chapter10)\nerror[E0369]: binary operation `>` cannot be applied to type `&T`\n --> src/main.rs:5:17\n |\n5 | if item > largest {\n | ---- ^ ------- &T\n | |\n | &T\n |\nhelp: consider restricting type parameter `T` with trait `PartialOrd`\n |\n1 | fn largest(list: &[T]) -> &T {\n | ++++++++++++++++++++++\n\nFor more information about this error, try `rustc --explain E0369`.\nerror: could not compile `chapter10` (bin \"chapter10\") due to 1 previous error\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Generic Data Types", "heading_path": ["Generic Data Types", "In Function Definitions"], "path": "ch10-01-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-01-syntax.html#in-function-definitions", "has_code": true, "code_tags": ["console", "rust,ignore,does_not_compile"]}} {"id": "book/ch10-01-syntax.md#in-function-definitions-4", "text": "The Rust Programming Language › Generic Data Types › In Function Definitions\n\nThe help text mentions `std::cmp::PartialOrd`, which is a trait, and we’re\ngoing to talk about traits in the next section. For now, know that this error\nstates that the body of `largest` won’t work for all possible types that `T`\ncould be. Because we want to compare values of type `T` in the body, we can\nonly use types whose values can be ordered. To enable comparisons, the standard\nlibrary has the `std::cmp::PartialOrd` trait that you can implement on types\n(see Appendix C for more on this trait). To fix Listing 10-5, we can follow the\nhelp text’s suggestion and restrict the types valid for `T` to only those that\nimplement `PartialOrd`. The listing will then compile, because the standard\nlibrary implements `PartialOrd` on both `i32` and `char`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Generic Data Types", "heading_path": ["Generic Data Types", "In Function Definitions"], "path": "ch10-01-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-01-syntax.html#in-function-definitions", "has_code": false, "code_tags": []}} {"id": "book/ch10-01-syntax.md#in-struct-definitions-5", "text": "The Rust Programming Language › Generic Data Types › In Struct Definitions\n\nWe can also define structs to use a generic type parameter in one or more\nfields using the `<>` syntax. Listing 10-6 defines a `Point` struct to hold\n`x` and `y` coordinate values of any type.\nListing 10-6 (src/main.rs)\n```rust\nstruct Point {\n x: T,\n y: T,\n}\n\nfn main() {\n let integer = Point { x: 5, y: 10 };\n let float = Point { x: 1.0, y: 4.0 };\n}\n```\nThe syntax for using generics in struct definitions is similar to that used in\nfunction definitions. First, we declare the name of the type parameter inside\nangle brackets just after the name of the struct. Then, we use the generic type\nin the struct definition where we would otherwise specify concrete data types.\nNote that because we’ve used only one generic type to define `Point`, this\ndefinition says that the `Point` struct is generic over some type `T`, and\nthe fields `x` and `y` are _both_ that same type, whatever that type may be. If\nwe create an instance of a `Point` that has values of different types, as in\nListing 10-7, our code won’t compile.\nListing 10-7: The fields `x` and `y` must be the same type because both have the same generic data type `T`. (src/main.rs)\n```rust,ignore,does_not_compile\nstruct Point {\n x: T,\n y: T,\n}\n\nfn main() {\n let wont_work = Point { x: 5, y: 4.0 };\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Generic Data Types", "heading_path": ["Generic Data Types", "In Struct Definitions"], "path": "ch10-01-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-01-syntax.html#in-struct-definitions", "has_code": true, "code_tags": ["rust", "rust,ignore,does_not_compile"]}} {"id": "book/ch10-01-syntax.md#in-struct-definitions-6", "text": "The Rust Programming Language › Generic Data Types › In Struct Definitions\n\nIn this example, when we assign the integer value `5` to `x`, we let the\ncompiler know that the generic type `T` will be an integer for this instance of\n`Point`. Then, when we specify `4.0` for `y`, which we’ve defined to have\nthe same type as `x`, we’ll get a type mismatch error like this:\n```console\n$ cargo run\n Compiling chapter10 v0.1.0 (file:///projects/chapter10)\nerror[E0308]: mismatched types\n --> src/main.rs:7:38\n |\n7 | let wont_work = Point { x: 5, y: 4.0 };\n | ^^^ expected integer, found floating-point number\n\nFor more information about this error, try `rustc --explain E0308`.\nerror: could not compile `chapter10` (bin \"chapter10\") due to 1 previous error\n```\nTo define a `Point` struct where `x` and `y` are both generics but could have\ndifferent types, we can use multiple generic type parameters. For example, in\nListing 10-8, we change the definition of `Point` to be generic over types `T`\nand `U` where `x` is of type `T` and `y` is of type `U`.\nListing 10-8 (src/main.rs)\n```rust\nstruct Point {\n x: T,\n y: U,\n}\n\nfn main() {\n let both_integer = Point { x: 5, y: 10 };\n let both_float = Point { x: 1.0, y: 4.0 };\n let integer_and_float = Point { x: 5, y: 4.0 };\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Generic Data Types", "heading_path": ["Generic Data Types", "In Struct Definitions"], "path": "ch10-01-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-01-syntax.html#in-struct-definitions", "has_code": true, "code_tags": ["console", "rust"]}} {"id": "book/ch10-01-syntax.md#in-struct-definitions-7", "text": "The Rust Programming Language › Generic Data Types › In Struct Definitions\n\nNow all the instances of `Point` shown are allowed! You can use as many generic\ntype parameters in a definition as you want, but using more than a few makes\nyour code hard to read. If you’re finding you need lots of generic types in\nyour code, it could indicate that your code needs restructuring into smaller\npieces.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Generic Data Types", "heading_path": ["Generic Data Types", "In Struct Definitions"], "path": "ch10-01-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-01-syntax.html#in-struct-definitions", "has_code": false, "code_tags": []}} {"id": "book/ch10-01-syntax.md#in-enum-definitions-8", "text": "The Rust Programming Language › Generic Data Types › In Enum Definitions\n\nAs we did with structs, we can define enums to hold generic data types in their\nvariants. Let’s take another look at the `Option` enum that the standard\nlibrary provides, which we used in Chapter 6:\n```rust\nenum Option {\n Some(T),\n None,\n}\n```\nThis definition should now make more sense to you. As you can see, the\n`Option` enum is generic over type `T` and has two variants: `Some`, which\nholds one value of type `T`, and a `None` variant that doesn’t hold any value.\nBy using the `Option` enum, we can express the abstract concept of an\noptional value, and because `Option` is generic, we can use this abstraction\nno matter what the type of the optional value is.\nEnums can use multiple generic types as well. The definition of the `Result`\nenum that we used in Chapter 9 is one example:\n```rust\nenum Result {\n Ok(T),\n Err(E),\n}\n```\nThe `Result` enum is generic over two types, `T` and `E`, and has two variants:\n`Ok`, which holds a value of type `T`, and `Err`, which holds a value of type\n`E`. This definition makes it convenient to use the `Result` enum anywhere we\nhave an operation that might succeed (return a value of some type `T`) or fail\n(return an error of some type `E`). In fact, this is what we used to open a\nfile in Listing 9-3, where `T` was filled in with the type `std::fs::File` when\nthe file was opened successfully and `E` was filled in with the type\n`std::io::Error` when there were problems opening the file.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Generic Data Types", "heading_path": ["Generic Data Types", "In Enum Definitions"], "path": "ch10-01-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-01-syntax.html#in-enum-definitions", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch10-01-syntax.md#in-enum-definitions-9", "text": "The Rust Programming Language › Generic Data Types › In Enum Definitions\n\nWhen you recognize situations in your code with multiple struct or enum\ndefinitions that differ only in the types of the values they hold, you can\navoid duplication by using generic types instead.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Generic Data Types", "heading_path": ["Generic Data Types", "In Enum Definitions"], "path": "ch10-01-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-01-syntax.html#in-enum-definitions", "has_code": false, "code_tags": []}} {"id": "book/ch10-01-syntax.md#in-method-definitions-10", "text": "The Rust Programming Language › Generic Data Types › In Method Definitions\n\nWe can implement methods on structs and enums (as we did in Chapter 5) and use\ngeneric types in their definitions too. Listing 10-9 shows the `Point`\nstruct we defined in Listing 10-6 with a method named `x` implemented on it.\nListing 10-9 (src/main.rs)\n```rust\nstruct Point {\n x: T,\n y: T,\n}\n\nimpl Point {\n fn x(&self) -> &T {\n &self.x\n }\n}\n\nfn main() {\n let p = Point { x: 5, y: 10 };\n\n println!(\"p.x = {}\", p.x());\n}\n```\nHere, we’ve defined a method named `x` on `Point` that returns a reference\nto the data in the field `x`.\nNote that we have to declare `T` just after `impl` so that we can use `T` to\nspecify that we’re implementing methods on the type `Point`. By declaring\n`T` as a generic type after `impl`, Rust can identify that the type in the\nangle brackets in `Point` is a generic type rather than a concrete type. We\ncould have chosen a different name for this generic parameter than the generic\nparameter declared in the struct definition, but using the same name is\nconventional. If you write a method within an `impl` that declares a generic\ntype, that method will be defined on any instance of the type, no matter what\nconcrete type ends up substituting for the generic type.\nWe can also specify constraints on generic types when defining methods on the\ntype. We could, for example, implement methods only on `Point` instances\nrather than on `Point` instances with any generic type. In Listing 10-10, we\nuse the concrete type `f32`, meaning we don’t declare any types after `impl`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Generic Data Types", "heading_path": ["Generic Data Types", "In Method Definitions"], "path": "ch10-01-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-01-syntax.html#in-method-definitions", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch10-01-syntax.md#in-method-definitions-11", "text": "The Rust Programming Language › Generic Data Types › In Method Definitions\n\nListing 10-10: An `impl` block that only applies to a struct with a particular concrete type for the generic type parameter `T` (src/main.rs)\n```rust\nimpl Point {\n fn distance_from_origin(&self) -> f32 {\n (self.x.powi(2) + self.y.powi(2)).sqrt()\n }\n}\n```\nThis code means the type `Point` will have a `distance_from_origin`\nmethod; other instances of `Point` where `T` is not of type `f32` will not\nhave this method defined. The method measures how far our point is from the\npoint at coordinates (0.0, 0.0) and uses mathematical operations that are\navailable only for floating-point types.\nGeneric type parameters in a struct definition aren’t always the same as those\nyou use in that same struct’s method signatures. Listing 10-11 uses the generic\ntypes `X1` and `Y1` for the `Point` struct and `X2` and `Y2` for the `mixup`\nmethod signature to make the example clearer. The method creates a new `Point`\ninstance with the `x` value from the `self` `Point` (of type `X1`) and the `y`\nvalue from the passed-in `Point` (of type `Y2`).\nListing 10-11: A method that uses generic types that are different from its struct’s definition (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Generic Data Types", "heading_path": ["Generic Data Types", "In Method Definitions"], "path": "ch10-01-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-01-syntax.html#in-method-definitions", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch10-01-syntax.md#in-method-definitions-12", "text": "The Rust Programming Language › Generic Data Types › In Method Definitions\n\n```rust\nstruct Point {\n x: X1,\n y: Y1,\n}\n\nimpl Point {\n fn mixup(self, other: Point) -> Point {\n Point {\n x: self.x,\n y: other.y,\n }\n }\n}\n\nfn main() {\n let p1 = Point { x: 5, y: 10.4 };\n let p2 = Point { x: \"Hello\", y: 'c' };\n\n let p3 = p1.mixup(p2);\n\n println!(\"p3.x = {}, p3.y = {}\", p3.x, p3.y);\n}\n```\nIn `main`, we’ve defined a `Point` that has an `i32` for `x` (with value `5`)\nand an `f64` for `y` (with value `10.4`). The `p2` variable is a `Point` struct\nthat has a string slice for `x` (with value `\"Hello\"`) and a `char` for `y`\n(with value `c`). Calling `mixup` on `p1` with the argument `p2` gives us `p3`,\nwhich will have an `i32` for `x` because `x` came from `p1`. The `p3` variable\nwill have a `char` for `y` because `y` came from `p2`. The `println!` macro\ncall will print `p3.x = 5, p3.y = c`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Generic Data Types", "heading_path": ["Generic Data Types", "In Method Definitions"], "path": "ch10-01-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-01-syntax.html#in-method-definitions", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch10-01-syntax.md#in-method-definitions-13", "text": "The Rust Programming Language › Generic Data Types › In Method Definitions\n\nThe purpose of this example is to demonstrate a situation in which some generic\nparameters are declared with `impl` and some are declared with the method\ndefinition. Here, the generic parameters `X1` and `Y1` are declared after\n`impl` because they go with the struct definition. The generic parameters `X2`\nand `Y2` are declared after `fn mixup` because they’re only relevant to the\nmethod.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Generic Data Types", "heading_path": ["Generic Data Types", "In Method Definitions"], "path": "ch10-01-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-01-syntax.html#in-method-definitions", "has_code": false, "code_tags": []}} {"id": "book/ch10-01-syntax.md#performance-of-code-using-generics-14", "text": "The Rust Programming Language › Generic Data Types › Performance of Code Using Generics\n\nYou might be wondering whether there is a runtime cost when using generic type\nparameters. The good news is that using generic types won’t make your program\nrun any slower than it would with concrete types.\nRust accomplishes this by performing monomorphization of the code using\ngenerics at compile time. _Monomorphization_ is the process of turning generic\ncode into specific code by filling in the concrete types that are used when\ncompiled. In this process, the compiler does the opposite of the steps we used\nto create the generic function in Listing 10-5: The compiler looks at all the\nplaces where generic code is called and generates code for the concrete types\nthe generic code is called with.\nLet’s look at how this works by using the standard library’s generic\n`Option` enum:\n```rust\nlet integer = Some(5);\nlet float = Some(5.0);\n```\nWhen Rust compiles this code, it performs monomorphization. During that\nprocess, the compiler reads the values that have been used in `Option`\ninstances and identifies two kinds of `Option`: One is `i32` and the other\nis `f64`. As such, it expands the generic definition of `Option` into two\ndefinitions specialized to `i32` and `f64`, thereby replacing the generic\ndefinition with the specific ones.\nThe monomorphized version of the code looks similar to the following (the\ncompiler uses different names than what we’re using here for illustration):\nListing (src/main.rs)\n```rust\nenum Option_i32 {\n Some(i32),\n None,\n}\n\nenum Option_f64 {\n Some(f64),\n None,\n}\n\nfn main() {\n let integer = Option_i32::Some(5);\n let float = Option_f64::Some(5.0);\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Generic Data Types", "heading_path": ["Generic Data Types", "Performance of Code Using Generics"], "path": "ch10-01-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-01-syntax.html#performance-of-code-using-generics", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch10-01-syntax.md#performance-of-code-using-generics-15", "text": "The Rust Programming Language › Generic Data Types › Performance of Code Using Generics\n\nThe generic `Option` is replaced with the specific definitions created by\nthe compiler. Because Rust compiles generic code into code that specifies the\ntype in each instance, we pay no runtime cost for using generics. When the code\nruns, it performs just as it would if we had duplicated each definition by\nhand. The process of monomorphization makes Rust’s generics extremely efficient\nat runtime.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Generic Data Types", "heading_path": ["Generic Data Types", "Performance of Code Using Generics"], "path": "ch10-01-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-01-syntax.html#performance-of-code-using-generics", "has_code": false, "code_tags": []}} {"id": "book/ch10-02-traits.md#defining-shared-behavior-with-traits-0", "text": "The Rust Programming Language › Defining Shared Behavior with Traits\n\nA _trait_ defines the functionality a particular type has and can share with\nother types. We can use traits to define shared behavior in an abstract way. We\ncan use _trait bounds_ to specify that a generic type can be any type that has\ncertain behavior.\nNote: Traits are similar to a feature often called _interfaces_ in other\nlanguages, although with some differences.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining Shared Behavior with Traits", "heading_path": ["Defining Shared Behavior with Traits"], "path": "ch10-02-traits.md", "url": "https://doc.rust-lang.org/book/ch10-02-traits.html#defining-shared-behavior-with-traits", "has_code": false, "code_tags": []}} {"id": "book/ch10-02-traits.md#defining-a-trait-1", "text": "The Rust Programming Language › Defining Shared Behavior with Traits › Defining a Trait\n\nA type’s behavior consists of the methods we can call on that type. Different\ntypes share the same behavior if we can call the same methods on all of those\ntypes. Trait definitions are a way to group method signatures together to\ndefine a set of behaviors necessary to accomplish some purpose.\nFor example, let’s say we have multiple structs that hold various kinds and\namounts of text: a `NewsArticle` struct that holds a news story filed in a\nparticular location and a `SocialPost` that can have, at most, 280 characters\nalong with metadata that indicates whether it was a new post, a repost, or a\nreply to another post.\nWe want to make a media aggregator library crate named `aggregator` that can\ndisplay summaries of data that might be stored in a `NewsArticle` or\n`SocialPost` instance. To do this, we need a summary from each type, and we’ll\nrequest that summary by calling a `summarize` method on an instance. Listing\n10-12 shows the definition of a public `Summary` trait that expresses this\nbehavior.\nListing 10-12: A `Summary` trait that consists of the behavior provided by a `summarize` method (src/lib.rs)\n```rust,noplayground\npub trait Summary {\n fn summarize(&self) -> String;\n}\n```\nHere, we declare a trait using the `trait` keyword and then the trait’s name,\nwhich is `Summary` in this case. We also declare the trait as `pub` so that\ncrates depending on this crate can make use of this trait too, as we’ll see in\na few examples. Inside the curly brackets, we declare the method signatures\nthat describe the behaviors of the types that implement this trait, which in\nthis case is `fn summarize(&self) -> String`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining Shared Behavior with Traits", "heading_path": ["Defining Shared Behavior with Traits", "Defining a Trait"], "path": "ch10-02-traits.md", "url": "https://doc.rust-lang.org/book/ch10-02-traits.html#defining-a-trait", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch10-02-traits.md#defining-a-trait-2", "text": "The Rust Programming Language › Defining Shared Behavior with Traits › Defining a Trait\n\nAfter the method signature, instead of providing an implementation within curly\nbrackets, we use a semicolon. Each type implementing this trait must provide\nits own custom behavior for the body of the method. The compiler will enforce\nthat any type that has the `Summary` trait will have the method `summarize`\ndefined with this signature exactly.\nA trait can have multiple methods in its body: The method signatures are listed\none per line, and each line ends in a semicolon.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining Shared Behavior with Traits", "heading_path": ["Defining Shared Behavior with Traits", "Defining a Trait"], "path": "ch10-02-traits.md", "url": "https://doc.rust-lang.org/book/ch10-02-traits.html#defining-a-trait", "has_code": false, "code_tags": []}} {"id": "book/ch10-02-traits.md#implementing-a-trait-on-a-type-3", "text": "The Rust Programming Language › Defining Shared Behavior with Traits › Implementing a Trait on a Type\n\nNow that we’ve defined the desired signatures of the `Summary` trait’s methods,\nwe can implement it on the types in our media aggregator. Listing 10-13 shows\nan implementation of the `Summary` trait on the `NewsArticle` struct that uses\nthe headline, the author, and the location to create the return value of\n`summarize`. For the `SocialPost` struct, we define `summarize` as the username\nfollowed by the entire text of the post, assuming that the post content is\nalready limited to 280 characters.\nListing 10-13: Implementing the `Summary` trait on the `NewsArticle` and `SocialPost` types (src/lib.rs)\n```rust,noplayground\npub struct NewsArticle {\n pub headline: String,\n pub location: String,\n pub author: String,\n pub content: String,\n}\n\nimpl Summary for NewsArticle {\n fn summarize(&self) -> String {\n format!(\"{}, by {} ({})\", self.headline, self.author, self.location)\n }\n}\n\npub struct SocialPost {\n pub username: String,\n pub content: String,\n pub reply: bool,\n pub repost: bool,\n}\n\nimpl Summary for SocialPost {\n fn summarize(&self) -> String {\n format!(\"{}: {}\", self.username, self.content)\n }\n}\n```\nImplementing a trait on a type is similar to implementing regular methods. The\ndifference is that after `impl`, we put the trait name we want to implement,\nthen use the `for` keyword, and then specify the name of the type we want to\nimplement the trait for. Within the `impl` block, we put the method signatures\nthat the trait definition has defined. Instead of adding a semicolon after each\nsignature, we use curly brackets and fill in the method body with the specific\nbehavior that we want the methods of the trait to have for the particular type.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining Shared Behavior with Traits", "heading_path": ["Defining Shared Behavior with Traits", "Implementing a Trait on a Type"], "path": "ch10-02-traits.md", "url": "https://doc.rust-lang.org/book/ch10-02-traits.html#implementing-a-trait-on-a-type", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch10-02-traits.md#implementing-a-trait-on-a-type-4", "text": "The Rust Programming Language › Defining Shared Behavior with Traits › Implementing a Trait on a Type\n\nNow that the library has implemented the `Summary` trait on `NewsArticle` and\n`SocialPost`, users of the crate can call the trait methods on instances of\n`NewsArticle` and `SocialPost` in the same way we call regular methods. The only\ndifference is that the user must bring the trait into scope as well as the\ntypes. Here’s an example of how a binary crate could use our `aggregator`\nlibrary crate:\n```rust,ignore\nuse aggregator::{SocialPost, Summary};\n\nfn main() {\n let post = SocialPost {\n username: String::from(\"horse_ebooks\"),\n content: String::from(\n \"of course, as you probably already know, people\",\n ),\n reply: false,\n repost: false,\n };\n\n println!(\"1 new post: {}\", post.summarize());\n}\n```\nThis code prints `1 new post: horse_ebooks: of course, as you probably already\nknow, people`.\nOther crates that depend on the `aggregator` crate can also bring the `Summary`\ntrait into scope to implement `Summary` on their own types. One restriction to\nnote is that we can implement a trait on a type only if either the trait or the\ntype, or both, are local to our crate. For example, we can implement standard\nlibrary traits like `Display` on a custom type like `SocialPost` as part of our\n`aggregator` crate functionality because the type `SocialPost` is local to our\n`aggregator` crate. We can also implement `Summary` on `Vec` in our\n`aggregator` crate because the trait `Summary` is local to our `aggregator`\ncrate.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining Shared Behavior with Traits", "heading_path": ["Defining Shared Behavior with Traits", "Implementing a Trait on a Type"], "path": "ch10-02-traits.md", "url": "https://doc.rust-lang.org/book/ch10-02-traits.html#implementing-a-trait-on-a-type", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch10-02-traits.md#implementing-a-trait-on-a-type-5", "text": "The Rust Programming Language › Defining Shared Behavior with Traits › Implementing a Trait on a Type\n\nBut we can’t implement external traits on external types. For example, we can’t\nimplement the `Display` trait on `Vec` within our `aggregator` crate,\nbecause `Display` and `Vec` are both defined in the standard library and\naren’t local to our `aggregator` crate. This restriction is part of a property\ncalled _coherence_, and more specifically the _orphan rule_, so named because\nthe parent type is not present. This rule ensures that other people’s code\ncan’t break your code and vice versa. Without the rule, two crates could\nimplement the same trait for the same type, and Rust wouldn’t know which\nimplementation to use.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining Shared Behavior with Traits", "heading_path": ["Defining Shared Behavior with Traits", "Implementing a Trait on a Type"], "path": "ch10-02-traits.md", "url": "https://doc.rust-lang.org/book/ch10-02-traits.html#implementing-a-trait-on-a-type", "has_code": false, "code_tags": []}} {"id": "book/ch10-02-traits.md#using-default-implementations-6", "text": "The Rust Programming Language › Defining Shared Behavior with Traits › Using Default Implementations\n\nSometimes it’s useful to have default behavior for some or all of the methods\nin a trait instead of requiring implementations for all methods on every type.\nThen, as we implement the trait on a particular type, we can keep or override\neach method’s default behavior.\nIn Listing 10-14, we specify a default string for the `summarize` method of the\n`Summary` trait instead of only defining the method signature, as we did in\nListing 10-12.\nListing 10-14: Defining a `Summary` trait with a default implementation of the `summarize` method (src/lib.rs)\n```rust,noplayground\npub trait Summary {\n fn summarize(&self) -> String {\n String::from(\"(Read more...)\")\n }\n}\n```\nTo use a default implementation to summarize instances of `NewsArticle`, we\nspecify an empty `impl` block with `impl Summary for NewsArticle {}`.\nEven though we’re no longer defining the `summarize` method on `NewsArticle`\ndirectly, we’ve provided a default implementation and specified that\n`NewsArticle` implements the `Summary` trait. As a result, we can still call\nthe `summarize` method on an instance of `NewsArticle`, like this:\n```rust,ignore\n let article = NewsArticle {\n headline: String::from(\"Penguins win the Stanley Cup Championship!\"),\n location: String::from(\"Pittsburgh, PA, USA\"),\n author: String::from(\"Iceburgh\"),\n content: String::from(\n \"The Pittsburgh Penguins once again are the best \\\n hockey team in the NHL.\",\n ),\n };\n\n println!(\"New article available! {}\", article.summarize());\n```\nThis code prints `New article available! (Read more...)`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining Shared Behavior with Traits", "heading_path": ["Defining Shared Behavior with Traits", "Using Default Implementations"], "path": "ch10-02-traits.md", "url": "https://doc.rust-lang.org/book/ch10-02-traits.html#using-default-implementations", "has_code": true, "code_tags": ["rust,ignore", "rust,noplayground"]}} {"id": "book/ch10-02-traits.md#using-default-implementations-7", "text": "The Rust Programming Language › Defining Shared Behavior with Traits › Using Default Implementations\n\nCreating a default implementation doesn’t require us to change anything about\nthe implementation of `Summary` on `SocialPost` in Listing 10-13. The reason is\nthat the syntax for overriding a default implementation is the same as the\nsyntax for implementing a trait method that doesn’t have a default\nimplementation.\nDefault implementations can call other methods in the same trait, even if those\nother methods don’t have a default implementation. In this way, a trait can\nprovide a lot of useful functionality and only require implementors to specify\na small part of it. For example, we could define the `Summary` trait to have a\n`summarize_author` method whose implementation is required, and then define a\n`summarize` method that has a default implementation that calls the\n`summarize_author` method:\n```rust,noplayground\npub trait Summary {\n fn summarize_author(&self) -> String;\n\n fn summarize(&self) -> String {\n format!(\"(Read more from {}...)\", self.summarize_author())\n }\n}\n```\nTo use this version of `Summary`, we only need to define `summarize_author`\nwhen we implement the trait on a type:\n```rust,ignore\nimpl Summary for SocialPost {\n fn summarize_author(&self) -> String {\n format!(\"@{}\", self.username)\n }\n}\n```\nAfter we define `summarize_author`, we can call `summarize` on instances of the\n`SocialPost` struct, and the default implementation of `summarize` will call the\ndefinition of `summarize_author` that we’ve provided. Because we’ve implemented\n`summarize_author`, the `Summary` trait has given us the behavior of the\n`summarize` method without requiring us to write any more code. Here’s what\nthat looks like:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining Shared Behavior with Traits", "heading_path": ["Defining Shared Behavior with Traits", "Using Default Implementations"], "path": "ch10-02-traits.md", "url": "https://doc.rust-lang.org/book/ch10-02-traits.html#using-default-implementations", "has_code": true, "code_tags": ["rust,ignore", "rust,noplayground"]}} {"id": "book/ch10-02-traits.md#using-default-implementations-8", "text": "The Rust Programming Language › Defining Shared Behavior with Traits › Using Default Implementations\n\n```rust,ignore\n let post = SocialPost {\n username: String::from(\"horse_ebooks\"),\n content: String::from(\n \"of course, as you probably already know, people\",\n ),\n reply: false,\n repost: false,\n };\n\n println!(\"1 new post: {}\", post.summarize());\n```\nThis code prints `1 new post: (Read more from @horse_ebooks...)`.\nNote that it isn’t possible to call the default implementation from an\noverriding implementation of that same method.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining Shared Behavior with Traits", "heading_path": ["Defining Shared Behavior with Traits", "Using Default Implementations"], "path": "ch10-02-traits.md", "url": "https://doc.rust-lang.org/book/ch10-02-traits.html#using-default-implementations", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch10-02-traits.md#trait-bound-syntax-9", "text": "The Rust Programming Language › Defining Shared Behavior with Traits › Using Traits as Parameters › Trait Bound Syntax\n\nNow that you know how to define and implement traits, we can explore how to use\ntraits to define functions that accept many different types. We’ll use the\n`Summary` trait we implemented on the `NewsArticle` and `SocialPost` types in\nListing 10-13 to define a `notify` function that calls the `summarize` method\non its `item` parameter, which is of some type that implements the `Summary`\ntrait. To do this, we use the `impl Trait` syntax, like this:\n```rust,ignore\npub fn notify(item: &impl Summary) {\n println!(\"Breaking news! {}\", item.summarize());\n}\n```\nInstead of a concrete type for the `item` parameter, we specify the `impl`\nkeyword and the trait name. This parameter accepts any type that implements the\nspecified trait. In the body of `notify`, we can call any methods on `item`\nthat come from the `Summary` trait, such as `summarize`. We can call `notify`\nand pass in any instance of `NewsArticle` or `SocialPost`. Code that calls the\nfunction with any other type, such as a `String` or an `i32`, won’t compile,\nbecause those types don’t implement `Summary`.\nThe `impl Trait` syntax works for straightforward cases but is actually syntax\nsugar for a longer form known as a _trait bound_; it looks like this:\n```rust,ignore\npub fn notify(item: &T) {\n println!(\"Breaking news! {}\", item.summarize());\n}\n```\nThis longer form is equivalent to the example in the previous section but is\nmore verbose. We place trait bounds with the declaration of the generic type\nparameter after a colon and inside angle brackets.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining Shared Behavior with Traits", "heading_path": ["Defining Shared Behavior with Traits", "Using Traits as Parameters", "Trait Bound Syntax"], "path": "ch10-02-traits.md", "url": "https://doc.rust-lang.org/book/ch10-02-traits.html#trait-bound-syntax", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch10-02-traits.md#clearer-trait-bounds-with-where-clauses-10", "text": "The Rust Programming Language › Defining Shared Behavior with Traits › Using Traits as Parameters › Clearer Trait Bounds with `where` Clauses\n\nThe `impl Trait` syntax is convenient and makes for more concise code in simple\ncases, while the fuller trait bound syntax can express more complexity in other\ncases. For example, we can have two parameters that implement `Summary`. Doing\nso with the `impl Trait` syntax looks like this:\n```rust,ignore\npub fn notify(item1: &impl Summary, item2: &impl Summary) {\n```\nUsing `impl Trait` is appropriate if we want this function to allow `item1` and\n`item2` to have different types (as long as both types implement `Summary`). If\nwe want to force both parameters to have the same type, however, we must use a\ntrait bound, like this:\n```rust,ignore\npub fn notify(item1: &T, item2: &T) {\n```\nThe generic type `T` specified as the type of the `item1` and `item2`\nparameters constrains the function such that the concrete type of the value\npassed as an argument for `item1` and `item2` must be the same.\nWe can also specify more than one trait bound. Say we wanted `notify` to use\ndisplay formatting as well as `summarize` on `item`: We specify in the `notify`\ndefinition that `item` must implement both `Display` and `Summary`. We can do\nso using the `+` syntax:\n```rust,ignore\npub fn notify(item: &(impl Summary + Display)) {\n```\nThe `+` syntax is also valid with trait bounds on generic types:\n```rust,ignore\npub fn notify(item: &T) {\n```\nWith the two trait bounds specified, the body of `notify` can call `summarize`\nand use `{}` to format `item`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining Shared Behavior with Traits", "heading_path": ["Defining Shared Behavior with Traits", "Using Traits as Parameters", "Clearer Trait Bounds with `where` Clauses"], "path": "ch10-02-traits.md", "url": "https://doc.rust-lang.org/book/ch10-02-traits.html#clearer-trait-bounds-with-where-clauses", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch10-02-traits.md#clearer-trait-bounds-with-where-clauses-11", "text": "The Rust Programming Language › Defining Shared Behavior with Traits › Using Traits as Parameters › Clearer Trait Bounds with `where` Clauses\n\nUsing too many trait bounds has its downsides. Each generic has its own trait\nbounds, so functions with multiple generic type parameters can contain lots of\ntrait bound information between the function’s name and its parameter list,\nmaking the function signature hard to read. For this reason, Rust has alternate\nsyntax for specifying trait bounds inside a `where` clause after the function\nsignature. So, instead of writing this:\n```rust,ignore\nfn some_function(t: &T, u: &U) -> i32 {\n```\nwe can use a `where` clause, like this:\n```rust,ignore\nfn some_function(t: &T, u: &U) -> i32\nwhere\n T: Display + Clone,\n U: Clone + Debug,\n{\n```\nThis function’s signature is less cluttered: The function name, parameter list,\nand return type are close together, similar to a function without lots of trait\nbounds.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining Shared Behavior with Traits", "heading_path": ["Defining Shared Behavior with Traits", "Using Traits as Parameters", "Clearer Trait Bounds with `where` Clauses"], "path": "ch10-02-traits.md", "url": "https://doc.rust-lang.org/book/ch10-02-traits.html#clearer-trait-bounds-with-where-clauses", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch10-02-traits.md#returning-types-that-implement-traits-12", "text": "The Rust Programming Language › Defining Shared Behavior with Traits › Returning Types That Implement Traits\n\nWe can also use the `impl Trait` syntax in the return position to return a\nvalue of some type that implements a trait, as shown here:\n```rust,ignore\nfn returns_summarizable() -> impl Summary {\n SocialPost {\n username: String::from(\"horse_ebooks\"),\n content: String::from(\n \"of course, as you probably already know, people\",\n ),\n reply: false,\n repost: false,\n }\n}\n```\nBy using `impl Summary` for the return type, we specify that the\n`returns_summarizable` function returns some type that implements the `Summary`\ntrait without naming the concrete type. In this case, `returns_summarizable`\nreturns a `SocialPost`, but the code calling this function doesn’t need to know\nthat.\nThe ability to specify a return type only by the trait it implements is\nespecially useful in the context of closures and iterators, which we cover in\nChapter 13. Closures and iterators create types that only the compiler knows or\ntypes that are very long to specify. The `impl Trait` syntax lets you concisely\nspecify that a function returns some type that implements the `Iterator` trait\nwithout needing to write out a very long type.\nHowever, you can only use `impl Trait` if you’re returning a single type. For\nexample, this code that returns either a `NewsArticle` or a `SocialPost` with\nthe return type specified as `impl Summary` wouldn’t work:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining Shared Behavior with Traits", "heading_path": ["Defining Shared Behavior with Traits", "Returning Types That Implement Traits"], "path": "ch10-02-traits.md", "url": "https://doc.rust-lang.org/book/ch10-02-traits.html#returning-types-that-implement-traits", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch10-02-traits.md#returning-types-that-implement-traits-13", "text": "The Rust Programming Language › Defining Shared Behavior with Traits › Returning Types That Implement Traits\n\n```rust,ignore,does_not_compile\nfn returns_summarizable(switch: bool) -> impl Summary {\n if switch {\n NewsArticle {\n headline: String::from(\n \"Penguins win the Stanley Cup Championship!\",\n ),\n location: String::from(\"Pittsburgh, PA, USA\"),\n author: String::from(\"Iceburgh\"),\n content: String::from(\n \"The Pittsburgh Penguins once again are the best \\\n hockey team in the NHL.\",\n ),\n }\n } else {\n SocialPost {\n username: String::from(\"horse_ebooks\"),\n content: String::from(\n \"of course, as you probably already know, people\",\n ),\n reply: false,\n repost: false,\n }\n }\n}\n```\nReturning either a `NewsArticle` or a `SocialPost` isn’t allowed due to\nrestrictions around how the `impl Trait` syntax is implemented in the compiler.\nWe’ll cover how to write a function with this behavior in the “Using Trait\nObjects to Abstract over Shared Behavior”\nsection of Chapter 18.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining Shared Behavior with Traits", "heading_path": ["Defining Shared Behavior with Traits", "Returning Types That Implement Traits"], "path": "ch10-02-traits.md", "url": "https://doc.rust-lang.org/book/ch10-02-traits.html#returning-types-that-implement-traits", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch10-02-traits.md#using-trait-bounds-to-conditionally-implement-methods-14", "text": "The Rust Programming Language › Defining Shared Behavior with Traits › Using Trait Bounds to Conditionally Implement Methods\n\nBy using a trait bound with an `impl` block that uses generic type parameters,\nwe can implement methods conditionally for types that implement the specified\ntraits. For example, the type `Pair` in Listing 10-15 always implements the\n`new` function to return a new instance of `Pair` (recall from the “Method\nSyntax” section of Chapter 5 that `Self` is a type\nalias for the type of the `impl` block, which in this case is `Pair`). But\nin the next `impl` block, `Pair` only implements the `cmp_display` method if\nits inner type `T` implements the `PartialOrd` trait that enables comparison\n_and_ the `Display` trait that enables printing.\nListing 10-15: Conditionally implementing methods on a generic type depending on trait bounds (src/lib.rs)\n```rust,noplayground\nuse std::fmt::Display;\n\nstruct Pair {\n x: T,\n y: T,\n}\n\nimpl Pair {\n fn new(x: T, y: T) -> Self {\n Self { x, y }\n }\n}\n\nimpl Pair {\n fn cmp_display(&self) {\n if self.x >= self.y {\n println!(\"The largest member is x = {}\", self.x);\n } else {\n println!(\"The largest member is y = {}\", self.y);\n }\n }\n}\n```\nWe can also conditionally implement a trait for any type that implements\nanother trait. Implementations of a trait on any type that satisfies the trait\nbounds are called _blanket implementations_ and are used extensively in the\nRust standard library. For example, the standard library implements the\n`ToString` trait on any type that implements the `Display` trait. The `impl`\nblock in the standard library looks similar to this code:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining Shared Behavior with Traits", "heading_path": ["Defining Shared Behavior with Traits", "Using Trait Bounds to Conditionally Implement Methods"], "path": "ch10-02-traits.md", "url": "https://doc.rust-lang.org/book/ch10-02-traits.html#using-trait-bounds-to-conditionally-implement-methods", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch10-02-traits.md#using-trait-bounds-to-conditionally-implement-methods-15", "text": "The Rust Programming Language › Defining Shared Behavior with Traits › Using Trait Bounds to Conditionally Implement Methods\n\n```rust,ignore\nimpl ToString for T {\n // --snip--\n}\n```\nBecause the standard library has this blanket implementation, we can call the\n`to_string` method defined by the `ToString` trait on any type that implements\nthe `Display` trait. For example, we can turn integers into their corresponding\n`String` values like this because integers implement `Display`:\n```rust\nlet s = 3.to_string();\n```\nBlanket implementations appear in the documentation for the trait in the\n“Implementors” section.\nTraits and trait bounds let us write code that uses generic type parameters to\nreduce duplication but also specify to the compiler that we want the generic\ntype to have particular behavior. The compiler can then use the trait bound\ninformation to check that all the concrete types used with our code provide the\ncorrect behavior. In dynamically typed languages, we would get an error at\nruntime if we called a method on a type that didn’t define the method. But Rust\nmoves these errors to compile time so that we’re forced to fix the problems\nbefore our code is even able to run. Additionally, we don’t have to write code\nthat checks for behavior at runtime, because we’ve already checked at compile\ntime. Doing so improves performance without having to give up the flexibility\nof generics.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Defining Shared Behavior with Traits", "heading_path": ["Defining Shared Behavior with Traits", "Using Trait Bounds to Conditionally Implement Methods"], "path": "ch10-02-traits.md", "url": "https://doc.rust-lang.org/book/ch10-02-traits.html#using-trait-bounds-to-conditionally-implement-methods", "has_code": true, "code_tags": ["rust", "rust,ignore"]}} {"id": "book/ch10-03-lifetime-syntax.md#validating-references-with-lifetimes-0", "text": "The Rust Programming Language › Validating References with Lifetimes\n\nLifetimes are another kind of generic that we’ve already been using. Rather\nthan ensuring that a type has the behavior we want, lifetimes ensure that\nreferences are valid as long as we need them to be.\nOne detail we didn’t discuss in the “References and\nBorrowing” section in Chapter 4 is\nthat every reference in Rust has a lifetime, which is the scope for which\nthat reference is valid. Most of the time, lifetimes are implicit and inferred,\njust like most of the time, types are inferred. We are only required to\nannotate types when multiple types are possible. In a similar way, we must\nannotate lifetimes when the lifetimes of references could be related in a few\ndifferent ways. Rust requires us to annotate the relationships using generic\nlifetime parameters to ensure that the actual references used at runtime will\ndefinitely be valid.\nAnnotating lifetimes is not even a concept most other programming languages\nhave, so this is going to feel unfamiliar. Although we won’t cover lifetimes in\ntheir entirety in this chapter, we’ll discuss common ways you might encounter\nlifetime syntax so that you can get comfortable with the concept.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Validating References with Lifetimes", "heading_path": ["Validating References with Lifetimes"], "path": "ch10-03-lifetime-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#validating-references-with-lifetimes", "has_code": false, "code_tags": []}} {"id": "book/ch10-03-lifetime-syntax.md#dangling-references-1", "text": "The Rust Programming Language › Validating References with Lifetimes › Dangling References\n\nThe main aim of lifetimes is to prevent dangling references, which, if they\nwere allowed to exist, would cause a program to reference data other than the\ndata it’s intended to reference. Consider the program in Listing 10-16, which\nhas an outer scope and an inner scope.\nListing 10-16: An attempt to use a reference whose value has gone out of scope\n```rust,ignore,does_not_compile\nfn main() {\n let r;\n\n {\n let x = 5;\n r = &x;\n }\n\n println!(\"r: {r}\");\n}\n```\nNote: The examples in Listings 10-16, 10-17, and 10-23 declare variables\nwithout giving them an initial value, so the variable name exists in the outer\nscope. At first glance, this might appear to be in conflict with Rust having\nno null values. However, if we try to use a variable before giving it a value,\nwe’ll get a compile-time error, which shows that indeed Rust does not allow\nnull values.\nThe outer scope declares a variable named `r` with no initial value, and the\ninner scope declares a variable named `x` with the initial value of `5`. Inside\nthe inner scope, we attempt to set the value of `r` as a reference to `x`.\nThen, the inner scope ends, and we attempt to print the value in `r`. This code\nwon’t compile, because the value that `r` is referring to has gone out of scope\nbefore we try to use it. Here is the error message:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Validating References with Lifetimes", "heading_path": ["Validating References with Lifetimes", "Dangling References"], "path": "ch10-03-lifetime-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#dangling-references", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch10-03-lifetime-syntax.md#dangling-references-2", "text": "The Rust Programming Language › Validating References with Lifetimes › Dangling References\n\n```console\n$ cargo run\n Compiling chapter10 v0.1.0 (file:///projects/chapter10)\nerror[E0597]: `x` does not live long enough\n --> src/main.rs:6:13\n |\n5 | let x = 5;\n | - binding `x` declared here\n6 | r = &x;\n | ^^ borrowed value does not live long enough\n7 | }\n | - `x` dropped here while still borrowed\n8 |\n9 | println!(\"r: {r}\");\n | - borrow later used here\n\nFor more information about this error, try `rustc --explain E0597`.\nerror: could not compile `chapter10` (bin \"chapter10\") due to 1 previous error\n```\nThe error message says that the variable `x` “does not live long enough.” The\nreason is that `x` will be out of scope when the inner scope ends on line 7.\nBut `r` is still valid for the outer scope; because its scope is larger, we say\nthat it “lives longer.” If Rust allowed this code to work, `r` would be\nreferencing memory that was deallocated when `x` went out of scope, and\nanything we tried to do with `r` wouldn’t work correctly. So, how does Rust\ndetermine that this code is invalid? It uses a borrow checker.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Validating References with Lifetimes", "heading_path": ["Validating References with Lifetimes", "Dangling References"], "path": "ch10-03-lifetime-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#dangling-references", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch10-03-lifetime-syntax.md#the-borrow-checker-3", "text": "The Rust Programming Language › Validating References with Lifetimes › The Borrow Checker\n\nThe Rust compiler has a _borrow checker_ that compares scopes to determine\nwhether all borrows are valid. Listing 10-17 shows the same code as Listing\n10-16 but with annotations showing the lifetimes of the variables.\nListing 10-17: Annotations of the lifetimes of `r` and `x`, named `'a` and `'b`, respectively\n```rust,ignore,does_not_compile\nfn main() {\n let r; // ---------+-- 'a\n // |\n { // |\n let x = 5; // -+-- 'b |\n r = &x; // | |\n } // -+ |\n // |\n println!(\"r: {r}\"); // |\n} // ---------+\n```\nHere, we’ve annotated the lifetime of `r` with `'a` and the lifetime of `x`\nwith `'b`. As you can see, the inner `'b` block is much smaller than the outer\n`'a` lifetime block. At compile time, Rust compares the size of the two\nlifetimes and sees that `r` has a lifetime of `'a` but that it refers to memory\nwith a lifetime of `'b`. The program is rejected because `'b` is shorter than\n`'a`: The subject of the reference doesn’t live as long as the reference.\nListing 10-18 fixes the code so that it doesn’t have a dangling reference and\nit compiles without any errors.\nListing 10-18: A valid reference because the data has a longer lifetime than the reference", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Validating References with Lifetimes", "heading_path": ["Validating References with Lifetimes", "The Borrow Checker"], "path": "ch10-03-lifetime-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#the-borrow-checker", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch10-03-lifetime-syntax.md#the-borrow-checker-4", "text": "The Rust Programming Language › Validating References with Lifetimes › The Borrow Checker\n\n```rust\nfn main() {\n let x = 5; // ----------+-- 'b\n // |\n let r = &x; // --+-- 'a |\n // | |\n println!(\"r: {r}\"); // | |\n // --+ |\n} // ----------+\n```\nHere, `x` has the lifetime `'b`, which in this case is larger than `'a`. This\nmeans `r` can reference `x` because Rust knows that the reference in `r` will\nalways be valid while `x` is valid.\nNow that you know where the lifetimes of references are and how Rust analyzes\nlifetimes to ensure that references will always be valid, let’s explore generic\nlifetimes in function parameters and return values.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Validating References with Lifetimes", "heading_path": ["Validating References with Lifetimes", "The Borrow Checker"], "path": "ch10-03-lifetime-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#the-borrow-checker", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch10-03-lifetime-syntax.md#generic-lifetimes-in-functions-5", "text": "The Rust Programming Language › Validating References with Lifetimes › Generic Lifetimes in Functions\n\nWe’ll write a function that returns the longer of two string slices. This\nfunction will take two string slices and return a single string slice. After\nwe’ve implemented the `longest` function, the code in Listing 10-19 should\nprint `The longest string is abcd`.\nListing 10-19: A `main` function that calls the `longest` function to find the longer of two string slices (src/main.rs)\n```rust,ignore\nfn main() {\n let string1 = String::from(\"abcd\");\n let string2 = \"xyz\";\n\n let result = longest(string1.as_str(), string2);\n println!(\"The longest string is {result}\");\n}\n```\nNote that we want the function to take string slices, which are references,\nrather than strings, because we don’t want the `longest` function to take\nownership of its parameters. Refer to “String Slices as\nParameters” in Chapter 4 for more\ndiscussion about why the parameters we use in Listing 10-19 are the ones we\nwant.\nIf we try to implement the `longest` function as shown in Listing 10-20, it\nwon’t compile.\nListing 10-20: An implementation of the `longest` function that returns the longer of two string slices but does not yet compile (src/main.rs)\n```rust,ignore,does_not_compile\nfn longest(x: &str, y: &str) -> &str {\n if x.len() > y.len() { x } else { y }\n}\n```\nInstead, we get the following error that talks about lifetimes:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Validating References with Lifetimes", "heading_path": ["Validating References with Lifetimes", "Generic Lifetimes in Functions"], "path": "ch10-03-lifetime-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#generic-lifetimes-in-functions", "has_code": true, "code_tags": ["rust,ignore", "rust,ignore,does_not_compile"]}} {"id": "book/ch10-03-lifetime-syntax.md#generic-lifetimes-in-functions-6", "text": "The Rust Programming Language › Validating References with Lifetimes › Generic Lifetimes in Functions\n\n```console\n$ cargo run\n Compiling chapter10 v0.1.0 (file:///projects/chapter10)\nerror[E0106]: missing lifetime specifier\n --> src/main.rs:9:33\n |\n9 | fn longest(x: &str, y: &str) -> &str {\n | ---- ---- ^ expected named lifetime parameter\n |\n = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `x` or `y`\nhelp: consider introducing a named lifetime parameter\n |\n9 | fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {\n | ++++ ++ ++ ++\n\nFor more information about this error, try `rustc --explain E0106`.\nerror: could not compile `chapter10` (bin \"chapter10\") due to 1 previous error\n```\nThe help text reveals that the return type needs a generic lifetime parameter\non it because Rust can’t tell whether the reference being returned refers to\n`x` or `y`. Actually, we don’t know either, because the `if` block in the body\nof this function returns a reference to `x` and the `else` block returns a\nreference to `y`!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Validating References with Lifetimes", "heading_path": ["Validating References with Lifetimes", "Generic Lifetimes in Functions"], "path": "ch10-03-lifetime-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#generic-lifetimes-in-functions", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch10-03-lifetime-syntax.md#generic-lifetimes-in-functions-7", "text": "The Rust Programming Language › Validating References with Lifetimes › Generic Lifetimes in Functions\n\nWhen we’re defining this function, we don’t know the concrete values that will\nbe passed into this function, so we don’t know whether the `if` case or the\n`else` case will execute. We also don’t know the concrete lifetimes of the\nreferences that will be passed in, so we can’t look at the scopes as we did in\nListings 10-17 and 10-18 to determine whether the reference we return will\nalways be valid. The borrow checker can’t determine this either, because it\ndoesn’t know how the lifetimes of `x` and `y` relate to the lifetime of the\nreturn value. To fix this error, we’ll add generic lifetime parameters that\ndefine the relationship between the references so that the borrow checker can\nperform its analysis.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Validating References with Lifetimes", "heading_path": ["Validating References with Lifetimes", "Generic Lifetimes in Functions"], "path": "ch10-03-lifetime-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#generic-lifetimes-in-functions", "has_code": false, "code_tags": []}} {"id": "book/ch10-03-lifetime-syntax.md#lifetime-annotation-syntax-8", "text": "The Rust Programming Language › Validating References with Lifetimes › Lifetime Annotation Syntax\n\nLifetime annotations don’t change how long any of the references live. Rather,\nthey describe the relationships of the lifetimes of multiple references to each\nother without affecting the lifetimes. Just as functions can accept any type\nwhen the signature specifies a generic type parameter, functions can accept\nreferences with any lifetime by specifying a generic lifetime parameter.\nLifetime annotations have a slightly unusual syntax: The names of lifetime\nparameters must start with an apostrophe (`'`) and are usually all lowercase\nand very short, like generic types. Most people use the name `'a` for the first\nlifetime annotation. We place lifetime parameter annotations after the `&` of a\nreference, using a space to separate the annotation from the reference’s type.\nHere are some examples—a reference to an `i32` without a lifetime parameter, a\nreference to an `i32` that has a lifetime parameter named `'a`, and a mutable\nreference to an `i32` that also has the lifetime `'a`:\n```rust,ignore\n&i32 // a reference\n&'a i32 // a reference with an explicit lifetime\n&'a mut i32 // a mutable reference with an explicit lifetime\n```\nOne lifetime annotation by itself doesn’t have much meaning, because the\nannotations are meant to tell Rust how generic lifetime parameters of multiple\nreferences relate to each other. Let’s examine how the lifetime annotations\nrelate to each other in the context of the `longest` function.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Validating References with Lifetimes", "heading_path": ["Validating References with Lifetimes", "Lifetime Annotation Syntax"], "path": "ch10-03-lifetime-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#lifetime-annotation-syntax", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch10-03-lifetime-syntax.md#in-function-signatures-9", "text": "The Rust Programming Language › Validating References with Lifetimes › In Function Signatures\n\nTo use lifetime annotations in function signatures, we need to declare the\ngeneric lifetime parameters inside angle brackets between the function name and\nthe parameter list, just as we did with generic type parameters.\nWe want the signature to express the following constraint: The returned\nreference will be valid as long as both of the parameters are valid. This is\nthe relationship between lifetimes of the parameters and the return value.\nWe’ll name the lifetime `'a` and then add it to each reference, as shown in\nListing 10-21.\nListing 10-21: The `longest` function definition specifying that all the references in the signature must have the same lifetime `'a` (src/main.rs)\n```rust\nfn longest<'a>(x: &'a str, y: &'a str) -> &'a str {\n if x.len() > y.len() { x } else { y }\n}\n```\nThis code should compile and produce the result we want when we use it with the\n`main` function in Listing 10-19.\nThe function signature now tells Rust that for some lifetime `'a`, the function\ntakes two parameters, both of which are string slices that live at least as\nlong as lifetime `'a`. The function signature also tells Rust that the string\nslice returned from the function will live at least as long as lifetime `'a`.\nIn practice, it means that the lifetime of the reference returned by the\n`longest` function is the same as the smaller of the lifetimes of the values\nreferred to by the function arguments. These relationships are what we want\nRust to use when analyzing this code.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Validating References with Lifetimes", "heading_path": ["Validating References with Lifetimes", "In Function Signatures"], "path": "ch10-03-lifetime-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#in-function-signatures", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch10-03-lifetime-syntax.md#in-function-signatures-10", "text": "The Rust Programming Language › Validating References with Lifetimes › In Function Signatures\n\nRemember, when we specify the lifetime parameters in this function signature,\nwe’re not changing the lifetimes of any values passed in or returned. Rather,\nwe’re specifying that the borrow checker should reject any values that don’t\nadhere to these constraints. Note that the `longest` function doesn’t need to\nknow exactly how long `x` and `y` will live, only that some scope can be\nsubstituted for `'a` that will satisfy this signature.\nWhen annotating lifetimes in functions, the annotations go in the function\nsignature, not in the function body. The lifetime annotations become part of\nthe contract of the function, much like the types in the signature. Having\nfunction signatures contain the lifetime contract means the analysis the Rust\ncompiler does can be simpler. If there’s a problem with the way a function is\nannotated or the way it is called, the compiler errors can point to the part of\nour code and the constraints more precisely. If, instead, the Rust compiler\nmade more inferences about what we intended the relationships of the lifetimes\nto be, the compiler might only be able to point to a use of our code many steps\naway from the cause of the problem.\nWhen we pass concrete references to `longest`, the concrete lifetime that is\nsubstituted for `'a` is the part of the scope of `x` that overlaps with the\nscope of `y`. In other words, the generic lifetime `'a` will get the concrete\nlifetime that is equal to the smaller of the lifetimes of `x` and `y`. Because\nwe’ve annotated the returned reference with the same lifetime parameter `'a`,\nthe returned reference will also be valid for the length of the smaller of the\nlifetimes of `x` and `y`.\nLet’s look at how the lifetime annotations restrict the `longest` function by\npassing in references that have different concrete lifetimes. Listing 10-22 is\na straightforward example.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Validating References with Lifetimes", "heading_path": ["Validating References with Lifetimes", "In Function Signatures"], "path": "ch10-03-lifetime-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#in-function-signatures", "has_code": false, "code_tags": []}} {"id": "book/ch10-03-lifetime-syntax.md#in-function-signatures-11", "text": "The Rust Programming Language › Validating References with Lifetimes › In Function Signatures\n\nListing 10-22: Using the `longest` function with references to `String` values that have different concrete lifetimes (src/main.rs)\n```rust\nfn main() {\n let string1 = String::from(\"long string is long\");\n\n {\n let string2 = String::from(\"xyz\");\n let result = longest(string1.as_str(), string2.as_str());\n println!(\"The longest string is {result}\");\n }\n}\n```\nIn this example, `string1` is valid until the end of the outer scope, `string2`\nis valid until the end of the inner scope, and `result` references something\nthat is valid until the end of the inner scope. Run this code and you’ll see\nthat the borrow checker approves; it will compile and print `The longest string\nis long string is long`.\nNext, let’s try an example that shows that the lifetime of the reference in\n`result` must be the smaller lifetime of the two arguments. We’ll move the\ndeclaration of the `result` variable outside the inner scope but leave the\nassignment of the value to the `result` variable inside the scope with\n`string2`. Then, we’ll move the `println!` that uses `result` to outside the\ninner scope, after the inner scope has ended. The code in Listing 10-23 will\nnot compile.\nListing 10-23: Attempting to use `result` after `string2` has gone out of scope (src/main.rs)\n```rust,ignore,does_not_compile\nfn main() {\n let string1 = String::from(\"long string is long\");\n let result;\n {\n let string2 = String::from(\"xyz\");\n result = longest(string1.as_str(), string2.as_str());\n }\n println!(\"The longest string is {result}\");\n}\n```\nWhen we try to compile this code, we get this error:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Validating References with Lifetimes", "heading_path": ["Validating References with Lifetimes", "In Function Signatures"], "path": "ch10-03-lifetime-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#in-function-signatures", "has_code": true, "code_tags": ["rust", "rust,ignore,does_not_compile"]}} {"id": "book/ch10-03-lifetime-syntax.md#in-function-signatures-12", "text": "The Rust Programming Language › Validating References with Lifetimes › In Function Signatures\n\n```console\n$ cargo run\n Compiling chapter10 v0.1.0 (file:///projects/chapter10)\nerror[E0597]: `string2` does not live long enough\n --> src/main.rs:6:44\n |\n5 | let string2 = String::from(\"xyz\");\n | ------- binding `string2` declared here\n6 | result = longest(string1.as_str(), string2.as_str());\n | ^^^^^^^ borrowed value does not live long enough\n7 | }\n | - `string2` dropped here while still borrowed\n8 | println!(\"The longest string is {result}\");\n | ------ borrow later used here\n\nFor more information about this error, try `rustc --explain E0597`.\nerror: could not compile `chapter10` (bin \"chapter10\") due to 1 previous error\n```\nThe error shows that for `result` to be valid for the `println!` statement,\n`string2` would need to be valid until the end of the outer scope. Rust knows\nthis because we annotated the lifetimes of the function parameters and return\nvalues using the same lifetime parameter `'a`.\nAs humans, we can look at this code and see that `string1` is longer than\n`string2`, and therefore, `result` will contain a reference to `string1`.\nBecause `string1` has not gone out of scope yet, a reference to `string1` will\nstill be valid for the `println!` statement. However, the compiler can’t see\nthat the reference is valid in this case. We’ve told Rust that the lifetime of\nthe reference returned by the `longest` function is the same as the smaller of\nthe lifetimes of the references passed in. Therefore, the borrow checker\ndisallows the code in Listing 10-23 as possibly having an invalid reference.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Validating References with Lifetimes", "heading_path": ["Validating References with Lifetimes", "In Function Signatures"], "path": "ch10-03-lifetime-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#in-function-signatures", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch10-03-lifetime-syntax.md#in-function-signatures-13", "text": "The Rust Programming Language › Validating References with Lifetimes › In Function Signatures\n\nTry designing more experiments that vary the values and lifetimes of the\nreferences passed in to the `longest` function and how the returned reference\nis used. Make hypotheses about whether or not your experiments will pass the\nborrow checker before you compile; then, check to see if you’re right!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Validating References with Lifetimes", "heading_path": ["Validating References with Lifetimes", "In Function Signatures"], "path": "ch10-03-lifetime-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#in-function-signatures", "has_code": false, "code_tags": []}} {"id": "book/ch10-03-lifetime-syntax.md#relationships-14", "text": "The Rust Programming Language › Validating References with Lifetimes › Relationships\n\nThe way in which you need to specify lifetime parameters depends on what your\nfunction is doing. For example, if we changed the implementation of the\n`longest` function to always return the first parameter rather than the longest\nstring slice, we wouldn’t need to specify a lifetime on the `y` parameter. The\nfollowing code will compile:\nListing (src/main.rs)\n```rust\nfn longest<'a>(x: &'a str, y: &str) -> &'a str {\n x\n}\n```\nWe’ve specified a lifetime parameter `'a` for the parameter `x` and the return\ntype, but not for the parameter `y`, because the lifetime of `y` does not have\nany relationship with the lifetime of `x` or the return value.\nWhen returning a reference from a function, the lifetime parameter for the\nreturn type needs to match the lifetime parameter for one of the parameters. If\nthe reference returned does _not_ refer to one of the parameters, it must refer\nto a value created within this function. However, this would be a dangling\nreference because the value will go out of scope at the end of the function.\nConsider this attempted implementation of the `longest` function that won’t\ncompile:\nListing (src/main.rs)\n```rust,ignore,does_not_compile\nfn longest<'a>(x: &str, y: &str) -> &'a str {\n let result = String::from(\"really long string\");\n result.as_str()\n}\n```\nHere, even though we’ve specified a lifetime parameter `'a` for the return\ntype, this implementation will fail to compile because the return value\nlifetime is not related to the lifetime of the parameters at all. Here is the\nerror message we get:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Validating References with Lifetimes", "heading_path": ["Validating References with Lifetimes", "Relationships"], "path": "ch10-03-lifetime-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#relationships", "has_code": true, "code_tags": ["rust", "rust,ignore,does_not_compile"]}} {"id": "book/ch10-03-lifetime-syntax.md#relationships-15", "text": "The Rust Programming Language › Validating References with Lifetimes › Relationships\n\n```console\n$ cargo run\n Compiling chapter10 v0.1.0 (file:///projects/chapter10)\nerror[E0515]: cannot return value referencing local variable `result`\n --> src/main.rs:11:5\n |\n11 | result.as_str()\n | ------^^^^^^^^^\n | |\n | returns a value referencing data owned by the current function\n | `result` is borrowed here\n\nFor more information about this error, try `rustc --explain E0515`.\nerror: could not compile `chapter10` (bin \"chapter10\") due to 1 previous error\n```\nThe problem is that `result` goes out of scope and gets cleaned up at the end\nof the `longest` function. We’re also trying to return a reference to `result`\nfrom the function. There is no way we can specify lifetime parameters that\nwould change the dangling reference, and Rust won’t let us create a dangling\nreference. In this case, the best fix would be to return an owned data type\nrather than a reference so that the calling function is then responsible for\ncleaning up the value.\nUltimately, lifetime syntax is about connecting the lifetimes of various\nparameters and return values of functions. Once they’re connected, Rust has\nenough information to allow memory-safe operations and disallow operations that\nwould create dangling pointers or otherwise violate memory safety.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Validating References with Lifetimes", "heading_path": ["Validating References with Lifetimes", "Relationships"], "path": "ch10-03-lifetime-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#relationships", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch10-03-lifetime-syntax.md#in-struct-definitions-16", "text": "The Rust Programming Language › Validating References with Lifetimes › In Struct Definitions\n\nSo far, the structs we’ve defined all hold owned types. We can define structs\nto hold references, but in that case, we would need to add a lifetime\nannotation on every reference in the struct’s definition. Listing 10-24 has a\nstruct named `ImportantExcerpt` that holds a string slice.\nListing 10-24: A struct that holds a reference, requiring a lifetime annotation (src/main.rs)\n```rust\nstruct ImportantExcerpt<'a> {\n part: &'a str,\n}\n\nfn main() {\n let novel = String::from(\"Call me Ishmael. Some years ago...\");\n let first_sentence = novel.split('.').next().unwrap();\n let i = ImportantExcerpt {\n part: first_sentence,\n };\n}\n```\nThis struct has the single field `part` that holds a string slice, which is a\nreference. As with generic data types, we declare the name of the generic\nlifetime parameter inside angle brackets after the name of the struct so that\nwe can use the lifetime parameter in the body of the struct definition. This\nannotation means an instance of `ImportantExcerpt` can’t outlive the reference\nit holds in its `part` field.\nThe `main` function here creates an instance of the `ImportantExcerpt` struct\nthat holds a reference to the first sentence of the `String` owned by the\nvariable `novel`. The data in `novel` exists before the `ImportantExcerpt`\ninstance is created. In addition, `novel` doesn’t go out of scope until after\nthe `ImportantExcerpt` goes out of scope, so the reference in the\n`ImportantExcerpt` instance is valid.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Validating References with Lifetimes", "heading_path": ["Validating References with Lifetimes", "In Struct Definitions"], "path": "ch10-03-lifetime-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#in-struct-definitions", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch10-03-lifetime-syntax.md#lifetime-elision-17", "text": "The Rust Programming Language › Validating References with Lifetimes › Lifetime Elision\n\nYou’ve learned that every reference has a lifetime and that you need to specify\nlifetime parameters for functions or structs that use references. However, we\nhad a function in Listing 4-9, shown again in Listing 10-25, that compiled\nwithout lifetime annotations.\nListing 10-25: A function we defined in Listing 4-9 that compiled without lifetime annotations, even though the parameter and return type are references (src/lib.rs)\n```rust\nfn first_word(s: &str) -> &str {\n let bytes = s.as_bytes();\n\n for (i, &item) in bytes.iter().enumerate() {\n if item == b' ' {\n return &s[0..i];\n }\n }\n\n &s[..]\n}\n```\nThe reason this function compiles without lifetime annotations is historical:\nIn early versions (pre-1.0) of Rust, this code wouldn’t have compiled, because\nevery reference needed an explicit lifetime. At that time, the function\nsignature would have been written like this:\n```rust,ignore\nfn first_word<'a>(s: &'a str) -> &'a str {\n```\nAfter writing a lot of Rust code, the Rust team found that Rust programmers\nwere entering the same lifetime annotations over and over in particular\nsituations. These situations were predictable and followed a few deterministic\npatterns. The developers programmed these patterns into the compiler’s code so\nthat the borrow checker could infer the lifetimes in these situations and\nwouldn’t need explicit annotations.\nThis piece of Rust history is relevant because it’s possible that more\ndeterministic patterns will emerge and be added to the compiler. In the future,\neven fewer lifetime annotations might be required.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Validating References with Lifetimes", "heading_path": ["Validating References with Lifetimes", "Lifetime Elision"], "path": "ch10-03-lifetime-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#lifetime-elision", "has_code": true, "code_tags": ["rust", "rust,ignore"]}} {"id": "book/ch10-03-lifetime-syntax.md#lifetime-elision-18", "text": "The Rust Programming Language › Validating References with Lifetimes › Lifetime Elision\n\nThe patterns programmed into Rust’s analysis of references are called the\n_lifetime elision rules_. These aren’t rules for programmers to follow; they’re\na set of particular cases that the compiler will consider, and if your code\nfits these cases, you don’t need to write the lifetimes explicitly.\nThe elision rules don’t provide full inference. If there is still ambiguity\nabout what lifetimes the references have after Rust applies the rules, the\ncompiler won’t guess what the lifetime of the remaining references should be.\nInstead of guessing, the compiler will give you an error that you can resolve\nby adding the lifetime annotations.\nLifetimes on function or method parameters are called _input lifetimes_, and\nlifetimes on return values are called _output lifetimes_.\nThe compiler uses three rules to figure out the lifetimes of the references\nwhen there aren’t explicit annotations. The first rule applies to input\nlifetimes, and the second and third rules apply to output lifetimes. If the\ncompiler gets to the end of the three rules and there are still references for\nwhich it can’t figure out lifetimes, the compiler will stop with an error.\nThese rules apply to `fn` definitions as well as `impl` blocks.\nThe first rule is that the compiler assigns a lifetime parameter to each\nparameter that’s a reference. In other words, a function with one parameter\ngets one lifetime parameter: `fn foo<'a>(x: &'a i32)`; a function with two\nparameters gets two separate lifetime parameters: `fn foo<'a, 'b>(x: &'a i32,\ny: &'b i32)`; and so on.\nThe second rule is that, if there is exactly one input lifetime parameter, that\nlifetime is assigned to all output lifetime parameters: `fn foo<'a>(x: &'a i32)\n-> &'a i32`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Validating References with Lifetimes", "heading_path": ["Validating References with Lifetimes", "Lifetime Elision"], "path": "ch10-03-lifetime-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#lifetime-elision", "has_code": false, "code_tags": []}} {"id": "book/ch10-03-lifetime-syntax.md#lifetime-elision-19", "text": "The Rust Programming Language › Validating References with Lifetimes › Lifetime Elision\n\nThe third rule is that, if there are multiple input lifetime parameters, but\none of them is `&self` or `&mut self` because this is a method, the lifetime of\n`self` is assigned to all output lifetime parameters. This third rule makes\nmethods much nicer to read and write because fewer symbols are necessary.\nLet’s pretend we’re the compiler. We’ll apply these rules to figure out the\nlifetimes of the references in the signature of the `first_word` function in\nListing 10-25. The signature starts without any lifetimes associated with the\nreferences:\n```rust,ignore\nfn first_word(s: &str) -> &str {\n```\nThen, the compiler applies the first rule, which specifies that each parameter\ngets its own lifetime. We’ll call it `'a` as usual, so now the signature is\nthis:\n```rust,ignore\nfn first_word<'a>(s: &'a str) -> &str {\n```\nThe second rule applies because there is exactly one input lifetime. The second\nrule specifies that the lifetime of the one input parameter gets assigned to\nthe output lifetime, so the signature is now this:\n```rust,ignore\nfn first_word<'a>(s: &'a str) -> &'a str {\n```\nNow all the references in this function signature have lifetimes, and the\ncompiler can continue its analysis without needing the programmer to annotate\nthe lifetimes in this function signature.\nLet’s look at another example, this time using the `longest` function that had\nno lifetime parameters when we started working with it in Listing 10-20:\n```rust,ignore\nfn longest(x: &str, y: &str) -> &str {\n```\nLet’s apply the first rule: Each parameter gets its own lifetime. This time we\nhave two parameters instead of one, so we have two lifetimes:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Validating References with Lifetimes", "heading_path": ["Validating References with Lifetimes", "Lifetime Elision"], "path": "ch10-03-lifetime-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#lifetime-elision", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch10-03-lifetime-syntax.md#lifetime-elision-20", "text": "The Rust Programming Language › Validating References with Lifetimes › Lifetime Elision\n\n```rust,ignore\nfn longest<'a, 'b>(x: &'a str, y: &'b str) -> &str {\n```\nYou can see that the second rule doesn’t apply, because there is more than one\ninput lifetime. The third rule doesn’t apply either, because `longest` is a\nfunction rather than a method, so none of the parameters are `self`. After\nworking through all three rules, we still haven’t figured out what the return\ntype’s lifetime is. This is why we got an error trying to compile the code in\nListing 10-20: The compiler worked through the lifetime elision rules but still\ncouldn’t figure out all the lifetimes of the references in the signature.\nBecause the third rule really only applies in method signatures, we’ll look at\nlifetimes in that context next to see why the third rule means we don’t have to\nannotate lifetimes in method signatures very often.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Validating References with Lifetimes", "heading_path": ["Validating References with Lifetimes", "Lifetime Elision"], "path": "ch10-03-lifetime-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#lifetime-elision", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch10-03-lifetime-syntax.md#in-method-definitions-21", "text": "The Rust Programming Language › Validating References with Lifetimes › In Method Definitions\n\nWhen we implement methods on a struct with lifetimes, we use the same syntax as\nthat of generic type parameters, as shown in Listing 10-11. Where we declare\nand use the lifetime parameters depends on whether they’re related to the\nstruct fields or the method parameters and return values.\nLifetime names for struct fields always need to be declared after the `impl`\nkeyword and then used after the struct’s name because those lifetimes are part\nof the struct’s type.\nIn method signatures inside the `impl` block, references might be tied to the\nlifetime of references in the struct’s fields, or they might be independent. In\naddition, the lifetime elision rules often make it so that lifetime annotations\naren’t necessary in method signatures. Let’s look at some examples using the\nstruct named `ImportantExcerpt` that we defined in Listing 10-24.\nFirst, we’ll use a method named `level` whose only parameter is a reference to\n`self` and whose return value is an `i32`, which is not a reference to anything:\n```rust\nimpl<'a> ImportantExcerpt<'a> {\n fn level(&self) -> i32 {\n 3\n }\n}\n```\nThe lifetime parameter declaration after `impl` and its use after the type name\nare required, but because of the first elision rule, we’re not required to\nannotate the lifetime of the reference to `self`.\nHere is an example where the third lifetime elision rule applies:\n```rust\nimpl<'a> ImportantExcerpt<'a> {\n fn announce_and_return_part(&self, announcement: &str) -> &str {\n println!(\"Attention please: {announcement}\");\n self.part\n }\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Validating References with Lifetimes", "heading_path": ["Validating References with Lifetimes", "In Method Definitions"], "path": "ch10-03-lifetime-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#in-method-definitions", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch10-03-lifetime-syntax.md#in-method-definitions-22", "text": "The Rust Programming Language › Validating References with Lifetimes › In Method Definitions\n\nThere are two input lifetimes, so Rust applies the first lifetime elision rule\nand gives both `&self` and `announcement` their own lifetimes. Then, because\none of the parameters is `&self`, the return type gets the lifetime of `&self`,\nand all lifetimes have been accounted for.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Validating References with Lifetimes", "heading_path": ["Validating References with Lifetimes", "In Method Definitions"], "path": "ch10-03-lifetime-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#in-method-definitions", "has_code": false, "code_tags": []}} {"id": "book/ch10-03-lifetime-syntax.md#the-static-lifetime-23", "text": "The Rust Programming Language › Validating References with Lifetimes › The Static Lifetime\n\nOne special lifetime we need to discuss is `'static`, which denotes that the\naffected reference _can_ live for the entire duration of the program. All\nstring literals have the `'static` lifetime, which we can annotate as follows:\n```rust\nlet s: &'static str = \"I have a static lifetime.\";\n```\nThe text of this string is stored directly in the program’s binary, which is\nalways available. Therefore, the lifetime of all string literals is `'static`.\nYou might see suggestions in error messages to use the `'static` lifetime. But\nbefore specifying `'static` as the lifetime for a reference, think about\nwhether or not the reference you have actually lives the entire lifetime of\nyour program, and whether you want it to. Most of the time, an error message\nsuggesting the `'static` lifetime results from attempting to create a dangling\nreference or a mismatch of the available lifetimes. In such cases, the solution\nis to fix those problems, not to specify the `'static` lifetime.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Validating References with Lifetimes", "heading_path": ["Validating References with Lifetimes", "The Static Lifetime"], "path": "ch10-03-lifetime-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#the-static-lifetime", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch10-03-lifetime-syntax.md#generic-type-parameters-trait-bounds-and-lifetimes-24", "text": "The Rust Programming Language › Generic Type Parameters, Trait Bounds, and Lifetimes\n\nLet’s briefly look at the syntax of specifying generic type parameters, trait\nbounds, and lifetimes all in one function!\n```rust\nuse std::fmt::Display;\n\nfn longest_with_an_announcement<'a, T>(\n x: &'a str,\n y: &'a str,\n ann: T,\n) -> &'a str\nwhere\n T: Display,\n{\n println!(\"Announcement! {ann}\");\n if x.len() > y.len() { x } else { y }\n}\n```\nThis is the `longest` function from Listing 10-21 that returns the longer of\ntwo string slices. But now it has an extra parameter named `ann` of the generic\ntype `T`, which can be filled in by any type that implements the `Display`\ntrait as specified by the `where` clause. This extra parameter will be printed\nusing `{}`, which is why the `Display` trait bound is necessary. Because\nlifetimes are a type of generic, the declarations of the lifetime parameter\n`'a` and the generic type parameter `T` go in the same list inside the angle\nbrackets after the function name.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Validating References with Lifetimes", "heading_path": ["Generic Type Parameters, Trait Bounds, and Lifetimes"], "path": "ch10-03-lifetime-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#generic-type-parameters-trait-bounds-and-lifetimes", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch10-03-lifetime-syntax.md#summary-25", "text": "The Rust Programming Language › Summary\n\nWe covered a lot in this chapter! Now that you know about generic type\nparameters, traits and trait bounds, and generic lifetime parameters, you’re\nready to write code without repetition that works in many different situations.\nGeneric type parameters let you apply the code to different types. Traits and\ntrait bounds ensure that even though the types are generic, they’ll have the\nbehavior the code needs. You learned how to use lifetime annotations to ensure\nthat this flexible code won’t have any dangling references. And all of this\nanalysis happens at compile time, which doesn’t affect runtime performance!\nBelieve it or not, there is much more to learn on the topics we discussed in\nthis chapter: Chapter 18 discusses trait objects, which are another way to use\ntraits. There are also more complex scenarios involving lifetime annotations\nthat you will only need in very advanced scenarios; for those, you should read\nthe Rust Reference. But next, you’ll learn how to write tests in\nRust so that you can make sure your code is working the way it should.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Validating References with Lifetimes", "heading_path": ["Summary"], "path": "ch10-03-lifetime-syntax.md", "url": "https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#summary", "has_code": false, "code_tags": []}} {"id": "book/ch11-00-testing.md#writing-automated-tests-0", "text": "The Rust Programming Language › Writing Automated Tests\n\nIn his 1972 essay “The Humble Programmer,” Edsger W. Dijkstra said that “program\ntesting can be a very effective way to show the presence of bugs, but it is\nhopelessly inadequate for showing their absence.” That doesn’t mean we shouldn’t\ntry to test as much as we can!\n_Correctness_ in our programs is the extent to which our code does what we\nintend it to do. Rust is designed with a high degree of concern about the\ncorrectness of programs, but correctness is complex and not easy to prove.\nRust’s type system shoulders a huge part of this burden, but the type system\ncannot catch everything. As such, Rust includes support for writing automated\nsoftware tests.\nSay we write a function `add_two` that adds 2 to whatever number is passed to\nit. This function’s signature accepts an integer as a parameter and returns an\ninteger as a result. When we implement and compile that function, Rust does all\nthe type checking and borrow checking that you’ve learned so far to ensure\nthat, for instance, we aren’t passing a `String` value or an invalid reference\nto this function. But Rust _can’t_ check that this function will do precisely\nwhat we intend, which is return the parameter plus 2 rather than, say, the\nparameter plus 10 or the parameter minus 50! That’s where tests come in.\nWe can write tests that assert, for example, that when we pass `3` to the\n`add_two` function, the returned value is `5`. We can run these tests whenever\nwe make changes to our code to make sure any existing correct behavior has not\nchanged.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Writing Automated Tests", "heading_path": ["Writing Automated Tests"], "path": "ch11-00-testing.md", "url": "https://doc.rust-lang.org/book/ch11-00-testing.html#writing-automated-tests", "has_code": false, "code_tags": []}} {"id": "book/ch11-00-testing.md#writing-automated-tests-1", "text": "The Rust Programming Language › Writing Automated Tests\n\nTesting is a complex skill: Although we can’t cover in one chapter every detail\nabout how to write good tests, in this chapter we will discuss the mechanics of\nRust’s testing facilities. We’ll talk about the annotations and macros\navailable to you when writing your tests, the default behavior and options\nprovided for running your tests, and how to organize tests into unit tests and\nintegration tests.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Writing Automated Tests", "heading_path": ["Writing Automated Tests"], "path": "ch11-00-testing.md", "url": "https://doc.rust-lang.org/book/ch11-00-testing.html#writing-automated-tests", "has_code": false, "code_tags": []}} {"id": "book/ch11-01-writing-tests.md#how-to-write-tests-0", "text": "The Rust Programming Language › How to Write Tests\n\n_Tests_ are Rust functions that verify that the non-test code is functioning in\nthe expected manner. The bodies of test functions typically perform these three\nactions:\n- Set up any needed data or state.\n- Run the code you want to test.\n- Assert that the results are what you expect.\nLet’s look at the features Rust provides specifically for writing tests that\ntake these actions, which include the `test` attribute, a few macros, and the\n`should_panic` attribute.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "How to Write Tests", "heading_path": ["How to Write Tests"], "path": "ch11-01-writing-tests.md", "url": "https://doc.rust-lang.org/book/ch11-01-writing-tests.html#how-to-write-tests", "has_code": false, "code_tags": []}} {"id": "book/ch11-01-writing-tests.md#structuring-test-functions-1", "text": "The Rust Programming Language › How to Write Tests › Structuring Test Functions\n\nAt its simplest, a test in Rust is a function that’s annotated with the `test`\nattribute. Attributes are metadata about pieces of Rust code; one example is\nthe `derive` attribute we used with structs in Chapter 5. To change a function\ninto a test function, add `#[test]` on the line before `fn`. When you run your\ntests with the `cargo test` command, Rust builds a test runner binary that runs\nthe annotated functions and reports on whether each test function passes or\nfails.\nWhenever we make a new library project with Cargo, a test module with a test\nfunction in it is automatically generated for us. This module gives you a\ntemplate for writing your tests so that you don’t have to look up the exact\nstructure and syntax every time you start a new project. You can add as many\nadditional test functions and as many test modules as you want!\nWe’ll explore some aspects of how tests work by experimenting with the template\ntest before we actually test any code. Then, we’ll write some real-world tests\nthat call some code that we’ve written and assert that its behavior is correct.\nLet’s create a new library project called `adder` that will add two numbers:\n```console\n$ cargo new adder --lib\n Created library `adder` project\n$ cd adder\n```\nThe contents of the _src/lib.rs_ file in your `adder` library should look like\nListing 11-1.\nListing 11-1: The code generated automatically by `cargo new` (src/lib.rs)\n```rust,noplayground\npub fn add(left: u64, right: u64) -> u64 {\n left + right\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn it_works() {\n let result = add(2, 2);\n assert_eq!(result, 4);\n }\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "How to Write Tests", "heading_path": ["How to Write Tests", "Structuring Test Functions"], "path": "ch11-01-writing-tests.md", "url": "https://doc.rust-lang.org/book/ch11-01-writing-tests.html#structuring-test-functions", "has_code": true, "code_tags": ["console", "rust,noplayground"]}} {"id": "book/ch11-01-writing-tests.md#structuring-test-functions-2", "text": "The Rust Programming Language › How to Write Tests › Structuring Test Functions\n\nThe file starts with an example `add` function so that we have something to\ntest.\nFor now, let’s focus solely on the `it_works` function. Note the `#[test]`\nannotation: This attribute indicates this is a test function, so the test\nrunner knows to treat this function as a test. We might also have non-test\nfunctions in the `tests` module to help set up common scenarios or perform\ncommon operations, so we always need to indicate which functions are tests.\nThe example function body uses the `assert_eq!` macro to assert that `result`,\nwhich contains the result of calling `add` with 2 and 2, equals 4. This\nassertion serves as an example of the format for a typical test. Let’s run it\nto see that this test passes.\nThe `cargo test` command runs all tests in our project, as shown in Listing\n11-2.\nListing 11-2: The output from running the automatically generated test\n```console\n$ cargo test\n Compiling adder v0.1.0 (file:///projects/adder)\n Finished `test` profile [unoptimized + debuginfo] target(s) in 0.57s\n Running unittests src/lib.rs (target/debug/deps/adder-01ad14159ff659ab)\n\nrunning 1 test\ntest tests::it_works ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n Doc-tests adder\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "How to Write Tests", "heading_path": ["How to Write Tests", "Structuring Test Functions"], "path": "ch11-01-writing-tests.md", "url": "https://doc.rust-lang.org/book/ch11-01-writing-tests.html#structuring-test-functions", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch11-01-writing-tests.md#structuring-test-functions-3", "text": "The Rust Programming Language › How to Write Tests › Structuring Test Functions\n\nCargo compiled and ran the test. We see the line `running 1 test`. The next\nline shows the name of the generated test function, called `tests::it_works`,\nand that the result of running that test is `ok`. The overall summary `test\nresult: ok.` means that all the tests passed, and the portion that reads `1\npassed; 0 failed` totals the number of tests that passed or failed.\nIt’s possible to mark a test as ignored so that it doesn’t run in a particular\ninstance; we’ll cover that in the “Ignoring Tests Unless Specifically\nRequested” section later in this chapter. Because we\nhaven’t done that here, the summary shows `0 ignored`. We can also pass an\nargument to the `cargo test` command to run only tests whose name matches a\nstring; this is called _filtering_, and we’ll cover it in the “Running a\nSubset of Tests by Name” section. Here, we haven’t\nfiltered the tests being run, so the end of the summary shows `0 filtered out`.\nThe `0 measured` statistic is for benchmark tests that measure performance.\nBenchmark tests are, as of this writing, only available in nightly Rust. See\nthe documentation about benchmark tests to learn more.\nThe next part of the test output starting at `Doc-tests adder` is for the\nresults of any documentation tests. We don’t have any documentation tests yet,\nbut Rust can compile any code examples that appear in our API documentation.\nThis feature helps keep your docs and your code in sync! We’ll discuss how to\nwrite documentation tests in the “Documentation Comments as\nTests” section of Chapter 14. For now, we’ll\nignore the `Doc-tests` output.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "How to Write Tests", "heading_path": ["How to Write Tests", "Structuring Test Functions"], "path": "ch11-01-writing-tests.md", "url": "https://doc.rust-lang.org/book/ch11-01-writing-tests.html#structuring-test-functions", "has_code": false, "code_tags": []}} {"id": "book/ch11-01-writing-tests.md#structuring-test-functions-4", "text": "The Rust Programming Language › How to Write Tests › Structuring Test Functions\n\nLet’s start to customize the test to our own needs. First, change the name of\nthe `it_works` function to a different name, such as `exploration`, like so:\nFilename: src/lib.rs\n```rust,noplayground\npub fn add(left: u64, right: u64) -> u64 {\n left + right\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn exploration() {\n let result = add(2, 2);\n assert_eq!(result, 4);\n }\n}\n```\nThen, run `cargo test` again. The output now shows `exploration` instead of\n`it_works`:\n```console\n$ cargo test\n Compiling adder v0.1.0 (file:///projects/adder)\n Finished `test` profile [unoptimized + debuginfo] target(s) in 0.59s\n Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)\n\nrunning 1 test\ntest tests::exploration ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n Doc-tests adder\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "How to Write Tests", "heading_path": ["How to Write Tests", "Structuring Test Functions"], "path": "ch11-01-writing-tests.md", "url": "https://doc.rust-lang.org/book/ch11-01-writing-tests.html#structuring-test-functions", "has_code": true, "code_tags": ["console", "rust,noplayground"]}} {"id": "book/ch11-01-writing-tests.md#structuring-test-functions-5", "text": "The Rust Programming Language › How to Write Tests › Structuring Test Functions\n\nNow we’ll add another test, but this time we’ll make a test that fails! Tests\nfail when something in the test function panics. Each test is run in a new\nthread, and when the main thread sees that a test thread has died, the test is\nmarked as failed. In Chapter 9, we talked about how the simplest way to panic\nis to call the `panic!` macro. Enter the new test as a function named\n`another`, so your _src/lib.rs_ file looks like Listing 11-3.\nListing 11-3: Adding a second test that will fail because we call the `panic!` macro (src/lib.rs)\n```rust,panics,noplayground\npub fn add(left: u64, right: u64) -> u64 {\n left + right\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn exploration() {\n let result = add(2, 2);\n assert_eq!(result, 4);\n }\n\n #[test]\n fn another() {\n panic!(\"Make this test fail\");\n }\n}\n```\nRun the tests again using `cargo test`. The output should look like Listing\n11-4, which shows that our `exploration` test passed and `another` failed.\nListing 11-4: Test results when one test passes and one test fails", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "How to Write Tests", "heading_path": ["How to Write Tests", "Structuring Test Functions"], "path": "ch11-01-writing-tests.md", "url": "https://doc.rust-lang.org/book/ch11-01-writing-tests.html#structuring-test-functions", "has_code": true, "code_tags": ["rust,panics,noplayground"]}} {"id": "book/ch11-01-writing-tests.md#structuring-test-functions-6", "text": "The Rust Programming Language › How to Write Tests › Structuring Test Functions\n\n```console\n$ cargo test\n Compiling adder v0.1.0 (file:///projects/adder)\n Finished `test` profile [unoptimized + debuginfo] target(s) in 0.72s\n Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)\n\nrunning 2 tests\ntest tests::another ... FAILED\ntest tests::exploration ... ok\n\nfailures:\n\n---- tests::another stdout ----\n\nthread 'tests::another' (6019162) panicked at src/lib.rs:17:9:\nMake this test fail\nnote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n\n\nfailures:\n tests::another\n\ntest result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\nerror: test failed, to rerun pass `--lib`\n```\nInstead of `ok`, the line `test tests::another` shows `FAILED`. Two new\nsections appear between the individual results and the summary: The first\ndisplays the detailed reason for each test failure. In this case, we get the\ndetails that `tests::another` failed because it panicked with the message `Make\nthis test fail` on line 17 in the _src/lib.rs_ file. The next section lists\njust the names of all the failing tests, which is useful when there are lots of\ntests and lots of detailed failing test output. We can use the name of a\nfailing test to run just that test to debug it more easily; we’ll talk more\nabout ways to run tests in the “Controlling How Tests Are\nRun” section.\nThe summary line displays at the end: Overall, our test result is `FAILED`. We\nhad one test pass and one test fail.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "How to Write Tests", "heading_path": ["How to Write Tests", "Structuring Test Functions"], "path": "ch11-01-writing-tests.md", "url": "https://doc.rust-lang.org/book/ch11-01-writing-tests.html#structuring-test-functions", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch11-01-writing-tests.md#structuring-test-functions-7", "text": "The Rust Programming Language › How to Write Tests › Structuring Test Functions\n\nNow that you’ve seen what the test results look like in different scenarios,\nlet’s look at some macros other than `panic!` that are useful in tests.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "How to Write Tests", "heading_path": ["How to Write Tests", "Structuring Test Functions"], "path": "ch11-01-writing-tests.md", "url": "https://doc.rust-lang.org/book/ch11-01-writing-tests.html#structuring-test-functions", "has_code": false, "code_tags": []}} {"id": "book/ch11-01-writing-tests.md#checking-results-with-assert-8", "text": "The Rust Programming Language › How to Write Tests › Checking Results with `assert!`\n\nThe `assert!` macro, provided by the standard library, is useful when you want\nto ensure that some condition in a test evaluates to `true`. We give the\n`assert!` macro an argument that evaluates to a Boolean. If the value is\n`true`, nothing happens and the test passes. If the value is `false`, the\n`assert!` macro calls `panic!` to cause the test to fail. Using the `assert!`\nmacro helps us check that our code is functioning in the way we intend.\nIn Chapter 5, Listing 5-15, we used a `Rectangle` struct and a `can_hold`\nmethod, which are repeated here in Listing 11-5. Let’s put this code in the\n_src/lib.rs_ file, then write some tests for it using the `assert!` macro.\nListing 11-5: The `Rectangle` struct and its `can_hold` method from Chapter 5 (src/lib.rs)\n```rust,noplayground\n#[derive(Debug)]\nstruct Rectangle {\n width: u32,\n height: u32,\n}\n\nimpl Rectangle {\n fn can_hold(&self, other: &Rectangle) -> bool {\n self.width > other.width && self.height > other.height\n }\n}\n```\nThe `can_hold` method returns a Boolean, which means it’s a perfect use case\nfor the `assert!` macro. In Listing 11-6, we write a test that exercises the\n`can_hold` method by creating a `Rectangle` instance that has a width of 8 and\na height of 7 and asserting that it can hold another `Rectangle` instance that\nhas a width of 5 and a height of 1.\nListing 11-6: A test for `can_hold` that checks whether a larger rectangle can indeed hold a smaller rectangle (src/lib.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "How to Write Tests", "heading_path": ["How to Write Tests", "Checking Results with `assert!`"], "path": "ch11-01-writing-tests.md", "url": "https://doc.rust-lang.org/book/ch11-01-writing-tests.html#checking-results-with-assert", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch11-01-writing-tests.md#checking-results-with-assert-9", "text": "The Rust Programming Language › How to Write Tests › Checking Results with `assert!`\n\n```rust,noplayground\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn larger_can_hold_smaller() {\n let larger = Rectangle {\n width: 8,\n height: 7,\n };\n let smaller = Rectangle {\n width: 5,\n height: 1,\n };\n\n assert!(larger.can_hold(&smaller));\n }\n}\n```\nNote the `use super::*;` line inside the `tests` module. The `tests` module is\na regular module that follows the usual visibility rules we covered in Chapter\n7 in the “Paths for Referring to an Item in the Module\nTree”\nsection. Because the `tests` module is an inner module, we need to bring the\ncode under test in the outer module into the scope of the inner module. We use\na glob here, so anything we define in the outer module is available to this\n`tests` module.\nWe’ve named our test `larger_can_hold_smaller`, and we’ve created the two\n`Rectangle` instances that we need. Then, we called the `assert!` macro and\npassed it the result of calling `larger.can_hold(&smaller)`. This expression is\nsupposed to return `true`, so our test should pass. Let’s find out!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "How to Write Tests", "heading_path": ["How to Write Tests", "Checking Results with `assert!`"], "path": "ch11-01-writing-tests.md", "url": "https://doc.rust-lang.org/book/ch11-01-writing-tests.html#checking-results-with-assert", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch11-01-writing-tests.md#checking-results-with-assert-10", "text": "The Rust Programming Language › How to Write Tests › Checking Results with `assert!`\n\n```console\n$ cargo test\n Compiling rectangle v0.1.0 (file:///projects/rectangle)\n Finished `test` profile [unoptimized + debuginfo] target(s) in 0.66s\n Running unittests src/lib.rs (target/debug/deps/rectangle-6584c4561e48942e)\n\nrunning 1 test\ntest tests::larger_can_hold_smaller ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n Doc-tests rectangle\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n```\nIt does pass! Let’s add another test, this time asserting that a smaller\nrectangle cannot hold a larger rectangle:\nFilename: src/lib.rs\n```rust,noplayground\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn larger_can_hold_smaller() {\n // --snip--\n }\n\n #[test]\n fn smaller_cannot_hold_larger() {\n let larger = Rectangle {\n width: 8,\n height: 7,\n };\n let smaller = Rectangle {\n width: 5,\n height: 1,\n };\n\n assert!(!smaller.can_hold(&larger));\n }\n}\n```\nBecause the correct result of the `can_hold` function in this case is `false`,\nwe need to negate that result before we pass it to the `assert!` macro. As a\nresult, our test will pass if `can_hold` returns `false`:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "How to Write Tests", "heading_path": ["How to Write Tests", "Checking Results with `assert!`"], "path": "ch11-01-writing-tests.md", "url": "https://doc.rust-lang.org/book/ch11-01-writing-tests.html#checking-results-with-assert", "has_code": true, "code_tags": ["console", "rust,noplayground"]}} {"id": "book/ch11-01-writing-tests.md#checking-results-with-assert-11", "text": "The Rust Programming Language › How to Write Tests › Checking Results with `assert!`\n\n```console\n$ cargo test\n Compiling rectangle v0.1.0 (file:///projects/rectangle)\n Finished `test` profile [unoptimized + debuginfo] target(s) in 0.66s\n Running unittests src/lib.rs (target/debug/deps/rectangle-6584c4561e48942e)\n\nrunning 2 tests\ntest tests::larger_can_hold_smaller ... ok\ntest tests::smaller_cannot_hold_larger ... ok\n\ntest result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n Doc-tests rectangle\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n```\nTwo tests that pass! Now let’s see what happens to our test results when we\nintroduce a bug in our code. We’ll change the implementation of the `can_hold`\nmethod by replacing the greater-than sign (`>`) with a less-than sign (`<`)\nwhen it compares the widths:\n```rust,not_desired_behavior,noplayground\n// --snip--\nimpl Rectangle {\n fn can_hold(&self, other: &Rectangle) -> bool {\n self.width < other.width && self.height > other.height\n }\n}\n```\nRunning the tests now produces the following:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "How to Write Tests", "heading_path": ["How to Write Tests", "Checking Results with `assert!`"], "path": "ch11-01-writing-tests.md", "url": "https://doc.rust-lang.org/book/ch11-01-writing-tests.html#checking-results-with-assert", "has_code": true, "code_tags": ["console", "rust,not_desired_behavior,noplayground"]}} {"id": "book/ch11-01-writing-tests.md#checking-results-with-assert-12", "text": "The Rust Programming Language › How to Write Tests › Checking Results with `assert!`\n\n```console\n$ cargo test\n Compiling rectangle v0.1.0 (file:///projects/rectangle)\n Finished `test` profile [unoptimized + debuginfo] target(s) in 0.66s\n Running unittests src/lib.rs (target/debug/deps/rectangle-6584c4561e48942e)\n\nrunning 2 tests\ntest tests::larger_can_hold_smaller ... FAILED\ntest tests::smaller_cannot_hold_larger ... ok\n\nfailures:\n\n---- tests::larger_can_hold_smaller stdout ----\n\nthread 'tests::larger_can_hold_smaller' (6020788) panicked at src/lib.rs:28:9:\nassertion failed: larger.can_hold(&smaller)\nnote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n\n\nfailures:\n tests::larger_can_hold_smaller\n\ntest result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\nerror: test failed, to rerun pass `--lib`\n```\nOur tests caught the bug! Because `larger.width` is `8` and `smaller.width` is\n`5`, the comparison of the widths in `can_hold` now returns `false`: 8 is not\nless than 5.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "How to Write Tests", "heading_path": ["How to Write Tests", "Checking Results with `assert!`"], "path": "ch11-01-writing-tests.md", "url": "https://doc.rust-lang.org/book/ch11-01-writing-tests.html#checking-results-with-assert", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch11-01-writing-tests.md#testing-equality-with-assert_eq-and-assert_ne-13", "text": "The Rust Programming Language › How to Write Tests › Testing Equality with `assert_eq!` and `assert_ne!`\n\nA common way to verify functionality is to test for equality between the result\nof the code under test and the value you expect the code to return. You could\ndo this by using the `assert!` macro and passing it an expression using the\n`==` operator. However, this is such a common test that the standard library\nprovides a pair of macros—`assert_eq!` and `assert_ne!`—to perform this test\nmore conveniently. These macros compare two arguments for equality or\ninequality, respectively. They’ll also print the two values if the assertion\nfails, which makes it easier to see _why_ the test failed; conversely, the\n`assert!` macro only indicates that it got a `false` value for the `==`\nexpression, without printing the values that led to the `false` value.\nIn Listing 11-7, we write a function named `add_two` that adds `2` to its\nparameter, and then we test this function using the `assert_eq!` macro.\nListing 11-7: Testing the function `add_two` using the `assert_eq!` macro (src/lib.rs)\n```rust,noplayground\npub fn add_two(a: u64) -> u64 {\n a + 2\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn it_adds_two() {\n let result = add_two(2);\n assert_eq!(result, 4);\n }\n}\n```\nLet’s check that it passes!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "How to Write Tests", "heading_path": ["How to Write Tests", "Testing Equality with `assert_eq!` and `assert_ne!`"], "path": "ch11-01-writing-tests.md", "url": "https://doc.rust-lang.org/book/ch11-01-writing-tests.html#testing-equality-with-assert_eq-and-assert_ne", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch11-01-writing-tests.md#testing-equality-with-assert_eq-and-assert_ne-14", "text": "The Rust Programming Language › How to Write Tests › Testing Equality with `assert_eq!` and `assert_ne!`\n\n```console\n$ cargo test\n Compiling adder v0.1.0 (file:///projects/adder)\n Finished `test` profile [unoptimized + debuginfo] target(s) in 0.58s\n Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)\n\nrunning 1 test\ntest tests::it_adds_two ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n Doc-tests adder\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n```\nWe create a variable named `result` that holds the result of calling\n`add_two(2)`. Then, we pass `result` and `4` as the arguments to the\n`assert_eq!` macro. The output line for this test is `test tests::it_adds_two\n... ok`, and the `ok` text indicates that our test passed!\nLet’s introduce a bug into our code to see what `assert_eq!` looks like when it\nfails. Change the implementation of the `add_two` function to instead add `3`:\n```rust,not_desired_behavior,noplayground\npub fn add_two(a: u64) -> u64 {\n a + 3\n}\n```\nRun the tests again:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "How to Write Tests", "heading_path": ["How to Write Tests", "Testing Equality with `assert_eq!` and `assert_ne!`"], "path": "ch11-01-writing-tests.md", "url": "https://doc.rust-lang.org/book/ch11-01-writing-tests.html#testing-equality-with-assert_eq-and-assert_ne", "has_code": true, "code_tags": ["console", "rust,not_desired_behavior,noplayground"]}} {"id": "book/ch11-01-writing-tests.md#testing-equality-with-assert_eq-and-assert_ne-15", "text": "The Rust Programming Language › How to Write Tests › Testing Equality with `assert_eq!` and `assert_ne!`\n\n```console\n$ cargo test\n Compiling adder v0.1.0 (file:///projects/adder)\n Finished `test` profile [unoptimized + debuginfo] target(s) in 0.61s\n Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)\n\nrunning 1 test\ntest tests::it_adds_two ... FAILED\n\nfailures:\n\n---- tests::it_adds_two stdout ----\n\nthread 'tests::it_adds_two' (6020955) panicked at src/lib.rs:12:9:\nassertion `left == right` failed\n left: 5\n right: 4\nnote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n\n\nfailures:\n tests::it_adds_two\n\ntest result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\nerror: test failed, to rerun pass `--lib`\n```\nOur test caught the bug! The `tests::it_adds_two` test failed, and the message\ntells us that the assertion that failed was `left == right` and what the `left`\nand `right` values are. This message helps us start debugging: The `left`\nargument, where we had the result of calling `add_two(2)`, was `5`, but the\n`right` argument was `4`. You can imagine that this would be especially helpful\nwhen we have a lot of tests going on.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "How to Write Tests", "heading_path": ["How to Write Tests", "Testing Equality with `assert_eq!` and `assert_ne!`"], "path": "ch11-01-writing-tests.md", "url": "https://doc.rust-lang.org/book/ch11-01-writing-tests.html#testing-equality-with-assert_eq-and-assert_ne", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch11-01-writing-tests.md#testing-equality-with-assert_eq-and-assert_ne-16", "text": "The Rust Programming Language › How to Write Tests › Testing Equality with `assert_eq!` and `assert_ne!`\n\nNote that in some languages and test frameworks, the parameters to equality\nassertion functions are called `expected` and `actual`, and the order in which\nwe specify the arguments matters. However, in Rust, they’re called `left` and\n`right`, and the order in which we specify the value we expect and the value\nthe code produces doesn’t matter. We could write the assertion in this test as\n`assert_eq!(4, result)`, which would result in the same failure message that\ndisplays `` assertion `left == right` failed ``.\nThe `assert_ne!` macro will pass if the two values we give it are not equal and\nwill fail if they are equal. This macro is most useful for cases when we’re not\nsure what a value _will_ be, but we know what the value definitely _shouldn’t_\nbe. For example, if we’re testing a function that is guaranteed to change its\ninput in some way, but the way in which the input is changed depends on the day\nof the week that we run our tests, the best thing to assert might be that the\noutput of the function is not equal to the input.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "How to Write Tests", "heading_path": ["How to Write Tests", "Testing Equality with `assert_eq!` and `assert_ne!`"], "path": "ch11-01-writing-tests.md", "url": "https://doc.rust-lang.org/book/ch11-01-writing-tests.html#testing-equality-with-assert_eq-and-assert_ne", "has_code": false, "code_tags": []}} {"id": "book/ch11-01-writing-tests.md#testing-equality-with-assert_eq-and-assert_ne-17", "text": "The Rust Programming Language › How to Write Tests › Testing Equality with `assert_eq!` and `assert_ne!`\n\nUnder the surface, the `assert_eq!` and `assert_ne!` macros use the operators\n`==` and `!=`, respectively. When the assertions fail, these macros print their\narguments using debug formatting, which means the values being compared must\nimplement the `PartialEq` and `Debug` traits. All primitive types and most of\nthe standard library types implement these traits. For structs and enums that\nyou define yourself, you’ll need to implement `PartialEq` to assert equality of\nthose types. You’ll also need to implement `Debug` to print the values when the\nassertion fails. Because both traits are derivable traits, as mentioned in\nListing 5-12 in Chapter 5, this is usually as straightforward as adding the\n`#[derive(PartialEq, Debug)]` annotation to your struct or enum definition. See\nAppendix C, “Derivable Traits,” for more\ndetails about these and other derivable traits.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "How to Write Tests", "heading_path": ["How to Write Tests", "Testing Equality with `assert_eq!` and `assert_ne!`"], "path": "ch11-01-writing-tests.md", "url": "https://doc.rust-lang.org/book/ch11-01-writing-tests.html#testing-equality-with-assert_eq-and-assert_ne", "has_code": false, "code_tags": []}} {"id": "book/ch11-01-writing-tests.md#adding-custom-failure-messages-18", "text": "The Rust Programming Language › How to Write Tests › Adding Custom Failure Messages\n\nYou can also add a custom message to be printed with the failure message as\noptional arguments to the `assert!`, `assert_eq!`, and `assert_ne!` macros. Any\narguments specified after the required arguments are passed along to the\n`format!` macro (discussed in “Concatenating with `+` or\n`format!`”\n in Chapter 8), so you can pass a format string that contains `{}`\nplaceholders and values to go in those placeholders. Custom messages are useful\nfor documenting what an assertion means; when a test fails, you’ll have a better\nidea of what the problem is with the code.\nFor example, let’s say we have a function that greets people by name and we\nwant to test that the name we pass into the function appears in the output:\nFilename: src/lib.rs\n```rust,noplayground\npub fn greeting(name: &str) -> String {\n format!(\"Hello {name}!\")\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn greeting_contains_name() {\n let result = greeting(\"Carol\");\n assert!(result.contains(\"Carol\"));\n }\n}\n```\nThe requirements for this program haven’t been agreed upon yet, and we’re\npretty sure the `Hello` text at the beginning of the greeting will change. We\ndecided we don’t want to have to update the test when the requirements change,\nso instead of checking for exact equality to the value returned from the\n`greeting` function, we’ll just assert that the output contains the text of the\ninput parameter.\nNow let’s introduce a bug into this code by changing `greeting` to exclude\n`name` to see what the default test failure looks like:\n```rust,not_desired_behavior,noplayground\npub fn greeting(name: &str) -> String {\n String::from(\"Hello!\")\n}\n```\nRunning this test produces the following:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "How to Write Tests", "heading_path": ["How to Write Tests", "Adding Custom Failure Messages"], "path": "ch11-01-writing-tests.md", "url": "https://doc.rust-lang.org/book/ch11-01-writing-tests.html#adding-custom-failure-messages", "has_code": true, "code_tags": ["rust,noplayground", "rust,not_desired_behavior,noplayground"]}} {"id": "book/ch11-01-writing-tests.md#adding-custom-failure-messages-19", "text": "The Rust Programming Language › How to Write Tests › Adding Custom Failure Messages\n\n```console\n$ cargo test\n Compiling greeter v0.1.0 (file:///projects/greeter)\n Finished `test` profile [unoptimized + debuginfo] target(s) in 0.91s\n Running unittests src/lib.rs (target/debug/deps/greeter-170b942eb5bf5e3a)\n\nrunning 1 test\ntest tests::greeting_contains_name ... FAILED\n\nfailures:\n\n---- tests::greeting_contains_name stdout ----\n\nthread 'tests::greeting_contains_name' (6021143) panicked at src/lib.rs:12:9:\nassertion failed: result.contains(\"Carol\")\nnote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n\n\nfailures:\n tests::greeting_contains_name\n\ntest result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\nerror: test failed, to rerun pass `--lib`\n```\nThis result just indicates that the assertion failed and which line the\nassertion is on. A more useful failure message would print the value from the\n`greeting` function. Let’s add a custom failure message composed of a format\nstring with a placeholder filled in with the actual value we got from the\n`greeting` function:\n```rust,ignore\n #[test]\n fn greeting_contains_name() {\n let result = greeting(\"Carol\");\n assert!(\n result.contains(\"Carol\"),\n \"Greeting did not contain name, value was `{result}`\"\n );\n }\n```\nNow when we run the test, we’ll get a more informative error message:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "How to Write Tests", "heading_path": ["How to Write Tests", "Adding Custom Failure Messages"], "path": "ch11-01-writing-tests.md", "url": "https://doc.rust-lang.org/book/ch11-01-writing-tests.html#adding-custom-failure-messages", "has_code": true, "code_tags": ["console", "rust,ignore"]}} {"id": "book/ch11-01-writing-tests.md#adding-custom-failure-messages-20", "text": "The Rust Programming Language › How to Write Tests › Adding Custom Failure Messages\n\n```console\n$ cargo test\n Compiling greeter v0.1.0 (file:///projects/greeter)\n Finished `test` profile [unoptimized + debuginfo] target(s) in 0.93s\n Running unittests src/lib.rs (target/debug/deps/greeter-170b942eb5bf5e3a)\n\nrunning 1 test\ntest tests::greeting_contains_name ... FAILED\n\nfailures:\n\n---- tests::greeting_contains_name stdout ----\n\nthread 'tests::greeting_contains_name' (6021333) panicked at src/lib.rs:12:9:\nGreeting did not contain name, value was `Hello!`\nnote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n\n\nfailures:\n tests::greeting_contains_name\n\ntest result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\nerror: test failed, to rerun pass `--lib`\n```\nWe can see the value we actually got in the test output, which would help us\ndebug what happened instead of what we were expecting to happen.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "How to Write Tests", "heading_path": ["How to Write Tests", "Adding Custom Failure Messages"], "path": "ch11-01-writing-tests.md", "url": "https://doc.rust-lang.org/book/ch11-01-writing-tests.html#adding-custom-failure-messages", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch11-01-writing-tests.md#checking-for-panics-with-should_panic-21", "text": "The Rust Programming Language › How to Write Tests › Checking for Panics with `should_panic`\n\nIn addition to checking return values, it’s important to check that our code\nhandles error conditions as we expect. For example, consider the `Guess` type\nthat we created in Chapter 9, Listing 9-13. Other code that uses `Guess`\ndepends on the guarantee that `Guess` instances will contain only values\nbetween 1 and 100. We can write a test that ensures that attempting to create a\n`Guess` instance with a value outside that range panics.\nWe do this by adding the attribute `should_panic` to our test function. The\ntest passes if the code inside the function panics; the test fails if the code\ninside the function doesn’t panic.\nListing 11-8 shows a test that checks that the error conditions of `Guess::new`\nhappen when we expect them to.\nListing 11-8: Testing that a condition will cause a `panic!` (src/lib.rs)\n```rust,noplayground\npub struct Guess {\n value: i32,\n}\n\nimpl Guess {\n pub fn new(value: i32) -> Guess {\n if value < 1 || value > 100 {\n panic!(\"Guess value must be between 1 and 100, got {value}.\");\n }\n\n Guess { value }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n #[should_panic]\n fn greater_than_100() {\n Guess::new(200);\n }\n}\n```\nWe place the `#[should_panic]` attribute after the `#[test]` attribute and\nbefore the test function it applies to. Let’s look at the result when this test\npasses:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "How to Write Tests", "heading_path": ["How to Write Tests", "Checking for Panics with `should_panic`"], "path": "ch11-01-writing-tests.md", "url": "https://doc.rust-lang.org/book/ch11-01-writing-tests.html#checking-for-panics-with-should_panic", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch11-01-writing-tests.md#checking-for-panics-with-should_panic-22", "text": "The Rust Programming Language › How to Write Tests › Checking for Panics with `should_panic`\n\n```console\n$ cargo test\n Compiling guessing_game v0.1.0 (file:///projects/guessing_game)\n Finished `test` profile [unoptimized + debuginfo] target(s) in 0.58s\n Running unittests src/lib.rs (target/debug/deps/guessing_game-57d70c3acb738f4d)\n\nrunning 1 test\ntest tests::greater_than_100 - should panic ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n Doc-tests guessing_game\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n```\nLooks good! Now let’s introduce a bug in our code by removing the condition\nthat the `new` function will panic if the value is greater than 100:\n```rust,not_desired_behavior,noplayground\n// --snip--\nimpl Guess {\n pub fn new(value: i32) -> Guess {\n if value < 1 {\n panic!(\"Guess value must be between 1 and 100, got {value}.\");\n }\n\n Guess { value }\n }\n}\n```\nWhen we run the test in Listing 11-8, it will fail:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "How to Write Tests", "heading_path": ["How to Write Tests", "Checking for Panics with `should_panic`"], "path": "ch11-01-writing-tests.md", "url": "https://doc.rust-lang.org/book/ch11-01-writing-tests.html#checking-for-panics-with-should_panic", "has_code": true, "code_tags": ["console", "rust,not_desired_behavior,noplayground"]}} {"id": "book/ch11-01-writing-tests.md#checking-for-panics-with-should_panic-23", "text": "The Rust Programming Language › How to Write Tests › Checking for Panics with `should_panic`\n\n```console\n$ cargo test\n Compiling guessing_game v0.1.0 (file:///projects/guessing_game)\n Finished `test` profile [unoptimized + debuginfo] target(s) in 0.62s\n Running unittests src/lib.rs (target/debug/deps/guessing_game-57d70c3acb738f4d)\n\nrunning 1 test\ntest tests::greater_than_100 - should panic ... FAILED\n\nfailures:\n\n---- tests::greater_than_100 stdout ----\nnote: test did not panic as expected at src/lib.rs:21:8\n\nfailures:\n tests::greater_than_100\n\ntest result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\nerror: test failed, to rerun pass `--lib`\n```\nWe don’t get a very helpful message in this case, but when we look at the test\nfunction, we see that it’s annotated with `#[should_panic]`. The failure we got\nmeans that the code in the test function did not cause a panic.\nTests that use `should_panic` can be imprecise. A `should_panic` test would\npass even if the test panics for a different reason from the one we were\nexpecting. To make `should_panic` tests more precise, we can add an optional\n`expected` parameter to the `should_panic` attribute. The test harness will\nmake sure that the failure message contains the provided text. For example,\nconsider the modified code for `Guess` in Listing 11-9 where the `new` function\npanics with different messages depending on whether the value is too small or\ntoo large.\nListing 11-9: Testing for a `panic!` with a panic message containing a specified substring (src/lib.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "How to Write Tests", "heading_path": ["How to Write Tests", "Checking for Panics with `should_panic`"], "path": "ch11-01-writing-tests.md", "url": "https://doc.rust-lang.org/book/ch11-01-writing-tests.html#checking-for-panics-with-should_panic", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch11-01-writing-tests.md#checking-for-panics-with-should_panic-24", "text": "The Rust Programming Language › How to Write Tests › Checking for Panics with `should_panic`\n\n```rust,noplayground\n// --snip--\n\nimpl Guess {\n pub fn new(value: i32) -> Guess {\n if value < 1 {\n panic!(\n \"Guess value must be greater than or equal to 1, got {value}.\"\n );\n } else if value > 100 {\n panic!(\n \"Guess value must be less than or equal to 100, got {value}.\"\n );\n }\n\n Guess { value }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n #[should_panic(expected = \"less than or equal to 100\")]\n fn greater_than_100() {\n Guess::new(200);\n }\n}\n```\nThis test will pass because the value we put in the `should_panic` attribute’s\n`expected` parameter is a substring of the message that the `Guess::new`\nfunction panics with. We could have specified the entire panic message that we\nexpect, which in this case would be `Guess value must be less than or equal to\n100, got 200`. What you choose to specify depends on how much of the panic\nmessage is unique or dynamic and how precise you want your test to be. In this\ncase, a substring of the panic message is enough to ensure that the code in the\ntest function executes the `else if value > 100` case.\nTo see what happens when a `should_panic` test with an `expected` message\nfails, let’s again introduce a bug into our code by swapping the bodies of the\n`if value < 1` and the `else if value > 100` blocks:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "How to Write Tests", "heading_path": ["How to Write Tests", "Checking for Panics with `should_panic`"], "path": "ch11-01-writing-tests.md", "url": "https://doc.rust-lang.org/book/ch11-01-writing-tests.html#checking-for-panics-with-should_panic", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch11-01-writing-tests.md#checking-for-panics-with-should_panic-25", "text": "The Rust Programming Language › How to Write Tests › Checking for Panics with `should_panic`\n\n```rust,ignore,not_desired_behavior\n if value < 1 {\n panic!(\n \"Guess value must be less than or equal to 100, got {value}.\"\n );\n } else if value > 100 {\n panic!(\n \"Guess value must be greater than or equal to 1, got {value}.\"\n );\n }\n```\nThis time when we run the `should_panic` test, it will fail:\n```console\n$ cargo test\n Compiling guessing_game v0.1.0 (file:///projects/guessing_game)\n Finished `test` profile [unoptimized + debuginfo] target(s) in 0.66s\n Running unittests src/lib.rs (target/debug/deps/guessing_game-57d70c3acb738f4d)\n\nrunning 1 test\ntest tests::greater_than_100 - should panic ... FAILED\n\nfailures:\n\n---- tests::greater_than_100 stdout ----\n\nthread 'tests::greater_than_100' (6021675) panicked at src/lib.rs:12:13:\nGuess value must be greater than or equal to 1, got 200.\nnote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\nnote: panic did not contain expected string\n panic message: \"Guess value must be greater than or equal to 1, got 200.\"\n expected substring: \"less than or equal to 100\"\n\nfailures:\n tests::greater_than_100\n\ntest result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\nerror: test failed, to rerun pass `--lib`\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "How to Write Tests", "heading_path": ["How to Write Tests", "Checking for Panics with `should_panic`"], "path": "ch11-01-writing-tests.md", "url": "https://doc.rust-lang.org/book/ch11-01-writing-tests.html#checking-for-panics-with-should_panic", "has_code": true, "code_tags": ["console", "rust,ignore,not_desired_behavior"]}} {"id": "book/ch11-01-writing-tests.md#checking-for-panics-with-should_panic-26", "text": "The Rust Programming Language › How to Write Tests › Checking for Panics with `should_panic`\n\nThe failure message indicates that this test did indeed panic as we expected,\nbut the panic message did not include the expected string `less than or equal\nto 100`. The panic message that we did get in this case was `Guess value must\nbe greater than or equal to 1, got 200`. Now we can start figuring out where\nour bug is!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "How to Write Tests", "heading_path": ["How to Write Tests", "Checking for Panics with `should_panic`"], "path": "ch11-01-writing-tests.md", "url": "https://doc.rust-lang.org/book/ch11-01-writing-tests.html#checking-for-panics-with-should_panic", "has_code": false, "code_tags": []}} {"id": "book/ch11-01-writing-tests.md#using-resultt-e-in-tests-27", "text": "The Rust Programming Language › How to Write Tests › Using `Result` in Tests\n\nAll of our tests so far panic when they fail. We can also write tests that use\n`Result`! Here’s the test from Listing 11-1, rewritten to use `Result` and return an `Err` instead of panicking:\n```rust,noplayground\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn it_works() -> Result<(), String> {\n let result = add(2, 2);\n\n if result == 4 {\n Ok(())\n } else {\n Err(String::from(\"two plus two does not equal four\"))\n }\n }\n}\n```\nThe `it_works` function now has the `Result<(), String>` return type. In the\nbody of the function, rather than calling the `assert_eq!` macro, we return\n`Ok(())` when the test passes and an `Err` with a `String` inside when the test\nfails.\nWriting tests so that they return a `Result` enables you to use the\nquestion mark operator in the body of tests, which can be a convenient way to\nwrite tests that should fail if any operation within them returns an `Err`\nvariant.\nYou can’t use the `#[should_panic]` annotation on tests that use `Result`. To assert that an operation returns an `Err` variant, _don’t_ use the\nquestion mark operator on the `Result` value. Instead, use\n`assert!(value.is_err())`.\nNow that you know several ways to write tests, let’s look at what is happening\nwhen we run our tests and explore the different options we can use with `cargo\ntest`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "How to Write Tests", "heading_path": ["How to Write Tests", "Using `Result` in Tests"], "path": "ch11-01-writing-tests.md", "url": "https://doc.rust-lang.org/book/ch11-01-writing-tests.html#using-resultt-e-in-tests", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch11-02-running-tests.md#controlling-how-tests-are-run-0", "text": "The Rust Programming Language › Controlling How Tests Are Run\n\nJust as `cargo run` compiles your code and then runs the resultant binary,\n`cargo test` compiles your code in test mode and runs the resultant test\nbinary. The default behavior of the binary produced by `cargo test` is to run\nall the tests in parallel and capture output generated during test runs,\npreventing the output from being displayed and making it easier to read the\noutput related to the test results. You can, however, specify command line\noptions to change this default behavior.\nSome command line options go to `cargo test`, and some go to the resultant test\nbinary. To separate these two types of arguments, you list the arguments that\ngo to `cargo test` followed by the separator `--` and then the ones that go to\nthe test binary. Running `cargo test --help` displays the options you can use\nwith `cargo test`, and running `cargo test -- --help` displays the options you\ncan use after the separator. These options are also documented in the “Tests”\nsection of _The `rustc` Book_.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Controlling How Tests Are Run", "heading_path": ["Controlling How Tests Are Run"], "path": "ch11-02-running-tests.md", "url": "https://doc.rust-lang.org/book/ch11-02-running-tests.html#controlling-how-tests-are-run", "has_code": false, "code_tags": []}} {"id": "book/ch11-02-running-tests.md#running-tests-in-parallel-or-consecutively-1", "text": "The Rust Programming Language › Controlling How Tests Are Run › Running Tests in Parallel or Consecutively\n\nWhen you run multiple tests, by default they run in parallel using threads,\nmeaning they finish running more quickly and you get feedback sooner. Because\nthe tests are running at the same time, you must make sure your tests don’t\ndepend on each other or on any shared state, including a shared environment,\nsuch as the current working directory or environment variables.\nFor example, say each of your tests runs some code that creates a file on disk\nnamed _test-output.txt_ and writes some data to that file. Then, each test\nreads the data in that file and asserts that the file contains a particular\nvalue, which is different in each test. Because the tests run at the same time,\none test might overwrite the file in the time between when another test is\nwriting and reading the file. The second test will then fail, not because the\ncode is incorrect but because the tests have interfered with each other while\nrunning in parallel. One solution is to make sure each test writes to a\ndifferent file; another solution is to run the tests one at a time.\nIf you don’t want to run the tests in parallel or if you want more fine-grained\ncontrol over the number of threads used, you can send the `--test-threads` flag\nand the number of threads you want to use to the test binary. Take a look at\nthe following example:\n```console\n$ cargo test -- --test-threads=1\n```\nWe set the number of test threads to `1`, telling the program not to use any\nparallelism. Running the tests using one thread will take longer than running\nthem in parallel, but the tests won’t interfere with each other if they share\nstate.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Controlling How Tests Are Run", "heading_path": ["Controlling How Tests Are Run", "Running Tests in Parallel or Consecutively"], "path": "ch11-02-running-tests.md", "url": "https://doc.rust-lang.org/book/ch11-02-running-tests.html#running-tests-in-parallel-or-consecutively", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch11-02-running-tests.md#showing-function-output-2", "text": "The Rust Programming Language › Controlling How Tests Are Run › Showing Function Output\n\nBy default, if a test passes, Rust’s test library captures anything printed to\nstandard output. For example, if we call `println!` in a test and the test\npasses, we won’t see the `println!` output in the terminal; we’ll see only the\nline that indicates the test passed. If a test fails, we’ll see whatever was\nprinted to standard output with the rest of the failure message.\nAs an example, Listing 11-10 has a silly function that prints the value of its\nparameter and returns 10, as well as a test that passes and a test that fails.\nListing 11-10: Tests for a function that calls `println!` (src/lib.rs)\n```rust,panics,noplayground\nfn prints_and_returns_10(a: i32) -> i32 {\n println!(\"I got the value {a}\");\n 10\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn this_test_will_pass() {\n let value = prints_and_returns_10(4);\n assert_eq!(value, 10);\n }\n\n #[test]\n fn this_test_will_fail() {\n let value = prints_and_returns_10(8);\n assert_eq!(value, 5);\n }\n}\n```\nWhen we run these tests with `cargo test`, we’ll see the following output:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Controlling How Tests Are Run", "heading_path": ["Controlling How Tests Are Run", "Showing Function Output"], "path": "ch11-02-running-tests.md", "url": "https://doc.rust-lang.org/book/ch11-02-running-tests.html#showing-function-output", "has_code": true, "code_tags": ["rust,panics,noplayground"]}} {"id": "book/ch11-02-running-tests.md#showing-function-output-3", "text": "The Rust Programming Language › Controlling How Tests Are Run › Showing Function Output\n\n```console\n$ cargo test\n Compiling silly-function v0.1.0 (file:///projects/silly-function)\n Finished `test` profile [unoptimized + debuginfo] target(s) in 0.58s\n Running unittests src/lib.rs (target/debug/deps/silly_function-160869f38cff9166)\n\nrunning 2 tests\ntest tests::this_test_will_fail ... FAILED\ntest tests::this_test_will_pass ... ok\n\nfailures:\n\n---- tests::this_test_will_fail stdout ----\nI got the value 8\n\nthread 'tests::this_test_will_fail' (6019863) panicked at src/lib.rs:19:9:\nassertion `left == right` failed\n left: 10\n right: 5\nnote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n\n\nfailures:\n tests::this_test_will_fail\n\ntest result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\nerror: test failed, to rerun pass `--lib`\n```\nNote that nowhere in this output do we see `I got the value 4`, which is\nprinted when the test that passes runs. That output has been captured. The\noutput from the test that failed, `I got the value 8`, appears in the section\nof the test summary output, which also shows the cause of the test failure.\nIf we want to see printed values for passing tests as well, we can tell Rust to\nalso show the output of successful tests with `--show-output`:\n```console\n$ cargo test -- --show-output\n```\nWhen we run the tests in Listing 11-10 again with the `--show-output` flag, we\nsee the following output:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Controlling How Tests Are Run", "heading_path": ["Controlling How Tests Are Run", "Showing Function Output"], "path": "ch11-02-running-tests.md", "url": "https://doc.rust-lang.org/book/ch11-02-running-tests.html#showing-function-output", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch11-02-running-tests.md#showing-function-output-4", "text": "The Rust Programming Language › Controlling How Tests Are Run › Showing Function Output\n\n```console\n$ cargo test -- --show-output\n Compiling silly-function v0.1.0 (file:///projects/silly-function)\n Finished `test` profile [unoptimized + debuginfo] target(s) in 0.60s\n Running unittests src/lib.rs (target/debug/deps/silly_function-160869f38cff9166)\n\nrunning 2 tests\ntest tests::this_test_will_fail ... FAILED\ntest tests::this_test_will_pass ... ok\n\nsuccesses:\n\n---- tests::this_test_will_pass stdout ----\nI got the value 4\n\n\nsuccesses:\n tests::this_test_will_pass\n\nfailures:\n\n---- tests::this_test_will_fail stdout ----\nI got the value 8\n\nthread 'tests::this_test_will_fail' (6022313) panicked at src/lib.rs:19:9:\nassertion `left == right` failed\n left: 10\n right: 5\nnote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n\n\nfailures:\n tests::this_test_will_fail\n\ntest result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\nerror: test failed, to rerun pass `--lib`\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Controlling How Tests Are Run", "heading_path": ["Controlling How Tests Are Run", "Showing Function Output"], "path": "ch11-02-running-tests.md", "url": "https://doc.rust-lang.org/book/ch11-02-running-tests.html#showing-function-output", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch11-02-running-tests.md#running-a-subset-of-tests-by-name-5", "text": "The Rust Programming Language › Controlling How Tests Are Run › Running a Subset of Tests by Name\n\nRunning a full test suite can sometimes take a long time. If you’re working on\ncode in a particular area, you might want to run only the tests pertaining to\nthat code. You can choose which tests to run by passing `cargo test` the name\nor names of the test(s) you want to run as an argument.\nTo demonstrate how to run a subset of tests, we’ll first create three tests for\nour `add_two` function, as shown in Listing 11-11, and choose which ones to run.\nListing 11-11: Three tests with three different names (src/lib.rs)\n```rust,noplayground\npub fn add_two(a: u64) -> u64 {\n a + 2\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn add_two_and_two() {\n let result = add_two(2);\n assert_eq!(result, 4);\n }\n\n #[test]\n fn add_three_and_two() {\n let result = add_two(3);\n assert_eq!(result, 5);\n }\n\n #[test]\n fn one_hundred() {\n let result = add_two(100);\n assert_eq!(result, 102);\n }\n}\n```\nIf we run the tests without passing any arguments, as we saw earlier, all the\ntests will run in parallel:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Controlling How Tests Are Run", "heading_path": ["Controlling How Tests Are Run", "Running a Subset of Tests by Name"], "path": "ch11-02-running-tests.md", "url": "https://doc.rust-lang.org/book/ch11-02-running-tests.html#running-a-subset-of-tests-by-name", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch11-02-running-tests.md#running-single-tests-6", "text": "The Rust Programming Language › Controlling How Tests Are Run › Running a Subset of Tests by Name › Running Single Tests\n\n```console\n$ cargo test\n Compiling adder v0.1.0 (file:///projects/adder)\n Finished `test` profile [unoptimized + debuginfo] target(s) in 0.62s\n Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)\n\nrunning 3 tests\ntest tests::add_three_and_two ... ok\ntest tests::add_two_and_two ... ok\ntest tests::one_hundred ... ok\n\ntest result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n Doc-tests adder\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n```\nWe can pass the name of any test function to `cargo test` to run only that test:\n```console\n$ cargo test one_hundred\n Compiling adder v0.1.0 (file:///projects/adder)\n Finished `test` profile [unoptimized + debuginfo] target(s) in 0.69s\n Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)\n\nrunning 1 test\ntest tests::one_hundred ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 2 filtered out; finished in 0.00s\n\n```\nOnly the test with the name `one_hundred` ran; the other two tests didn’t match\nthat name. The test output lets us know we had more tests that didn’t run by\ndisplaying `2 filtered out` at the end.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Controlling How Tests Are Run", "heading_path": ["Controlling How Tests Are Run", "Running a Subset of Tests by Name", "Running Single Tests"], "path": "ch11-02-running-tests.md", "url": "https://doc.rust-lang.org/book/ch11-02-running-tests.html#running-single-tests", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch11-02-running-tests.md#filtering-to-run-multiple-tests-7", "text": "The Rust Programming Language › Controlling How Tests Are Run › Running a Subset of Tests by Name › Filtering to Run Multiple Tests\n\nWe can’t specify the names of multiple tests in this way; only the first value\ngiven to `cargo test` will be used. But there is a way to run multiple tests.\nWe can specify part of a test name, and any test whose name matches that value\nwill be run. For example, because two of our tests’ names contain `add`, we can\nrun those two by running `cargo test add`:\n```console\n$ cargo test add\n Compiling adder v0.1.0 (file:///projects/adder)\n Finished `test` profile [unoptimized + debuginfo] target(s) in 0.61s\n Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)\n\nrunning 2 tests\ntest tests::add_three_and_two ... ok\ntest tests::add_two_and_two ... ok\n\ntest result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out; finished in 0.00s\n\n```\nThis command ran all tests with `add` in the name and filtered out the test\nnamed `one_hundred`. Also note that the module in which a test appears becomes\npart of the test’s name, so we can run all the tests in a module by filtering\non the module’s name.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Controlling How Tests Are Run", "heading_path": ["Controlling How Tests Are Run", "Running a Subset of Tests by Name", "Filtering to Run Multiple Tests"], "path": "ch11-02-running-tests.md", "url": "https://doc.rust-lang.org/book/ch11-02-running-tests.html#filtering-to-run-multiple-tests", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch11-02-running-tests.md#ignoring-tests-unless-specifically-requested-8", "text": "The Rust Programming Language › Controlling How Tests Are Run › Ignoring Tests Unless Specifically Requested\n\nSometimes a few specific tests can be very time-consuming to execute, so you\nmight want to exclude them during most runs of `cargo test`. Rather than\nlisting as arguments all tests you do want to run, you can instead annotate the\ntime-consuming tests using the `ignore` attribute to exclude them, as shown\nhere:\nFilename: src/lib.rs\n```rust,noplayground\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn it_works() {\n let result = add(2, 2);\n assert_eq!(result, 4);\n }\n\n #[test]\n #[ignore]\n fn expensive_test() {\n // code that takes an hour to run\n }\n}\n```\nAfter `#[test]`, we add the `#[ignore]` line to the test we want to exclude.\nNow when we run our tests, `it_works` runs, but `expensive_test` doesn’t:\n```console\n$ cargo test\n Compiling adder v0.1.0 (file:///projects/adder)\n Finished `test` profile [unoptimized + debuginfo] target(s) in 0.60s\n Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)\n\nrunning 2 tests\ntest tests::expensive_test ... ignored\ntest tests::it_works ... ok\n\ntest result: ok. 1 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n Doc-tests adder\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Controlling How Tests Are Run", "heading_path": ["Controlling How Tests Are Run", "Ignoring Tests Unless Specifically Requested"], "path": "ch11-02-running-tests.md", "url": "https://doc.rust-lang.org/book/ch11-02-running-tests.html#ignoring-tests-unless-specifically-requested", "has_code": true, "code_tags": ["console", "rust,noplayground"]}} {"id": "book/ch11-02-running-tests.md#ignoring-tests-unless-specifically-requested-9", "text": "The Rust Programming Language › Controlling How Tests Are Run › Ignoring Tests Unless Specifically Requested\n\nThe `expensive_test` function is listed as `ignored`. If we want to run only\nthe ignored tests, we can use `cargo test -- --ignored`:\n```console\n$ cargo test -- --ignored\n Compiling adder v0.1.0 (file:///projects/adder)\n Finished `test` profile [unoptimized + debuginfo] target(s) in 0.61s\n Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)\n\nrunning 1 test\ntest tests::expensive_test ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out; finished in 0.00s\n\n Doc-tests adder\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n```\nBy controlling which tests run, you can make sure your `cargo test` results\nwill be returned quickly. When you’re at a point where it makes sense to check\nthe results of the `ignored` tests and you have time to wait for the results,\nyou can run `cargo test -- --ignored` instead. If you want to run all tests\nwhether they’re ignored or not, you can run `cargo test -- --include-ignored`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Controlling How Tests Are Run", "heading_path": ["Controlling How Tests Are Run", "Ignoring Tests Unless Specifically Requested"], "path": "ch11-02-running-tests.md", "url": "https://doc.rust-lang.org/book/ch11-02-running-tests.html#ignoring-tests-unless-specifically-requested", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch11-03-test-organization.md#test-organization-0", "text": "The Rust Programming Language › Test Organization\n\nAs mentioned at the start of the chapter, testing is a complex discipline, and\ndifferent people use different terminology and organization. The Rust community\nthinks about tests in terms of two main categories: unit tests and integration\ntests. _Unit tests_ are small and more focused, testing one module in isolation\nat a time, and can test private interfaces. _Integration tests_ are entirely\nexternal to your library and use your code in the same way any other external\ncode would, using only the public interface and potentially exercising multiple\nmodules per test.\nWriting both kinds of tests is important to ensure that the pieces of your\nlibrary are doing what you expect them to, separately and together.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Test Organization", "heading_path": ["Test Organization"], "path": "ch11-03-test-organization.md", "url": "https://doc.rust-lang.org/book/ch11-03-test-organization.html#test-organization", "has_code": false, "code_tags": []}} {"id": "book/ch11-03-test-organization.md#the-tests-module-and-cfgtest-1", "text": "The Rust Programming Language › Test Organization › Unit Tests › The `tests` Module and `#[cfg(test)]`\n\nThe purpose of unit tests is to test each unit of code in isolation from the\nrest of the code to quickly pinpoint where code is and isn’t working as\nexpected. You’ll put unit tests in the _src_ directory in each file with the\ncode that they’re testing. The convention is to create a module named `tests`\nin each file to contain the test functions and to annotate the module with\n`cfg(test)`.\nThe `#[cfg(test)]` annotation on the `tests` module tells Rust to compile and\nrun the test code only when you run `cargo test`, not when you run `cargo\nbuild`. This saves compile time when you only want to build the library and\nsaves space in the resultant compiled artifact because the tests are not\nincluded. You’ll see that because integration tests go in a different\ndirectory, they don’t need the `#[cfg(test)]` annotation. However, because unit\ntests go in the same files as the code, you’ll use `#[cfg(test)]` to specify\nthat they shouldn’t be included in the compiled result.\nRecall that when we generated the new `adder` project in the first section of\nthis chapter, Cargo generated this code for us:\nFilename: src/lib.rs\n```rust,noplayground\npub fn add(left: u64, right: u64) -> u64 {\n left + right\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn it_works() {\n let result = add(2, 2);\n assert_eq!(result, 4);\n }\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Test Organization", "heading_path": ["Test Organization", "Unit Tests", "The `tests` Module and `#[cfg(test)]`"], "path": "ch11-03-test-organization.md", "url": "https://doc.rust-lang.org/book/ch11-03-test-organization.html#the-tests-module-and-cfgtest", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch11-03-test-organization.md#private-function-tests-2", "text": "The Rust Programming Language › Test Organization › Unit Tests › Private Function Tests\n\nOn the automatically generated `tests` module, the attribute `cfg` stands for\n_configuration_ and tells Rust that the following item should only be included\ngiven a certain configuration option. In this case, the configuration option is\n`test`, which is provided by Rust for compiling and running tests. By using the\n`cfg` attribute, Cargo compiles our test code only if we actively run the tests\nwith `cargo test`. This includes any helper functions that might be within this\nmodule, in addition to the functions annotated with `#[test]`.\nThere’s debate within the testing community about whether or not private\nfunctions should be tested directly, and other languages make it difficult or\nimpossible to test private functions. Regardless of which testing ideology you\nadhere to, Rust’s privacy rules do allow you to test private functions.\nConsider the code in Listing 11-12 with the private function `internal_adder`.\nListing 11-12: Testing a private function (src/lib.rs)\n```rust,noplayground\npub fn add_two(a: u64) -> u64 {\n internal_adder(a, 2)\n}\n\nfn internal_adder(left: u64, right: u64) -> u64 {\n left + right\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn internal() {\n let result = internal_adder(2, 2);\n assert_eq!(result, 4);\n }\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Test Organization", "heading_path": ["Test Organization", "Unit Tests", "Private Function Tests"], "path": "ch11-03-test-organization.md", "url": "https://doc.rust-lang.org/book/ch11-03-test-organization.html#private-function-tests", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch11-03-test-organization.md#private-function-tests-3", "text": "The Rust Programming Language › Test Organization › Unit Tests › Private Function Tests\n\nNote that the `internal_adder` function is not marked as `pub`. Tests are just\nRust code, and the `tests` module is just another module. As we discussed in\n“Paths for Referring to an Item in the Module Tree”,\nitems in child modules can use the items in their ancestor modules. In this\ntest, we bring all of the items belonging to the `tests` module’s parent into\nscope with `use super::*`, and then the test can call `internal_adder`. If you\ndon’t think private functions should be tested, there’s nothing in Rust that\nwill compel you to do so.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Test Organization", "heading_path": ["Test Organization", "Unit Tests", "Private Function Tests"], "path": "ch11-03-test-organization.md", "url": "https://doc.rust-lang.org/book/ch11-03-test-organization.html#private-function-tests", "has_code": false, "code_tags": []}} {"id": "book/ch11-03-test-organization.md#the-tests-directory-4", "text": "The Rust Programming Language › Test Organization › Integration Tests › The tests Directory\n\nIn Rust, integration tests are entirely external to your library. They use your\nlibrary in the same way any other code would, which means they can only call\nfunctions that are part of your library’s public API. Their purpose is to test\nwhether many parts of your library work together correctly. Units of code that\nwork correctly on their own could have problems when integrated, so test\ncoverage of the integrated code is important as well. To create integration\ntests, you first need a _tests_ directory.\nWe create a _tests_ directory at the top level of our project directory, next\nto _src_. Cargo knows to look for integration test files in this directory. We\ncan then make as many test files as we want, and Cargo will compile each of the\nfiles as an individual crate.\nLet’s create an integration test. With the code in Listing 11-12 still in the\n_src/lib.rs_ file, make a _tests_ directory, and create a new file named\n_tests/integration_test.rs_. Your directory structure should look like this:\n```text\nadder\n├── Cargo.lock\n├── Cargo.toml\n├── src\n│   └── lib.rs\n└── tests\n └── integration_test.rs\n```\nEnter the code in Listing 11-13 into the _tests/integration_test.rs_ file.\nListing 11-13: An integration test of a function in the `adder` crate (tests/integration_test.rs)\n```rust,ignore\nuse adder::add_two;\n\n#[test]\nfn it_adds_two() {\n let result = add_two(2);\n assert_eq!(result, 4);\n}\n```\nEach file in the _tests_ directory is a separate crate, so we need to bring our\nlibrary into each test crate’s scope. For that reason, we add `use\nadder::add_two;` at the top of the code, which we didn’t need in the unit tests.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Test Organization", "heading_path": ["Test Organization", "Integration Tests", "The tests Directory"], "path": "ch11-03-test-organization.md", "url": "https://doc.rust-lang.org/book/ch11-03-test-organization.html#the-tests-directory", "has_code": true, "code_tags": ["rust,ignore", "text"]}} {"id": "book/ch11-03-test-organization.md#the-tests-directory-5", "text": "The Rust Programming Language › Test Organization › Integration Tests › The tests Directory\n\nWe don’t need to annotate any code in _tests/integration_test.rs_ with\n`#[cfg(test)]`. Cargo treats the _tests_ directory specially and compiles files\nin this directory only when we run `cargo test`. Run `cargo test` now:\n```console\n$ cargo test\n Compiling adder v0.1.0 (file:///projects/adder)\n Finished `test` profile [unoptimized + debuginfo] target(s) in 1.31s\n Running unittests src/lib.rs (target/debug/deps/adder-1082c4b063a8fbe6)\n\nrunning 1 test\ntest tests::internal ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n Running tests/integration_test.rs (target/debug/deps/integration_test-1082c4b063a8fbe6)\n\nrunning 1 test\ntest it_adds_two ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n Doc-tests adder\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n```\nThe three sections of output include the unit tests, the integration test, and\nthe doc tests. Note that if any test in a section fails, the following sections\nwill not be run. For example, if a unit test fails, there won’t be any output\nfor integration and doc tests, because those tests will only be run if all unit\ntests are passing.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Test Organization", "heading_path": ["Test Organization", "Integration Tests", "The tests Directory"], "path": "ch11-03-test-organization.md", "url": "https://doc.rust-lang.org/book/ch11-03-test-organization.html#the-tests-directory", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch11-03-test-organization.md#submodules-in-integration-tests-6", "text": "The Rust Programming Language › Test Organization › Integration Tests › Submodules in Integration Tests\n\nThe first section for the unit tests is the same as we’ve been seeing: one line\nfor each unit test (one named `internal` that we added in Listing 11-12) and\nthen a summary line for the unit tests.\nThe integration tests section starts with the line `Running\ntests/integration_test.rs`. Next, there is a line for each test function in\nthat integration test and a summary line for the results of the integration\ntest just before the `Doc-tests adder` section starts.\nEach integration test file has its own section, so if we add more files in the\n_tests_ directory, there will be more integration test sections.\nWe can still run a particular integration test function by specifying the test\nfunction’s name as an argument to `cargo test`. To run all the tests in a\nparticular integration test file, use the `--test` argument of `cargo test`\nfollowed by the name of the file:\n```console\n$ cargo test --test integration_test\n Compiling adder v0.1.0 (file:///projects/adder)\n Finished `test` profile [unoptimized + debuginfo] target(s) in 0.64s\n Running tests/integration_test.rs (target/debug/deps/integration_test-82e7799c1bc62298)\n\nrunning 1 test\ntest it_adds_two ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n```\nThis command runs only the tests in the _tests/integration_test.rs_ file.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Test Organization", "heading_path": ["Test Organization", "Integration Tests", "Submodules in Integration Tests"], "path": "ch11-03-test-organization.md", "url": "https://doc.rust-lang.org/book/ch11-03-test-organization.html#submodules-in-integration-tests", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch11-03-test-organization.md#submodules-in-integration-tests-7", "text": "The Rust Programming Language › Test Organization › Integration Tests › Submodules in Integration Tests\n\nAs you add more integration tests, you might want to make more files in the\n_tests_ directory to help organize them; for example, you can group the test\nfunctions by the functionality they’re testing. As mentioned earlier, each file\nin the _tests_ directory is compiled as its own separate crate, which is useful\nfor creating separate scopes to more closely imitate the way end users will be\nusing your crate. However, this means files in the _tests_ directory don’t\nshare the same behavior as files in _src_ do, as you learned in Chapter 7\nregarding how to separate code into modules and files.\nThe different behavior of _tests_ directory files is most noticeable when you\nhave a set of helper functions to use in multiple integration test files, and\nyou try to follow the steps in the “Separating Modules into Different\nFiles” section of Chapter 7 to\nextract them into a common module. For example, if we create _tests/common.rs_\nand place a function named `setup` in it, we can add some code to `setup` that\nwe want to call from multiple test functions in multiple test files:\nFilename: tests/common.rs\n```rust,noplayground\npub fn setup() {\n // setup code specific to your library's tests would go here\n}\n```\nWhen we run the tests again, we’ll see a new section in the test output for the\n_common.rs_ file, even though this file doesn’t contain any test functions nor\ndid we call the `setup` function from anywhere:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Test Organization", "heading_path": ["Test Organization", "Integration Tests", "Submodules in Integration Tests"], "path": "ch11-03-test-organization.md", "url": "https://doc.rust-lang.org/book/ch11-03-test-organization.html#submodules-in-integration-tests", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch11-03-test-organization.md#submodules-in-integration-tests-8", "text": "The Rust Programming Language › Test Organization › Integration Tests › Submodules in Integration Tests\n\n```console\n$ cargo test\n Compiling adder v0.1.0 (file:///projects/adder)\n Finished `test` profile [unoptimized + debuginfo] target(s) in 0.89s\n Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)\n\nrunning 1 test\ntest tests::internal ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n Running tests/common.rs (target/debug/deps/common-92948b65e88960b4)\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n Running tests/integration_test.rs (target/debug/deps/integration_test-92948b65e88960b4)\n\nrunning 1 test\ntest it_adds_two ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n Doc-tests adder\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n```\nHaving `common` appear in the test results with `running 0 tests` displayed for\nit is not what we wanted. We just wanted to share some code with the other\nintegration test files. To avoid having `common` appear in the test output,\ninstead of creating _tests/common.rs_, we’ll create _tests/common/mod.rs_. The\nproject directory now looks like this:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Test Organization", "heading_path": ["Test Organization", "Integration Tests", "Submodules in Integration Tests"], "path": "ch11-03-test-organization.md", "url": "https://doc.rust-lang.org/book/ch11-03-test-organization.html#submodules-in-integration-tests", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch11-03-test-organization.md#integration-tests-for-binary-crates-9", "text": "The Rust Programming Language › Test Organization › Integration Tests › Integration Tests for Binary Crates\n\n```text\n├── Cargo.lock\n├── Cargo.toml\n├── src\n│   └── lib.rs\n└── tests\n ├── common\n │   └── mod.rs\n └── integration_test.rs\n```\nThis is the older naming convention that Rust also understands that we mentioned\nin “Alternate File Paths” in Chapter 7. Naming the\nfile this way tells Rust not to treat the `common` module as an integration test\nfile. When we move the `setup` function code into _tests/common/mod.rs_ and\ndelete the _tests/common.rs_ file, the section in the test output will no longer\nappear. Files in subdirectories of the _tests_ directory don’t get compiled as\nseparate crates or have sections in the test output.\nAfter we’ve created _tests/common/mod.rs_, we can use it from any of the\nintegration test files as a module. Here’s an example of calling the `setup`\nfunction from the `it_adds_two` test in _tests/integration_test.rs_:\nFilename: tests/integration_test.rs\n```rust,ignore\nuse adder::add_two;\n\nmod common;\n\n#[test]\nfn it_adds_two() {\n common::setup();\n\n let result = add_two(2);\n assert_eq!(result, 4);\n}\n```\nNote that the `mod common;` declaration is the same as the module declaration\nwe demonstrated in Listing 7-21. Then, in the test function, we can call the\n`common::setup()` function.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Test Organization", "heading_path": ["Test Organization", "Integration Tests", "Integration Tests for Binary Crates"], "path": "ch11-03-test-organization.md", "url": "https://doc.rust-lang.org/book/ch11-03-test-organization.html#integration-tests-for-binary-crates", "has_code": true, "code_tags": ["rust,ignore", "text"]}} {"id": "book/ch11-03-test-organization.md#integration-tests-for-binary-crates-10", "text": "The Rust Programming Language › Test Organization › Integration Tests › Integration Tests for Binary Crates\n\nIf our project is a binary crate that only contains a _src/main.rs_ file and\ndoesn’t have a _src/lib.rs_ file, we can’t create integration tests in the\n_tests_ directory and bring functions defined in the _src/main.rs_ file into\nscope with a `use` statement. Only library crates expose functions that other\ncrates can use; binary crates are meant to be run on their own.\nThis is one of the reasons Rust projects that provide a binary have a\nstraightforward _src/main.rs_ file that calls logic that lives in the\n_src/lib.rs_ file. Using that structure, integration tests _can_ test the\nlibrary crate with `use` to make the important functionality available. If the\nimportant functionality works, the small amount of code in the _src/main.rs_\nfile will work as well, and that small amount of code doesn’t need to be tested.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Test Organization", "heading_path": ["Test Organization", "Integration Tests", "Integration Tests for Binary Crates"], "path": "ch11-03-test-organization.md", "url": "https://doc.rust-lang.org/book/ch11-03-test-organization.html#integration-tests-for-binary-crates", "has_code": false, "code_tags": []}} {"id": "book/ch11-03-test-organization.md#summary-11", "text": "The Rust Programming Language › Summary\n\nRust’s testing features provide a way to specify how code should function to\nensure that it continues to work as you expect, even as you make changes. Unit\ntests exercise different parts of a library separately and can test private\nimplementation details. Integration tests check that many parts of the library\nwork together correctly, and they use the library’s public API to test the code\nin the same way external code will use it. Even though Rust’s type system and\nownership rules help prevent some kinds of bugs, tests are still important to\nreduce logic bugs having to do with how your code is expected to behave.\nLet’s combine the knowledge you learned in this chapter and in previous\nchapters to work on a project!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Test Organization", "heading_path": ["Summary"], "path": "ch11-03-test-organization.md", "url": "https://doc.rust-lang.org/book/ch11-03-test-organization.html#summary", "has_code": false, "code_tags": []}} {"id": "book/ch12-00-an-io-project.md#an-io-project-building-a-command-line-program-0", "text": "The Rust Programming Language › An I/O Project: Building a Command Line Program\n\nThis chapter is a recap of the many skills you’ve learned so far and an\nexploration of a few more standard library features. We’ll build a command line\ntool that interacts with file and command line input/output to practice some of\nthe Rust concepts you now have under your belt.\nRust’s speed, safety, single binary output, and cross-platform support make it\nan ideal language for creating command line tools, so for our project, we’ll\nmake our own version of the classic command line search tool `grep`\n(**g**lobally search a **r**egular **e**xpression and **p**rint). In the\nsimplest use case, `grep` searches a specified file for a specified string. To\ndo so, `grep` takes as its arguments a file path and a string. Then, it reads\nthe file, finds lines in that file that contain the string argument, and prints\nthose lines.\nAlong the way, we’ll show how to make our command line tool use the terminal\nfeatures that many other command line tools use. We’ll read the value of an\nenvironment variable to allow the user to configure the behavior of our tool.\nWe’ll also print error messages to the standard error console stream (`stderr`)\ninstead of standard output (`stdout`) so that, for example, the user can\nredirect successful output to a file while still seeing error messages onscreen.\nOne Rust community member, Andrew Gallant, has already created a fully\nfeatured, very fast version of `grep`, called `ripgrep`. By comparison, our\nversion will be fairly simple, but this chapter will give you some of the\nbackground knowledge you need to understand a real-world project such as\n`ripgrep`.\nOur `grep` project will combine a number of concepts you’ve learned so far:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "An I/O Project: Building a Command Line Program", "heading_path": ["An I/O Project: Building a Command Line Program"], "path": "ch12-00-an-io-project.md", "url": "https://doc.rust-lang.org/book/ch12-00-an-io-project.html#an-io-project-building-a-command-line-program", "has_code": false, "code_tags": []}} {"id": "book/ch12-00-an-io-project.md#an-io-project-building-a-command-line-program-1", "text": "The Rust Programming Language › An I/O Project: Building a Command Line Program\n\n- Organizing code (Chapter 7)\n- Using vectors and strings (Chapter 8)\n- Handling errors (Chapter 9)\n- Using traits and lifetimes where appropriate (Chapter 10)\n- Writing tests (Chapter 11)\nWe’ll also briefly introduce closures, iterators, and trait objects, which\nChapter 13 and Chapter 18 will\ncover in detail.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "An I/O Project: Building a Command Line Program", "heading_path": ["An I/O Project: Building a Command Line Program"], "path": "ch12-00-an-io-project.md", "url": "https://doc.rust-lang.org/book/ch12-00-an-io-project.html#an-io-project-building-a-command-line-program", "has_code": false, "code_tags": []}} {"id": "book/ch12-01-accepting-command-line-arguments.md#accepting-command-line-arguments-0", "text": "The Rust Programming Language › Accepting Command Line Arguments\n\nLet’s create a new project with, as always, `cargo new`. We’ll call our project\n`minigrep` to distinguish it from the `grep` tool that you might already have\non your system:\n```console\n$ cargo new minigrep\n Created binary (application) `minigrep` project\n$ cd minigrep\n```\nThe first task is to make `minigrep` accept its two command line arguments: the\nfile path and a string to search for. That is, we want to be able to run our\nprogram with `cargo run`, two hyphens to indicate the following arguments are\nfor our program rather than for `cargo`, a string to search for, and a path to\na file to search in, like so:\n```console\n$ cargo run -- searchstring example-filename.txt\n```\nRight now, the program generated by `cargo new` cannot process arguments we\ngive it. Some existing libraries on crates.io can help\nwith writing a program that accepts command line arguments, but because you’re\njust learning this concept, let’s implement this capability ourselves.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Accepting Command Line Arguments", "heading_path": ["Accepting Command Line Arguments"], "path": "ch12-01-accepting-command-line-arguments.md", "url": "https://doc.rust-lang.org/book/ch12-01-accepting-command-line-arguments.html#accepting-command-line-arguments", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch12-01-accepting-command-line-arguments.md#reading-the-argument-values-1", "text": "The Rust Programming Language › Accepting Command Line Arguments › Reading the Argument Values\n\nTo enable `minigrep` to read the values of command line arguments we pass to\nit, we’ll need the `std::env::args` function provided in Rust’s standard\nlibrary. This function returns an iterator of the command line arguments passed\nto `minigrep`. We’ll cover iterators fully in Chapter 13\n. For now, you only need to know two details about iterators: Iterators\nproduce a series of values, and we can call the `collect` method on an iterator\nto turn it into a collection, such as a vector, which contains all the elements\nthe iterator produces.\nThe code in Listing 12-1 allows your `minigrep` program to read any command\nline arguments passed to it and then collect the values into a vector.\nListing 12-1: Collecting the command line arguments into a vector and printing them (src/main.rs)\n```rust\nuse std::env;\n\nfn main() {\n let args: Vec = env::args().collect();\n dbg!(args);\n}\n```\nFirst, we bring the `std::env` module into scope with a `use` statement so that\nwe can use its `args` function. Notice that the `std::env::args` function is\nnested in two levels of modules. As we discussed in Chapter\n7, in cases where the desired function is\nnested in more than one module, we’ve chosen to bring the parent module into\nscope rather than the function. By doing so, we can easily use other functions\nfrom `std::env`. It’s also less ambiguous than adding `use std::env::args` and\nthen calling the function with just `args`, because `args` might easily be\nmistaken for a function that’s defined in the current module.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Accepting Command Line Arguments", "heading_path": ["Accepting Command Line Arguments", "Reading the Argument Values"], "path": "ch12-01-accepting-command-line-arguments.md", "url": "https://doc.rust-lang.org/book/ch12-01-accepting-command-line-arguments.html#reading-the-argument-values", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch12-01-accepting-command-line-arguments.md#the-args-function-and-invalid-unicode-2", "text": "The Rust Programming Language › Accepting Command Line Arguments › The `args` Function and Invalid Unicode\n\nNote that `std::env::args` will panic if any argument contains invalid\nUnicode. If your program needs to accept arguments containing invalid\nUnicode, use `std::env::args_os` instead. That function returns an iterator\nthat produces `OsString` values instead of `String` values. We’ve chosen to\nuse `std::env::args` here for simplicity because `OsString` values differ per\nplatform and are more complex to work with than `String` values.\nOn the first line of `main`, we call `env::args`, and we immediately use\n`collect` to turn the iterator into a vector containing all the values produced\nby the iterator. We can use the `collect` function to create many kinds of\ncollections, so we explicitly annotate the type of `args` to specify that we\nwant a vector of strings. Although you very rarely need to annotate types in\nRust, `collect` is one function you do often need to annotate because Rust\nisn’t able to infer the kind of collection you want.\nFinally, we print the vector using the debug macro. Let’s try running the code\nfirst with no arguments and then with two arguments:\n```console\n$ cargo run\n Compiling minigrep v0.1.0 (file:///projects/minigrep)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.61s\n Running `target/debug/minigrep`\n[src/main.rs:5:5] args = [\n \"target/debug/minigrep\",\n]\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Accepting Command Line Arguments", "heading_path": ["Accepting Command Line Arguments", "The `args` Function and Invalid Unicode"], "path": "ch12-01-accepting-command-line-arguments.md", "url": "https://doc.rust-lang.org/book/ch12-01-accepting-command-line-arguments.html#the-args-function-and-invalid-unicode", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch12-01-accepting-command-line-arguments.md#the-args-function-and-invalid-unicode-3", "text": "The Rust Programming Language › Accepting Command Line Arguments › The `args` Function and Invalid Unicode\n\n```console\n$ cargo run -- needle haystack\n Compiling minigrep v0.1.0 (file:///projects/minigrep)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.57s\n Running `target/debug/minigrep needle haystack`\n[src/main.rs:5:5] args = [\n \"target/debug/minigrep\",\n \"needle\",\n \"haystack\",\n]\n```\nNotice that the first value in the vector is `\"target/debug/minigrep\"`, which\nis the name of our binary. This matches the behavior of the arguments list in\nC, letting programs use the name by which they were invoked in their execution.\nIt’s often convenient to have access to the program name in case you want to\nprint it in messages or change the behavior of the program based on what\ncommand line alias was used to invoke the program. But for the purposes of this\nchapter, we’ll ignore it and save only the two arguments we need.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Accepting Command Line Arguments", "heading_path": ["Accepting Command Line Arguments", "The `args` Function and Invalid Unicode"], "path": "ch12-01-accepting-command-line-arguments.md", "url": "https://doc.rust-lang.org/book/ch12-01-accepting-command-line-arguments.html#the-args-function-and-invalid-unicode", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch12-01-accepting-command-line-arguments.md#saving-the-argument-values-in-variables-4", "text": "The Rust Programming Language › Accepting Command Line Arguments › Saving the Argument Values in Variables\n\nThe program is currently able to access the values specified as command line\narguments. Now we need to save the values of the two arguments in variables so\nthat we can use the values throughout the rest of the program. We do that in\nListing 12-2.\nListing 12-2: Creating variables to hold the query argument and file path argument (src/main.rs)\n```rust,should_panic,noplayground\nuse std::env;\n\nfn main() {\n let args: Vec = env::args().collect();\n\n let query = &args[1];\n let file_path = &args[2];\n\n println!(\"Searching for {query}\");\n println!(\"In file {file_path}\");\n}\n```\nAs we saw when we printed the vector, the program’s name takes up the first\nvalue in the vector at `args[0]`, so we’re starting arguments at index 1. The\nfirst argument `minigrep` takes is the string we’re searching for, so we put a\nreference to the first argument in the variable `query`. The second argument\nwill be the file path, so we put a reference to the second argument in the\nvariable `file_path`.\nWe temporarily print the values of these variables to prove that the code is\nworking as we intend. Let’s run this program again with the arguments `test`\nand `sample.txt`:\n```console\n$ cargo run -- test sample.txt\n Compiling minigrep v0.1.0 (file:///projects/minigrep)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.0s\n Running `target/debug/minigrep test sample.txt`\nSearching for test\nIn file sample.txt\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Accepting Command Line Arguments", "heading_path": ["Accepting Command Line Arguments", "Saving the Argument Values in Variables"], "path": "ch12-01-accepting-command-line-arguments.md", "url": "https://doc.rust-lang.org/book/ch12-01-accepting-command-line-arguments.html#saving-the-argument-values-in-variables", "has_code": true, "code_tags": ["console", "rust,should_panic,noplayground"]}} {"id": "book/ch12-01-accepting-command-line-arguments.md#saving-the-argument-values-in-variables-5", "text": "The Rust Programming Language › Accepting Command Line Arguments › Saving the Argument Values in Variables\n\nGreat, the program is working! The values of the arguments we need are being\nsaved into the right variables. Later we’ll add some error handling to deal\nwith certain potential erroneous situations, such as when the user provides no\narguments; for now, we’ll ignore that situation and work on adding file-reading\ncapabilities instead.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Accepting Command Line Arguments", "heading_path": ["Accepting Command Line Arguments", "Saving the Argument Values in Variables"], "path": "ch12-01-accepting-command-line-arguments.md", "url": "https://doc.rust-lang.org/book/ch12-01-accepting-command-line-arguments.html#saving-the-argument-values-in-variables", "has_code": false, "code_tags": []}} {"id": "book/ch12-02-reading-a-file.md#reading-a-file-0", "text": "The Rust Programming Language › Reading a File\n\nNow we’ll add functionality to read the file specified in the `file_path`\nargument. First, we need a sample file to test it with: We’ll use a file with a\nsmall amount of text over multiple lines with some repeated words. Listing 12-3\nhas an Emily Dickinson poem that will work well! Create a file called\n_poem.txt_ at the root level of your project, and enter the poem “I’m Nobody!\nWho are you?”\nListing 12-3: A poem by Emily Dickinson makes a good test case. (poem.txt)\n```text\nI'm nobody! Who are you?\nAre you nobody, too?\nThen there's a pair of us - don't tell!\nThey'd banish us, you know.\n\nHow dreary to be somebody!\nHow public, like a frog\nTo tell your name the livelong day\nTo an admiring bog!\n```\nWith the text in place, edit _src/main.rs_ and add code to read the file, as\nshown in Listing 12-4.\nListing 12-4: Reading the contents of the file specified by the second argument (src/main.rs)\n```rust,should_panic,noplayground\nuse std::env;\nuse std::fs;\n\nfn main() {\n // --snip--\n println!(\"In file {file_path}\");\n\n let contents = fs::read_to_string(file_path)\n .expect(\"Should have been able to read the file\");\n\n println!(\"With text:\\n{contents}\");\n}\n```\nFirst, we bring in a relevant part of the standard library with a `use`\nstatement: We need `std::fs` to handle files.\nIn `main`, the new statement `fs::read_to_string` takes the `file_path`, opens\nthat file, and returns a value of type `std::io::Result` that contains\nthe file’s contents.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Reading a File", "heading_path": ["Reading a File"], "path": "ch12-02-reading-a-file.md", "url": "https://doc.rust-lang.org/book/ch12-02-reading-a-file.html#reading-a-file", "has_code": true, "code_tags": ["rust,should_panic,noplayground", "text"]}} {"id": "book/ch12-02-reading-a-file.md#reading-a-file-1", "text": "The Rust Programming Language › Reading a File\n\nAfter that, we again add a temporary `println!` statement that prints the value\nof `contents` after the file is read so that we can check that the program is\nworking so far.\nLet’s run this code with any string as the first command line argument (because\nwe haven’t implemented the searching part yet) and the _poem.txt_ file as the\nsecond argument:\n```console\n$ cargo run -- the poem.txt\n Compiling minigrep v0.1.0 (file:///projects/minigrep)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.0s\n Running `target/debug/minigrep the poem.txt`\nSearching for the\nIn file poem.txt\nWith text:\nI'm nobody! Who are you?\nAre you nobody, too?\nThen there's a pair of us - don't tell!\nThey'd banish us, you know.\n\nHow dreary to be somebody!\nHow public, like a frog\nTo tell your name the livelong day\nTo an admiring bog!\n\n```\nGreat! The code read and then printed the contents of the file. But the code\nhas a few flaws. At the moment, the `main` function has multiple\nresponsibilities: Generally, functions are clearer and easier to maintain if\neach function is responsible for only one idea. The other problem is that we’re\nnot handling errors as well as we could. The program is still small, so these\nflaws aren’t a big problem, but as the program grows, it will be harder to fix\nthem cleanly. It’s a good practice to begin refactoring early on when\ndeveloping a program because it’s much easier to refactor smaller amounts of\ncode. We’ll do that next.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Reading a File", "heading_path": ["Reading a File"], "path": "ch12-02-reading-a-file.md", "url": "https://doc.rust-lang.org/book/ch12-02-reading-a-file.html#reading-a-file", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch12-03-improving-error-handling-and-modularity.md#refactoring-to-improve-modularity-and-error-handling-0", "text": "The Rust Programming Language › Refactoring to Improve Modularity and Error Handling\n\nTo improve our program, we’ll fix four problems that have to do with the\nprogram’s structure and how it’s handling potential errors. First, our `main`\nfunction now performs two tasks: It parses arguments and reads files. As our\nprogram grows, the number of separate tasks the `main` function handles will\nincrease. As a function gains responsibilities, it becomes more difficult to\nreason about, harder to test, and harder to change without breaking one of its\nparts. It’s best to separate functionality so that each function is responsible\nfor one task.\nThis issue also ties into the second problem: Although `query` and `file_path`\nare configuration variables to our program, variables like `contents` are used\nto perform the program’s logic. The longer `main` becomes, the more variables\nwe’ll need to bring into scope; the more variables we have in scope, the harder\nit will be to keep track of the purpose of each. It’s best to group the\nconfiguration variables into one structure to make their purpose clear.\nThe third problem is that we’ve used `expect` to print an error message when\nreading the file fails, but the error message just prints `Should have been\nable to read the file`. Reading a file can fail in a number of ways: For\nexample, the file could be missing, or we might not have permission to open it.\nRight now, regardless of the situation, we’d print the same error message for\neverything, which wouldn’t give the user any information!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Refactoring to Improve Modularity and Error Handling", "heading_path": ["Refactoring to Improve Modularity and Error Handling"], "path": "ch12-03-improving-error-handling-and-modularity.md", "url": "https://doc.rust-lang.org/book/ch12-03-improving-error-handling-and-modularity.html#refactoring-to-improve-modularity-and-error-handling", "has_code": false, "code_tags": []}} {"id": "book/ch12-03-improving-error-handling-and-modularity.md#refactoring-to-improve-modularity-and-error-handling-1", "text": "The Rust Programming Language › Refactoring to Improve Modularity and Error Handling\n\nFourth, we use `expect` to handle an error, and if the user runs our program\nwithout specifying enough arguments, they’ll get an `index out of bounds` error\nfrom Rust that doesn’t clearly explain the problem. It would be best if all the\nerror-handling code were in one place so that future maintainers had only one\nplace to consult the code if the error-handling logic needed to change. Having\nall the error-handling code in one place will also ensure that we’re printing\nmessages that will be meaningful to our end users.\nLet’s address these four problems by refactoring our project.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Refactoring to Improve Modularity and Error Handling", "heading_path": ["Refactoring to Improve Modularity and Error Handling"], "path": "ch12-03-improving-error-handling-and-modularity.md", "url": "https://doc.rust-lang.org/book/ch12-03-improving-error-handling-and-modularity.html#refactoring-to-improve-modularity-and-error-handling", "has_code": false, "code_tags": []}} {"id": "book/ch12-03-improving-error-handling-and-modularity.md#extracting-the-argument-parser-2", "text": "The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › Separating Concerns in Binary Projects › Extracting the Argument Parser\n\nThe organizational problem of allocating responsibility for multiple tasks to\nthe `main` function is common to many binary projects. As a result, many Rust\nprogrammers find it useful to split up the separate concerns of a binary\nprogram when the `main` function starts getting large. This process has the\nfollowing steps:\n- Split your program into a _main.rs_ file and a _lib.rs_ file and move your\n program’s logic to _lib.rs_.\n- As long as your command line parsing logic is small, it can remain in\n the `main` function.\n- When the command line parsing logic starts getting complicated, extract it\n from the `main` function into other functions or types.\nThe responsibilities that remain in the `main` function after this process\nshould be limited to the following:\n- Calling the command line parsing logic with the argument values\n- Setting up any other configuration\n- Calling a `run` function in _lib.rs_\n- Handling the error if `run` returns an error\nThis pattern is about separating concerns: _main.rs_ handles running the\nprogram and _lib.rs_ handles all the logic of the task at hand. Because you\ncan’t test the `main` function directly, this structure lets you test all of\nyour program’s logic by moving it out of the `main` function. The code that\nremains in the `main` function will be small enough to verify its correctness\nby reading it. Let’s rework our program by following this process.\nWe’ll extract the functionality for parsing arguments into a function that\n`main` will call. Listing 12-5 shows the new start of the `main` function that\ncalls a new function `parse_config`, which we’ll define in _src/main.rs_.\nListing 12-5: Extracting a `parse_config` function from `main` (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Refactoring to Improve Modularity and Error Handling", "heading_path": ["Refactoring to Improve Modularity and Error Handling", "Separating Concerns in Binary Projects", "Extracting the Argument Parser"], "path": "ch12-03-improving-error-handling-and-modularity.md", "url": "https://doc.rust-lang.org/book/ch12-03-improving-error-handling-and-modularity.html#extracting-the-argument-parser", "has_code": false, "code_tags": []}} {"id": "book/ch12-03-improving-error-handling-and-modularity.md#grouping-configuration-values-3", "text": "The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › Separating Concerns in Binary Projects › Grouping Configuration Values\n\n```rust,ignore\nfn main() {\n let args: Vec = env::args().collect();\n\n let (query, file_path) = parse_config(&args);\n\n // --snip--\n}\n\nfn parse_config(args: &[String]) -> (&str, &str) {\n let query = &args[1];\n let file_path = &args[2];\n\n (query, file_path)\n}\n```\nWe’re still collecting the command line arguments into a vector, but instead of\nassigning the argument value at index 1 to the variable `query` and the\nargument value at index 2 to the variable `file_path` within the `main`\nfunction, we pass the whole vector to the `parse_config` function. The\n`parse_config` function then holds the logic that determines which argument\ngoes in which variable and passes the values back to `main`. We still create\nthe `query` and `file_path` variables in `main`, but `main` no longer has the\nresponsibility of determining how the command line arguments and variables\ncorrespond.\nThis rework may seem like overkill for our small program, but we’re refactoring\nin small, incremental steps. After making this change, run the program again to\nverify that the argument parsing still works. It’s good to check your progress\noften, to help identify the cause of problems when they occur.\nWe can take another small step to improve the `parse_config` function further.\nAt the moment, we’re returning a tuple, but then we immediately break that\ntuple into individual parts again. This is a sign that perhaps we don’t have\nthe right abstraction yet.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Refactoring to Improve Modularity and Error Handling", "heading_path": ["Refactoring to Improve Modularity and Error Handling", "Separating Concerns in Binary Projects", "Grouping Configuration Values"], "path": "ch12-03-improving-error-handling-and-modularity.md", "url": "https://doc.rust-lang.org/book/ch12-03-improving-error-handling-and-modularity.html#grouping-configuration-values", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch12-03-improving-error-handling-and-modularity.md#grouping-configuration-values-4", "text": "The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › Separating Concerns in Binary Projects › Grouping Configuration Values\n\nAnother indicator that shows there’s room for improvement is the `config` part\nof `parse_config`, which implies that the two values we return are related and\nare both part of one configuration value. We’re not currently conveying this\nmeaning in the structure of the data other than by grouping the two values into\na tuple; we’ll instead put the two values into one struct and give each of the\nstruct fields a meaningful name. Doing so will make it easier for future\nmaintainers of this code to understand how the different values relate to each\nother and what their purpose is.\nListing 12-6 shows the improvements to the `parse_config` function.\nListing 12-6: Refactoring `parse_config` to return an instance of a `Config` struct (src/main.rs)\n```rust,should_panic,noplayground\nfn main() {\n let args: Vec = env::args().collect();\n\n let config = parse_config(&args);\n\n println!(\"Searching for {}\", config.query);\n println!(\"In file {}\", config.file_path);\n\n let contents = fs::read_to_string(config.file_path)\n .expect(\"Should have been able to read the file\");\n\n // --snip--\n}\n\nstruct Config {\n query: String,\n file_path: String,\n}\n\nfn parse_config(args: &[String]) -> Config {\n let query = args[1].clone();\n let file_path = args[2].clone();\n\n Config { query, file_path }\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Refactoring to Improve Modularity and Error Handling", "heading_path": ["Refactoring to Improve Modularity and Error Handling", "Separating Concerns in Binary Projects", "Grouping Configuration Values"], "path": "ch12-03-improving-error-handling-and-modularity.md", "url": "https://doc.rust-lang.org/book/ch12-03-improving-error-handling-and-modularity.html#grouping-configuration-values", "has_code": true, "code_tags": ["rust,should_panic,noplayground"]}} {"id": "book/ch12-03-improving-error-handling-and-modularity.md#grouping-configuration-values-5", "text": "The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › Separating Concerns in Binary Projects › Grouping Configuration Values\n\nWe’ve added a struct named `Config` defined to have fields named `query` and\n`file_path`. The signature of `parse_config` now indicates that it returns a\n`Config` value. In the body of `parse_config`, where we used to return\nstring slices that reference `String` values in `args`, we now define `Config`\nto contain owned `String` values. The `args` variable in `main` is the owner of\nthe argument values and is only letting the `parse_config` function borrow\nthem, which means we’d violate Rust’s borrowing rules if `Config` tried to take\nownership of the values in `args`.\nThere are a number of ways we could manage the `String` data; the easiest,\nthough somewhat inefficient, route is to call the `clone` method on the values.\nThis will make a full copy of the data for the `Config` instance to own, which\ntakes more time and memory than storing a reference to the string data.\nHowever, cloning the data also makes our code very straightforward because we\ndon’t have to manage the lifetimes of the references; in this circumstance,\ngiving up a little performance to gain simplicity is a worthwhile trade-off.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Refactoring to Improve Modularity and Error Handling", "heading_path": ["Refactoring to Improve Modularity and Error Handling", "Separating Concerns in Binary Projects", "Grouping Configuration Values"], "path": "ch12-03-improving-error-handling-and-modularity.md", "url": "https://doc.rust-lang.org/book/ch12-03-improving-error-handling-and-modularity.html#grouping-configuration-values", "has_code": false, "code_tags": []}} {"id": "book/ch12-03-improving-error-handling-and-modularity.md#creating-a-constructor-for-config-6", "text": "The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › The Trade-Offs of Using `clone` › Creating a Constructor for `Config`\n\nThere’s a tendency among many Rustaceans to avoid using `clone` to fix\nownership problems because of its runtime cost. In\nChapter 13, you’ll learn how to use more efficient\nmethods in this type of situation. But for now, it’s okay to copy a few\nstrings to continue making progress because you’ll make these copies only\nonce and your file path and query string are very small. It’s better to have\na working program that’s a bit inefficient than to try to hyperoptimize code\non your first pass. As you become more experienced with Rust, it’ll be\neasier to start with the most efficient solution, but for now, it’s\nperfectly acceptable to call `clone`.\nWe’ve updated `main` so that it places the instance of `Config` returned by\n`parse_config` into a variable named `config`, and we updated the code that\npreviously used the separate `query` and `file_path` variables so that it now\nuses the fields on the `Config` struct instead.\nNow our code more clearly conveys that `query` and `file_path` are related and\nthat their purpose is to configure how the program will work. Any code that\nuses these values knows to find them in the `config` instance in the fields\nnamed for their purpose.\nSo far, we’ve extracted the logic responsible for parsing the command line\narguments from `main` and placed it in the `parse_config` function. Doing so\nhelped us see that the `query` and `file_path` values were related, and that\nrelationship should be conveyed in our code. We then added a `Config` struct to\nname the related purpose of `query` and `file_path` and to be able to return the\nvalues’ names as struct field names from the `parse_config` function.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Refactoring to Improve Modularity and Error Handling", "heading_path": ["Refactoring to Improve Modularity and Error Handling", "The Trade-Offs of Using `clone`", "Creating a Constructor for `Config`"], "path": "ch12-03-improving-error-handling-and-modularity.md", "url": "https://doc.rust-lang.org/book/ch12-03-improving-error-handling-and-modularity.html#creating-a-constructor-for-config", "has_code": false, "code_tags": []}} {"id": "book/ch12-03-improving-error-handling-and-modularity.md#creating-a-constructor-for-config-7", "text": "The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › The Trade-Offs of Using `clone` › Creating a Constructor for `Config`\n\nSo, now that the purpose of the `parse_config` function is to create a `Config`\ninstance, we can change `parse_config` from a plain function to a function\nnamed `new` that is associated with the `Config` struct. Making this change\nwill make the code more idiomatic. We can create instances of types in the\nstandard library, such as `String`, by calling `String::new`. Similarly, by\nchanging `parse_config` into a `new` function associated with `Config`, we’ll\nbe able to create instances of `Config` by calling `Config::new`. Listing 12-7\nshows the changes we need to make.\nListing 12-7: Changing `parse_config` into `Config::new` (src/main.rs)\n```rust,should_panic,noplayground\nfn main() {\n let args: Vec = env::args().collect();\n\n let config = Config::new(&args);\n\n // --snip--\n}\n\n// --snip--\n\nimpl Config {\n fn new(args: &[String]) -> Config {\n let query = args[1].clone();\n let file_path = args[2].clone();\n\n Config { query, file_path }\n }\n}\n```\nWe’ve updated `main` where we were calling `parse_config` to instead call\n`Config::new`. We’ve changed the name of `parse_config` to `new` and moved it\nwithin an `impl` block, which associates the `new` function with `Config`. Try\ncompiling this code again to make sure it works.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Refactoring to Improve Modularity and Error Handling", "heading_path": ["Refactoring to Improve Modularity and Error Handling", "The Trade-Offs of Using `clone`", "Creating a Constructor for `Config`"], "path": "ch12-03-improving-error-handling-and-modularity.md", "url": "https://doc.rust-lang.org/book/ch12-03-improving-error-handling-and-modularity.html#creating-a-constructor-for-config", "has_code": true, "code_tags": ["rust,should_panic,noplayground"]}} {"id": "book/ch12-03-improving-error-handling-and-modularity.md#improving-the-error-message-8", "text": "The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › Fixing the Error Handling › Improving the Error Message\n\nNow we’ll work on fixing our error handling. Recall that attempting to access\nthe values in the `args` vector at index 1 or index 2 will cause the program to\npanic if the vector contains fewer than three items. Try running the program\nwithout any arguments; it will look like this:\n```console\n$ cargo run\n Compiling minigrep v0.1.0 (file:///projects/minigrep)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.0s\n Running `target/debug/minigrep`\n\nthread 'main' (6023615) panicked at src/main.rs:27:21:\nindex out of bounds: the len is 1 but the index is 1\nnote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n```\nThe line `index out of bounds: the len is 1 but the index is 1` is an error\nmessage intended for programmers. It won’t help our end users understand what\nthey should do instead. Let’s fix that now.\nIn Listing 12-8, we add a check in the `new` function that will verify that the\nslice is long enough before accessing index 1 and index 2. If the slice isn’t\nlong enough, the program panics and displays a better error message.\nListing 12-8: Adding a check for the number of arguments (src/main.rs)\n```rust,ignore\n // --snip--\n fn new(args: &[String]) -> Config {\n if args.len() < 3 {\n panic!(\"not enough arguments\");\n }\n // --snip--\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Refactoring to Improve Modularity and Error Handling", "heading_path": ["Refactoring to Improve Modularity and Error Handling", "Fixing the Error Handling", "Improving the Error Message"], "path": "ch12-03-improving-error-handling-and-modularity.md", "url": "https://doc.rust-lang.org/book/ch12-03-improving-error-handling-and-modularity.html#improving-the-error-message", "has_code": true, "code_tags": ["console", "rust,ignore"]}} {"id": "book/ch12-03-improving-error-handling-and-modularity.md#returning-a-result-instead-of-calling-panic-9", "text": "The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › Fixing the Error Handling › Returning a `Result` Instead of Calling `panic!`\n\nThis code is similar to the `Guess::new` function we wrote in Listing\n9-13, where we called `panic!` when the\n`value` argument was out of the range of valid values. Instead of checking for\na range of values here, we’re checking that the length of `args` is at least\n`3` and the rest of the function can operate under the assumption that this\ncondition has been met. If `args` has fewer than three items, this condition\nwill be `true`, and we call the `panic!` macro to end the program immediately.\nWith these extra few lines of code in `new`, let’s run the program without any\narguments again to see what the error looks like now:\n```console\n$ cargo run\n Compiling minigrep v0.1.0 (file:///projects/minigrep)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.0s\n Running `target/debug/minigrep`\n\nthread 'main' (6023776) panicked at src/main.rs:26:13:\nnot enough arguments\nnote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n```\nThis output is better: We now have a reasonable error message. However, we also\nhave extraneous information we don’t want to give to our users. Perhaps the\ntechnique we used in Listing 9-13 isn’t the best one to use here: A call to\n`panic!` is more appropriate for a programming problem than a usage problem,\nas discussed in Chapter 9. Instead,\nwe’ll use the other technique you learned about in Chapter 9—returning a\n`Result` that indicates either success or an error.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Refactoring to Improve Modularity and Error Handling", "heading_path": ["Refactoring to Improve Modularity and Error Handling", "Fixing the Error Handling", "Returning a `Result` Instead of Calling `panic!`"], "path": "ch12-03-improving-error-handling-and-modularity.md", "url": "https://doc.rust-lang.org/book/ch12-03-improving-error-handling-and-modularity.html#returning-a-result-instead-of-calling-panic", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch12-03-improving-error-handling-and-modularity.md#returning-a-result-instead-of-calling-panic-10", "text": "The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › Fixing the Error Handling › Returning a `Result` Instead of Calling `panic!`\n\nWe can instead return a `Result` value that will contain a `Config` instance in\nthe successful case and will describe the problem in the error case. We’re also\ngoing to change the function name from `new` to `build` because many\nprogrammers expect `new` functions to never fail. When `Config::build` is\ncommunicating to `main`, we can use the `Result` type to signal there was a\nproblem. Then, we can change `main` to convert an `Err` variant into a more\npractical error for our users without the surrounding text about `thread\n'main'` and `RUST_BACKTRACE` that a call to `panic!` causes.\nListing 12-9 shows the changes we need to make to the return value of the\nfunction we’re now calling `Config::build` and the body of the function needed\nto return a `Result`. Note that this won’t compile until we update `main` as\nwell, which we’ll do in the next listing.\nListing 12-9: Returning a `Result` from `Config::build` (src/main.rs)\n```rust,ignore,does_not_compile\nimpl Config {\n fn build(args: &[String]) -> Result {\n if args.len() < 3 {\n return Err(\"not enough arguments\");\n }\n\n let query = args[1].clone();\n let file_path = args[2].clone();\n\n Ok(Config { query, file_path })\n }\n}\n```\nOur `build` function returns a `Result` with a `Config` instance in the success\ncase and a string literal in the error case. Our error values will always be\nstring literals that have the `'static` lifetime.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Refactoring to Improve Modularity and Error Handling", "heading_path": ["Refactoring to Improve Modularity and Error Handling", "Fixing the Error Handling", "Returning a `Result` Instead of Calling `panic!`"], "path": "ch12-03-improving-error-handling-and-modularity.md", "url": "https://doc.rust-lang.org/book/ch12-03-improving-error-handling-and-modularity.html#returning-a-result-instead-of-calling-panic", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch12-03-improving-error-handling-and-modularity.md#calling-configbuild-and-handling-errors-11", "text": "The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › Fixing the Error Handling › Calling `Config::build` and Handling Errors\n\nWe’ve made two changes in the body of the function: Instead of calling `panic!`\nwhen the user doesn’t pass enough arguments, we now return an `Err` value, and\nwe’ve wrapped the `Config` return value in an `Ok`. These changes make the\nfunction conform to its new type signature.\nReturning an `Err` value from `Config::build` allows the `main` function to\nhandle the `Result` value returned from the `build` function and exit the\nprocess more cleanly in the error case.\nTo handle the error case and print a user-friendly message, we need to update\n`main` to handle the `Result` being returned by `Config::build`, as shown in\nListing 12-10. We’ll also take the responsibility of exiting the command line\ntool with a nonzero error code away from `panic!` and instead implement it by\nhand. A nonzero exit status is a convention to signal to the process that\ncalled our program that the program exited with an error state.\nListing 12-10: Exiting with an error code if building a `Config` fails (src/main.rs)\n```rust,ignore\nuse std::process;\n\nfn main() {\n let args: Vec = env::args().collect();\n\n let config = Config::build(&args).unwrap_or_else(|err| {\n println!(\"Problem parsing arguments: {err}\");\n process::exit(1);\n });\n\n // --snip--\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Refactoring to Improve Modularity and Error Handling", "heading_path": ["Refactoring to Improve Modularity and Error Handling", "Fixing the Error Handling", "Calling `Config::build` and Handling Errors"], "path": "ch12-03-improving-error-handling-and-modularity.md", "url": "https://doc.rust-lang.org/book/ch12-03-improving-error-handling-and-modularity.html#calling-configbuild-and-handling-errors", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch12-03-improving-error-handling-and-modularity.md#calling-configbuild-and-handling-errors-12", "text": "The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › Fixing the Error Handling › Calling `Config::build` and Handling Errors\n\nIn this listing, we’ve used a method we haven’t covered in detail yet:\n`unwrap_or_else`, which is defined on `Result` by the standard library.\nUsing `unwrap_or_else` allows us to define some custom, non-`panic!` error\nhandling. If the `Result` is an `Ok` value, this method’s behavior is similar\nto `unwrap`: It returns the inner value that `Ok` is wrapping. However, if the\nvalue is an `Err` value, this method calls the code in the closure, which is\nan anonymous function we define and pass as an argument to `unwrap_or_else`.\nWe’ll cover closures in more detail in Chapter 13. For\nnow, you just need to know that `unwrap_or_else` will pass the inner value of\nthe `Err`, which in this case is the static string `\"not enough arguments\"`\nthat we added in Listing 12-9, to our closure in the argument `err` that\nappears between the vertical pipes. The code in the closure can then use the\n`err` value when it runs.\nWe’ve added a new `use` line to bring `process` from the standard library into\nscope. The code in the closure that will be run in the error case is only two\nlines: We print the `err` value and then call `process::exit`. The\n`process::exit` function will stop the program immediately and return the\nnumber that was passed as the exit status code. This is similar to the\n`panic!`-based handling we used in Listing 12-8, but we no longer get all the\nextra output. Let’s try it:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Refactoring to Improve Modularity and Error Handling", "heading_path": ["Refactoring to Improve Modularity and Error Handling", "Fixing the Error Handling", "Calling `Config::build` and Handling Errors"], "path": "ch12-03-improving-error-handling-and-modularity.md", "url": "https://doc.rust-lang.org/book/ch12-03-improving-error-handling-and-modularity.html#calling-configbuild-and-handling-errors", "has_code": false, "code_tags": []}} {"id": "book/ch12-03-improving-error-handling-and-modularity.md#calling-configbuild-and-handling-errors-13", "text": "The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › Fixing the Error Handling › Calling `Config::build` and Handling Errors\n\n```console\n$ cargo run\n Compiling minigrep v0.1.0 (file:///projects/minigrep)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.48s\n Running `target/debug/minigrep`\nProblem parsing arguments: not enough arguments\n```\nGreat! This output is much friendlier for our users.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Refactoring to Improve Modularity and Error Handling", "heading_path": ["Refactoring to Improve Modularity and Error Handling", "Fixing the Error Handling", "Calling `Config::build` and Handling Errors"], "path": "ch12-03-improving-error-handling-and-modularity.md", "url": "https://doc.rust-lang.org/book/ch12-03-improving-error-handling-and-modularity.html#calling-configbuild-and-handling-errors", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch12-03-improving-error-handling-and-modularity.md#returning-errors-from-run-14", "text": "The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › Extracting Logic from `main` › Returning Errors from `run`\n\nNow that we’ve finished refactoring the configuration parsing, let’s turn to\nthe program’s logic. As we stated in “Separating Concerns in Binary\nProjects”, we’ll\nextract a function named `run` that will hold all the logic currently in the\n`main` function that isn’t involved with setting up configuration or handling\nerrors. When we’re done, the `main` function will be concise and easy to verify\nby inspection, and we’ll be able to write tests for all the other logic.\nListing 12-11 shows the small, incremental improvement of extracting a `run`\nfunction.\nListing 12-11: Extracting a `run` function containing the rest of the program logic (src/main.rs)\n```rust,ignore\nfn main() {\n // --snip--\n\n println!(\"Searching for {}\", config.query);\n println!(\"In file {}\", config.file_path);\n\n run(config);\n}\n\nfn run(config: Config) {\n let contents = fs::read_to_string(config.file_path)\n .expect(\"Should have been able to read the file\");\n\n println!(\"With text:\\n{contents}\");\n}\n\n// --snip--\n```\nThe `run` function now contains all the remaining logic from `main`, starting\nfrom reading the file. The `run` function takes the `Config` instance as an\nargument.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Refactoring to Improve Modularity and Error Handling", "heading_path": ["Refactoring to Improve Modularity and Error Handling", "Extracting Logic from `main`", "Returning Errors from `run`"], "path": "ch12-03-improving-error-handling-and-modularity.md", "url": "https://doc.rust-lang.org/book/ch12-03-improving-error-handling-and-modularity.html#returning-errors-from-run", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch12-03-improving-error-handling-and-modularity.md#returning-errors-from-run-15", "text": "The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › Extracting Logic from `main` › Returning Errors from `run`\n\nWith the remaining program logic separated into the `run` function, we can\nimprove the error handling, as we did with `Config::build` in Listing 12-9.\nInstead of allowing the program to panic by calling `expect`, the `run`\nfunction will return a `Result` when something goes wrong. This will let\nus further consolidate the logic around handling errors into `main` in a\nuser-friendly way. Listing 12-12 shows the changes we need to make to the\nsignature and body of `run`.\nListing 12-12: Changing the `run` function to return `Result` (src/main.rs)\n```rust,ignore\nuse std::error::Error;\n\n// --snip--\n\nfn run(config: Config) -> Result<(), Box> {\n let contents = fs::read_to_string(config.file_path)?;\n\n println!(\"With text:\\n{contents}\");\n\n Ok(())\n}\n```\nWe’ve made three significant changes here. First, we changed the return type of\nthe `run` function to `Result<(), Box>`. This function previously\nreturned the unit type, `()`, and we keep that as the value returned in the\n`Ok` case.\nFor the error type, we used the trait object `Box` (and we brought\n`std::error::Error` into scope with a `use` statement at the top). We’ll cover\ntrait objects in Chapter 18. For now, just know that\n`Box` means the function will return a type that implements the\n`Error` trait, but we don’t have to specify what particular type the return\nvalue will be. This gives us flexibility to return error values that may be of\ndifferent types in different error cases. The `dyn` keyword is short for\n_dynamic_.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Refactoring to Improve Modularity and Error Handling", "heading_path": ["Refactoring to Improve Modularity and Error Handling", "Extracting Logic from `main`", "Returning Errors from `run`"], "path": "ch12-03-improving-error-handling-and-modularity.md", "url": "https://doc.rust-lang.org/book/ch12-03-improving-error-handling-and-modularity.html#returning-errors-from-run", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch12-03-improving-error-handling-and-modularity.md#returning-errors-from-run-16", "text": "The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › Extracting Logic from `main` › Returning Errors from `run`\n\nSecond, we’ve removed the call to `expect` in favor of the `?` operator, as we\ntalked about in Chapter 9. Rather than\n`panic!` on an error, `?` will return the error value from the current function\nfor the caller to handle.\nThird, the `run` function now returns an `Ok` value in the success case.\nWe’ve declared the `run` function’s success type as `()` in the signature,\nwhich means we need to wrap the unit type value in the `Ok` value. This\n`Ok(())` syntax might look a bit strange at first. But using `()` like this is\nthe idiomatic way to indicate that we’re calling `run` for its side effects\nonly; it doesn’t return a value we need.\nWhen you run this code, it will compile but will display a warning:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Refactoring to Improve Modularity and Error Handling", "heading_path": ["Refactoring to Improve Modularity and Error Handling", "Extracting Logic from `main`", "Returning Errors from `run`"], "path": "ch12-03-improving-error-handling-and-modularity.md", "url": "https://doc.rust-lang.org/book/ch12-03-improving-error-handling-and-modularity.html#returning-errors-from-run", "has_code": false, "code_tags": []}} {"id": "book/ch12-03-improving-error-handling-and-modularity.md#handling-errors-returned-from-run-in-main-17", "text": "The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › Extracting Logic from `main` › Handling Errors Returned from `run` in `main`\n\n```console\n$ cargo run -- the poem.txt\n Compiling minigrep v0.1.0 (file:///projects/minigrep)\nwarning: unused `Result` that must be used\n --> src/main.rs:19:5\n |\n19 | run(config);\n | ^^^^^^^^^^^\n |\n = note: this `Result` may be an `Err` variant, which should be handled\n = note: `#[warn(unused_must_use)]` (part of `#[warn(unused)]`) on by default\nhelp: use `let _ = ...` to ignore the resulting value\n |\n19 | let _ = run(config);\n | +++++++\n\nwarning: `minigrep` (bin \"minigrep\") generated 1 warning\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.71s\n Running `target/debug/minigrep the poem.txt`\nSearching for the\nIn file poem.txt\nWith text:\nI'm nobody! Who are you?\nAre you nobody, too?\nThen there's a pair of us - don't tell!\nThey'd banish us, you know.\n\nHow dreary to be somebody!\nHow public, like a frog\nTo tell your name the livelong day\nTo an admiring bog!\n\n```\nRust tells us that our code ignored the `Result` value and the `Result` value\nmight indicate that an error occurred. But we’re not checking to see whether or\nnot there was an error, and the compiler reminds us that we probably meant to\nhave some error-handling code here! Let’s rectify that problem now.\nWe’ll check for errors and handle them using a technique similar to one we used\nwith `Config::build` in Listing 12-10, but with a slight difference:\nFilename: src/main.rs", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Refactoring to Improve Modularity and Error Handling", "heading_path": ["Refactoring to Improve Modularity and Error Handling", "Extracting Logic from `main`", "Handling Errors Returned from `run` in `main`"], "path": "ch12-03-improving-error-handling-and-modularity.md", "url": "https://doc.rust-lang.org/book/ch12-03-improving-error-handling-and-modularity.html#handling-errors-returned-from-run-in-main", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch12-03-improving-error-handling-and-modularity.md#handling-errors-returned-from-run-in-main-18", "text": "The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › Extracting Logic from `main` › Handling Errors Returned from `run` in `main`\n\n```rust,ignore\nfn main() {\n // --snip--\n\n println!(\"Searching for {}\", config.query);\n println!(\"In file {}\", config.file_path);\n\n if let Err(e) = run(config) {\n println!(\"Application error: {e}\");\n process::exit(1);\n }\n}\n```\nWe use `if let` rather than `unwrap_or_else` to check whether `run` returns an\n`Err` value and to call `process::exit(1)` if it does. The `run` function\ndoesn’t return a value that we want to `unwrap` in the same way that\n`Config::build` returns the `Config` instance. Because `run` returns `()` in\nthe success case, we only care about detecting an error, so we don’t need\n`unwrap_or_else` to return the unwrapped value, which would only be `()`.\nThe bodies of the `if let` and the `unwrap_or_else` functions are the same in\nboth cases: We print the error and exit.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Refactoring to Improve Modularity and Error Handling", "heading_path": ["Refactoring to Improve Modularity and Error Handling", "Extracting Logic from `main`", "Handling Errors Returned from `run` in `main`"], "path": "ch12-03-improving-error-handling-and-modularity.md", "url": "https://doc.rust-lang.org/book/ch12-03-improving-error-handling-and-modularity.html#handling-errors-returned-from-run-in-main", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch12-03-improving-error-handling-and-modularity.md#splitting-code-into-a-library-crate-19", "text": "The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › Splitting Code into a Library Crate\n\nOur `minigrep` project is looking good so far! Now we’ll split the\n_src/main.rs_ file and put some code into the _src/lib.rs_ file. That way, we\ncan test the code and have a _src/main.rs_ file with fewer responsibilities.\nLet’s define the code responsible for searching text in _src/lib.rs_ rather\nthan in _src/main.rs_, which will let us (or anyone else using our\n`minigrep` library) call the searching function from more contexts than our\n`minigrep` binary.\nFirst, let’s define the `search` function signature in _src/lib.rs_ as shown in\nListing 12-13, with a body that calls the `unimplemented!` macro. We’ll explain\nthe signature in more detail when we fill in the implementation.\nListing 12-13: Defining the `search` function in *src/lib.rs* (src/lib.rs)\n```rust,ignore,does_not_compile\npub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {\n unimplemented!();\n}\n```\nWe’ve used the `pub` keyword on the function definition to designate `search`\nas part of our library crate’s public API. We now have a library crate that we\ncan use from our binary crate and that we can test!\nNow we need to bring the code defined in _src/lib.rs_ into the scope of the\nbinary crate in _src/main.rs_ and call it, as shown in Listing 12-14.\nListing 12-14: Using the `minigrep` library crate’s `search` function in *src/main.rs* (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Refactoring to Improve Modularity and Error Handling", "heading_path": ["Refactoring to Improve Modularity and Error Handling", "Splitting Code into a Library Crate"], "path": "ch12-03-improving-error-handling-and-modularity.md", "url": "https://doc.rust-lang.org/book/ch12-03-improving-error-handling-and-modularity.html#splitting-code-into-a-library-crate", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch12-03-improving-error-handling-and-modularity.md#splitting-code-into-a-library-crate-20", "text": "The Rust Programming Language › Refactoring to Improve Modularity and Error Handling › Splitting Code into a Library Crate\n\n```rust,ignore\n// --snip--\nuse minigrep::search;\n\nfn main() {\n // --snip--\n}\n\n// --snip--\n\nfn run(config: Config) -> Result<(), Box> {\n let contents = fs::read_to_string(config.file_path)?;\n\n for line in search(&config.query, &contents) {\n println!(\"{line}\");\n }\n\n Ok(())\n}\n```\nWe add a `use minigrep::search` line to bring the `search` function from\nthe library crate into the binary crate’s scope. Then, in the `run` function,\nrather than printing out the contents of the file, we call the `search`\nfunction and pass the `config.query` value and `contents` as arguments. Then,\n`run` will use a `for` loop to print each line returned from `search` that\nmatched the query. This is also a good time to remove the `println!` calls in\nthe `main` function that displayed the query and the file path so that our\nprogram only prints the search results (if no errors occur).\nNote that the search function will be collecting all the results into a vector\nit returns before any printing happens. This implementation could be slow to\ndisplay results when searching large files, because results aren’t printed as\nthey’re found; we’ll discuss a possible way to fix this using iterators in\nChapter 13.\nWhew! That was a lot of work, but we’ve set ourselves up for success in the\nfuture. Now it’s much easier to handle errors, and we’ve made the code more\nmodular. Almost all of our work will be done in _src/lib.rs_ from here on out.\nLet’s take advantage of this newfound modularity by doing something that would\nhave been difficult with the old code but is easy with the new code: We’ll\nwrite some tests!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Refactoring to Improve Modularity and Error Handling", "heading_path": ["Refactoring to Improve Modularity and Error Handling", "Splitting Code into a Library Crate"], "path": "ch12-03-improving-error-handling-and-modularity.md", "url": "https://doc.rust-lang.org/book/ch12-03-improving-error-handling-and-modularity.html#splitting-code-into-a-library-crate", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch12-04-testing-the-librarys-functionality.md#adding-functionality-with-test-driven-development-0", "text": "The Rust Programming Language › Adding Functionality with Test-Driven Development\n\nNow that we have the search logic in _src/lib.rs_ separate from the `main`\nfunction, it’s much easier to write tests for the core functionality of our\ncode. We can call functions directly with various arguments and check return\nvalues without having to call our binary from the command line.\nIn this section, we’ll add the searching logic to the `minigrep` program using\nthe test-driven development (TDD) process with the following steps:\n1. Write a test that fails and run it to make sure it fails for the reason you\n expect.\n2. Write or modify just enough code to make the new test pass.\n3. Refactor the code you just added or changed and make sure the tests continue\n to pass.\n4. Repeat from step 1!\nThough it’s just one of many ways to write software, TDD can help drive code\ndesign. Writing the test before you write the code that makes the test pass\nhelps maintain high test coverage throughout the process.\nWe’ll test-drive the implementation of the functionality that will actually do\nthe searching for the query string in the file contents and produce a list of\nlines that match the query. We’ll add this functionality in a function called\n`search`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Adding Functionality with Test Driven Development", "heading_path": ["Adding Functionality with Test-Driven Development"], "path": "ch12-04-testing-the-librarys-functionality.md", "url": "https://doc.rust-lang.org/book/ch12-04-testing-the-librarys-functionality.html#adding-functionality-with-test-driven-development", "has_code": false, "code_tags": []}} {"id": "book/ch12-04-testing-the-librarys-functionality.md#writing-a-failing-test-1", "text": "The Rust Programming Language › Adding Functionality with Test-Driven Development › Writing a Failing Test\n\nIn _src/lib.rs_, we’ll add a `tests` module with a test function, as we did in\nChapter 11. The test function specifies the\nbehavior we want the `search` function to have: It will take a query and the\ntext to search, and it will return only the lines from the text that contain\nthe query. Listing 12-15 shows this test.\nListing 12-15: Creating a failing test for the `search` function for the functionality we wish we had (src/lib.rs)\n```rust,ignore,does_not_compile\n// --snip--\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn one_result() {\n let query = \"duct\";\n let contents = \"\\\nRust:\nsafe, fast, productive.\nPick three.\";\n\n assert_eq!(vec![\"safe, fast, productive.\"], search(query, contents));\n }\n}\n```\nThis test searches for the string `\"duct\"`. The text we’re searching is three\nlines, only one of which contains `\"duct\"` (note that the backslash after the\nopening double quote tells Rust not to put a newline character at the beginning\nof the contents of this string literal). We assert that the value returned from\nthe `search` function contains only the line we expect.\nIf we run this test, it will currently fail because the `unimplemented!` macro\npanics with the message “not implemented”. In accordance with TDD principles,\nwe’ll take a small step of adding just enough code to get the test to not panic\nwhen calling the function by defining the `search` function to always return an\nempty vector, as shown in Listing 12-16. Then, the test should compile and fail\nbecause an empty vector doesn’t match a vector containing the line `\"safe,\nfast, productive.\"`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Adding Functionality with Test Driven Development", "heading_path": ["Adding Functionality with Test-Driven Development", "Writing a Failing Test"], "path": "ch12-04-testing-the-librarys-functionality.md", "url": "https://doc.rust-lang.org/book/ch12-04-testing-the-librarys-functionality.html#writing-a-failing-test", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch12-04-testing-the-librarys-functionality.md#writing-a-failing-test-2", "text": "The Rust Programming Language › Adding Functionality with Test-Driven Development › Writing a Failing Test\n\nListing 12-16: Defining just enough of the `search` function so that calling it won’t panic (src/lib.rs)\n```rust,noplayground\npub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {\n vec![]\n}\n```\nNow let’s discuss why we need to define an explicit lifetime `'a` in the\nsignature of `search` and use that lifetime with the `contents` argument and\nthe return value. Recall in Chapter 10 that\nthe lifetime parameters specify which argument lifetime is connected to the\nlifetime of the return value. In this case, we indicate that the returned\nvector should contain string slices that reference slices of the argument\n`contents` (rather than the argument `query`).\nIn other words, we tell Rust that the data returned by the `search` function\nwill live as long as the data passed into the `search` function in the\n`contents` argument. This is important! The data referenced _by_ a slice needs\nto be valid for the reference to be valid; if the compiler assumes we’re making\nstring slices of `query` rather than `contents`, it will do its safety checking\nincorrectly.\nIf we forget the lifetime annotations and try to compile this function, we’ll\nget this error:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Adding Functionality with Test Driven Development", "heading_path": ["Adding Functionality with Test-Driven Development", "Writing a Failing Test"], "path": "ch12-04-testing-the-librarys-functionality.md", "url": "https://doc.rust-lang.org/book/ch12-04-testing-the-librarys-functionality.html#writing-a-failing-test", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch12-04-testing-the-librarys-functionality.md#writing-a-failing-test-3", "text": "The Rust Programming Language › Adding Functionality with Test-Driven Development › Writing a Failing Test\n\n```console\n$ cargo build\n Compiling minigrep v0.1.0 (file:///projects/minigrep)\nerror[E0106]: missing lifetime specifier\n --> src/lib.rs:1:51\n |\n1 | pub fn search(query: &str, contents: &str) -> Vec<&str> {\n | ---- ---- ^ expected named lifetime parameter\n |\n = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `query` or `contents`\nhelp: consider introducing a named lifetime parameter\n |\n1 | pub fn search<'a>(query: &'a str, contents: &'a str) -> Vec<&'a str> {\n | ++++ ++ ++ ++\n\nFor more information about this error, try `rustc --explain E0106`.\nerror: could not compile `minigrep` (lib) due to 1 previous error\n```\nRust can’t know which of the two parameters we need for the output, so we need\nto tell it explicitly. Note that the help text suggests specifying the same\nlifetime parameter for all the parameters and the output type, which is\nincorrect! Because `contents` is the parameter that contains all of our text\nand we want to return the parts of that text that match, we know `contents` is\nthe only parameter that should be connected to the return value using the\nlifetime syntax.\nOther programming languages don’t require you to connect arguments to return\nvalues in the signature, but this practice will get easier over time. You might\nwant to compare this example with the examples in the “Validating References\nwith Lifetimes” section\nin Chapter 10.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Adding Functionality with Test Driven Development", "heading_path": ["Adding Functionality with Test-Driven Development", "Writing a Failing Test"], "path": "ch12-04-testing-the-librarys-functionality.md", "url": "https://doc.rust-lang.org/book/ch12-04-testing-the-librarys-functionality.html#writing-a-failing-test", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch12-04-testing-the-librarys-functionality.md#searching-each-line-for-the-query-4", "text": "The Rust Programming Language › Adding Functionality with Test-Driven Development › Writing Code to Pass the Test › Searching Each Line for the Query\n\nCurrently, our test is failing because we always return an empty vector. To fix\nthat and implement `search`, our program needs to follow these steps:\n1. Iterate through each line of the contents.\n2. Check whether the line contains our query string.\n3. If it does, add it to the list of values we’re returning.\n4. If it doesn’t, do nothing.\n5. Return the list of results that match.\nLet’s work through each step, starting with iterating through lines.\nRust has a helpful method to handle line-by-line iteration of strings,\nconveniently named `lines`, that works as shown in Listing 12-17. Note that\nthis won’t compile yet.\nListing 12-17: Iterating through each line in `contents` (src/lib.rs)\n```rust,ignore,does_not_compile\npub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {\n for line in contents.lines() {\n // do something with line\n }\n}\n```\nThe `lines` method returns an iterator. We’ll talk about iterators in depth in\nChapter 13. But recall that you saw this way\nof using an iterator in Listing 3-5, where we used a\n`for` loop with an iterator to run some code on each item in a collection.\nNext, we’ll check whether the current line contains our query string.\nFortunately, strings have a helpful method named `contains` that does this for\nus! Add a call to the `contains` method in the `search` function, as shown in\nListing 12-18. Note that this still won’t compile yet.\nListing 12-18: Adding functionality to see whether the line contains the string in `query` (src/lib.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Adding Functionality with Test Driven Development", "heading_path": ["Adding Functionality with Test-Driven Development", "Writing Code to Pass the Test", "Searching Each Line for the Query"], "path": "ch12-04-testing-the-librarys-functionality.md", "url": "https://doc.rust-lang.org/book/ch12-04-testing-the-librarys-functionality.html#searching-each-line-for-the-query", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch12-04-testing-the-librarys-functionality.md#storing-matching-lines-5", "text": "The Rust Programming Language › Adding Functionality with Test-Driven Development › Writing Code to Pass the Test › Storing Matching Lines\n\n```rust,ignore,does_not_compile\npub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {\n for line in contents.lines() {\n if line.contains(query) {\n // do something with line\n }\n }\n}\n```\nAt the moment, we’re building up functionality. To get the code to compile, we\nneed to return a value from the body as we indicated we would in the function\nsignature.\nTo finish this function, we need a way to store the matching lines that we want\nto return. For that, we can make a mutable vector before the `for` loop and\ncall the `push` method to store a `line` in the vector. After the `for` loop,\nwe return the vector, as shown in Listing 12-19.\nListing 12-19: Storing the lines that match so that we can return them (src/lib.rs)\n```rust,ignore\npub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {\n let mut results = Vec::new();\n\n for line in contents.lines() {\n if line.contains(query) {\n results.push(line);\n }\n }\n\n results\n}\n```\nNow the `search` function should return only the lines that contain `query`,\nand our test should pass. Let’s run the test:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Adding Functionality with Test Driven Development", "heading_path": ["Adding Functionality with Test-Driven Development", "Writing Code to Pass the Test", "Storing Matching Lines"], "path": "ch12-04-testing-the-librarys-functionality.md", "url": "https://doc.rust-lang.org/book/ch12-04-testing-the-librarys-functionality.html#storing-matching-lines", "has_code": true, "code_tags": ["rust,ignore", "rust,ignore,does_not_compile"]}} {"id": "book/ch12-04-testing-the-librarys-functionality.md#storing-matching-lines-6", "text": "The Rust Programming Language › Adding Functionality with Test-Driven Development › Writing Code to Pass the Test › Storing Matching Lines\n\n```console\n$ cargo test\n Compiling minigrep v0.1.0 (file:///projects/minigrep)\n Finished `test` profile [unoptimized + debuginfo] target(s) in 1.22s\n Running unittests src/lib.rs (target/debug/deps/minigrep-9cd200e5fac0fc94)\n\nrunning 1 test\ntest tests::one_result ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n Running unittests src/main.rs (target/debug/deps/minigrep-9cd200e5fac0fc94)\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n Doc-tests minigrep\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n```\nOur test passed, so we know it works!\nAt this point, we could consider opportunities for refactoring the\nimplementation of the search function while keeping the tests passing to\nmaintain the same functionality. The code in the search function isn’t too bad,\nbut it doesn’t take advantage of some useful features of iterators. We’ll\nreturn to this example in Chapter 13, where\nwe’ll explore iterators in detail, and look at how to improve it.\nNow the entire program should work! Let’s try it out, first with a word that\nshould return exactly one line from the Emily Dickinson poem: _frog_.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Adding Functionality with Test Driven Development", "heading_path": ["Adding Functionality with Test-Driven Development", "Writing Code to Pass the Test", "Storing Matching Lines"], "path": "ch12-04-testing-the-librarys-functionality.md", "url": "https://doc.rust-lang.org/book/ch12-04-testing-the-librarys-functionality.html#storing-matching-lines", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch12-04-testing-the-librarys-functionality.md#storing-matching-lines-7", "text": "The Rust Programming Language › Adding Functionality with Test-Driven Development › Writing Code to Pass the Test › Storing Matching Lines\n\n```console\n$ cargo run -- frog poem.txt\n Compiling minigrep v0.1.0 (file:///projects/minigrep)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.38s\n Running `target/debug/minigrep frog poem.txt`\nHow public, like a frog\n```\nCool! Now let’s try a word that will match multiple lines, like _body_:\n```console\n$ cargo run -- body poem.txt\n Compiling minigrep v0.1.0 (file:///projects/minigrep)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.0s\n Running `target/debug/minigrep body poem.txt`\nI'm nobody! Who are you?\nAre you nobody, too?\nHow dreary to be somebody!\n```\nAnd finally, let’s make sure that we don’t get any lines when we search for a\nword that isn’t anywhere in the poem, such as _monomorphization_:\n```console\n$ cargo run -- monomorphization poem.txt\n Compiling minigrep v0.1.0 (file:///projects/minigrep)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.0s\n Running `target/debug/minigrep monomorphization poem.txt`\n```\nExcellent! We’ve built our own mini version of a classic tool and learned a lot\nabout how to structure applications. We’ve also learned a bit about file input\nand output, lifetimes, testing, and command line parsing.\nTo round out this project, we’ll briefly demonstrate how to work with\nenvironment variables and how to print to standard error, both of which are\nuseful when you’re writing command line programs.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Adding Functionality with Test Driven Development", "heading_path": ["Adding Functionality with Test-Driven Development", "Writing Code to Pass the Test", "Storing Matching Lines"], "path": "ch12-04-testing-the-librarys-functionality.md", "url": "https://doc.rust-lang.org/book/ch12-04-testing-the-librarys-functionality.html#storing-matching-lines", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch12-05-working-with-environment-variables.md#working-with-environment-variables-0", "text": "The Rust Programming Language › Working with Environment Variables\n\nWe’ll improve the `minigrep` binary by adding an extra feature: an option for\ncase-insensitive searching that the user can turn on via an environment\nvariable. We could make this feature a command line option and require that\nusers enter it each time they want it to apply, but by instead making it an\nenvironment variable, we allow our users to set the environment variable once\nand have all their searches be case insensitive in that terminal session.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Working with Environment Variables", "heading_path": ["Working with Environment Variables"], "path": "ch12-05-working-with-environment-variables.md", "url": "https://doc.rust-lang.org/book/ch12-05-working-with-environment-variables.html#working-with-environment-variables", "has_code": false, "code_tags": []}} {"id": "book/ch12-05-working-with-environment-variables.md#writing-a-failing-test-for-case-insensitive-search-1", "text": "The Rust Programming Language › Working with Environment Variables › Writing a Failing Test for Case-Insensitive Search\n\nWe first add a new `search_case_insensitive` function to the `minigrep` library\nthat will be called when the environment variable has a value. We’ll continue\nto follow the TDD process, so the first step is again to write a failing test.\nWe’ll add a new test for the new `search_case_insensitive` function and rename\nour old test from `one_result` to `case_sensitive` to clarify the differences\nbetween the two tests, as shown in Listing 12-20.\nListing 12-20: Adding a new failing test for the case-insensitive function we’re about to add (src/lib.rs)\n```rust,ignore,does_not_compile\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn case_sensitive() {\n let query = \"duct\";\n let contents = \"\\\nRust:\nsafe, fast, productive.\nPick three.\nDuct tape.\";\n\n assert_eq!(vec![\"safe, fast, productive.\"], search(query, contents));\n }\n\n #[test]\n fn case_insensitive() {\n let query = \"rUsT\";\n let contents = \"\\\nRust:\nsafe, fast, productive.\nPick three.\nTrust me.\";\n\n assert_eq!(\n vec![\"Rust:\", \"Trust me.\"],\n search_case_insensitive(query, contents)\n );\n }\n}\n```\nNote that we’ve edited the old test’s `contents` too. We’ve added a new line\nwith the text `\"Duct tape.\"` using a capital _D_ that shouldn’t match the query\n`\"duct\"` when we’re searching in a case-sensitive manner. Changing the old test\nin this way helps ensure that we don’t accidentally break the case-sensitive\nsearch functionality that we’ve already implemented. This test should pass now\nand should continue to pass as we work on the case-insensitive search.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Working with Environment Variables", "heading_path": ["Working with Environment Variables", "Writing a Failing Test for Case-Insensitive Search"], "path": "ch12-05-working-with-environment-variables.md", "url": "https://doc.rust-lang.org/book/ch12-05-working-with-environment-variables.html#writing-a-failing-test-for-case-insensitive-search", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch12-05-working-with-environment-variables.md#writing-a-failing-test-for-case-insensitive-search-2", "text": "The Rust Programming Language › Working with Environment Variables › Writing a Failing Test for Case-Insensitive Search\n\nThe new test for the case-_insensitive_ search uses `\"rUsT\"` as its query. In\nthe `search_case_insensitive` function we’re about to add, the query `\"rUsT\"`\nshould match the line containing `\"Rust:\"` with a capital _R_ and match the\nline `\"Trust me.\"` even though both have different casing from the query. This\nis our failing test, and it will fail to compile because we haven’t yet defined\nthe `search_case_insensitive` function. Feel free to add a skeleton\nimplementation that always returns an empty vector, similar to the way we did\nfor the `search` function in Listing 12-16 to see the test compile and fail.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Working with Environment Variables", "heading_path": ["Working with Environment Variables", "Writing a Failing Test for Case-Insensitive Search"], "path": "ch12-05-working-with-environment-variables.md", "url": "https://doc.rust-lang.org/book/ch12-05-working-with-environment-variables.html#writing-a-failing-test-for-case-insensitive-search", "has_code": false, "code_tags": []}} {"id": "book/ch12-05-working-with-environment-variables.md#implementing-the-search_case_insensitive-function-3", "text": "The Rust Programming Language › Working with Environment Variables › Implementing the `search_case_insensitive` Function\n\nThe `search_case_insensitive` function, shown in Listing 12-21, will be almost\nthe same as the `search` function. The only difference is that we’ll lowercase\nthe `query` and each `line` so that whatever the case of the input arguments,\nthey’ll be the same case when we check whether the line contains the query.\nListing 12-21: Defining the `search_case_insensitive` function to lowercase the query and the line before comparing them (src/lib.rs)\n```rust,noplayground\npub fn search_case_insensitive<'a>(\n query: &str,\n contents: &'a str,\n) -> Vec<&'a str> {\n let query = query.to_lowercase();\n let mut results = Vec::new();\n\n for line in contents.lines() {\n if line.to_lowercase().contains(&query) {\n results.push(line);\n }\n }\n\n results\n}\n```\nFirst, we lowercase the `query` string and store it in a new variable with the\nsame name, shadowing the original `query`. Calling `to_lowercase` on the query\nis necessary so that no matter whether the user’s query is `\"rust\"`, `\"RUST\"`,\n`\"Rust\"`, or `\"rUsT\"`, we’ll treat the query as if it were `\"rust\"` and be\ninsensitive to the case. While `to_lowercase` will handle basic Unicode, it\nwon’t be 100 percent accurate. If we were writing a real application, we’d want\nto do a bit more work here, but this section is about environment variables,\nnot Unicode, so we’ll leave it at that here.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Working with Environment Variables", "heading_path": ["Working with Environment Variables", "Implementing the `search_case_insensitive` Function"], "path": "ch12-05-working-with-environment-variables.md", "url": "https://doc.rust-lang.org/book/ch12-05-working-with-environment-variables.html#implementing-the-search_case_insensitive-function", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch12-05-working-with-environment-variables.md#implementing-the-search_case_insensitive-function-4", "text": "The Rust Programming Language › Working with Environment Variables › Implementing the `search_case_insensitive` Function\n\nNote that `query` is now a `String` rather than a string slice because calling\n`to_lowercase` creates new data rather than referencing existing data. Say the\nquery is `\"rUsT\"`, as an example: That string slice doesn’t contain a lowercase\n`u` or `t` for us to use, so we have to allocate a new `String` containing\n`\"rust\"`. When we pass `query` as an argument to the `contains` method now, we\nneed to add an ampersand because the signature of `contains` is defined to take\na string slice.\nNext, we add a call to `to_lowercase` on each `line` to lowercase all\ncharacters. Now that we’ve converted `line` and `query` to lowercase, we’ll\nfind matches no matter what the case of the query is.\nLet’s see if this implementation passes the tests:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Working with Environment Variables", "heading_path": ["Working with Environment Variables", "Implementing the `search_case_insensitive` Function"], "path": "ch12-05-working-with-environment-variables.md", "url": "https://doc.rust-lang.org/book/ch12-05-working-with-environment-variables.html#implementing-the-search_case_insensitive-function", "has_code": false, "code_tags": []}} {"id": "book/ch12-05-working-with-environment-variables.md#implementing-the-search_case_insensitive-function-5", "text": "The Rust Programming Language › Working with Environment Variables › Implementing the `search_case_insensitive` Function\n\n```console\n$ cargo test\n Compiling minigrep v0.1.0 (file:///projects/minigrep)\n Finished `test` profile [unoptimized + debuginfo] target(s) in 1.33s\n Running unittests src/lib.rs (target/debug/deps/minigrep-9cd200e5fac0fc94)\n\nrunning 2 tests\ntest tests::case_insensitive ... ok\ntest tests::case_sensitive ... ok\n\ntest result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n Running unittests src/main.rs (target/debug/deps/minigrep-9cd200e5fac0fc94)\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n Doc-tests minigrep\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n```\nGreat! They passed. Now let’s call the new `search_case_insensitive` function\nfrom the `run` function. First, we’ll add a configuration option to the `Config`\nstruct to switch between case-sensitive and case-insensitive search. Adding\nthis field will cause compiler errors because we aren’t initializing this field\nanywhere yet:\nFilename: src/main.rs\n```rust,ignore,does_not_compile\npub struct Config {\n pub query: String,\n pub file_path: String,\n pub ignore_case: bool,\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Working with Environment Variables", "heading_path": ["Working with Environment Variables", "Implementing the `search_case_insensitive` Function"], "path": "ch12-05-working-with-environment-variables.md", "url": "https://doc.rust-lang.org/book/ch12-05-working-with-environment-variables.html#implementing-the-search_case_insensitive-function", "has_code": true, "code_tags": ["console", "rust,ignore,does_not_compile"]}} {"id": "book/ch12-05-working-with-environment-variables.md#implementing-the-search_case_insensitive-function-6", "text": "The Rust Programming Language › Working with Environment Variables › Implementing the `search_case_insensitive` Function\n\nWe added the `ignore_case` field that holds a Boolean. Next, we need the `run`\nfunction to check the `ignore_case` field’s value and use that to decide\nwhether to call the `search` function or the `search_case_insensitive`\nfunction, as shown in Listing 12-22. This still won’t compile yet.\nListing 12-22: Calling either `search` or `search_case_insensitive` based on the value in `config.ignore_case` (src/main.rs)\n```rust,ignore,does_not_compile\nuse minigrep::{search, search_case_insensitive};\n\n// --snip--\n\nfn run(config: Config) -> Result<(), Box> {\n let contents = fs::read_to_string(config.file_path)?;\n\n let results = if config.ignore_case {\n search_case_insensitive(&config.query, &contents)\n } else {\n search(&config.query, &contents)\n };\n\n for line in results {\n println!(\"{line}\");\n }\n\n Ok(())\n}\n```\nFinally, we need to check for the environment variable. The functions for\nworking with environment variables are in the `env` module in the standard\nlibrary, which is already in scope at the top of _src/main.rs_. We’ll use the\n`var` function from the `env` module to check to see if any value has been set\nfor an environment variable named `IGNORE_CASE`, as shown in Listing 12-23.\nListing 12-23: Checking for any value in an environment variable named `IGNORE_CASE` (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Working with Environment Variables", "heading_path": ["Working with Environment Variables", "Implementing the `search_case_insensitive` Function"], "path": "ch12-05-working-with-environment-variables.md", "url": "https://doc.rust-lang.org/book/ch12-05-working-with-environment-variables.html#implementing-the-search_case_insensitive-function", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch12-05-working-with-environment-variables.md#implementing-the-search_case_insensitive-function-7", "text": "The Rust Programming Language › Working with Environment Variables › Implementing the `search_case_insensitive` Function\n\n```rust,ignore,noplayground\nimpl Config {\n fn build(args: &[String]) -> Result {\n if args.len() < 3 {\n return Err(\"not enough arguments\");\n }\n\n let query = args[1].clone();\n let file_path = args[2].clone();\n\n let ignore_case = env::var(\"IGNORE_CASE\").is_ok();\n\n Ok(Config {\n query,\n file_path,\n ignore_case,\n })\n }\n}\n```\nHere, we create a new variable, `ignore_case`. To set its value, we call the\n`env::var` function and pass it the name of the `IGNORE_CASE` environment\nvariable. The `env::var` function returns a `Result` that will be the\nsuccessful `Ok` variant that contains the value of the environment variable if\nthe environment variable is set to any value. It will return the `Err` variant\nif the environment variable is not set.\nWe’re using the `is_ok` method on the `Result` to check whether the environment\nvariable is set, which means the program should do a case-insensitive search.\nIf the `IGNORE_CASE` environment variable isn’t set to anything, `is_ok` will\nreturn `false` and the program will perform a case-sensitive search. We don’t\ncare about the _value_ of the environment variable, just whether it’s set or\nunset, so we’re checking `is_ok` rather than using `unwrap`, `expect`, or any\nof the other methods we’ve seen on `Result`.\nWe pass the value in the `ignore_case` variable to the `Config` instance so\nthat the `run` function can read that value and decide whether to call\n`search_case_insensitive` or `search`, as we implemented in Listing 12-22.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Working with Environment Variables", "heading_path": ["Working with Environment Variables", "Implementing the `search_case_insensitive` Function"], "path": "ch12-05-working-with-environment-variables.md", "url": "https://doc.rust-lang.org/book/ch12-05-working-with-environment-variables.html#implementing-the-search_case_insensitive-function", "has_code": true, "code_tags": ["rust,ignore,noplayground"]}} {"id": "book/ch12-05-working-with-environment-variables.md#implementing-the-search_case_insensitive-function-8", "text": "The Rust Programming Language › Working with Environment Variables › Implementing the `search_case_insensitive` Function\n\nLet’s give it a try! First, we’ll run our program without the environment\nvariable set and with the query `to`, which should match any line that contains\nthe word _to_ in all lowercase:\n```console\n$ cargo run -- to poem.txt\n Compiling minigrep v0.1.0 (file:///projects/minigrep)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.0s\n Running `target/debug/minigrep to poem.txt`\nAre you nobody, too?\nHow dreary to be somebody!\n```\nLooks like that still works! Now let’s run the program with `IGNORE_CASE` set\nto `1` but with the same query `to`:\n```console\n$ IGNORE_CASE=1 cargo run -- to poem.txt\n```\nIf you’re using PowerShell, you will need to set the environment variable and\nrun the program as separate commands:\n```console\nPS> $Env:IGNORE_CASE=1; cargo run -- to poem.txt\n```\nThis will make `IGNORE_CASE` persist for the remainder of your shell session.\nIt can be unset with the `Remove-Item` cmdlet:\n```console\nPS> Remove-Item Env:IGNORE_CASE\n```\nWe should get lines that contain _to_ that might have uppercase letters:\n```console\nAre you nobody, too?\nHow dreary to be somebody!\nTo tell your name the livelong day\nTo an admiring bog!\n```\nExcellent, we also got lines containing _To_! Our `minigrep` program can now do\ncase-insensitive searching controlled by an environment variable. Now you know\nhow to manage options set using either command line arguments or environment\nvariables.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Working with Environment Variables", "heading_path": ["Working with Environment Variables", "Implementing the `search_case_insensitive` Function"], "path": "ch12-05-working-with-environment-variables.md", "url": "https://doc.rust-lang.org/book/ch12-05-working-with-environment-variables.html#implementing-the-search_case_insensitive-function", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch12-05-working-with-environment-variables.md#implementing-the-search_case_insensitive-function-9", "text": "The Rust Programming Language › Working with Environment Variables › Implementing the `search_case_insensitive` Function\n\nSome programs allow arguments _and_ environment variables for the same\nconfiguration. In those cases, the programs decide that one or the other takes\nprecedence. For another exercise on your own, try controlling case sensitivity\nthrough either a command line argument or an environment variable. Decide\nwhether the command line argument or the environment variable should take\nprecedence if the program is run with one set to case sensitive and one set to\nignore case.\nThe `std::env` module contains many more useful features for dealing with\nenvironment variables: Check out its documentation to see what is available.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Working with Environment Variables", "heading_path": ["Working with Environment Variables", "Implementing the `search_case_insensitive` Function"], "path": "ch12-05-working-with-environment-variables.md", "url": "https://doc.rust-lang.org/book/ch12-05-working-with-environment-variables.html#implementing-the-search_case_insensitive-function", "has_code": false, "code_tags": []}} {"id": "book/ch12-06-writing-to-stderr-instead-of-stdout.md#redirecting-errors-to-standard-error-0", "text": "The Rust Programming Language › Redirecting Errors to Standard Error\n\nAt the moment, we’re writing all of our output to the terminal using the\n`println!` macro. In most terminals, there are two kinds of output: _standard\noutput_ (`stdout`) for general information and _standard error_ (`stderr`) for\nerror messages. This distinction enables users to choose to direct the\nsuccessful output of a program to a file but still print error messages to the\nscreen.\nThe `println!` macro is only capable of printing to standard output, so we have\nto use something else to print to standard error.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Redirecting Errors to Standard Error", "heading_path": ["Redirecting Errors to Standard Error"], "path": "ch12-06-writing-to-stderr-instead-of-stdout.md", "url": "https://doc.rust-lang.org/book/ch12-06-writing-to-stderr-instead-of-stdout.html#redirecting-errors-to-standard-error", "has_code": false, "code_tags": []}} {"id": "book/ch12-06-writing-to-stderr-instead-of-stdout.md#checking-where-errors-are-written-1", "text": "The Rust Programming Language › Redirecting Errors to Standard Error › Checking Where Errors Are Written\n\nFirst, let’s observe how the content printed by `minigrep` is currently being\nwritten to standard output, including any error messages we want to write to\nstandard error instead. We’ll do that by redirecting the standard output stream\nto a file while intentionally causing an error. We won’t redirect the standard\nerror stream, so any content sent to standard error will continue to display on\nthe screen.\nCommand line programs are expected to send error messages to the standard error\nstream so that we can still see error messages on the screen even if we\nredirect the standard output stream to a file. Our program is not currently\nwell behaved: We’re about to see that it saves the error message output to a\nfile instead!\nTo demonstrate this behavior, we’ll run the program with `>` and the file path,\n_output.txt_, that we want to redirect the standard output stream to. We won’t\npass any arguments, which should cause an error:\n```console\n$ cargo run > output.txt\n```\nThe `>` syntax tells the shell to write the contents of standard output to\n_output.txt_ instead of the screen. We didn’t see the error message we were\nexpecting printed to the screen, so that means it must have ended up in the\nfile. This is what _output.txt_ contains:\n```text\nProblem parsing arguments: not enough arguments\n```\nYup, our error message is being printed to standard output. It’s much more\nuseful for error messages like this to be printed to standard error so that\nonly data from a successful run ends up in the file. We’ll change that.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Redirecting Errors to Standard Error", "heading_path": ["Redirecting Errors to Standard Error", "Checking Where Errors Are Written"], "path": "ch12-06-writing-to-stderr-instead-of-stdout.md", "url": "https://doc.rust-lang.org/book/ch12-06-writing-to-stderr-instead-of-stdout.html#checking-where-errors-are-written", "has_code": true, "code_tags": ["console", "text"]}} {"id": "book/ch12-06-writing-to-stderr-instead-of-stdout.md#printing-errors-to-standard-error-2", "text": "The Rust Programming Language › Redirecting Errors to Standard Error › Printing Errors to Standard Error\n\nWe’ll use the code in Listing 12-24 to change how error messages are printed.\nBecause of the refactoring we did earlier in this chapter, all the code that\nprints error messages is in one function, `main`. The standard library provides\nthe `eprintln!` macro that prints to the standard error stream, so let’s change\nthe two places we were calling `println!` to print errors to use `eprintln!`\ninstead.\nListing 12-24: Writing error messages to standard error instead of standard output using `eprintln!` (src/main.rs)\n```rust,ignore\nfn main() {\n let args: Vec = env::args().collect();\n\n let config = Config::build(&args).unwrap_or_else(|err| {\n eprintln!(\"Problem parsing arguments: {err}\");\n process::exit(1);\n });\n\n if let Err(e) = run(config) {\n eprintln!(\"Application error: {e}\");\n process::exit(1);\n }\n}\n```\nLet’s now run the program again in the same way, without any arguments and\nredirecting standard output with `>`:\n```console\n$ cargo run > output.txt\nProblem parsing arguments: not enough arguments\n```\nNow we see the error onscreen and _output.txt_ contains nothing, which is the\nbehavior we expect of command line programs.\nLet’s run the program again with arguments that don’t cause an error but still\nredirect standard output to a file, like so:\n```console\n$ cargo run -- to poem.txt > output.txt\n```\nWe won’t see any output to the terminal, and _output.txt_ will contain our\nresults:\nFilename: output.txt\n```text\nAre you nobody, too?\nHow dreary to be somebody!\n```\nThis demonstrates that we’re now using standard output for successful output\nand standard error for error output as appropriate.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Redirecting Errors to Standard Error", "heading_path": ["Redirecting Errors to Standard Error", "Printing Errors to Standard Error"], "path": "ch12-06-writing-to-stderr-instead-of-stdout.md", "url": "https://doc.rust-lang.org/book/ch12-06-writing-to-stderr-instead-of-stdout.html#printing-errors-to-standard-error", "has_code": true, "code_tags": ["console", "rust,ignore", "text"]}} {"id": "book/ch12-06-writing-to-stderr-instead-of-stdout.md#summary-3", "text": "The Rust Programming Language › Summary\n\nThis chapter recapped some of the major concepts you’ve learned so far and\ncovered how to perform common I/O operations in Rust. By using command line\narguments, files, environment variables, and the `eprintln!` macro for printing\nerrors, you’re now prepared to write command line applications. Combined with\nthe concepts in previous chapters, your code will be well organized, store data\neffectively in the appropriate data structures, handle errors nicely, and be\nwell tested.\nNext, we’ll explore some Rust features that were influenced by functional\nlanguages: closures and iterators.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Redirecting Errors to Standard Error", "heading_path": ["Summary"], "path": "ch12-06-writing-to-stderr-instead-of-stdout.md", "url": "https://doc.rust-lang.org/book/ch12-06-writing-to-stderr-instead-of-stdout.html#summary", "has_code": false, "code_tags": []}} {"id": "book/ch13-00-functional-features.md#functional-language-features-iterators-and-closures-0", "text": "The Rust Programming Language › Functional Language Features: Iterators and Closures\n\nRust’s design has taken inspiration from many existing languages and\ntechniques, and one significant influence is _functional programming_.\nProgramming in a functional style often includes using functions as values by\npassing them in arguments, returning them from other functions, assigning them\nto variables for later execution, and so forth.\nIn this chapter, we won’t debate the issue of what functional programming is or\nisn’t but will instead discuss some features of Rust that are similar to\nfeatures in many languages often referred to as functional.\nMore specifically, we’ll cover:\n- _Closures_, a function-like construct you can store in a variable\n- _Iterators_, a way of processing a series of elements\n- How to use closures and iterators to improve the I/O project in Chapter 12\n- The performance of closures and iterators (spoiler alert: They’re faster than\n you might think!)\nWe’ve already covered some other Rust features, such as pattern matching and\nenums, that are also influenced by the functional style. Because mastering\nclosures and iterators is an important part of writing fast, idiomatic, Rust\ncode, we’ll devote this entire chapter to them.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Functional Language Features: Iterators and Closures", "heading_path": ["Functional Language Features: Iterators and Closures"], "path": "ch13-00-functional-features.md", "url": "https://doc.rust-lang.org/book/ch13-00-functional-features.html#functional-language-features-iterators-and-closures", "has_code": false, "code_tags": []}} {"id": "book/ch13-01-closures.md#closures-0", "text": "The Rust Programming Language › Closures\n\nRust’s closures are anonymous functions you can save in a variable or pass as\narguments to other functions. You can create the closure in one place and then\ncall the closure elsewhere to evaluate it in a different context. Unlike\nfunctions, closures can capture values from the scope in which they’re defined.\nWe’ll demonstrate how these closure features allow for code reuse and behavior\ncustomization.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Closures", "heading_path": ["Closures"], "path": "ch13-01-closures.md", "url": "https://doc.rust-lang.org/book/ch13-01-closures.html#closures", "has_code": false, "code_tags": []}} {"id": "book/ch13-01-closures.md#capturing-the-environment-1", "text": "The Rust Programming Language › Closures › Capturing the Environment\n\nWe’ll first examine how we can use closures to capture values from the\nenvironment they’re defined in for later use. Here’s the scenario: Every so\noften, our T-shirt company gives away an exclusive, limited-edition shirt to\nsomeone on our mailing list as a promotion. People on the mailing list can\noptionally add their favorite color to their profile. If the person chosen for\na free shirt has their favorite color set, they get that color shirt. If the\nperson hasn’t specified a favorite color, they get whatever color the company\ncurrently has the most of.\nThere are many ways to implement this. For this example, we’re going to use an\nenum called `ShirtColor` that has the variants `Red` and `Blue` (limiting the\nnumber of colors available for simplicity). We represent the company’s\ninventory with an `Inventory` struct that has a field named `shirts` that\ncontains a `Vec` representing the shirt colors currently in stock.\nThe method `giveaway` defined on `Inventory` gets the optional shirt color\npreference of the free-shirt winner, and it returns the shirt color the\nperson will get. This setup is shown in Listing 13-1.\nListing 13-1: Shirt company giveaway situation (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Closures", "heading_path": ["Closures", "Capturing the Environment"], "path": "ch13-01-closures.md", "url": "https://doc.rust-lang.org/book/ch13-01-closures.html#capturing-the-environment", "has_code": false, "code_tags": []}} {"id": "book/ch13-01-closures.md#capturing-the-environment-2", "text": "The Rust Programming Language › Closures › Capturing the Environment\n\n```rust,noplayground\n#[derive(Debug, PartialEq, Copy, Clone)]\nenum ShirtColor {\n Red,\n Blue,\n}\n\nstruct Inventory {\n shirts: Vec,\n}\n\nimpl Inventory {\n fn giveaway(&self, user_preference: Option) -> ShirtColor {\n user_preference.unwrap_or_else(|| self.most_stocked())\n }\n\n fn most_stocked(&self) -> ShirtColor {\n let mut num_red = 0;\n let mut num_blue = 0;\n\n for color in &self.shirts {\n match color {\n ShirtColor::Red => num_red += 1,\n ShirtColor::Blue => num_blue += 1,\n }\n }\n if num_red > num_blue {\n ShirtColor::Red\n } else {\n ShirtColor::Blue\n }\n }\n}\n\nfn main() {\n let store = Inventory {\n shirts: vec![ShirtColor::Blue, ShirtColor::Red, ShirtColor::Blue],\n };\n\n let user_pref1 = Some(ShirtColor::Red);\n let giveaway1 = store.giveaway(user_pref1);\n println!(\n \"The user with preference {:?} gets {:?}\",\n user_pref1, giveaway1\n );\n\n let user_pref2 = None;\n let giveaway2 = store.giveaway(user_pref2);\n println!(\n \"The user with preference {:?} gets {:?}\",\n user_pref2, giveaway2\n );\n}\n```\nThe `store` defined in `main` has two blue shirts and one red shirt remaining\nto distribute for this limited-edition promotion. We call the `giveaway` method\nfor a user with a preference for a red shirt and a user without any preference.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Closures", "heading_path": ["Closures", "Capturing the Environment"], "path": "ch13-01-closures.md", "url": "https://doc.rust-lang.org/book/ch13-01-closures.html#capturing-the-environment", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch13-01-closures.md#capturing-the-environment-3", "text": "The Rust Programming Language › Closures › Capturing the Environment\n\nAgain, this code could be implemented in many ways, and here, to focus on\nclosures, we’ve stuck to concepts you’ve already learned, except for the body of\nthe `giveaway` method that uses a closure. In the `giveaway` method, we get the\nuser preference as a parameter of type `Option` and call the\n`unwrap_or_else` method on `user_preference`. The `unwrap_or_else` method on\n`Option` is defined by the standard library.\nIt takes one argument: a closure without any arguments that returns a value `T`\n(the same type stored in the `Some` variant of the `Option`, in this case\n`ShirtColor`). If the `Option` is the `Some` variant, `unwrap_or_else`\nreturns the value from within the `Some`. If the `Option` is the `None`\nvariant, `unwrap_or_else` calls the closure and returns the value returned by\nthe closure.\nWe specify the closure expression `|| self.most_stocked()` as the argument to\n`unwrap_or_else`. This is a closure that takes no parameters itself (if the\nclosure had parameters, they would appear between the two vertical pipes). The\nbody of the closure calls `self.most_stocked()`. We’re defining the closure\nhere, and the implementation of `unwrap_or_else` will evaluate the closure\nlater if the result is needed.\nRunning this code prints the following:\n```console\n$ cargo run\n Compiling shirt-company v0.1.0 (file:///projects/shirt-company)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.27s\n Running `target/debug/shirt-company`\nThe user with preference Some(Red) gets Red\nThe user with preference None gets Blue\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Closures", "heading_path": ["Closures", "Capturing the Environment"], "path": "ch13-01-closures.md", "url": "https://doc.rust-lang.org/book/ch13-01-closures.html#capturing-the-environment", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch13-01-closures.md#capturing-the-environment-4", "text": "The Rust Programming Language › Closures › Capturing the Environment\n\nOne interesting aspect here is that we’ve passed a closure that calls\n`self.most_stocked()` on the current `Inventory` instance. The standard library\ndidn’t need to know anything about the `Inventory` or `ShirtColor` types we\ndefined, or the logic we want to use in this scenario. The closure captures an\nimmutable reference to the `self` `Inventory` instance and passes it with the\ncode we specify to the `unwrap_or_else` method. Functions, on the other hand,\nare not able to capture their environment in this way.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Closures", "heading_path": ["Closures", "Capturing the Environment"], "path": "ch13-01-closures.md", "url": "https://doc.rust-lang.org/book/ch13-01-closures.html#capturing-the-environment", "has_code": false, "code_tags": []}} {"id": "book/ch13-01-closures.md#inferring-and-annotating-closure-types-5", "text": "The Rust Programming Language › Closures › Inferring and Annotating Closure Types\n\nThere are more differences between functions and closures. Closures don’t\nusually require you to annotate the types of the parameters or the return value\nlike `fn` functions do. Type annotations are required on functions because the\ntypes are part of an explicit interface exposed to your users. Defining this\ninterface rigidly is important for ensuring that everyone agrees on what types\nof values a function uses and returns. Closures, on the other hand, aren’t used\nin an exposed interface like this: They’re stored in variables, and they’re\nused without naming them and exposing them to users of our library.\nClosures are typically short and relevant only within a narrow context rather\nthan in any arbitrary scenario. Within these limited contexts, the compiler can\ninfer the types of the parameters and the return type, similar to how it’s able\nto infer the types of most variables (there are rare cases where the compiler\nneeds closure type annotations too).\nAs with variables, we can add type annotations if we want to increase\nexplicitness and clarity at the cost of being more verbose than is strictly\nnecessary. Annotating the types for a closure would look like the definition\nshown in Listing 13-2. In this example, we’re defining a closure and storing it\nin a variable rather than defining the closure in the spot we pass it as an\nargument, as we did in Listing 13-1.\nListing 13-2: Adding optional type annotations of the parameter and return value types in the closure (src/main.rs)\n```rust\n let expensive_closure = |num: u32| -> u32 {\n println!(\"calculating slowly...\");\n thread::sleep(Duration::from_secs(2));\n num\n };\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Closures", "heading_path": ["Closures", "Inferring and Annotating Closure Types"], "path": "ch13-01-closures.md", "url": "https://doc.rust-lang.org/book/ch13-01-closures.html#inferring-and-annotating-closure-types", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch13-01-closures.md#inferring-and-annotating-closure-types-6", "text": "The Rust Programming Language › Closures › Inferring and Annotating Closure Types\n\nWith type annotations added, the syntax of closures looks more similar to the\nsyntax of functions. Here, we define a function that adds 1 to its parameter and\na closure that has the same behavior, for comparison. We’ve added some spaces\nto line up the relevant parts. This illustrates how closure syntax is similar\nto function syntax except for the use of pipes and the amount of syntax that is\noptional:\n```rust,ignore\nfn add_one_v1 (x: u32) -> u32 { x + 1 }\nlet add_one_v2 = |x: u32| -> u32 { x + 1 };\nlet add_one_v3 = |x| { x + 1 };\nlet add_one_v4 = |x| x + 1 ;\n```\nThe first line shows a function definition and the second line shows a fully\nannotated closure definition. In the third line, we remove the type annotations\nfrom the closure definition. In the fourth line, we remove the brackets, which\nare optional because the closure body has only one expression. These are all\nvalid definitions that will produce the same behavior when they’re called. The\n`add_one_v3` and `add_one_v4` lines require the closures to be evaluated to be\nable to compile because the types will be inferred from their usage. This is\nsimilar to `let v = Vec::new();` needing either type annotations or values of\nsome type to be inserted into the `Vec` for Rust to be able to infer the type.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Closures", "heading_path": ["Closures", "Inferring and Annotating Closure Types"], "path": "ch13-01-closures.md", "url": "https://doc.rust-lang.org/book/ch13-01-closures.html#inferring-and-annotating-closure-types", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch13-01-closures.md#inferring-and-annotating-closure-types-7", "text": "The Rust Programming Language › Closures › Inferring and Annotating Closure Types\n\nFor closure definitions, the compiler will infer one concrete type for each of\ntheir parameters and for their return value. For instance, Listing 13-3 shows\nthe definition of a short closure that just returns the value it receives as a\nparameter. This closure isn’t very useful except for the purposes of this\nexample. Note that we haven’t added any type annotations to the definition.\nBecause there are no type annotations, we can call the closure with any type,\nwhich we’ve done here with `String` the first time. If we then try to call\n`example_closure` with an integer, we’ll get an error.\nListing 13-3: Attempting to call a closure whose types are inferred with two different types (src/main.rs)\n```rust,ignore,does_not_compile\n let example_closure = |x| x;\n\n let s = example_closure(String::from(\"hello\"));\n let n = example_closure(5);\n```\nThe compiler gives us this error:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Closures", "heading_path": ["Closures", "Inferring and Annotating Closure Types"], "path": "ch13-01-closures.md", "url": "https://doc.rust-lang.org/book/ch13-01-closures.html#inferring-and-annotating-closure-types", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch13-01-closures.md#inferring-and-annotating-closure-types-8", "text": "The Rust Programming Language › Closures › Inferring and Annotating Closure Types\n\n```console\n$ cargo run\n Compiling closure-example v0.1.0 (file:///projects/closure-example)\nerror[E0308]: mismatched types\n --> src/main.rs:5:29\n |\n5 | let n = example_closure(5);\n | --------------- ^ expected `String`, found integer\n | |\n | arguments to this function are incorrect\n |\nnote: expected because the closure was earlier called with an argument of type `String`\n --> src/main.rs:4:29\n |\n4 | let s = example_closure(String::from(\"hello\"));\n | --------------- ^^^^^^^^^^^^^^^^^^^^^ expected because this argument is of type `String`\n | |\n | in this closure call\nnote: closure parameter defined here\n --> src/main.rs:2:28\n |\n2 | let example_closure = |x| x;\n | ^\nhelp: try using a conversion method\n |\n5 | let n = example_closure(5.to_string());\n | ++++++++++++\n\nFor more information about this error, try `rustc --explain E0308`.\nerror: could not compile `closure-example` (bin \"closure-example\") due to 1 previous error\n```\nThe first time we call `example_closure` with the `String` value, the compiler\ninfers the type of `x` and the return type of the closure to be `String`. Those\ntypes are then locked into the closure in `example_closure`, and we get a type\nerror when we next try to use a different type with the same closure.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Closures", "heading_path": ["Closures", "Inferring and Annotating Closure Types"], "path": "ch13-01-closures.md", "url": "https://doc.rust-lang.org/book/ch13-01-closures.html#inferring-and-annotating-closure-types", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch13-01-closures.md#capturing-references-or-moving-ownership-9", "text": "The Rust Programming Language › Closures › Capturing References or Moving Ownership\n\nClosures can capture values from their environment in three ways, which\ndirectly map to the three ways a function can take a parameter: borrowing\nimmutably, borrowing mutably, and taking ownership. The closure will decide\nwhich of these to use based on what the body of the function does with the\ncaptured values.\nIn Listing 13-4, we define a closure that captures an immutable reference to\nthe vector named `list` because it only needs an immutable reference to print\nthe value.\nListing 13-4: Defining and calling a closure that captures an immutable reference (src/main.rs)\n```rust\nfn main() {\n let list = vec![1, 2, 3];\n println!(\"Before defining closure: {list:?}\");\n\n let only_borrows = || println!(\"From closure: {list:?}\");\n\n println!(\"Before calling closure: {list:?}\");\n only_borrows();\n println!(\"After calling closure: {list:?}\");\n}\n```\nThis example also illustrates that a variable can bind to a closure definition,\nand we can later call the closure by using the variable name and parentheses as\nif the variable name were a function name.\nBecause we can have multiple immutable references to `list` at the same time,\n`list` is still accessible from the code before the closure definition, after\nthe closure definition but before the closure is called, and after the closure\nis called. This code compiles, runs, and prints:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Closures", "heading_path": ["Closures", "Capturing References or Moving Ownership"], "path": "ch13-01-closures.md", "url": "https://doc.rust-lang.org/book/ch13-01-closures.html#capturing-references-or-moving-ownership", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch13-01-closures.md#capturing-references-or-moving-ownership-10", "text": "The Rust Programming Language › Closures › Capturing References or Moving Ownership\n\n```console\n$ cargo run\n Compiling closure-example v0.1.0 (file:///projects/closure-example)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.43s\n Running `target/debug/closure-example`\nBefore defining closure: [1, 2, 3]\nBefore calling closure: [1, 2, 3]\nFrom closure: [1, 2, 3]\nAfter calling closure: [1, 2, 3]\n```\nNext, in Listing 13-5, we change the closure body so that it adds an element to\nthe `list` vector. The closure now captures a mutable reference.\nListing 13-5: Defining and calling a closure that captures a mutable reference (src/main.rs)\n```rust\nfn main() {\n let mut list = vec![1, 2, 3];\n println!(\"Before defining closure: {list:?}\");\n\n let mut borrows_mutably = || list.push(7);\n\n borrows_mutably();\n println!(\"After calling closure: {list:?}\");\n}\n```\nThis code compiles, runs, and prints:\n```console\n$ cargo run\n Compiling closure-example v0.1.0 (file:///projects/closure-example)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.43s\n Running `target/debug/closure-example`\nBefore defining closure: [1, 2, 3]\nAfter calling closure: [1, 2, 3, 7]\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Closures", "heading_path": ["Closures", "Capturing References or Moving Ownership"], "path": "ch13-01-closures.md", "url": "https://doc.rust-lang.org/book/ch13-01-closures.html#capturing-references-or-moving-ownership", "has_code": true, "code_tags": ["console", "rust"]}} {"id": "book/ch13-01-closures.md#capturing-references-or-moving-ownership-11", "text": "The Rust Programming Language › Closures › Capturing References or Moving Ownership\n\nNote that there’s no longer a `println!` between the definition and the call of\nthe `borrows_mutably` closure: When `borrows_mutably` is defined, it captures a\nmutable reference to `list`. We don’t use the closure again after the closure\nis called, so the mutable borrow ends. Between the closure definition and the\nclosure call, an immutable borrow to print isn’t allowed, because no other\nborrows are allowed when there’s a mutable borrow. Try adding a `println!`\nthere to see what error message you get!\nIf you want to force the closure to take ownership of the values it uses in the\nenvironment even though the body of the closure doesn’t strictly need\nownership, you can use the `move` keyword before the parameter list.\nThis technique is mostly useful when passing a closure to a new thread to move\nthe data so that it’s owned by the new thread. We’ll discuss threads and why\nyou would want to use them in detail in Chapter 16 when we talk about\nconcurrency, but for now, let’s briefly explore spawning a new thread using a\nclosure that needs the `move` keyword. Listing 13-6 shows Listing 13-4 modified\nto print the vector in a new thread rather than in the main thread.\nListing 13-6: Using `move` to force the closure for the thread to take ownership of `list` (src/main.rs)\n```rust\nuse std::thread;\n\nfn main() {\n let list = vec![1, 2, 3];\n println!(\"Before defining closure: {list:?}\");\n\n thread::spawn(move || println!(\"From thread: {list:?}\"))\n .join()\n .unwrap();\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Closures", "heading_path": ["Closures", "Capturing References or Moving Ownership"], "path": "ch13-01-closures.md", "url": "https://doc.rust-lang.org/book/ch13-01-closures.html#capturing-references-or-moving-ownership", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch13-01-closures.md#capturing-references-or-moving-ownership-12", "text": "The Rust Programming Language › Closures › Capturing References or Moving Ownership\n\nWe spawn a new thread, giving the thread a closure to run as an argument. The\nclosure body prints out the list. In Listing 13-4, the closure only captured\n`list` using an immutable reference because that's the least amount of access\nto `list` needed to print it. In this example, even though the closure body\nstill only needs an immutable reference, we need to specify that `list` should\nbe moved into the closure by putting the `move` keyword at the beginning of the\nclosure definition. If the main thread performed more operations before calling\n`join` on the new thread, the new thread might finish before the rest of the\nmain thread finishes, or the main thread might finish first. If the main thread\nmaintained ownership of `list` but ended before the new thread and drops\n`list`, the immutable reference in the thread would be invalid. Therefore, the\ncompiler requires that `list` be moved into the closure given to the new thread\nso that the reference will be valid. Try removing the `move` keyword or using\n`list` in the main thread after the closure is defined to see what compiler\nerrors you get!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Closures", "heading_path": ["Closures", "Capturing References or Moving Ownership"], "path": "ch13-01-closures.md", "url": "https://doc.rust-lang.org/book/ch13-01-closures.html#capturing-references-or-moving-ownership", "has_code": false, "code_tags": []}} {"id": "book/ch13-01-closures.md#moving-captured-values-out-of-closures-13", "text": "The Rust Programming Language › Closures › Moving Captured Values Out of Closures\n\nOnce a closure has captured a reference or captured ownership of a value from\nthe environment where the closure is defined (thus affecting what, if anything,\nis moved _into_ the closure), the code in the body of the closure defines what\nhappens to the references or values when the closure is evaluated later (thus\naffecting what, if anything, is moved _out of_ the closure).\nA closure body can do any of the following: Move a captured value out of the\nclosure, mutate the captured value, neither move nor mutate the value, or\ncapture nothing from the environment to begin with.\nThe way a closure captures and handles values from the environment affects\nwhich traits the closure implements, and traits are how functions and structs\ncan specify what kinds of closures they can use. Closures will automatically\nimplement one, two, or all three of these `Fn` traits, in an additive fashion,\ndepending on how the closure’s body handles the values:\n* `FnOnce` applies to closures that can be called once. All closures implement\n at least this trait because all closures can be called. A closure that moves\n captured values out of its body will only implement `FnOnce` and none of the\n other `Fn` traits because it can only be called once.\n* `FnMut` applies to closures that don’t move captured values out of their body\n but might mutate the captured values. These closures can be called more than\n once.\n* `Fn` applies to closures that don’t move captured values out of their body\n and don’t mutate captured values, as well as closures that capture nothing\n from their environment. These closures can be called more than once without\n mutating their environment, which is important in cases such as calling a closure multiple times concurrently.\nLet’s look at the definition of the `unwrap_or_else` method on `Option` that\nwe used in Listing 13-1:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Closures", "heading_path": ["Closures", "Moving Captured Values Out of Closures"], "path": "ch13-01-closures.md", "url": "https://doc.rust-lang.org/book/ch13-01-closures.html#moving-captured-values-out-of-closures", "has_code": false, "code_tags": []}} {"id": "book/ch13-01-closures.md#moving-captured-values-out-of-closures-14", "text": "The Rust Programming Language › Closures › Moving Captured Values Out of Closures\n\n```rust,ignore\nimpl Option {\n pub fn unwrap_or_else(self, f: F) -> T\n where\n F: FnOnce() -> T\n {\n match self {\n Some(x) => x,\n None => f(),\n }\n }\n}\n```\nRecall that `T` is the generic type representing the type of the value in the\n`Some` variant of an `Option`. That type `T` is also the return type of the\n`unwrap_or_else` function: Code that calls `unwrap_or_else` on an\n`Option`, for example, will get a `String`.\nNext, notice that the `unwrap_or_else` function has the additional generic type\nparameter `F`. The `F` type is the type of the parameter named `f`, which is\nthe closure we provide when calling `unwrap_or_else`.\nThe trait bound specified on the generic type `F` is `FnOnce() -> T`, which\nmeans `F` must be able to be called once, take no arguments, and return a `T`.\nUsing `FnOnce` in the trait bound expresses the constraint that\n`unwrap_or_else` will not call `f` more than once. In the body of\n`unwrap_or_else`, we can see that if the `Option` is `Some`, `f` won’t be\ncalled. If the `Option` is `None`, `f` will be called once. Because all\nclosures implement `FnOnce`, `unwrap_or_else` accepts all three kinds of\nclosures and is as flexible as it can be.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Closures", "heading_path": ["Closures", "Moving Captured Values Out of Closures"], "path": "ch13-01-closures.md", "url": "https://doc.rust-lang.org/book/ch13-01-closures.html#moving-captured-values-out-of-closures", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch13-01-closures.md#moving-captured-values-out-of-closures-15", "text": "The Rust Programming Language › Closures › Moving Captured Values Out of Closures\n\nNote: If what we want to do doesn’t require capturing a value from the\nenvironment, we can use the name of a function rather than a closure where we\nneed something that implements one of the `Fn` traits. For example, on an\n`Option>` value, we could call `unwrap_or_else(Vec::new)` to get a\nnew, empty vector if the value is `None`. The compiler automatically\nimplements whichever of the `Fn` traits is applicable for a function\ndefinition.\nNow let’s look at the standard library method `sort_by_key`, defined on slices,\nto see how that differs from `unwrap_or_else` and why `sort_by_key` uses\n`FnMut` instead of `FnOnce` for the trait bound. The closure gets one argument\nin the form of a reference to the current item in the slice being considered,\nand it returns a value of type `K` that can be ordered. This function is useful\nwhen you want to sort a slice by a particular attribute of each item. In\nListing 13-7, we have a list of `Rectangle` instances, and we use `sort_by_key`\nto order them by their `width` attribute from low to high.\nListing 13-7: Using `sort_by_key` to order rectangles by width (src/main.rs)\n```rust\n#[derive(Debug)]\nstruct Rectangle {\n width: u32,\n height: u32,\n}\n\nfn main() {\n let mut list = [\n Rectangle { width: 10, height: 1 },\n Rectangle { width: 3, height: 5 },\n Rectangle { width: 7, height: 12 },\n ];\n\n list.sort_by_key(|r| r.width);\n println!(\"{list:#?}\");\n}\n```\nThis code prints:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Closures", "heading_path": ["Closures", "Moving Captured Values Out of Closures"], "path": "ch13-01-closures.md", "url": "https://doc.rust-lang.org/book/ch13-01-closures.html#moving-captured-values-out-of-closures", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch13-01-closures.md#moving-captured-values-out-of-closures-16", "text": "The Rust Programming Language › Closures › Moving Captured Values Out of Closures\n\n```console\n$ cargo run\n Compiling rectangles v0.1.0 (file:///projects/rectangles)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.41s\n Running `target/debug/rectangles`\n[\n Rectangle {\n width: 3,\n height: 5,\n },\n Rectangle {\n width: 7,\n height: 12,\n },\n Rectangle {\n width: 10,\n height: 1,\n },\n]\n```\nThe reason `sort_by_key` is defined to take an `FnMut` closure is that it calls\nthe closure multiple times: once for each item in the slice. The closure `|r|\nr.width` doesn’t capture, mutate, or move anything out from its environment, so\nit meets the trait bound requirements.\nIn contrast, Listing 13-8 shows an example of a closure that implements just\nthe `FnOnce` trait, because it moves a value out of the environment. The\ncompiler won’t let us use this closure with `sort_by_key`.\nListing 13-8: Attempting to use an `FnOnce` closure with `sort_by_key` (src/main.rs)\n```rust,ignore,does_not_compile\n#[derive(Debug)]\nstruct Rectangle {\n width: u32,\n height: u32,\n}\n\nfn main() {\n let mut list = [\n Rectangle { width: 10, height: 1 },\n Rectangle { width: 3, height: 5 },\n Rectangle { width: 7, height: 12 },\n ];\n\n let mut sort_operations = vec![];\n let value = String::from(\"closure called\");\n\n list.sort_by_key(|r| {\n sort_operations.push(value);\n r.width\n });\n println!(\"{list:#?}\");\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Closures", "heading_path": ["Closures", "Moving Captured Values Out of Closures"], "path": "ch13-01-closures.md", "url": "https://doc.rust-lang.org/book/ch13-01-closures.html#moving-captured-values-out-of-closures", "has_code": true, "code_tags": ["console", "rust,ignore,does_not_compile"]}} {"id": "book/ch13-01-closures.md#moving-captured-values-out-of-closures-17", "text": "The Rust Programming Language › Closures › Moving Captured Values Out of Closures\n\nThis is a contrived, convoluted way (that doesn’t work) to try to count the\nnumber of times `sort_by_key` calls the closure when sorting `list`. This code\nattempts to do this counting by pushing `value`—a `String` from the closure’s\nenvironment—into the `sort_operations` vector. The closure captures `value` and\nthen moves `value` out of the closure by transferring ownership of `value` to\nthe `sort_operations` vector. This closure can be called once; trying to call\nit a second time wouldn’t work, because `value` would no longer be in the\nenvironment to be pushed into `sort_operations` again! Therefore, this closure\nonly implements `FnOnce`. When we try to compile this code, we get this error\nthat `value` can’t be moved out of the closure because the closure must\nimplement `FnMut`:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Closures", "heading_path": ["Closures", "Moving Captured Values Out of Closures"], "path": "ch13-01-closures.md", "url": "https://doc.rust-lang.org/book/ch13-01-closures.html#moving-captured-values-out-of-closures", "has_code": false, "code_tags": []}} {"id": "book/ch13-01-closures.md#moving-captured-values-out-of-closures-18", "text": "The Rust Programming Language › Closures › Moving Captured Values Out of Closures\n\n```console\n$ cargo run\n Compiling rectangles v0.1.0 (file:///projects/rectangles)\nerror[E0507]: cannot move out of `value`, a captured variable in an `FnMut` closure\n --> src/main.rs:18:30\n |\n15 | let value = String::from(\"closure called\");\n | ----- ------------------------------ move occurs because `value` has type `String`, which does not implement the `Copy` trait\n | |\n | captured outer variable\n16 |\n17 | list.sort_by_key(|r| {\n | --- captured by this `FnMut` closure\n18 | sort_operations.push(value);\n | ^^^^^ `value` is moved here\n |\nhelp: `Fn` and `FnMut` closures require captured values to be able to be consumed multiple times, but `FnOnce` closures may consume them only once\n --> /rustc/2d8144b7880597b6e6d3dfd63a9a9efae3f533d3/library/alloc/src/slice.rs:249:11\nhelp: consider cloning the value if the performance cost is acceptable\n |\n18 | sort_operations.push(value.clone());\n | ++++++++\n\nFor more information about this error, try `rustc --explain E0507`.\nerror: could not compile `rectangles` (bin \"rectangles\") due to 1 previous error\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Closures", "heading_path": ["Closures", "Moving Captured Values Out of Closures"], "path": "ch13-01-closures.md", "url": "https://doc.rust-lang.org/book/ch13-01-closures.html#moving-captured-values-out-of-closures", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch13-01-closures.md#moving-captured-values-out-of-closures-19", "text": "The Rust Programming Language › Closures › Moving Captured Values Out of Closures\n\nThe error points to the line in the closure body that moves `value` out of the\nenvironment. To fix this, we need to change the closure body so that it doesn’t\nmove values out of the environment. Keeping a counter in the environment and\nincrementing its value in the closure body is a more straightforward way to\ncount the number of times the closure is called. The closure in Listing 13-9\nworks with `sort_by_key` because it is only capturing a mutable reference to the\n`num_sort_operations` counter and can therefore be called more than once.\nListing 13-9: Using an `FnMut` closure with `sort_by_key` is allowed. (src/main.rs)\n```rust\n#[derive(Debug)]\nstruct Rectangle {\n width: u32,\n height: u32,\n}\n\nfn main() {\n let mut list = [\n Rectangle { width: 10, height: 1 },\n Rectangle { width: 3, height: 5 },\n Rectangle { width: 7, height: 12 },\n ];\n\n let mut num_sort_operations = 0;\n list.sort_by_key(|r| {\n num_sort_operations += 1;\n r.width\n });\n println!(\"{list:#?}, sorted in {num_sort_operations} operations\");\n}\n```\nThe `Fn` traits are important when defining or using functions or types that\nmake use of closures. In the next section, we’ll discuss iterators. Many\niterator methods take closure arguments, so keep these closure details in mind\nas we continue!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Closures", "heading_path": ["Closures", "Moving Captured Values Out of Closures"], "path": "ch13-01-closures.md", "url": "https://doc.rust-lang.org/book/ch13-01-closures.html#moving-captured-values-out-of-closures", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch13-02-iterators.md#processing-a-series-of-items-with-iterators-0", "text": "The Rust Programming Language › Processing a Series of Items with Iterators\n\nThe iterator pattern allows you to perform some task on a sequence of items in\nturn. An iterator is responsible for the logic of iterating over each item and\ndetermining when the sequence has finished. When you use iterators, you don’t\nhave to reimplement that logic yourself.\nIn Rust, iterators are _lazy_, meaning they have no effect until you call\nmethods that consume the iterator to use it up. For example, the code in\nListing 13-10 creates an iterator over the items in the vector `v1` by calling\nthe `iter` method defined on `Vec`. This code by itself doesn’t do anything\nuseful.\nListing 13-10: Creating an iterator (src/main.rs)\n```rust\n let v1 = vec![1, 2, 3];\n\n let v1_iter = v1.iter();\n```\nThe iterator is stored in the `v1_iter` variable. Once we’ve created an\niterator, we can use it in a variety of ways. In Listing 3-5, we iterated over\nan array using a `for` loop to execute some code on each of its items. Under\nthe hood, this implicitly created and then consumed an iterator, but we glossed\nover how exactly that works until now.\nIn the example in Listing 13-11, we separate the creation of the iterator from\nthe use of the iterator in the `for` loop. When the `for` loop is called using\nthe iterator in `v1_iter`, each element in the iterator is used in one\niteration of the loop, which prints out each value.\nListing 13-11: Using an iterator in a `for` loop (src/main.rs)\n```rust\n let v1 = vec![1, 2, 3];\n\n let v1_iter = v1.iter();\n\n for val in v1_iter {\n println!(\"Got: {val}\");\n }\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Processing a Series of Items with Iterators", "heading_path": ["Processing a Series of Items with Iterators"], "path": "ch13-02-iterators.md", "url": "https://doc.rust-lang.org/book/ch13-02-iterators.html#processing-a-series-of-items-with-iterators", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch13-02-iterators.md#processing-a-series-of-items-with-iterators-1", "text": "The Rust Programming Language › Processing a Series of Items with Iterators\n\nIn languages that don’t have iterators provided by their standard libraries,\nyou would likely write this same functionality by starting a variable at index\n0, using that variable to index into the vector to get a value, and\nincrementing the variable value in a loop until it reached the total number of\nitems in the vector.\nIterators handle all of that logic for you, cutting down on repetitive code you\ncould potentially mess up. Iterators give you more flexibility to use the same\nlogic with many different kinds of sequences, not just data structures you can\nindex into, like vectors. Let’s examine how iterators do that.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Processing a Series of Items with Iterators", "heading_path": ["Processing a Series of Items with Iterators"], "path": "ch13-02-iterators.md", "url": "https://doc.rust-lang.org/book/ch13-02-iterators.html#processing-a-series-of-items-with-iterators", "has_code": false, "code_tags": []}} {"id": "book/ch13-02-iterators.md#the-iterator-trait-and-the-next-method-2", "text": "The Rust Programming Language › Processing a Series of Items with Iterators › The `Iterator` Trait and the `next` Method\n\nAll iterators implement a trait named `Iterator` that is defined in the\nstandard library. The definition of the trait looks like this:\n```rust\npub trait Iterator {\n type Item;\n\n fn next(&mut self) -> Option;\n\n // methods with default implementations elided\n}\n```\nNotice that this definition uses some new syntax: `type Item` and `Self::Item`,\nwhich are defining an associated type with this trait. We’ll talk about\nassociated types in depth in Chapter 20. For now, all you need to know is that\nthis code says implementing the `Iterator` trait requires that you also define\nan `Item` type, and this `Item` type is used in the return type of the `next`\nmethod. In other words, the `Item` type will be the type returned from the\niterator.\nThe `Iterator` trait only requires implementors to define one method: the\n`next` method, which returns one item of the iterator at a time, wrapped in\n`Some`, and, when iteration is over, returns `None`.\nWe can call the `next` method on iterators directly; Listing 13-12 demonstrates\nwhat values are returned from repeated calls to `next` on the iterator created\nfrom the vector.\nListing 13-12: Calling the `next` method on an iterator (src/lib.rs)\n```rust,noplayground\n #[test]\n fn iterator_demonstration() {\n let v1 = vec![1, 2, 3];\n\n let mut v1_iter = v1.iter();\n\n assert_eq!(v1_iter.next(), Some(&1));\n assert_eq!(v1_iter.next(), Some(&2));\n assert_eq!(v1_iter.next(), Some(&3));\n assert_eq!(v1_iter.next(), None);\n }\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Processing a Series of Items with Iterators", "heading_path": ["Processing a Series of Items with Iterators", "The `Iterator` Trait and the `next` Method"], "path": "ch13-02-iterators.md", "url": "https://doc.rust-lang.org/book/ch13-02-iterators.html#the-iterator-trait-and-the-next-method", "has_code": true, "code_tags": ["rust", "rust,noplayground"]}} {"id": "book/ch13-02-iterators.md#the-iterator-trait-and-the-next-method-3", "text": "The Rust Programming Language › Processing a Series of Items with Iterators › The `Iterator` Trait and the `next` Method\n\nNote that we needed to make `v1_iter` mutable: Calling the `next` method on an\niterator changes internal state that the iterator uses to keep track of where\nit is in the sequence. In other words, this code _consumes_, or uses up, the\niterator. Each call to `next` eats up an item from the iterator. We didn’t need\nto make `v1_iter` mutable when we used a `for` loop, because the loop took\nownership of `v1_iter` and made it mutable behind the scenes.\nAlso note that the values we get from the calls to `next` are immutable\nreferences to the values in the vector. The `iter` method produces an iterator\nover immutable references. If we want to create an iterator that takes\nownership of `v1` and returns owned values, we can call `into_iter` instead of\n`iter`. Similarly, if we want to iterate over mutable references, we can call\n`iter_mut` instead of `iter`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Processing a Series of Items with Iterators", "heading_path": ["Processing a Series of Items with Iterators", "The `Iterator` Trait and the `next` Method"], "path": "ch13-02-iterators.md", "url": "https://doc.rust-lang.org/book/ch13-02-iterators.html#the-iterator-trait-and-the-next-method", "has_code": false, "code_tags": []}} {"id": "book/ch13-02-iterators.md#methods-that-consume-the-iterator-4", "text": "The Rust Programming Language › Processing a Series of Items with Iterators › Methods That Consume the Iterator\n\nThe `Iterator` trait has a number of different methods with default\nimplementations provided by the standard library; you can find out about these\nmethods by looking in the standard library API documentation for the `Iterator`\ntrait. Some of these methods call the `next` method in their definition, which\nis why you’re required to implement the `next` method when implementing the\n`Iterator` trait.\nMethods that call `next` are called _consuming adapters_ because calling them\nuses up the iterator. One example is the `sum` method, which takes ownership of\nthe iterator and iterates through the items by repeatedly calling `next`, thus\nconsuming the iterator. As it iterates through, it adds each item to a running\ntotal and returns the total when iteration is complete. Listing 13-13 has a\ntest illustrating a use of the `sum` method.\nListing 13-13: Calling the `sum` method to get the total of all items in the iterator (src/lib.rs)\n```rust,noplayground\n #[test]\n fn iterator_sum() {\n let v1 = vec![1, 2, 3];\n\n let v1_iter = v1.iter();\n\n let total: i32 = v1_iter.sum();\n\n assert_eq!(total, 6);\n }\n```\nWe aren’t allowed to use `v1_iter` after the call to `sum`, because `sum` takes\nownership of the iterator we call it on.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Processing a Series of Items with Iterators", "heading_path": ["Processing a Series of Items with Iterators", "Methods That Consume the Iterator"], "path": "ch13-02-iterators.md", "url": "https://doc.rust-lang.org/book/ch13-02-iterators.html#methods-that-consume-the-iterator", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch13-02-iterators.md#methods-that-produce-other-iterators-5", "text": "The Rust Programming Language › Processing a Series of Items with Iterators › Methods That Produce Other Iterators\n\n_Iterator adapters_ are methods defined on the `Iterator` trait that don’t\nconsume the iterator. Instead, they produce different iterators by changing\nsome aspect of the original iterator.\nListing 13-14 shows an example of calling the iterator adapter method `map`,\nwhich takes a closure to call on each item as the items are iterated through.\nThe `map` method returns a new iterator that produces the modified items. The\nclosure here creates a new iterator in which each item from the vector will be\nincremented by 1.\nListing 13-14: Calling the iterator adapter `map` to create a new iterator (src/main.rs)\n```rust,not_desired_behavior\n let v1: Vec = vec![1, 2, 3];\n\n v1.iter().map(|x| x + 1);\n```\nHowever, this code produces a warning:\n```console\n$ cargo run\n Compiling iterators v0.1.0 (file:///projects/iterators)\nwarning: unused `Map` that must be used\n --> src/main.rs:4:5\n |\n4 | v1.iter().map(|x| x + 1);\n | ^^^^^^^^^^^^^^^^^^^^^^^^\n |\n = note: iterators are lazy and do nothing unless consumed\n = note: `#[warn(unused_must_use)]` (part of `#[warn(unused)]`) on by default\nhelp: use `let _ = ...` to ignore the resulting value\n |\n4 | let _ = v1.iter().map(|x| x + 1);\n | +++++++\n\nwarning: `iterators` (bin \"iterators\") generated 1 warning\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.47s\n Running `target/debug/iterators`\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Processing a Series of Items with Iterators", "heading_path": ["Processing a Series of Items with Iterators", "Methods That Produce Other Iterators"], "path": "ch13-02-iterators.md", "url": "https://doc.rust-lang.org/book/ch13-02-iterators.html#methods-that-produce-other-iterators", "has_code": true, "code_tags": ["console", "rust,not_desired_behavior"]}} {"id": "book/ch13-02-iterators.md#methods-that-produce-other-iterators-6", "text": "The Rust Programming Language › Processing a Series of Items with Iterators › Methods That Produce Other Iterators\n\nThe code in Listing 13-14 doesn’t do anything; the closure we’ve specified\nnever gets called. The warning reminds us why: Iterator adapters are lazy, and\nwe need to consume the iterator here.\nTo fix this warning and consume the iterator, we’ll use the `collect` method,\nwhich we used with `env::args` in Listing 12-1. This method consumes the\niterator and collects the resultant values into a collection data type.\nIn Listing 13-15, we collect the results of iterating over the iterator that’s\nreturned from the call to `map` into a vector. This vector will end up\ncontaining each item from the original vector, incremented by 1.\nListing 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 (src/main.rs)\n```rust\n let v1: Vec = vec![1, 2, 3];\n\n let v2: Vec<_> = v1.iter().map(|x| x + 1).collect();\n\n assert_eq!(v2, vec![2, 3, 4]);\n```\nBecause `map` takes a closure, we can specify any operation we want to perform\non each item. This is a great example of how closures let you customize some\nbehavior while reusing the iteration behavior that the `Iterator` trait\nprovides.\nYou can chain multiple calls to iterator adapters to perform complex actions in\na readable way. But because all iterators are lazy, you have to call one of the\nconsuming adapter methods to get results from calls to iterator adapters.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Processing a Series of Items with Iterators", "heading_path": ["Processing a Series of Items with Iterators", "Methods That Produce Other Iterators"], "path": "ch13-02-iterators.md", "url": "https://doc.rust-lang.org/book/ch13-02-iterators.html#methods-that-produce-other-iterators", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch13-02-iterators.md#closures-that-capture-their-environment-7", "text": "The Rust Programming Language › Processing a Series of Items with Iterators › Closures That Capture Their Environment\n\nMany iterator adapters take closures as arguments, and commonly the closures\nwe’ll specify as arguments to iterator adapters will be closures that capture\ntheir environment.\nFor this example, we’ll use the `filter` method that takes a closure. The\nclosure gets an item from the iterator and returns a `bool`. If the closure\nreturns `true`, the value will be included in the iterator produced by\n`filter`. If the closure returns `false`, the value won’t be included.\nIn Listing 13-16, we use `filter` with a closure that captures the `shoe_size`\nvariable from its environment to iterate over a collection of `Shoe` struct\ninstances. It will return only shoes that are the specified size.\nListing 13-16: Using the `filter` method with a closure that captures `shoe_size` (src/lib.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Processing a Series of Items with Iterators", "heading_path": ["Processing a Series of Items with Iterators", "Closures That Capture Their Environment"], "path": "ch13-02-iterators.md", "url": "https://doc.rust-lang.org/book/ch13-02-iterators.html#closures-that-capture-their-environment", "has_code": false, "code_tags": []}} {"id": "book/ch13-02-iterators.md#closures-that-capture-their-environment-8", "text": "The Rust Programming Language › Processing a Series of Items with Iterators › Closures That Capture Their Environment\n\n```rust,noplayground\n#[derive(PartialEq, Debug)]\nstruct Shoe {\n size: u32,\n style: String,\n}\n\nfn shoes_in_size(shoes: Vec, shoe_size: u32) -> Vec {\n shoes.into_iter().filter(|s| s.size == shoe_size).collect()\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn filters_by_size() {\n let shoes = vec![\n Shoe {\n size: 10,\n style: String::from(\"sneaker\"),\n },\n Shoe {\n size: 13,\n style: String::from(\"sandal\"),\n },\n Shoe {\n size: 10,\n style: String::from(\"boot\"),\n },\n ];\n\n let in_my_size = shoes_in_size(shoes, 10);\n\n assert_eq!(\n in_my_size,\n vec![\n Shoe {\n size: 10,\n style: String::from(\"sneaker\")\n },\n Shoe {\n size: 10,\n style: String::from(\"boot\")\n },\n ]\n );\n }\n}\n```\nThe `shoes_in_size` function takes ownership of a vector of shoes and a shoe\nsize as parameters. It returns a vector containing only shoes of the specified\nsize.\nIn the body of `shoes_in_size`, we call `into_iter` to create an iterator that\ntakes ownership of the vector. Then, we call `filter` to adapt that iterator\ninto a new iterator that only contains elements for which the closure returns\n`true`.\nThe closure captures the `shoe_size` parameter from the environment and\ncompares the value with each shoe’s size, keeping only shoes of the size\nspecified. Finally, calling `collect` gathers the values returned by the\nadapted iterator into a vector that’s returned by the function.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Processing a Series of Items with Iterators", "heading_path": ["Processing a Series of Items with Iterators", "Closures That Capture Their Environment"], "path": "ch13-02-iterators.md", "url": "https://doc.rust-lang.org/book/ch13-02-iterators.html#closures-that-capture-their-environment", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch13-02-iterators.md#closures-that-capture-their-environment-9", "text": "The Rust Programming Language › Processing a Series of Items with Iterators › Closures That Capture Their Environment\n\nThe test shows that when we call `shoes_in_size`, we get back only shoes that\nhave the same size as the value we specified.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Processing a Series of Items with Iterators", "heading_path": ["Processing a Series of Items with Iterators", "Closures That Capture Their Environment"], "path": "ch13-02-iterators.md", "url": "https://doc.rust-lang.org/book/ch13-02-iterators.html#closures-that-capture-their-environment", "has_code": false, "code_tags": []}} {"id": "book/ch13-03-improving-our-io-project.md#improving-our-io-project-0", "text": "The Rust Programming Language › Improving Our I/O Project\n\nWith this new knowledge about iterators, we can improve the I/O project in\nChapter 12 by using iterators to make places in the code clearer and more\nconcise. Let’s look at how iterators can improve our implementation of the\n`Config::build` function and the `search` function.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Improving Our I/O Project", "heading_path": ["Improving Our I/O Project"], "path": "ch13-03-improving-our-io-project.md", "url": "https://doc.rust-lang.org/book/ch13-03-improving-our-io-project.html#improving-our-io-project", "has_code": false, "code_tags": []}} {"id": "book/ch13-03-improving-our-io-project.md#removing-a-clone-using-an-iterator-1", "text": "The Rust Programming Language › Improving Our I/O Project › Removing a `clone` Using an Iterator\n\nIn Listing 12-6, we added code that took a slice of `String` values and created\nan instance of the `Config` struct by indexing into the slice and cloning the\nvalues, allowing the `Config` struct to own those values. In Listing 13-17,\nwe’ve reproduced the implementation of the `Config::build` function as it was\nin Listing 12-23.\nListing 13-17: Reproduction of the `Config::build` function from Listing 12-23 (src/main.rs)\n```rust,ignore\nimpl Config {\n fn build(args: &[String]) -> Result {\n if args.len() < 3 {\n return Err(\"not enough arguments\");\n }\n\n let query = args[1].clone();\n let file_path = args[2].clone();\n\n let ignore_case = env::var(\"IGNORE_CASE\").is_ok();\n\n Ok(Config {\n query,\n file_path,\n ignore_case,\n })\n }\n}\n```\nAt the time, we said not to worry about the inefficient `clone` calls because\nwe would remove them in the future. Well, that time is now!\nWe needed `clone` here because we have a slice with `String` elements in the\nparameter `args`, but the `build` function doesn’t own `args`. To return\nownership of a `Config` instance, we had to clone the values from the `query`\nand `file_path` fields of `Config` so that the `Config` instance can own its\nvalues.\nWith our new knowledge about iterators, we can change the `build` function to\ntake ownership of an iterator as its argument instead of borrowing a slice.\nWe’ll use the iterator functionality instead of the code that checks the length\nof the slice and indexes into specific locations. This will clarify what the\n`Config::build` function is doing because the iterator will access the values.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Improving Our I/O Project", "heading_path": ["Improving Our I/O Project", "Removing a `clone` Using an Iterator"], "path": "ch13-03-improving-our-io-project.md", "url": "https://doc.rust-lang.org/book/ch13-03-improving-our-io-project.html#removing-a-clone-using-an-iterator", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch13-03-improving-our-io-project.md#using-the-returned-iterator-directly-2", "text": "The Rust Programming Language › Improving Our I/O Project › Removing a `clone` Using an Iterator › Using the Returned Iterator Directly\n\nOnce `Config::build` takes ownership of the iterator and stops using indexing\noperations that borrow, we can move the `String` values from the iterator into\n`Config` rather than calling `clone` and making a new allocation.\nOpen your I/O project’s _src/main.rs_ file, which should look like this:\nFilename: src/main.rs\n```rust,ignore\nfn main() {\n let args: Vec = env::args().collect();\n\n let config = Config::build(&args).unwrap_or_else(|err| {\n eprintln!(\"Problem parsing arguments: {err}\");\n process::exit(1);\n });\n\n // --snip--\n}\n```\nWe’ll first change the start of the `main` function that we had in Listing\n12-24 to the code in Listing 13-18, which this time uses an iterator. This\nwon’t compile until we update `Config::build` as well.\nListing 13-18: Passing the return value of `env::args` to `Config::build` (src/main.rs)\n```rust,ignore,does_not_compile\nfn main() {\n let config = Config::build(env::args()).unwrap_or_else(|err| {\n eprintln!(\"Problem parsing arguments: {err}\");\n process::exit(1);\n });\n\n // --snip--\n}\n```\nThe `env::args` function returns an iterator! Rather than collecting the\niterator values into a vector and then passing a slice to `Config::build`, now\nwe’re passing ownership of the iterator returned from `env::args` to\n`Config::build` directly.\nNext, we need to update the definition of `Config::build`. Let’s change the\nsignature of `Config::build` to look like Listing 13-19. This still won’t\ncompile, because we need to update the function body.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Improving Our I/O Project", "heading_path": ["Improving Our I/O Project", "Removing a `clone` Using an Iterator", "Using the Returned Iterator Directly"], "path": "ch13-03-improving-our-io-project.md", "url": "https://doc.rust-lang.org/book/ch13-03-improving-our-io-project.html#using-the-returned-iterator-directly", "has_code": true, "code_tags": ["rust,ignore", "rust,ignore,does_not_compile"]}} {"id": "book/ch13-03-improving-our-io-project.md#using-iterator-trait-methods-3", "text": "The Rust Programming Language › Improving Our I/O Project › Removing a `clone` Using an Iterator › Using `Iterator` Trait Methods\n\nListing 13-19: Updating the signature of `Config::build` to expect an iterator (src/main.rs)\n```rust,ignore,does_not_compile\nimpl Config {\n fn build(\n mut args: impl Iterator,\n ) -> Result {\n // --snip--\n```\nThe standard library documentation for the `env::args` function shows that the\ntype of the iterator it returns is `std::env::Args`, and that type implements\nthe `Iterator` trait and returns `String` values.\nWe’ve updated the signature of the `Config::build` function so that the\nparameter `args` has a generic type with the trait bounds `impl Iterator` instead of `&[String]`. This usage of the `impl Trait` syntax we\ndiscussed in the “Using Traits as Parameters”\nsection of Chapter 10 means that `args` can be any type that implements the\n`Iterator` trait and returns `String` items.\nBecause we’re taking ownership of `args` and we’ll be mutating `args` by\niterating over it, we can add the `mut` keyword into the specification of the\n`args` parameter to make it mutable.\nNext, we’ll fix the body of `Config::build`. Because `args` implements the\n`Iterator` trait, we know we can call the `next` method on it! Listing 13-20\nupdates the code from Listing 12-23 to use the `next` method.\nListing 13-20: Changing the body of `Config::build` to use iterator methods (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Improving Our I/O Project", "heading_path": ["Improving Our I/O Project", "Removing a `clone` Using an Iterator", "Using `Iterator` Trait Methods"], "path": "ch13-03-improving-our-io-project.md", "url": "https://doc.rust-lang.org/book/ch13-03-improving-our-io-project.html#using-iterator-trait-methods", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch13-03-improving-our-io-project.md#using-iterator-trait-methods-4", "text": "The Rust Programming Language › Improving Our I/O Project › Removing a `clone` Using an Iterator › Using `Iterator` Trait Methods\n\n```rust,ignore,noplayground\nimpl Config {\n fn build(\n mut args: impl Iterator,\n ) -> Result {\n args.next();\n\n let query = match args.next() {\n Some(arg) => arg,\n None => return Err(\"Didn't get a query string\"),\n };\n\n let file_path = match args.next() {\n Some(arg) => arg,\n None => return Err(\"Didn't get a file path\"),\n };\n\n let ignore_case = env::var(\"IGNORE_CASE\").is_ok();\n\n Ok(Config {\n query,\n file_path,\n ignore_case,\n })\n }\n}\n```\nRemember that the first value in the return value of `env::args` is the name of\nthe program. We want to ignore that and get to the next value, so first we call\n`next` and do nothing with the return value. Then, we call `next` to get the\nvalue we want to put in the `query` field of `Config`. If `next` returns\n`Some`, we use a `match` to extract the value. If it returns `None`, it means\nnot enough arguments were given, and we return early with an `Err` value. We do\nthe same thing for the `file_path` value.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Improving Our I/O Project", "heading_path": ["Improving Our I/O Project", "Removing a `clone` Using an Iterator", "Using `Iterator` Trait Methods"], "path": "ch13-03-improving-our-io-project.md", "url": "https://doc.rust-lang.org/book/ch13-03-improving-our-io-project.html#using-iterator-trait-methods", "has_code": true, "code_tags": ["rust,ignore,noplayground"]}} {"id": "book/ch13-03-improving-our-io-project.md#clarifying-code-with-iterator-adapters-5", "text": "The Rust Programming Language › Improving Our I/O Project › Clarifying Code with Iterator Adapters\n\nWe can also take advantage of iterators in the `search` function in our I/O\nproject, which is reproduced here in Listing 13-21 as it was in Listing 12-19.\nListing 13-21: The implementation of the `search` function from Listing 12-19 (src/lib.rs)\n```rust,ignore\npub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {\n let mut results = Vec::new();\n\n for line in contents.lines() {\n if line.contains(query) {\n results.push(line);\n }\n }\n\n results\n}\n```\nWe can write this code in a more concise way using iterator adapter methods.\nDoing so also lets us avoid having a mutable intermediate `results` vector. The\nfunctional programming style prefers to minimize the amount of mutable state to\nmake code clearer. Removing the mutable state might enable a future enhancement\nto make searching happen in parallel because we wouldn’t have to manage\nconcurrent access to the `results` vector. Listing 13-22 shows this change.\nListing 13-22: Using iterator adapter methods in the implementation of the `search` function (src/lib.rs)\n```rust,ignore\npub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {\n contents\n .lines()\n .filter(|line| line.contains(query))\n .collect()\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Improving Our I/O Project", "heading_path": ["Improving Our I/O Project", "Clarifying Code with Iterator Adapters"], "path": "ch13-03-improving-our-io-project.md", "url": "https://doc.rust-lang.org/book/ch13-03-improving-our-io-project.html#clarifying-code-with-iterator-adapters", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch13-03-improving-our-io-project.md#clarifying-code-with-iterator-adapters-6", "text": "The Rust Programming Language › Improving Our I/O Project › Clarifying Code with Iterator Adapters\n\nRecall that the purpose of the `search` function is to return all lines in\n`contents` that contain the `query`. Similar to the `filter` example in Listing\n13-16, this code uses the `filter` adapter to keep only the lines for which\n`line.contains(query)` returns `true`. We then collect the matching lines into\nanother vector with `collect`. Much simpler! Feel free to make the same change\nto use iterator methods in the `search_case_insensitive` function as well.\nFor a further improvement, return an iterator from the `search` function by\nremoving the call to `collect` and changing the return type to `impl\nIterator` so that the function becomes an iterator adapter.\nNote that you’ll also need to update the tests! Search through a large file\nusing your `minigrep` tool before and after making this change to observe the\ndifference in behavior. Before this change, the program won’t print any results\nuntil it has collected all of the results, but after the change, the results\nwill be printed as each matching line is found because the `for` loop in the\n`run` function is able to take advantage of the laziness of the iterator.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Improving Our I/O Project", "heading_path": ["Improving Our I/O Project", "Clarifying Code with Iterator Adapters"], "path": "ch13-03-improving-our-io-project.md", "url": "https://doc.rust-lang.org/book/ch13-03-improving-our-io-project.html#clarifying-code-with-iterator-adapters", "has_code": false, "code_tags": []}} {"id": "book/ch13-03-improving-our-io-project.md#choosing-between-loops-and-iterators-7", "text": "The Rust Programming Language › Improving Our I/O Project › Choosing Between Loops and Iterators\n\nThe next logical question is which style you should choose in your own code and\nwhy: the original implementation in Listing 13-21 or the version using\niterators in Listing 13-22 (assuming we’re collecting all the results before\nreturning them rather than returning the iterator). Most Rust programmers\nprefer to use the iterator style. It’s a bit tougher to get the hang of at\nfirst, but once you get a feel for the various iterator adapters and what they\ndo, iterators can be easier to understand. Instead of fiddling with the various\nbits of looping and building new vectors, the code focuses on the high-level\nobjective of the loop. This abstracts away some of the commonplace code so that\nit’s easier to see the concepts that are unique to this code, such as the\nfiltering condition each element in the iterator must pass.\nBut are the two implementations truly equivalent? The intuitive assumption\nmight be that the lower-level loop will be faster. Let’s talk about performance.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Improving Our I/O Project", "heading_path": ["Improving Our I/O Project", "Choosing Between Loops and Iterators"], "path": "ch13-03-improving-our-io-project.md", "url": "https://doc.rust-lang.org/book/ch13-03-improving-our-io-project.html#choosing-between-loops-and-iterators", "has_code": false, "code_tags": []}} {"id": "book/ch13-04-performance.md#performance-in-loops-vs-iterators-0", "text": "The Rust Programming Language › Performance in Loops vs. Iterators\n\nTo determine whether to use loops or iterators, you need to know which\nimplementation is faster: the version of the `search` function with an explicit\n`for` loop or the version with iterators.\nWe ran a benchmark by loading the entire contents of _The Adventures of\nSherlock Holmes_ by Sir Arthur Conan Doyle into a `String` and looking for the\nword _the_ in the contents. Here are the results of the benchmark on the\nversion of `search` using the `for` loop and the version using iterators:\n```text\ntest bench_search_for ... bench: 19,620,300 ns/iter (+/- 915,700)\ntest bench_search_iter ... bench: 19,234,900 ns/iter (+/- 657,200)\n```\nThe two implementations have similar performance! We won’t explain the\nbenchmark code here because the point is not to prove that the two versions\nare equivalent but to get a general sense of how these two implementations\ncompare performance-wise.\nFor a more comprehensive benchmark, you should check using various texts of\nvarious sizes as the `contents`, different words and words of different lengths\nas the `query`, and all kinds of other variations. The point is this:\nIterators, although a high-level abstraction, get compiled down to roughly the\nsame code as if you’d written the lower-level code yourself. Iterators are one\nof Rust’s _zero-cost abstractions_, by which we mean that using the abstraction\nimposes no additional runtime overhead. This is analogous to how Bjarne\nStroustrup, the original designer and implementor of C++, defines\nzero-overhead in his 2012 ETAPS keynote presentation “Foundations of C++”:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Performance in Loops vs. Iterators", "heading_path": ["Performance in Loops vs. Iterators"], "path": "ch13-04-performance.md", "url": "https://doc.rust-lang.org/book/ch13-04-performance.html#performance-in-loops-vs-iterators", "has_code": true, "code_tags": ["text"]}} {"id": "book/ch13-04-performance.md#performance-in-loops-vs-iterators-1", "text": "The Rust Programming Language › Performance in Loops vs. Iterators\n\nIn general, C++ implementations obey the zero-overhead principle: What you\ndon’t use, you don’t pay for. And further: What you do use, you couldn’t hand\ncode any better.\nIn many cases, Rust code using iterators compiles to the same assembly you’d\nwrite by hand. Optimizations such as loop unrolling and eliminating bounds\nchecking on array access apply and make the resultant code extremely efficient.\nNow that you know this, you can use iterators and closures without fear! They\nmake code seem like it’s higher level but don’t impose a runtime performance\npenalty for doing so.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Performance in Loops vs. Iterators", "heading_path": ["Performance in Loops vs. Iterators"], "path": "ch13-04-performance.md", "url": "https://doc.rust-lang.org/book/ch13-04-performance.html#performance-in-loops-vs-iterators", "has_code": false, "code_tags": []}} {"id": "book/ch13-04-performance.md#summary-2", "text": "The Rust Programming Language › Summary\n\nClosures and iterators are Rust features inspired by functional programming\nlanguage ideas. They contribute to Rust’s capability to clearly express\nhigh-level ideas at low-level performance. The implementations of closures and\niterators are such that runtime performance is not affected. This is part of\nRust’s goal to strive to provide zero-cost abstractions.\nNow that we’ve improved the expressiveness of our I/O project, let’s look at\nsome more features of `cargo` that will help us share the project with the\nworld.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Performance in Loops vs. Iterators", "heading_path": ["Summary"], "path": "ch13-04-performance.md", "url": "https://doc.rust-lang.org/book/ch13-04-performance.html#summary", "has_code": false, "code_tags": []}} {"id": "book/ch14-00-more-about-cargo.md#more-about-cargo-and-cratesio-0", "text": "The Rust Programming Language › More About Cargo and Crates.io\n\nSo far, we’ve used only the most basic features of Cargo to build, run, and\ntest our code, but it can do a lot more. In this chapter, we’ll discuss some of\nits other, more advanced features to show you how to do the following:\n- Customize your build through release profiles.\n- Publish libraries on crates.io.\n- Organize large projects with workspaces.\n- Install binaries from crates.io.\n- Extend Cargo using custom commands.\nCargo can do even more than the functionality we cover in this chapter, so for\na full explanation of all its features, see its documentation.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "More about Cargo and Crates.io", "heading_path": ["More About Cargo and Crates.io"], "path": "ch14-00-more-about-cargo.md", "url": "https://doc.rust-lang.org/book/ch14-00-more-about-cargo.html#more-about-cargo-and-cratesio", "has_code": false, "code_tags": []}} {"id": "book/ch14-01-release-profiles.md#customizing-builds-with-release-profiles-0", "text": "The Rust Programming Language › Customizing Builds with Release Profiles\n\nIn Rust, _release profiles_ are predefined, customizable profiles with\ndifferent configurations that allow a programmer to have more control over\nvarious options for compiling code. Each profile is configured independently of\nthe others.\nCargo has two main profiles: the `dev` profile Cargo uses when you run `cargo\nbuild`, and the `release` profile Cargo uses when you run `cargo build\n--release`. The `dev` profile is defined with good defaults for development,\nand the `release` profile has good defaults for release builds.\nThese profile names might be familiar from the output of your builds:\n```console\n$ cargo build\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.00s\n$ cargo build --release\n Finished `release` profile [optimized] target(s) in 0.32s\n```\nThe `dev` and `release` are these different profiles used by the compiler.\nCargo has default settings for each of the profiles that apply when you haven't\nexplicitly added any `[profile.*]` sections in the project’s _Cargo.toml_ file.\nBy adding `[profile.*]` sections for any profile you want to customize, you\noverride any subset of the default settings. For example, here are the default\nvalues for the `opt-level` setting for the `dev` and `release` profiles:\nFilename: Cargo.toml\n```toml\n[profile.dev]\nopt-level = 0\n\n[profile.release]\nopt-level = 3\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Customizing Builds with Release Profiles", "heading_path": ["Customizing Builds with Release Profiles"], "path": "ch14-01-release-profiles.md", "url": "https://doc.rust-lang.org/book/ch14-01-release-profiles.html#customizing-builds-with-release-profiles", "has_code": true, "code_tags": ["console", "toml"]}} {"id": "book/ch14-01-release-profiles.md#customizing-builds-with-release-profiles-1", "text": "The Rust Programming Language › Customizing Builds with Release Profiles\n\nThe `opt-level` setting controls the number of optimizations Rust will apply to\nyour code, with a range of 0 to 3. Applying more optimizations extends\ncompiling time, so if you’re in development and compiling your code often,\nyou’ll want fewer optimizations to compile faster even if the resultant code\nruns slower. The default `opt-level` for `dev` is therefore `0`. When you’re\nready to release your code, it’s best to spend more time compiling. You’ll only\ncompile in release mode once, but you’ll run the compiled program many times,\nso release mode trades longer compile time for code that runs faster. That is\nwhy the default `opt-level` for the `release` profile is `3`.\nYou can override a default setting by adding a different value for it in\n_Cargo.toml_. For example, if we want to use optimization level 1 in the\ndevelopment profile, we can add these two lines to our project’s _Cargo.toml_\nfile:\nFilename: Cargo.toml\n```toml\n[profile.dev]\nopt-level = 1\n```\nThis code overrides the default setting of `0`. Now when we run `cargo build`,\nCargo will use the defaults for the `dev` profile plus our customization to\n`opt-level`. Because we set `opt-level` to `1`, Cargo will apply more\noptimizations than the default, but not as many as in a release build.\nFor the full list of configuration options and defaults for each profile, see\nCargo’s documentation.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Customizing Builds with Release Profiles", "heading_path": ["Customizing Builds with Release Profiles"], "path": "ch14-01-release-profiles.md", "url": "https://doc.rust-lang.org/book/ch14-01-release-profiles.html#customizing-builds-with-release-profiles", "has_code": true, "code_tags": ["toml"]}} {"id": "book/ch14-02-publishing-to-crates-io.md#publishing-a-crate-to-cratesio-0", "text": "The Rust Programming Language › Publishing a Crate to Crates.io\n\nWe’ve used packages from crates.io as\ndependencies of our project, but you can also share your code with other people\nby publishing your own packages. The crate registry at\ncrates.io distributes the source code of\nyour packages, so it primarily hosts code that is open source.\nRust and Cargo have features that make your published package easier for people\nto find and use. We’ll talk about some of these features next and then explain\nhow to publish a package.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Publishing a Crate to Crates.io", "heading_path": ["Publishing a Crate to Crates.io"], "path": "ch14-02-publishing-to-crates-io.md", "url": "https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html#publishing-a-crate-to-cratesio", "has_code": false, "code_tags": []}} {"id": "book/ch14-02-publishing-to-crates-io.md#making-useful-documentation-comments-1", "text": "The Rust Programming Language › Publishing a Crate to Crates.io › Making Useful Documentation Comments\n\nAccurately documenting your packages will help other users know how and when to\nuse them, so it’s worth investing the time to write documentation. In Chapter\n3, we discussed how to comment Rust code using two slashes, `//`. Rust also has\na particular kind of comment for documentation, known conveniently as a\n_documentation comment_, that will generate HTML documentation. The HTML\ndisplays the contents of documentation comments for public API items intended\nfor programmers interested in knowing how to _use_ your crate as opposed to how\nyour crate is _implemented_.\nDocumentation comments use three slashes, `///`, instead of two and support\nMarkdown notation for formatting the text. Place documentation comments just\nbefore the item they’re documenting. Listing 14-1 shows documentation comments\nfor an `add_one` function in a crate named `my_crate`.\nListing 14-1: A documentation comment for a function (src/lib.rs)\n```rust,ignore\n/// Adds one to the number given.\n///\n/// # Examples\n///\n/// ```\n/// let arg = 5;\n/// let answer = my_crate::add_one(arg);\n///\n/// assert_eq!(6, answer);\n/// ```\npub fn add_one(x: i32) -> i32 {\n x + 1\n}\n```\nHere, we give a description of what the `add_one` function does, start a\nsection with the heading `Examples`, and then provide code that demonstrates\nhow to use the `add_one` function. We can generate the HTML documentation from\nthis documentation comment by running `cargo doc`. This command runs the\n`rustdoc` tool distributed with Rust and puts the generated HTML documentation\nin the _target/doc_ directory.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Publishing a Crate to Crates.io", "heading_path": ["Publishing a Crate to Crates.io", "Making Useful Documentation Comments"], "path": "ch14-02-publishing-to-crates-io.md", "url": "https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html#making-useful-documentation-comments", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch14-02-publishing-to-crates-io.md#documentation-comments-as-tests-2", "text": "The Rust Programming Language › Publishing a Crate to Crates.io › Making Useful Documentation Comments › Documentation Comments as Tests\n\nFor convenience, running `cargo doc --open` will build the HTML for your\ncurrent crate’s documentation (as well as the documentation for all of your\ncrate’s dependencies) and open the result in a web browser. Navigate to the\n`add_one` function and you’ll see how the text in the documentation comments is\nrendered, as shown in Figure 14-1.\n\"Rendered\nFigure 14-1: The HTML documentation for the `add_one`\nfunction\nWe used the `# Examples` Markdown heading in Listing 14-1 to create a section\nin the HTML with the title “Examples.” Here are some other sections that crate\nauthors commonly use in their documentation:\n- **Panics**: These are the scenarios in which the function being documented\n could panic. Callers of the function who don’t want their programs to panic\n should make sure they don’t call the function in these situations.\n- **Errors**: If the function returns a `Result`, describing the kinds of\n errors that might occur and what conditions might cause those errors to be\n returned can be helpful to callers so that they can write code to handle the\n different kinds of errors in different ways.\n- **Safety**: If the function is `unsafe` to call (we discuss unsafety in\n Chapter 20), there should be a section explaining why the function is unsafe\n and covering the invariants that the function expects callers to uphold.\nMost documentation comments don’t need all of these sections, but this is a\ngood checklist to remind you of the aspects of your code users will be\ninterested in knowing about.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Publishing a Crate to Crates.io", "heading_path": ["Publishing a Crate to Crates.io", "Making Useful Documentation Comments", "Documentation Comments as Tests"], "path": "ch14-02-publishing-to-crates-io.md", "url": "https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html#documentation-comments-as-tests", "has_code": false, "code_tags": []}} {"id": "book/ch14-02-publishing-to-crates-io.md#contained-item-comments-3", "text": "The Rust Programming Language › Publishing a Crate to Crates.io › Making Useful Documentation Comments › Contained Item Comments\n\nAdding example code blocks in your documentation comments can help demonstrate\nhow to use your library and has an additional bonus: Running `cargo test` will\nrun the code examples in your documentation as tests! Nothing is better than\ndocumentation with examples. But nothing is worse than examples that don’t work\nbecause the code has changed since the documentation was written. If we run\n`cargo test` with the documentation for the `add_one` function from Listing\n14-1, we will see a section in the test results that looks like this:\n```text\n Doc-tests my_crate\n\nrunning 1 test\ntest src/lib.rs - add_one (line 5) ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.27s\n```\nNow, if we change either the function or the example so that the `assert_eq!`\nin the example panics, and run `cargo test` again, we’ll see that the doc tests\ncatch that the example and the code are out of sync with each other!\nThe style of doc comment `//!` adds documentation to the item that *contains*\nthe comments rather than to the items *following* the comments. We typically\nuse these doc comments inside the crate root file (_src/lib.rs_ by convention)\nor inside a module to document the crate or the module as a whole.\nFor example, to add documentation that describes the purpose of the `my_crate`\ncrate that contains the `add_one` function, we add documentation comments that\nstart with `//!` to the beginning of the _src/lib.rs_ file, as shown in Listing\n14-2.\nListing 14-2: The documentation for the `my_crate` crate as a whole (src/lib.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Publishing a Crate to Crates.io", "heading_path": ["Publishing a Crate to Crates.io", "Making Useful Documentation Comments", "Contained Item Comments"], "path": "ch14-02-publishing-to-crates-io.md", "url": "https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html#contained-item-comments", "has_code": true, "code_tags": ["text"]}} {"id": "book/ch14-02-publishing-to-crates-io.md#contained-item-comments-4", "text": "The Rust Programming Language › Publishing a Crate to Crates.io › Making Useful Documentation Comments › Contained Item Comments\n\n```rust,ignore\n//! # My Crate\n//!\n//! `my_crate` is a collection of utilities to make performing certain\n//! calculations more convenient.\n\n/// Adds one to the number given.\n// --snip--\n```\nNotice there isn’t any code after the last line that begins with `//!`. Because\nwe started the comments with `//!` instead of `///`, we’re documenting the item\nthat contains this comment rather than an item that follows this comment. In\nthis case, that item is the _src/lib.rs_ file, which is the crate root. These\ncomments describe the entire crate.\nWhen we run `cargo doc --open`, these comments will display on the front page\nof the documentation for `my_crate` above the list of public items in the\ncrate, as shown in Figure 14-2.\nDocumentation comments within items are useful for describing crates and\nmodules especially. Use them to explain the overall purpose of the container to\nhelp your users understand the crate’s organization.\n\"Rendered\nFigure 14-2: The rendered documentation for `my_crate`,\nincluding the comment describing the crate as a whole", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Publishing a Crate to Crates.io", "heading_path": ["Publishing a Crate to Crates.io", "Making Useful Documentation Comments", "Contained Item Comments"], "path": "ch14-02-publishing-to-crates-io.md", "url": "https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html#contained-item-comments", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch14-02-publishing-to-crates-io.md#exporting-a-convenient-public-api-5", "text": "The Rust Programming Language › Publishing a Crate to Crates.io › Exporting a Convenient Public API\n\nThe structure of your public API is a major consideration when publishing a\ncrate. People who use your crate are less familiar with the structure than you\nare and might have difficulty finding the pieces they want to use if your crate\nhas a large module hierarchy.\nIn Chapter 7, we covered how to make items public using the `pub` keyword, and\nhow to bring items into a scope with the `use` keyword. However, the structure\nthat makes sense to you while you’re developing a crate might not be very\nconvenient for your users. You might want to organize your structs in a\nhierarchy containing multiple levels, but then people who want to use a type\nyou’ve defined deep in the hierarchy might have trouble finding out that type\nexists. They might also be annoyed at having to enter `use\nmy_crate::some_module::another_module::UsefulType;` rather than `use\nmy_crate::UsefulType;`.\nThe good news is that if the structure _isn’t_ convenient for others to use\nfrom another library, you don’t have to rearrange your internal organization:\nInstead, you can re-export items to make a public structure that’s different\nfrom your private structure by using `pub use`. *Re-exporting* takes a public\nitem in one location and makes it public in another location, as if it were\ndefined in the other location instead.\nFor example, say we made a library named `art` for modeling artistic concepts.\nWithin this library are two modules: a `kinds` module containing two enums\nnamed `PrimaryColor` and `SecondaryColor` and a `utils` module containing a\nfunction named `mix`, as shown in Listing 14-3.\nListing 14-3: An `art` library with items organized into `kinds` and `utils` modules (src/lib.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Publishing a Crate to Crates.io", "heading_path": ["Publishing a Crate to Crates.io", "Exporting a Convenient Public API"], "path": "ch14-02-publishing-to-crates-io.md", "url": "https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html#exporting-a-convenient-public-api", "has_code": false, "code_tags": []}} {"id": "book/ch14-02-publishing-to-crates-io.md#exporting-a-convenient-public-api-6", "text": "The Rust Programming Language › Publishing a Crate to Crates.io › Exporting a Convenient Public API\n\n```rust,noplayground,test_harness\n//! # Art\n//!\n//! A library for modeling artistic concepts.\n\npub mod kinds {\n /// The primary colors according to the RYB color model.\n pub enum PrimaryColor {\n Red,\n Yellow,\n Blue,\n }\n\n /// The secondary colors according to the RYB color model.\n pub enum SecondaryColor {\n Orange,\n Green,\n Purple,\n }\n}\n\npub mod utils {\n use crate::kinds::*;\n\n /// Combines two primary colors in equal amounts to create\n /// a secondary color.\n pub fn mix(c1: PrimaryColor, c2: PrimaryColor) -> SecondaryColor {\n // --snip--\n }\n}\n```\nFigure 14-3 shows what the front page of the documentation for this crate\ngenerated by `cargo doc` would look like.\n\"Rendered\nFigure 14-3: The front page of the documentation for `art`\nthat lists the `kinds` and `utils` modules\nNote that the `PrimaryColor` and `SecondaryColor` types aren’t listed on the\nfront page, nor is the `mix` function. We have to click `kinds` and `utils` to\nsee them.\nAnother crate that depends on this library would need `use` statements that\nbring the items from `art` into scope, specifying the module structure that’s\ncurrently defined. Listing 14-4 shows an example of a crate that uses the\n`PrimaryColor` and `mix` items from the `art` crate.\nListing 14-4: A crate using the `art` crate’s items with its internal structure exported (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Publishing a Crate to Crates.io", "heading_path": ["Publishing a Crate to Crates.io", "Exporting a Convenient Public API"], "path": "ch14-02-publishing-to-crates-io.md", "url": "https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html#exporting-a-convenient-public-api", "has_code": true, "code_tags": ["rust,noplayground,test_harness"]}} {"id": "book/ch14-02-publishing-to-crates-io.md#exporting-a-convenient-public-api-7", "text": "The Rust Programming Language › Publishing a Crate to Crates.io › Exporting a Convenient Public API\n\n```rust,ignore\nuse art::kinds::PrimaryColor;\nuse art::utils::mix;\n\nfn main() {\n let red = PrimaryColor::Red;\n let yellow = PrimaryColor::Yellow;\n mix(red, yellow);\n}\n```\nThe author of the code in Listing 14-4, which uses the `art` crate, had to\nfigure out that `PrimaryColor` is in the `kinds` module and `mix` is in the\n`utils` module. The module structure of the `art` crate is more relevant to\ndevelopers working on the `art` crate than to those using it. The internal\nstructure doesn’t contain any useful information for someone trying to\nunderstand how to use the `art` crate, but rather causes confusion because\ndevelopers who use it have to figure out where to look, and must specify the\nmodule names in the `use` statements.\nTo remove the internal organization from the public API, we can modify the\n`art` crate code in Listing 14-3 to add `pub use` statements to re-export the\nitems at the top level, as shown in Listing 14-5.\nListing 14-5: Adding `pub use` statements to re-export items (src/lib.rs)\n```rust,ignore\n//! # Art\n//!\n//! A library for modeling artistic concepts.\n\npub use self::kinds::PrimaryColor;\npub use self::kinds::SecondaryColor;\npub use self::utils::mix;\n\npub mod kinds {\n // --snip--\n}\n\npub mod utils {\n // --snip--\n}\n```\nThe API documentation that `cargo doc` generates for this crate will now list\nand link re-exports on the front page, as shown in Figure 14-4, making the\n`PrimaryColor` and `SecondaryColor` types and the `mix` function easier to find.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Publishing a Crate to Crates.io", "heading_path": ["Publishing a Crate to Crates.io", "Exporting a Convenient Public API"], "path": "ch14-02-publishing-to-crates-io.md", "url": "https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html#exporting-a-convenient-public-api", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch14-02-publishing-to-crates-io.md#exporting-a-convenient-public-api-8", "text": "The Rust Programming Language › Publishing a Crate to Crates.io › Exporting a Convenient Public API\n\n\"Rendered\nFigure 14-4: The front page of the documentation for `art`\nthat lists the re-exports\nThe `art` crate users can still see and use the internal structure from Listing\n14-3 as demonstrated in Listing 14-4, or they can use the more convenient\nstructure in Listing 14-5, as shown in Listing 14-6.\nListing 14-6: A program using the re-exported items from the `art` crate (src/main.rs)\n```rust,ignore\nuse art::PrimaryColor;\nuse art::mix;\n\nfn main() {\n // --snip--\n}\n```\nIn cases where there are many nested modules, re-exporting the types at the top\nlevel with `pub use` can make a significant difference in the experience of\npeople who use the crate. Another common use of `pub use` is to re-export\ndefinitions of a dependency in the current crate to make that crate's\ndefinitions part of your crate’s public API.\nCreating a useful public API structure is more an art than a science, and you\ncan iterate to find the API that works best for your users. Choosing `pub use`\ngives you flexibility in how you structure your crate internally and decouples\nthat internal structure from what you present to your users. Look at some of\nthe code of crates you’ve installed to see if their internal structure differs\nfrom their public API.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Publishing a Crate to Crates.io", "heading_path": ["Publishing a Crate to Crates.io", "Exporting a Convenient Public API"], "path": "ch14-02-publishing-to-crates-io.md", "url": "https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html#exporting-a-convenient-public-api", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch14-02-publishing-to-crates-io.md#setting-up-a-cratesio-account-9", "text": "The Rust Programming Language › Publishing a Crate to Crates.io › Setting Up a Crates.io Account\n\nBefore you can publish any crates, you need to create an account on\ncrates.io and get an API token. To do so,\nvisit the home page at crates.io and log\nin via a GitHub account. (The GitHub account is currently a requirement, but\nthe site might support other ways of creating an account in the future.) Once\nyou’re logged in, visit your account settings at\nhttps://crates.io/me/ and retrieve your\nAPI key. Then, run the `cargo login` command and paste your API key when prompted, like this:\n```console\n$ cargo login\nabcdefghijklmnopqrstuvwxyz012345\n```\nThis command will inform Cargo of your API token and store it locally in\n_~/.cargo/credentials.toml_. Note that this token is a secret: Do not share\nit with anyone else. If you do share it with anyone for any reason, you should\nrevoke it and generate a new token on crates.io\n.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Publishing a Crate to Crates.io", "heading_path": ["Publishing a Crate to Crates.io", "Setting Up a Crates.io Account"], "path": "ch14-02-publishing-to-crates-io.md", "url": "https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html#setting-up-a-cratesio-account", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch14-02-publishing-to-crates-io.md#adding-metadata-to-a-new-crate-10", "text": "The Rust Programming Language › Publishing a Crate to Crates.io › Adding Metadata to a New Crate\n\nLet’s say you have a crate you want to publish. Before publishing, you’ll need\nto add some metadata in the `[package]` section of the crate’s _Cargo.toml_\nfile.\nYour crate will need a unique name. While you’re working on a crate locally,\nyou can name a crate whatever you’d like. However, crate names on\ncrates.io are allocated on a first-come,\nfirst-served basis. Once a crate name is taken, no one else can publish a crate\nwith that name. Before attempting to publish a crate, search for the name you\nwant to use. If the name has been used, you will need to find another name and\nedit the `name` field in the _Cargo.toml_ file under the `[package]` section to\nuse the new name for publishing, like so:\nFilename: Cargo.toml\n```toml\n[package]\nname = \"guessing_game\"\n```\nEven if you’ve chosen a unique name, when you run `cargo publish` to publish\nthe crate at this point, you’ll get a warning and then an error:\n```console\n$ cargo publish\n Updating crates.io index\nwarning: manifest has no description, license, license-file, documentation, homepage or repository.\nSee https://doc.rust-lang.org/cargo/reference/manifest.html#package-metadata for more info.\n--snip--\nerror: failed to publish to registry at https://crates.io\n\nCaused by:\n the remote server responded with an error (status 400 Bad Request): missing or empty metadata fields: description, license. Please see https://doc.rust-lang.org/cargo/reference/manifest.html for more information on configuring these fields\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Publishing a Crate to Crates.io", "heading_path": ["Publishing a Crate to Crates.io", "Adding Metadata to a New Crate"], "path": "ch14-02-publishing-to-crates-io.md", "url": "https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html#adding-metadata-to-a-new-crate", "has_code": true, "code_tags": ["console", "toml"]}} {"id": "book/ch14-02-publishing-to-crates-io.md#adding-metadata-to-a-new-crate-11", "text": "The Rust Programming Language › Publishing a Crate to Crates.io › Adding Metadata to a New Crate\n\nThis results in an error because you’re missing some crucial information: A\ndescription and license are required so that people will know what your crate\ndoes and under what terms they can use it. In _Cargo.toml_, add a description\nthat's just a sentence or two, because it will appear with your crate in search\nresults. For the `license` field, you need to give a _license identifier\nvalue_. The Linux Foundation’s Software Package Data Exchange (SPDX)\nlists the identifiers you can use for this value. For example, to specify that\nyou’ve licensed your crate using the MIT License, add the `MIT` identifier:\nFilename: Cargo.toml\n```toml\n[package]\nname = \"guessing_game\"\nlicense = \"MIT\"\n```\nIf you want to use a license that doesn’t appear in the SPDX, you need to place\nthe text of that license in a file, include the file in your project, and then\nuse `license-file` to specify the name of that file instead of using the\n`license` key.\nGuidance on which license is appropriate for your project is beyond the scope\nof this book. Many people in the Rust community license their projects in the\nsame way as Rust by using a dual license of `MIT OR Apache-2.0`. This practice\ndemonstrates that you can also specify multiple license identifiers separated\nby `OR` to have multiple licenses for your project.\nWith a unique name, the version, your description, and a license added, the\n_Cargo.toml_ file for a project that is ready to publish might look like this:\nFilename: Cargo.toml", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Publishing a Crate to Crates.io", "heading_path": ["Publishing a Crate to Crates.io", "Adding Metadata to a New Crate"], "path": "ch14-02-publishing-to-crates-io.md", "url": "https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html#adding-metadata-to-a-new-crate", "has_code": true, "code_tags": ["toml"]}} {"id": "book/ch14-02-publishing-to-crates-io.md#adding-metadata-to-a-new-crate-12", "text": "The Rust Programming Language › Publishing a Crate to Crates.io › Adding Metadata to a New Crate\n\n```toml\n[package]\nname = \"guessing_game\"\nversion = \"0.1.0\"\nedition = \"2024\"\ndescription = \"A fun game where you guess what number the computer has chosen.\"\nlicense = \"MIT OR Apache-2.0\"\n\n[dependencies]\n```\nCargo’s documentation describes other\nmetadata you can specify to ensure that others can discover and use your crate\nmore easily.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Publishing a Crate to Crates.io", "heading_path": ["Publishing a Crate to Crates.io", "Adding Metadata to a New Crate"], "path": "ch14-02-publishing-to-crates-io.md", "url": "https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html#adding-metadata-to-a-new-crate", "has_code": true, "code_tags": ["toml"]}} {"id": "book/ch14-02-publishing-to-crates-io.md#publishing-to-cratesio-13", "text": "The Rust Programming Language › Publishing a Crate to Crates.io › Publishing to Crates.io\n\nNow that you’ve created an account, saved your API token, chosen a name for\nyour crate, and specified the required metadata, you’re ready to publish!\nPublishing a crate uploads a specific version to\ncrates.io for others to use.\nBe careful, because a publish is _permanent_. The version can never be\noverwritten, and the code cannot be deleted except in certain circumstances.\nOne major goal of Crates.io is to act as a permanent archive of code so that\nbuilds of all projects that depend on crates from\ncrates.io will continue to work. Allowing\nversion deletions would make fulfilling that goal impossible. However, there is\nno limit to the number of crate versions you can publish.\nRun the `cargo publish` command again. It should succeed now:\n```console\n$ cargo publish\n Updating crates.io index\n Packaging guessing_game v0.1.0 (file:///projects/guessing_game)\n Packaged 6 files, 1.2KiB (895.0B compressed)\n Verifying guessing_game v0.1.0 (file:///projects/guessing_game)\n Compiling guessing_game v0.1.0\n(file:///projects/guessing_game/target/package/guessing_game-0.1.0)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.19s\n Uploading guessing_game v0.1.0 (file:///projects/guessing_game)\n Uploaded guessing_game v0.1.0 to registry `crates-io`\nnote: waiting for `guessing_game v0.1.0` to be available at registry\n`crates-io`.\nYou may press ctrl-c to skip waiting; the crate should be available shortly.\n Published guessing_game v0.1.0 at registry `crates-io`\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Publishing a Crate to Crates.io", "heading_path": ["Publishing a Crate to Crates.io", "Publishing to Crates.io"], "path": "ch14-02-publishing-to-crates-io.md", "url": "https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html#publishing-to-cratesio", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch14-02-publishing-to-crates-io.md#publishing-to-cratesio-14", "text": "The Rust Programming Language › Publishing a Crate to Crates.io › Publishing to Crates.io\n\nCongratulations! You’ve now shared your code with the Rust community, and\nanyone can easily add your crate as a dependency of their project.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Publishing a Crate to Crates.io", "heading_path": ["Publishing a Crate to Crates.io", "Publishing to Crates.io"], "path": "ch14-02-publishing-to-crates-io.md", "url": "https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html#publishing-to-cratesio", "has_code": false, "code_tags": []}} {"id": "book/ch14-02-publishing-to-crates-io.md#publishing-a-new-version-of-an-existing-crate-15", "text": "The Rust Programming Language › Publishing a Crate to Crates.io › Publishing a New Version of an Existing Crate\n\nWhen you’ve made changes to your crate and are ready to release a new version,\nyou change the `version` value specified in your _Cargo.toml_ file and\nrepublish. Use the Semantic Versioning rules to decide what an\nappropriate next version number is, based on the kinds of changes you’ve made.\nThen, run `cargo publish` to upload the new version.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Publishing a Crate to Crates.io", "heading_path": ["Publishing a Crate to Crates.io", "Publishing a New Version of an Existing Crate"], "path": "ch14-02-publishing-to-crates-io.md", "url": "https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html#publishing-a-new-version-of-an-existing-crate", "has_code": false, "code_tags": []}} {"id": "book/ch14-02-publishing-to-crates-io.md#deprecating-versions-from-cratesio-16", "text": "The Rust Programming Language › Publishing a Crate to Crates.io › Deprecating Versions from Crates.io\n\nAlthough you can’t remove previous versions of a crate, you can prevent any\nfuture projects from adding them as a new dependency. This is useful when a\ncrate version is broken for one reason or another. In such situations, Cargo\nsupports yanking a crate version.\n_Yanking_ a version prevents new projects from depending on that version while\nallowing all existing projects that depend on it to continue. Essentially, a\nyank means that all projects with a _Cargo.lock_ will not break, and any future\n_Cargo.lock_ files generated will not use the yanked version.\nTo yank a version of a crate, in the directory of the crate that you’ve\npreviously published, run `cargo yank` and specify which version you want to\nyank. For example, if we’ve published a crate named `guessing_game` version\n1.0.1 and we want to yank it, then we’d run the following in the project\ndirectory for `guessing_game`:\n```console\n$ cargo yank --vers 1.0.1\n Updating crates.io index\n Yank guessing_game@1.0.1\n```\nBy adding `--undo` to the command, you can also undo a yank and allow projects\nto start depending on a version again:\n```console\n$ cargo yank --vers 1.0.1 --undo\n Updating crates.io index\n Unyank guessing_game@1.0.1\n```\nA yank _does not_ delete any code. It cannot, for example, delete accidentally\nuploaded secrets. If that happens, you must reset those secrets immediately.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Publishing a Crate to Crates.io", "heading_path": ["Publishing a Crate to Crates.io", "Deprecating Versions from Crates.io"], "path": "ch14-02-publishing-to-crates-io.md", "url": "https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html#deprecating-versions-from-cratesio", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch14-03-cargo-workspaces.md#cargo-workspaces-0", "text": "The Rust Programming Language › Cargo Workspaces\n\nIn Chapter 12, we built a package that included a binary crate and a library\ncrate. As your project develops, you might find that the library crate\ncontinues to get bigger and you want to split your package further into\nmultiple library crates. Cargo offers a feature called _workspaces_ that can\nhelp manage multiple related packages that are developed in tandem.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Cargo Workspaces", "heading_path": ["Cargo Workspaces"], "path": "ch14-03-cargo-workspaces.md", "url": "https://doc.rust-lang.org/book/ch14-03-cargo-workspaces.html#cargo-workspaces", "has_code": false, "code_tags": []}} {"id": "book/ch14-03-cargo-workspaces.md#creating-a-workspace-1", "text": "The Rust Programming Language › Cargo Workspaces › Creating a Workspace\n\nA _workspace_ is a set of packages that share the same _Cargo.lock_ and output\ndirectory. Let’s make a project using a workspace—we’ll use trivial code so\nthat we can concentrate on the structure of the workspace. There are multiple\nways to structure a workspace, so we'll just show one common way. We’ll have a\nworkspace containing a binary and two libraries. The binary, which will provide\nthe main functionality, will depend on the two libraries. One library will\nprovide an `add_one` function and the other library an `add_two` function.\nThese three crates will be part of the same workspace. We’ll start by creating\na new directory for the workspace:\n```console\n$ mkdir add\n$ cd add\n```\nNext, in the _add_ directory, we create the _Cargo.toml_ file that will\nconfigure the entire workspace. This file won’t have a `[package]` section.\nInstead, it will start with a `[workspace]` section that will allow us to add\nmembers to the workspace. We also make a point to use the latest and greatest\nversion of Cargo’s resolver algorithm in our workspace by setting the\n`resolver` value to `\"3\"`:\nFilename: Cargo.toml\n```toml\n[workspace]\nresolver = \"3\"\n```\nNext, we’ll create the `adder` binary crate by running `cargo new` within the\n_add_ directory:\n```console\n$ cargo new adder\n Created binary (application) `adder` package\n Adding `adder` as member of workspace at `file:///projects/add`\n```\nRunning `cargo new` inside a workspace also automatically adds the newly created\npackage to the `members` key in the `[workspace]` definition in the workspace\n_Cargo.toml_, like this:\n```toml\n[workspace]\nresolver = \"3\"\nmembers = [\"adder\"]\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Cargo Workspaces", "heading_path": ["Cargo Workspaces", "Creating a Workspace"], "path": "ch14-03-cargo-workspaces.md", "url": "https://doc.rust-lang.org/book/ch14-03-cargo-workspaces.html#creating-a-workspace", "has_code": true, "code_tags": ["console", "toml"]}} {"id": "book/ch14-03-cargo-workspaces.md#creating-a-workspace-2", "text": "The Rust Programming Language › Cargo Workspaces › Creating a Workspace\n\nAt this point, we can build the workspace by running `cargo build`. The files\nin your _add_ directory should look like this:\n```text\n├── Cargo.lock\n├── Cargo.toml\n├── adder\n│ ├── Cargo.toml\n│ └── src\n│ └── main.rs\n└── target\n```\nThe workspace has one _target_ directory at the top level that the compiled\nartifacts will be placed into; the `adder` package doesn’t have its own\n_target_ directory. Even if we were to run `cargo build` from inside the\n_adder_ directory, the compiled artifacts would still end up in _add/target_\nrather than _add/adder/target_. Cargo structures the _target_ directory in a\nworkspace like this because the crates in a workspace are meant to depend on\neach other. If each crate had its own _target_ directory, each crate would have\nto recompile each of the other crates in the workspace to place the artifacts\nin its own _target_ directory. By sharing one _target_ directory, the crates\ncan avoid unnecessary rebuilding.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Cargo Workspaces", "heading_path": ["Cargo Workspaces", "Creating a Workspace"], "path": "ch14-03-cargo-workspaces.md", "url": "https://doc.rust-lang.org/book/ch14-03-cargo-workspaces.html#creating-a-workspace", "has_code": true, "code_tags": ["text"]}} {"id": "book/ch14-03-cargo-workspaces.md#creating-the-second-package-in-the-workspace-3", "text": "The Rust Programming Language › Cargo Workspaces › Creating the Second Package in the Workspace\n\nNext, let’s create another member package in the workspace and call it\n`add_one`. Generate a new library crate named `add_one`:\n```console\n$ cargo new add_one --lib\n Created library `add_one` package\n Adding `add_one` as member of workspace at `file:///projects/add`\n```\nThe top-level _Cargo.toml_ will now include the _add_one_ path in the `members`\nlist:\nFilename: Cargo.toml\n```toml\n[workspace]\nresolver = \"3\"\nmembers = [\"adder\", \"add_one\"]\n```\nYour _add_ directory should now have these directories and files:\n```text\n├── Cargo.lock\n├── Cargo.toml\n├── add_one\n│ ├── Cargo.toml\n│ └── src\n│ └── lib.rs\n├── adder\n│ ├── Cargo.toml\n│ └── src\n│ └── main.rs\n└── target\n```\nIn the _add_one/src/lib.rs_ file, let’s add an `add_one` function:\nFilename: add_one/src/lib.rs\n```rust,noplayground\npub fn add_one(x: i32) -> i32 {\n x + 1\n}\n```\nNow we can have the `adder` package with our binary depend on the `add_one`\npackage that has our library. First, we’ll need to add a path dependency on\n`add_one` to _adder/Cargo.toml_.\nFilename: adder/Cargo.toml\n```toml\n[dependencies]\nadd_one = { path = \"../add_one\" }\n```\nCargo doesn’t assume that crates in a workspace will depend on each other, so\nwe need to be explicit about the dependency relationships.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Cargo Workspaces", "heading_path": ["Cargo Workspaces", "Creating the Second Package in the Workspace"], "path": "ch14-03-cargo-workspaces.md", "url": "https://doc.rust-lang.org/book/ch14-03-cargo-workspaces.html#creating-the-second-package-in-the-workspace", "has_code": true, "code_tags": ["console", "rust,noplayground", "text", "toml"]}} {"id": "book/ch14-03-cargo-workspaces.md#creating-the-second-package-in-the-workspace-4", "text": "The Rust Programming Language › Cargo Workspaces › Creating the Second Package in the Workspace\n\nNext, let’s use the `add_one` function (from the `add_one` crate) in the\n`adder` crate. Open the _adder/src/main.rs_ file and change the `main`\nfunction to call the `add_one` function, as in Listing 14-7.\nListing 14-7: Using the `add_one` library crate from the `adder` crate (adder/src/main.rs)\n```rust,ignore\nfn main() {\n let num = 10;\n println!(\"Hello, world! {num} plus one is {}!\", add_one::add_one(num));\n}\n```\nLet’s build the workspace by running `cargo build` in the top-level _add_\ndirectory!\n```console\n$ cargo build\n Compiling add_one v0.1.0 (file:///projects/add/add_one)\n Compiling adder v0.1.0 (file:///projects/add/adder)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.22s\n```\nTo run the binary crate from the _add_ directory, we can specify which package\nin the workspace we want to run by using the `-p` argument and the package name\nwith `cargo run`:\n```console\n$ cargo run -p adder\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.00s\n Running `target/debug/adder`\nHello, world! 10 plus one is 11!\n```\nThis runs the code in _adder/src/main.rs_, which depends on the `add_one` crate.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Cargo Workspaces", "heading_path": ["Cargo Workspaces", "Creating the Second Package in the Workspace"], "path": "ch14-03-cargo-workspaces.md", "url": "https://doc.rust-lang.org/book/ch14-03-cargo-workspaces.html#creating-the-second-package-in-the-workspace", "has_code": true, "code_tags": ["console", "rust,ignore"]}} {"id": "book/ch14-03-cargo-workspaces.md#depending-on-an-external-package-5", "text": "The Rust Programming Language › Cargo Workspaces › Depending on an External Package\n\nNotice that the workspace has only one _Cargo.lock_ file at the top level,\nrather than having a _Cargo.lock_ in each crate’s directory. This ensures that\nall crates are using the same version of all dependencies. If we add the `rand`\npackage to the _adder/Cargo.toml_ and _add_one/Cargo.toml_ files, Cargo will\nresolve both of those to one version of `rand` and record that in the one\n_Cargo.lock_. Making all crates in the workspace use the same dependencies\nmeans the crates will always be compatible with each other. Let’s add the\n`rand` crate to the `[dependencies]` section in the _add_one/Cargo.toml_ file\nso that we can use the `rand` crate in the `add_one` crate:\nFilename: add_one/Cargo.toml\n```toml\n[dependencies]\nrand = \"0.10.1\"\n```\nWe can now add `use rand;` to the _add_one/src/lib.rs_ file, and building the\nwhole workspace by running `cargo build` in the _add_ directory will bring in\nand compile the `rand` crate. We will get one warning because we aren’t\nreferring to the `rand` we brought into scope:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Cargo Workspaces", "heading_path": ["Cargo Workspaces", "Depending on an External Package"], "path": "ch14-03-cargo-workspaces.md", "url": "https://doc.rust-lang.org/book/ch14-03-cargo-workspaces.html#depending-on-an-external-package", "has_code": true, "code_tags": ["toml"]}} {"id": "book/ch14-03-cargo-workspaces.md#depending-on-an-external-package-6", "text": "The Rust Programming Language › Cargo Workspaces › Depending on an External Package\n\n```console\n$ cargo build\n Updating crates.io index\n Downloaded rand v0.10.1\n --snip--\n Compiling rand v0.10.1\n Compiling add_one v0.1.0 (file:///projects/add/add_one)\nwarning: unused import: `rand`\n --> add_one/src/lib.rs:1:5\n |\n1 | use rand;\n | ^^^^\n |\n = note: `#[warn(unused_imports)]` (part of `#[warn(unused)]`) on by default\n\nwarning: `add_one` (lib) generated 1 warning (run `cargo fix --lib -p add_one` to apply 1 suggestion)\n Compiling adder v0.1.0 (file:///projects/add/adder)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.95s\n```\nThe top-level _Cargo.lock_ now contains information about the dependency of\n`add_one` on `rand`. However, even though `rand` is used somewhere in the\nworkspace, we can’t use it in other crates in the workspace unless we add\n`rand` to their _Cargo.toml_ files as well. For example, if we add `use rand;`\nto the _adder/src/main.rs_ file for the `adder` package, we’ll get an error:\n```console\n$ cargo build\n --snip--\n Compiling adder v0.1.0 (file:///projects/add/adder)\nerror[E0432]: unresolved import `rand`\n --> adder/src/main.rs:2:5\n |\n2 | use rand;\n | ^^^^ no external crate `rand`\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Cargo Workspaces", "heading_path": ["Cargo Workspaces", "Depending on an External Package"], "path": "ch14-03-cargo-workspaces.md", "url": "https://doc.rust-lang.org/book/ch14-03-cargo-workspaces.html#depending-on-an-external-package", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch14-03-cargo-workspaces.md#depending-on-an-external-package-7", "text": "The Rust Programming Language › Cargo Workspaces › Depending on an External Package\n\nTo fix this, edit the _Cargo.toml_ file for the `adder` package and indicate\nthat `rand` is a dependency for it as well. Building the `adder` package will\nadd `rand` to the list of dependencies for `adder` in _Cargo.lock_, but no\nadditional copies of `rand` will be downloaded. Cargo will ensure that every\ncrate in every package in the workspace using the `rand` package will use the\nsame version as long as they specify compatible versions of `rand`, saving us\nspace and ensuring that the crates in the workspace will be compatible with\neach other.\nIf crates in the workspace specify incompatible versions of the same\ndependency, Cargo will resolve each of them but will still try to resolve as\nfew versions as possible.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Cargo Workspaces", "heading_path": ["Cargo Workspaces", "Depending on an External Package"], "path": "ch14-03-cargo-workspaces.md", "url": "https://doc.rust-lang.org/book/ch14-03-cargo-workspaces.html#depending-on-an-external-package", "has_code": false, "code_tags": []}} {"id": "book/ch14-03-cargo-workspaces.md#adding-a-test-to-a-workspace-8", "text": "The Rust Programming Language › Cargo Workspaces › Adding a Test to a Workspace\n\nFor another enhancement, let’s add a test of the `add_one::add_one` function\nwithin the `add_one` crate:\nFilename: add_one/src/lib.rs\n```rust,noplayground\npub fn add_one(x: i32) -> i32 {\n x + 1\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn it_works() {\n assert_eq!(3, add_one(2));\n }\n}\n```\nNow run `cargo test` in the top-level _add_ directory. Running `cargo test` in\na workspace structured like this one will run the tests for all the crates in\nthe workspace:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Cargo Workspaces", "heading_path": ["Cargo Workspaces", "Adding a Test to a Workspace"], "path": "ch14-03-cargo-workspaces.md", "url": "https://doc.rust-lang.org/book/ch14-03-cargo-workspaces.html#adding-a-test-to-a-workspace", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch14-03-cargo-workspaces.md#adding-a-test-to-a-workspace-9", "text": "The Rust Programming Language › Cargo Workspaces › Adding a Test to a Workspace\n\n```console\n$ cargo test\n Compiling add_one v0.1.0 (file:///projects/add/add_one)\n Compiling adder v0.1.0 (file:///projects/add/adder)\n Finished `test` profile [unoptimized + debuginfo] target(s) in 0.20s\n Running unittests src/lib.rs (target/debug/deps/add_one-93c49ee75dc46543)\n\nrunning 1 test\ntest tests::it_works ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n Running unittests src/main.rs (target/debug/deps/adder-3a47283c568d2b6a)\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n Doc-tests add_one\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n```\nThe first section of the output shows that the `it_works` test in the `add_one`\ncrate passed. The next section shows that zero tests were found in the `adder`\ncrate, and then the last section shows that zero documentation tests were found\nin the `add_one` crate.\nWe can also run tests for one particular crate in a workspace from the\ntop-level directory by using the `-p` flag and specifying the name of the crate\nwe want to test:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Cargo Workspaces", "heading_path": ["Cargo Workspaces", "Adding a Test to a Workspace"], "path": "ch14-03-cargo-workspaces.md", "url": "https://doc.rust-lang.org/book/ch14-03-cargo-workspaces.html#adding-a-test-to-a-workspace", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch14-03-cargo-workspaces.md#adding-a-test-to-a-workspace-10", "text": "The Rust Programming Language › Cargo Workspaces › Adding a Test to a Workspace\n\n```console\n$ cargo test -p add_one\n Finished `test` profile [unoptimized + debuginfo] target(s) in 0.00s\n Running unittests src/lib.rs (target/debug/deps/add_one-93c49ee75dc46543)\n\nrunning 1 test\ntest tests::it_works ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\n Doc-tests add_one\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n```\nThis output shows `cargo test` only ran the tests for the `add_one` crate and\ndidn’t run the `adder` crate tests.\nIf you publish the crates in the workspace to\ncrates.io, each crate in the workspace\nwill need to be published separately. Like `cargo test`, we can publish a\nparticular crate in our workspace by using the `-p` flag and specifying the\nname of the crate we want to publish.\nFor additional practice, add an `add_two` crate to this workspace in a similar\nway as the `add_one` crate!\nAs your project grows, consider using a workspace: It enables you to work with\nsmaller, easier-to-understand components than one big blob of code.\nFurthermore, keeping the crates in a workspace can make coordination between\ncrates easier if they are often changed at the same time.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Cargo Workspaces", "heading_path": ["Cargo Workspaces", "Adding a Test to a Workspace"], "path": "ch14-03-cargo-workspaces.md", "url": "https://doc.rust-lang.org/book/ch14-03-cargo-workspaces.html#adding-a-test-to-a-workspace", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch14-04-installing-binaries.md#installing-binaries-with-cargo-install-0", "text": "The Rust Programming Language › Installing Binaries with `cargo install`\n\nThe `cargo install` command allows you to install and use binary crates\nlocally. This isn’t intended to replace system packages; it’s meant to be a\nconvenient way for Rust developers to install tools that others have shared on\ncrates.io. Note that you can only install\npackages that have binary targets. A _binary target_ is the runnable program\nthat is created if the crate has a _src/main.rs_ file or another file specified\nas a binary, as opposed to a library target that isn’t runnable on its own but\nis suitable for including within other programs. Usually, crates have\ninformation in the README file about whether a crate is a library, has a\nbinary target, or both.\nAll binaries installed with `cargo install` are stored in the installation\nroot’s _bin_ folder. If you installed Rust using _rustup.rs_ and don’t have any\ncustom configurations, this directory will be *$HOME/.cargo/bin*. Ensure that\nthis directory is in your `$PATH` to be able to run programs you’ve installed\nwith `cargo install`.\nFor example, in Chapter 12 we mentioned that there’s a Rust implementation of\nthe `grep` tool called `ripgrep` for searching files. To install `ripgrep`, we\ncan run the following:\n```console\n$ cargo install ripgrep\n Updating crates.io index\n Downloaded ripgrep v14.1.1\n Downloaded 1 crate (213.6 KB) in 0.40s\n Installing ripgrep v14.1.1\n--snip--\n Compiling grep v0.3.2\n Finished `release` profile [optimized + debuginfo] target(s) in 6.73s\n Installing ~/.cargo/bin/rg\n Installed package `ripgrep v14.1.1` (executable `rg`)\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Installing Binaries with `cargo install`", "heading_path": ["Installing Binaries with `cargo install`"], "path": "ch14-04-installing-binaries.md", "url": "https://doc.rust-lang.org/book/ch14-04-installing-binaries.html#installing-binaries-with-cargo-install", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch14-04-installing-binaries.md#installing-binaries-with-cargo-install-1", "text": "The Rust Programming Language › Installing Binaries with `cargo install`\n\nThe second-to-last line of the output shows the location and the name of the\ninstalled binary, which in the case of `ripgrep` is `rg`. As long as the\ninstallation directory is in your `$PATH`, as mentioned previously, you can\nthen run `rg --help` and start using a faster, Rustier tool for searching files!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Installing Binaries with `cargo install`", "heading_path": ["Installing Binaries with `cargo install`"], "path": "ch14-04-installing-binaries.md", "url": "https://doc.rust-lang.org/book/ch14-04-installing-binaries.html#installing-binaries-with-cargo-install", "has_code": false, "code_tags": []}} {"id": "book/ch14-05-extending-cargo.md#extending-cargo-with-custom-commands-0", "text": "The Rust Programming Language › Extending Cargo with Custom Commands\n\nCargo is designed so that you can extend it with new subcommands without having\nto modify it. If a binary in your `$PATH` is named `cargo-something`, you can\nrun it as if it were a Cargo subcommand by running `cargo something`. Custom\ncommands like this are also listed when you run `cargo --list`. Being able to\nuse `cargo install` to install extensions and then run them just like the\nbuilt-in Cargo tools is a super-convenient benefit of Cargo’s design!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Extending Cargo with Custom Commands", "heading_path": ["Extending Cargo with Custom Commands"], "path": "ch14-05-extending-cargo.md", "url": "https://doc.rust-lang.org/book/ch14-05-extending-cargo.html#extending-cargo-with-custom-commands", "has_code": false, "code_tags": []}} {"id": "book/ch14-05-extending-cargo.md#summary-1", "text": "The Rust Programming Language › Summary\n\nSharing code with Cargo and crates.io is\npart of what makes the Rust ecosystem useful for many different tasks. Rust’s\nstandard library is small and stable, but crates are easy to share, use, and\nimprove on a timeline different from that of the language. Don’t be shy about\nsharing code that’s useful to you on crates.io\n; it’s likely that it will be useful to someone else as well!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Extending Cargo with Custom Commands", "heading_path": ["Summary"], "path": "ch14-05-extending-cargo.md", "url": "https://doc.rust-lang.org/book/ch14-05-extending-cargo.html#summary", "has_code": false, "code_tags": []}} {"id": "book/ch15-00-smart-pointers.md#smart-pointers-0", "text": "The Rust Programming Language › Smart Pointers\n\nA pointer is a general concept for a variable that contains an address in\nmemory. This address refers to, or “points at,” some other data. The most\ncommon kind of pointer in Rust is a reference, which you learned about in\nChapter 4. References are indicated by the `&` symbol and borrow the value they\npoint to. They don’t have any special capabilities other than referring to\ndata, and they have no overhead.\n_Smart pointers_, on the other hand, are data structures that act like a\npointer but also have additional metadata and capabilities. The concept of\nsmart pointers isn’t unique to Rust: Smart pointers originated in C++ and exist\nin other languages as well. Rust has a variety of smart pointers defined in the\nstandard library that provide functionality beyond that provided by references.\nTo explore the general concept, we’ll look at a couple of different examples of\nsmart pointers, including a _reference counting_ smart pointer type. This\npointer enables you to allow data to have multiple owners by keeping track of\nthe number of owners and, when no owners remain, cleaning up the data.\nIn Rust, with its concept of ownership and borrowing, there is an additional\ndifference between references and smart pointers: While references only borrow\ndata, in many cases smart pointers _own_ the data they point to.\nSmart pointers are usually implemented using structs. Unlike an ordinary\nstruct, smart pointers implement the `Deref` and `Drop` traits. The `Deref`\ntrait allows an instance of the smart pointer struct to behave like a reference\nso that you can write your code to work with either references or smart\npointers. The `Drop` trait allows you to customize the code that’s run when an\ninstance of the smart pointer goes out of scope. In this chapter, we’ll discuss\nboth of these traits and demonstrate why they’re important to smart pointers.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Smart Pointers", "heading_path": ["Smart Pointers"], "path": "ch15-00-smart-pointers.md", "url": "https://doc.rust-lang.org/book/ch15-00-smart-pointers.html#smart-pointers", "has_code": false, "code_tags": []}} {"id": "book/ch15-00-smart-pointers.md#smart-pointers-1", "text": "The Rust Programming Language › Smart Pointers\n\nGiven that the smart pointer pattern is a general design pattern used\nfrequently in Rust, this chapter won’t cover every existing smart pointer. Many\nlibraries have their own smart pointers, and you can even write your own. We’ll\ncover the most common smart pointers in the standard library:\n- `Box`, for allocating values on the heap\n- `Rc`, a reference counting type that enables multiple ownership\n- `Ref` and `RefMut`, accessed through `RefCell`, a type that enforces\n the borrowing rules at runtime instead of compile time\nIn addition, we’ll cover the _interior mutability_ pattern where an immutable\ntype exposes an API for mutating an interior value. We’ll also discuss\nreference cycles: how they can leak memory and how to prevent them.\nLet’s dive in!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Smart Pointers", "heading_path": ["Smart Pointers"], "path": "ch15-00-smart-pointers.md", "url": "https://doc.rust-lang.org/book/ch15-00-smart-pointers.html#smart-pointers", "has_code": false, "code_tags": []}} {"id": "book/ch15-01-box.md#using-boxt-to-point-to-data-on-the-heap-0", "text": "The Rust Programming Language › Using `Box` to Point to Data on the Heap\n\nThe most straightforward smart pointer is a box, whose type is written\n`Box`. _Boxes_ allow you to store data on the heap rather than the stack.\nWhat remains on the stack is the pointer to the heap data. Refer to Chapter 4\nto review the difference between the stack and the heap.\nBoxes don’t have performance overhead, other than storing their data on the\nheap instead of on the stack. But they don’t have many extra capabilities\neither. You’ll use them most often in these situations:\n- When you have a type whose size can’t be known at compile time, and you want\n to use a value of that type in a context that requires an exact size\n- When you have a large amount of data, and you want to transfer ownership but\n ensure that the data won’t be copied when you do so\n- When you want to own a value, and you care only that it’s a type that\n implements a particular trait rather than being of a specific type\nWe’ll demonstrate the first situation in “Enabling Recursive Types with\nBoxes”. In the second\ncase, transferring ownership of a large amount of data can take a long time\nbecause the data is copied around on the stack. To improve performance in this\nsituation, we can store the large amount of data on the heap in a box. Then,\nonly the small amount of pointer data is copied around on the stack, while the\ndata it references stays in one place on the heap. The third case is known as a\n_trait object_, and “Using Trait Objects to Abstract over Shared\nBehavior” in Chapter 18 is devoted to that\ntopic. So, what you learn here you’ll apply again in that section!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using `Box` to Point to Data on the Heap", "heading_path": ["Using `Box` to Point to Data on the Heap"], "path": "ch15-01-box.md", "url": "https://doc.rust-lang.org/book/ch15-01-box.html#using-boxt-to-point-to-data-on-the-heap", "has_code": false, "code_tags": []}} {"id": "book/ch15-01-box.md#storing-data-on-the-heap-1", "text": "The Rust Programming Language › Using `Box` to Point to Data on the Heap › Storing Data on the Heap\n\nBefore we discuss the heap storage use case for `Box`, we’ll cover the\nsyntax and how to interact with values stored within a `Box`.\nListing 15-1 shows how to use a box to store an `i32` value on the heap.\nListing 15-1: Storing an `i32` value on the heap using a box (src/main.rs)\n```rust\nfn main() {\n let b = Box::new(5);\n println!(\"b = {b}\");\n}\n```\nWe define the variable `b` to have the value of a `Box` that points to the\nvalue `5`, which is allocated on the heap. This program will print `b = 5`; in\nthis case, we can access the data in the box similarly to how we would if this\ndata were on the stack. Just like any owned value, when a box goes out of\nscope, as `b` does at the end of `main`, it will be deallocated. The\ndeallocation happens both for the box (stored on the stack) and the data it\npoints to (stored on the heap).\nPutting a single value on the heap isn’t very useful, so you won’t use boxes by\nthemselves in this way very often. Having values like a single `i32` on the\nstack, where they’re stored by default, is more appropriate in the majority of\nsituations. Let’s look at a case where boxes allow us to define types that we\nwouldn’t be allowed to define if we didn’t have boxes.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using `Box` to Point to Data on the Heap", "heading_path": ["Using `Box` to Point to Data on the Heap", "Storing Data on the Heap"], "path": "ch15-01-box.md", "url": "https://doc.rust-lang.org/book/ch15-01-box.html#storing-data-on-the-heap", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch15-01-box.md#understanding-the-cons-list-2", "text": "The Rust Programming Language › Using `Box` to Point to Data on the Heap › Enabling Recursive Types with Boxes › Understanding the Cons List\n\nA value of a _recursive type_ can have another value of the same type as part of\nitself. Recursive types pose an issue because Rust needs to know at compile time\nhow much space a type takes up. However, the nesting of values of recursive\ntypes could theoretically continue infinitely, so Rust can’t know how much space\nthe value needs. Because boxes have a known size, we can enable recursive types\nby inserting a box in the recursive type definition.\nAs an example of a recursive type, let’s explore the cons list. This is a data\ntype commonly found in functional programming languages. The cons list type\nwe’ll define is straightforward except for the recursion; therefore, the\nconcepts in the example we’ll work with will be useful anytime you get into\nmore complex situations involving recursive types.\nA _cons list_ is a data structure that comes from the Lisp programming language\nand its dialects, is made up of nested pairs, and is the Lisp version of a\nlinked list. Its name comes from the `cons` function (short for _construct\nfunction_) in Lisp that constructs a new pair from its two arguments. By\ncalling `cons` on a pair consisting of a value and another pair, we can\nconstruct cons lists made up of recursive pairs.\nFor example, here’s a pseudocode representation of a cons list containing the\nlist `1, 2, 3` with each pair in parentheses:\n```text\n(1, (2, (3, Nil)))\n```\nEach item in a cons list contains two elements: the value of the current item\nand of the next item. The last item in the list contains only a value called\n`Nil` without a next item. A cons list is produced by recursively calling the\n`cons` function. The canonical name to denote the base case of the recursion is\n`Nil`. Note that this is not the same as the “null” or “nil” concept discussed\nin Chapter 6, which is an invalid or absent value.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using `Box` to Point to Data on the Heap", "heading_path": ["Using `Box` to Point to Data on the Heap", "Enabling Recursive Types with Boxes", "Understanding the Cons List"], "path": "ch15-01-box.md", "url": "https://doc.rust-lang.org/book/ch15-01-box.html#understanding-the-cons-list", "has_code": true, "code_tags": ["text"]}} {"id": "book/ch15-01-box.md#understanding-the-cons-list-3", "text": "The Rust Programming Language › Using `Box` to Point to Data on the Heap › Enabling Recursive Types with Boxes › Understanding the Cons List\n\nThe cons list isn’t a commonly used data structure in Rust. Most of the time\nwhen you have a list of items in Rust, `Vec` is a better choice to use.\nOther, more complex recursive data types _are_ useful in various situations,\nbut by starting with the cons list in this chapter, we can explore how boxes\nlet us define a recursive data type without much distraction.\nListing 15-2 contains an enum definition for a cons list. Note that this code\nwon’t compile yet, because the `List` type doesn’t have a known size, which\nwe’ll demonstrate.\nListing 15-2: The first attempt at defining an enum to represent a cons list data structure of `i32` values (src/main.rs)\n```rust,ignore,does_not_compile\nenum List {\n Cons(i32, List),\n Nil,\n}\n```\nNote: We’re implementing a cons list that holds only `i32` values for the\npurposes of this example. We could have implemented it using generics, as we\ndiscussed in Chapter 10, to define a cons list type that could store values of\nany type.\nUsing the `List` type to store the list `1, 2, 3` would look like the code in\nListing 15-3.\nListing 15-3: Using the `List` enum to store the list `1, 2, 3` (src/main.rs)\n```rust,ignore,does_not_compile\n// --snip--\n\nuse crate::List::{Cons, Nil};\n\nfn main() {\n let list = Cons(1, Cons(2, Cons(3, Nil)));\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using `Box` to Point to Data on the Heap", "heading_path": ["Using `Box` to Point to Data on the Heap", "Enabling Recursive Types with Boxes", "Understanding the Cons List"], "path": "ch15-01-box.md", "url": "https://doc.rust-lang.org/book/ch15-01-box.html#understanding-the-cons-list", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch15-01-box.md#computing-the-size-of-a-non-recursive-type-4", "text": "The Rust Programming Language › Using `Box` to Point to Data on the Heap › Enabling Recursive Types with Boxes › Computing the Size of a Non-Recursive Type\n\nThe first `Cons` value holds `1` and another `List` value. This `List` value is\nanother `Cons` value that holds `2` and another `List` value. This `List` value\nis one more `Cons` value that holds `3` and a `List` value, which is finally\n`Nil`, the non-recursive variant that signals the end of the list.\nIf we try to compile the code in Listing 15-3, we get the error shown in\nListing 15-4.\nListing 15-4: The error we get when attempting to define a recursive enum\n```console\n$ cargo run\n Compiling cons-list v0.1.0 (file:///projects/cons-list)\nerror[E0072]: recursive type `List` has infinite size\n --> src/main.rs:1:1\n |\n1 | enum List {\n | ^^^^^^^^^\n2 | Cons(i32, List),\n | ---- recursive without indirection\n |\nhelp: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to break the cycle\n |\n2 | Cons(i32, Box),\n | ++++ +\n\nFor more information about this error, try `rustc --explain E0072`.\nerror: could not compile `cons-list` (bin \"cons-list\") due to 1 previous error\n```\nThe error shows this type “has infinite size.” The reason is that we’ve defined\n`List` with a variant that is recursive: It holds another value of itself\ndirectly. As a result, Rust can’t figure out how much space it needs to store a\n`List` value. Let’s break down why we get this error. First, we’ll look at how\nRust decides how much space it needs to store a value of a non-recursive type.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using `Box` to Point to Data on the Heap", "heading_path": ["Using `Box` to Point to Data on the Heap", "Enabling Recursive Types with Boxes", "Computing the Size of a Non-Recursive Type"], "path": "ch15-01-box.md", "url": "https://doc.rust-lang.org/book/ch15-01-box.html#computing-the-size-of-a-non-recursive-type", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch15-01-box.md#computing-the-size-of-a-non-recursive-type-5", "text": "The Rust Programming Language › Using `Box` to Point to Data on the Heap › Enabling Recursive Types with Boxes › Computing the Size of a Non-Recursive Type\n\nRecall the `Message` enum we defined in Listing 6-2 when we discussed enum\ndefinitions in Chapter 6:\n```rust\nenum Message {\n Quit,\n Move { x: i32, y: i32 },\n Write(String),\n ChangeColor(i32, i32, i32),\n}\n```\nTo determine how much space to allocate for a `Message` value, Rust goes\nthrough each of the variants to see which variant needs the most space. Rust\nsees that `Message::Quit` doesn’t need any space, `Message::Move` needs enough\nspace to store two `i32` values, and so forth. Because only one variant will be\nused, the most space a `Message` value will need is the space it would take to\nstore the largest of its variants.\nContrast this with what happens when Rust tries to determine how much space a\nrecursive type like the `List` enum in Listing 15-2 needs. The compiler starts\nby looking at the `Cons` variant, which holds a value of type `i32` and a value\nof type `List`. Therefore, `Cons` needs an amount of space equal to the size of\nan `i32` plus the size of a `List`. To figure out how much memory the `List`\ntype needs, the compiler looks at the variants, starting with the `Cons`\nvariant. The `Cons` variant holds a value of type `i32` and a value of type\n`List`, and this process continues infinitely, as shown in Figure 15-1.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using `Box` to Point to Data on the Heap", "heading_path": ["Using `Box` to Point to Data on the Heap", "Enabling Recursive Types with Boxes", "Computing the Size of a Non-Recursive Type"], "path": "ch15-01-box.md", "url": "https://doc.rust-lang.org/book/ch15-01-box.html#computing-the-size-of-a-non-recursive-type", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch15-01-box.md#getting-a-recursive-type-with-a-known-size-6", "text": "The Rust Programming Language › Using `Box` to Point to Data on the Heap › Enabling Recursive Types with Boxes › Getting a Recursive Type with a Known Size\n\n\"An\nFigure 15-1: An infinite `List` consisting of infinite\n`Cons` variants\nBecause Rust can’t figure out how much space to allocate for recursively\ndefined types, the compiler gives an error with this helpful suggestion:\n```text\nhelp: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to break the cycle\n |\n2 | Cons(i32, Box),\n | ++++ +\n```\nIn this suggestion, _indirection_ means that instead of storing a value\ndirectly, we should change the data structure to store the value indirectly by\nstoring a pointer to the value instead.\nBecause a `Box` is a pointer, Rust always knows how much space a `Box`\nneeds: A pointer’s size doesn’t change based on the amount of data it’s\npointing to. This means we can put a `Box` inside the `Cons` variant instead\nof another `List` value directly. The `Box` will point to the next `List`\nvalue that will be on the heap rather than inside the `Cons` variant.\nConceptually, we still have a list, created with lists holding other lists, but\nthis implementation is now more like placing the items next to one another\nrather than inside one another.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using `Box` to Point to Data on the Heap", "heading_path": ["Using `Box` to Point to Data on the Heap", "Enabling Recursive Types with Boxes", "Getting a Recursive Type with a Known Size"], "path": "ch15-01-box.md", "url": "https://doc.rust-lang.org/book/ch15-01-box.html#getting-a-recursive-type-with-a-known-size", "has_code": true, "code_tags": ["text"]}} {"id": "book/ch15-01-box.md#getting-a-recursive-type-with-a-known-size-7", "text": "The Rust Programming Language › Using `Box` to Point to Data on the Heap › Enabling Recursive Types with Boxes › Getting a Recursive Type with a Known Size\n\nWe can change the definition of the `List` enum in Listing 15-2 and the usage\nof the `List` in Listing 15-3 to the code in Listing 15-5, which will compile.\nListing 15-5 (src/main.rs)\n```rust\nenum List {\n Cons(i32, Box),\n Nil,\n}\n\nuse crate::List::{Cons, Nil};\n\nfn main() {\n let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil))))));\n}\n```\nThe `Cons` variant needs the size of an `i32` plus the space to store the box’s\npointer data. The `Nil` variant stores no values, so it needs less space on the\nstack than the `Cons` variant. We now know that any `List` value will take up\nthe size of an `i32` plus the size of a box’s pointer data. By using a box,\nwe’ve broken the infinite, recursive chain, so the compiler can figure out the\nsize it needs to store a `List` value. Figure 15-2 shows what the `Cons`\nvariant looks like now.\n\"A\nFigure 15-2: A `List` that is not infinitely sized,\nbecause `Cons` holds a `Box`", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using `Box` to Point to Data on the Heap", "heading_path": ["Using `Box` to Point to Data on the Heap", "Enabling Recursive Types with Boxes", "Getting a Recursive Type with a Known Size"], "path": "ch15-01-box.md", "url": "https://doc.rust-lang.org/book/ch15-01-box.html#getting-a-recursive-type-with-a-known-size", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch15-01-box.md#getting-a-recursive-type-with-a-known-size-8", "text": "The Rust Programming Language › Using `Box` to Point to Data on the Heap › Enabling Recursive Types with Boxes › Getting a Recursive Type with a Known Size\n\nBoxes provide only the indirection and heap allocation; they don’t have any\nother special capabilities, like those we’ll see with the other smart pointer\ntypes. They also don’t have the performance overhead that these special\ncapabilities incur, so they can be useful in cases like the cons list where the\nindirection is the only feature we need. We’ll look at more use cases for boxes\nin Chapter 18.\nThe `Box` type is a smart pointer because it implements the `Deref` trait,\nwhich allows `Box` values to be treated like references. When a `Box`\nvalue goes out of scope, the heap data that the box is pointing to is cleaned\nup as well because of the `Drop` trait implementation. These two traits will be\neven more important to the functionality provided by the other smart pointer\ntypes we’ll discuss in the rest of this chapter. Let’s explore these two traits\nin more detail.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using `Box` to Point to Data on the Heap", "heading_path": ["Using `Box` to Point to Data on the Heap", "Enabling Recursive Types with Boxes", "Getting a Recursive Type with a Known Size"], "path": "ch15-01-box.md", "url": "https://doc.rust-lang.org/book/ch15-01-box.html#getting-a-recursive-type-with-a-known-size", "has_code": false, "code_tags": []}} {"id": "book/ch15-02-deref.md#treating-smart-pointers-like-regular-references-0", "text": "The Rust Programming Language › Treating Smart Pointers Like Regular References\n\nImplementing the `Deref` trait allows you to customize the behavior of the\n_dereference operator_ `*` (not to be confused with the multiplication or glob\noperator). By implementing `Deref` in such a way that a smart pointer can be\ntreated like a regular reference, you can write code that operates on\nreferences and use that code with smart pointers too.\nLet’s first look at how the dereference operator works with regular references.\nThen, we’ll try to define a custom type that behaves like `Box` and see why\nthe dereference operator doesn’t work like a reference on our newly defined\ntype. We’ll explore how implementing the `Deref` trait makes it possible for\nsmart pointers to work in ways similar to references. Then, we’ll look at\nRust’s deref coercion feature and how it lets us work with either references or\nsmart pointers.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Treating Smart Pointers Like Regular References", "heading_path": ["Treating Smart Pointers Like Regular References"], "path": "ch15-02-deref.md", "url": "https://doc.rust-lang.org/book/ch15-02-deref.html#treating-smart-pointers-like-regular-references", "has_code": false, "code_tags": []}} {"id": "book/ch15-02-deref.md#following-the-reference-to-the-value-1", "text": "The Rust Programming Language › Treating Smart Pointers Like Regular References › Following the Reference to the Value\n\nA regular reference is a type of pointer, and one way to think of a pointer is\nas an arrow to a value stored somewhere else. In Listing 15-6, we create a\nreference to an `i32` value and then use the dereference operator to follow the\nreference to the value.\nListing 15-6: Using the dereference operator to follow a reference to an `i32` value (src/main.rs)\n```rust\nfn main() {\n let x = 5;\n let y = &x;\n\n assert_eq!(5, x);\n assert_eq!(5, *y);\n}\n```\nThe variable `x` holds an `i32` value `5`. We set `y` equal to a reference to\n`x`. We can assert that `x` is equal to `5`. However, if we want to make an\nassertion about the value in `y`, we have to use `*y` to follow the reference\nto the value it’s pointing to (hence, _dereference_) so that the compiler can\ncompare the actual value. Once we dereference `y`, we have access to the\ninteger value `y` is pointing to that we can compare with `5`.\nIf we tried to write `assert_eq!(5, y);` instead, we would get this compilation\nerror:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Treating Smart Pointers Like Regular References", "heading_path": ["Treating Smart Pointers Like Regular References", "Following the Reference to the Value"], "path": "ch15-02-deref.md", "url": "https://doc.rust-lang.org/book/ch15-02-deref.html#following-the-reference-to-the-value", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch15-02-deref.md#following-the-reference-to-the-value-2", "text": "The Rust Programming Language › Treating Smart Pointers Like Regular References › Following the Reference to the Value\n\n```console\n$ cargo run\n Compiling deref-example v0.1.0 (file:///projects/deref-example)\nerror[E0277]: can't compare `{integer}` with `&{integer}`\n --> src/main.rs:6:5\n |\n6 | assert_eq!(5, y);\n | ^^^^^^^^^^^^^^^^ no implementation for `{integer} == &{integer}`\n |\n = help: the trait `PartialEq<&{integer}>` is not implemented for `{integer}`\n = help: the following other types implement trait `PartialEq`:\n f128\n f16\n f32\n f64\n i128\n i16\n i32\n i64\n and 8 others\n\nFor more information about this error, try `rustc --explain E0277`.\nerror: could not compile `deref-example` (bin \"deref-example\") due to 1 previous error\n```\nComparing a number and a reference to a number isn’t allowed because they’re\ndifferent types. We must use the dereference operator to follow the reference\nto the value it’s pointing to.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Treating Smart Pointers Like Regular References", "heading_path": ["Treating Smart Pointers Like Regular References", "Following the Reference to the Value"], "path": "ch15-02-deref.md", "url": "https://doc.rust-lang.org/book/ch15-02-deref.html#following-the-reference-to-the-value", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch15-02-deref.md#using-boxt-like-a-reference-3", "text": "The Rust Programming Language › Treating Smart Pointers Like Regular References › Using `Box` Like a Reference\n\nWe can rewrite the code in Listing 15-6 to use a `Box` instead of a\nreference; the dereference operator used on the `Box` in Listing 15-7\nfunctions in the same way as the dereference operator used on the reference in\nListing 15-6.\nListing 15-7 (src/main.rs)\n```rust\nfn main() {\n let x = 5;\n let y = Box::new(x);\n\n assert_eq!(5, x);\n assert_eq!(5, *y);\n}\n```\nThe main difference between Listing 15-7 and Listing 15-6 is that here we set\n`y` to be an instance of a box pointing to a copied value of `x` rather than a\nreference pointing to the value of `x`. In the last assertion, we can use the\ndereference operator to follow the box’s pointer in the same way that we did\nwhen `y` was a reference. Next, we’ll explore what is special about `Box`\nthat enables us to use the dereference operator by defining our own box type.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Treating Smart Pointers Like Regular References", "heading_path": ["Treating Smart Pointers Like Regular References", "Using `Box` Like a Reference"], "path": "ch15-02-deref.md", "url": "https://doc.rust-lang.org/book/ch15-02-deref.html#using-boxt-like-a-reference", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch15-02-deref.md#defining-our-own-smart-pointer-4", "text": "The Rust Programming Language › Treating Smart Pointers Like Regular References › Defining Our Own Smart Pointer\n\nLet’s build a wrapper type similar to the `Box` type provided by the\nstandard library to experience how smart pointer types behave differently from\nreferences by default. Then, we’ll look at how to add the ability to use the\ndereference operator.\nNote: There’s one big difference between the `MyBox` type we’re about to\nbuild and the real `Box`: Our version will not store its data on the heap.\nWe are focusing this example on `Deref`, so where the data is actually stored\nis less important than the pointer-like behavior.\nThe `Box` type is ultimately defined as a tuple struct with one element, so\nListing 15-8 defines a `MyBox` type in the same way. We’ll also define a\n`new` function to match the `new` function defined on `Box`.\nListing 15-8 (src/main.rs)\n```rust\nstruct MyBox(T);\n\nimpl MyBox {\n fn new(x: T) -> MyBox {\n MyBox(x)\n }\n}\n```\nWe define a struct named `MyBox` and declare a generic parameter `T` because we\nwant our type to hold values of any type. The `MyBox` type is a tuple struct\nwith one element of type `T`. The `MyBox::new` function takes one parameter of\ntype `T` and returns a `MyBox` instance that holds the value passed in.\nLet’s try adding the `main` function in Listing 15-7 to Listing 15-8 and\nchanging it to use the `MyBox` type we’ve defined instead of `Box`. The\ncode in Listing 15-9 won’t compile, because Rust doesn’t know how to\ndereference `MyBox`.\nListing 15-9 (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Treating Smart Pointers Like Regular References", "heading_path": ["Treating Smart Pointers Like Regular References", "Defining Our Own Smart Pointer"], "path": "ch15-02-deref.md", "url": "https://doc.rust-lang.org/book/ch15-02-deref.html#defining-our-own-smart-pointer", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch15-02-deref.md#defining-our-own-smart-pointer-5", "text": "The Rust Programming Language › Treating Smart Pointers Like Regular References › Defining Our Own Smart Pointer\n\n```rust,ignore,does_not_compile\nfn main() {\n let x = 5;\n let y = MyBox::new(x);\n\n assert_eq!(5, x);\n assert_eq!(5, *y);\n}\n```\nHere’s the resultant compilation error:\n```console\n$ cargo run\n Compiling deref-example v0.1.0 (file:///projects/deref-example)\nerror[E0614]: type `MyBox<{integer}>` cannot be dereferenced\n --> src/main.rs:14:19\n |\n14 | assert_eq!(5, *y);\n | ^^ can't be dereferenced\n\nFor more information about this error, try `rustc --explain E0614`.\nerror: could not compile `deref-example` (bin \"deref-example\") due to 1 previous error\n```\nOur `MyBox` type can’t be dereferenced because we haven’t implemented that\nability on our type. To enable dereferencing with the `*` operator, we\nimplement the `Deref` trait.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Treating Smart Pointers Like Regular References", "heading_path": ["Treating Smart Pointers Like Regular References", "Defining Our Own Smart Pointer"], "path": "ch15-02-deref.md", "url": "https://doc.rust-lang.org/book/ch15-02-deref.html#defining-our-own-smart-pointer", "has_code": true, "code_tags": ["console", "rust,ignore,does_not_compile"]}} {"id": "book/ch15-02-deref.md#implementing-the-deref-trait-6", "text": "The Rust Programming Language › Treating Smart Pointers Like Regular References › Implementing the `Deref` Trait\n\nAs discussed in “Implementing a Trait on a Type” in\nChapter 10, to implement a trait we need to provide implementations for the\ntrait’s required methods. The `Deref` trait, provided by the standard library,\nrequires us to implement one method named `deref` that borrows `self` and\nreturns a reference to the inner data. Listing 15-10 contains an implementation\nof `Deref` to add to the definition of `MyBox`.\nListing 15-10 (src/main.rs)\n```rust\nuse std::ops::Deref;\n\nimpl Deref for MyBox {\n type Target = T;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n```\nThe `type Target = T;` syntax defines an associated type for the `Deref` trait\nto use. Associated types are a slightly different way of declaring a generic\nparameter, but you don’t need to worry about them for now; we’ll cover them in\nmore detail in Chapter 20.\nWe fill in the body of the `deref` method with `&self.0` so that `deref`\nreturns a reference to the value we want to access with the `*` operator;\nrecall from “Creating Different Types with Tuple Structs”\n in Chapter 5 that `.0` accesses the first value in a tuple struct.\nThe `main` function in Listing 15-9 that calls `*` on the `MyBox` value now\ncompiles, and the assertions pass!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Treating Smart Pointers Like Regular References", "heading_path": ["Treating Smart Pointers Like Regular References", "Implementing the `Deref` Trait"], "path": "ch15-02-deref.md", "url": "https://doc.rust-lang.org/book/ch15-02-deref.html#implementing-the-deref-trait", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch15-02-deref.md#implementing-the-deref-trait-7", "text": "The Rust Programming Language › Treating Smart Pointers Like Regular References › Implementing the `Deref` Trait\n\nWithout the `Deref` trait, the compiler can only dereference `&` references.\nThe `deref` method gives the compiler the ability to take a value of any type\nthat implements `Deref` and call the `deref` method to get a reference that\nit knows how to dereference.\nWhen we entered `*y` in Listing 15-9, behind the scenes Rust actually ran this\ncode:\n```rust,ignore\n*(y.deref())\n```\nRust substitutes the `*` operator with a call to the `deref` method and then a\nplain dereference so that we don’t have to think about whether or not we need\nto call the `deref` method. This Rust feature lets us write code that functions\nidentically whether we have a regular reference or a type that implements\n`Deref`.\nThe reason the `deref` method returns a reference to a value, and that the\nplain dereference outside the parentheses in `*(y.deref())` is still necessary,\nhas to do with the ownership system. If the `deref` method returned the value\ndirectly instead of a reference to the value, the value would be moved out of\n`self`. We don’t want to take ownership of the inner value inside `MyBox` in\nthis case or in most cases where we use the dereference operator.\nNote that the `*` operator is replaced with a call to the `deref` method and\nthen a call to the `*` operator just once, each time we use a `*` in our code.\nBecause the substitution of the `*` operator does not recurse infinitely, we\nend up with data of type `i32`, which matches the `5` in `assert_eq!` in\nListing 15-9.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Treating Smart Pointers Like Regular References", "heading_path": ["Treating Smart Pointers Like Regular References", "Implementing the `Deref` Trait"], "path": "ch15-02-deref.md", "url": "https://doc.rust-lang.org/book/ch15-02-deref.html#implementing-the-deref-trait", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch15-02-deref.md#using-deref-coercion-in-functions-and-methods-8", "text": "The Rust Programming Language › Treating Smart Pointers Like Regular References › Using Deref Coercion in Functions and Methods\n\n_Deref coercion_ converts a reference to a type that implements the `Deref`\ntrait into a reference to another type. For example, deref coercion can convert\n`&String` to `&str` because `String` implements the `Deref` trait such that it\nreturns `&str`. Deref coercion is a convenience Rust performs on arguments to\nfunctions and methods, and it works only on types that implement the `Deref`\ntrait. It happens automatically when we pass a reference to a particular type’s\nvalue as an argument to a function or method that doesn’t match the parameter\ntype in the function or method definition. A sequence of calls to the `deref`\nmethod converts the type we provided into the type the parameter needs.\nDeref coercion was added to Rust so that programmers writing function and\nmethod calls don’t need to add as many explicit references and dereferences\nwith `&` and `*`. The deref coercion feature also lets us write more code that\ncan work for either references or smart pointers.\nTo see deref coercion in action, let’s use the `MyBox` type we defined in\nListing 15-8 as well as the implementation of `Deref` that we added in Listing\n15-10. Listing 15-11 shows the definition of a function that has a string slice\nparameter.\nListing 15-11: A `hello` function that has the parameter `name` of type `&str` (src/main.rs)\n```rust\nfn hello(name: &str) {\n println!(\"Hello, {name}!\");\n}\n```\nWe can call the `hello` function with a string slice as an argument, such as\n`hello(\"Rust\");`, for example. Deref coercion makes it possible to call `hello`\nwith a reference to a value of type `MyBox`, as shown in Listing 15-12.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Treating Smart Pointers Like Regular References", "heading_path": ["Treating Smart Pointers Like Regular References", "Using Deref Coercion in Functions and Methods"], "path": "ch15-02-deref.md", "url": "https://doc.rust-lang.org/book/ch15-02-deref.html#using-deref-coercion-in-functions-and-methods", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch15-02-deref.md#using-deref-coercion-in-functions-and-methods-9", "text": "The Rust Programming Language › Treating Smart Pointers Like Regular References › Using Deref Coercion in Functions and Methods\n\nListing 15-12 (src/main.rs)\n```rust\nfn main() {\n let m = MyBox::new(String::from(\"Rust\"));\n hello(&m);\n}\n```\nHere we’re calling the `hello` function with the argument `&m`, which is a\nreference to a `MyBox` value. Because we implemented the `Deref` trait\non `MyBox` in Listing 15-10, Rust can turn `&MyBox` into `&String`\nby calling `deref`. The standard library provides an implementation of `Deref`\non `String` that returns a string slice, and this is in the API documentation\nfor `Deref`. Rust calls `deref` again to turn the `&String` into `&str`, which\nmatches the `hello` function’s definition.\nIf Rust didn’t implement deref coercion, we would have to write the code in\nListing 15-13 instead of the code in Listing 15-12 to call `hello` with a value\nof type `&MyBox`.\nListing 15-13: The code we would have to write if Rust didn’t have deref coercion (src/main.rs)\n```rust\nfn main() {\n let m = MyBox::new(String::from(\"Rust\"));\n hello(&(*m)[..]);\n}\n```\nThe `(*m)` dereferences the `MyBox` into a `String`. Then, the `&` and\n`[..]` take a string slice of the `String` that is equal to the whole string to\nmatch the signature of `hello`. This code without deref coercions is harder to\nread, write, and understand with all of these symbols involved. Deref coercion\nallows Rust to handle these conversions for us automatically.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Treating Smart Pointers Like Regular References", "heading_path": ["Treating Smart Pointers Like Regular References", "Using Deref Coercion in Functions and Methods"], "path": "ch15-02-deref.md", "url": "https://doc.rust-lang.org/book/ch15-02-deref.html#using-deref-coercion-in-functions-and-methods", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch15-02-deref.md#using-deref-coercion-in-functions-and-methods-10", "text": "The Rust Programming Language › Treating Smart Pointers Like Regular References › Using Deref Coercion in Functions and Methods\n\nWhen the `Deref` trait is defined for the types involved, Rust will analyze the\ntypes and use `Deref::deref` as many times as necessary to get a reference to\nmatch the parameter’s type. The number of times that `Deref::deref` needs to be\ninserted is resolved at compile time, so there is no runtime penalty for taking\nadvantage of deref coercion!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Treating Smart Pointers Like Regular References", "heading_path": ["Treating Smart Pointers Like Regular References", "Using Deref Coercion in Functions and Methods"], "path": "ch15-02-deref.md", "url": "https://doc.rust-lang.org/book/ch15-02-deref.html#using-deref-coercion-in-functions-and-methods", "has_code": false, "code_tags": []}} {"id": "book/ch15-02-deref.md#handling-deref-coercion-with-mutable-references-11", "text": "The Rust Programming Language › Treating Smart Pointers Like Regular References › Handling Deref Coercion with Mutable References\n\nSimilar to how you use the `Deref` trait to override the `*` operator on\nimmutable references, you can use the `DerefMut` trait to override the `*`\noperator on mutable references.\nRust does deref coercion when it finds types and trait implementations in three\ncases:\n1. From `&T` to `&U` when `T: Deref`\n2. From `&mut T` to `&mut U` when `T: DerefMut`\n3. From `&mut T` to `&U` when `T: Deref`\nThe first two cases are the same except that the second implements mutability.\nThe first case states that if you have a `&T`, and `T` implements `Deref` to\nsome type `U`, you can get a `&U` transparently. The second case states that\nthe same deref coercion happens for mutable references.\nThe third case is trickier: Rust will also coerce a mutable reference to an\nimmutable one. But the reverse is _not_ possible: Immutable references will\nnever coerce to mutable references. Because of the borrowing rules, if you have\na mutable reference, that mutable reference must be the only reference to that\ndata (otherwise, the program wouldn’t compile). Converting one mutable\nreference to one immutable reference will never break the borrowing rules.\nConverting an immutable reference to a mutable reference would require that the\ninitial immutable reference is the only immutable reference to that data, but\nthe borrowing rules don’t guarantee that. Therefore, Rust can’t make the\nassumption that converting an immutable reference to a mutable reference is\npossible.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Treating Smart Pointers Like Regular References", "heading_path": ["Treating Smart Pointers Like Regular References", "Handling Deref Coercion with Mutable References"], "path": "ch15-02-deref.md", "url": "https://doc.rust-lang.org/book/ch15-02-deref.html#handling-deref-coercion-with-mutable-references", "has_code": false, "code_tags": []}} {"id": "book/ch15-03-drop.md#running-code-on-cleanup-with-the-drop-trait-0", "text": "The Rust Programming Language › Running Code on Cleanup with the `Drop` Trait\n\nThe second trait important to the smart pointer pattern is `Drop`, which lets\nyou customize what happens when a value is about to go out of scope. You can\nprovide an implementation for the `Drop` trait on any type, and that code can\nbe used to release resources like files or network connections.\nWe’re introducing `Drop` in the context of smart pointers because the\nfunctionality of the `Drop` trait is almost always used when implementing a\nsmart pointer. For example, when a `Box` is dropped, it will deallocate the\nspace on the heap that the box points to.\nIn some languages, for some types, the programmer must call code to free memory\nor resources every time they finish using an instance of those types. Examples\ninclude file handles, sockets, and locks. If the programmer forgets, the system\nmight become overloaded and crash. In Rust, you can specify that a particular\nbit of code be run whenever a value goes out of scope, and the compiler will\ninsert this code automatically. As a result, you don’t need to be careful about\nplacing cleanup code everywhere in a program that an instance of a particular\ntype is finished with—you still won’t leak resources!\nYou specify the code to run when a value goes out of scope by implementing the\n`Drop` trait. The `Drop` trait requires you to implement one method named\n`drop` that takes a mutable reference to `self`. To see when Rust calls `drop`,\nlet’s implement `drop` with `println!` statements for now.\nListing 15-14 shows a `CustomSmartPointer` struct whose only custom\nfunctionality is that it will print `Dropping CustomSmartPointer!` when the\ninstance goes out of scope, to show when Rust runs the `drop` method.\nListing 15-14: A `CustomSmartPointer` struct that implements the `Drop` trait where we would put our cleanup code (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Running Code on Cleanup with the `Drop` Trait", "heading_path": ["Running Code on Cleanup with the `Drop` Trait"], "path": "ch15-03-drop.md", "url": "https://doc.rust-lang.org/book/ch15-03-drop.html#running-code-on-cleanup-with-the-drop-trait", "has_code": false, "code_tags": []}} {"id": "book/ch15-03-drop.md#running-code-on-cleanup-with-the-drop-trait-1", "text": "The Rust Programming Language › Running Code on Cleanup with the `Drop` Trait\n\n```rust\nstruct CustomSmartPointer {\n data: String,\n}\n\nimpl Drop for CustomSmartPointer {\n fn drop(&mut self) {\n println!(\"Dropping CustomSmartPointer with data `{}`!\", self.data);\n }\n}\n\nfn main() {\n let c = CustomSmartPointer {\n data: String::from(\"my stuff\"),\n };\n let d = CustomSmartPointer {\n data: String::from(\"other stuff\"),\n };\n println!(\"CustomSmartPointers created\");\n}\n```\nThe `Drop` trait is included in the prelude, so we don’t need to bring it into\nscope. We implement the `Drop` trait on `CustomSmartPointer` and provide an\nimplementation for the `drop` method that calls `println!`. The body of the\n`drop` method is where you would place any logic that you wanted to run when an\ninstance of your type goes out of scope. We’re printing some text here to\ndemonstrate visually when Rust will call `drop`.\nIn `main`, we create two instances of `CustomSmartPointer` and then print\n`CustomSmartPointers created`. At the end of `main`, our instances of\n`CustomSmartPointer` will go out of scope, and Rust will call the code we put\nin the `drop` method, printing our final message. Note that we didn’t need to\ncall the `drop` method explicitly.\nWhen we run this program, we’ll see the following output:\n```console\n$ cargo run\n Compiling drop-example v0.1.0 (file:///projects/drop-example)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.60s\n Running `target/debug/drop-example`\nCustomSmartPointers created\nDropping CustomSmartPointer with data `other stuff`!\nDropping CustomSmartPointer with data `my stuff`!\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Running Code on Cleanup with the `Drop` Trait", "heading_path": ["Running Code on Cleanup with the `Drop` Trait"], "path": "ch15-03-drop.md", "url": "https://doc.rust-lang.org/book/ch15-03-drop.html#running-code-on-cleanup-with-the-drop-trait", "has_code": true, "code_tags": ["console", "rust"]}} {"id": "book/ch15-03-drop.md#running-code-on-cleanup-with-the-drop-trait-2", "text": "The Rust Programming Language › Running Code on Cleanup with the `Drop` Trait\n\nRust automatically called `drop` for us when our instances went out of scope,\ncalling the code we specified. Variables are dropped in the reverse order of\ntheir creation, so `d` was dropped before `c`. This example’s purpose is to\ngive you a visual guide to how the `drop` method works; usually you would\nspecify the cleanup code that your type needs to run rather than a print\nmessage.\nUnfortunately, it’s not straightforward to disable the automatic `drop`\nfunctionality. Disabling `drop` isn’t usually necessary; the whole point of the\n`Drop` trait is that it’s taken care of automatically. Occasionally, however,\nyou might want to clean up a value early. One example is when using smart\npointers that manage locks: You might want to force the `drop` method that\nreleases the lock so that other code in the same scope can acquire the lock.\nRust doesn’t let you call the `Drop` trait’s `drop` method manually; instead,\nyou have to call the `std::mem::drop` function provided by the standard library\nif you want to force a value to be dropped before the end of its scope.\nTrying to call the `Drop` trait’s `drop` method manually by modifying the\n`main` function from Listing 15-14 won’t work, as shown in Listing 15-15.\nListing 15-15: Attempting to call the `drop` method from the `Drop` trait manually to clean up early (src/main.rs)\n```rust,ignore,does_not_compile\nfn main() {\n let c = CustomSmartPointer {\n data: String::from(\"some data\"),\n };\n println!(\"CustomSmartPointer created\");\n c.drop();\n println!(\"CustomSmartPointer dropped before the end of main\");\n}\n```\nWhen we try to compile this code, we’ll get this error:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Running Code on Cleanup with the `Drop` Trait", "heading_path": ["Running Code on Cleanup with the `Drop` Trait"], "path": "ch15-03-drop.md", "url": "https://doc.rust-lang.org/book/ch15-03-drop.html#running-code-on-cleanup-with-the-drop-trait", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch15-03-drop.md#running-code-on-cleanup-with-the-drop-trait-3", "text": "The Rust Programming Language › Running Code on Cleanup with the `Drop` Trait\n\n```console\n$ cargo run\n Compiling drop-example v0.1.0 (file:///projects/drop-example)\nerror[E0040]: explicit use of destructor method\n --> src/main.rs:16:7\n |\n16 | c.drop();\n | ^^^^ explicit destructor calls not allowed\n |\nhelp: consider using `drop` function\n |\n16 - c.drop();\n16 + drop(c);\n |\n\nFor more information about this error, try `rustc --explain E0040`.\nerror: could not compile `drop-example` (bin \"drop-example\") due to 1 previous error\n```\nThis error message states that we’re not allowed to explicitly call `drop`. The\nerror message uses the term _destructor_, which is the general programming term\nfor a function that cleans up an instance. A _destructor_ is analogous to a\n_constructor_, which creates an instance. The `drop` function in Rust is one\nparticular destructor.\nRust doesn’t let us call `drop` explicitly, because Rust would still\nautomatically call `drop` on the value at the end of `main`. This would cause a\ndouble free error because Rust would be trying to clean up the same value twice.\nWe can’t disable the automatic insertion of `drop` when a value goes out of\nscope, and we can’t call the `drop` method explicitly. So, if we need to force\na value to be cleaned up early, we use the `std::mem::drop` function.\nThe `std::mem::drop` function is different from the `drop` method in the `Drop`\ntrait. We call it by passing as an argument the value we want to force-drop.\nThe function is in the prelude, so we can modify `main` in Listing 15-15 to\ncall the `drop` function, as shown in Listing 15-16.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Running Code on Cleanup with the `Drop` Trait", "heading_path": ["Running Code on Cleanup with the `Drop` Trait"], "path": "ch15-03-drop.md", "url": "https://doc.rust-lang.org/book/ch15-03-drop.html#running-code-on-cleanup-with-the-drop-trait", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch15-03-drop.md#running-code-on-cleanup-with-the-drop-trait-4", "text": "The Rust Programming Language › Running Code on Cleanup with the `Drop` Trait\n\nListing 15-16: Calling `std::mem::drop` to explicitly drop a value before it goes out of scope (src/main.rs)\n```rust\nfn main() {\n let c = CustomSmartPointer {\n data: String::from(\"some data\"),\n };\n println!(\"CustomSmartPointer created\");\n drop(c);\n println!(\"CustomSmartPointer dropped before the end of main\");\n}\n```\nRunning this code will print the following:\n```console\n$ cargo run\n Compiling drop-example v0.1.0 (file:///projects/drop-example)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.73s\n Running `target/debug/drop-example`\nCustomSmartPointer created\nDropping CustomSmartPointer with data `some data`!\nCustomSmartPointer dropped before the end of main\n```\nThe text ``Dropping CustomSmartPointer with data `some data`!`` is printed\nbetween the `CustomSmartPointer created` and `CustomSmartPointer dropped before\nthe end of main` text, showing that the `drop` method code is called to drop\n`c` at that point.\nYou can use code specified in a `Drop` trait implementation in many ways to\nmake cleanup convenient and safe: For instance, you could use it to create your\nown memory allocator! With the `Drop` trait and Rust’s ownership system, you\ndon’t have to remember to clean up, because Rust does it automatically.\nYou also don’t have to worry about problems resulting from accidentally\ncleaning up values still in use: The ownership system that makes sure\nreferences are always valid also ensures that `drop` gets called only once when\nthe value is no longer being used.\nNow that we’ve examined `Box` and some of the characteristics of smart\npointers, let’s look at a few other smart pointers defined in the standard\nlibrary.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Running Code on Cleanup with the `Drop` Trait", "heading_path": ["Running Code on Cleanup with the `Drop` Trait"], "path": "ch15-03-drop.md", "url": "https://doc.rust-lang.org/book/ch15-03-drop.html#running-code-on-cleanup-with-the-drop-trait", "has_code": true, "code_tags": ["console", "rust"]}} {"id": "book/ch15-04-rc.md#rct-the-reference-counted-smart-pointer-0", "text": "The Rust Programming Language › `Rc`, the Reference-Counted Smart Pointer\n\nIn the majority of cases, ownership is clear: You know exactly which variable\nowns a given value. However, there are cases when a single value might have\nmultiple owners. For example, in graph data structures, multiple edges might\npoint to the same node, and that node is conceptually owned by all of the edges\nthat point to it. A node shouldn’t be cleaned up unless it doesn’t have any\nedges pointing to it and so has no owners.\nYou have to enable multiple ownership explicitly by using the Rust type\n`Rc`, which is an abbreviation for _reference counting_. The `Rc` type\nkeeps track of the number of references to a value to determine whether or not\nthe value is still in use. If there are zero references to a value, the value\ncan be cleaned up without any references becoming invalid.\nImagine `Rc` as a TV in a family room. When one person enters to watch TV,\nthey turn it on. Others can come into the room and watch the TV. When the last\nperson leaves the room, they turn off the TV because it’s no longer being used.\nIf someone turns off the TV while others are still watching it, there would be\nan uproar from the remaining TV watchers!\nWe use the `Rc` type when we want to allocate some data on the heap for\nmultiple parts of our program to read and we can’t determine at compile time\nwhich part will finish using the data last. If we knew which part would finish\nlast, we could just make that part the data’s owner, and the normal ownership\nrules enforced at compile time would take effect.\nNote that `Rc` is only for use in single-threaded scenarios. When we discuss\nconcurrency in Chapter 16, we’ll cover how to do reference counting in\nmultithreaded programs.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "`Rc`, the Reference Counted Smart Pointer", "heading_path": ["`Rc`, the Reference-Counted Smart Pointer"], "path": "ch15-04-rc.md", "url": "https://doc.rust-lang.org/book/ch15-04-rc.html#rct-the-reference-counted-smart-pointer", "has_code": false, "code_tags": []}} {"id": "book/ch15-04-rc.md#sharing-data-1", "text": "The Rust Programming Language › `Rc`, the Reference-Counted Smart Pointer › Sharing Data\n\nLet’s return to our cons list example in Listing 15-5. Recall that we defined\nit using `Box`. This time, we’ll create two lists that both share ownership\nof a third list. Conceptually, this looks similar to Figure 15-3.\n\"A\nFigure 15-3: Two lists, `b` and `c`, sharing ownership of\na third list, `a`\nWe’ll create list `a` that contains `5` and then `10`. Then, we’ll make two\nmore lists: `b` that starts with `3` and `c` that starts with `4`. Both the `b`\nand `c` lists will then continue on to the first `a` list containing `5` and\n`10`. In other words, both lists will share the first list containing `5` and\n`10`.\nTrying to implement this scenario using our definition of `List` with `Box`\nwon’t work, as shown in Listing 15-17.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "`Rc`, the Reference Counted Smart Pointer", "heading_path": ["`Rc`, the Reference-Counted Smart Pointer", "Sharing Data"], "path": "ch15-04-rc.md", "url": "https://doc.rust-lang.org/book/ch15-04-rc.html#sharing-data", "has_code": false, "code_tags": []}} {"id": "book/ch15-04-rc.md#sharing-data-2", "text": "The Rust Programming Language › `Rc`, the Reference-Counted Smart Pointer › Sharing Data\n\nListing 15-17 (src/main.rs)\n```rust,ignore,does_not_compile\nenum List {\n Cons(i32, Box),\n Nil,\n}\n\nuse crate::List::{Cons, Nil};\n\nfn main() {\n let a = Cons(5, Box::new(Cons(10, Box::new(Nil))));\n let b = Cons(3, Box::new(a));\n let c = Cons(4, Box::new(a));\n}\n```\nWhen we compile this code, we get this error:\n```console\n$ cargo run\n Compiling cons-list v0.1.0 (file:///projects/cons-list)\nerror[E0382]: use of moved value: `a`\n --> src/main.rs:11:30\n |\n 9 | let a = Cons(5, Box::new(Cons(10, Box::new(Nil))));\n | - move occurs because `a` has type `List`, which does not implement the `Copy` trait\n10 | let b = Cons(3, Box::new(a));\n | - value moved here\n11 | let c = Cons(4, Box::new(a));\n | ^ value used here after move\n |\nnote: if `List` implemented `Clone`, you could clone the value\n --> src/main.rs:1:1\n |\n 1 | enum List {\n | ^^^^^^^^^ consider implementing `Clone` for this type\n...\n10 | let b = Cons(3, Box::new(a));\n | - you could clone this value\n\nFor more information about this error, try `rustc --explain E0382`.\nerror: could not compile `cons-list` (bin \"cons-list\") due to 1 previous error\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "`Rc`, the Reference Counted Smart Pointer", "heading_path": ["`Rc`, the Reference-Counted Smart Pointer", "Sharing Data"], "path": "ch15-04-rc.md", "url": "https://doc.rust-lang.org/book/ch15-04-rc.html#sharing-data", "has_code": true, "code_tags": ["console", "rust,ignore,does_not_compile"]}} {"id": "book/ch15-04-rc.md#sharing-data-3", "text": "The Rust Programming Language › `Rc`, the Reference-Counted Smart Pointer › Sharing Data\n\nThe `Cons` variants own the data they hold, so when we create the `b` list, `a`\nis moved into `b` and `b` owns `a`. Then, when we try to use `a` again when\ncreating `c`, we’re not allowed to because `a` has been moved.\nWe could change the definition of `Cons` to hold references instead, but then\nwe would have to specify lifetime parameters. By specifying lifetime\nparameters, we would be specifying that every element in the list will live at\nleast as long as the entire list. This is the case for the elements and lists\nin Listing 15-17, but not in every scenario.\nInstead, we’ll change our definition of `List` to use `Rc` in place of\n`Box`, as shown in Listing 15-18. Each `Cons` variant will now hold a value\nand an `Rc` pointing to a `List`. When we create `b`, instead of taking\nownership of `a`, we’ll clone the `Rc` that `a` is holding, thereby\nincreasing the number of references from one to two and letting `a` and `b`\nshare ownership of the data in that `Rc`. We’ll also clone `a` when\ncreating `c`, increasing the number of references from two to three. Every time\nwe call `Rc::clone`, the reference count to the data within the `Rc` will\nincrease, and the data won’t be cleaned up unless there are zero references to\nit.\nListing 15-18 (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "`Rc`, the Reference Counted Smart Pointer", "heading_path": ["`Rc`, the Reference-Counted Smart Pointer", "Sharing Data"], "path": "ch15-04-rc.md", "url": "https://doc.rust-lang.org/book/ch15-04-rc.html#sharing-data", "has_code": false, "code_tags": []}} {"id": "book/ch15-04-rc.md#sharing-data-4", "text": "The Rust Programming Language › `Rc`, the Reference-Counted Smart Pointer › Sharing Data\n\n```rust\nenum List {\n Cons(i32, Rc),\n Nil,\n}\n\nuse crate::List::{Cons, Nil};\nuse std::rc::Rc;\n\nfn main() {\n let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil)))));\n let b = Cons(3, Rc::clone(&a));\n let c = Cons(4, Rc::clone(&a));\n}\n```\nWe need to add a `use` statement to bring `Rc` into scope because it’s not\nin the prelude. In `main`, we create the list holding `5` and `10` and store it\nin a new `Rc` in `a`. Then, when we create `b` and `c`, we call the\n`Rc::clone` function and pass a reference to the `Rc` in `a` as an\nargument.\nWe could have called `a.clone()` rather than `Rc::clone(&a)`, but Rust’s\nconvention is to use `Rc::clone` in this case. The implementation of\n`Rc::clone` doesn’t make a deep copy of all the data like most types’\nimplementations of `clone` do. The call to `Rc::clone` only increments the\nreference count, which doesn’t take much time. Deep copies of data can take a\nlot of time. By using `Rc::clone` for reference counting, we can visually\ndistinguish between the deep-copy kinds of clones and the kinds of clones that\nincrease the reference count. When looking for performance problems in the\ncode, we only need to consider the deep-copy clones and can disregard calls to\n`Rc::clone`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "`Rc`, the Reference Counted Smart Pointer", "heading_path": ["`Rc`, the Reference-Counted Smart Pointer", "Sharing Data"], "path": "ch15-04-rc.md", "url": "https://doc.rust-lang.org/book/ch15-04-rc.html#sharing-data", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch15-04-rc.md#cloning-to-increase-the-reference-count-5", "text": "The Rust Programming Language › `Rc`, the Reference-Counted Smart Pointer › Cloning to Increase the Reference Count\n\nLet’s change our working example in Listing 15-18 so that we can see the\nreference counts changing as we create and drop references to the `Rc` in\n`a`.\nIn Listing 15-19, we’ll change `main` so that it has an inner scope around list\n`c`; then, we can see how the reference count changes when `c` goes out of\nscope.\nListing 15-19: Printing the reference count (src/main.rs)\n```rust\n// --snip--\n\nfn main() {\n let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil)))));\n println!(\"count after creating a = {}\", Rc::strong_count(&a));\n let b = Cons(3, Rc::clone(&a));\n println!(\"count after creating b = {}\", Rc::strong_count(&a));\n {\n let c = Cons(4, Rc::clone(&a));\n println!(\"count after creating c = {}\", Rc::strong_count(&a));\n }\n println!(\"count after c goes out of scope = {}\", Rc::strong_count(&a));\n}\n```\nAt each point in the program where the reference count changes, we print the\nreference count, which we get by calling the `Rc::strong_count` function. This\nfunction is named `strong_count` rather than `count` because the `Rc` type\nalso has a `weak_count`; we’ll see what `weak_count` is used for in “Preventing\nReference Cycles Using `Weak`”.\nThis code prints the following:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "`Rc`, the Reference Counted Smart Pointer", "heading_path": ["`Rc`, the Reference-Counted Smart Pointer", "Cloning to Increase the Reference Count"], "path": "ch15-04-rc.md", "url": "https://doc.rust-lang.org/book/ch15-04-rc.html#cloning-to-increase-the-reference-count", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch15-04-rc.md#cloning-to-increase-the-reference-count-6", "text": "The Rust Programming Language › `Rc`, the Reference-Counted Smart Pointer › Cloning to Increase the Reference Count\n\n```console\n$ cargo run\n Compiling cons-list v0.1.0 (file:///projects/cons-list)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.45s\n Running `target/debug/cons-list`\ncount after creating a = 1\ncount after creating b = 2\ncount after creating c = 3\ncount after c goes out of scope = 2\n```\nWe can see that the `Rc` in `a` has an initial reference count of 1;\nthen, each time we call `clone`, the count goes up by 1. When `c` goes out of\nscope, the count goes down by 1. We don’t have to call a function to decrease\nthe reference count like we have to call `Rc::clone` to increase the reference\ncount: The implementation of the `Drop` trait decreases the reference count\nautomatically when an `Rc` value goes out of scope.\nWhat we can’t see in this example is that when `b` and then `a` go out of scope\nat the end of `main`, the count is 0, and the `Rc` is cleaned up\ncompletely. Using `Rc` allows a single value to have multiple owners, and\nthe count ensures that the value remains valid as long as any of the owners\nstill exist.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "`Rc`, the Reference Counted Smart Pointer", "heading_path": ["`Rc`, the Reference-Counted Smart Pointer", "Cloning to Increase the Reference Count"], "path": "ch15-04-rc.md", "url": "https://doc.rust-lang.org/book/ch15-04-rc.html#cloning-to-increase-the-reference-count", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch15-04-rc.md#cloning-to-increase-the-reference-count-7", "text": "The Rust Programming Language › `Rc`, the Reference-Counted Smart Pointer › Cloning to Increase the Reference Count\n\nVia immutable references, `Rc` allows you to share data between multiple\nparts of your program for reading only. If `Rc` allowed you to have multiple\nmutable references too, you might violate one of the borrowing rules discussed\nin Chapter 4: Multiple mutable borrows to the same place can cause data races\nand inconsistencies. But being able to mutate data is very useful! In the next\nsection, we’ll discuss the interior mutability pattern and the `RefCell`\ntype that you can use in conjunction with an `Rc` to work with this\nimmutability restriction.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "`Rc`, the Reference Counted Smart Pointer", "heading_path": ["`Rc`, the Reference-Counted Smart Pointer", "Cloning to Increase the Reference Count"], "path": "ch15-04-rc.md", "url": "https://doc.rust-lang.org/book/ch15-04-rc.html#cloning-to-increase-the-reference-count", "has_code": false, "code_tags": []}} {"id": "book/ch15-05-interior-mutability.md#refcellt-and-the-interior-mutability-pattern-0", "text": "The Rust Programming Language › `RefCell` and the Interior Mutability Pattern\n\n_Interior mutability_ is a design pattern in Rust that allows you to mutate\ndata even when there are immutable references to that data; normally, this\naction is disallowed by the borrowing rules. To mutate data, the pattern uses\n`unsafe` code inside a data structure to bend Rust’s usual rules that govern\nmutation and borrowing. Unsafe code indicates to the compiler that we’re\nchecking the rules manually instead of relying on the compiler to check them\nfor us; we will discuss unsafe code more in Chapter 20.\nWe can use types that use the interior mutability pattern only when we can\nensure that the borrowing rules will be followed at runtime, even though the\ncompiler can’t guarantee that. The `unsafe` code involved is then wrapped in a\nsafe API, and the outer type is still immutable.\nLet’s explore this concept by looking at the `RefCell` type that follows the\ninterior mutability pattern.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "`RefCell` and the Interior Mutability Pattern", "heading_path": ["`RefCell` and the Interior Mutability Pattern"], "path": "ch15-05-interior-mutability.md", "url": "https://doc.rust-lang.org/book/ch15-05-interior-mutability.html#refcellt-and-the-interior-mutability-pattern", "has_code": false, "code_tags": []}} {"id": "book/ch15-05-interior-mutability.md#enforcing-borrowing-rules-at-runtime-1", "text": "The Rust Programming Language › `RefCell` and the Interior Mutability Pattern › Enforcing Borrowing Rules at Runtime\n\nUnlike `Rc`, the `RefCell` type represents single ownership over the data\nit holds. So, what makes `RefCell` different from a type like `Box`?\nRecall the borrowing rules you learned in Chapter 4:\n- At any given time, you can have _either_ one mutable reference or any number\n of immutable references (but not both).\n- References must always be valid.\nWith references and `Box`, the borrowing rules’ invariants are enforced at\ncompile time. With `RefCell`, these invariants are enforced _at runtime_.\nWith references, if you break these rules, you’ll get a compiler error. With\n`RefCell`, if you break these rules, your program will panic and exit.\nThe advantages of checking the borrowing rules at compile time are that errors\nwill be caught sooner in the development process, and there is no impact on\nruntime performance because all the analysis is completed beforehand. For those\nreasons, checking the borrowing rules at compile time is the best choice in the\nmajority of cases, which is why this is Rust’s default.\nThe advantage of checking the borrowing rules at runtime instead is that\ncertain memory-safe scenarios are then allowed, where they would’ve been\ndisallowed by the compile-time checks. Static analysis, like the Rust compiler,\nis inherently conservative. Some properties of code are impossible to detect by\nanalyzing the code: The most famous example is the Halting Problem, which is\nbeyond the scope of this book but is an interesting topic to research.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "`RefCell` and the Interior Mutability Pattern", "heading_path": ["`RefCell` and the Interior Mutability Pattern", "Enforcing Borrowing Rules at Runtime"], "path": "ch15-05-interior-mutability.md", "url": "https://doc.rust-lang.org/book/ch15-05-interior-mutability.html#enforcing-borrowing-rules-at-runtime", "has_code": false, "code_tags": []}} {"id": "book/ch15-05-interior-mutability.md#enforcing-borrowing-rules-at-runtime-2", "text": "The Rust Programming Language › `RefCell` and the Interior Mutability Pattern › Enforcing Borrowing Rules at Runtime\n\nBecause some analysis is impossible, if the Rust compiler can’t be sure the\ncode complies with the ownership rules, it might reject a correct program; in\nthis way, it’s conservative. If Rust accepted an incorrect program, users\nwouldn’t be able to trust the guarantees Rust makes. However, if Rust rejects a\ncorrect program, the programmer will be inconvenienced, but nothing\ncatastrophic can occur. The `RefCell` type is useful when you’re sure your\ncode follows the borrowing rules but the compiler is unable to understand and\nguarantee that.\nSimilar to `Rc`, `RefCell` is only for use in single-threaded scenarios\nand will give you a compile-time error if you try using it in a multithreaded\ncontext. We’ll talk about how to get the functionality of `RefCell` in a\nmultithreaded program in Chapter 16.\nHere is a recap of the reasons to choose `Box`, `Rc`, or `RefCell`:\n- `Rc` enables multiple owners of the same data; `Box` and `RefCell`\n have single owners.\n- `Box` allows immutable or mutable borrows checked at compile time; `Rc`\n allows only immutable borrows checked at compile time; `RefCell` allows\n immutable or mutable borrows checked at runtime.\n- Because `RefCell` allows mutable borrows checked at runtime, you can\n mutate the value inside the `RefCell` even when the `RefCell` is\n immutable.\nMutating the value inside an immutable value is the interior mutability\npattern. Let’s look at a situation in which interior mutability is useful and\nexamine how it’s possible.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "`RefCell` and the Interior Mutability Pattern", "heading_path": ["`RefCell` and the Interior Mutability Pattern", "Enforcing Borrowing Rules at Runtime"], "path": "ch15-05-interior-mutability.md", "url": "https://doc.rust-lang.org/book/ch15-05-interior-mutability.html#enforcing-borrowing-rules-at-runtime", "has_code": false, "code_tags": []}} {"id": "book/ch15-05-interior-mutability.md#testing-with-mock-objects-3", "text": "The Rust Programming Language › `RefCell` and the Interior Mutability Pattern › Using Interior Mutability › Testing with Mock Objects\n\nA consequence of the borrowing rules is that when you have an immutable value,\nyou can’t borrow it mutably. For example, this code won’t compile:\n```rust,ignore,does_not_compile\nfn main() {\n let x = 5;\n let y = &mut x;\n}\n```\nIf you tried to compile this code, you’d get the following error:\n```console\n$ cargo run\n Compiling borrowing v0.1.0 (file:///projects/borrowing)\nerror[E0596]: cannot borrow `x` as mutable, as it is not declared as mutable\n --> src/main.rs:3:13\n |\n3 | let y = &mut x;\n | ^^^^^^ cannot borrow as mutable\n |\nhelp: consider changing this to be mutable\n |\n2 | let mut x = 5;\n | +++\n\nFor more information about this error, try `rustc --explain E0596`.\nerror: could not compile `borrowing` (bin \"borrowing\") due to 1 previous error\n```\nHowever, there are situations in which it would be useful for a value to mutate\nitself in its methods but appear immutable to other code. Code outside the\nvalue’s methods would not be able to mutate the value. Using `RefCell` is\none way to get the ability to have interior mutability, but `RefCell`\ndoesn’t get around the borrowing rules completely: The borrow checker in the\ncompiler allows this interior mutability, and the borrowing rules are checked\nat runtime instead. If you violate the rules, you’ll get a `panic!` instead of\na compiler error.\nLet’s work through a practical example where we can use `RefCell` to mutate\nan immutable value and see why that is useful.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "`RefCell` and the Interior Mutability Pattern", "heading_path": ["`RefCell` and the Interior Mutability Pattern", "Using Interior Mutability", "Testing with Mock Objects"], "path": "ch15-05-interior-mutability.md", "url": "https://doc.rust-lang.org/book/ch15-05-interior-mutability.html#testing-with-mock-objects", "has_code": true, "code_tags": ["console", "rust,ignore,does_not_compile"]}} {"id": "book/ch15-05-interior-mutability.md#testing-with-mock-objects-4", "text": "The Rust Programming Language › `RefCell` and the Interior Mutability Pattern › Using Interior Mutability › Testing with Mock Objects\n\nSometimes during testing a programmer will use a type in place of another type,\nin order to observe particular behavior and assert that it’s implemented\ncorrectly. This placeholder type is called a _test double_. Think of it in the\nsense of a stunt double in filmmaking, where a person steps in and substitutes\nfor an actor to do a particularly tricky scene. Test doubles stand in for other\ntypes when we’re running tests. _Mock objects_ are specific types of test\ndoubles that record what happens during a test so that you can assert that the\ncorrect actions took place.\nRust doesn’t have objects in the same sense as other languages have objects,\nand Rust doesn’t have mock object functionality built into the standard library\nas some other languages do. However, you can definitely create a struct that\nwill serve the same purposes as a mock object.\nHere’s the scenario we’ll test: We’ll create a library that tracks a value\nagainst a maximum value and sends messages based on how close to the maximum\nvalue the current value is. This library could be used to keep track of a\nuser’s quota for the number of API calls they’re allowed to make, for example.\nOur library will only provide the functionality of tracking how close to the\nmaximum a value is and what the messages should be at what times. Applications\nthat use our library will be expected to provide the mechanism for sending the\nmessages: The application could show the message to the user directly, send an\nemail, send a text message, or do something else. The library doesn’t need to\nknow that detail. All it needs is something that implements a trait we’ll\nprovide, called `Messenger`. Listing 15-20 shows the library code.\nListing 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 (src/lib.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "`RefCell` and the Interior Mutability Pattern", "heading_path": ["`RefCell` and the Interior Mutability Pattern", "Using Interior Mutability", "Testing with Mock Objects"], "path": "ch15-05-interior-mutability.md", "url": "https://doc.rust-lang.org/book/ch15-05-interior-mutability.html#testing-with-mock-objects", "has_code": false, "code_tags": []}} {"id": "book/ch15-05-interior-mutability.md#testing-with-mock-objects-5", "text": "The Rust Programming Language › `RefCell` and the Interior Mutability Pattern › Using Interior Mutability › Testing with Mock Objects\n\n```rust,noplayground\npub trait Messenger {\n fn send(&self, msg: &str);\n}\n\npub struct LimitTracker<'a, T: Messenger> {\n messenger: &'a T,\n value: usize,\n max: usize,\n}\n\nimpl<'a, T> LimitTracker<'a, T>\nwhere\n T: Messenger,\n{\n pub fn new(messenger: &'a T, max: usize) -> LimitTracker<'a, T> {\n LimitTracker {\n messenger,\n value: 0,\n max,\n }\n }\n\n pub fn set_value(&mut self, value: usize) {\n self.value = value;\n\n let percentage_of_max = self.value as f64 / self.max as f64;\n\n if percentage_of_max >= 1.0 {\n self.messenger.send(\"Error: You are over your quota!\");\n } else if percentage_of_max >= 0.9 {\n self.messenger\n .send(\"Urgent warning: You've used up over 90% of your quota!\");\n } else if percentage_of_max >= 0.75 {\n self.messenger\n .send(\"Warning: You've used up over 75% of your quota!\");\n }\n }\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "`RefCell` and the Interior Mutability Pattern", "heading_path": ["`RefCell` and the Interior Mutability Pattern", "Using Interior Mutability", "Testing with Mock Objects"], "path": "ch15-05-interior-mutability.md", "url": "https://doc.rust-lang.org/book/ch15-05-interior-mutability.html#testing-with-mock-objects", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch15-05-interior-mutability.md#testing-with-mock-objects-6", "text": "The Rust Programming Language › `RefCell` and the Interior Mutability Pattern › Using Interior Mutability › Testing with Mock Objects\n\nOne important part of this code is that the `Messenger` trait has one method\ncalled `send` that takes an immutable reference to `self` and the text of the\nmessage. This trait is the interface our mock object needs to implement so that\nthe mock can be used in the same way a real object is. The other important part\nis that we want to test the behavior of the `set_value` method on the\n`LimitTracker`. We can change what we pass in for the `value` parameter, but\n`set_value` doesn’t return anything for us to make assertions on. We want to be\nable to say that if we create a `LimitTracker` with something that implements\nthe `Messenger` trait and a particular value for `max`, the messenger is told\nto send the appropriate messages when we pass different numbers for `value`.\nWe need a mock object that, instead of sending an email or text message when we\ncall `send`, will only keep track of the messages it’s told to send. We can\ncreate a new instance of the mock object, create a `LimitTracker` that uses the\nmock object, call the `set_value` method on `LimitTracker`, and then check that\nthe mock object has the messages we expect. Listing 15-21 shows an attempt to\nimplement a mock object to do just that, but the borrow checker won’t allow it.\nListing 15-21: An attempt to implement a `MockMessenger` that isn’t allowed by the borrow checker (src/lib.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "`RefCell` and the Interior Mutability Pattern", "heading_path": ["`RefCell` and the Interior Mutability Pattern", "Using Interior Mutability", "Testing with Mock Objects"], "path": "ch15-05-interior-mutability.md", "url": "https://doc.rust-lang.org/book/ch15-05-interior-mutability.html#testing-with-mock-objects", "has_code": false, "code_tags": []}} {"id": "book/ch15-05-interior-mutability.md#testing-with-mock-objects-7", "text": "The Rust Programming Language › `RefCell` and the Interior Mutability Pattern › Using Interior Mutability › Testing with Mock Objects\n\n```rust,ignore,does_not_compile\n#[cfg(test)]\nmod tests {\n use super::*;\n\n struct MockMessenger {\n sent_messages: Vec,\n }\n\n impl MockMessenger {\n fn new() -> MockMessenger {\n MockMessenger {\n sent_messages: vec![],\n }\n }\n }\n\n impl Messenger for MockMessenger {\n fn send(&self, message: &str) {\n self.sent_messages.push(String::from(message));\n }\n }\n\n #[test]\n fn it_sends_an_over_75_percent_warning_message() {\n let mock_messenger = MockMessenger::new();\n let mut limit_tracker = LimitTracker::new(&mock_messenger, 100);\n\n limit_tracker.set_value(80);\n\n assert_eq!(mock_messenger.sent_messages.len(), 1);\n }\n}\n```\nThis test code defines a `MockMessenger` struct that has a `sent_messages`\nfield with a `Vec` of `String` values to keep track of the messages it’s told\nto send. We also define an associated function `new` to make it convenient to\ncreate new `MockMessenger` values that start with an empty list of messages. We\nthen implement the `Messenger` trait for `MockMessenger` so that we can give a\n`MockMessenger` to a `LimitTracker`. In the definition of the `send` method, we\ntake the message passed in as a parameter and store it in the `MockMessenger`\nlist of `sent_messages`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "`RefCell` and the Interior Mutability Pattern", "heading_path": ["`RefCell` and the Interior Mutability Pattern", "Using Interior Mutability", "Testing with Mock Objects"], "path": "ch15-05-interior-mutability.md", "url": "https://doc.rust-lang.org/book/ch15-05-interior-mutability.html#testing-with-mock-objects", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch15-05-interior-mutability.md#testing-with-mock-objects-8", "text": "The Rust Programming Language › `RefCell` and the Interior Mutability Pattern › Using Interior Mutability › Testing with Mock Objects\n\nIn the test, we’re testing what happens when the `LimitTracker` is told to set\n`value` to something that is more than 75 percent of the `max` value. First, we\ncreate a new `MockMessenger`, which will start with an empty list of messages.\nThen, we create a new `LimitTracker` and give it a reference to the new\n`MockMessenger` and a `max` value of `100`. We call the `set_value` method on\nthe `LimitTracker` with a value of `80`, which is more than 75 percent of 100.\nThen, we assert that the list of messages that the `MockMessenger` is keeping\ntrack of should now have one message in it.\nHowever, there’s one problem with this test, as shown here:\n```console\n$ cargo test\n Compiling limit-tracker v0.1.0 (file:///projects/limit-tracker)\nerror[E0596]: cannot borrow `self.sent_messages` as mutable, as it is behind a `&` reference\n --> src/lib.rs:58:13\n |\n58 | self.sent_messages.push(String::from(message));\n | ^^^^^^^^^^^^^^^^^^ `self` is a `&` reference, so it cannot be borrowed as mutable\n |\nhelp: consider changing this to be a mutable reference in the `impl` method and the `trait` definition\n |\n 2 ~ fn send(&mut self, msg: &str);\n 3 | }\n...\n56 | impl Messenger for MockMessenger {\n57 ~ fn send(&mut self, message: &str) {\n |\n\nFor more information about this error, try `rustc --explain E0596`.\nerror: could not compile `limit-tracker` (lib test) due to 1 previous error\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "`RefCell` and the Interior Mutability Pattern", "heading_path": ["`RefCell` and the Interior Mutability Pattern", "Using Interior Mutability", "Testing with Mock Objects"], "path": "ch15-05-interior-mutability.md", "url": "https://doc.rust-lang.org/book/ch15-05-interior-mutability.html#testing-with-mock-objects", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch15-05-interior-mutability.md#testing-with-mock-objects-9", "text": "The Rust Programming Language › `RefCell` and the Interior Mutability Pattern › Using Interior Mutability › Testing with Mock Objects\n\nWe can’t modify the `MockMessenger` to keep track of the messages, because the\n`send` method takes an immutable reference to `self`. We also can’t take the\nsuggestion from the error text to use `&mut self` in both the `impl` method and\nthe trait definition. We do not want to change the `Messenger` trait solely for\nthe sake of testing. Instead, we need to find a way to make our test code work\ncorrectly with our existing design.\nThis is a situation in which interior mutability can help! We’ll store the\n`sent_messages` within a `RefCell`, and then the `send` method will be able\nto modify `sent_messages` to store the messages we’ve seen. Listing 15-22 shows\nwhat that looks like.\nListing 15-22 (src/lib.rs)\n```rust,noplayground\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::cell::RefCell;\n\n struct MockMessenger {\n sent_messages: RefCell>,\n }\n\n impl MockMessenger {\n fn new() -> MockMessenger {\n MockMessenger {\n sent_messages: RefCell::new(vec![]),\n }\n }\n }\n\n impl Messenger for MockMessenger {\n fn send(&self, message: &str) {\n self.sent_messages.borrow_mut().push(String::from(message));\n }\n }\n\n #[test]\n fn it_sends_an_over_75_percent_warning_message() {\n // --snip--\n\n assert_eq!(mock_messenger.sent_messages.borrow().len(), 1);\n }\n}\n```\nThe `sent_messages` field is now of type `RefCell>` instead of\n`Vec`. In the `new` function, we create a new `RefCell>`\ninstance around the empty vector.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "`RefCell` and the Interior Mutability Pattern", "heading_path": ["`RefCell` and the Interior Mutability Pattern", "Using Interior Mutability", "Testing with Mock Objects"], "path": "ch15-05-interior-mutability.md", "url": "https://doc.rust-lang.org/book/ch15-05-interior-mutability.html#testing-with-mock-objects", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch15-05-interior-mutability.md#tracking-borrows-at-runtime-10", "text": "The Rust Programming Language › `RefCell` and the Interior Mutability Pattern › Using Interior Mutability › Tracking Borrows at Runtime\n\nFor the implementation of the `send` method, the first parameter is still an\nimmutable borrow of `self`, which matches the trait definition. We call\n`borrow_mut` on the `RefCell>` in `self.sent_messages` to get a\nmutable reference to the value inside the `RefCell>`, which is the\nvector. Then, we can call `push` on the mutable reference to the vector to keep\ntrack of the messages sent during the test.\nThe last change we have to make is in the assertion: To see how many items are\nin the inner vector, we call `borrow` on the `RefCell>` to get an\nimmutable reference to the vector.\nNow that you’ve seen how to use `RefCell`, let’s dig into how it works!\nWhen creating immutable and mutable references, we use the `&` and `&mut`\nsyntax, respectively. With `RefCell`, we use the `borrow` and `borrow_mut`\nmethods, which are part of the safe API that belongs to `RefCell`. The\n`borrow` method returns the smart pointer type `Ref`, and `borrow_mut`\nreturns the smart pointer type `RefMut`. Both types implement `Deref`, so we\ncan treat them like regular references.\nThe `RefCell` keeps track of how many `Ref` and `RefMut` smart\npointers are currently active. Every time we call `borrow`, the `RefCell`\nincreases its count of how many immutable borrows are active. When a `Ref`\nvalue goes out of scope, the count of immutable borrows goes down by 1. Just\nlike the compile-time borrowing rules, `RefCell` lets us have many immutable\nborrows or one mutable borrow at any point in time.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "`RefCell` and the Interior Mutability Pattern", "heading_path": ["`RefCell` and the Interior Mutability Pattern", "Using Interior Mutability", "Tracking Borrows at Runtime"], "path": "ch15-05-interior-mutability.md", "url": "https://doc.rust-lang.org/book/ch15-05-interior-mutability.html#tracking-borrows-at-runtime", "has_code": false, "code_tags": []}} {"id": "book/ch15-05-interior-mutability.md#tracking-borrows-at-runtime-11", "text": "The Rust Programming Language › `RefCell` and the Interior Mutability Pattern › Using Interior Mutability › Tracking Borrows at Runtime\n\nIf we try to violate these rules, rather than getting a compiler error as we\nwould with references, the implementation of `RefCell` will panic at\nruntime. Listing 15-23 shows a modification of the implementation of `send` in\nListing 15-22. We’re deliberately trying to create two mutable borrows active\nfor the same scope to illustrate that `RefCell` prevents us from doing this\nat runtime.\nListing 15-23 (src/lib.rs)\n```rust,ignore,panics\n impl Messenger for MockMessenger {\n fn send(&self, message: &str) {\n let mut one_borrow = self.sent_messages.borrow_mut();\n let mut two_borrow = self.sent_messages.borrow_mut();\n\n one_borrow.push(String::from(message));\n two_borrow.push(String::from(message));\n }\n }\n```\nWe create a variable `one_borrow` for the `RefMut` smart pointer returned\nfrom `borrow_mut`. Then, we create another mutable borrow in the same way in\nthe variable `two_borrow`. This makes two mutable references in the same scope,\nwhich isn’t allowed. When we run the tests for our library, the code in Listing\n15-23 will compile without any errors, but the test will fail:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "`RefCell` and the Interior Mutability Pattern", "heading_path": ["`RefCell` and the Interior Mutability Pattern", "Using Interior Mutability", "Tracking Borrows at Runtime"], "path": "ch15-05-interior-mutability.md", "url": "https://doc.rust-lang.org/book/ch15-05-interior-mutability.html#tracking-borrows-at-runtime", "has_code": true, "code_tags": ["rust,ignore,panics"]}} {"id": "book/ch15-05-interior-mutability.md#tracking-borrows-at-runtime-12", "text": "The Rust Programming Language › `RefCell` and the Interior Mutability Pattern › Using Interior Mutability › Tracking Borrows at Runtime\n\n```console\n$ cargo test\n Compiling limit-tracker v0.1.0 (file:///projects/limit-tracker)\n Finished `test` profile [unoptimized + debuginfo] target(s) in 0.91s\n Running unittests src/lib.rs (target/debug/deps/limit_tracker-e599811fa246dbde)\n\nrunning 1 test\ntest tests::it_sends_an_over_75_percent_warning_message ... FAILED\n\nfailures:\n\n---- tests::it_sends_an_over_75_percent_warning_message stdout ----\n\nthread 'tests::it_sends_an_over_75_percent_warning_message' (6028024) panicked at src/lib.rs:60:53:\nRefCell already borrowed\nnote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n\n\nfailures:\n tests::it_sends_an_over_75_percent_warning_message\n\ntest result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n\nerror: test failed, to rerun pass `--lib`\n```\nNotice that the code panicked with the message `already borrowed:\nBorrowMutError`. This is how `RefCell` handles violations of the borrowing\nrules at runtime.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "`RefCell` and the Interior Mutability Pattern", "heading_path": ["`RefCell` and the Interior Mutability Pattern", "Using Interior Mutability", "Tracking Borrows at Runtime"], "path": "ch15-05-interior-mutability.md", "url": "https://doc.rust-lang.org/book/ch15-05-interior-mutability.html#tracking-borrows-at-runtime", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch15-05-interior-mutability.md#tracking-borrows-at-runtime-13", "text": "The Rust Programming Language › `RefCell` and the Interior Mutability Pattern › Using Interior Mutability › Tracking Borrows at Runtime\n\nChoosing to catch borrowing errors at runtime rather than compile time, as\nwe’ve done here, means you’d potentially be finding mistakes in your code later\nin the development process: possibly not until your code was deployed to\nproduction. Also, your code would incur a small runtime performance penalty as\na result of keeping track of the borrows at runtime rather than compile time.\nHowever, using `RefCell` makes it possible to write a mock object that can\nmodify itself to keep track of the messages it has seen while you’re using it\nin a context where only immutable values are allowed. You can use `RefCell`\ndespite its trade-offs to get more functionality than regular references\nprovide.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "`RefCell` and the Interior Mutability Pattern", "heading_path": ["`RefCell` and the Interior Mutability Pattern", "Using Interior Mutability", "Tracking Borrows at Runtime"], "path": "ch15-05-interior-mutability.md", "url": "https://doc.rust-lang.org/book/ch15-05-interior-mutability.html#tracking-borrows-at-runtime", "has_code": false, "code_tags": []}} {"id": "book/ch15-05-interior-mutability.md#allowing-multiple-owners-of-mutable-data-14", "text": "The Rust Programming Language › `RefCell` and the Interior Mutability Pattern › Allowing Multiple Owners of Mutable Data\n\nA common way to use `RefCell` is in combination with `Rc`. Recall that\n`Rc` lets you have multiple owners of some data, but it only gives immutable\naccess to that data. If you have an `Rc` that holds a `RefCell`, you can\nget a value that can have multiple owners _and_ that you can mutate!\nFor example, recall the cons list example in Listing 15-18 where we used\n`Rc` to allow multiple lists to share ownership of another list. Because\n`Rc` holds only immutable values, we can’t change any of the values in the\nlist once we’ve created them. Let’s add in `RefCell` for its ability to\nchange the values in the lists. Listing 15-24 shows that by using a\n`RefCell` in the `Cons` definition, we can modify the value stored in all\nthe lists.\nListing 15-24 (src/main.rs)\n```rust\n#[derive(Debug)]\nenum List {\n Cons(Rc>, Rc),\n Nil,\n}\n\nuse crate::List::{Cons, Nil};\nuse std::cell::RefCell;\nuse std::rc::Rc;\n\nfn main() {\n let value = Rc::new(RefCell::new(5));\n\n let a = Rc::new(Cons(Rc::clone(&value), Rc::new(Nil)));\n\n let b = Cons(Rc::new(RefCell::new(3)), Rc::clone(&a));\n let c = Cons(Rc::new(RefCell::new(4)), Rc::clone(&a));\n\n *value.borrow_mut() += 10;\n\n println!(\"a after = {a:?}\");\n println!(\"b after = {b:?}\");\n println!(\"c after = {c:?}\");\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "`RefCell` and the Interior Mutability Pattern", "heading_path": ["`RefCell` and the Interior Mutability Pattern", "Allowing Multiple Owners of Mutable Data"], "path": "ch15-05-interior-mutability.md", "url": "https://doc.rust-lang.org/book/ch15-05-interior-mutability.html#allowing-multiple-owners-of-mutable-data", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch15-05-interior-mutability.md#allowing-multiple-owners-of-mutable-data-15", "text": "The Rust Programming Language › `RefCell` and the Interior Mutability Pattern › Allowing Multiple Owners of Mutable Data\n\nWe create a value that is an instance of `Rc>` and store it in a\nvariable named `value` so that we can access it directly later. Then, we create\na `List` in `a` with a `Cons` variant that holds `value`. We need to clone\n`value` so that both `a` and `value` have ownership of the inner `5` value\nrather than transferring ownership from `value` to `a` or having `a` borrow\nfrom `value`.\nWe wrap the list `a` in an `Rc` so that when we create lists `b` and `c`,\nthey can both refer to `a`, which is what we did in Listing 15-18.\nAfter we’ve created the lists in `a`, `b`, and `c`, we want to add 10 to the\nvalue in `value`. We do this by calling `borrow_mut` on `value`, which uses the\nautomatic dereferencing feature we discussed in “Where’s the `->`\nOperator?” in Chapter 5 to dereference\nthe `Rc` to the inner `RefCell` value. The `borrow_mut` method returns a\n`RefMut` smart pointer, and we use the dereference operator on it and change\nthe inner value.\nWhen we print `a`, `b`, and `c`, we can see that they all have the modified\nvalue of `15` rather than `5`:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "`RefCell` and the Interior Mutability Pattern", "heading_path": ["`RefCell` and the Interior Mutability Pattern", "Allowing Multiple Owners of Mutable Data"], "path": "ch15-05-interior-mutability.md", "url": "https://doc.rust-lang.org/book/ch15-05-interior-mutability.html#allowing-multiple-owners-of-mutable-data", "has_code": false, "code_tags": []}} {"id": "book/ch15-05-interior-mutability.md#allowing-multiple-owners-of-mutable-data-16", "text": "The Rust Programming Language › `RefCell` and the Interior Mutability Pattern › Allowing Multiple Owners of Mutable Data\n\n```console\n$ cargo run\n Compiling cons-list v0.1.0 (file:///projects/cons-list)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.63s\n Running `target/debug/cons-list`\na after = Cons(RefCell { value: 15 }, Nil)\nb after = Cons(RefCell { value: 3 }, Cons(RefCell { value: 15 }, Nil))\nc after = Cons(RefCell { value: 4 }, Cons(RefCell { value: 15 }, Nil))\n```\nThis technique is pretty neat! By using `RefCell`, we have an outwardly\nimmutable `List` value. But we can use the methods on `RefCell` that provide\naccess to its interior mutability so that we can modify our data when we need\nto. The runtime checks of the borrowing rules protect us from data races, and\nit’s sometimes worth trading a bit of speed for this flexibility in our data\nstructures. Note that `RefCell` does not work for multithreaded code!\n`Mutex` is the thread-safe version of `RefCell`, and we’ll discuss\n`Mutex` in Chapter 16.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "`RefCell` and the Interior Mutability Pattern", "heading_path": ["`RefCell` and the Interior Mutability Pattern", "Allowing Multiple Owners of Mutable Data"], "path": "ch15-05-interior-mutability.md", "url": "https://doc.rust-lang.org/book/ch15-05-interior-mutability.html#allowing-multiple-owners-of-mutable-data", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch15-06-reference-cycles.md#reference-cycles-can-leak-memory-0", "text": "The Rust Programming Language › Reference Cycles Can Leak Memory\n\nRust’s memory safety guarantees make it difficult, but not impossible, to\naccidentally create memory that is never cleaned up (known as a _memory leak_).\nPreventing memory leaks entirely is not one of Rust’s guarantees, meaning\nmemory leaks are memory safe in Rust. We can see that Rust allows memory leaks\nby using `Rc` and `RefCell`: It’s possible to create references where\nitems refer to each other in a cycle. This creates memory leaks because the\nreference count of each item in the cycle will never reach 0, and the values\nwill never be dropped.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Reference Cycles Can Leak Memory", "heading_path": ["Reference Cycles Can Leak Memory"], "path": "ch15-06-reference-cycles.md", "url": "https://doc.rust-lang.org/book/ch15-06-reference-cycles.html#reference-cycles-can-leak-memory", "has_code": false, "code_tags": []}} {"id": "book/ch15-06-reference-cycles.md#creating-a-reference-cycle-1", "text": "The Rust Programming Language › Reference Cycles Can Leak Memory › Creating a Reference Cycle\n\nLet’s look at how a reference cycle might happen and how to prevent it,\nstarting with the definition of the `List` enum and a `tail` method in Listing\n15-25.\nListing 15-25 (src/main.rs)\n```rust\nuse crate::List::{Cons, Nil};\nuse std::cell::RefCell;\nuse std::rc::Rc;\n\n#[derive(Debug)]\nenum List {\n Cons(i32, RefCell>),\n Nil,\n}\n\nimpl List {\n fn tail(&self) -> Option<&RefCell>> {\n match self {\n Cons(_, item) => Some(item),\n Nil => None,\n }\n }\n}\n```\nWe’re using another variation of the `List` definition from Listing 15-5. The\nsecond element in the `Cons` variant is now `RefCell>`, meaning that\ninstead of having the ability to modify the `i32` value as we did in Listing\n15-24, we want to modify the `List` value a `Cons` variant is pointing to.\nWe’re also adding a `tail` method to make it convenient for us to access the\nsecond item if we have a `Cons` variant.\nIn Listing 15-26, we’re adding a `main` function that uses the definitions in\nListing 15-25. This code creates a list in `a` and a list in `b` that points to\nthe list in `a`. Then, it modifies the list in `a` to point to `b`, creating a\nreference cycle. There are `println!` statements along the way to show what the\nreference counts are at various points in this process.\nListing 15-26: Creating a reference cycle of two `List` values pointing to each other (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Reference Cycles Can Leak Memory", "heading_path": ["Reference Cycles Can Leak Memory", "Creating a Reference Cycle"], "path": "ch15-06-reference-cycles.md", "url": "https://doc.rust-lang.org/book/ch15-06-reference-cycles.html#creating-a-reference-cycle", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch15-06-reference-cycles.md#creating-a-reference-cycle-2", "text": "The Rust Programming Language › Reference Cycles Can Leak Memory › Creating a Reference Cycle\n\n```rust\nfn main() {\n let a = Rc::new(Cons(5, RefCell::new(Rc::new(Nil))));\n\n println!(\"a initial rc count = {}\", Rc::strong_count(&a));\n println!(\"a next item = {:?}\", a.tail());\n\n let b = Rc::new(Cons(10, RefCell::new(Rc::clone(&a))));\n\n println!(\"a rc count after b creation = {}\", Rc::strong_count(&a));\n println!(\"b initial rc count = {}\", Rc::strong_count(&b));\n println!(\"b next item = {:?}\", b.tail());\n\n if let Some(link) = a.tail() {\n *link.borrow_mut() = Rc::clone(&b);\n }\n\n println!(\"b rc count after changing a = {}\", Rc::strong_count(&b));\n println!(\"a rc count after changing a = {}\", Rc::strong_count(&a));\n\n // Uncomment the next line to see that we have a cycle;\n // it will overflow the stack.\n // println!(\"a next item = {:?}\", a.tail());\n}\n```\nWe create an `Rc` instance holding a `List` value in the variable `a`\nwith an initial list of `5, Nil`. We then create an `Rc` instance holding\nanother `List` value in the variable `b` that contains the value `10` and\npoints to the list in `a`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Reference Cycles Can Leak Memory", "heading_path": ["Reference Cycles Can Leak Memory", "Creating a Reference Cycle"], "path": "ch15-06-reference-cycles.md", "url": "https://doc.rust-lang.org/book/ch15-06-reference-cycles.html#creating-a-reference-cycle", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch15-06-reference-cycles.md#creating-a-reference-cycle-3", "text": "The Rust Programming Language › Reference Cycles Can Leak Memory › Creating a Reference Cycle\n\nWe modify `a` so that it points to `b` instead of `Nil`, creating a cycle. We\ndo that by using the `tail` method to get a reference to the\n`RefCell>` in `a`, which we put in the variable `link`. Then, we use\nthe `borrow_mut` method on the `RefCell>` to change the value inside\nfrom an `Rc` that holds a `Nil` value to the `Rc` in `b`.\nWhen we run this code, keeping the last `println!` commented out for the\nmoment, we’ll get this output:\n```console\n$ cargo run\n Compiling cons-list v0.1.0 (file:///projects/cons-list)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.53s\n Running `target/debug/cons-list`\na initial rc count = 1\na next item = Some(RefCell { value: Nil })\na rc count after b creation = 2\nb initial rc count = 1\nb next item = Some(RefCell { value: Cons(5, RefCell { value: Nil }) })\nb rc count after changing a = 2\na rc count after changing a = 2\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Reference Cycles Can Leak Memory", "heading_path": ["Reference Cycles Can Leak Memory", "Creating a Reference Cycle"], "path": "ch15-06-reference-cycles.md", "url": "https://doc.rust-lang.org/book/ch15-06-reference-cycles.html#creating-a-reference-cycle", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch15-06-reference-cycles.md#creating-a-reference-cycle-4", "text": "The Rust Programming Language › Reference Cycles Can Leak Memory › Creating a Reference Cycle\n\nThe reference count of the `Rc` instances in both `a` and `b` is 2 after\nwe change the list in `a` to point to `b`. At the end of `main`, Rust drops the\nvariable `b`, which decreases the reference count of the `b` `Rc`\ninstance from 2 to 1. The memory that `Rc` has on the heap won’t be\ndropped at this point because its reference count is 1, not 0. Then, Rust drops\n`a`, which decreases the reference count of the `a` `Rc` instance from 2\nto 1 as well. This instance’s memory can’t be dropped either, because the other\n`Rc` instance still refers to it. The memory allocated to the list will\nremain uncollected forever. To visualize this reference cycle, we’ve created\nthe diagram in Figure 15-4.\n\"A\nFigure 15-4: A reference cycle of lists `a` and `b`\npointing to each other\nIf you uncomment the last `println!` and run the program, Rust will try to\nprint this cycle with `a` pointing to `b` pointing to `a` and so forth until it\noverflows the stack.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Reference Cycles Can Leak Memory", "heading_path": ["Reference Cycles Can Leak Memory", "Creating a Reference Cycle"], "path": "ch15-06-reference-cycles.md", "url": "https://doc.rust-lang.org/book/ch15-06-reference-cycles.html#creating-a-reference-cycle", "has_code": false, "code_tags": []}} {"id": "book/ch15-06-reference-cycles.md#creating-a-reference-cycle-5", "text": "The Rust Programming Language › Reference Cycles Can Leak Memory › Creating a Reference Cycle\n\nCompared to a real-world program, the consequences of creating a reference\ncycle in this example aren’t very dire: Right after we create the reference\ncycle, the program ends. However, if a more complex program allocated lots of\nmemory in a cycle and held onto it for a long time, the program would use more\nmemory than it needed and might overwhelm the system, causing it to run out of\navailable memory.\nCreating reference cycles is not easily done, but it’s not impossible either.\nIf you have `RefCell` values that contain `Rc` values or similar nested\ncombinations of types with interior mutability and reference counting, you must\nensure that you don’t create cycles; you can’t rely on Rust to catch them.\nCreating a reference cycle would be a logic bug in your program that you should\nuse automated tests, code reviews, and other software development practices to\nminimize.\nAnother solution for avoiding reference cycles is reorganizing your data\nstructures so that some references express ownership and some references don’t.\nAs a result, you can have cycles made up of some ownership relationships and\nsome non-ownership relationships, and only the ownership relationships affect\nwhether or not a value can be dropped. In Listing 15-25, we always want `Cons`\nvariants to own their list, so reorganizing the data structure isn’t possible.\nLet’s look at an example using graphs made up of parent nodes and child nodes\nto see when non-ownership relationships are an appropriate way to prevent\nreference cycles.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Reference Cycles Can Leak Memory", "heading_path": ["Reference Cycles Can Leak Memory", "Creating a Reference Cycle"], "path": "ch15-06-reference-cycles.md", "url": "https://doc.rust-lang.org/book/ch15-06-reference-cycles.html#creating-a-reference-cycle", "has_code": false, "code_tags": []}} {"id": "book/ch15-06-reference-cycles.md#preventing-reference-cycles-using-weakt-6", "text": "The Rust Programming Language › Reference Cycles Can Leak Memory › Preventing Reference Cycles Using `Weak`\n\nSo far, we’ve demonstrated that calling `Rc::clone` increases the\n`strong_count` of an `Rc` instance, and an `Rc` instance is only cleaned\nup if its `strong_count` is 0. You can also create a weak reference to the\nvalue within an `Rc` instance by calling `Rc::downgrade` and passing a\nreference to the `Rc`. *Strong references* are how you can share ownership\nof an `Rc` instance. *Weak references* don’t express an ownership\nrelationship, and their count doesn’t affect when an `Rc` instance is\ncleaned up. They won’t cause a reference cycle, because any cycle involving\nsome weak references will be broken once the strong reference count of values\ninvolved is 0.\nWhen you call `Rc::downgrade`, you get a smart pointer of type `Weak`.\nInstead of increasing the `strong_count` in the `Rc` instance by 1, calling\n`Rc::downgrade` increases the `weak_count` by 1. The `Rc` type uses\n`weak_count` to keep track of how many `Weak` references exist, similar to\n`strong_count`. The difference is the `weak_count` doesn’t need to be 0 for the\n`Rc` instance to be cleaned up.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Reference Cycles Can Leak Memory", "heading_path": ["Reference Cycles Can Leak Memory", "Preventing Reference Cycles Using `Weak`"], "path": "ch15-06-reference-cycles.md", "url": "https://doc.rust-lang.org/book/ch15-06-reference-cycles.html#preventing-reference-cycles-using-weakt", "has_code": false, "code_tags": []}} {"id": "book/ch15-06-reference-cycles.md#creating-a-tree-data-structure-7", "text": "The Rust Programming Language › Reference Cycles Can Leak Memory › Preventing Reference Cycles Using `Weak` › Creating a Tree Data Structure\n\nBecause the value that `Weak` references might have been dropped, to do\nanything with the value that a `Weak` is pointing to you must make sure the\nvalue still exists. Do this by calling the `upgrade` method on a `Weak`\ninstance, which will return an `Option>`. You’ll get a result of `Some`\nif the `Rc` value has not been dropped yet and a result of `None` if the\n`Rc` value has been dropped. Because `upgrade` returns an `Option>`,\nRust will ensure that the `Some` case and the `None` case are handled, and\nthere won’t be an invalid pointer.\nAs an example, rather than using a list whose items know only about the next\nitem, we’ll create a tree whose items know about their child items _and_ their\nparent items.\nTo start, we’ll build a tree with nodes that know about their child nodes.\nWe’ll create a struct named `Node` that holds its own `i32` value as well as\nreferences to its child `Node` values:\nFilename: src/main.rs\n```rust\nuse std::cell::RefCell;\nuse std::rc::Rc;\n\n#[derive(Debug)]\nstruct Node {\n value: i32,\n children: RefCell>>,\n}\n```\nWe want a `Node` to own its children, and we want to share that ownership with\nvariables so that we can access each `Node` in the tree directly. To do this,\nwe define the `Vec` items to be values of type `Rc`. We also want to\nmodify which nodes are children of another node, so we have a `RefCell` in\n`children` around the `Vec>`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Reference Cycles Can Leak Memory", "heading_path": ["Reference Cycles Can Leak Memory", "Preventing Reference Cycles Using `Weak`", "Creating a Tree Data Structure"], "path": "ch15-06-reference-cycles.md", "url": "https://doc.rust-lang.org/book/ch15-06-reference-cycles.html#creating-a-tree-data-structure", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch15-06-reference-cycles.md#adding-a-reference-from-a-child-to-its-parent-8", "text": "The Rust Programming Language › Reference Cycles Can Leak Memory › Preventing Reference Cycles Using `Weak` › Adding a Reference from a Child to Its Parent\n\nNext, we’ll use our struct definition and create one `Node` instance named\n`leaf` with the value `3` and no children, and another instance named `branch`\nwith the value `5` and `leaf` as one of its children, as shown in Listing 15-27.\nListing 15-27: Creating a `leaf` node with no children and a `branch` node with `leaf` as one of its children (src/main.rs)\n```rust\nfn main() {\n let leaf = Rc::new(Node {\n value: 3,\n children: RefCell::new(vec![]),\n });\n\n let branch = Rc::new(Node {\n value: 5,\n children: RefCell::new(vec![Rc::clone(&leaf)]),\n });\n}\n```\nWe clone the `Rc` in `leaf` and store that in `branch`, meaning the\n`Node` in `leaf` now has two owners: `leaf` and `branch`. We can get from\n`branch` to `leaf` through `branch.children`, but there’s no way to get from\n`leaf` to `branch`. The reason is that `leaf` has no reference to `branch` and\ndoesn’t know they’re related. We want `leaf` to know that `branch` is its\nparent. We’ll do that next.\nTo make the child node aware of its parent, we need to add a `parent` field to\nour `Node` struct definition. The trouble is in deciding what the type of\n`parent` should be. We know it can’t contain an `Rc`, because that would\ncreate a reference cycle with `leaf.parent` pointing to `branch` and\n`branch.children` pointing to `leaf`, which would cause their `strong_count`\nvalues to never be 0.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Reference Cycles Can Leak Memory", "heading_path": ["Reference Cycles Can Leak Memory", "Preventing Reference Cycles Using `Weak`", "Adding a Reference from a Child to Its Parent"], "path": "ch15-06-reference-cycles.md", "url": "https://doc.rust-lang.org/book/ch15-06-reference-cycles.html#adding-a-reference-from-a-child-to-its-parent", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch15-06-reference-cycles.md#adding-a-reference-from-a-child-to-its-parent-9", "text": "The Rust Programming Language › Reference Cycles Can Leak Memory › Preventing Reference Cycles Using `Weak` › Adding a Reference from a Child to Its Parent\n\nThinking about the relationships another way, a parent node should own its\nchildren: If a parent node is dropped, its child nodes should be dropped as\nwell. However, a child should not own its parent: If we drop a child node, the\nparent should still exist. This is a case for weak references!\nSo, instead of `Rc`, we’ll make the type of `parent` use `Weak`,\nspecifically a `RefCell>`. Now our `Node` struct definition looks\nlike this:\nFilename: src/main.rs\n```rust\nuse std::cell::RefCell;\nuse std::rc::{Rc, Weak};\n\n#[derive(Debug)]\nstruct Node {\n value: i32,\n parent: RefCell>,\n children: RefCell>>,\n}\n```\nA node will be able to refer to its parent node but doesn’t own its parent. In\nListing 15-28, we update `main` to use this new definition so that the `leaf`\nnode will have a way to refer to its parent, `branch`.\nListing 15-28: A `leaf` node with a weak reference to its parent node, `branch` (src/main.rs)\n```rust\nfn main() {\n let leaf = Rc::new(Node {\n value: 3,\n parent: RefCell::new(Weak::new()),\n children: RefCell::new(vec![]),\n });\n\n println!(\"leaf parent = {:?}\", leaf.parent.borrow().upgrade());\n\n let branch = Rc::new(Node {\n value: 5,\n parent: RefCell::new(Weak::new()),\n children: RefCell::new(vec![Rc::clone(&leaf)]),\n });\n\n *leaf.parent.borrow_mut() = Rc::downgrade(&branch);\n\n println!(\"leaf parent = {:?}\", leaf.parent.borrow().upgrade());\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Reference Cycles Can Leak Memory", "heading_path": ["Reference Cycles Can Leak Memory", "Preventing Reference Cycles Using `Weak`", "Adding a Reference from a Child to Its Parent"], "path": "ch15-06-reference-cycles.md", "url": "https://doc.rust-lang.org/book/ch15-06-reference-cycles.html#adding-a-reference-from-a-child-to-its-parent", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch15-06-reference-cycles.md#adding-a-reference-from-a-child-to-its-parent-10", "text": "The Rust Programming Language › Reference Cycles Can Leak Memory › Preventing Reference Cycles Using `Weak` › Adding a Reference from a Child to Its Parent\n\nCreating the `leaf` node looks similar to Listing 15-27 with the exception of\nthe `parent` field: `leaf` starts out without a parent, so we create a new,\nempty `Weak` reference instance.\nAt this point, when we try to get a reference to the parent of `leaf` by using\nthe `upgrade` method, we get a `None` value. We see this in the output from the\nfirst `println!` statement:\n```text\nleaf parent = None\n```\nWhen we create the `branch` node, it will also have a new `Weak`\nreference in the `parent` field because `branch` doesn’t have a parent node. We\nstill have `leaf` as one of the children of `branch`. Once we have the `Node`\ninstance in `branch`, we can modify `leaf` to give it a `Weak` reference\nto its parent. We use the `borrow_mut` method on the `RefCell>` in\nthe `parent` field of `leaf`, and then we use the `Rc::downgrade` function to\ncreate a `Weak` reference to `branch` from the `Rc` in `branch`.\nWhen we print the parent of `leaf` again, this time we’ll get a `Some` variant\nholding `branch`: Now `leaf` can access its parent! When we print `leaf`, we\nalso avoid the cycle that eventually ended in a stack overflow like we had in\nListing 15-26; the `Weak` references are printed as `(Weak)`:\n```text\nleaf parent = Some(Node { value: 5, parent: RefCell { value: (Weak) },\nchildren: RefCell { value: [Node { value: 3, parent: RefCell { value: (Weak) },\nchildren: RefCell { value: [] } }] } })\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Reference Cycles Can Leak Memory", "heading_path": ["Reference Cycles Can Leak Memory", "Preventing Reference Cycles Using `Weak`", "Adding a Reference from a Child to Its Parent"], "path": "ch15-06-reference-cycles.md", "url": "https://doc.rust-lang.org/book/ch15-06-reference-cycles.html#adding-a-reference-from-a-child-to-its-parent", "has_code": true, "code_tags": ["text"]}} {"id": "book/ch15-06-reference-cycles.md#visualizing-changes-to-strong_count-and-weak_count-11", "text": "The Rust Programming Language › Reference Cycles Can Leak Memory › Preventing Reference Cycles Using `Weak` › Visualizing Changes to `strong_count` and `weak_count`\n\nThe lack of infinite output indicates that this code didn’t create a reference\ncycle. We can also tell this by looking at the values we get from calling\n`Rc::strong_count` and `Rc::weak_count`.\nLet’s look at how the `strong_count` and `weak_count` values of the `Rc`\ninstances change by creating a new inner scope and moving the creation of\n`branch` into that scope. By doing so, we can see what happens when `branch` is\ncreated and then dropped when it goes out of scope. The modifications are shown\nin Listing 15-29.\nListing 15-29: Creating `branch` in an inner scope and examining strong and weak reference counts (src/main.rs)\n```rust\nfn main() {\n let leaf = Rc::new(Node {\n value: 3,\n parent: RefCell::new(Weak::new()),\n children: RefCell::new(vec![]),\n });\n\n println!(\n \"leaf strong = {}, weak = {}\",\n Rc::strong_count(&leaf),\n Rc::weak_count(&leaf),\n );\n\n {\n let branch = Rc::new(Node {\n value: 5,\n parent: RefCell::new(Weak::new()),\n children: RefCell::new(vec![Rc::clone(&leaf)]),\n });\n\n *leaf.parent.borrow_mut() = Rc::downgrade(&branch);\n\n println!(\n \"branch strong = {}, weak = {}\",\n Rc::strong_count(&branch),\n Rc::weak_count(&branch),\n );\n\n println!(\n \"leaf strong = {}, weak = {}\",\n Rc::strong_count(&leaf),\n Rc::weak_count(&leaf),\n );\n }\n\n println!(\"leaf parent = {:?}\", leaf.parent.borrow().upgrade());\n println!(\n \"leaf strong = {}, weak = {}\",\n Rc::strong_count(&leaf),\n Rc::weak_count(&leaf),\n );\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Reference Cycles Can Leak Memory", "heading_path": ["Reference Cycles Can Leak Memory", "Preventing Reference Cycles Using `Weak`", "Visualizing Changes to `strong_count` and `weak_count`"], "path": "ch15-06-reference-cycles.md", "url": "https://doc.rust-lang.org/book/ch15-06-reference-cycles.html#visualizing-changes-to-strong_count-and-weak_count", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch15-06-reference-cycles.md#visualizing-changes-to-strong_count-and-weak_count-12", "text": "The Rust Programming Language › Reference Cycles Can Leak Memory › Preventing Reference Cycles Using `Weak` › Visualizing Changes to `strong_count` and `weak_count`\n\nAfter `leaf` is created, its `Rc` has a strong count of 1 and a weak\ncount of 0. In the inner scope, we create `branch` and associate it with\n`leaf`, at which point when we print the counts, the `Rc` in `branch`\nwill have a strong count of 1 and a weak count of 1 (for `leaf.parent` pointing\nto `branch` with a `Weak`). When we print the counts in `leaf`, we’ll see\nit will have a strong count of 2 because `branch` now has a clone of the\n`Rc` of `leaf` stored in `branch.children` but will still have a weak\ncount of 0.\nWhen the inner scope ends, `branch` goes out of scope and the strong count of\nthe `Rc` decreases to 0, so its `Node` is dropped. The weak count of 1\nfrom `leaf.parent` has no bearing on whether or not `Node` is dropped, so we\ndon’t get any memory leaks!\nIf we try to access the parent of `leaf` after the end of the scope, we’ll get\n`None` again. At the end of the program, the `Rc` in `leaf` has a strong\ncount of 1 and a weak count of 0 because the variable `leaf` is now the only\nreference to the `Rc` again.\nAll of the logic that manages the counts and value dropping is built into\n`Rc` and `Weak` and their implementations of the `Drop` trait. By\nspecifying that the relationship from a child to its parent should be a\n`Weak` reference in the definition of `Node`, you’re able to have parent\nnodes point to child nodes and vice versa without creating a reference cycle\nand memory leaks.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Reference Cycles Can Leak Memory", "heading_path": ["Reference Cycles Can Leak Memory", "Preventing Reference Cycles Using `Weak`", "Visualizing Changes to `strong_count` and `weak_count`"], "path": "ch15-06-reference-cycles.md", "url": "https://doc.rust-lang.org/book/ch15-06-reference-cycles.html#visualizing-changes-to-strong_count-and-weak_count", "has_code": false, "code_tags": []}} {"id": "book/ch15-06-reference-cycles.md#summary-13", "text": "The Rust Programming Language › Summary\n\nThis chapter covered how to use smart pointers to make different guarantees and\ntrade-offs from those Rust makes by default with regular references. The\n`Box` type has a known size and points to data allocated on the heap. The\n`Rc` type keeps track of the number of references to data on the heap so\nthat the data can have multiple owners. The `RefCell` type with its interior\nmutability gives us a type that we can use when we need an immutable type but\nneed to change an inner value of that type; it also enforces the borrowing\nrules at runtime instead of at compile time.\nAlso discussed were the `Deref` and `Drop` traits, which enable a lot of the\nfunctionality of smart pointers. We explored reference cycles that can cause\nmemory leaks and how to prevent them using `Weak`.\nIf this chapter has piqued your interest and you want to implement your own\nsmart pointers, check out “The Rustonomicon” for more useful\ninformation.\nNext, we’ll talk about concurrency in Rust. You’ll even learn about a few new\nsmart pointers.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Reference Cycles Can Leak Memory", "heading_path": ["Summary"], "path": "ch15-06-reference-cycles.md", "url": "https://doc.rust-lang.org/book/ch15-06-reference-cycles.html#summary", "has_code": false, "code_tags": []}} {"id": "book/ch16-00-concurrency.md#fearless-concurrency-0", "text": "The Rust Programming Language › Fearless Concurrency\n\nHandling concurrent programming safely and efficiently is another of Rust’s\nmajor goals. _Concurrent programming_, in which different parts of a program\nexecute independently, and _parallel programming_, in which different parts of\na program execute at the same time, are becoming increasingly important as more\ncomputers take advantage of their multiple processors. Historically,\nprogramming in these contexts has been difficult and error-prone. Rust hopes to\nchange that.\nInitially, the Rust team thought that ensuring memory safety and preventing\nconcurrency problems were two separate challenges to be solved with different\nmethods. Over time, the team discovered that the ownership and type systems are\na powerful set of tools to help manage memory safety _and_ concurrency\nproblems! By leveraging ownership and type checking, many concurrency errors\nare compile-time errors in Rust rather than runtime errors. Therefore, rather\nthan making you spend lots of time trying to reproduce the exact circumstances\nunder which a runtime concurrency bug occurs, incorrect code will refuse to\ncompile and present an error explaining the problem. As a result, you can fix\nyour code while you’re working on it rather than potentially after it has been\nshipped to production. We’ve nicknamed this aspect of Rust _fearless\nconcurrency_. Fearless concurrency allows you to write code that is free of\nsubtle bugs and is easy to refactor without introducing new bugs.\nNote: For simplicity’s sake, we’ll refer to many of the problems as\n_concurrent_ rather than being more precise by saying _concurrent and/or\nparallel_. For this chapter, please mentally substitute _concurrent and/or\nparallel_ whenever we use _concurrent_. In the next chapter, where the\ndistinction matters more, we’ll be more specific.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Fearless Concurrency", "heading_path": ["Fearless Concurrency"], "path": "ch16-00-concurrency.md", "url": "https://doc.rust-lang.org/book/ch16-00-concurrency.html#fearless-concurrency", "has_code": false, "code_tags": []}} {"id": "book/ch16-00-concurrency.md#fearless-concurrency-1", "text": "The Rust Programming Language › Fearless Concurrency\n\nMany languages are dogmatic about the solutions they offer for handling\nconcurrent problems. For example, Erlang has elegant functionality for\nmessage-passing concurrency but has only obscure ways to share state between\nthreads. Supporting only a subset of possible solutions is a reasonable\nstrategy for higher-level languages because a higher-level language promises\nbenefits from giving up some control to gain abstractions. However, lower-level\nlanguages are expected to provide the solution with the best performance in any\ngiven situation and have fewer abstractions over the hardware. Therefore, Rust\noffers a variety of tools for modeling problems in whatever way is appropriate\nfor your situation and requirements.\nHere are the topics we’ll cover in this chapter:\n- How to create threads to run multiple pieces of code at the same time\n- _Message-passing_ concurrency, where channels send messages between threads\n- _Shared-state_ concurrency, where multiple threads have access to some piece\n of data\n- The `Sync` and `Send` traits, which extend Rust’s concurrency guarantees to\n user-defined types as well as types provided by the standard library", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Fearless Concurrency", "heading_path": ["Fearless Concurrency"], "path": "ch16-00-concurrency.md", "url": "https://doc.rust-lang.org/book/ch16-00-concurrency.html#fearless-concurrency", "has_code": false, "code_tags": []}} {"id": "book/ch16-01-threads.md#using-threads-to-run-code-simultaneously-0", "text": "The Rust Programming Language › Using Threads to Run Code Simultaneously\n\nIn most current operating systems, an executed program’s code is run in a\n_process_, and the operating system will manage multiple processes at once.\nWithin a program, you can also have independent parts that run simultaneously.\nThe features that run these independent parts are called _threads_. For\nexample, a web server could have multiple threads so that it can respond to\nmore than one request at the same time.\nSplitting the computation in your program into multiple threads to run multiple\ntasks at the same time can improve performance, but it also adds complexity.\nBecause threads can run simultaneously, there’s no inherent guarantee about the\norder in which parts of your code on different threads will run. This can lead\nto problems, such as:\n- Race conditions, in which threads are accessing data or resources in an\n inconsistent order\n- Deadlocks, in which two threads are waiting for each other, preventing both\n threads from continuing\n- Bugs that only happen in certain situations and are hard to reproduce and fix\n reliably\nRust attempts to mitigate the negative effects of using threads, but\nprogramming in a multithreaded context still takes careful thought and requires\na code structure that is different from that in programs running in a single\nthread.\nProgramming languages implement threads in a few different ways, and many\noperating systems provide an API the programming language can call for creating\nnew threads. The Rust standard library uses a _1:1_ model of thread\nimplementation, whereby a program uses one operating system thread per one\nlanguage thread. There are crates that implement other models of threading that\nmake different trade-offs to the 1:1 model. (Rust’s async system, which we will\nsee in the next chapter, provides another approach to concurrency as well.)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using Threads to Run Code Simultaneously", "heading_path": ["Using Threads to Run Code Simultaneously"], "path": "ch16-01-threads.md", "url": "https://doc.rust-lang.org/book/ch16-01-threads.html#using-threads-to-run-code-simultaneously", "has_code": false, "code_tags": []}} {"id": "book/ch16-01-threads.md#creating-a-new-thread-with-spawn-1", "text": "The Rust Programming Language › Using Threads to Run Code Simultaneously › Creating a New Thread with `spawn`\n\nTo create a new thread, we call the `thread::spawn` function and pass it a\nclosure (we talked about closures in Chapter 13) containing the code we want to\nrun in the new thread. The example in Listing 16-1 prints some text from a main\nthread and other text from a new thread.\nListing 16-1: Creating a new thread to print one thing while the main thread prints something else (src/main.rs)\n```rust\nuse std::thread;\nuse std::time::Duration;\n\nfn main() {\n thread::spawn(|| {\n for i in 1..10 {\n println!(\"hi number {i} from the spawned thread!\");\n thread::sleep(Duration::from_millis(1));\n }\n });\n\n for i in 1..5 {\n println!(\"hi number {i} from the main thread!\");\n thread::sleep(Duration::from_millis(1));\n }\n}\n```\nNote that when the main thread of a Rust program completes, all spawned threads\nare shut down, whether or not they have finished running. The output from this\nprogram might be a little different every time, but it will look similar to the\nfollowing:\n```text\nhi number 1 from the main thread!\nhi number 1 from the spawned thread!\nhi number 2 from the main thread!\nhi number 2 from the spawned thread!\nhi number 3 from the main thread!\nhi number 3 from the spawned thread!\nhi number 4 from the main thread!\nhi number 4 from the spawned thread!\nhi number 5 from the spawned thread!\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using Threads to Run Code Simultaneously", "heading_path": ["Using Threads to Run Code Simultaneously", "Creating a New Thread with `spawn`"], "path": "ch16-01-threads.md", "url": "https://doc.rust-lang.org/book/ch16-01-threads.html#creating-a-new-thread-with-spawn", "has_code": true, "code_tags": ["rust", "text"]}} {"id": "book/ch16-01-threads.md#creating-a-new-thread-with-spawn-2", "text": "The Rust Programming Language › Using Threads to Run Code Simultaneously › Creating a New Thread with `spawn`\n\nThe calls to `thread::sleep` force a thread to stop its execution for a short\nduration, allowing a different thread to run. The threads will probably take\nturns, but that isn’t guaranteed: It depends on how your operating system\nschedules the threads. In this run, the main thread printed first, even though\nthe print statement from the spawned thread appears first in the code. And even\nthough we told the spawned thread to print until `i` is `9`, it only got to `5`\nbefore the main thread shut down.\nIf you run this code and only see output from the main thread, or don’t see any\noverlap, try increasing the numbers in the ranges to create more opportunities\nfor the operating system to switch between the threads.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using Threads to Run Code Simultaneously", "heading_path": ["Using Threads to Run Code Simultaneously", "Creating a New Thread with `spawn`"], "path": "ch16-01-threads.md", "url": "https://doc.rust-lang.org/book/ch16-01-threads.html#creating-a-new-thread-with-spawn", "has_code": false, "code_tags": []}} {"id": "book/ch16-01-threads.md#waiting-for-all-threads-to-finish-3", "text": "The Rust Programming Language › Using Threads to Run Code Simultaneously › Waiting for All Threads to Finish\n\nThe code in Listing 16-1 not only stops the spawned thread prematurely most of\nthe time due to the main thread ending, but because there is no guarantee on\nthe order in which threads run, we also can’t guarantee that the spawned thread\nwill get to run at all!\nWe can fix the problem of the spawned thread not running or of it ending\nprematurely by saving the return value of `thread::spawn` in a variable. The\nreturn type of `thread::spawn` is `JoinHandle`. A `JoinHandle` is an\nowned value that, when we call the `join` method on it, will wait for its\nthread to finish. Listing 16-2 shows how to use the `JoinHandle` of the\nthread we created in Listing 16-1 and how to call `join` to make sure the\nspawned thread finishes before `main` exits.\nListing 16-2 (src/main.rs)\n```rust\nuse std::thread;\nuse std::time::Duration;\n\nfn main() {\n let handle = thread::spawn(|| {\n for i in 1..10 {\n println!(\"hi number {i} from the spawned thread!\");\n thread::sleep(Duration::from_millis(1));\n }\n });\n\n for i in 1..5 {\n println!(\"hi number {i} from the main thread!\");\n thread::sleep(Duration::from_millis(1));\n }\n\n handle.join().unwrap();\n}\n```\nCalling `join` on the handle blocks the thread currently running until the\nthread represented by the handle terminates. _Blocking_ a thread means that\nthread is prevented from performing work or exiting. Because we’ve put the call\nto `join` after the main thread’s `for` loop, running Listing 16-2 should\nproduce output similar to this:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using Threads to Run Code Simultaneously", "heading_path": ["Using Threads to Run Code Simultaneously", "Waiting for All Threads to Finish"], "path": "ch16-01-threads.md", "url": "https://doc.rust-lang.org/book/ch16-01-threads.html#waiting-for-all-threads-to-finish", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch16-01-threads.md#waiting-for-all-threads-to-finish-4", "text": "The Rust Programming Language › Using Threads to Run Code Simultaneously › Waiting for All Threads to Finish\n\n```text\nhi number 1 from the main thread!\nhi number 2 from the main thread!\nhi number 1 from the spawned thread!\nhi number 3 from the main thread!\nhi number 2 from the spawned thread!\nhi number 4 from the main thread!\nhi number 3 from the spawned thread!\nhi number 4 from the spawned thread!\nhi number 5 from the spawned thread!\nhi number 6 from the spawned thread!\nhi number 7 from the spawned thread!\nhi number 8 from the spawned thread!\nhi number 9 from the spawned thread!\n```\nThe two threads continue alternating, but the main thread waits because of the\ncall to `handle.join()` and does not end until the spawned thread is finished.\nBut let’s see what happens when we instead move `handle.join()` before the\n`for` loop in `main`, like this:\nListing (src/main.rs)\n```rust\nuse std::thread;\nuse std::time::Duration;\n\nfn main() {\n let handle = thread::spawn(|| {\n for i in 1..10 {\n println!(\"hi number {i} from the spawned thread!\");\n thread::sleep(Duration::from_millis(1));\n }\n });\n\n handle.join().unwrap();\n\n for i in 1..5 {\n println!(\"hi number {i} from the main thread!\");\n thread::sleep(Duration::from_millis(1));\n }\n}\n```\nThe main thread will wait for the spawned thread to finish and then run its\n`for` loop, so the output won’t be interleaved anymore, as shown here:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using Threads to Run Code Simultaneously", "heading_path": ["Using Threads to Run Code Simultaneously", "Waiting for All Threads to Finish"], "path": "ch16-01-threads.md", "url": "https://doc.rust-lang.org/book/ch16-01-threads.html#waiting-for-all-threads-to-finish", "has_code": true, "code_tags": ["rust", "text"]}} {"id": "book/ch16-01-threads.md#waiting-for-all-threads-to-finish-5", "text": "The Rust Programming Language › Using Threads to Run Code Simultaneously › Waiting for All Threads to Finish\n\n```text\nhi number 1 from the spawned thread!\nhi number 2 from the spawned thread!\nhi number 3 from the spawned thread!\nhi number 4 from the spawned thread!\nhi number 5 from the spawned thread!\nhi number 6 from the spawned thread!\nhi number 7 from the spawned thread!\nhi number 8 from the spawned thread!\nhi number 9 from the spawned thread!\nhi number 1 from the main thread!\nhi number 2 from the main thread!\nhi number 3 from the main thread!\nhi number 4 from the main thread!\n```\nSmall details, such as where `join` is called, can affect whether or not your\nthreads run at the same time.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using Threads to Run Code Simultaneously", "heading_path": ["Using Threads to Run Code Simultaneously", "Waiting for All Threads to Finish"], "path": "ch16-01-threads.md", "url": "https://doc.rust-lang.org/book/ch16-01-threads.html#waiting-for-all-threads-to-finish", "has_code": true, "code_tags": ["text"]}} {"id": "book/ch16-01-threads.md#using-move-closures-with-threads-6", "text": "The Rust Programming Language › Using Threads to Run Code Simultaneously › Using `move` Closures with Threads\n\nWe’ll often use the `move` keyword with closures passed to `thread::spawn`\nbecause the closure will then take ownership of the values it uses from the\nenvironment, thus transferring ownership of those values from one thread to\nanother. In “Capturing References or Moving Ownership”\n in Chapter 13, we discussed `move` in the context of closures. Now we’ll\nconcentrate more on the interaction between `move` and `thread::spawn`.\nNotice in Listing 16-1 that the closure we pass to `thread::spawn` takes no\narguments: We’re not using any data from the main thread in the spawned\nthread’s code. To use data from the main thread in the spawned thread, the\nspawned thread’s closure must capture the values it needs. Listing 16-3 shows\nan attempt to create a vector in the main thread and use it in the spawned\nthread. However, this won’t work yet, as you’ll see in a moment.\nListing 16-3: Attempting to use a vector created by the main thread in another thread (src/main.rs)\n```rust,ignore,does_not_compile\nuse std::thread;\n\nfn main() {\n let v = vec![1, 2, 3];\n\n let handle = thread::spawn(|| {\n println!(\"Here's a vector: {v:?}\");\n });\n\n handle.join().unwrap();\n}\n```\nThe closure uses `v`, so it will capture `v` and make it part of the closure’s\nenvironment. Because `thread::spawn` runs this closure in a new thread, we\nshould be able to access `v` inside that new thread. But when we compile this\nexample, we get the following error:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using Threads to Run Code Simultaneously", "heading_path": ["Using Threads to Run Code Simultaneously", "Using `move` Closures with Threads"], "path": "ch16-01-threads.md", "url": "https://doc.rust-lang.org/book/ch16-01-threads.html#using-move-closures-with-threads", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch16-01-threads.md#using-move-closures-with-threads-7", "text": "The Rust Programming Language › Using Threads to Run Code Simultaneously › Using `move` Closures with Threads\n\n```console\n$ cargo run\n Compiling threads v0.1.0 (file:///projects/threads)\nerror[E0373]: closure may outlive the current function, but it borrows `v`, which is owned by the current function\n --> src/main.rs:6:32\n |\n6 | let handle = thread::spawn(|| {\n | ^^ may outlive borrowed value `v`\n7 | println!(\"Here's a vector: {v:?}\");\n | - `v` is borrowed here\n |\nnote: function requires argument type to outlive `'static`\n --> src/main.rs:6:18\n |\n6 | let handle = thread::spawn(|| {\n | __________________^\n7 | | println!(\"Here's a vector: {v:?}\");\n8 | | });\n | |______^\nhelp: to force the closure to take ownership of `v` (and any other referenced variables), use the `move` keyword\n |\n6 | let handle = thread::spawn(move || {\n | ++++\n\nFor more information about this error, try `rustc --explain E0373`.\nerror: could not compile `threads` (bin \"threads\") due to 1 previous error\n```\nRust _infers_ how to capture `v`, and because `println!` only needs a reference\nto `v`, the closure tries to borrow `v`. However, there’s a problem: Rust can’t\ntell how long the spawned thread will run, so it doesn’t know whether the\nreference to `v` will always be valid.\nListing 16-4 provides a scenario that’s more likely to have a reference to `v`\nthat won’t be valid.\nListing 16-4: A thread with a closure that attempts to capture a reference to `v` from a main thread that drops `v` (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using Threads to Run Code Simultaneously", "heading_path": ["Using Threads to Run Code Simultaneously", "Using `move` Closures with Threads"], "path": "ch16-01-threads.md", "url": "https://doc.rust-lang.org/book/ch16-01-threads.html#using-move-closures-with-threads", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch16-01-threads.md#using-move-closures-with-threads-8", "text": "The Rust Programming Language › Using Threads to Run Code Simultaneously › Using `move` Closures with Threads\n\n```rust,ignore,does_not_compile\nuse std::thread;\n\nfn main() {\n let v = vec![1, 2, 3];\n\n let handle = thread::spawn(|| {\n println!(\"Here's a vector: {v:?}\");\n });\n\n drop(v); // oh no!\n\n handle.join().unwrap();\n}\n```\nIf Rust allowed us to run this code, there’s a possibility that the spawned\nthread would be immediately put in the background without running at all. The\nspawned thread has a reference to `v` inside, but the main thread immediately\ndrops `v`, using the `drop` function we discussed in Chapter 15. Then, when the\nspawned thread starts to execute, `v` is no longer valid, so a reference to it\nis also invalid. Oh no!\nTo fix the compiler error in Listing 16-3, we can use the error message’s\nadvice:\n```text\nhelp: to force the closure to take ownership of `v` (and any other referenced variables), use the `move` keyword\n |\n6 | let handle = thread::spawn(move || {\n | ++++\n```\nBy adding the `move` keyword before the closure, we force the closure to take\nownership of the values it’s using rather than allowing Rust to infer that it\nshould borrow the values. The modification to Listing 16-3 shown in Listing\n16-5 will compile and run as we intend.\nListing 16-5: Using the `move` keyword to force a closure to take ownership of the values it uses (src/main.rs)\n```rust\nuse std::thread;\n\nfn main() {\n let v = vec![1, 2, 3];\n\n let handle = thread::spawn(move || {\n println!(\"Here's a vector: {v:?}\");\n });\n\n handle.join().unwrap();\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using Threads to Run Code Simultaneously", "heading_path": ["Using Threads to Run Code Simultaneously", "Using `move` Closures with Threads"], "path": "ch16-01-threads.md", "url": "https://doc.rust-lang.org/book/ch16-01-threads.html#using-move-closures-with-threads", "has_code": true, "code_tags": ["rust", "rust,ignore,does_not_compile", "text"]}} {"id": "book/ch16-01-threads.md#using-move-closures-with-threads-9", "text": "The Rust Programming Language › Using Threads to Run Code Simultaneously › Using `move` Closures with Threads\n\nWe might be tempted to try the same thing to fix the code in Listing 16-4 where\nthe main thread called `drop` by using a `move` closure. However, this fix will\nnot work because what Listing 16-4 is trying to do is disallowed for a\ndifferent reason. If we added `move` to the closure, we would move `v` into the\nclosure’s environment, and we could no longer call `drop` on it in the main\nthread. We would get this compiler error instead:\n```console\n$ cargo run\n Compiling threads v0.1.0 (file:///projects/threads)\nerror[E0382]: use of moved value: `v`\n --> src/main.rs:10:10\n |\n 4 | let v = vec![1, 2, 3];\n | - move occurs because `v` has type `Vec`, which does not implement the `Copy` trait\n 5 |\n 6 | let handle = thread::spawn(move || {\n | ------- value moved into closure here\n 7 | println!(\"Here's a vector: {v:?}\");\n | - variable moved due to use in closure\n...\n10 | drop(v); // oh no!\n | ^ value used here after move\n |\nhelp: consider cloning the value before moving it into the closure\n |\n 6 ~ let value = v.clone();\n 7 ~ let handle = thread::spawn(move || {\n 8 ~ println!(\"Here's a vector: {value:?}\");\n |\n\nFor more information about this error, try `rustc --explain E0382`.\nerror: could not compile `threads` (bin \"threads\") due to 1 previous error\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using Threads to Run Code Simultaneously", "heading_path": ["Using Threads to Run Code Simultaneously", "Using `move` Closures with Threads"], "path": "ch16-01-threads.md", "url": "https://doc.rust-lang.org/book/ch16-01-threads.html#using-move-closures-with-threads", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch16-01-threads.md#using-move-closures-with-threads-10", "text": "The Rust Programming Language › Using Threads to Run Code Simultaneously › Using `move` Closures with Threads\n\nRust’s ownership rules have saved us again! We got an error from the code in\nListing 16-3 because Rust was being conservative and only borrowing `v` for the\nthread, which meant the main thread could theoretically invalidate the spawned\nthread’s reference. By telling Rust to move ownership of `v` to the spawned\nthread, we’re guaranteeing to Rust that the main thread won’t use `v` anymore.\nIf we change Listing 16-4 in the same way, we’re then violating the ownership\nrules when we try to use `v` in the main thread. The `move` keyword overrides\nRust’s conservative default of borrowing; it doesn’t let us violate the\nownership rules.\nNow that we’ve covered what threads are and the methods supplied by the thread\nAPI, let’s look at some situations in which we can use threads.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using Threads to Run Code Simultaneously", "heading_path": ["Using Threads to Run Code Simultaneously", "Using `move` Closures with Threads"], "path": "ch16-01-threads.md", "url": "https://doc.rust-lang.org/book/ch16-01-threads.html#using-move-closures-with-threads", "has_code": false, "code_tags": []}} {"id": "book/ch16-02-message-passing.md#transfer-data-between-threads-with-message-passing-0", "text": "The Rust Programming Language › Transfer Data Between Threads with Message Passing\n\nOne increasingly popular approach to ensuring safe concurrency is message\npassing, where threads or actors communicate by sending each other messages\ncontaining data. Here’s the idea in a slogan from the Go language documentation:\n“Do not communicate by sharing memory; instead, share memory by communicating.”\nTo accomplish message-sending concurrency, Rust’s standard library provides an\nimplementation of channels. A _channel_ is a general programming concept by\nwhich data is sent from one thread to another.\nYou can imagine a channel in programming as being like a directional channel of\nwater, such as a stream or a river. If you put something like a rubber duck\ninto a river, it will travel downstream to the end of the waterway.\nA channel has two halves: a transmitter and a receiver. The transmitter half is\nthe upstream location where you put the rubber duck into the river, and the\nreceiver half is where the rubber duck ends up downstream. One part of your\ncode calls methods on the transmitter with the data you want to send, and\nanother part checks the receiving end for arriving messages. A channel is said\nto be _closed_ if either the transmitter or receiver half is dropped.\nHere, we’ll work up to a program that has one thread to generate values and\nsend them down a channel, and another thread that will receive the values and\nprint them out. We’ll be sending simple values between threads using a channel\nto illustrate the feature. Once you’re familiar with the technique, you could\nuse channels for any threads that need to communicate with each other, such as\na chat system or a system where many threads perform parts of a calculation and\nsend the parts to one thread that aggregates the results.\nFirst, in Listing 16-6, we’ll create a channel but not do anything with it.\nNote that this won’t compile yet because Rust can’t tell what type of values we\nwant to send over the channel.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Transfer Data Between Threads with Message Passing", "heading_path": ["Transfer Data Between Threads with Message Passing"], "path": "ch16-02-message-passing.md", "url": "https://doc.rust-lang.org/book/ch16-02-message-passing.html#transfer-data-between-threads-with-message-passing", "has_code": false, "code_tags": []}} {"id": "book/ch16-02-message-passing.md#transfer-data-between-threads-with-message-passing-1", "text": "The Rust Programming Language › Transfer Data Between Threads with Message Passing\n\nListing 16-6: Creating a channel and assigning the two halves to `tx` and `rx` (src/main.rs)\n```rust,ignore,does_not_compile\nuse std::sync::mpsc;\n\nfn main() {\n let (tx, rx) = mpsc::channel();\n}\n```\nWe create a new channel using the `mpsc::channel` function; `mpsc` stands for\n_multiple producer, single consumer_. In short, the way Rust’s standard library\nimplements channels means a channel can have multiple _sending_ ends that\nproduce values but only one _receiving_ end that consumes those values. Imagine\nmultiple streams flowing together into one big river: Everything sent down any\nof the streams will end up in one river at the end. We’ll start with a single\nproducer for now, but we’ll add multiple producers when we get this example\nworking.\nThe `mpsc::channel` function returns a tuple, the first element of which is the\nsending end—the transmitter—and the second element of which is the receiving\nend—the receiver. The abbreviations `tx` and `rx` are traditionally used in\nmany fields for _transmitter_ and _receiver_, respectively, so we name our\nvariables as such to indicate each end. We’re using a `let` statement with a\npattern that destructures the tuples; we’ll discuss the use of patterns in\n`let` statements and destructuring in Chapter 19. For now, know that using a\n`let` statement in this way is a convenient approach to extract the pieces of\nthe tuple returned by `mpsc::channel`.\nLet’s move the transmitting end into a spawned thread and have it send one\nstring so that the spawned thread is communicating with the main thread, as\nshown in Listing 16-7. This is like putting a rubber duck in the river upstream\nor sending a chat message from one thread to another.\nListing 16-7 (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Transfer Data Between Threads with Message Passing", "heading_path": ["Transfer Data Between Threads with Message Passing"], "path": "ch16-02-message-passing.md", "url": "https://doc.rust-lang.org/book/ch16-02-message-passing.html#transfer-data-between-threads-with-message-passing", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch16-02-message-passing.md#transfer-data-between-threads-with-message-passing-2", "text": "The Rust Programming Language › Transfer Data Between Threads with Message Passing\n\n```rust\nuse std::sync::mpsc;\nuse std::thread;\n\nfn main() {\n let (tx, rx) = mpsc::channel();\n\n thread::spawn(move || {\n let val = String::from(\"hi\");\n tx.send(val).unwrap();\n });\n}\n```\nAgain, we’re using `thread::spawn` to create a new thread and then using `move`\nto move `tx` into the closure so that the spawned thread owns `tx`. The spawned\nthread needs to own the transmitter to be able to send messages through the\nchannel.\nThe transmitter has a `send` method that takes the value we want to send. The\n`send` method returns a `Result` type, so if the receiver has already\nbeen dropped and there’s nowhere to send a value, the send operation will\nreturn an error. In this example, we’re calling `unwrap` to panic in case of an\nerror. But in a real application, we would handle it properly: Return to\nChapter 9 to review strategies for proper error handling.\nIn Listing 16-8, we’ll get the value from the receiver in the main thread. This\nis like retrieving the rubber duck from the water at the end of the river or\nreceiving a chat message.\nListing 16-8 (src/main.rs)\n```rust\nuse std::sync::mpsc;\nuse std::thread;\n\nfn main() {\n let (tx, rx) = mpsc::channel();\n\n thread::spawn(move || {\n let val = String::from(\"hi\");\n tx.send(val).unwrap();\n });\n\n let received = rx.recv().unwrap();\n println!(\"Got: {received}\");\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Transfer Data Between Threads with Message Passing", "heading_path": ["Transfer Data Between Threads with Message Passing"], "path": "ch16-02-message-passing.md", "url": "https://doc.rust-lang.org/book/ch16-02-message-passing.html#transfer-data-between-threads-with-message-passing", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch16-02-message-passing.md#transfer-data-between-threads-with-message-passing-3", "text": "The Rust Programming Language › Transfer Data Between Threads with Message Passing\n\nThe receiver has two useful methods: `recv` and `try_recv`. We’re using `recv`,\nshort for _receive_, which will block the main thread’s execution and wait\nuntil a value is sent down the channel. Once a value is sent, `recv` will\nreturn it in a `Result`. When the transmitter closes, `recv` will return\nan error to signal that no more values will be coming.\nThe `try_recv` method doesn’t block, but will instead return a `Result`\nimmediately: an `Ok` value holding a message if one is available and an `Err`\nvalue if there aren’t any messages this time. Using `try_recv` is useful if\nthis thread has other work to do while waiting for messages: We could write a\nloop that calls `try_recv` every so often, handles a message if one is\navailable, and otherwise does other work for a little while until checking\nagain.\nWe’ve used `recv` in this example for simplicity; we don’t have any other work\nfor the main thread to do other than wait for messages, so blocking the main\nthread is appropriate.\nWhen we run the code in Listing 16-8, we’ll see the value printed from the main\nthread:\n```text\nGot: hi\n```\nPerfect!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Transfer Data Between Threads with Message Passing", "heading_path": ["Transfer Data Between Threads with Message Passing"], "path": "ch16-02-message-passing.md", "url": "https://doc.rust-lang.org/book/ch16-02-message-passing.html#transfer-data-between-threads-with-message-passing", "has_code": true, "code_tags": ["text"]}} {"id": "book/ch16-02-message-passing.md#transferring-ownership-through-channels-4", "text": "The Rust Programming Language › Transfer Data Between Threads with Message Passing › Transferring Ownership Through Channels\n\nThe ownership rules play a vital role in message sending because they help you\nwrite safe, concurrent code. Preventing errors in concurrent programming is the\nadvantage of thinking about ownership throughout your Rust programs. Let’s do\nan experiment to show how channels and ownership work together to prevent\nproblems: We’ll try to use a `val` value in the spawned thread _after_ we’ve\nsent it down the channel. Try compiling the code in Listing 16-9 to see why\nthis code isn’t allowed.\nListing 16-9: Attempting to use `val` after we’ve sent it down the channel (src/main.rs)\n```rust,ignore,does_not_compile\nuse std::sync::mpsc;\nuse std::thread;\n\nfn main() {\n let (tx, rx) = mpsc::channel();\n\n thread::spawn(move || {\n let val = String::from(\"hi\");\n tx.send(val).unwrap();\n println!(\"val is {val}\");\n });\n\n let received = rx.recv().unwrap();\n println!(\"Got: {received}\");\n}\n```\nHere, we try to print `val` after we’ve sent it down the channel via `tx.send`.\nAllowing this would be a bad idea: Once the value has been sent to another\nthread, that thread could modify or drop it before we try to use the value\nagain. Potentially, the other thread’s modifications could cause errors or\nunexpected results due to inconsistent or nonexistent data. However, Rust gives\nus an error if we try to compile the code in Listing 16-9:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Transfer Data Between Threads with Message Passing", "heading_path": ["Transfer Data Between Threads with Message Passing", "Transferring Ownership Through Channels"], "path": "ch16-02-message-passing.md", "url": "https://doc.rust-lang.org/book/ch16-02-message-passing.html#transferring-ownership-through-channels", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch16-02-message-passing.md#transferring-ownership-through-channels-5", "text": "The Rust Programming Language › Transfer Data Between Threads with Message Passing › Transferring Ownership Through Channels\n\n```console\n$ cargo run\n Compiling message-passing v0.1.0 (file:///projects/message-passing)\nerror[E0382]: borrow of moved value: `val`\n --> src/main.rs:10:27\n |\n 8 | let val = String::from(\"hi\");\n | --- move occurs because `val` has type `String`, which does not implement the `Copy` trait\n 9 | tx.send(val).unwrap();\n | --- value moved here\n10 | println!(\"val is {val}\");\n | ^^^ value borrowed here after move\n\nFor more information about this error, try `rustc --explain E0382`.\nerror: could not compile `message-passing` (bin \"message-passing\") due to 1 previous error\n```\nOur concurrency mistake has caused a compile-time error. The `send` function\ntakes ownership of its parameter, and when the value is moved the receiver\ntakes ownership of it. This stops us from accidentally using the value again\nafter sending it; the ownership system checks that everything is okay.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Transfer Data Between Threads with Message Passing", "heading_path": ["Transfer Data Between Threads with Message Passing", "Transferring Ownership Through Channels"], "path": "ch16-02-message-passing.md", "url": "https://doc.rust-lang.org/book/ch16-02-message-passing.html#transferring-ownership-through-channels", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch16-02-message-passing.md#sending-multiple-values-6", "text": "The Rust Programming Language › Transfer Data Between Threads with Message Passing › Sending Multiple Values\n\nThe code in Listing 16-8 compiled and ran, but it didn’t clearly show us that\ntwo separate threads were talking to each other over the channel.\nIn Listing 16-10, we’ve made some modifications that will prove the code in\nListing 16-8 is running concurrently: The spawned thread will now send multiple\nmessages and pause for a second between each message.\nListing 16-10: Sending multiple messages and pausing between each one (src/main.rs)\n```rust,noplayground\nuse std::sync::mpsc;\nuse std::thread;\nuse std::time::Duration;\n\nfn main() {\n let (tx, rx) = mpsc::channel();\n\n thread::spawn(move || {\n let vals = vec![\n String::from(\"hi\"),\n String::from(\"from\"),\n String::from(\"the\"),\n String::from(\"thread\"),\n ];\n\n for val in vals {\n tx.send(val).unwrap();\n thread::sleep(Duration::from_secs(1));\n }\n });\n\n for received in rx {\n println!(\"Got: {received}\");\n }\n}\n```\nThis time, the spawned thread has a vector of strings that we want to send to\nthe main thread. We iterate over them, sending each individually, and pause\nbetween each by calling the `thread::sleep` function with a `Duration` value of\none second.\nIn the main thread, we’re not calling the `recv` function explicitly anymore:\nInstead, we’re treating `rx` as an iterator. For each value received, we’re\nprinting it. When the channel is closed, iteration will end.\nWhen running the code in Listing 16-10, you should see the following output\nwith a one-second pause in between each line:\n```text\nGot: hi\nGot: from\nGot: the\nGot: thread\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Transfer Data Between Threads with Message Passing", "heading_path": ["Transfer Data Between Threads with Message Passing", "Sending Multiple Values"], "path": "ch16-02-message-passing.md", "url": "https://doc.rust-lang.org/book/ch16-02-message-passing.html#sending-multiple-values", "has_code": true, "code_tags": ["rust,noplayground", "text"]}} {"id": "book/ch16-02-message-passing.md#sending-multiple-values-7", "text": "The Rust Programming Language › Transfer Data Between Threads with Message Passing › Sending Multiple Values\n\nBecause we don’t have any code that pauses or delays in the `for` loop in the\nmain thread, we can tell that the main thread is waiting to receive values from\nthe spawned thread.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Transfer Data Between Threads with Message Passing", "heading_path": ["Transfer Data Between Threads with Message Passing", "Sending Multiple Values"], "path": "ch16-02-message-passing.md", "url": "https://doc.rust-lang.org/book/ch16-02-message-passing.html#sending-multiple-values", "has_code": false, "code_tags": []}} {"id": "book/ch16-02-message-passing.md#creating-multiple-producers-8", "text": "The Rust Programming Language › Transfer Data Between Threads with Message Passing › Creating Multiple Producers\n\nEarlier we mentioned that `mpsc` was an acronym for _multiple producer, single\nconsumer_. Let’s put `mpsc` to use and expand the code in Listing 16-10 to\ncreate multiple threads that all send values to the same receiver. We can do so\nby cloning the transmitter, as shown in Listing 16-11.\nListing 16-11: Sending multiple messages from multiple producers (src/main.rs)\n```rust,noplayground\n // --snip--\n\n let (tx, rx) = mpsc::channel();\n\n let tx1 = tx.clone();\n thread::spawn(move || {\n let vals = vec![\n String::from(\"hi\"),\n String::from(\"from\"),\n String::from(\"the\"),\n String::from(\"thread\"),\n ];\n\n for val in vals {\n tx1.send(val).unwrap();\n thread::sleep(Duration::from_secs(1));\n }\n });\n\n thread::spawn(move || {\n let vals = vec![\n String::from(\"more\"),\n String::from(\"messages\"),\n String::from(\"for\"),\n String::from(\"you\"),\n ];\n\n for val in vals {\n tx.send(val).unwrap();\n thread::sleep(Duration::from_secs(1));\n }\n });\n\n for received in rx {\n println!(\"Got: {received}\");\n }\n\n // --snip--\n```\nThis time, before we create the first spawned thread, we call `clone` on the\ntransmitter. This will give us a new transmitter we can pass to the first\nspawned thread. We pass the original transmitter to a second spawned thread.\nThis gives us two threads, each sending different messages to the one receiver.\nWhen you run the code, your output should look something like this:\n```text\nGot: hi\nGot: more\nGot: from\nGot: messages\nGot: for\nGot: the\nGot: thread\nGot: you\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Transfer Data Between Threads with Message Passing", "heading_path": ["Transfer Data Between Threads with Message Passing", "Creating Multiple Producers"], "path": "ch16-02-message-passing.md", "url": "https://doc.rust-lang.org/book/ch16-02-message-passing.html#creating-multiple-producers", "has_code": true, "code_tags": ["rust,noplayground", "text"]}} {"id": "book/ch16-02-message-passing.md#creating-multiple-producers-9", "text": "The Rust Programming Language › Transfer Data Between Threads with Message Passing › Creating Multiple Producers\n\nYou might see the values in another order, depending on your system. This is\nwhat makes concurrency interesting as well as difficult. If you experiment with\n`thread::sleep`, giving it various values in the different threads, each run\nwill be more nondeterministic and create different output each time.\nNow that we’ve looked at how channels work, let’s look at a different method of\nconcurrency.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Transfer Data Between Threads with Message Passing", "heading_path": ["Transfer Data Between Threads with Message Passing", "Creating Multiple Producers"], "path": "ch16-02-message-passing.md", "url": "https://doc.rust-lang.org/book/ch16-02-message-passing.html#creating-multiple-producers", "has_code": false, "code_tags": []}} {"id": "book/ch16-03-shared-state.md#shared-state-concurrency-0", "text": "The Rust Programming Language › Shared-State Concurrency\n\nMessage passing is a fine way to handle concurrency, but it’s not the only way.\nAnother method would be for multiple threads to access the same shared data.\nConsider this part of the slogan from the Go language documentation again: “Do\nnot communicate by sharing memory.”\nWhat would communicating by sharing memory look like? In addition, why would\nmessage-passing enthusiasts caution not to use memory sharing?\nIn a way, channels in any programming language are similar to single ownership\nbecause once you transfer a value down a channel, you should no longer use that\nvalue. Shared-memory concurrency is like multiple ownership: Multiple threads\ncan access the same memory location at the same time. As you saw in Chapter 15,\nwhere smart pointers made multiple ownership possible, multiple ownership can\nadd complexity because these different owners need managing. Rust’s type system\nand ownership rules greatly assist in getting this management correct. For an\nexample, let’s look at mutexes, one of the more common concurrency primitives\nfor shared memory.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Shared-State Concurrency", "heading_path": ["Shared-State Concurrency"], "path": "ch16-03-shared-state.md", "url": "https://doc.rust-lang.org/book/ch16-03-shared-state.html#shared-state-concurrency", "has_code": false, "code_tags": []}} {"id": "book/ch16-03-shared-state.md#the-api-of-mutext-1", "text": "The Rust Programming Language › Shared-State Concurrency › Controlling Access with Mutexes › The API of `Mutex`\n\n_Mutex_ is an abbreviation for _mutual exclusion_, as in a mutex allows only\none thread to access some data at any given time. To access the data in a\nmutex, a thread must first signal that it wants access by asking to acquire the\nmutex’s lock. The _lock_ is a data structure that is part of the mutex that\nkeeps track of who currently has exclusive access to the data. Therefore, the\nmutex is described as _guarding_ the data it holds via the locking system.\nMutexes have a reputation for being difficult to use because you have to\nremember two rules:\n1. You must attempt to acquire the lock before using the data.\n2. When you’re done with the data that the mutex guards, you must unlock the\n data so that other threads can acquire the lock.\nFor a real-world metaphor for a mutex, imagine a panel discussion at a\nconference with only one microphone. Before a panelist can speak, they have to\nask or signal that they want to use the microphone. When they get the\nmicrophone, they can talk for as long as they want to and then hand the\nmicrophone to the next panelist who requests to speak. If a panelist forgets to\nhand the microphone off when they’re finished with it, no one else is able to\nspeak. If management of the shared microphone goes wrong, the panel won’t work\nas planned!\nManagement of mutexes can be incredibly tricky to get right, which is why so\nmany people are enthusiastic about channels. However, thanks to Rust’s type\nsystem and ownership rules, you can’t get locking and unlocking wrong.\nAs an example of how to use a mutex, let’s start by using a mutex in a\nsingle-threaded context, as shown in Listing 16-12.\nListing 16-12 (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Shared-State Concurrency", "heading_path": ["Shared-State Concurrency", "Controlling Access with Mutexes", "The API of `Mutex`"], "path": "ch16-03-shared-state.md", "url": "https://doc.rust-lang.org/book/ch16-03-shared-state.html#the-api-of-mutext", "has_code": false, "code_tags": []}} {"id": "book/ch16-03-shared-state.md#the-api-of-mutext-2", "text": "The Rust Programming Language › Shared-State Concurrency › Controlling Access with Mutexes › The API of `Mutex`\n\n```rust\nuse std::sync::Mutex;\n\nfn main() {\n let m = Mutex::new(5);\n\n {\n let mut num = m.lock().unwrap();\n *num = 6;\n }\n\n println!(\"m = {m:?}\");\n}\n```\nAs with many types, we create a `Mutex` using the associated function `new`.\nTo access the data inside the mutex, we use the `lock` method to acquire the\nlock. This call will block the current thread so that it can’t do any work\nuntil it’s our turn to have the lock.\nThe call to `lock` would fail if another thread holding the lock panicked. In\nthat case, no one would ever be able to get the lock, so we’ve chosen to\n`unwrap` and have this thread panic if we’re in that situation.\nAfter we’ve acquired the lock, we can treat the return value, named `num` in\nthis case, as a mutable reference to the data inside. The type system ensures\nthat we acquire a lock before using the value in `m`. The type of `m` is\n`Mutex`, not `i32`, so we _must_ call `lock` to be able to use the `i32`\nvalue. We can’t forget; the type system won’t let us access the inner `i32`\notherwise.\nThe call to `lock` returns a type called `MutexGuard`, wrapped in a\n`LockResult` that we handled with the call to `unwrap`. The `MutexGuard` type\nimplements `Deref` to point at our inner data; the type also has a `Drop`\nimplementation that releases the lock automatically when a `MutexGuard` goes\nout of scope, which happens at the end of the inner scope. As a result, we\ndon’t risk forgetting to release the lock and blocking the mutex from being\nused by other threads because the lock release happens automatically.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Shared-State Concurrency", "heading_path": ["Shared-State Concurrency", "Controlling Access with Mutexes", "The API of `Mutex`"], "path": "ch16-03-shared-state.md", "url": "https://doc.rust-lang.org/book/ch16-03-shared-state.html#the-api-of-mutext", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch16-03-shared-state.md#shared-access-to-mutext-3", "text": "The Rust Programming Language › Shared-State Concurrency › Controlling Access with Mutexes › Shared Access to `Mutex`\n\nAfter dropping the lock, we can print the mutex value and see that we were able\nto change the inner `i32` to `6`.\nNow let’s try to share a value between multiple threads using `Mutex`. We’ll\nspin up 10 threads and have them each increment a counter value by 1, so the\ncounter goes from 0 to 10. The example in Listing 16-13 will have a compiler\nerror, and we’ll use that error to learn more about using `Mutex` and how\nRust helps us use it correctly.\nListing 16-13 (src/main.rs)\n```rust,ignore,does_not_compile\nuse std::sync::Mutex;\nuse std::thread;\n\nfn main() {\n let counter = Mutex::new(0);\n let mut handles = vec![];\n\n for _ in 0..10 {\n let handle = thread::spawn(move || {\n let mut num = counter.lock().unwrap();\n\n *num += 1;\n });\n handles.push(handle);\n }\n\n for handle in handles {\n handle.join().unwrap();\n }\n\n println!(\"Result: {}\", *counter.lock().unwrap());\n}\n```\nWe create a `counter` variable to hold an `i32` inside a `Mutex`, as we did\nin Listing 16-12. Next, we create 10 threads by iterating over a range of\nnumbers. We use `thread::spawn` and give all the threads the same closure: one\nthat moves the counter into the thread, acquires a lock on the `Mutex` by\ncalling the `lock` method, and then adds 1 to the value in the mutex. When a\nthread finishes running its closure, `num` will go out of scope and release the\nlock so that another thread can acquire it.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Shared-State Concurrency", "heading_path": ["Shared-State Concurrency", "Controlling Access with Mutexes", "Shared Access to `Mutex`"], "path": "ch16-03-shared-state.md", "url": "https://doc.rust-lang.org/book/ch16-03-shared-state.html#shared-access-to-mutext", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch16-03-shared-state.md#multiple-ownership-with-multiple-threads-4", "text": "The Rust Programming Language › Shared-State Concurrency › Controlling Access with Mutexes › Multiple Ownership with Multiple Threads\n\nIn the main thread, we collect all the join handles. Then, as we did in Listing\n16-2, we call `join` on each handle to make sure all the threads finish. At\nthat point, the main thread will acquire the lock and print the result of this\nprogram.\nWe hinted that this example wouldn’t compile. Now let’s find out why!\n```console\n$ cargo run\n Compiling shared-state v0.1.0 (file:///projects/shared-state)\nerror[E0382]: borrow of moved value: `counter`\n --> src/main.rs:21:29\n |\n 5 | let counter = Mutex::new(0);\n | ------- move occurs because `counter` has type `std::sync::Mutex`, which does not implement the `Copy` trait\n...\n 8 | for _ in 0..10 {\n | -------------- inside of this loop\n 9 | let handle = thread::spawn(move || {\n | ------- value moved into closure here, in previous iteration of loop\n...\n21 | println!(\"Result: {}\", *counter.lock().unwrap());\n | ^^^^^^^ value borrowed here after move\n\nFor more information about this error, try `rustc --explain E0382`.\nerror: could not compile `shared-state` (bin \"shared-state\") due to 1 previous error\n```\nThe error message states that the `counter` value was moved in the previous\niteration of the loop. Rust is telling us that we can’t move the ownership of\nlock `counter` into multiple threads. Let’s fix the compiler error with the\nmultiple-ownership method we discussed in Chapter 15.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Shared-State Concurrency", "heading_path": ["Shared-State Concurrency", "Controlling Access with Mutexes", "Multiple Ownership with Multiple Threads"], "path": "ch16-03-shared-state.md", "url": "https://doc.rust-lang.org/book/ch16-03-shared-state.html#multiple-ownership-with-multiple-threads", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch16-03-shared-state.md#multiple-ownership-with-multiple-threads-5", "text": "The Rust Programming Language › Shared-State Concurrency › Controlling Access with Mutexes › Multiple Ownership with Multiple Threads\n\nIn Chapter 15, we gave a value to multiple owners by using the smart pointer\n`Rc` to create a reference-counted value. Let’s do the same here and see\nwhat happens. We’ll wrap the `Mutex` in `Rc` in Listing 16-14 and clone\nthe `Rc` before moving ownership to the thread.\nListing 16-14 (src/main.rs)\n```rust,ignore,does_not_compile\nuse std::rc::Rc;\nuse std::sync::Mutex;\nuse std::thread;\n\nfn main() {\n let counter = Rc::new(Mutex::new(0));\n let mut handles = vec![];\n\n for _ in 0..10 {\n let counter = Rc::clone(&counter);\n let handle = thread::spawn(move || {\n let mut num = counter.lock().unwrap();\n\n *num += 1;\n });\n handles.push(handle);\n }\n\n for handle in handles {\n handle.join().unwrap();\n }\n\n println!(\"Result: {}\", *counter.lock().unwrap());\n}\n```\nOnce again, we compile and get... different errors! The compiler is teaching us\na lot:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Shared-State Concurrency", "heading_path": ["Shared-State Concurrency", "Controlling Access with Mutexes", "Multiple Ownership with Multiple Threads"], "path": "ch16-03-shared-state.md", "url": "https://doc.rust-lang.org/book/ch16-03-shared-state.html#multiple-ownership-with-multiple-threads", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch16-03-shared-state.md#multiple-ownership-with-multiple-threads-6", "text": "The Rust Programming Language › Shared-State Concurrency › Controlling Access with Mutexes › Multiple Ownership with Multiple Threads\n\n```console\n$ cargo run\n Compiling shared-state v0.1.0 (file:///projects/shared-state)\nerror[E0277]: `Rc>` cannot be sent between threads safely\n --> src/main.rs:11:36\n |\n11 | let handle = thread::spawn(move || {\n | ------------- ^------\n | | |\n | ______________________|_____________within this `{closure@src/main.rs:11:36: 11:43}`\n | | |\n | | required by a bound introduced by this call\n12 | | let mut num = counter.lock().unwrap();\n13 | |\n14 | | *num += 1;\n15 | | });\n | |_________^ `Rc>` cannot be sent between threads safely\n |\n = help: within `{closure@src/main.rs:11:36: 11:43}`, the trait `Send` is not implemented for `Rc>`\nnote: required because it's used within this closure\n --> src/main.rs:11:36\n |\n11 | let handle = thread::spawn(move || {\n | ^^^^^^^\nnote: required by a bound in `spawn`\n --> /rustc/2d8144b7880597b6e6d3dfd63a9a9efae3f533d3/library/std/src/thread/functions.rs:125:0\n\nFor more information about this error, try `rustc --explain E0277`.\nerror: could not compile `shared-state` (bin \"shared-state\") due to 1 previous error\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Shared-State Concurrency", "heading_path": ["Shared-State Concurrency", "Controlling Access with Mutexes", "Multiple Ownership with Multiple Threads"], "path": "ch16-03-shared-state.md", "url": "https://doc.rust-lang.org/book/ch16-03-shared-state.html#multiple-ownership-with-multiple-threads", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch16-03-shared-state.md#atomic-reference-counting-with-arct-7", "text": "The Rust Programming Language › Shared-State Concurrency › Controlling Access with Mutexes › Atomic Reference Counting with `Arc`\n\nWow, that error message is very wordy! Here’s the important part to focus on:\n`` `Rc>` cannot be sent between threads safely ``. The compiler is\nalso telling us the reason why: `` the trait `Send` is not implemented for\n`Rc>` ``. We’ll talk about `Send` in the next section: It’s one of\nthe traits that ensures that the types we use with threads are meant for use in\nconcurrent situations.\nUnfortunately, `Rc` is not safe to share across threads. When `Rc`\nmanages the reference count, it adds to the count for each call to `clone` and\nsubtracts from the count when each clone is dropped. But it doesn’t use any\nconcurrency primitives to make sure that changes to the count can’t be\ninterrupted by another thread. This could lead to wrong counts—subtle bugs that\ncould in turn lead to memory leaks or a value being dropped before we’re done\nwith it. What we need is a type that is exactly like `Rc`, but that makes\nchanges to the reference count in a thread-safe way.\nFortunately, `Arc` _is_ a type like `Rc` that is safe to use in\nconcurrent situations. The _a_ stands for _atomic_, meaning it’s an _atomically\nreference-counted_ type. Atomics are an additional kind of concurrency\nprimitive that we won’t cover in detail here: See the standard library\ndocumentation for `std::sync::atomic` for more\ndetails. At this point, you just need to know that atomics work like primitive\ntypes but are safe to share across threads.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Shared-State Concurrency", "heading_path": ["Shared-State Concurrency", "Controlling Access with Mutexes", "Atomic Reference Counting with `Arc`"], "path": "ch16-03-shared-state.md", "url": "https://doc.rust-lang.org/book/ch16-03-shared-state.html#atomic-reference-counting-with-arct", "has_code": false, "code_tags": []}} {"id": "book/ch16-03-shared-state.md#atomic-reference-counting-with-arct-8", "text": "The Rust Programming Language › Shared-State Concurrency › Controlling Access with Mutexes › Atomic Reference Counting with `Arc`\n\nYou might then wonder why all primitive types aren’t atomic and why standard\nlibrary types aren’t implemented to use `Arc` by default. The reason is that\nthread safety comes with a performance penalty that you only want to pay when\nyou really need to. If you’re just performing operations on values within a\nsingle thread, your code can run faster if it doesn’t have to enforce the\nguarantees atomics provide.\nLet’s return to our example: `Arc` and `Rc` have the same API, so we fix\nour program by changing the `use` line, the call to `new`, and the call to\n`clone`. The code in Listing 16-15 will finally compile and run.\nListing 16-15 (src/main.rs)\n```rust\nuse std::sync::{Arc, Mutex};\nuse std::thread;\n\nfn main() {\n let counter = Arc::new(Mutex::new(0));\n let mut handles = vec![];\n\n for _ in 0..10 {\n let counter = Arc::clone(&counter);\n let handle = thread::spawn(move || {\n let mut num = counter.lock().unwrap();\n\n *num += 1;\n });\n handles.push(handle);\n }\n\n for handle in handles {\n handle.join().unwrap();\n }\n\n println!(\"Result: {}\", *counter.lock().unwrap());\n}\n```\nThis code will print the following:\n```text\nResult: 10\n```\nWe did it! We counted from 0 to 10, which may not seem very impressive, but it\ndid teach us a lot about `Mutex` and thread safety. You could also use this\nprogram’s structure to do more complicated operations than just incrementing a\ncounter. Using this strategy, you can divide a calculation into independent\nparts, split those parts across threads, and then use a `Mutex` to have each\nthread update the final result with its part.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Shared-State Concurrency", "heading_path": ["Shared-State Concurrency", "Controlling Access with Mutexes", "Atomic Reference Counting with `Arc`"], "path": "ch16-03-shared-state.md", "url": "https://doc.rust-lang.org/book/ch16-03-shared-state.html#atomic-reference-counting-with-arct", "has_code": true, "code_tags": ["rust", "text"]}} {"id": "book/ch16-03-shared-state.md#atomic-reference-counting-with-arct-9", "text": "The Rust Programming Language › Shared-State Concurrency › Controlling Access with Mutexes › Atomic Reference Counting with `Arc`\n\nNote that if you are doing simple numerical operations, there are types simpler\nthan `Mutex` types provided by the `std::sync::atomic` module of the\nstandard library. These types provide safe, concurrent,\natomic access to primitive types. We chose to use `Mutex` with a primitive\ntype for this example so that we could concentrate on how `Mutex` works.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Shared-State Concurrency", "heading_path": ["Shared-State Concurrency", "Controlling Access with Mutexes", "Atomic Reference Counting with `Arc`"], "path": "ch16-03-shared-state.md", "url": "https://doc.rust-lang.org/book/ch16-03-shared-state.html#atomic-reference-counting-with-arct", "has_code": false, "code_tags": []}} {"id": "book/ch16-03-shared-state.md#comparing-refcelltrct-and-mutextarct-10", "text": "The Rust Programming Language › Shared-State Concurrency › Comparing `RefCell`/`Rc` and `Mutex`/`Arc`\n\nYou might have noticed that `counter` is immutable but that we could get a\nmutable reference to the value inside it; this means `Mutex` provides\ninterior mutability, as the `Cell` family does. In the same way we used\n`RefCell` in Chapter 15 to allow us to mutate contents inside an `Rc`, we\nuse `Mutex` to mutate contents inside an `Arc`.\nAnother detail to note is that Rust can’t protect you from all kinds of logic\nerrors when you use `Mutex`. Recall from Chapter 15 that using `Rc` came\nwith the risk of creating reference cycles, where two `Rc` values refer to\neach other, causing memory leaks. Similarly, `Mutex` comes with the risk of\ncreating _deadlocks_. These occur when an operation needs to lock two resources\nand two threads have each acquired one of the locks, causing them to wait for\neach other forever. If you’re interested in deadlocks, try creating a Rust\nprogram that has a deadlock; then, research deadlock mitigation strategies for\nmutexes in any language and have a go at implementing them in Rust. The\nstandard library API documentation for `Mutex` and `MutexGuard` offers\nuseful information.\nWe’ll round out this chapter by talking about the `Send` and `Sync` traits and\nhow we can use them with custom types.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Shared-State Concurrency", "heading_path": ["Shared-State Concurrency", "Comparing `RefCell`/`Rc` and `Mutex`/`Arc`"], "path": "ch16-03-shared-state.md", "url": "https://doc.rust-lang.org/book/ch16-03-shared-state.html#comparing-refcelltrct-and-mutextarct", "has_code": false, "code_tags": []}} {"id": "book/ch16-04-extensible-concurrency-sync-and-send.md#extensible-concurrency-with-send-and-sync-0", "text": "The Rust Programming Language › Extensible Concurrency with `Send` and `Sync`\n\nInterestingly, almost every concurrency feature we’ve talked about so far in\nthis chapter has been part of the standard library, not the language. Your\noptions for handling concurrency are not limited to the language or the\nstandard library; you can write your own concurrency features or use those\nwritten by others.\nHowever, among the key concurrency concepts that are embedded in the language\nrather than the standard library are the `std::marker` traits `Send` and `Sync`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Extensible Concurrency with `Send` and `Sync`", "heading_path": ["Extensible Concurrency with `Send` and `Sync`"], "path": "ch16-04-extensible-concurrency-sync-and-send.md", "url": "https://doc.rust-lang.org/book/ch16-04-extensible-concurrency-sync-and-send.html#extensible-concurrency-with-send-and-sync", "has_code": false, "code_tags": []}} {"id": "book/ch16-04-extensible-concurrency-sync-and-send.md#transferring-ownership-between-threads-1", "text": "The Rust Programming Language › Extensible Concurrency with `Send` and `Sync` › Transferring Ownership Between Threads\n\nThe `Send` marker trait indicates that ownership of values of the type\nimplementing `Send` can be transferred between threads. Almost every Rust type\nimplements `Send`, but there are some exceptions, including `Rc`: This\ncannot implement `Send` because if you cloned an `Rc` value and tried to\ntransfer ownership of the clone to another thread, both threads might update\nthe reference count at the same time. For this reason, `Rc` is implemented\nfor use in single-threaded situations where you don’t want to pay the\nthread-safe performance penalty.\nTherefore, Rust’s type system and trait bounds ensure that you can never\naccidentally send an `Rc` value across threads unsafely. When we tried to do\nthis in Listing 16-14, we got the error `` the trait `Send` is not implemented\nfor `Rc>` ``. When we switched to `Arc`, which does implement\n`Send`, the code compiled.\nAny type composed entirely of `Send` types is automatically marked as `Send` as\nwell. Almost all primitive types are `Send`, aside from raw pointers, which\nwe’ll discuss in Chapter 20.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Extensible Concurrency with `Send` and `Sync`", "heading_path": ["Extensible Concurrency with `Send` and `Sync`", "Transferring Ownership Between Threads"], "path": "ch16-04-extensible-concurrency-sync-and-send.md", "url": "https://doc.rust-lang.org/book/ch16-04-extensible-concurrency-sync-and-send.html#transferring-ownership-between-threads", "has_code": false, "code_tags": []}} {"id": "book/ch16-04-extensible-concurrency-sync-and-send.md#accessing-from-multiple-threads-2", "text": "The Rust Programming Language › Extensible Concurrency with `Send` and `Sync` › Accessing from Multiple Threads\n\nThe `Sync` marker trait indicates that it is safe for the type implementing\n`Sync` to be referenced from multiple threads. In other words, any type `T`\nimplements `Sync` if `&T` (an immutable reference to `T`) implements `Send`,\nmeaning the reference can be sent safely to another thread. Similar to `Send`,\nprimitive types all implement `Sync`, and types composed entirely of types that\nimplement `Sync` also implement `Sync`.\nThe smart pointer `Rc` also doesn’t implement `Sync` for the same reasons\nthat it doesn’t implement `Send`. The `RefCell` type (which we talked about\nin Chapter 15) and the family of related `Cell` types don’t implement\n`Sync`. The implementation of borrow checking that `RefCell` does at runtime\nis not thread-safe. The smart pointer `Mutex` implements `Sync` and can be\nused to share access with multiple threads, as you saw in “Shared Access to\n`Mutex`”.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Extensible Concurrency with `Send` and `Sync`", "heading_path": ["Extensible Concurrency with `Send` and `Sync`", "Accessing from Multiple Threads"], "path": "ch16-04-extensible-concurrency-sync-and-send.md", "url": "https://doc.rust-lang.org/book/ch16-04-extensible-concurrency-sync-and-send.html#accessing-from-multiple-threads", "has_code": false, "code_tags": []}} {"id": "book/ch16-04-extensible-concurrency-sync-and-send.md#implementing-send-and-sync-manually-is-unsafe-3", "text": "The Rust Programming Language › Extensible Concurrency with `Send` and `Sync` › Implementing `Send` and `Sync` Manually Is Unsafe\n\nBecause types composed entirely of other types that implement the `Send` and\n`Sync` traits also automatically implement `Send` and `Sync`, we don’t have to\nimplement those traits manually. As marker traits, they don’t even have any\nmethods to implement. They’re just useful for enforcing invariants related to\nconcurrency.\nManually implementing these traits involves implementing unsafe Rust code.\nWe’ll talk about using unsafe Rust code in Chapter 20; for now, the important\ninformation is that building new concurrent types not made up of `Send` and\n`Sync` parts requires careful thought to uphold the safety guarantees. “The\nRustonomicon” has more information about these guarantees and how to\nuphold them.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Extensible Concurrency with `Send` and `Sync`", "heading_path": ["Extensible Concurrency with `Send` and `Sync`", "Implementing `Send` and `Sync` Manually Is Unsafe"], "path": "ch16-04-extensible-concurrency-sync-and-send.md", "url": "https://doc.rust-lang.org/book/ch16-04-extensible-concurrency-sync-and-send.html#implementing-send-and-sync-manually-is-unsafe", "has_code": false, "code_tags": []}} {"id": "book/ch16-04-extensible-concurrency-sync-and-send.md#summary-4", "text": "The Rust Programming Language › Summary\n\nThis isn’t the last you’ll see of concurrency in this book: The next chapter\nfocuses on async programming, and the project in Chapter 21 will use the\nconcepts in this chapter in a more realistic situation than the smaller\nexamples discussed here.\nAs mentioned earlier, because very little of how Rust handles concurrency is\npart of the language, many concurrency solutions are implemented as crates.\nThese evolve more quickly than the standard library, so be sure to search\nonline for the current, state-of-the-art crates to use in multithreaded\nsituations.\nThe Rust standard library provides channels for message passing and smart\npointer types, such as `Mutex` and `Arc`, that are safe to use in\nconcurrent contexts. The type system and the borrow checker ensure that the\ncode using these solutions won’t end up with data races or invalid references.\nOnce you get your code to compile, you can rest assured that it will happily\nrun on multiple threads without the kinds of hard-to-track-down bugs common in\nother languages. Concurrent programming is no longer a concept to be afraid of:\nGo forth and make your programs concurrent, fearlessly!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Extensible Concurrency with `Send` and `Sync`", "heading_path": ["Summary"], "path": "ch16-04-extensible-concurrency-sync-and-send.md", "url": "https://doc.rust-lang.org/book/ch16-04-extensible-concurrency-sync-and-send.html#summary", "has_code": false, "code_tags": []}} {"id": "book/ch17-00-async-await.md#fundamentals-of-asynchronous-programming-async-await-futures-and-streams-0", "text": "The Rust Programming Language › Fundamentals of Asynchronous Programming: Async, Await, Futures, and Streams\n\nMany operations we ask the computer to do can take a while to finish. It would\nbe nice if we could do something else while we’re waiting for those\nlong-running processes to complete. Modern computers offer two techniques for\nworking on more than one operation at a time: parallelism and concurrency. Our\nprograms’ logic, however, is written in a mostly linear fashion. We’d like to\nbe able to specify the operations a program should perform and points at which\na function could pause and some other part of the program could run instead,\nwithout needing to specify up front exactly the order and manner in which each\nbit of code should run. _Asynchronous programming_ is an abstraction that lets\nus express our code in terms of potential pausing points and eventual results\nthat takes care of the details of coordination for us.\nThis chapter builds on Chapter 16’s use of threads for parallelism and\nconcurrency by introducing an alternative approach to writing code: Rust’s\nfutures, streams, and the `async` and `await` syntax that let us express how\noperations could be asynchronous, and the third-party crates that implement\nasynchronous runtimes: code that manages and coordinates the execution of\nasynchronous operations.\nLet’s consider an example. Say you’re exporting a video you’ve created of a\nfamily celebration, an operation that could take anywhere from minutes to\nhours. The video export will use as much CPU and GPU power as it can. If you\nhad only one CPU core and your operating system didn’t pause that export until\nit completed—that is, if it executed the export _synchronously_—you couldn’t do\nanything else on your computer while that task was running. That would be a\npretty frustrating experience. Fortunately, your computer’s operating system\ncan, and does, invisibly interrupt the export often enough to let you get other\nwork done simultaneously.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Fundamentals of Asynchronous Programming: Async, Await, Futures, and Streams", "heading_path": ["Fundamentals of Asynchronous Programming: Async, Await, Futures, and Streams"], "path": "ch17-00-async-await.md", "url": "https://doc.rust-lang.org/book/ch17-00-async-await.html#fundamentals-of-asynchronous-programming-async-await-futures-and-streams", "has_code": false, "code_tags": []}} {"id": "book/ch17-00-async-await.md#fundamentals-of-asynchronous-programming-async-await-futures-and-streams-1", "text": "The Rust Programming Language › Fundamentals of Asynchronous Programming: Async, Await, Futures, and Streams\n\nNow say you’re downloading a video shared by someone else, which can also take\na while but does not take up as much CPU time. In this case, the CPU has to\nwait for data to arrive from the network. While you can start reading the data\nonce it starts to arrive, it might take some time for all of it to show up.\nEven once the data is all present, if the video is quite large, it could take\nat least a second or two to load it all. That might not sound like much, but\nit’s a very long time for a modern processor, which can perform billions of\noperations every second. Again, your operating system will invisibly interrupt\nyour program to allow the CPU to perform other work while waiting for the\nnetwork call to finish.\nThe video export is an example of a _CPU-bound_ or _compute-bound_ operation.\nIt’s limited by the computer’s potential data processing speed within the CPU\nor GPU, and how much of that speed it can dedicate to the operation. The video\ndownload is an example of an _I/O-bound_ operation, because it’s limited by the\nspeed of the computer’s _input and output_; it can only go as fast as the data\ncan be sent across the network.\nIn both of these examples, the operating system’s invisible interrupts provide\na form of concurrency. That concurrency happens only at the level of the entire\nprogram, though: the operating system interrupts one program to let other\nprograms get work done. In many cases, because we understand our programs at a\nmuch more granular level than the operating system does, we can spot\nopportunities for concurrency that the operating system can’t see.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Fundamentals of Asynchronous Programming: Async, Await, Futures, and Streams", "heading_path": ["Fundamentals of Asynchronous Programming: Async, Await, Futures, and Streams"], "path": "ch17-00-async-await.md", "url": "https://doc.rust-lang.org/book/ch17-00-async-await.html#fundamentals-of-asynchronous-programming-async-await-futures-and-streams", "has_code": false, "code_tags": []}} {"id": "book/ch17-00-async-await.md#fundamentals-of-asynchronous-programming-async-await-futures-and-streams-2", "text": "The Rust Programming Language › Fundamentals of Asynchronous Programming: Async, Await, Futures, and Streams\n\nFor example, if we’re building a tool to manage file downloads, we should be\nable to write our program so that starting one download won’t lock up the UI,\nand users should be able to start multiple downloads at the same time. Many\noperating system APIs for interacting with the network are _blocking_, though;\nthat is, they block the program’s progress until the data they’re processing is\ncompletely ready.\nNote: This is how _most_ function calls work, if you think about it. However,\nthe term _blocking_ is usually reserved for function calls that interact with\nfiles, the network, or other resources on the computer, because those are the\ncases where an individual program would benefit from the operation being\n_non_-blocking.\nWe could avoid blocking our main thread by spawning a dedicated thread to\ndownload each file. However, the overhead of the system resources used by those\nthreads would eventually become a problem. It would be preferable if the call\ndidn’t block in the first place, and instead we could define a number of tasks\nthat we’d like our program to complete and allow the runtime to choose the best\norder and manner in which to run them.\nThat is exactly what Rust’s _async_ (short for _asynchronous_) abstraction\ngives us. In this chapter, you’ll learn all about async as we cover the\nfollowing topics:\n- How to use Rust’s `async` and `await` syntax and execute asynchronous\n functions with a runtime\n- How to use the async model to solve some of the same challenges we looked at\n in Chapter 16\n- How multithreading and async provide complementary solutions that you can\n combine in many cases\nBefore we see how async works in practice, though, we need to take a short\ndetour to discuss the differences between parallelism and concurrency.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Fundamentals of Asynchronous Programming: Async, Await, Futures, and Streams", "heading_path": ["Fundamentals of Asynchronous Programming: Async, Await, Futures, and Streams"], "path": "ch17-00-async-await.md", "url": "https://doc.rust-lang.org/book/ch17-00-async-await.html#fundamentals-of-asynchronous-programming-async-await-futures-and-streams", "has_code": false, "code_tags": []}} {"id": "book/ch17-00-async-await.md#parallelism-and-concurrency-3", "text": "The Rust Programming Language › Fundamentals of Asynchronous Programming: Async, Await, Futures, and Streams › Parallelism and Concurrency\n\nWe’ve treated parallelism and concurrency as mostly interchangeable so far. Now\nwe need to distinguish between them more precisely, because the differences\nwill show up as we start working.\nConsider the different ways a team could split up work on a software project.\nYou could assign a single member multiple tasks, assign each member one task,\nor use a mix of the two approaches.\nWhen an individual works on several different tasks before any of them is\ncomplete, this is _concurrency_. One way to implement concurrency is similar to\nhaving two different projects checked out on your computer, and when you get\nbored or stuck on one project, you switch to the other. You’re just one person,\nso you can’t make progress on both tasks at the exact same time, but you can\nmultitask, making progress on one at a time by switching between them (see\nFigure 17-1).\n
\n\"A\n
Figure 17-1: A concurrent workflow, switching between Task A and Task B
\n
\nWhen the team splits up a group of tasks by having each member take one task\nand work on it alone, this is _parallelism_. Each person on the team can make\nprogress at the exact same time (see Figure 17-2).\n
", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Fundamentals of Asynchronous Programming: Async, Await, Futures, and Streams", "heading_path": ["Fundamentals of Asynchronous Programming: Async, Await, Futures, and Streams", "Parallelism and Concurrency"], "path": "ch17-00-async-await.md", "url": "https://doc.rust-lang.org/book/ch17-00-async-await.html#parallelism-and-concurrency", "has_code": false, "code_tags": []}} {"id": "book/ch17-00-async-await.md#parallelism-and-concurrency-4", "text": "The Rust Programming Language › Fundamentals of Asynchronous Programming: Async, Await, Futures, and Streams › Parallelism and Concurrency\n\n\"A\n
Figure 17-2: A parallel workflow, where work happens on Task A and Task B independently
\n
\nIn both of these workflows, you might have to coordinate between different\ntasks. Maybe you thought the task assigned to one person was totally\nindependent from everyone else’s work, but it actually requires another person\non the team to finish their task first. Some of the work could be done in\nparallel, but some of it was actually _serial_: it could only happen in a\nseries, one task after the other, as in Figure 17-3.\n
\n\"A\n
Figure 17-3: A partially parallel workflow, where work happens on Task A and Task B independently until Task A3 is blocked on the results of Task B3.
\n
\nLikewise, you might realize that one of your own tasks depends on another of\nyour tasks. Now your concurrent work has also become serial.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Fundamentals of Asynchronous Programming: Async, Await, Futures, and Streams", "heading_path": ["Fundamentals of Asynchronous Programming: Async, Await, Futures, and Streams", "Parallelism and Concurrency"], "path": "ch17-00-async-await.md", "url": "https://doc.rust-lang.org/book/ch17-00-async-await.html#parallelism-and-concurrency", "has_code": false, "code_tags": []}} {"id": "book/ch17-00-async-await.md#parallelism-and-concurrency-5", "text": "The Rust Programming Language › Fundamentals of Asynchronous Programming: Async, Await, Futures, and Streams › Parallelism and Concurrency\n\nParallelism and concurrency can intersect with each other, too. If you learn\nthat a colleague is stuck until you finish one of your tasks, you’ll probably\nfocus all your efforts on that task to “unblock” your colleague. You and your\ncoworker are no longer able to work in parallel, and you’re also no longer able\nto work concurrently on your own tasks.\nThe same basic dynamics come into play with software and hardware. On a machine\nwith a single CPU core, the CPU can perform only one operation at a time, but\nit can still work concurrently. Using tools such as threads, processes, and\nasync, the computer can pause one activity and switch to others before\neventually cycling back to that first activity again. On a machine with\nmultiple CPU cores, it can also do work in parallel. One core can be performing\none task while another core performs a completely unrelated one, and those\noperations actually happen at the same time.\nRunning async code in Rust usually happens concurrently. Depending on the\nhardware, the operating system, and the async runtime we are using (more on\nasync runtimes shortly), that concurrency may also use parallelism under the\nhood.\nNow, let’s dive into how async programming in Rust actually works.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Fundamentals of Asynchronous Programming: Async, Await, Futures, and Streams", "heading_path": ["Fundamentals of Asynchronous Programming: Async, Await, Futures, and Streams", "Parallelism and Concurrency"], "path": "ch17-00-async-await.md", "url": "https://doc.rust-lang.org/book/ch17-00-async-await.html#parallelism-and-concurrency", "has_code": false, "code_tags": []}} {"id": "book/ch17-01-futures-and-syntax.md#futures-and-the-async-syntax-0", "text": "The Rust Programming Language › Futures and the Async Syntax\n\nThe key elements of asynchronous programming in Rust are _futures_ and Rust’s\n`async` and `await` keywords.\nA _future_ is a value that may not be ready now but will become ready at some\npoint in the future. (This same concept shows up in many languages, sometimes\nunder other names such as _task_ or _promise_.) Rust provides a `Future` trait\nas a building block so that different async operations can be implemented with\ndifferent data structures but with a common interface. In Rust, futures are\ntypes that implement the `Future` trait. Each future holds its own information\nabout the progress that has been made and what “ready” means.\nYou can apply the `async` keyword to blocks and functions to specify that they\ncan be interrupted and resumed. Within an async block or async function, you\ncan use the `await` keyword to _await a future_ (that is, wait for it to become\nready). Any point where you await a future within an async block or function is\na potential spot for that block or function to pause and resume. The process of\nchecking with a future to see if its value is available yet is called _polling_.\nSome other languages, such as C# and JavaScript, also use `async` and `await`\nkeywords for async programming. If you’re familiar with those languages, you\nmay notice some significant differences in how Rust handles the syntax. That’s\nfor good reason, as we’ll see!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Futures and the Async Syntax", "heading_path": ["Futures and the Async Syntax"], "path": "ch17-01-futures-and-syntax.md", "url": "https://doc.rust-lang.org/book/ch17-01-futures-and-syntax.html#futures-and-the-async-syntax", "has_code": false, "code_tags": []}} {"id": "book/ch17-01-futures-and-syntax.md#futures-and-the-async-syntax-1", "text": "The Rust Programming Language › Futures and the Async Syntax\n\nWhen writing async Rust, we use the `async` and `await` keywords most of the\ntime. Rust compiles them into equivalent code using the `Future` trait, much as\nit compiles `for` loops into equivalent code using the `Iterator` trait.\nBecause Rust provides the `Future` trait, though, you can also implement it for\nyour own data types when you need to. Many of the functions we’ll see\nthroughout this chapter return types with their own implementations of\n`Future`. We’ll return to the definition of the trait at the end of the chapter\nand dig into more of how it works, but this is enough detail to keep us moving\nforward.\nThis may all feel a bit abstract, so let’s write our first async program: a\nlittle web scraper. We’ll pass in two URLs from the command line, fetch both of\nthem concurrently, and return the result of whichever one finishes first. This\nexample will have a fair bit of new syntax, but don’t worry—we’ll explain\neverything you need to know as we go.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Futures and the Async Syntax", "heading_path": ["Futures and the Async Syntax"], "path": "ch17-01-futures-and-syntax.md", "url": "https://doc.rust-lang.org/book/ch17-01-futures-and-syntax.html#futures-and-the-async-syntax", "has_code": false, "code_tags": []}} {"id": "book/ch17-01-futures-and-syntax.md#our-first-async-program-2", "text": "The Rust Programming Language › Our First Async Program\n\nTo keep the focus of this chapter on learning async rather than juggling parts\nof the ecosystem, we’ve created the `trpl` crate (`trpl` is short for “The Rust\nProgramming Language”). It re-exports all the types, traits, and functions\nyou’ll need, primarily from the `futures` and\n`tokio` crates. The `futures` crate is an official home\nfor Rust experimentation for async code, and it’s actually where the `Future`\ntrait was originally designed. Tokio is the most widely used async runtime in\nRust today, especially for web applications. There are other great runtimes out\nthere, and they may be more suitable for your purposes. We use the `tokio`\ncrate under the hood for `trpl` because it’s well tested and widely used.\nIn some cases, `trpl` also renames or wraps the original APIs to keep you\nfocused on the details relevant to this chapter. If you want to understand what\nthe crate does, we encourage you to check out its source code.\nYou’ll be able to see what crate each re-export comes from, and we’ve left\nextensive comments explaining what the crate does.\nCreate a new binary project named `hello-async` and add the `trpl` crate as a\ndependency:\n```console\n$ cargo new hello-async\n$ cd hello-async\n$ cargo add trpl\n```\nNow we can use the various pieces provided by `trpl` to write our first async\nprogram. We’ll build a little command line tool that fetches two web pages,\npulls the `` element from each, and prints out the title of whichever\npage finishes that whole process first.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Futures and the Async Syntax", "heading_path": ["Our First Async Program"], "path": "ch17-01-futures-and-syntax.md", "url": "https://doc.rust-lang.org/book/ch17-01-futures-and-syntax.html#our-first-async-program", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch17-01-futures-and-syntax.md#defining-the-page_title-function-3", "text": "The Rust Programming Language › Our First Async Program › Defining the page_title Function\n\nLet’s start by writing a function that takes one page URL as a parameter, makes\na request to it, and returns the text of the `<title>` element (see Listing\n17-1).\nListing 17-1: Defining an async function to get the title element from an HTML page (src/main.rs)\n```rust\nuse trpl::Html;\n\nasync fn page_title(url: &str) -> Option<String> {\n let response = trpl::get(url).await;\n let response_text = response.text().await;\n Html::parse(&response_text)\n .select_first(\"title\")\n .map(|title| title.inner_html())\n}\n```\nFirst, we define a function named `page_title` and mark it with the `async`\nkeyword. Then we use the `trpl::get` function to fetch whatever URL is passed\nin and add the `await` keyword to await the response. To get the text of the\n`response`, we call its `text` method and once again await it with the `await`\nkeyword. Both of these steps are asynchronous. For the `get` function, we have\nto wait for the server to send back the first part of its response, which will\ninclude HTTP headers, cookies, and so on and can be delivered separately from\nthe response body. Especially if the body is very large, it can take some time\nfor it all to arrive. Because we have to wait for the _entirety_ of the\nresponse to arrive, the `text` method is also async.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Futures and the Async Syntax", "heading_path": ["Our First Async Program", "Defining the page_title Function"], "path": "ch17-01-futures-and-syntax.md", "url": "https://doc.rust-lang.org/book/ch17-01-futures-and-syntax.html#defining-the-page_title-function", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch17-01-futures-and-syntax.md#defining-the-page_title-function-4", "text": "The Rust Programming Language › Our First Async Program › Defining the page_title Function\n\nWe have to explicitly await both of these futures, because futures in Rust are\n_lazy_: they don’t do anything until you ask them to with the `await` keyword.\n(In fact, Rust will show a compiler warning if you don’t use a future.) This\nmight remind you of the discussion of iterators in the “Processing a Series of\nItems with Iterators” section in Chapter 13.\nIterators do nothing unless you call their `next` method—whether directly or by\nusing `for` loops or methods such as `map` that use `next` under the hood.\nLikewise, futures do nothing unless you explicitly ask them to. This laziness\nallows Rust to avoid running async code until it’s actually needed.\nNote: This is different from the behavior we saw when using `thread::spawn`\nin the “Creating a New Thread with spawn”\nsection in Chapter 16, where the closure we passed to another thread started\nrunning immediately. It’s also different from how many other languages\napproach async. But it’s important for Rust to be able to provide its\nperformance guarantees, just as it is with iterators.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Futures and the Async Syntax", "heading_path": ["Our First Async Program", "Defining the page_title Function"], "path": "ch17-01-futures-and-syntax.md", "url": "https://doc.rust-lang.org/book/ch17-01-futures-and-syntax.html#defining-the-page_title-function", "has_code": false, "code_tags": []}} {"id": "book/ch17-01-futures-and-syntax.md#defining-the-page_title-function-5", "text": "The Rust Programming Language › Our First Async Program › Defining the page_title Function\n\nOnce we have `response_text`, we can parse it into an instance of the `Html`\ntype using `Html::parse`. Instead of a raw string, we now have a data type we\ncan use to work with the HTML as a richer data structure. In particular, we can\nuse the `select_first` method to find the first instance of a given CSS\nselector. By passing the string `\"title\"`, we’ll get the first `<title>`\nelement in the document, if there is one. Because there may not be any matching\nelement, `select_first` returns an `Option<ElementRef>`. Finally, we use the\n`Option::map` method, which lets us work with the item in the `Option` if it’s\npresent, and do nothing if it isn’t. (We could also use a `match` expression\nhere, but `map` is more idiomatic.) In the body of the function we supply to\n`map`, we call `inner_html` on the `title` to get its content, which is a\n`String`. When all is said and done, we have an `Option<String>`.\nNotice that Rust’s `await` keyword goes _after_ the expression you’re awaiting,\nnot before it. That is, it’s a _postfix_ keyword. This may differ from what\nyou’re used to if you’ve used `async` in other languages, but in Rust it makes\nchains of methods much nicer to work with. As a result, we could change the\nbody of `page_title` to chain the `trpl::get` and `text` function calls\ntogether with `await` between them, as shown in Listing 17-2.\nListing 17-2: Chaining with the `await` keyword (src/main.rs)\n```rust\n let response_text = trpl::get(url).await.text().await;\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Futures and the Async Syntax", "heading_path": ["Our First Async Program", "Defining the page_title Function"], "path": "ch17-01-futures-and-syntax.md", "url": "https://doc.rust-lang.org/book/ch17-01-futures-and-syntax.html#defining-the-page_title-function", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch17-01-futures-and-syntax.md#defining-the-page_title-function-6", "text": "The Rust Programming Language › Our First Async Program › Defining the page_title Function\n\nWith that, we have successfully written our first async function! Before we add\nsome code in `main` to call it, let’s talk a little more about what we’ve\nwritten and what it means.\nWhen Rust sees a _block_ marked with the `async` keyword, it compiles it into a\nunique, anonymous data type that implements the `Future` trait. When Rust sees\na _function_ marked with `async`, it compiles it into a non-async function\nwhose body is an async block. An async function’s return type is the type of\nthe anonymous data type the compiler creates for that async block.\nThus, writing `async fn` is equivalent to writing a function that returns a\n_future_ of the return type. To the compiler, a function definition such as the\n`async fn page_title` in Listing 17-1 is roughly equivalent to a non-async\nfunction defined like this:\n```rust\nuse std::future::Future;\nuse trpl::Html;\n\nfn page_title(url: &str) -> impl Future<Output = Option<String>> {\n async move {\n let text = trpl::get(url).await.text().await;\n Html::parse(&text)\n .select_first(\"title\")\n .map(|title| title.inner_html())\n }\n}\n```\nLet’s walk through each part of the transformed version:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Futures and the Async Syntax", "heading_path": ["Our First Async Program", "Defining the page_title Function"], "path": "ch17-01-futures-and-syntax.md", "url": "https://doc.rust-lang.org/book/ch17-01-futures-and-syntax.html#defining-the-page_title-function", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch17-01-futures-and-syntax.md#defining-the-page_title-function-7", "text": "The Rust Programming Language › Our First Async Program › Defining the page_title Function\n\n- It uses the `impl Trait` syntax we discussed back in Chapter 10 in the\n “Traits as Parameters” section.\n- The returned value implements the `Future` trait with an associated type of\n `Output`. Notice that the `Output` type is `Option<String>`, which is the\n same as the original return type from the `async fn` version of `page_title`.\n- All of the code called in the body of the original function is wrapped in\n an `async move` block. Remember that blocks are expressions. This whole block\n is the expression returned from the function.\n- This async block produces a value with the type `Option<String>`, as just\n described. That value matches the `Output` type in the return type. This is\n just like other blocks you have seen.\n- The new function body is an `async move` block because of how it uses the\n `url` parameter. (We’ll talk much more about `async` versus `async move`\n later in the chapter.)\nNow we can call `page_title` in `main`.\n<a id =\"determining-a-single-pages-title\"></a>", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Futures and the Async Syntax", "heading_path": ["Our First Async Program", "Defining the page_title Function"], "path": "ch17-01-futures-and-syntax.md", "url": "https://doc.rust-lang.org/book/ch17-01-futures-and-syntax.html#defining-the-page_title-function", "has_code": false, "code_tags": []}} {"id": "book/ch17-01-futures-and-syntax.md#executing-an-async-function-with-a-runtime-8", "text": "The Rust Programming Language › Our First Async Program › Executing an Async Function with a Runtime\n\nTo start, we’ll get the title for a single page, shown in Listing 17-3.\nUnfortunately, this code doesn’t compile yet.\nListing 17-3: Calling the `page_title` function from `main` with a user-supplied argument (src/main.rs)\n```rust,ignore,does_not_compile\nasync fn main() {\n let args: Vec<String> = std::env::args().collect();\n let url = &args[1];\n match page_title(url).await {\n Some(title) => println!(\"The title for {url} was {title}\"),\n None => println!(\"{url} had no title\"),\n }\n}\n```\nWe follow the same pattern we used to get command line arguments in the\n“Accepting Command Line Arguments” section in\nChapter 12. Then we pass the URL argument to `page_title` and await the result.\nBecause the value produced by the future is an `Option<String>`, we use a\n`match` expression to print different messages to account for whether the page\nhad a `<title>`.\nThe only place we can use the `await` keyword is in async functions or blocks,\nand Rust won’t let us mark the special `main` function as `async`.\n```text\nerror[E0752]: `main` function is not allowed to be `async`\n --> src/main.rs:6:1\n |\n6 | async fn main() {\n | ^^^^^^^^^^^^^^^ `main` function is not allowed to be `async`\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Futures and the Async Syntax", "heading_path": ["Our First Async Program", "Executing an Async Function with a Runtime"], "path": "ch17-01-futures-and-syntax.md", "url": "https://doc.rust-lang.org/book/ch17-01-futures-and-syntax.html#executing-an-async-function-with-a-runtime", "has_code": true, "code_tags": ["rust,ignore,does_not_compile", "text"]}} {"id": "book/ch17-01-futures-and-syntax.md#executing-an-async-function-with-a-runtime-9", "text": "The Rust Programming Language › Our First Async Program › Executing an Async Function with a Runtime\n\nThe reason `main` can’t be marked `async` is that async code needs a _runtime_:\na Rust crate that manages the details of executing asynchronous code. A\nprogram’s `main` function can _initialize_ a runtime, but it’s not a runtime\n_itself_. (We’ll see more about why this is the case in a bit.) Every Rust\nprogram that executes async code has at least one place where it sets up a\nruntime that executes the futures.\nMost languages that support async bundle a runtime, but Rust does not. Instead,\nthere are many different async runtimes available, each of which makes different\ntradeoffs suitable to the use case it targets. For example, a high-throughput\nweb server with many CPU cores and a large amount of RAM has very different\nneeds than a microcontroller with a single core, a small amount of RAM, and no\nheap allocation ability. The crates that provide those runtimes also often\nsupply async versions of common functionality such as file or network I/O.\nHere, and throughout the rest of this chapter, we’ll use the `block_on`\nfunction from the `trpl` crate, which takes a future as an argument and blocks\nthe current thread until this future runs to completion. Behind the scenes,\ncalling `block_on` sets up a runtime using the `tokio` crate that’s used to run\nthe future passed in (the `trpl` crate’s `block_on` behavior is similar to\nother runtime crates’ `block_on` functions). Once the future completes,\n`block_on` returns whatever value the future produced.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Futures and the Async Syntax", "heading_path": ["Our First Async Program", "Executing an Async Function with a Runtime"], "path": "ch17-01-futures-and-syntax.md", "url": "https://doc.rust-lang.org/book/ch17-01-futures-and-syntax.html#executing-an-async-function-with-a-runtime", "has_code": false, "code_tags": []}} {"id": "book/ch17-01-futures-and-syntax.md#executing-an-async-function-with-a-runtime-10", "text": "The Rust Programming Language › Our First Async Program › Executing an Async Function with a Runtime\n\nWe could pass the future returned by `page_title` directly to `block_on` and,\nonce it completed, we could match on the resulting `Option<String>` as we tried\nto do in Listing 17-3. However, for most of the examples in the chapter (and\nmost async code in the real world), we’ll be doing more than just one async\nfunction call, so instead we’ll pass an `async` block and explicitly await the\nresult of the `page_title` call, as in Listing 17-4.\nListing 17-4: Awaiting an async block with `trpl::block_on` (src/main.rs)\n```rust,should_panic,noplayground\nfn main() {\n let args: Vec<String> = std::env::args().collect();\n\n trpl::block_on(async {\n let url = &args[1];\n match page_title(url).await {\n Some(title) => println!(\"The title for {url} was {title}\"),\n None => println!(\"{url} had no title\"),\n }\n })\n}\n```\nWhen we run this code, we get the behavior we expected initially:\n```console\n$ cargo run -- \"https://www.rust-lang.org\"\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.05s\n Running `target/debug/async_await 'https://www.rust-lang.org'`\nThe title for https://www.rust-lang.org was\n Rust Programming Language\n```\nPhew—we finally have some working async code! But before we add the code to\nrace two sites against each other, let’s briefly turn our attention back to how\nfutures work.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Futures and the Async Syntax", "heading_path": ["Our First Async Program", "Executing an Async Function with a Runtime"], "path": "ch17-01-futures-and-syntax.md", "url": "https://doc.rust-lang.org/book/ch17-01-futures-and-syntax.html#executing-an-async-function-with-a-runtime", "has_code": true, "code_tags": ["console", "rust,should_panic,noplayground"]}} {"id": "book/ch17-01-futures-and-syntax.md#executing-an-async-function-with-a-runtime-11", "text": "The Rust Programming Language › Our First Async Program › Executing an Async Function with a Runtime\n\nEach _await point_—that is, every place where the code uses the `await`\nkeyword—represents a place where control is handed back to the runtime. To make\nthat work, Rust needs to keep track of the state involved in the async block so\nthat the runtime could kick off some other work and then come back when it’s\nready to try advancing the first one again. This is an invisible state machine,\nas if you’d written an enum like this to save the current state at each await\npoint:\n```rust\nenum PageTitleFuture<'a> {\n Initial { url: &'a str },\n GetAwaitPoint { url: &'a str },\n TextAwaitPoint { response: trpl::Response },\n}\n```\nWriting the code to transition between each state by hand would be tedious and\nerror-prone, however, especially when you need to add more functionality and\nmore states to the code later. Fortunately, the Rust compiler creates and\nmanages the state machine data structures for async code automatically. The\nnormal borrowing and ownership rules around data structures all still apply,\nand happily, the compiler also handles checking those for us and provides\nuseful error messages. We’ll work through a few of those later in the chapter.\nUltimately, something has to execute this state machine, and that something is\na runtime. (This is why you may come across mentions of _executors_ when\nlooking into runtimes: an executor is the part of a runtime responsible for\nexecuting the async code.)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Futures and the Async Syntax", "heading_path": ["Our First Async Program", "Executing an Async Function with a Runtime"], "path": "ch17-01-futures-and-syntax.md", "url": "https://doc.rust-lang.org/book/ch17-01-futures-and-syntax.html#executing-an-async-function-with-a-runtime", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch17-01-futures-and-syntax.md#executing-an-async-function-with-a-runtime-12", "text": "The Rust Programming Language › Our First Async Program › Executing an Async Function with a Runtime\n\nNow you can see why the compiler stopped us from making `main` itself an async\nfunction back in Listing 17-3. If `main` were an async function, something else\nwould need to manage the state machine for whatever future `main` returned, but\n`main` is the starting point for the program! Instead, we called the\n`trpl::block_on` function in `main` to set up a runtime and run the future\nreturned by the `async` block until it’s done.\nNote: Some runtimes provide macros so you _can_ write an async `main`\nfunction. Those macros rewrite `async fn main() { ... }` to be a normal `fn\nmain`, which does the same thing we did by hand in Listing 17-4: call a\nfunction that runs a future to completion the way `trpl::block_on` does.\nNow let’s put these pieces together and see how we can write concurrent code.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Futures and the Async Syntax", "heading_path": ["Our First Async Program", "Executing an Async Function with a Runtime"], "path": "ch17-01-futures-and-syntax.md", "url": "https://doc.rust-lang.org/book/ch17-01-futures-and-syntax.html#executing-an-async-function-with-a-runtime", "has_code": false, "code_tags": []}} {"id": "book/ch17-01-futures-and-syntax.md#racing-two-urls-against-each-other-concurrently-13", "text": "The Rust Programming Language › Our First Async Program › Racing Two URLs Against Each Other Concurrently\n\nIn Listing 17-5, we call `page_title` with two different URLs passed in from the\ncommand line and race them by selecting whichever future finishes first.\nListing 17-5: Calling `page_title` for two URLs to see which returns first (src/main.rs)\n```rust,should_panic,noplayground\nuse trpl::{Either, Html};\n\nfn main() {\n let args: Vec<String> = std::env::args().collect();\n\n trpl::block_on(async {\n let title_fut_1 = page_title(&args[1]);\n let title_fut_2 = page_title(&args[2]);\n\n let (url, maybe_title) =\n match trpl::select(title_fut_1, title_fut_2).await {\n Either::Left(left) => left,\n Either::Right(right) => right,\n };\n\n println!(\"{url} returned first\");\n match maybe_title {\n Some(title) => println!(\"Its page title was: '{title}'\"),\n None => println!(\"It had no title.\"),\n }\n })\n}\n\nasync fn page_title(url: &str) -> (&str, Option<String>) {\n let response_text = trpl::get(url).await.text().await;\n let title = Html::parse(&response_text)\n .select_first(\"title\")\n .map(|title| title.inner_html());\n (url, title)\n}\n```\nWe begin by calling `page_title` for each of the user-supplied URLs. We save\nthe resulting futures as `title_fut_1` and `title_fut_2`. Remember, these don’t\ndo anything yet, because futures are lazy and we haven’t yet awaited them. Then\nwe pass the futures to `trpl::select`, which returns a value to indicate which\nof the futures passed to it finishes first.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Futures and the Async Syntax", "heading_path": ["Our First Async Program", "Racing Two URLs Against Each Other Concurrently"], "path": "ch17-01-futures-and-syntax.md", "url": "https://doc.rust-lang.org/book/ch17-01-futures-and-syntax.html#racing-two-urls-against-each-other-concurrently", "has_code": true, "code_tags": ["rust,should_panic,noplayground"]}} {"id": "book/ch17-01-futures-and-syntax.md#racing-two-urls-against-each-other-concurrently-14", "text": "The Rust Programming Language › Our First Async Program › Racing Two URLs Against Each Other Concurrently\n\nNote: Under the hood, `trpl::select` is built on a more general `select`\nfunction defined in the `futures` crate. The `futures` crate’s `select`\nfunction can do a lot of things that the `trpl::select` function can’t, but\nit also has some additional complexity that we can skip over for now.\nEither future can legitimately “win,” so it doesn’t make sense to return a\n`Result`. Instead, `trpl::select` returns a type we haven’t seen before,\n`trpl::Either`. The `Either` type is somewhat similar to a `Result` in that it\nhas two cases. Unlike `Result`, though, there is no notion of success or\nfailure baked into `Either`. Instead, it uses `Left` and `Right` to indicate\n“one or the other”:\n```rust\nenum Either<A, B> {\n Left(A),\n Right(B),\n}\n```\nThe `select` function returns `Left` with that future’s output if the first\nargument wins, and `Right` with the second future argument’s output if _that_\none wins. This matches the order the arguments appear in when calling the\nfunction: the first argument is to the left of the second argument.\nWe also update `page_title` to return the same URL passed in. That way, if the\npage that returns first does not have a `<title>` we can resolve, we can still\nprint a meaningful message. With that information available, we wrap up by\nupdating our `println!` output to indicate both which URL finished first and\nwhat, if any, the `<title>` is for the web page at that URL.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Futures and the Async Syntax", "heading_path": ["Our First Async Program", "Racing Two URLs Against Each Other Concurrently"], "path": "ch17-01-futures-and-syntax.md", "url": "https://doc.rust-lang.org/book/ch17-01-futures-and-syntax.html#racing-two-urls-against-each-other-concurrently", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch17-01-futures-and-syntax.md#racing-two-urls-against-each-other-concurrently-15", "text": "The Rust Programming Language › Our First Async Program › Racing Two URLs Against Each Other Concurrently\n\nYou have built a small working web scraper now! Pick a couple URLs and run the\ncommand line tool. You may discover that some sites are consistently faster\nthan others, while in other cases the faster site varies from run to run. More\nimportantly, you’ve learned the basics of working with futures, so now we can\ndig deeper into what we can do with async.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Futures and the Async Syntax", "heading_path": ["Our First Async Program", "Racing Two URLs Against Each Other Concurrently"], "path": "ch17-01-futures-and-syntax.md", "url": "https://doc.rust-lang.org/book/ch17-01-futures-and-syntax.html#racing-two-urls-against-each-other-concurrently", "has_code": false, "code_tags": []}} {"id": "book/ch17-02-concurrency-with-async.md#applying-concurrency-with-async-0", "text": "The Rust Programming Language › Applying Concurrency with Async\n\nIn this section, we’ll apply async to some of the same concurrency challenges\nwe tackled with threads in Chapter 16. Because we already talked about a lot of\nthe key ideas there, in this section we’ll focus on what’s different between\nthreads and futures.\nIn many cases, the APIs for working with concurrency using async are very\nsimilar to those for using threads. In other cases, they end up being quite\ndifferent. Even when the APIs _look_ similar between threads and async, they\noften have different behavior—and they nearly always have different performance\ncharacteristics.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Applying Concurrency with Async", "heading_path": ["Applying Concurrency with Async"], "path": "ch17-02-concurrency-with-async.md", "url": "https://doc.rust-lang.org/book/ch17-02-concurrency-with-async.html#applying-concurrency-with-async", "has_code": false, "code_tags": []}} {"id": "book/ch17-02-concurrency-with-async.md#creating-a-new-task-with-spawn_task-1", "text": "The Rust Programming Language › Applying Concurrency with Async › Creating a New Task with `spawn_task`\n\nThe first operation we tackled in the “Creating a New Thread with\n`spawn`” section in Chapter 16 was counting up on\ntwo separate threads. Let’s do the same using async. The `trpl` crate supplies\na `spawn_task` function that looks very similar to the `thread::spawn` API, and\na `sleep` function that is an async version of the `thread::sleep` API. We can\nuse these together to implement the counting example, as shown in Listing 17-6.\nListing 17-6: Creating a new task to print one thing while the main task prints something else (src/main.rs)\n```rust\nuse std::time::Duration;\n\nfn main() {\n trpl::block_on(async {\n trpl::spawn_task(async {\n for i in 1..10 {\n println!(\"hi number {i} from the first task!\");\n trpl::sleep(Duration::from_millis(500)).await;\n }\n });\n\n for i in 1..5 {\n println!(\"hi number {i} from the second task!\");\n trpl::sleep(Duration::from_millis(500)).await;\n }\n });\n}\n```\nAs our starting point, we set up our `main` function with `trpl::block_on` so\nthat our top-level function can be async.\nNote: From this point forward in the chapter, every example will include this\nexact same wrapping code with `trpl::block_on` in `main`, so we’ll often skip it\njust as we do with `main`. Remember to include it in your code!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Applying Concurrency with Async", "heading_path": ["Applying Concurrency with Async", "Creating a New Task with `spawn_task`"], "path": "ch17-02-concurrency-with-async.md", "url": "https://doc.rust-lang.org/book/ch17-02-concurrency-with-async.html#creating-a-new-task-with-spawn_task", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch17-02-concurrency-with-async.md#creating-a-new-task-with-spawn_task-2", "text": "The Rust Programming Language › Applying Concurrency with Async › Creating a New Task with `spawn_task`\n\nThen we write two loops within that block, each containing a `trpl::sleep`\ncall, which waits for half a second (500 milliseconds) before sending the next\nmessage. We put one loop in the body of a `trpl::spawn_task` and the other in a\ntop-level `for` loop. We also add an `await` after the `sleep` calls.\nThis code behaves similarly to the thread-based implementation—including the\nfact that you may see the messages appear in a different order in your own\nterminal when you run it:\n```text\nhi number 1 from the second task!\nhi number 1 from the first task!\nhi number 2 from the first task!\nhi number 2 from the second task!\nhi number 3 from the first task!\nhi number 3 from the second task!\nhi number 4 from the first task!\nhi number 4 from the second task!\nhi number 5 from the first task!\n```\nThis version stops as soon as the `for` loop in the body of the main async\nblock finishes, because the task spawned by `spawn_task` is shut down when the\n`main` function ends. If you want it to run all the way to the task’s\ncompletion, you will need to use a join handle to wait for the first task to\ncomplete. With threads, we used the `join` method to “block” until the thread\nwas done running. In Listing 17-7, we can use `await` to do the same thing,\nbecause the task handle itself is a future. Its `Output` type is a `Result`, so\nwe also unwrap it after awaiting it.\nListing 17-7: Using `await` with a join handle to run a task to completion (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Applying Concurrency with Async", "heading_path": ["Applying Concurrency with Async", "Creating a New Task with `spawn_task`"], "path": "ch17-02-concurrency-with-async.md", "url": "https://doc.rust-lang.org/book/ch17-02-concurrency-with-async.html#creating-a-new-task-with-spawn_task", "has_code": true, "code_tags": ["text"]}} {"id": "book/ch17-02-concurrency-with-async.md#creating-a-new-task-with-spawn_task-3", "text": "The Rust Programming Language › Applying Concurrency with Async › Creating a New Task with `spawn_task`\n\n```rust\n let handle = trpl::spawn_task(async {\n for i in 1..10 {\n println!(\"hi number {i} from the first task!\");\n trpl::sleep(Duration::from_millis(500)).await;\n }\n });\n\n for i in 1..5 {\n println!(\"hi number {i} from the second task!\");\n trpl::sleep(Duration::from_millis(500)).await;\n }\n\n handle.await.unwrap();\n```\nThis updated version runs until _both_ loops finish:\n```text\nhi number 1 from the second task!\nhi number 1 from the first task!\nhi number 2 from the first task!\nhi number 2 from the second task!\nhi number 3 from the first task!\nhi number 3 from the second task!\nhi number 4 from the first task!\nhi number 4 from the second task!\nhi number 5 from the first task!\nhi number 6 from the first task!\nhi number 7 from the first task!\nhi number 8 from the first task!\nhi number 9 from the first task!\n```\nSo far, it looks like async and threads give us similar outcomes, just with\ndifferent syntax: using `await` instead of calling `join` on the join handle,\nand awaiting the `sleep` calls.\nThe bigger difference is that we didn’t need to spawn another operating system\nthread to do this. In fact, we don’t even need to spawn a task here. Because\nasync blocks compile to anonymous futures, we can put each loop in an async\nblock and have the runtime run them both to completion using the `trpl::join`\nfunction.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Applying Concurrency with Async", "heading_path": ["Applying Concurrency with Async", "Creating a New Task with `spawn_task`"], "path": "ch17-02-concurrency-with-async.md", "url": "https://doc.rust-lang.org/book/ch17-02-concurrency-with-async.html#creating-a-new-task-with-spawn_task", "has_code": true, "code_tags": ["rust", "text"]}} {"id": "book/ch17-02-concurrency-with-async.md#creating-a-new-task-with-spawn_task-4", "text": "The Rust Programming Language › Applying Concurrency with Async › Creating a New Task with `spawn_task`\n\nIn the “Waiting for All Threads to Finish”\nsection in Chapter 16, we showed how to use the `join` method on the\n`JoinHandle` type returned when you call `std::thread::spawn`. The `trpl::join`\nfunction is similar, but for futures. When you give it two futures, it produces\na single new future whose output is a tuple containing the output of each\nfuture you passed in once they _both_ complete. Thus, in Listing 17-8, we use\n`trpl::join` to wait for both `fut1` and `fut2` to finish. We do _not_ await\n`fut1` and `fut2` but instead the new future produced by `trpl::join`. We\nignore the output, because it’s just a tuple containing two unit values.\nListing 17-8: Using `trpl::join` to await two anonymous futures (src/main.rs)\n```rust\n let fut1 = async {\n for i in 1..10 {\n println!(\"hi number {i} from the first task!\");\n trpl::sleep(Duration::from_millis(500)).await;\n }\n };\n\n let fut2 = async {\n for i in 1..5 {\n println!(\"hi number {i} from the second task!\");\n trpl::sleep(Duration::from_millis(500)).await;\n }\n };\n\n trpl::join(fut1, fut2).await;\n```\nWhen we run this, we see both futures run to completion:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Applying Concurrency with Async", "heading_path": ["Applying Concurrency with Async", "Creating a New Task with `spawn_task`"], "path": "ch17-02-concurrency-with-async.md", "url": "https://doc.rust-lang.org/book/ch17-02-concurrency-with-async.html#creating-a-new-task-with-spawn_task", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch17-02-concurrency-with-async.md#creating-a-new-task-with-spawn_task-5", "text": "The Rust Programming Language › Applying Concurrency with Async › Creating a New Task with `spawn_task`\n\n```text\nhi number 1 from the first task!\nhi number 1 from the second task!\nhi number 2 from the first task!\nhi number 2 from the second task!\nhi number 3 from the first task!\nhi number 3 from the second task!\nhi number 4 from the first task!\nhi number 4 from the second task!\nhi number 5 from the first task!\nhi number 6 from the first task!\nhi number 7 from the first task!\nhi number 8 from the first task!\nhi number 9 from the first task!\n```\nNow, you’ll see the exact same order every time, which is very different from\nwhat we saw with threads and with `trpl::spawn_task` in Listing 17-7. That is\nbecause the `trpl::join` function is _fair_, meaning it checks each future\nequally often, alternating between them, and never lets one race ahead if the\nother is ready. With threads, the operating system decides which thread to\ncheck and how long to let it run. With async Rust, the runtime decides which\ntask to check. (In practice, the details get complicated because an async\nruntime might use operating system threads under the hood as part of how it\nmanages concurrency, so guaranteeing fairness can be more work for a\nruntime—but it’s still possible!) Runtimes don’t have to guarantee fairness for\nany given operation, and they often offer different APIs to let you choose\nwhether or not you want fairness.\nTry some of these variations on awaiting the futures and see what they do:\n- Remove the async block from around either or both of the loops.\n- Await each async block immediately after defining it.\n- Wrap only the first loop in an async block, and await the resulting future\n after the body of second loop.\nFor an extra challenge, see if you can figure out what the output will be in\neach case _before_ running the code!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Applying Concurrency with Async", "heading_path": ["Applying Concurrency with Async", "Creating a New Task with `spawn_task`"], "path": "ch17-02-concurrency-with-async.md", "url": "https://doc.rust-lang.org/book/ch17-02-concurrency-with-async.html#creating-a-new-task-with-spawn_task", "has_code": true, "code_tags": ["text"]}} {"id": "book/ch17-02-concurrency-with-async.md#sending-data-between-two-tasks-using-message-passing-6", "text": "The Rust Programming Language › Applying Concurrency with Async › Sending Data Between Two Tasks Using Message Passing\n\nSharing data between futures will also be familiar: we’ll use message passing\nagain, but this time with async versions of the types and functions. We’ll take\na slightly different path than we did in the “Transfer Data Between Threads\nwith Message Passing” section in\nChapter 16 to illustrate some of the key differences between thread-based and\nfutures-based concurrency. In Listing 17-9, we’ll begin with just a single\nasync block—_not_ spawning a separate task as we spawned a separate thread.\nListing 17-9: Creating an async channel and assigning the two halves to `tx` and `rx` (src/main.rs)\n```rust\n let (tx, mut rx) = trpl::channel();\n\n let val = String::from(\"hi\");\n tx.send(val).unwrap();\n\n let received = rx.recv().await.unwrap();\n println!(\"received '{received}'\");\n```\nHere, we use `trpl::channel`, an async version of the multiple-producer,\nsingle-consumer channel API we used with threads back in Chapter 16. The async\nversion of the API is only a little different from the thread-based version: it\nuses a mutable rather than an immutable receiver `rx`, and its `recv` method\nproduces a future we need to await rather than producing the value directly.\nNow we can send messages from the sender to the receiver. Notice that we don’t\nhave to spawn a separate thread or even a task; we merely need to await the\n`rx.recv` call.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Applying Concurrency with Async", "heading_path": ["Applying Concurrency with Async", "Sending Data Between Two Tasks Using Message Passing"], "path": "ch17-02-concurrency-with-async.md", "url": "https://doc.rust-lang.org/book/ch17-02-concurrency-with-async.html#sending-data-between-two-tasks-using-message-passing", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch17-02-concurrency-with-async.md#sending-data-between-two-tasks-using-message-passing-7", "text": "The Rust Programming Language › Applying Concurrency with Async › Sending Data Between Two Tasks Using Message Passing\n\nThe synchronous `Receiver::recv` method in `std::mpsc::channel` blocks until it\nreceives a message. The `trpl::Receiver::recv` method does not, because it is\nasync. Instead of blocking, it hands control back to the runtime until either a\nmessage is received or the send side of the channel closes. By contrast, we\ndon’t await the `send` call, because it doesn’t block. It doesn’t need to,\nbecause the channel we’re sending it into is unbounded.\nNote: Because all of this async code runs in an async block in a\n`trpl::block_on` call, everything within it can avoid blocking. However, the\ncode _outside_ it will block on the `block_on` function returning. That’s the\nwhole point of the `trpl::block_on` function: it lets you _choose_ where to\nblock on some set of async code, and thus where to transition between sync\nand async code.\nNotice two things about this example. First, the message will arrive right\naway. Second, although we use a future here, there’s no concurrency yet.\nEverything in the listing happens in sequence, just as it would if there were\nno futures involved.\nLet’s address the first part by sending a series of messages and sleeping in\nbetween them, as shown in Listing 17-10.\nListing 17-10: Sending and receiving multiple messages over the async channel and sleeping with an `await` between each message (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Applying Concurrency with Async", "heading_path": ["Applying Concurrency with Async", "Sending Data Between Two Tasks Using Message Passing"], "path": "ch17-02-concurrency-with-async.md", "url": "https://doc.rust-lang.org/book/ch17-02-concurrency-with-async.html#sending-data-between-two-tasks-using-message-passing", "has_code": false, "code_tags": []}} {"id": "book/ch17-02-concurrency-with-async.md#sending-data-between-two-tasks-using-message-passing-8", "text": "The Rust Programming Language › Applying Concurrency with Async › Sending Data Between Two Tasks Using Message Passing\n\n```rust,ignore\n let (tx, mut rx) = trpl::channel();\n\n let vals = vec![\n String::from(\"hi\"),\n String::from(\"from\"),\n String::from(\"the\"),\n String::from(\"future\"),\n ];\n\n for val in vals {\n tx.send(val).unwrap();\n trpl::sleep(Duration::from_millis(500)).await;\n }\n\n while let Some(value) = rx.recv().await {\n println!(\"received '{value}'\");\n }\n```\nIn addition to sending the messages, we need to receive them. In this case,\nbecause we know how many messages are coming in, we could do that manually by\ncalling `rx.recv().await` four times. In the real world, though, we’ll generally\nbe waiting on some _unknown_ number of messages, so we need to keep waiting\nuntil we determine that there are no more messages.\nIn Listing 16-10, we used a `for` loop to process all the items received from a\nsynchronous channel. Rust doesn’t yet have a way to use a `for` loop with an\n_asynchronously produced_ series of items, however, so we need to use a loop we\nhaven’t seen before: the `while let` conditional loop. This is the loop version\nof the `if let` construct we saw back in the “Concise Control Flow with `if\nlet` and `let...else`” section in Chapter 6. The loop\nwill continue executing as long as the pattern it specifies continues to match\nthe value.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Applying Concurrency with Async", "heading_path": ["Applying Concurrency with Async", "Sending Data Between Two Tasks Using Message Passing"], "path": "ch17-02-concurrency-with-async.md", "url": "https://doc.rust-lang.org/book/ch17-02-concurrency-with-async.html#sending-data-between-two-tasks-using-message-passing", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch17-02-concurrency-with-async.md#code-within-one-async-block-executes-linearly-9", "text": "The Rust Programming Language › Applying Concurrency with Async › Sending Data Between Two Tasks Using Message Passing › Code Within One Async Block Executes Linearly\n\nThe `rx.recv` call produces a future, which we await. The runtime will pause\nthe future until it is ready. Once a message arrives, the future will resolve\nto `Some(message)` as many times as a message arrives. When the channel closes,\nregardless of whether _any_ messages have arrived, the future will instead\nresolve to `None` to indicate that there are no more values and thus we should\nstop polling—that is, stop awaiting.\nThe `while let` loop pulls all of this together. If the result of calling\n`rx.recv().await` is `Some(message)`, we get access to the message and we can\nuse it in the loop body, just as we could with `if let`. If the result is\n`None`, the loop ends. Every time the loop completes, it hits the await point\nagain, so the runtime pauses it again until another message arrives.\nThe code now successfully sends and receives all of the messages.\nUnfortunately, there are still a couple of problems. For one thing, the\nmessages do not arrive at half-second intervals. They arrive all at once, 2\nseconds (2,000 milliseconds) after we start the program. For another, this\nprogram also never exits! Instead, it waits forever for new messages. You will\nneed to shut it down using <kbd>ctrl</kbd>-<kbd>C</kbd>.\nLet’s start by examining why the messages come in all at once after the full\ndelay, rather than coming in with delays between each one. Within a given async\nblock, the order in which `await` keywords appear in the code is also the order\nin which they’re executed when the program runs.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Applying Concurrency with Async", "heading_path": ["Applying Concurrency with Async", "Sending Data Between Two Tasks Using Message Passing", "Code Within One Async Block Executes Linearly"], "path": "ch17-02-concurrency-with-async.md", "url": "https://doc.rust-lang.org/book/ch17-02-concurrency-with-async.html#code-within-one-async-block-executes-linearly", "has_code": false, "code_tags": []}} {"id": "book/ch17-02-concurrency-with-async.md#code-within-one-async-block-executes-linearly-10", "text": "The Rust Programming Language › Applying Concurrency with Async › Sending Data Between Two Tasks Using Message Passing › Code Within One Async Block Executes Linearly\n\nThere’s only one async block in Listing 17-10, so everything in it runs\nlinearly. There’s still no concurrency. All the `tx.send` calls happen,\ninterspersed with all of the `trpl::sleep` calls and their associated await\npoints. Only then does the `while let` loop get to go through any of the\n`await` points on the `recv` calls.\nTo get the behavior we want, where the sleep delay happens between each\nmessage, we need to put the `tx` and `rx` operations in their own async blocks,\nas shown in Listing 17-11. Then the runtime can execute each of them separately\nusing `trpl::join`, just as in Listing 17-8. Once again, we await the result of\ncalling `trpl::join`, not the individual futures. If we awaited the individual\nfutures in sequence, we would just end up back in a sequential flow—exactly\nwhat we’re trying _not_ to do.\nListing 17-11: Separating `send` and `recv` into their own `async` blocks and awaiting the futures for those blocks (src/main.rs)\n```rust,ignore\n let tx_fut = async {\n let vals = vec![\n String::from(\"hi\"),\n String::from(\"from\"),\n String::from(\"the\"),\n String::from(\"future\"),\n ];\n\n for val in vals {\n tx.send(val).unwrap();\n trpl::sleep(Duration::from_millis(500)).await;\n }\n };\n\n let rx_fut = async {\n while let Some(value) = rx.recv().await {\n println!(\"received '{value}'\");\n }\n };\n\n trpl::join(tx_fut, rx_fut).await;\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Applying Concurrency with Async", "heading_path": ["Applying Concurrency with Async", "Sending Data Between Two Tasks Using Message Passing", "Code Within One Async Block Executes Linearly"], "path": "ch17-02-concurrency-with-async.md", "url": "https://doc.rust-lang.org/book/ch17-02-concurrency-with-async.html#code-within-one-async-block-executes-linearly", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch17-02-concurrency-with-async.md#moving-ownership-into-an-async-block-11", "text": "The Rust Programming Language › Applying Concurrency with Async › Sending Data Between Two Tasks Using Message Passing › Moving Ownership Into an Async Block\n\nWith the updated code in Listing 17-11, the messages get printed at\n500-millisecond intervals, rather than all in a rush after 2 seconds.\nThe program still never exits, though, because of the way the `while let` loop\ninteracts with `trpl::join`:\n- The future returned from `trpl::join` completes only once _both_ futures\n passed to it have completed.\n- The `tx_fut` future completes once it finishes sleeping after sending the last\n message in `vals`.\n- The `rx_fut` future won’t complete until the `while let` loop ends.\n- The `while let` loop won’t end until awaiting `rx.recv` produces `None`.\n- Awaiting `rx.recv` will return `None` only once the other end of the channel\n is closed.\n- The channel will close only if we call `rx.close` or when the sender side,\n `tx`, is dropped.\n- We don’t call `rx.close` anywhere, and `tx` won’t be dropped until the\n outermost async block passed to `trpl::block_on` ends.\n- The block can’t end because it is blocked on `trpl::join` completing, which\n takes us back to the top of this list.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Applying Concurrency with Async", "heading_path": ["Applying Concurrency with Async", "Sending Data Between Two Tasks Using Message Passing", "Moving Ownership Into an Async Block"], "path": "ch17-02-concurrency-with-async.md", "url": "https://doc.rust-lang.org/book/ch17-02-concurrency-with-async.html#moving-ownership-into-an-async-block", "has_code": false, "code_tags": []}} {"id": "book/ch17-02-concurrency-with-async.md#joining-a-number-of-futures-with-the-join-macro-12", "text": "The Rust Programming Language › Applying Concurrency with Async › Sending Data Between Two Tasks Using Message Passing › Joining a Number of Futures with the `join!` Macro\n\nRight now, the async block where we send the messages only _borrows_ `tx`\nbecause sending a message doesn’t require ownership, but if we could _move_\n`tx` into that async block, it would be dropped once that block ends. In the\n“Capturing References or Moving Ownership”\nsection in Chapter 13, you learned how to use the `move` keyword with closures,\nand, as discussed in the “Using `move` Closures with\nThreads” section in Chapter 16, we often need to\nmove data into closures when working with threads. The same basic dynamics\napply to async blocks, so the `move` keyword works with async blocks just as it\ndoes with closures.\nIn Listing 17-12, we change the block used to send messages from `async` to\n`async move`.\nListing 17-12: A revision of the code from Listing 17-11 that correctly shuts down when complete (src/main.rs)\n```rust\n let (tx, mut rx) = trpl::channel();\n\n let tx_fut = async move {\n // --snip--\n```\nWhen we run _this_ version of the code, it shuts down gracefully after the last\nmessage is sent and received. Next, let’s see what would need to change to send\ndata from more than one future.\nThis async channel is also a multiple-producer channel, so we can call `clone`\non `tx` if we want to send messages from multiple futures, as shown in Listing\n17-13.\nListing 17-13: Using multiple producers with async blocks (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Applying Concurrency with Async", "heading_path": ["Applying Concurrency with Async", "Sending Data Between Two Tasks Using Message Passing", "Joining a Number of Futures with the `join!` Macro"], "path": "ch17-02-concurrency-with-async.md", "url": "https://doc.rust-lang.org/book/ch17-02-concurrency-with-async.html#joining-a-number-of-futures-with-the-join-macro", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch17-02-concurrency-with-async.md#joining-a-number-of-futures-with-the-join-macro-13", "text": "The Rust Programming Language › Applying Concurrency with Async › Sending Data Between Two Tasks Using Message Passing › Joining a Number of Futures with the `join!` Macro\n\n```rust\n let (tx, mut rx) = trpl::channel();\n\n let tx1 = tx.clone();\n let tx1_fut = async move {\n let vals = vec![\n String::from(\"hi\"),\n String::from(\"from\"),\n String::from(\"the\"),\n String::from(\"future\"),\n ];\n\n for val in vals {\n tx1.send(val).unwrap();\n trpl::sleep(Duration::from_millis(500)).await;\n }\n };\n\n let rx_fut = async {\n while let Some(value) = rx.recv().await {\n println!(\"received '{value}'\");\n }\n };\n\n let tx_fut = async move {\n let vals = vec![\n String::from(\"more\"),\n String::from(\"messages\"),\n String::from(\"for\"),\n String::from(\"you\"),\n ];\n\n for val in vals {\n tx.send(val).unwrap();\n trpl::sleep(Duration::from_millis(1500)).await;\n }\n };\n\n trpl::join!(tx1_fut, tx_fut, rx_fut);\n```\nFirst, we clone `tx`, creating `tx1` outside the first async block. We move\n`tx1` into that block just as we did before with `tx`. Then, later, we move the\noriginal `tx` into a _new_ async block, where we send more messages on a\nslightly slower delay. We happen to put this new async block after the async\nblock for receiving messages, but it could go before it just as well. The key is\nthe order in which the futures are awaited, not in which they’re created.\nBoth of the async blocks for sending messages need to be `async move` blocks so\nthat both `tx` and `tx1` get dropped when those blocks finish. Otherwise, we’ll\nend up back in the same infinite loop we started out in.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Applying Concurrency with Async", "heading_path": ["Applying Concurrency with Async", "Sending Data Between Two Tasks Using Message Passing", "Joining a Number of Futures with the `join!` Macro"], "path": "ch17-02-concurrency-with-async.md", "url": "https://doc.rust-lang.org/book/ch17-02-concurrency-with-async.html#joining-a-number-of-futures-with-the-join-macro", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch17-02-concurrency-with-async.md#joining-a-number-of-futures-with-the-join-macro-14", "text": "The Rust Programming Language › Applying Concurrency with Async › Sending Data Between Two Tasks Using Message Passing › Joining a Number of Futures with the `join!` Macro\n\nFinally, we switch from `trpl::join` to `trpl::join!` to handle the additional\nfuture: the `join!` macro awaits an arbitrary number of futures where we know\nthe number of futures at compile time. We’ll discuss awaiting a collection of\nan unknown number of futures later in this chapter.\nNow we see all the messages from both sending futures, and because the sending\nfutures use slightly different delays after sending, the messages are also\nreceived at those different intervals:\n```text\nreceived 'hi'\nreceived 'more'\nreceived 'from'\nreceived 'the'\nreceived 'messages'\nreceived 'future'\nreceived 'for'\nreceived 'you'\n```\nWe’ve explored how to use message passing to send data between futures, how\ncode within an async block runs sequentially, how to move ownership into an\nasync block, and how to join multiple futures. Next, let’s discuss how and why\nto tell the runtime it can switch to another task.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Applying Concurrency with Async", "heading_path": ["Applying Concurrency with Async", "Sending Data Between Two Tasks Using Message Passing", "Joining a Number of Futures with the `join!` Macro"], "path": "ch17-02-concurrency-with-async.md", "url": "https://doc.rust-lang.org/book/ch17-02-concurrency-with-async.html#joining-a-number-of-futures-with-the-join-macro", "has_code": true, "code_tags": ["text"]}} {"id": "book/ch17-03-more-futures.md#yielding-control-to-the-runtime-0", "text": "The Rust Programming Language › Yielding Control to the Runtime\n\nRecall from the “Our First Async Program”\nsection that at each await point, Rust gives a runtime a chance to pause the\ntask and switch to another one if the future being awaited isn’t ready. The\ninverse is also true: Rust _only_ pauses async blocks and hands control back to\na runtime at an await point. Everything between await points is synchronous.\nThat means if you do a bunch of work in an async block without an await point,\nthat future will block any other futures from making progress. You may sometimes\nhear this referred to as one future _starving_ other futures. In some cases,\nthat may not be a big deal. However, if you are doing some kind of expensive\nsetup or long-running work, or if you have a future that will keep doing some\nparticular task indefinitely, you’ll need to think about when and where to hand\ncontrol back to the runtime.\nLet’s simulate a long-running operation to illustrate the starvation problem,\nthen explore how to solve it. Listing 17-14 introduces a `slow` function.\nListing 17-14: Using `thread::sleep` to simulate slow operations (src/main.rs)\n```rust\nfn slow(name: &str, ms: u64) {\n thread::sleep(Duration::from_millis(ms));\n println!(\"'{name}' ran for {ms}ms\");\n}\n```\nThis code uses `std::thread::sleep` instead of `trpl::sleep` so that calling\n`slow` will block the current thread for some number of milliseconds. We can\nuse `slow` to stand in for real-world operations that are both long-running and\nblocking.\nIn Listing 17-15, we use `slow` to emulate doing this kind of CPU-bound work in\na pair of futures.\nListing 17-15: Calling the `slow` function to simulate slow operations (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Working With Any Number of Futures", "heading_path": ["Yielding Control to the Runtime"], "path": "ch17-03-more-futures.md", "url": "https://doc.rust-lang.org/book/ch17-03-more-futures.html#yielding-control-to-the-runtime", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch17-03-more-futures.md#yielding-control-to-the-runtime-1", "text": "The Rust Programming Language › Yielding Control to the Runtime\n\n```rust\n let a = async {\n println!(\"'a' started.\");\n slow(\"a\", 30);\n slow(\"a\", 10);\n slow(\"a\", 20);\n trpl::sleep(Duration::from_millis(50)).await;\n println!(\"'a' finished.\");\n };\n\n let b = async {\n println!(\"'b' started.\");\n slow(\"b\", 75);\n slow(\"b\", 10);\n slow(\"b\", 15);\n slow(\"b\", 350);\n trpl::sleep(Duration::from_millis(50)).await;\n println!(\"'b' finished.\");\n };\n\n trpl::select(a, b).await;\n```\nEach future hands control back to the runtime only _after_ carrying out a bunch\nof slow operations. If you run this code, you will see this output:\n```text\n'a' started.\n'a' ran for 30ms\n'a' ran for 10ms\n'a' ran for 20ms\n'b' started.\n'b' ran for 75ms\n'b' ran for 10ms\n'b' ran for 15ms\n'b' ran for 350ms\n'a' finished.\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Working With Any Number of Futures", "heading_path": ["Yielding Control to the Runtime"], "path": "ch17-03-more-futures.md", "url": "https://doc.rust-lang.org/book/ch17-03-more-futures.html#yielding-control-to-the-runtime", "has_code": true, "code_tags": ["rust", "text"]}} {"id": "book/ch17-03-more-futures.md#yielding-control-to-the-runtime-2", "text": "The Rust Programming Language › Yielding Control to the Runtime\n\nAs with Listing 17-5 where we used `trpl::select` to race futures fetching two\nURLs, `select` still finishes as soon as `a` is done. There’s no interleaving\nbetween the calls to `slow` in the two futures, though. The `a` future does all\nof its work until the `trpl::sleep` call is awaited, then the `b` future does\nall of its work until its own `trpl::sleep` call is awaited, and finally the\n`a` future completes. To allow both futures to make progress between their slow\ntasks, we need await points so we can hand control back to the runtime. That\nmeans we need something we can await!\nWe can already see this kind of handoff happening in Listing 17-15: if we\nremoved the `trpl::sleep` at the end of the `a` future, it would complete\nwithout the `b` future running _at all_. Let’s try using the `trpl::sleep`\nfunction as a starting point for letting operations switch off making progress,\nas shown in Listing 17-16.\nListing 17-16: Using `trpl::sleep` to let operations switch off making progress (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Working With Any Number of Futures", "heading_path": ["Yielding Control to the Runtime"], "path": "ch17-03-more-futures.md", "url": "https://doc.rust-lang.org/book/ch17-03-more-futures.html#yielding-control-to-the-runtime", "has_code": false, "code_tags": []}} {"id": "book/ch17-03-more-futures.md#yielding-control-to-the-runtime-3", "text": "The Rust Programming Language › Yielding Control to the Runtime\n\n```rust\n let one_ms = Duration::from_millis(1);\n\n let a = async {\n println!(\"'a' started.\");\n slow(\"a\", 30);\n trpl::sleep(one_ms).await;\n slow(\"a\", 10);\n trpl::sleep(one_ms).await;\n slow(\"a\", 20);\n trpl::sleep(one_ms).await;\n println!(\"'a' finished.\");\n };\n\n let b = async {\n println!(\"'b' started.\");\n slow(\"b\", 75);\n trpl::sleep(one_ms).await;\n slow(\"b\", 10);\n trpl::sleep(one_ms).await;\n slow(\"b\", 15);\n trpl::sleep(one_ms).await;\n slow(\"b\", 350);\n trpl::sleep(one_ms).await;\n println!(\"'b' finished.\");\n };\n```\nWe’ve added `trpl::sleep` calls with await points between each call to `slow`.\nNow the two futures’ work is interleaved:\n```text\n'a' started.\n'a' ran for 30ms\n'b' started.\n'b' ran for 75ms\n'a' ran for 10ms\n'b' ran for 10ms\n'a' ran for 20ms\n'b' ran for 15ms\n'a' finished.\n```\nThe `a` future still runs for a bit before handing off control to `b`, because\nit calls `slow` before ever calling `trpl::sleep`, but after that the futures\nswap back and forth each time one of them hits an await point. In this case, we\nhave done that after every call to `slow`, but we could break up the work in\nwhatever way makes the most sense to us.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Working With Any Number of Futures", "heading_path": ["Yielding Control to the Runtime"], "path": "ch17-03-more-futures.md", "url": "https://doc.rust-lang.org/book/ch17-03-more-futures.html#yielding-control-to-the-runtime", "has_code": true, "code_tags": ["rust", "text"]}} {"id": "book/ch17-03-more-futures.md#yielding-control-to-the-runtime-4", "text": "The Rust Programming Language › Yielding Control to the Runtime\n\nWe don’t really want to _sleep_ here, though: we want to make progress as fast\nas we can. We just need to hand back control to the runtime. We can do that\ndirectly, using the `trpl::yield_now` function. In Listing 17-17, we replace\nall those `trpl::sleep` calls with `trpl::yield_now`.\nListing 17-17: Using `yield_now` to let operations switch off making progress (src/main.rs)\n```rust\n let a = async {\n println!(\"'a' started.\");\n slow(\"a\", 30);\n trpl::yield_now().await;\n slow(\"a\", 10);\n trpl::yield_now().await;\n slow(\"a\", 20);\n trpl::yield_now().await;\n println!(\"'a' finished.\");\n };\n\n let b = async {\n println!(\"'b' started.\");\n slow(\"b\", 75);\n trpl::yield_now().await;\n slow(\"b\", 10);\n trpl::yield_now().await;\n slow(\"b\", 15);\n trpl::yield_now().await;\n slow(\"b\", 350);\n trpl::yield_now().await;\n println!(\"'b' finished.\");\n };\n```\nThis code is both clearer about the actual intent and can be significantly\nfaster than using `sleep`, because timers such as the one used by `sleep` often\nhave limits on how granular they can be. The version of `sleep` we are using,\nfor example, will always sleep for at least a millisecond, even if we pass it a\n`Duration` of one nanosecond. Again, modern computers are _fast_: they can do a\nlot in one millisecond!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Working With Any Number of Futures", "heading_path": ["Yielding Control to the Runtime"], "path": "ch17-03-more-futures.md", "url": "https://doc.rust-lang.org/book/ch17-03-more-futures.html#yielding-control-to-the-runtime", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch17-03-more-futures.md#yielding-control-to-the-runtime-5", "text": "The Rust Programming Language › Yielding Control to the Runtime\n\nThis means that async can be useful even for compute-bound tasks, depending on\nwhat else your program is doing, because it provides a useful tool for\nstructuring the relationships between different parts of the program (but at a\ncost of the overhead of the async state machine). This is a form of\n_cooperative multitasking_, where each future has the power to determine when\nit hands over control via await points. Each future therefore also has the\nresponsibility to avoid blocking for too long. In some Rust-based embedded\noperating systems, this is the _only_ kind of multitasking!\nIn real-world code, you won’t usually be alternating function calls with await\npoints on every single line, of course. While yielding control in this way is\nrelatively inexpensive, it’s not free. In many cases, trying to break up a\ncompute-bound task might make it significantly slower, so sometimes it’s better\nfor _overall_ performance to let an operation block briefly. Always\nmeasure to see what your code’s actual performance bottlenecks are. The\nunderlying dynamic is important to keep in mind, though, if you _are_ seeing a\nlot of work happening in serial that you expected to happen concurrently!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Working With Any Number of Futures", "heading_path": ["Yielding Control to the Runtime"], "path": "ch17-03-more-futures.md", "url": "https://doc.rust-lang.org/book/ch17-03-more-futures.html#yielding-control-to-the-runtime", "has_code": false, "code_tags": []}} {"id": "book/ch17-03-more-futures.md#building-our-own-async-abstractions-6", "text": "The Rust Programming Language › Building Our Own Async Abstractions\n\nWe can also compose futures together to create new patterns. For example, we can\nbuild a `timeout` function with async building blocks we already have. When\nwe’re done, the result will be another building block we could use to create\nstill more async abstractions.\nListing 17-18 shows how we would expect this `timeout` to work with a slow\nfuture.\nListing 17-18: Using our imagined `timeout` to run a slow operation with a time limit (src/main.rs)\n```rust,ignore,does_not_compile\n let slow = async {\n trpl::sleep(Duration::from_secs(5)).await;\n \"Finally finished\"\n };\n\n match timeout(slow, Duration::from_secs(2)).await {\n Ok(message) => println!(\"Succeeded with '{message}'\"),\n Err(duration) => {\n println!(\"Failed after {} seconds\", duration.as_secs())\n }\n }\n```\nLet’s implement this! To begin, let’s think about the API for `timeout`:\n- It needs to be an async function itself so we can await it.\n- Its first parameter should be a future to run. We can make it generic to allow\n it to work with any future.\n- Its second parameter will be the maximum time to wait. If we use a `Duration`,\n that will make it easy to pass along to `trpl::sleep`.\n- It should return a `Result`. If the future completes successfully, the\n `Result` will be `Ok` with the value produced by the future. If the timeout\n elapses first, the `Result` will be `Err` with the duration that the timeout\n waited for.\nListing 17-19 shows this declaration.\nListing 17-19: Defining the signature of `timeout` (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Working With Any Number of Futures", "heading_path": ["Building Our Own Async Abstractions"], "path": "ch17-03-more-futures.md", "url": "https://doc.rust-lang.org/book/ch17-03-more-futures.html#building-our-own-async-abstractions", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch17-03-more-futures.md#building-our-own-async-abstractions-7", "text": "The Rust Programming Language › Building Our Own Async Abstractions\n\n```rust,ignore,does_not_compile\nasync fn timeout<F: Future>(\n future_to_try: F,\n max_time: Duration,\n) -> Result<F::Output, Duration> {\n // Here is where our implementation will go!\n}\n```\nThat satisfies our goals for the types. Now let’s think about the _behavior_ we\nneed: we want to race the future passed in against the duration. We can use\n`trpl::sleep` to make a timer future from the duration, and use `trpl::select`\nto run that timer with the future the caller passes in.\nIn Listing 17-20, we implement `timeout` by matching on the result of awaiting\n`trpl::select`.\nListing 17-20: Defining `timeout` with `select` and `sleep` (src/main.rs)\n```rust\nuse trpl::Either;\n\n// --snip--\n\nasync fn timeout<F: Future>(\n future_to_try: F,\n max_time: Duration,\n) -> Result<F::Output, Duration> {\n match trpl::select(future_to_try, trpl::sleep(max_time)).await {\n Either::Left(output) => Ok(output),\n Either::Right(_) => Err(max_time),\n }\n}\n```\nThe implementation of `trpl::select` is not fair: it always polls arguments in\nthe order in which they are passed (other `select` implementations will\nrandomly choose which argument to poll first). Thus, we pass `future_to_try` to\n`select` first so it gets a chance to complete even if `max_time` is a very\nshort duration. If `future_to_try` finishes first, `select` will return `Left`\nwith the output from `future_to_try`. If `timer` finishes first, `select` will\nreturn `Right` with the timer’s output of `()`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Working With Any Number of Futures", "heading_path": ["Building Our Own Async Abstractions"], "path": "ch17-03-more-futures.md", "url": "https://doc.rust-lang.org/book/ch17-03-more-futures.html#building-our-own-async-abstractions", "has_code": true, "code_tags": ["rust", "rust,ignore,does_not_compile"]}} {"id": "book/ch17-03-more-futures.md#building-our-own-async-abstractions-8", "text": "The Rust Programming Language › Building Our Own Async Abstractions\n\nIf the `future_to_try` succeeds and we get a `Left(output)`, we return\n`Ok(output)`. If the sleep timer elapses instead and we get a `Right(())`, we\nignore the `()` with `_` and return `Err(max_time)` instead.\nWith that, we have a working `timeout` built out of two other async helpers. If\nwe run our code, it will print the failure mode after the timeout:\n```text\nFailed after 2 seconds\n```\nBecause futures compose with other futures, you can build really powerful tools\nusing smaller async building blocks. For example, you can use this same\napproach to combine timeouts with retries, and in turn use those with\noperations such as network calls (such as those in Listing 17-5).\nIn practice, you’ll usually work directly with `async` and `await`, and\nsecondarily with functions such as `select` and macros such as the `join!`\nmacro to control how the outermost futures are executed.\nWe’ve now seen a number of ways to work with multiple futures at the same time.\nUp next, we’ll look at how we can work with multiple futures in a sequence over\ntime with _streams_.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Working With Any Number of Futures", "heading_path": ["Building Our Own Async Abstractions"], "path": "ch17-03-more-futures.md", "url": "https://doc.rust-lang.org/book/ch17-03-more-futures.html#building-our-own-async-abstractions", "has_code": true, "code_tags": ["text"]}} {"id": "book/ch17-04-streams.md#streams-futures-in-sequence-0", "text": "The Rust Programming Language › Streams: Futures in Sequence\n\nRecall how we used the receiver for our async channel earlier in this chapter\nin the “Message Passing” section. The async\n`recv` method produces a sequence of items over time. This is an instance of a\nmuch more general pattern known as a _stream_. Many concepts are naturally\nrepresented as streams: items becoming available in a queue, chunks of data\nbeing pulled incrementally from the filesystem when the full data set is too\nlarge for the computer’s memory, or data arriving over the network over time.\nBecause streams are futures, we can use them with any other kind of future and\ncombine them in interesting ways. For example, we can batch up events to avoid\ntriggering too many network calls, set timeouts on sequences of long-running\noperations, or throttle user interface events to avoid doing needless work.\nWe saw a sequence of items back in Chapter 13, when we looked at the Iterator\ntrait in “The Iterator Trait and the `next` Method”\n section, but there are two differences between iterators and the\nasync channel receiver. The first difference is time: iterators are\nsynchronous, while the channel receiver is asynchronous. The second difference\nis the API. When working directly with `Iterator`, we call its synchronous\n`next` method. With the `trpl::Receiver` stream in particular, we called an\nasynchronous `recv` method instead. Otherwise, these APIs feel very similar,\nand that similarity isn’t a coincidence. A stream is like an asynchronous form\nof iteration. Whereas the `trpl::Receiver` specifically waits to receive\nmessages, though, the general-purpose stream API is much broader: it provides\nthe next item the way `Iterator` does, but asynchronously.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Streams: Futures in Sequence", "heading_path": ["Streams: Futures in Sequence"], "path": "ch17-04-streams.md", "url": "https://doc.rust-lang.org/book/ch17-04-streams.html#streams-futures-in-sequence", "has_code": false, "code_tags": []}} {"id": "book/ch17-04-streams.md#streams-futures-in-sequence-1", "text": "The Rust Programming Language › Streams: Futures in Sequence\n\nThe similarity between iterators and streams in Rust means we can actually\ncreate a stream from any iterator. As with an iterator, we can work with a\nstream by calling its `next` method and then awaiting the output, as in Listing\n17-21, which won’t compile yet.\nListing 17-21: Creating a stream from an iterator and printing its values (src/main.rs)\n```rust,ignore,does_not_compile\n let values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\n let iter = values.iter().map(|n| n * 2);\n let mut stream = trpl::stream_from_iter(iter);\n\n while let Some(value) = stream.next().await {\n println!(\"The value was: {value}\");\n }\n```\nWe start with an array of numbers, which we convert to an iterator and then\ncall `map` on to double all the values. Then we convert the iterator into a\nstream using the `trpl::stream_from_iter` function. Next, we loop over the\nitems in the stream as they arrive with the `while let` loop.\nUnfortunately, when we try to run the code, it doesn’t compile but instead\nreports that there’s no `next` method available:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Streams: Futures in Sequence", "heading_path": ["Streams: Futures in Sequence"], "path": "ch17-04-streams.md", "url": "https://doc.rust-lang.org/book/ch17-04-streams.html#streams-futures-in-sequence", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch17-04-streams.md#streams-futures-in-sequence-2", "text": "The Rust Programming Language › Streams: Futures in Sequence\n\n```text\nerror[E0599]: no method named `next` found for struct `tokio_stream::iter::Iter` in the current scope\n --> src/main.rs:10:40\n |\n10 | while let Some(value) = stream.next().await {\n | ^^^^\n |\n = help: items from traits can only be used if the trait is in scope\nhelp: the following traits which provide `next` are implemented but not in scope; perhaps you want to import one of them\n |\n1 + use crate::trpl::StreamExt;\n |\n1 + use futures_util::stream::stream::StreamExt;\n |\n1 + use std::iter::Iterator;\n |\n1 + use std::str::pattern::Searcher;\n |\nhelp: there is a method `try_next` with a similar name\n |\n10 | while let Some(value) = stream.try_next().await {\n | ~~~~~~~~\n```\nAs this output explains, the reason for the compiler error is that we need the\nright trait in scope to be able to use the `next` method. Given our discussion\nso far, you might reasonably expect that trait to be `Stream`, but it’s\nactually `StreamExt`. Short for _extension_, `Ext` is a common pattern in the\nRust community for extending one trait with another.\nThe `Stream` trait defines a low-level interface that effectively combines the\n`Iterator` and `Future` traits. `StreamExt` supplies a higher-level set of APIs\non top of `Stream`, including the `next` method as well as other utility\nmethods similar to those provided by the `Iterator` trait. `Stream` and\n`StreamExt` are not yet part of Rust’s standard library, but most ecosystem\ncrates use similar definitions.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Streams: Futures in Sequence", "heading_path": ["Streams: Futures in Sequence"], "path": "ch17-04-streams.md", "url": "https://doc.rust-lang.org/book/ch17-04-streams.html#streams-futures-in-sequence", "has_code": true, "code_tags": ["text"]}} {"id": "book/ch17-04-streams.md#streams-futures-in-sequence-3", "text": "The Rust Programming Language › Streams: Futures in Sequence\n\nThe fix to the compiler error is to add a `use` statement for\n`trpl::StreamExt`, as in Listing 17-22.\nListing 17-22: Successfully using an iterator as the basis for a stream (src/main.rs)\n```rust\nuse trpl::StreamExt;\n\nfn main() {\n trpl::block_on(async {\n let values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\n // --snip--\n```\nWith all those pieces put together, this code works the way we want! What’s\nmore, now that we have `StreamExt` in scope, we can use all of its utility\nmethods, just as with iterators.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Streams: Futures in Sequence", "heading_path": ["Streams: Futures in Sequence"], "path": "ch17-04-streams.md", "url": "https://doc.rust-lang.org/book/ch17-04-streams.html#streams-futures-in-sequence", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch17-05-traits-for-async.md#a-closer-look-at-the-traits-for-async-0", "text": "The Rust Programming Language › A Closer Look at the Traits for Async\n\nThroughout the chapter, we’ve used the `Future`, `Stream`, and `StreamExt`\ntraits in various ways. So far, though, we’ve avoided getting too far into the\ndetails of how they work or how they fit together, which is fine most of the\ntime for your day-to-day Rust work. Sometimes, though, you’ll encounter\nsituations where you’ll need to understand a few more of these traits’ details,\nalong with the `Pin` type and the `Unpin` trait. In this section, we’ll dig in\njust enough to help in those scenarios, still leaving the _really_ deep dive\nfor other documentation.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "A Closer Look at the Traits for Async", "heading_path": ["A Closer Look at the Traits for Async"], "path": "ch17-05-traits-for-async.md", "url": "https://doc.rust-lang.org/book/ch17-05-traits-for-async.html#a-closer-look-at-the-traits-for-async", "has_code": false, "code_tags": []}} {"id": "book/ch17-05-traits-for-async.md#the-future-trait-1", "text": "The Rust Programming Language › A Closer Look at the Traits for Async › The `Future` Trait\n\nLet’s start by taking a closer look at how the `Future` trait works. Here’s how\nRust defines it:\n```rust\nuse std::pin::Pin;\nuse std::task::{Context, Poll};\n\npub trait Future {\n type Output;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;\n}\n```\nThat trait definition includes a bunch of new types and also some syntax we\nhaven’t seen before, so let’s walk through the definition piece by piece.\nFirst, `Future`’s associated type `Output` says what the future resolves to.\nThis is analogous to the `Item` associated type for the `Iterator` trait.\nSecond, `Future` has the `poll` method, which takes a special `Pin` reference\nfor its `self` parameter and a mutable reference to a `Context` type, and\nreturns a `Poll<Self::Output>`. We’ll talk more about `Pin` and `Context` in a\nmoment. For now, let’s focus on what the method returns, the `Poll` type:\n```rust\npub enum Poll<T> {\n Ready(T),\n Pending,\n}\n```\nThis `Poll` type is similar to an `Option`. It has one variant that has a value,\n`Ready(T)`, and one that does not, `Pending`. `Poll` means something quite\ndifferent from `Option`, though! The `Pending` variant indicates that the future\nstill has work to do, so the caller will need to check again later. The `Ready`\nvariant indicates that the `Future` has finished its work and the `T` value is\navailable.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "A Closer Look at the Traits for Async", "heading_path": ["A Closer Look at the Traits for Async", "The `Future` Trait"], "path": "ch17-05-traits-for-async.md", "url": "https://doc.rust-lang.org/book/ch17-05-traits-for-async.html#the-future-trait", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch17-05-traits-for-async.md#the-future-trait-2", "text": "The Rust Programming Language › A Closer Look at the Traits for Async › The `Future` Trait\n\nNote: It’s rare to need to call `poll` directly, but if you do need to, keep\nin mind that with most futures, the caller should not call `poll` again after\nthe future has returned `Ready`. Many futures will panic if polled again after\nbecoming ready. Futures that are safe to poll again will say so explicitly in\ntheir documentation. This is similar to how `Iterator::next` behaves.\nWhen you see code that uses `await`, Rust compiles it under the hood to code\nthat calls `poll`. If you look back at Listing 17-4, where we printed out the\npage title for a single URL once it resolved, Rust compiles it into something\nkind of (although not exactly) like this:\n```rust,ignore\nmatch page_title(url).poll() {\n Ready(page_title) => match page_title {\n Some(title) => println!(\"The title for {url} was {title}\"),\n None => println!(\"{url} had no title\"),\n }\n Pending => {\n // But what goes here?\n }\n}\n```\nWhat should we do when the future is still `Pending`? We need some way to try\nagain, and again, and again, until the future is finally ready. In other words,\nwe need a loop:\n```rust,ignore\nlet mut page_title_fut = page_title(url);\nloop {\n match page_title_fut.poll() {\n Ready(value) => match page_title {\n Some(title) => println!(\"The title for {url} was {title}\"),\n None => println!(\"{url} had no title\"),\n }\n Pending => {\n // continue\n }\n }\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "A Closer Look at the Traits for Async", "heading_path": ["A Closer Look at the Traits for Async", "The `Future` Trait"], "path": "ch17-05-traits-for-async.md", "url": "https://doc.rust-lang.org/book/ch17-05-traits-for-async.html#the-future-trait", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch17-05-traits-for-async.md#the-future-trait-3", "text": "The Rust Programming Language › A Closer Look at the Traits for Async › The `Future` Trait\n\nIf Rust compiled it to exactly that code, though, every `await` would be\nblocking—exactly the opposite of what we were going for! Instead, Rust ensures\nthat the loop can hand off control to something that can pause work on this\nfuture to work on other futures and then check this one again later. As we’ve\nseen, that something is an async runtime, and this scheduling and coordination\nwork is one of its main jobs.\nIn the “Sending Data Between Two Tasks Using Message\nPassing” section, we described waiting on\n`rx.recv`. The `recv` call returns a future, and awaiting the future polls it.\nWe noted that a runtime will pause the future until it’s ready with either\n`Some(message)` or `None` when the channel closes. With our deeper\nunderstanding of the `Future` trait, and specifically `Future::poll`, we can\nsee how that works. The runtime knows the future isn’t ready when it returns\n`Poll::Pending`. Conversely, the runtime knows the future _is_ ready and\nadvances it when `poll` returns `Poll::Ready(Some(message))` or\n`Poll::Ready(None)`.\nThe exact details of how a runtime does that are beyond the scope of this book,\nbut the key is to see the basic mechanics of futures: a runtime _polls_ each\nfuture it is responsible for, putting the future back to sleep when it is not\nyet ready.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "A Closer Look at the Traits for Async", "heading_path": ["A Closer Look at the Traits for Async", "The `Future` Trait"], "path": "ch17-05-traits-for-async.md", "url": "https://doc.rust-lang.org/book/ch17-05-traits-for-async.html#the-future-trait", "has_code": false, "code_tags": []}} {"id": "book/ch17-05-traits-for-async.md#the-pin-type-and-the-unpin-trait-4", "text": "The Rust Programming Language › A Closer Look at the Traits for Async › The `Pin` Type and the `Unpin` Trait\n\nBack in Listing 17-13, we used the `trpl::join!` macro to await three\nfutures. However, it’s common to have a collection such as a vector containing\nsome number of futures that won’t be known until runtime. Let’s change Listing\n17-13 to the code in Listing 17-23 that puts the three futures into a vector\nand calls the `trpl::join_all` function instead, which won’t compile yet.\nListing 17-23: Awaiting futures in a collection (src/main.rs)\n```rust,ignore,does_not_compile\n let tx_fut = async move {\n // --snip--\n };\n\n let futures: Vec<Box<dyn Future<Output = ()>>> =\n vec![Box::new(tx1_fut), Box::new(rx_fut), Box::new(tx_fut)];\n\n trpl::join_all(futures).await;\n```\nWe put each future within a `Box` to make them into _trait objects_, just as\nwe did in the “Returning Errors from `run`” section in Chapter 12. (We’ll cover\ntrait objects in detail in Chapter 18.) Using trait objects lets us treat each\nof the anonymous futures produced by these types as the same type, because all\nof them implement the `Future` trait.\nThis might be surprising. After all, none of the async blocks returns anything,\nso each one produces a `Future<Output = ()>`. Remember that `Future` is a\ntrait, though, and that the compiler creates a unique enum for each async\nblock, even when they have identical output types. Just as you can’t put two\ndifferent handwritten structs in a `Vec`, you can’t mix compiler-generated\nenums.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "A Closer Look at the Traits for Async", "heading_path": ["A Closer Look at the Traits for Async", "The `Pin` Type and the `Unpin` Trait"], "path": "ch17-05-traits-for-async.md", "url": "https://doc.rust-lang.org/book/ch17-05-traits-for-async.html#the-pin-type-and-the-unpin-trait", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch17-05-traits-for-async.md#the-pin-type-and-the-unpin-trait-5", "text": "The Rust Programming Language › A Closer Look at the Traits for Async › The `Pin` Type and the `Unpin` Trait\n\nThen we pass the collection of futures to the `trpl::join_all` function and\nawait the result. However, this doesn’t compile; here’s the relevant part of\nthe error messages.\n```text\nerror[E0277]: `dyn Future<Output = ()>` cannot be unpinned\n --> src/main.rs:48:33\n |\n48 | trpl::join_all(futures).await;\n | ^^^^^ the trait `Unpin` is not implemented for `dyn Future<Output = ()>`\n |\n = note: consider using the `pin!` macro\n consider using `Box::pin` if you need to access the pinned value outside of the current scope\n = note: required for `Box<dyn Future<Output = ()>>` to implement `Future`\nnote: required by a bound in `futures_util::future::join_all::JoinAll`\n --> file:///home/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/futures-util-0.3.30/src/future/join_all.rs:29:8\n |\n27 | pub struct JoinAll<F>\n | ------- required by a bound in this struct\n28 | where\n29 | F: Future,\n | ^^^^^^ required by this bound in `JoinAll`\n```\nThe note in this error message tells us that we should use the `pin!` macro to\n_pin_ the values, which means putting them inside the `Pin` type that\nguarantees the values won’t be moved in memory. The error message says pinning\nis required because `dyn Future<Output = ()>` needs to implement the `Unpin`\ntrait and it currently does not.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "A Closer Look at the Traits for Async", "heading_path": ["A Closer Look at the Traits for Async", "The `Pin` Type and the `Unpin` Trait"], "path": "ch17-05-traits-for-async.md", "url": "https://doc.rust-lang.org/book/ch17-05-traits-for-async.html#the-pin-type-and-the-unpin-trait", "has_code": true, "code_tags": ["text"]}} {"id": "book/ch17-05-traits-for-async.md#the-pin-type-and-the-unpin-trait-6", "text": "The Rust Programming Language › A Closer Look at the Traits for Async › The `Pin` Type and the `Unpin` Trait\n\nThe `trpl::join_all` function returns a struct called `JoinAll`. That struct is\ngeneric over a type `F`, which is constrained to implement the `Future` trait.\nDirectly awaiting a future with `await` pins the future implicitly. That’s why\nwe don’t need to use `pin!` everywhere we want to await futures.\nHowever, we’re not directly awaiting a future here. Instead, we construct a new\nfuture, JoinAll, by passing a collection of futures to the `join_all` function.\nThe signature for `join_all` requires that the types of the items in the\ncollection all implement the `Future` trait, and `Box<T>` implements `Future`\nonly if the `T` it wraps is a future that implements the `Unpin` trait.\nThat’s a lot to absorb! To really understand it, let’s dive a little further\ninto how the `Future` trait actually works, in particular around pinning. Look\nagain at the definition of the `Future` trait:\n```rust\nuse std::pin::Pin;\nuse std::task::{Context, Poll};\n\npub trait Future {\n type Output;\n\n // Required method\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;\n}\n```\nThe `cx` parameter and its `Context` type are the key to how a runtime actually\nknows when to check any given future while still being lazy. Again, the details\nof how that works are beyond the scope of this chapter, and you generally only\nneed to think about this when writing a custom `Future` implementation. We’ll\nfocus instead on the type for `self`, as this is the first time we’ve seen a\nmethod where `self` has a type annotation. A type annotation for `self` works\nlike type annotations for other function parameters but with two key\ndifferences:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "A Closer Look at the Traits for Async", "heading_path": ["A Closer Look at the Traits for Async", "The `Pin` Type and the `Unpin` Trait"], "path": "ch17-05-traits-for-async.md", "url": "https://doc.rust-lang.org/book/ch17-05-traits-for-async.html#the-pin-type-and-the-unpin-trait", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch17-05-traits-for-async.md#the-pin-type-and-the-unpin-trait-7", "text": "The Rust Programming Language › A Closer Look at the Traits for Async › The `Pin` Type and the `Unpin` Trait\n\n- It tells Rust what type `self` must be for the method to be called.\n- It can’t be just any type. It’s restricted to the type on which the method is\n implemented, a reference or smart pointer to that type, or a `Pin` wrapping a\n reference to that type.\nWe’ll see more on this syntax in Chapter 18. For now,\nit’s enough to know that if we want to poll a future to check whether it is\n`Pending` or `Ready(Output)`, we need a `Pin`-wrapped mutable reference to the\ntype.\n`Pin` is a wrapper for pointer-like types such as `&`, `&mut`, `Box`, and `Rc`.\n(Technically, `Pin` works with types that implement the `Deref` or `DerefMut`\ntraits, but this is effectively equivalent to working only with references and\nsmart pointers.) `Pin` is not a pointer itself and doesn’t have any behavior of\nits own like `Rc` and `Arc` do with reference counting; it’s purely a tool the\ncompiler can use to enforce constraints on pointer usage.\nRecalling that `await` is implemented in terms of calls to `poll` starts to\nexplain the error message we saw earlier, but that was in terms of `Unpin`, not\n`Pin`. So how exactly does `Pin` relate to `Unpin`, and why does `Future` need\n`self` to be in a `Pin` type to call `poll`?", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "A Closer Look at the Traits for Async", "heading_path": ["A Closer Look at the Traits for Async", "The `Pin` Type and the `Unpin` Trait"], "path": "ch17-05-traits-for-async.md", "url": "https://doc.rust-lang.org/book/ch17-05-traits-for-async.html#the-pin-type-and-the-unpin-trait", "has_code": false, "code_tags": []}} {"id": "book/ch17-05-traits-for-async.md#the-pin-type-and-the-unpin-trait-8", "text": "The Rust Programming Language › A Closer Look at the Traits for Async › The `Pin` Type and the `Unpin` Trait\n\nRemember from earlier in this chapter that a series of await points in a future\nget compiled into a state machine, and the compiler makes sure that state\nmachine follows all of Rust’s normal rules around safety, including borrowing\nand ownership. To make that work, Rust looks at what data is needed between one\nawait point and either the next await point or the end of the async block. It\nthen creates a corresponding variant in the compiled state machine. Each\nvariant gets the access it needs to the data that will be used in that section\nof the source code, whether by taking ownership of that data or by getting a\nmutable or immutable reference to it.\nSo far, so good: if we get anything wrong about the ownership or references in\na given async block, the borrow checker will tell us. When we want to move\naround the future that corresponds to that block—like moving it into a `Vec` to\npass to `join_all`—things get trickier.\nWhen we move a future—whether by pushing it into a data structure to use as an\niterator with `join_all` or by returning it from a function—that actually means\nmoving the state machine Rust creates for us. And unlike most other types in\nRust, the futures Rust creates for async blocks can end up with references to\nthemselves in the fields of any given variant, as shown in the simplified illustration in Figure 17-4.\n<figure>\n<img alt=\"A single-column, three-row table representing a future, fut1, which has data values 0 and 1 in the first two rows and an arrow pointing from the third row back to the second row, representing an internal reference within the future.\" src=\"img/trpl17-04.svg\" class=\"center\" />\n<figcaption>Figure 17-4: A self-referential data type</figcaption>\n</figure>", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "A Closer Look at the Traits for Async", "heading_path": ["A Closer Look at the Traits for Async", "The `Pin` Type and the `Unpin` Trait"], "path": "ch17-05-traits-for-async.md", "url": "https://doc.rust-lang.org/book/ch17-05-traits-for-async.html#the-pin-type-and-the-unpin-trait", "has_code": false, "code_tags": []}} {"id": "book/ch17-05-traits-for-async.md#the-pin-type-and-the-unpin-trait-9", "text": "The Rust Programming Language › A Closer Look at the Traits for Async › The `Pin` Type and the `Unpin` Trait\n\nBy default, though, any object that has a reference to itself is unsafe to move,\nbecause references always point to the actual memory address of whatever they\nrefer to (see Figure 17-5). If you move the data structure itself, those\ninternal references will be left pointing to the old location. However, that\nmemory location is now invalid. For one thing, its value will not be updated\nwhen you make changes to the data structure. For another—more important—thing,\nthe computer is now free to reuse that memory for other purposes! You could end\nup reading completely unrelated data later.\n<figure>\n<img alt=\"Two tables, depicting two futures, fut1 and fut2, each of which has one column and three rows, representing the result of having moved a future out of fut1 into fut2. The first, fut1, is grayed out, with a question mark in each index, representing unknown memory. The second, fut2, has 0 and 1 in the first and second rows and an arrow pointing from its third row back to the second row of fut1, representing a pointer that is referencing the old location in memory of the future before it was moved.\" src=\"img/trpl17-05.svg\" class=\"center\" />\n<figcaption>Figure 17-5: The unsafe result of moving a self-referential data type</figcaption>\n</figure>\nTheoretically, the Rust compiler could try to update every reference to an\nobject whenever it gets moved, but that could add a lot of performance overhead,\nespecially if a whole web of references needs updating. If we could instead make\nsure the data structure in question _doesn’t move in memory_, we wouldn’t have\nto update any references. This is exactly what Rust’s borrow checker is for:\nin safe code, it prevents you from moving any item with an active reference to\nit.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "A Closer Look at the Traits for Async", "heading_path": ["A Closer Look at the Traits for Async", "The `Pin` Type and the `Unpin` Trait"], "path": "ch17-05-traits-for-async.md", "url": "https://doc.rust-lang.org/book/ch17-05-traits-for-async.html#the-pin-type-and-the-unpin-trait", "has_code": false, "code_tags": []}} {"id": "book/ch17-05-traits-for-async.md#the-pin-type-and-the-unpin-trait-10", "text": "The Rust Programming Language › A Closer Look at the Traits for Async › The `Pin` Type and the `Unpin` Trait\n\n`Pin` builds on that to give us the exact guarantee we need. When we _pin_ a\nvalue by wrapping a pointer to that value in `Pin`, it can no longer move. Thus,\nif you have `Pin<Box<SomeType>>`, you actually pin the `SomeType` value, _not_\nthe `Box` pointer. Figure 17-6 illustrates this process.\n<figure>\n<img alt=\"Three boxes laid out side by side. The first is labeled “Pin”, the second “b1”, and the third “pinned”. Within “pinned” is a table labeled “fut”, with a single column; it represents a future with cells for each part of the data structure. Its first cell has the value “0”, its second cell has an arrow coming out of it and pointing to the fourth and final cell, which has the value “1” in it, and the third cell has dashed lines and an ellipsis to indicate there may be other parts to the data structure. All together, the “fut” table represents a future which is self-referential. An arrow leaves the box labeled “Pin”, goes through the box labeled “b1” and terminates inside the “pinned” box at the “fut” table.\" src=\"img/trpl17-06.svg\" class=\"center\" />\n<figcaption>Figure 17-6: Pinning a `Box` that points to a self-referential future type</figcaption>\n</figure>", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "A Closer Look at the Traits for Async", "heading_path": ["A Closer Look at the Traits for Async", "The `Pin` Type and the `Unpin` Trait"], "path": "ch17-05-traits-for-async.md", "url": "https://doc.rust-lang.org/book/ch17-05-traits-for-async.html#the-pin-type-and-the-unpin-trait", "has_code": false, "code_tags": []}} {"id": "book/ch17-05-traits-for-async.md#the-pin-type-and-the-unpin-trait-11", "text": "The Rust Programming Language › A Closer Look at the Traits for Async › The `Pin` Type and the `Unpin` Trait\n\nIn fact, the `Box` pointer can still move around freely. Remember: we care about\nmaking sure the data ultimately being referenced stays in place. If a pointer\nmoves around, _but the data it points to_ is in the same place, as in Figure\n17-7, there’s no potential problem. (As an independent exercise, look at the docs\nfor the types as well as the `std::pin` module and try to work out how you’d do\nthis with a `Pin` wrapping a `Box`.) The key is that the self-referential type\nitself cannot move, because it is still pinned.\n<figure>\n<img alt=\"Four boxes laid out in three rough columns, identical to the previous diagram with a change to the second column. Now there are two boxes in the second column, labeled “b1” and “b2”, “b1” is grayed out, and the arrow from “Pin” goes through “b2” instead of “b1”, indicating that the pointer has moved from “b1” to “b2”, but the data in “pinned” has not moved.\" src=\"img/trpl17-07.svg\" class=\"center\" />\n<figcaption>Figure 17-7: Moving a `Box` which points to a self-referential future type</figcaption>\n</figure>", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "A Closer Look at the Traits for Async", "heading_path": ["A Closer Look at the Traits for Async", "The `Pin` Type and the `Unpin` Trait"], "path": "ch17-05-traits-for-async.md", "url": "https://doc.rust-lang.org/book/ch17-05-traits-for-async.html#the-pin-type-and-the-unpin-trait", "has_code": false, "code_tags": []}} {"id": "book/ch17-05-traits-for-async.md#the-pin-type-and-the-unpin-trait-12", "text": "The Rust Programming Language › A Closer Look at the Traits for Async › The `Pin` Type and the `Unpin` Trait\n\nHowever, most types are perfectly safe to move around, even if they happen to be\nbehind a `Pin` pointer. We only need to think about pinning when items have\ninternal references. Primitive values such as numbers and Booleans are safe\nbecause they obviously don’t have any internal references.\nNeither do most types you normally work with in Rust. You can move around\na `Vec`, for example, without worrying. Given what we have seen so far, if\nyou have a `Pin<Vec<String>>`, you’d have to do everything via the safe but\nrestrictive APIs provided by `Pin`, even though a `Vec<String>` is always safe\nto move if there are no other references to it. We need a way to tell the\ncompiler that it’s fine to move items around in cases like this—and that’s\nwhere `Unpin` comes into play.\n`Unpin` is a marker trait, similar to the `Send` and `Sync` traits we saw in\nChapter 16, and thus has no functionality of its own. Marker traits exist only\nto tell the compiler it’s safe to use the type implementing a given trait in a\nparticular context. `Unpin` informs the compiler that a given type does _not_\nneed to uphold any guarantees about whether the value in question can be safely\nmoved.\nJust as with `Send` and `Sync`, the compiler implements `Unpin` automatically\nfor all types where it can prove it is safe. A special case, again similar to\n`Send` and `Sync`, is where `Unpin` is _not_ implemented for a type. The\nnotation for this is <code>impl !Unpin for <em>SomeType</em></code>, where\n<code><em>SomeType</em></code> is the name of a type that _does_ need to uphold\nthose guarantees to be safe whenever a pointer to that type is used in a `Pin`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "A Closer Look at the Traits for Async", "heading_path": ["A Closer Look at the Traits for Async", "The `Pin` Type and the `Unpin` Trait"], "path": "ch17-05-traits-for-async.md", "url": "https://doc.rust-lang.org/book/ch17-05-traits-for-async.html#the-pin-type-and-the-unpin-trait", "has_code": false, "code_tags": []}} {"id": "book/ch17-05-traits-for-async.md#the-pin-type-and-the-unpin-trait-13", "text": "The Rust Programming Language › A Closer Look at the Traits for Async › The `Pin` Type and the `Unpin` Trait\n\nIn other words, there are two things to keep in mind about the relationship\nbetween `Pin` and `Unpin`. First, `Unpin` is the “normal” case, and `!Unpin` is\nthe special case. Second, whether a type implements `Unpin` or `!Unpin` _only_\nmatters when you’re using a pinned pointer to that type like <code>Pin<&mut\n<em>SomeType</em>></code>.\nTo make that concrete, think about a `String`: it has a length and the Unicode\ncharacters that make it up. We can wrap a `String` in `Pin`, as seen in Figure\n17-8. However, `String` automatically implements `Unpin`, as do most other types\nin Rust.\n<figure>\n<img alt=\"A box labeled “Pin” on the left with an arrow going from it to a box labeled “String” on the right. The “String” box contains the data 5usize, representing the length of the string, and the letters “h”, “e”, “l”, “l”, and “o” representing the characters of the string “hello” stored in this String instance. A dotted rectangle surrounds the “String” box and its label, but not the “Pin” box.\" src=\"img/trpl17-08.svg\" class=\"center\" />\n<figcaption>Figure 17-8: Pinning a `String`; the dotted line indicates that the `String` implements the `Unpin` trait and thus is not pinned</figcaption>\n</figure>", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "A Closer Look at the Traits for Async", "heading_path": ["A Closer Look at the Traits for Async", "The `Pin` Type and the `Unpin` Trait"], "path": "ch17-05-traits-for-async.md", "url": "https://doc.rust-lang.org/book/ch17-05-traits-for-async.html#the-pin-type-and-the-unpin-trait", "has_code": false, "code_tags": []}} {"id": "book/ch17-05-traits-for-async.md#the-pin-type-and-the-unpin-trait-14", "text": "The Rust Programming Language › A Closer Look at the Traits for Async › The `Pin` Type and the `Unpin` Trait\n\nAs a result, we can do things that would be illegal if `String` implemented\n`!Unpin` instead, such as replacing one string with another at the exact same\nlocation in memory as in Figure 17-9. This doesn’t violate the `Pin` contract,\nbecause `String` has no internal references that make it unsafe to move around.\nThat is precisely why it implements `Unpin` rather than `!Unpin`.\n<figure>\n<img alt=\"The same “hello” string data from the previous example, now labeled “s1” and grayed out. The “Pin” box from the previous example now points to a different String instance, one that is labeled “s2”, is valid, has a length of 7usize, and contains the characters of the string “goodbye”. s2 is surrounded by a dotted rectangle because it, too, implements the Unpin trait.\" src=\"img/trpl17-09.svg\" class=\"center\" />\n<figcaption>Figure 17-9: Replacing the `String` with an entirely different `String` in memory</figcaption>\n</figure>\nNow we know enough to understand the errors reported for that `join_all` call\nfrom back in Listing 17-23. We originally tried to move the futures produced by\nasync blocks into a `Vec<Box<dyn Future<Output = ()>>>`, but as we’ve seen,\nthose futures may have internal references, so they don’t automatically\nimplement `Unpin`. Once we pin them, we can pass the resulting `Pin` type into\nthe `Vec`, confident that the underlying data in the futures will _not_ be\nmoved. Listing 17-24 shows how to fix the code by calling the `pin!` macro\nwhere each of the three futures are defined and adjusting the trait object type.\nListing 17-24: Pinning the futures to enable moving them into the vector", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "A Closer Look at the Traits for Async", "heading_path": ["A Closer Look at the Traits for Async", "The `Pin` Type and the `Unpin` Trait"], "path": "ch17-05-traits-for-async.md", "url": "https://doc.rust-lang.org/book/ch17-05-traits-for-async.html#the-pin-type-and-the-unpin-trait", "has_code": false, "code_tags": []}} {"id": "book/ch17-05-traits-for-async.md#the-pin-type-and-the-unpin-trait-15", "text": "The Rust Programming Language › A Closer Look at the Traits for Async › The `Pin` Type and the `Unpin` Trait\n\n```rust\nuse std::pin::{Pin, pin};\n\n// --snip--\n\n let tx1_fut = pin!(async move {\n // --snip--\n });\n\n let rx_fut = pin!(async {\n // --snip--\n });\n\n let tx_fut = pin!(async move {\n // --snip--\n });\n\n let futures: Vec<Pin<&mut dyn Future<Output = ()>>> =\n vec![tx1_fut, rx_fut, tx_fut];\n```\nThis example now compiles and runs, and we could add or remove futures from the\nvector at runtime and join them all.\n`Pin` and `Unpin` are mostly important for building lower-level libraries, or\nwhen you’re building a runtime itself, rather than for day-to-day Rust code.\nWhen you see these traits in error messages, though, now you’ll have a better\nidea of how to fix your code!\nNote: This combination of `Pin` and `Unpin` makes it possible to safely\nimplement a whole class of complex types in Rust that would otherwise prove\nchallenging because they’re self-referential. Types that require `Pin` show up\nmost commonly in async Rust today, but every once in a while, you might see\nthem in other contexts, too.\nThe specifics of how `Pin` and `Unpin` work, and the rules they’re required\nto uphold, are covered extensively in the API documentation for `std::pin`, so\nif you’re interested in learning more, that’s a great place to start.\nIf you want to understand how things work under the hood in even more detail,\nsee Chapters 2 and\n4 of\n_Asynchronous Programming in Rust_.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "A Closer Look at the Traits for Async", "heading_path": ["A Closer Look at the Traits for Async", "The `Pin` Type and the `Unpin` Trait"], "path": "ch17-05-traits-for-async.md", "url": "https://doc.rust-lang.org/book/ch17-05-traits-for-async.html#the-pin-type-and-the-unpin-trait", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch17-05-traits-for-async.md#the-stream-trait-16", "text": "The Rust Programming Language › A Closer Look at the Traits for Async › The `Stream` Trait\n\nNow that you have a deeper grasp on the `Future`, `Pin`, and `Unpin` traits, we\ncan turn our attention to the `Stream` trait. As you learned earlier in the\nchapter, streams are similar to asynchronous iterators. Unlike `Iterator` and\n`Future`, however, `Stream` has no definition in the standard library as of\nthis writing, but there _is_ a very common definition from the `futures` crate\nused throughout the ecosystem.\nLet’s review the definitions of the `Iterator` and `Future` traits before\nlooking at how a `Stream` trait might merge them together. From `Iterator`, we\nhave the idea of a sequence: its `next` method provides an\n`Option<Self::Item>`. From `Future`, we have the idea of readiness over time:\nits `poll` method provides a `Poll<Self::Output>`. To represent a sequence of\nitems that become ready over time, we define a `Stream` trait that puts those\nfeatures together:\n```rust\nuse std::pin::Pin;\nuse std::task::{Context, Poll};\n\ntrait Stream {\n type Item;\n\n fn poll_next(\n self: Pin<&mut Self>,\n cx: &mut Context<'_>\n ) -> Poll<Option<Self::Item>>;\n}\n```\nThe `Stream` trait defines an associated type called `Item` for the type of the\nitems produced by the stream. This is similar to `Iterator`, where there may be\nzero to many items, and unlike `Future`, where there is always a single\n`Output`, even if it’s the unit type `()`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "A Closer Look at the Traits for Async", "heading_path": ["A Closer Look at the Traits for Async", "The `Stream` Trait"], "path": "ch17-05-traits-for-async.md", "url": "https://doc.rust-lang.org/book/ch17-05-traits-for-async.html#the-stream-trait", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch17-05-traits-for-async.md#the-stream-trait-17", "text": "The Rust Programming Language › A Closer Look at the Traits for Async › The `Stream` Trait\n\n`Stream` also defines a method to get those items. We call it `poll_next`, to\nmake it clear that it polls in the same way `Future::poll` does and produces a\nsequence of items in the same way `Iterator::next` does. Its return type\ncombines `Poll` with `Option`. The outer type is `Poll`, because it has to be\nchecked for readiness, just as a future does. The inner type is `Option`,\nbecause it needs to signal whether there are more messages, just as an iterator\ndoes.\nSomething very similar to this definition will likely end up as part of Rust’s\nstandard library. In the meantime, it’s part of the toolkit of most runtimes,\nso you can rely on it, and everything we cover next should generally apply!\nIn the examples we saw in the “Streams: Futures in Sequence”\n section, though, we didn’t use `poll_next` _or_ `Stream`, but\ninstead used `next` and `StreamExt`. We _could_ work directly in terms of the\n`poll_next` API by hand-writing our own `Stream` state machines, of course,\njust as we _could_ work with futures directly via their `poll` method. Using\n`await` is much nicer, though, and the `StreamExt` trait supplies the `next`\nmethod so we can do just that:\n```rust\ntrait StreamExt: Stream {\n async fn next(&mut self) -> Option<Self::Item>\n where\n Self: Unpin;\n\n // other methods...\n}\n```\nNote: The actual definition we used earlier in the chapter looks slightly\ndifferent than this, because it supports versions of Rust that did not yet\nsupport using async functions in traits. As a result, it looks like this:\n```rust,ignore\nfn next(&mut self) -> Next<'_, Self> where Self: Unpin;\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "A Closer Look at the Traits for Async", "heading_path": ["A Closer Look at the Traits for Async", "The `Stream` Trait"], "path": "ch17-05-traits-for-async.md", "url": "https://doc.rust-lang.org/book/ch17-05-traits-for-async.html#the-stream-trait", "has_code": true, "code_tags": ["rust", "rust,ignore"]}} {"id": "book/ch17-05-traits-for-async.md#the-stream-trait-18", "text": "The Rust Programming Language › A Closer Look at the Traits for Async › The `Stream` Trait\n\nThat `Next` type is a `struct` that implements `Future` and allows us to name\nthe lifetime of the reference to `self` with `Next<'_, Self>`, so that `await`\ncan work with this method.\nThe `StreamExt` trait is also the home of all the interesting methods available\nto use with streams. `StreamExt` is automatically implemented for every type\nthat implements `Stream`, but these traits are defined separately to enable the\ncommunity to iterate on convenience APIs without affecting the foundational\ntrait.\nIn the version of `StreamExt` used in the `trpl` crate, the trait not only\ndefines the `next` method but also supplies a default implementation of `next`\nthat correctly handles the details of calling `Stream::poll_next`. This means\nthat even when you need to write your own streaming data type, you _only_ have\nto implement `Stream`, and then anyone who uses your data type can use\n`StreamExt` and its methods with it automatically.\nThat’s all we’re going to cover for the lower-level details on these traits. To\nwrap up, let’s consider how futures (including streams), tasks, and threads all\nfit together!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "A Closer Look at the Traits for Async", "heading_path": ["A Closer Look at the Traits for Async", "The `Stream` Trait"], "path": "ch17-05-traits-for-async.md", "url": "https://doc.rust-lang.org/book/ch17-05-traits-for-async.html#the-stream-trait", "has_code": false, "code_tags": []}} {"id": "book/ch17-06-futures-tasks-threads.md#putting-it-all-together-futures-tasks-and-threads-0", "text": "The Rust Programming Language › Putting It All Together: Futures, Tasks, and Threads\n\nAs we saw in Chapter 16, threads provide one approach to\nconcurrency. We’ve seen another approach in this chapter: using async with\nfutures and streams. If you’re wondering when to choose one method over the other,\nthe answer is: it depends! And in many cases, the choice isn’t threads _or_\nasync but rather threads _and_ async.\nMany operating systems have supplied threading-based concurrency models for\ndecades now, and many programming languages support them as a result. However,\nthese models are not without their tradeoffs. On many operating systems, they\nuse a fair bit of memory for each thread. Threads are also only an option when\nyour operating system and hardware support them. Unlike mainstream desktop and\nmobile computers, some embedded systems don’t have an OS at all, so they also\ndon’t have threads.\nThe async model provides a different—and ultimately complementary—set of\ntradeoffs. In the async model, concurrent operations don’t require their own\nthreads. Instead, they can run on tasks, as when we used `trpl::spawn_task` to\nkick off work from a synchronous function in the streams section. A task is\nsimilar to a thread, but instead of being managed by the operating system, it’s\nmanaged by library-level code: the runtime.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Futures, Tasks, and Threads", "heading_path": ["Putting It All Together: Futures, Tasks, and Threads"], "path": "ch17-06-futures-tasks-threads.md", "url": "https://doc.rust-lang.org/book/ch17-06-futures-tasks-threads.html#putting-it-all-together-futures-tasks-and-threads", "has_code": false, "code_tags": []}} {"id": "book/ch17-06-futures-tasks-threads.md#putting-it-all-together-futures-tasks-and-threads-1", "text": "The Rust Programming Language › Putting It All Together: Futures, Tasks, and Threads\n\nThere’s a reason the APIs for spawning threads and spawning tasks are so\nsimilar. Threads act as a boundary for sets of synchronous operations;\nconcurrency is possible _between_ threads. Tasks act as a boundary for sets of\n_asynchronous_ operations; concurrency is possible both _between_ and _within_\ntasks, because a task can switch between futures in its body. Finally, futures\nare Rust’s most granular unit of concurrency, and each future may represent a\ntree of other futures. The runtime—specifically, its executor—manages tasks,\nand tasks manage futures. In that regard, tasks are similar to lightweight,\nruntime-managed threads with added capabilities that come from being managed by\na runtime instead of by the operating system.\nThis doesn’t mean that async tasks are always better than threads (or vice\nversa). Concurrency with threads is in some ways a simpler programming model\nthan concurrency with `async`. That can be a strength or a weakness. Threads are\nsomewhat “fire and forget”; they have no native equivalent to a future, so they\nsimply run to completion without being interrupted except by the operating\nsystem itself.\nAnd it turns out that threads and tasks often work\nvery well together, because tasks can (at least in some runtimes) be moved\naround between threads. In fact, under the hood, the runtime we’ve been\nusing—including the `spawn_blocking` and `spawn_task` functions—is multithreaded\nby default! Many runtimes use an approach called _work stealing_ to\ntransparently move tasks around between threads, based on how the threads are\ncurrently being utilized, to improve the system’s overall performance. That\napproach actually requires threads _and_ tasks, and therefore futures.\nWhen thinking about which method to use when, consider these rules of thumb:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Futures, Tasks, and Threads", "heading_path": ["Putting It All Together: Futures, Tasks, and Threads"], "path": "ch17-06-futures-tasks-threads.md", "url": "https://doc.rust-lang.org/book/ch17-06-futures-tasks-threads.html#putting-it-all-together-futures-tasks-and-threads", "has_code": false, "code_tags": []}} {"id": "book/ch17-06-futures-tasks-threads.md#putting-it-all-together-futures-tasks-and-threads-2", "text": "The Rust Programming Language › Putting It All Together: Futures, Tasks, and Threads\n\n- If the work is _very parallelizable_ (that is, CPU-bound), such as processing\n a bunch of data where each part can be processed separately, threads are a\n better choice.\n- If the work is _very concurrent_ (that is, I/O-bound), such as handling\n messages from a bunch of different sources that may come in at different\n intervals or different rates, async is a better choice.\nAnd if you need both parallelism and concurrency, you don’t have to choose\nbetween threads and async. You can use them together freely, letting each\nplay the part it’s best at. For example, Listing 17-25 shows a fairly common\nexample of this kind of mix in real-world Rust code.\nListing 17-25: Sending messages with blocking code in a thread and awaiting the messages in an async block (src/main.rs)\n```rust\nuse std::{thread, time::Duration};\n\nfn main() {\n let (tx, mut rx) = trpl::channel();\n\n thread::spawn(move || {\n for i in 1..11 {\n tx.send(i).unwrap();\n thread::sleep(Duration::from_secs(1));\n }\n });\n\n trpl::block_on(async {\n while let Some(message) = rx.recv().await {\n println!(\"{message}\");\n }\n });\n}\n```\nWe begin by creating an async channel, then spawning a thread that takes\nownership of the sender side of the channel using the `move` keyword. Within\nthe thread, we send the numbers 1 through 10, sleeping for a second between\neach. Finally, we run a future created with an async block passed to\n`trpl::block_on` just as we have throughout the chapter. In that future, we\nawait those messages, just as in the other message-passing examples we have\nseen.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Futures, Tasks, and Threads", "heading_path": ["Putting It All Together: Futures, Tasks, and Threads"], "path": "ch17-06-futures-tasks-threads.md", "url": "https://doc.rust-lang.org/book/ch17-06-futures-tasks-threads.html#putting-it-all-together-futures-tasks-and-threads", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch17-06-futures-tasks-threads.md#putting-it-all-together-futures-tasks-and-threads-3", "text": "The Rust Programming Language › Putting It All Together: Futures, Tasks, and Threads\n\nTo return to the scenario we opened the chapter with, imagine running a set of\nvideo encoding tasks using a dedicated thread (because video encoding is\ncompute-bound) but notifying the UI that those operations are done with an\nasync channel. There are countless examples of these kinds of combinations in\nreal-world use cases.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Futures, Tasks, and Threads", "heading_path": ["Putting It All Together: Futures, Tasks, and Threads"], "path": "ch17-06-futures-tasks-threads.md", "url": "https://doc.rust-lang.org/book/ch17-06-futures-tasks-threads.html#putting-it-all-together-futures-tasks-and-threads", "has_code": false, "code_tags": []}} {"id": "book/ch17-06-futures-tasks-threads.md#summary-4", "text": "The Rust Programming Language › Summary\n\nThis isn’t the last you’ll see of concurrency in this book. The project in\nChapter 21 will apply these concepts in a more realistic\nsituation than the simpler examples discussed here and compare problem-solving\nwith threading versus tasks and futures more directly.\nNo matter which of these approaches you choose, Rust gives you the tools you\nneed to write safe, fast, concurrent code—whether for a high-throughput web\nserver or an embedded operating system.\nNext, we’ll talk about idiomatic ways to model problems and structure solutions\nas your Rust programs get bigger. In addition, we’ll discuss how Rust’s idioms\nrelate to those you might be familiar with from object-oriented programming.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Futures, Tasks, and Threads", "heading_path": ["Summary"], "path": "ch17-06-futures-tasks-threads.md", "url": "https://doc.rust-lang.org/book/ch17-06-futures-tasks-threads.html#summary", "has_code": false, "code_tags": []}} {"id": "book/ch18-00-oop.md#object-oriented-programming-features-0", "text": "The Rust Programming Language › Object-Oriented Programming Features\n\nObject-oriented programming (OOP) is a way of modeling programs. Objects as a\nprogrammatic concept were introduced in the programming language Simula in the\n1960s. Those objects influenced Alan Kay’s programming architecture in which\nobjects pass messages to each other. To describe this architecture, he coined\nthe term _object-oriented programming_ in 1967. Many competing definitions\ndescribe what OOP is, and by some of these definitions Rust is object oriented\nbut by others it is not. In this chapter, we’ll explore certain characteristics\nthat are commonly considered object oriented and how those characteristics\ntranslate to idiomatic Rust. We’ll then show you how to implement an\nobject-oriented design pattern in Rust and discuss the trade-offs of doing so\nversus implementing a solution using some of Rust’s strengths instead.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Object Oriented Programming Features", "heading_path": ["Object-Oriented Programming Features"], "path": "ch18-00-oop.md", "url": "https://doc.rust-lang.org/book/ch18-00-oop.html#object-oriented-programming-features", "has_code": false, "code_tags": []}} {"id": "book/ch18-01-what-is-oo.md#characteristics-of-object-oriented-languages-0", "text": "The Rust Programming Language › Characteristics of Object-Oriented Languages\n\nThere is no consensus in the programming community about what features a\nlanguage must have to be considered object oriented. Rust is influenced by many\nprogramming paradigms, including OOP; for example, we explored the features\nthat came from functional programming in Chapter 13. Arguably, OOP languages\nshare certain common characteristics—namely, objects, encapsulation, and\ninheritance. Let’s look at what each of those characteristics means and whether\nRust supports it.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Characteristics of Object-Oriented Languages", "heading_path": ["Characteristics of Object-Oriented Languages"], "path": "ch18-01-what-is-oo.md", "url": "https://doc.rust-lang.org/book/ch18-01-what-is-oo.html#characteristics-of-object-oriented-languages", "has_code": false, "code_tags": []}} {"id": "book/ch18-01-what-is-oo.md#objects-contain-data-and-behavior-1", "text": "The Rust Programming Language › Characteristics of Object-Oriented Languages › Objects Contain Data and Behavior\n\nThe book _Design Patterns: Elements of Reusable Object-Oriented Software_ by\nErich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (Addison-Wesley,\n1994), colloquially referred to as _The Gang of Four_ book, is a catalog of\nobject-oriented design patterns. It defines OOP in this way:\nObject-oriented programs are made up of objects. An **object** packages both\ndata and the procedures that operate on that data. The procedures are\ntypically called **methods** or **operations**.\nUsing this definition, Rust is object oriented: Structs and enums have data,\nand `impl` blocks provide methods on structs and enums. Even though structs and\nenums with methods aren’t _called_ objects, they provide the same\nfunctionality, according to the Gang of Four’s definition of objects.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Characteristics of Object-Oriented Languages", "heading_path": ["Characteristics of Object-Oriented Languages", "Objects Contain Data and Behavior"], "path": "ch18-01-what-is-oo.md", "url": "https://doc.rust-lang.org/book/ch18-01-what-is-oo.html#objects-contain-data-and-behavior", "has_code": false, "code_tags": []}} {"id": "book/ch18-01-what-is-oo.md#encapsulation-that-hides-implementation-details-2", "text": "The Rust Programming Language › Characteristics of Object-Oriented Languages › Encapsulation That Hides Implementation Details\n\nAnother aspect commonly associated with OOP is the idea of _encapsulation_,\nwhich means that the implementation details of an object aren’t accessible to\ncode using that object. Therefore, the only way to interact with an object is\nthrough its public API; code using the object shouldn’t be able to reach into\nthe object’s internals and change data or behavior directly. This enables the\nprogrammer to change and refactor an object’s internals without needing to\nchange the code that uses the object.\nWe discussed how to control encapsulation in Chapter 7: We can use the `pub`\nkeyword to decide which modules, types, functions, and methods in our code\nshould be public, and by default everything else is private. For example, we\ncan define a struct `AveragedCollection` that has a field containing a vector\nof `i32` values. The struct can also have a field that contains the average of\nthe values in the vector, meaning the average doesn’t have to be computed on\ndemand whenever anyone needs it. In other words, `AveragedCollection` will\ncache the calculated average for us. Listing 18-1 has the definition of the\n`AveragedCollection` struct.\nListing 18-1: An `AveragedCollection` struct that maintains a list of integers and the average of the items in the collection (src/lib.rs)\n```rust,noplayground\npub struct AveragedCollection {\n list: Vec<i32>,\n average: f64,\n}\n```\nThe struct is marked `pub` so that other code can use it, but the fields within\nthe struct remain private. This is important in this case because we want to\nensure that whenever a value is added or removed from the list, the average is\nalso updated. We do this by implementing `add`, `remove`, and `average` methods\non the struct, as shown in Listing 18-2.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Characteristics of Object-Oriented Languages", "heading_path": ["Characteristics of Object-Oriented Languages", "Encapsulation That Hides Implementation Details"], "path": "ch18-01-what-is-oo.md", "url": "https://doc.rust-lang.org/book/ch18-01-what-is-oo.html#encapsulation-that-hides-implementation-details", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch18-01-what-is-oo.md#encapsulation-that-hides-implementation-details-3", "text": "The Rust Programming Language › Characteristics of Object-Oriented Languages › Encapsulation That Hides Implementation Details\n\nListing 18-2: Implementations of the public methods `add`, `remove`, and `average` on `AveragedCollection` (src/lib.rs)\n```rust,noplayground\nimpl AveragedCollection {\n pub fn add(&mut self, value: i32) {\n self.list.push(value);\n self.update_average();\n }\n\n pub fn remove(&mut self) -> Option<i32> {\n let result = self.list.pop();\n match result {\n Some(value) => {\n self.update_average();\n Some(value)\n }\n None => None,\n }\n }\n\n pub fn average(&self) -> f64 {\n self.average\n }\n\n fn update_average(&mut self) {\n let total: i32 = self.list.iter().sum();\n self.average = total as f64 / self.list.len() as f64;\n }\n}\n```\nThe public methods `add`, `remove`, and `average` are the only ways to access\nor modify data in an instance of `AveragedCollection`. When an item is added to\n`list` using the `add` method or removed using the `remove` method, the\nimplementations of each call the private `update_average` method that handles\nupdating the `average` field as well.\nWe leave the `list` and `average` fields private so that there is no way for\nexternal code to add or remove items to or from the `list` field directly;\notherwise, the `average` field might become out of sync when the `list`\nchanges. The `average` method returns the value in the `average` field,\nallowing external code to read the `average` but not modify it.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Characteristics of Object-Oriented Languages", "heading_path": ["Characteristics of Object-Oriented Languages", "Encapsulation That Hides Implementation Details"], "path": "ch18-01-what-is-oo.md", "url": "https://doc.rust-lang.org/book/ch18-01-what-is-oo.html#encapsulation-that-hides-implementation-details", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch18-01-what-is-oo.md#encapsulation-that-hides-implementation-details-4", "text": "The Rust Programming Language › Characteristics of Object-Oriented Languages › Encapsulation That Hides Implementation Details\n\nBecause we’ve encapsulated the implementation details of the struct\n`AveragedCollection`, we can easily change aspects, such as the data structure,\nin the future. For instance, we could use a `HashSet<i32>` instead of a\n`Vec<i32>` for the `list` field. As long as the signatures of the `add`,\n`remove`, and `average` public methods stayed the same, code using\n`AveragedCollection` wouldn’t need to change. If we made `list` public instead,\nthis wouldn’t necessarily be the case: `HashSet<i32>` and `Vec<i32>` have\ndifferent methods for adding and removing items, so the external code would\nlikely have to change if it were modifying `list` directly.\nIf encapsulation is a required aspect for a language to be considered object\noriented, then Rust meets that requirement. The option to use `pub` or not for\ndifferent parts of code enables encapsulation of implementation details.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Characteristics of Object-Oriented Languages", "heading_path": ["Characteristics of Object-Oriented Languages", "Encapsulation That Hides Implementation Details"], "path": "ch18-01-what-is-oo.md", "url": "https://doc.rust-lang.org/book/ch18-01-what-is-oo.html#encapsulation-that-hides-implementation-details", "has_code": false, "code_tags": []}} {"id": "book/ch18-01-what-is-oo.md#inheritance-as-a-type-system-and-as-code-sharing-5", "text": "The Rust Programming Language › Characteristics of Object-Oriented Languages › Inheritance as a Type System and as Code Sharing\n\n_Inheritance_ is a mechanism whereby an object can inherit elements from\nanother object’s definition, thus gaining the parent object’s data and behavior\nwithout you having to define them again.\nIf a language must have inheritance to be object oriented, then Rust is not\nsuch a language. There is no way to define a struct that inherits the parent\nstruct’s fields and method implementations without using a macro.\nHowever, if you’re used to having inheritance in your programming toolbox, you\ncan use other solutions in Rust, depending on your reason for reaching for\ninheritance in the first place.\nYou would choose inheritance for two main reasons. One is for reuse of code:\nYou can implement particular behavior for one type, and inheritance enables you\nto reuse that implementation for a different type. You can do this in a limited\nway in Rust code using default trait method implementations, which you saw in\nListing 10-14 when we added a default implementation of the `summarize` method\non the `Summary` trait. Any type implementing the `Summary` trait would have\nthe `summarize` method available on it without any further code. This is\nsimilar to a parent class having an implementation of a method and an\ninheriting child class also having the implementation of the method. We can\nalso override the default implementation of the `summarize` method when we\nimplement the `Summary` trait, which is similar to a child class overriding the\nimplementation of a method inherited from a parent class.\nThe other reason to use inheritance relates to the type system: to enable a\nchild type to be used in the same places as the parent type. This is also\ncalled _polymorphism_, which means that you can substitute multiple objects for\neach other at runtime if they share certain characteristics.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Characteristics of Object-Oriented Languages", "heading_path": ["Characteristics of Object-Oriented Languages", "Inheritance as a Type System and as Code Sharing"], "path": "ch18-01-what-is-oo.md", "url": "https://doc.rust-lang.org/book/ch18-01-what-is-oo.html#inheritance-as-a-type-system-and-as-code-sharing", "has_code": false, "code_tags": []}} {"id": "book/ch18-01-what-is-oo.md#polymorphism-6", "text": "The Rust Programming Language › Characteristics of Object-Oriented Languages › Polymorphism\n\nTo many people, polymorphism is synonymous with inheritance. But it’s\nactually a more general concept that refers to code that can work with data of\nmultiple types. For inheritance, those types are generally subclasses.\nRust instead uses generics to abstract over different possible types and\ntrait bounds to impose constraints on what those types must provide. This is\nsometimes called _bounded parametric polymorphism_.\nRust has chosen a different set of trade-offs by not offering inheritance.\nInheritance is often at risk of sharing more code than necessary. Subclasses\nshouldn’t always share all characteristics of their parent class but will do so\nwith inheritance. This can make a program’s design less flexible. It also\nintroduces the possibility of calling methods on subclasses that don’t make\nsense or that cause errors because the methods don’t apply to the subclass. In\naddition, some languages will only allow _single inheritance_ (meaning a\nsubclass can only inherit from one class), further restricting the flexibility\nof a program’s design.\nFor these reasons, Rust takes the different approach of using trait objects\ninstead of inheritance to achieve polymorphism at runtime. Let’s look at how\ntrait objects work.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Characteristics of Object-Oriented Languages", "heading_path": ["Characteristics of Object-Oriented Languages", "Polymorphism"], "path": "ch18-01-what-is-oo.md", "url": "https://doc.rust-lang.org/book/ch18-01-what-is-oo.html#polymorphism", "has_code": false, "code_tags": []}} {"id": "book/ch18-02-trait-objects.md#using-trait-objects-to-abstract-over-shared-behavior-0", "text": "The Rust Programming Language › Using Trait Objects to Abstract over Shared Behavior\n\nIn Chapter 8, we mentioned that one limitation of vectors is that they can\nstore elements of only one type. We created a workaround in Listing 8-9 where\nwe defined a `SpreadsheetCell` enum that had variants to hold integers, floats,\nand text. This meant we could store different types of data in each cell and\nstill have a vector that represented a row of cells. This is a perfectly good\nsolution when our interchangeable items are a fixed set of types that we know\nwhen our code is compiled.\nHowever, sometimes we want our library user to be able to extend the set of\ntypes that are valid in a particular situation. To show how we might achieve\nthis, we’ll create an example graphical user interface (GUI) tool that iterates\nthrough a list of items, calling a `draw` method on each one to draw it to the\nscreen—a common technique for GUI tools. We’ll create a library crate called\n`gui` that contains the structure of a GUI library. This crate might include\nsome types for people to use, such as `Button` or `TextField`. In addition,\n`gui` users will want to create their own types that can be drawn: For\ninstance, one programmer might add an `Image`, and another might add a\n`SelectBox`.\nAt the time of writing the library, we can’t know and define all the types\nother programmers might want to create. But we do know that `gui` needs to keep\ntrack of many values of different types, and it needs to call a `draw` method\non each of these differently typed values. It doesn’t need to know exactly what\nwill happen when we call the `draw` method, just that the value will have that\nmethod available for us to call.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using Trait Objects to Abstract over Shared Behavior", "heading_path": ["Using Trait Objects to Abstract over Shared Behavior"], "path": "ch18-02-trait-objects.md", "url": "https://doc.rust-lang.org/book/ch18-02-trait-objects.html#using-trait-objects-to-abstract-over-shared-behavior", "has_code": false, "code_tags": []}} {"id": "book/ch18-02-trait-objects.md#using-trait-objects-to-abstract-over-shared-behavior-1", "text": "The Rust Programming Language › Using Trait Objects to Abstract over Shared Behavior\n\nTo do this in a language with inheritance, we might define a class named\n`Component` that has a method named `draw` on it. The other classes, such as\n`Button`, `Image`, and `SelectBox`, would inherit from `Component` and thus\ninherit the `draw` method. They could each override the `draw` method to define\ntheir custom behavior, but the framework could treat all of the types as if\nthey were `Component` instances and call `draw` on them. But because Rust\ndoesn’t have inheritance, we need another way to structure the `gui` library to\nallow users to create new types compatible with the library.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using Trait Objects to Abstract over Shared Behavior", "heading_path": ["Using Trait Objects to Abstract over Shared Behavior"], "path": "ch18-02-trait-objects.md", "url": "https://doc.rust-lang.org/book/ch18-02-trait-objects.html#using-trait-objects-to-abstract-over-shared-behavior", "has_code": false, "code_tags": []}} {"id": "book/ch18-02-trait-objects.md#defining-a-trait-for-common-behavior-2", "text": "The Rust Programming Language › Using Trait Objects to Abstract over Shared Behavior › Defining a Trait for Common Behavior\n\nTo implement the behavior that we want `gui` to have, we’ll define a trait\nnamed `Draw` that will have one method named `draw`. Then, we can define a\nvector that takes a trait object. A _trait object_ points to both an instance\nof a type implementing our specified trait and a table used to look up trait\nmethods on that type at runtime. We create a trait object by specifying some\nsort of pointer, such as a reference or a `Box<T>` smart pointer, then the\n`dyn` keyword, and then specifying the relevant trait. (We’ll talk about the\nreason trait objects must use a pointer in “Dynamically Sized Types and the\n`Sized` Trait” in Chapter 20.) We can use\ntrait objects in place of a generic or concrete type. Wherever we use a trait\nobject, Rust’s type system will ensure at compile time that any value used in\nthat context will implement the trait object’s trait. Consequently, we don’t\nneed to know all the possible types at compile time.\nWe’ve mentioned that, in Rust, we refrain from calling structs and enums\n“objects” to distinguish them from other languages’ objects. In a struct or\nenum, the data in the struct fields and the behavior in `impl` blocks are\nseparated, whereas in other languages, the data and behavior combined into one\nconcept is often labeled an object. Trait objects differ from objects in other\nlanguages in that we can’t add data to a trait object. Trait objects aren’t as\ngenerally useful as objects in other languages: Their specific purpose is to\nallow abstraction across common behavior.\nListing 18-3 shows how to define a trait named `Draw` with one method named\n`draw`.\nListing 18-3: Definition of the `Draw` trait (src/lib.rs)\n```rust,noplayground\npub trait Draw {\n fn draw(&self);\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using Trait Objects to Abstract over Shared Behavior", "heading_path": ["Using Trait Objects to Abstract over Shared Behavior", "Defining a Trait for Common Behavior"], "path": "ch18-02-trait-objects.md", "url": "https://doc.rust-lang.org/book/ch18-02-trait-objects.html#defining-a-trait-for-common-behavior", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch18-02-trait-objects.md#defining-a-trait-for-common-behavior-3", "text": "The Rust Programming Language › Using Trait Objects to Abstract over Shared Behavior › Defining a Trait for Common Behavior\n\nThis syntax should look familiar from our discussions on how to define traits\nin Chapter 10. Next comes some new syntax: Listing 18-4 defines a struct named\n`Screen` that holds a vector named `components`. This vector is of type\n`Box<dyn Draw>`, which is a trait object; it’s a stand-in for any type inside a\n`Box` that implements the `Draw` trait.\nListing 18-4: Definition of the `Screen` struct with a `components` field holding a vector of trait objects that implement the `Draw` trait (src/lib.rs)\n```rust,noplayground\npub struct Screen {\n pub components: Vec<Box<dyn Draw>>,\n}\n```\nOn the `Screen` struct, we’ll define a method named `run` that will call the\n`draw` method on each of its `components`, as shown in Listing 18-5.\nListing 18-5: A `run` method on `Screen` that calls the `draw` method on each component (src/lib.rs)\n```rust,noplayground\nimpl Screen {\n pub fn run(&self) {\n for component in self.components.iter() {\n component.draw();\n }\n }\n}\n```\nThis works differently from defining a struct that uses a generic type\nparameter with trait bounds. A generic type parameter can be substituted with\nonly one concrete type at a time, whereas trait objects allow for multiple\nconcrete types to fill in for the trait object at runtime. For example, we\ncould have defined the `Screen` struct using a generic type and a trait bound,\nas in Listing 18-6.\nListing 18-6: An alternate implementation of the `Screen` struct and its `run` method using generics and trait bounds (src/lib.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using Trait Objects to Abstract over Shared Behavior", "heading_path": ["Using Trait Objects to Abstract over Shared Behavior", "Defining a Trait for Common Behavior"], "path": "ch18-02-trait-objects.md", "url": "https://doc.rust-lang.org/book/ch18-02-trait-objects.html#defining-a-trait-for-common-behavior", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch18-02-trait-objects.md#defining-a-trait-for-common-behavior-4", "text": "The Rust Programming Language › Using Trait Objects to Abstract over Shared Behavior › Defining a Trait for Common Behavior\n\n```rust,noplayground\npub struct Screen<T: Draw> {\n pub components: Vec<T>,\n}\n\nimpl<T> Screen<T>\nwhere\n T: Draw,\n{\n pub fn run(&self) {\n for component in self.components.iter() {\n component.draw();\n }\n }\n}\n```\nThis restricts us to a `Screen` instance that has a list of components all of\ntype `Button` or all of type `TextField`. If you’ll only ever have homogeneous\ncollections, using generics and trait bounds is preferable because the\ndefinitions will be monomorphized at compile time to use the concrete types.\nOn the other hand, with the method using trait objects, one `Screen` instance\ncan hold a `Vec<T>` that contains a `Box<Button>` as well as a\n`Box<TextField>`. Let’s look at how this works, and then we’ll talk about the\nruntime performance implications.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using Trait Objects to Abstract over Shared Behavior", "heading_path": ["Using Trait Objects to Abstract over Shared Behavior", "Defining a Trait for Common Behavior"], "path": "ch18-02-trait-objects.md", "url": "https://doc.rust-lang.org/book/ch18-02-trait-objects.html#defining-a-trait-for-common-behavior", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch18-02-trait-objects.md#implementing-the-trait-5", "text": "The Rust Programming Language › Using Trait Objects to Abstract over Shared Behavior › Implementing the Trait\n\nNow we’ll add some types that implement the `Draw` trait. We’ll provide the\n`Button` type. Again, actually implementing a GUI library is beyond the scope\nof this book, so the `draw` method won’t have any useful implementation in its\nbody. To imagine what the implementation might look like, a `Button` struct\nmight have fields for `width`, `height`, and `label`, as shown in Listing 18-7.\nListing 18-7: A `Button` struct that implements the `Draw` trait (src/lib.rs)\n```rust,noplayground\npub struct Button {\n pub width: u32,\n pub height: u32,\n pub label: String,\n}\n\nimpl Draw for Button {\n fn draw(&self) {\n // code to actually draw a button\n }\n}\n```\nThe `width`, `height`, and `label` fields on `Button` will differ from the\nfields on other components; for example, a `TextField` type might have those\nsame fields plus a `placeholder` field. Each of the types we want to draw on\nthe screen will implement the `Draw` trait but will use different code in the\n`draw` method to define how to draw that particular type, as `Button` has here\n(without the actual GUI code, as mentioned). The `Button` type, for instance,\nmight have an additional `impl` block containing methods related to what\nhappens when a user clicks the button. These kinds of methods won’t apply to\ntypes like `TextField`.\nIf someone using our library decides to implement a `SelectBox` struct that has\n`width`, `height`, and `options` fields, they would implement the `Draw` trait\non the `SelectBox` type as well, as shown in Listing 18-8.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using Trait Objects to Abstract over Shared Behavior", "heading_path": ["Using Trait Objects to Abstract over Shared Behavior", "Implementing the Trait"], "path": "ch18-02-trait-objects.md", "url": "https://doc.rust-lang.org/book/ch18-02-trait-objects.html#implementing-the-trait", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch18-02-trait-objects.md#implementing-the-trait-6", "text": "The Rust Programming Language › Using Trait Objects to Abstract over Shared Behavior › Implementing the Trait\n\nListing 18-8: Another crate using `gui` and implementing the `Draw` trait on a `SelectBox` struct (src/main.rs)\n```rust,ignore\nuse gui::Draw;\n\nstruct SelectBox {\n width: u32,\n height: u32,\n options: Vec<String>,\n}\n\nimpl Draw for SelectBox {\n fn draw(&self) {\n // code to actually draw a select box\n }\n}\n```\nOur library’s user can now write their `main` function to create a `Screen`\ninstance. To the `Screen` instance, they can add a `SelectBox` and a `Button`\nby putting each in a `Box<T>` to become a trait object. They can then call the\n`run` method on the `Screen` instance, which will call `draw` on each of the\ncomponents. Listing 18-9 shows this implementation.\nListing 18-9: Using trait objects to store values of different types that implement the same trait (src/main.rs)\n```rust,ignore\nuse gui::{Button, Screen};\n\nfn main() {\n let screen = Screen {\n components: vec![\n Box::new(SelectBox {\n width: 75,\n height: 10,\n options: vec![\n String::from(\"Yes\"),\n String::from(\"Maybe\"),\n String::from(\"No\"),\n ],\n }),\n Box::new(Button {\n width: 50,\n height: 10,\n label: String::from(\"OK\"),\n }),\n ],\n };\n\n screen.run();\n}\n```\nWhen we wrote the library, we didn’t know that someone might add the\n`SelectBox` type, but our `Screen` implementation was able to operate on the\nnew type and draw it because `SelectBox` implements the `Draw` trait, which\nmeans it implements the `draw` method.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using Trait Objects to Abstract over Shared Behavior", "heading_path": ["Using Trait Objects to Abstract over Shared Behavior", "Implementing the Trait"], "path": "ch18-02-trait-objects.md", "url": "https://doc.rust-lang.org/book/ch18-02-trait-objects.html#implementing-the-trait", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch18-02-trait-objects.md#implementing-the-trait-7", "text": "The Rust Programming Language › Using Trait Objects to Abstract over Shared Behavior › Implementing the Trait\n\nThis concept—of being concerned only with the messages a value responds to\nrather than the value’s concrete type—is similar to the concept of _duck\ntyping_ in dynamically typed languages: If it walks like a duck and quacks like\na duck, then it must be a duck! In the implementation of `run` on `Screen` in\nListing 18-5, `run` doesn’t need to know what the concrete type of each\ncomponent is. It doesn’t check whether a component is an instance of a `Button`\nor a `SelectBox`, it just calls the `draw` method on the component. By\nspecifying `Box<dyn Draw>` as the type of the values in the `components`\nvector, we’ve defined `Screen` to need values that we can call the `draw`\nmethod on.\nThe advantage of using trait objects and Rust’s type system to write code\nsimilar to code using duck typing is that we never have to check whether a\nvalue implements a particular method at runtime or worry about getting errors\nif a value doesn’t implement a method but we call it anyway. Rust won’t compile\nour code if the values don’t implement the traits that the trait objects need.\nFor example, Listing 18-10 shows what happens if we try to create a `Screen`\nwith a `String` as a component.\nListing 18-10: Attempting to use a type that doesn’t implement the trait object’s trait (src/main.rs)\n```rust,ignore,does_not_compile\nuse gui::Screen;\n\nfn main() {\n let screen = Screen {\n components: vec![Box::new(String::from(\"Hi\"))],\n };\n\n screen.run();\n}\n```\nWe’ll get this error because `String` doesn’t implement the `Draw` trait:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using Trait Objects to Abstract over Shared Behavior", "heading_path": ["Using Trait Objects to Abstract over Shared Behavior", "Implementing the Trait"], "path": "ch18-02-trait-objects.md", "url": "https://doc.rust-lang.org/book/ch18-02-trait-objects.html#implementing-the-trait", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch18-02-trait-objects.md#implementing-the-trait-8", "text": "The Rust Programming Language › Using Trait Objects to Abstract over Shared Behavior › Implementing the Trait\n\n```console\n$ cargo run\n Compiling gui v0.1.0 (file:///projects/gui)\nerror[E0277]: the trait bound `String: Draw` is not satisfied\n --> src/main.rs:5:26\n |\n 5 | components: vec![Box::new(String::from(\"Hi\"))],\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Draw` is not implemented for `String`\n |\nhelp: the trait `Draw` is implemented for `Button`\n --> src/lib.rs:23:1\n |\n23 | impl Draw for Button {\n | ^^^^^^^^^^^^^^^^^^^^\n = note: required for the cast from `Box<String>` to `Box<dyn Draw>`\n\nFor more information about this error, try `rustc --explain E0277`.\nerror: could not compile `gui` (bin \"gui\") due to 1 previous error\n```\nThis error lets us know that either we’re passing something to `Screen` that we\ndidn’t mean to pass and so should pass a different type, or we should implement\n`Draw` on `String` so that `Screen` is able to call `draw` on it.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using Trait Objects to Abstract over Shared Behavior", "heading_path": ["Using Trait Objects to Abstract over Shared Behavior", "Implementing the Trait"], "path": "ch18-02-trait-objects.md", "url": "https://doc.rust-lang.org/book/ch18-02-trait-objects.html#implementing-the-trait", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch18-02-trait-objects.md#performing-dynamic-dispatch-9", "text": "The Rust Programming Language › Using Trait Objects to Abstract over Shared Behavior › Performing Dynamic Dispatch\n\nRecall in “Performance of Code Using\nGenerics” in Chapter 10 our\ndiscussion on the monomorphization process performed on generics by the\ncompiler: The compiler generates nongeneric implementations of functions and\nmethods for each concrete type that we use in place of a generic type\nparameter. The code that results from monomorphization is doing _static\ndispatch_, which is when the compiler knows what method you’re calling at\ncompile time. This is opposed to _dynamic dispatch_, which is when the compiler\ncan’t tell at compile time which method you’re calling. In dynamic dispatch\ncases, the compiler emits code that at runtime will know which method to call.\nWhen we use trait objects, Rust must use dynamic dispatch. The compiler doesn’t\nknow all the types that might be used with the code that’s using trait objects,\nso it doesn’t know which method implemented on which type to call. Instead, at\nruntime, Rust uses the pointers inside the trait object to know which method to\ncall. This lookup incurs a runtime cost that doesn’t occur with static dispatch.\nDynamic dispatch also prevents the compiler from choosing to inline a method’s\ncode, which in turn prevents some optimizations, and Rust has some rules about\nwhere you can and cannot use dynamic dispatch, called _dyn compatibility_. Those\nrules are beyond the scope of this discussion, but you can read more about them\nin the reference. However, we did get extra\nflexibility in the code that we wrote in Listing 18-5 and were able to support\nin Listing 18-9, so it’s a trade-off to consider.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Using Trait Objects to Abstract over Shared Behavior", "heading_path": ["Using Trait Objects to Abstract over Shared Behavior", "Performing Dynamic Dispatch"], "path": "ch18-02-trait-objects.md", "url": "https://doc.rust-lang.org/book/ch18-02-trait-objects.html#performing-dynamic-dispatch", "has_code": false, "code_tags": []}} {"id": "book/ch18-03-oo-design-patterns.md#implementing-an-object-oriented-design-pattern-0", "text": "The Rust Programming Language › Implementing an Object-Oriented Design Pattern\n\nThe _state pattern_ is an object-oriented design pattern. The crux of the\npattern is that we define a set of states a value can have internally. The\nstates are represented by a set of _state objects_, and the value’s behavior\nchanges based on its state. We’re going to work through an example of a blog\npost struct that has a field to hold its state, which will be a state object\nfrom the set “draft,” “review,” or “published.”\nThe state objects share functionality: In Rust, of course, we use structs and\ntraits rather than objects and inheritance. Each state object is responsible\nfor its own behavior and for governing when it should change into another\nstate. The value that holds a state object knows nothing about the different\nbehavior of the states or when to transition between states.\nThe advantage of using the state pattern is that, when the business\nrequirements of the program change, we won’t need to change the code of the\nvalue holding the state or the code that uses the value. We’ll only need to\nupdate the code inside one of the state objects to change its rules or perhaps\nadd more state objects.\nFirst, we’re going to implement the state pattern in a more traditional\nobject-oriented way. Then, we’ll use an approach that’s a bit more natural in\nRust. Let’s dig in to incrementally implement a blog post workflow using the\nstate pattern.\nThe final functionality will look like this:\n1. A blog post starts as an empty draft.\n1. When the draft is done, a review of the post is requested.\n1. When the post is approved, it gets published.\n1. Only published blog posts return content to print so that unapproved posts\n can’t accidentally be published.\nAny other changes attempted on a post should have no effect. For example, if we\ntry to approve a draft blog post before we’ve requested a review, the post\nshould remain an unpublished draft.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Implementing an Object-Oriented Design Pattern", "heading_path": ["Implementing an Object-Oriented Design Pattern"], "path": "ch18-03-oo-design-patterns.md", "url": "https://doc.rust-lang.org/book/ch18-03-oo-design-patterns.html#implementing-an-object-oriented-design-pattern", "has_code": false, "code_tags": []}} {"id": "book/ch18-03-oo-design-patterns.md#attempting-traditional-object-oriented-style-1", "text": "The Rust Programming Language › Implementing an Object-Oriented Design Pattern › Attempting Traditional Object-Oriented Style\n\nThere are infinite ways to structure code to solve the same problem, each with\ndifferent trade-offs. This section’s implementation is more of a traditional\nobject-oriented style, which is possible to write in Rust, but doesn’t take\nadvantage of some of Rust’s strengths. Later, we’ll demonstrate a different\nsolution that still uses the object-oriented design pattern but is structured\nin a way that might look less familiar to programmers with object-oriented\nexperience. We’ll compare the two solutions to experience the trade-offs of\ndesigning Rust code differently than code in other languages.\nListing 18-11 shows this workflow in code form: This is an example usage of the\nAPI we’ll implement in a library crate named `blog`. This won’t compile yet\nbecause we haven’t implemented the `blog` crate.\nListing 18-11: Code that demonstrates the desired behavior we want our `blog` crate to have (src/main.rs)\n```rust,ignore,does_not_compile\nuse blog::Post;\n\nfn main() {\n let mut post = Post::new();\n\n post.add_text(\"I ate a salad for lunch today\");\n assert_eq!(\"\", post.content());\n\n post.request_review();\n assert_eq!(\"\", post.content());\n\n post.approve();\n assert_eq!(\"I ate a salad for lunch today\", post.content());\n}\n```\nWe want to allow the user to create a new draft blog post with `Post::new`. We\nwant to allow text to be added to the blog post. If we try to get the post’s\ncontent immediately, before approval, we shouldn’t get any text because the\npost is still a draft. We’ve added `assert_eq!` in the code for demonstration\npurposes. An excellent unit test for this would be to assert that a draft blog\npost returns an empty string from the `content` method, but we’re not going to\nwrite tests for this example.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Implementing an Object-Oriented Design Pattern", "heading_path": ["Implementing an Object-Oriented Design Pattern", "Attempting Traditional Object-Oriented Style"], "path": "ch18-03-oo-design-patterns.md", "url": "https://doc.rust-lang.org/book/ch18-03-oo-design-patterns.html#attempting-traditional-object-oriented-style", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch18-03-oo-design-patterns.md#defining-post-and-creating-a-new-instance-2", "text": "The Rust Programming Language › Implementing an Object-Oriented Design Pattern › Attempting Traditional Object-Oriented Style › Defining `Post` and Creating a New Instance\n\nNext, we want to enable a request for a review of the post, and we want\n`content` to return an empty string while waiting for the review. When the post\nreceives approval, it should get published, meaning the text of the post will\nbe returned when `content` is called.\nNotice that the only type we’re interacting with from the crate is the `Post`\ntype. This type will use the state pattern and will hold a value that will be\none of three state objects representing the various states a post can be\nin—draft, review, or published. Changing from one state to another will be\nmanaged internally within the `Post` type. The states change in response to the\nmethods called by our library’s users on the `Post` instance, but they don’t\nhave to manage the state changes directly. Also, users can’t make a mistake\nwith the states, such as publishing a post before it’s reviewed.\nLet’s get started on the implementation of the library! We know we need a\npublic `Post` struct that holds some content, so we’ll start with the\ndefinition of the struct and an associated public `new` function to create an\ninstance of `Post`, as shown in Listing 18-12. We’ll also make a private\n`State` trait that will define the behavior that all state objects for a `Post`\nmust have.\nThen, `Post` will hold a trait object of `Box<dyn State>` inside an `Option<T>`\nin a private field named `state` to hold the state object. You’ll see why the\n`Option<T>` is necessary in a bit.\nListing 18-12: Definition of a `Post` struct and a `new` function that creates a new `Post` instance, a `State` trait, and a `Draft` struct (src/lib.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Implementing an Object-Oriented Design Pattern", "heading_path": ["Implementing an Object-Oriented Design Pattern", "Attempting Traditional Object-Oriented Style", "Defining `Post` and Creating a New Instance"], "path": "ch18-03-oo-design-patterns.md", "url": "https://doc.rust-lang.org/book/ch18-03-oo-design-patterns.html#defining-post-and-creating-a-new-instance", "has_code": false, "code_tags": []}} {"id": "book/ch18-03-oo-design-patterns.md#storing-the-text-of-the-post-content-3", "text": "The Rust Programming Language › Implementing an Object-Oriented Design Pattern › Attempting Traditional Object-Oriented Style › Storing the Text of the Post Content\n\n```rust,noplayground\npub struct Post {\n state: Option<Box<dyn State>>,\n content: String,\n}\n\nimpl Post {\n pub fn new() -> Post {\n Post {\n state: Some(Box::new(Draft {})),\n content: String::new(),\n }\n }\n}\n\ntrait State {}\n\nstruct Draft {}\n\nimpl State for Draft {}\n```\nThe `State` trait defines the behavior shared by different post states. The\nstate objects are `Draft`, `PendingReview`, and `Published`, and they will all\nimplement the `State` trait. For now, the trait doesn’t have any methods, and\nwe’ll start by defining just the `Draft` state because that is the state we\nwant a post to start in.\nWhen we create a new `Post`, we set its `state` field to a `Some` value that\nholds a `Box`. This `Box` points to a new instance of the `Draft` struct. This\nensures that whenever we create a new instance of `Post`, it will start out as\na draft. Because the `state` field of `Post` is private, there is no way to\ncreate a `Post` in any other state! In the `Post::new` function, we set the\n`content` field to a new, empty `String`.\nWe saw in Listing 18-11 that we want to be able to call a method named\n`add_text` and pass it a `&str` that is then added as the text content of the\nblog post. We implement this as a method, rather than exposing the `content`\nfield as `pub`, so that later we can implement a method that will control how\nthe `content` field’s data is read. The `add_text` method is pretty\nstraightforward, so let’s add the implementation in Listing 18-13 to the `impl\nPost` block.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Implementing an Object-Oriented Design Pattern", "heading_path": ["Implementing an Object-Oriented Design Pattern", "Attempting Traditional Object-Oriented Style", "Storing the Text of the Post Content"], "path": "ch18-03-oo-design-patterns.md", "url": "https://doc.rust-lang.org/book/ch18-03-oo-design-patterns.html#storing-the-text-of-the-post-content", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch18-03-oo-design-patterns.md#ensuring-that-the-content-of-a-draft-post-is-empty-4", "text": "The Rust Programming Language › Implementing an Object-Oriented Design Pattern › Attempting Traditional Object-Oriented Style › Ensuring That the Content of a Draft Post Is Empty\n\nListing 18-13: Implementing the `add_text` method to add text to a post’s `content` (src/lib.rs)\n```rust,noplayground\nimpl Post {\n // --snip--\n pub fn add_text(&mut self, text: &str) {\n self.content.push_str(text);\n }\n}\n```\nThe `add_text` method takes a mutable reference to `self` because we’re\nchanging the `Post` instance that we’re calling `add_text` on. We then call\n`push_str` on the `String` in `content` and pass the `text` argument to add to\nthe saved `content`. This behavior doesn’t depend on the state the post is in,\nso it’s not part of the state pattern. The `add_text` method doesn’t interact\nwith the `state` field at all, but it is part of the behavior we want to\nsupport.\nEven after we’ve called `add_text` and added some content to our post, we still\nwant the `content` method to return an empty string slice because the post is\nstill in the draft state, as shown by the first `assert_eq!` in Listing 18-11.\nFor now, let’s implement the `content` method with the simplest thing that will\nfulfill this requirement: always returning an empty string slice. We’ll change\nthis later once we implement the ability to change a post’s state so that it\ncan be published. So far, posts can only be in the draft state, so the post\ncontent should always be empty. Listing 18-14 shows this placeholder\nimplementation.\nListing 18-14: Adding a placeholder implementation for the `content` method on `Post` that always returns an empty string slice (src/lib.rs)\n```rust,noplayground\nimpl Post {\n // --snip--\n pub fn content(&self) -> &str {\n \"\"\n }\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Implementing an Object-Oriented Design Pattern", "heading_path": ["Implementing an Object-Oriented Design Pattern", "Attempting Traditional Object-Oriented Style", "Ensuring That the Content of a Draft Post Is Empty"], "path": "ch18-03-oo-design-patterns.md", "url": "https://doc.rust-lang.org/book/ch18-03-oo-design-patterns.html#ensuring-that-the-content-of-a-draft-post-is-empty", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch18-03-oo-design-patterns.md#requesting-a-review-which-changes-the-posts-state-5", "text": "The Rust Programming Language › Implementing an Object-Oriented Design Pattern › Attempting Traditional Object-Oriented Style › Requesting a Review, Which Changes the Post’s State\n\nWith this added `content` method, everything in Listing 18-11 through the first\n`assert_eq!` works as intended.\nNext, we need to add functionality to request a review of a post, which should\nchange its state from `Draft` to `PendingReview`. Listing 18-15 shows this code.\nListing 18-15: Implementing `request_review` methods on `Post` and the `State` trait (src/lib.rs)\n```rust,noplayground\nimpl Post {\n // --snip--\n pub fn request_review(&mut self) {\n if let Some(s) = self.state.take() {\n self.state = Some(s.request_review())\n }\n }\n}\n\ntrait State {\n fn request_review(self: Box<Self>) -> Box<dyn State>;\n}\n\nstruct Draft {}\n\nimpl State for Draft {\n fn request_review(self: Box<Self>) -> Box<dyn State> {\n Box::new(PendingReview {})\n }\n}\n\nstruct PendingReview {}\n\nimpl State for PendingReview {\n fn request_review(self: Box<Self>) -> Box<dyn State> {\n self\n }\n}\n```\nWe give `Post` a public method named `request_review` that will take a mutable\nreference to `self`. Then, we call an internal `request_review` method on the\ncurrent state of `Post`, and this second `request_review` method consumes the\ncurrent state and returns a new state.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Implementing an Object-Oriented Design Pattern", "heading_path": ["Implementing an Object-Oriented Design Pattern", "Attempting Traditional Object-Oriented Style", "Requesting a Review, Which Changes the Post’s State"], "path": "ch18-03-oo-design-patterns.md", "url": "https://doc.rust-lang.org/book/ch18-03-oo-design-patterns.html#requesting-a-review-which-changes-the-posts-state", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch18-03-oo-design-patterns.md#requesting-a-review-which-changes-the-posts-state-6", "text": "The Rust Programming Language › Implementing an Object-Oriented Design Pattern › Attempting Traditional Object-Oriented Style › Requesting a Review, Which Changes the Post’s State\n\nWe add the `request_review` method to the `State` trait; all types that\nimplement the trait will now need to implement the `request_review` method.\nNote that rather than having `self`, `&self`, or `&mut self` as the first\nparameter of the method, we have `self: Box<Self>`. This syntax means the\nmethod is only valid when called on a `Box` holding the type. This syntax takes\nownership of `Box<Self>`, invalidating the old state so that the state value of\nthe `Post` can transform into a new state.\nTo consume the old state, the `request_review` method needs to take ownership\nof the state value. This is where the `Option` in the `state` field of `Post`\ncomes in: We call the `take` method to take the `Some` value out of the `state`\nfield and leave a `None` in its place because Rust doesn’t let us have\nunpopulated fields in structs. This lets us move the `state` value out of\n`Post` rather than borrowing it. Then, we’ll set the post’s `state` value to\nthe result of this operation.\nWe need to set `state` to `None` temporarily rather than setting it directly\nwith code like `self.state = self.state.request_review();` to get ownership of\nthe `state` value. This ensures that `Post` can’t use the old `state` value\nafter we’ve transformed it into a new state.\nThe `request_review` method on `Draft` returns a new, boxed instance of a new\n`PendingReview` struct, which represents the state when a post is waiting for a\nreview. The `PendingReview` struct also implements the `request_review` method\nbut doesn’t do any transformations. Rather, it returns itself because when we\nrequest a review on a post already in the `PendingReview` state, it should stay\nin the `PendingReview` state.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Implementing an Object-Oriented Design Pattern", "heading_path": ["Implementing an Object-Oriented Design Pattern", "Attempting Traditional Object-Oriented Style", "Requesting a Review, Which Changes the Post’s State"], "path": "ch18-03-oo-design-patterns.md", "url": "https://doc.rust-lang.org/book/ch18-03-oo-design-patterns.html#requesting-a-review-which-changes-the-posts-state", "has_code": false, "code_tags": []}} {"id": "book/ch18-03-oo-design-patterns.md#adding-approve-to-change-contents-behavior-7", "text": "The Rust Programming Language › Implementing an Object-Oriented Design Pattern › Attempting Traditional Object-Oriented Style › Adding `approve` to Change `content`'s Behavior\n\nNow we can start seeing the advantages of the state pattern: The\n`request_review` method on `Post` is the same no matter its `state` value. Each\nstate is responsible for its own rules.\nWe’ll leave the `content` method on `Post` as is, returning an empty string\nslice. We can now have a `Post` in the `PendingReview` state as well as in the\n`Draft` state, but we want the same behavior in the `PendingReview` state.\nListing 18-11 now works up to the second `assert_eq!` call!\nThe `approve` method will be similar to the `request_review` method: It will\nset `state` to the value that the current state says it should have when that\nstate is approved, as shown in Listing 18-16.\nListing 18-16: Implementing the `approve` method on `Post` and the `State` trait (src/lib.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Implementing an Object-Oriented Design Pattern", "heading_path": ["Implementing an Object-Oriented Design Pattern", "Attempting Traditional Object-Oriented Style", "Adding `approve` to Change `content`'s Behavior"], "path": "ch18-03-oo-design-patterns.md", "url": "https://doc.rust-lang.org/book/ch18-03-oo-design-patterns.html#adding-approve-to-change-contents-behavior", "has_code": false, "code_tags": []}} {"id": "book/ch18-03-oo-design-patterns.md#adding-approve-to-change-contents-behavior-8", "text": "The Rust Programming Language › Implementing an Object-Oriented Design Pattern › Attempting Traditional Object-Oriented Style › Adding `approve` to Change `content`'s Behavior\n\n```rust,noplayground\nimpl Post {\n // --snip--\n pub fn approve(&mut self) {\n if let Some(s) = self.state.take() {\n self.state = Some(s.approve())\n }\n }\n}\n\ntrait State {\n fn request_review(self: Box<Self>) -> Box<dyn State>;\n fn approve(self: Box<Self>) -> Box<dyn State>;\n}\n\nstruct Draft {}\n\nimpl State for Draft {\n // --snip--\n fn approve(self: Box<Self>) -> Box<dyn State> {\n self\n }\n}\n\nstruct PendingReview {}\n\nimpl State for PendingReview {\n // --snip--\n fn approve(self: Box<Self>) -> Box<dyn State> {\n Box::new(Published {})\n }\n}\n\nstruct Published {}\n\nimpl State for Published {\n fn request_review(self: Box<Self>) -> Box<dyn State> {\n self\n }\n\n fn approve(self: Box<Self>) -> Box<dyn State> {\n self\n }\n}\n```\nWe add the `approve` method to the `State` trait and add a new struct that\nimplements `State`, the `Published` state.\nSimilar to the way `request_review` on `PendingReview` works, if we call the\n`approve` method on a `Draft`, it will have no effect because `approve` will\nreturn `self`. When we call `approve` on `PendingReview`, it returns a new,\nboxed instance of the `Published` struct. The `Published` struct implements the\n`State` trait, and for both the `request_review` method and the `approve`\nmethod, it returns itself because the post should stay in the `Published` state\nin those cases.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Implementing an Object-Oriented Design Pattern", "heading_path": ["Implementing an Object-Oriented Design Pattern", "Attempting Traditional Object-Oriented Style", "Adding `approve` to Change `content`'s Behavior"], "path": "ch18-03-oo-design-patterns.md", "url": "https://doc.rust-lang.org/book/ch18-03-oo-design-patterns.html#adding-approve-to-change-contents-behavior", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch18-03-oo-design-patterns.md#adding-approve-to-change-contents-behavior-9", "text": "The Rust Programming Language › Implementing an Object-Oriented Design Pattern › Attempting Traditional Object-Oriented Style › Adding `approve` to Change `content`'s Behavior\n\nNow we need to update the `content` method on `Post`. We want the value\nreturned from `content` to depend on the current state of the `Post`, so we’re\ngoing to have the `Post` delegate to a `content` method defined on its `state`,\nas shown in Listing 18-17.\nListing 18-17: Updating the `content` method on `Post` to delegate to a `content` method on `State` (src/lib.rs)\n```rust,ignore,does_not_compile\nimpl Post {\n // --snip--\n pub fn content(&self) -> &str {\n self.state.as_ref().unwrap().content(self)\n }\n // --snip--\n}\n```\nBecause the goal is to keep all of these rules inside the structs that\nimplement `State`, we call a `content` method on the value in `state` and pass\nthe post instance (that is, `self`) as an argument. Then, we return the value\nthat’s returned from using the `content` method on the `state` value.\nWe call the `as_ref` method on the `Option` because we want a reference to the\nvalue inside the `Option` rather than ownership of the value. Because `state` is\nan `Option<Box<dyn State>>`, when we call `as_ref`, an `Option<&Box<dyn\nState>>` is returned. If we didn’t call `as_ref`, we would get an error because\nwe can’t move `state` out of the borrowed `&self` of the function parameter.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Implementing an Object-Oriented Design Pattern", "heading_path": ["Implementing an Object-Oriented Design Pattern", "Attempting Traditional Object-Oriented Style", "Adding `approve` to Change `content`'s Behavior"], "path": "ch18-03-oo-design-patterns.md", "url": "https://doc.rust-lang.org/book/ch18-03-oo-design-patterns.html#adding-approve-to-change-contents-behavior", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch18-03-oo-design-patterns.md#adding-approve-to-change-contents-behavior-10", "text": "The Rust Programming Language › Implementing an Object-Oriented Design Pattern › Attempting Traditional Object-Oriented Style › Adding `approve` to Change `content`'s Behavior\n\nWe then call the `unwrap` method, which we know will never panic because we\nknow the methods on `Post` ensure that `state` will always contain a `Some`\nvalue when those methods are done. This is one of the cases we talked about in\nthe “When You Have More Information Than the\nCompiler” section of Chapter 9 when we\nknow that a `None` value is never possible, even though the compiler isn’t able\nto understand that.\nAt this point, when we call `content` on the `&Box<dyn State>`, deref coercion\nwill take effect on the `&` and the `Box` so that the `content` method will\nultimately be called on the type that implements the `State` trait. That means\nwe need to add `content` to the `State` trait definition, and that is where\nwe’ll put the logic for what content to return depending on which state we\nhave, as shown in Listing 18-18.\nListing 18-18: Adding the `content` method to the `State` trait (src/lib.rs)\n```rust,noplayground\ntrait State {\n // --snip--\n fn content<'a>(&self, post: &'a Post) -> &'a str {\n \"\"\n }\n}\n\n// --snip--\nstruct Published {}\n\nimpl State for Published {\n // --snip--\n fn content<'a>(&self, post: &'a Post) -> &'a str {\n &post.content\n }\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Implementing an Object-Oriented Design Pattern", "heading_path": ["Implementing an Object-Oriented Design Pattern", "Attempting Traditional Object-Oriented Style", "Adding `approve` to Change `content`'s Behavior"], "path": "ch18-03-oo-design-patterns.md", "url": "https://doc.rust-lang.org/book/ch18-03-oo-design-patterns.html#adding-approve-to-change-contents-behavior", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch18-03-oo-design-patterns.md#adding-approve-to-change-contents-behavior-11", "text": "The Rust Programming Language › Implementing an Object-Oriented Design Pattern › Attempting Traditional Object-Oriented Style › Adding `approve` to Change `content`'s Behavior\n\nWe add a default implementation for the `content` method that returns an empty\nstring slice. That means we don’t need to implement `content` on the `Draft`\nand `PendingReview` structs. The `Published` struct will override the `content`\nmethod and return the value in `post.content`. While convenient, having the\n`content` method on `State` determine the content of the `Post` is blurring\nthe lines between the responsibility of `State` and the responsibility of\n`Post`.\nNote that we need lifetime annotations on this method, as we discussed in\nChapter 10. We’re taking a reference to a `post` as an argument and returning a\nreference to part of that `post`, so the lifetime of the returned reference is\nrelated to the lifetime of the `post` argument.\nAnd we’re done—all of Listing 18-11 now works! We’ve implemented the state\npattern with the rules of the blog post workflow. The logic related to the\nrules lives in the state objects rather than being scattered throughout `Post`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Implementing an Object-Oriented Design Pattern", "heading_path": ["Implementing an Object-Oriented Design Pattern", "Attempting Traditional Object-Oriented Style", "Adding `approve` to Change `content`'s Behavior"], "path": "ch18-03-oo-design-patterns.md", "url": "https://doc.rust-lang.org/book/ch18-03-oo-design-patterns.html#adding-approve-to-change-contents-behavior", "has_code": false, "code_tags": []}} {"id": "book/ch18-03-oo-design-patterns.md#evaluating-the-state-pattern-12", "text": "The Rust Programming Language › Implementing an Object-Oriented Design Pattern › Why Not An Enum? › Evaluating the State Pattern\n\nYou may have been wondering why we didn’t use an enum with the different\npossible post states as variants. That’s certainly a possible solution; try it\nand compare the end results to see which you prefer! One disadvantage of using\nan enum is that every place that checks the value of the enum will need a\n`match` expression or similar to handle every possible variant. This could get\nmore repetitive than this trait object solution.\nWe’ve shown that Rust is capable of implementing the object-oriented state\npattern to encapsulate the different kinds of behavior a post should have in\neach state. The methods on `Post` know nothing about the various behaviors.\nBecause of the way we organized the code, we have to look in only one place to\nknow the different ways a published post can behave: the implementation of the\n`State` trait on the `Published` struct.\nIf we were to create an alternative implementation that didn’t use the state\npattern, we might instead use `match` expressions in the methods on `Post` or\neven in the `main` code that checks the state of the post and changes behavior\nin those places. That would mean we would have to look in several places to\nunderstand all the implications of a post being in the published state.\nWith the state pattern, the `Post` methods and the places we use `Post` don’t\nneed `match` expressions, and to add a new state, we would only need to add a\nnew struct and implement the trait methods on that one struct in one location.\nThe implementation using the state pattern is easy to extend to add more\nfunctionality. To see the simplicity of maintaining code that uses the state\npattern, try a few of these suggestions:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Implementing an Object-Oriented Design Pattern", "heading_path": ["Implementing an Object-Oriented Design Pattern", "Why Not An Enum?", "Evaluating the State Pattern"], "path": "ch18-03-oo-design-patterns.md", "url": "https://doc.rust-lang.org/book/ch18-03-oo-design-patterns.html#evaluating-the-state-pattern", "has_code": false, "code_tags": []}} {"id": "book/ch18-03-oo-design-patterns.md#evaluating-the-state-pattern-13", "text": "The Rust Programming Language › Implementing an Object-Oriented Design Pattern › Why Not An Enum? › Evaluating the State Pattern\n\n- Add a `reject` method that changes the post’s state from `PendingReview` back\n to `Draft`.\n- Require two calls to `approve` before the state can be changed to `Published`.\n- Allow users to add text content only when a post is in the `Draft` state.\n Hint: have the state object responsible for what might change about the\n content but not responsible for modifying the `Post`.\nOne downside of the state pattern is that, because the states implement the\ntransitions between states, some of the states are coupled to each other. If we\nadd another state between `PendingReview` and `Published`, such as `Scheduled`,\nwe would have to change the code in `PendingReview` to transition to\n`Scheduled` instead. It would be less work if `PendingReview` didn’t need to\nchange with the addition of a new state, but that would mean switching to\nanother design pattern.\nAnother downside is that we’ve duplicated some logic. To eliminate some of the\nduplication, we might try to make default implementations for the\n`request_review` and `approve` methods on the `State` trait that return `self`.\nHowever, this wouldn’t work: When using `State` as a trait object, the trait\ndoesn’t know what the concrete `self` will be exactly, so the return type isn’t\nknown at compile time. (This is one of the dyn compatibility rules mentioned\nearlier.)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Implementing an Object-Oriented Design Pattern", "heading_path": ["Implementing an Object-Oriented Design Pattern", "Why Not An Enum?", "Evaluating the State Pattern"], "path": "ch18-03-oo-design-patterns.md", "url": "https://doc.rust-lang.org/book/ch18-03-oo-design-patterns.html#evaluating-the-state-pattern", "has_code": false, "code_tags": []}} {"id": "book/ch18-03-oo-design-patterns.md#evaluating-the-state-pattern-14", "text": "The Rust Programming Language › Implementing an Object-Oriented Design Pattern › Why Not An Enum? › Evaluating the State Pattern\n\nOther duplication includes the similar implementations of the `request_review`\nand `approve` methods on `Post`. Both methods use `Option::take` with the\n`state` field of `Post`, and if `state` is `Some`, they delegate to the wrapped\nvalue’s implementation of the same method and set the new value of the `state`\nfield to the result. If we had a lot of methods on `Post` that followed this\npattern, we might consider defining a macro to eliminate the repetition (see\nthe “Macros” section in Chapter 20).\nBy implementing the state pattern exactly as it’s defined for object-oriented\nlanguages, we’re not taking as full advantage of Rust’s strengths as we could.\nLet’s look at some changes we can make to the `blog` crate that can make\ninvalid states and transitions into compile-time errors.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Implementing an Object-Oriented Design Pattern", "heading_path": ["Implementing an Object-Oriented Design Pattern", "Why Not An Enum?", "Evaluating the State Pattern"], "path": "ch18-03-oo-design-patterns.md", "url": "https://doc.rust-lang.org/book/ch18-03-oo-design-patterns.html#evaluating-the-state-pattern", "has_code": false, "code_tags": []}} {"id": "book/ch18-03-oo-design-patterns.md#encoding-states-and-behavior-as-types-15", "text": "The Rust Programming Language › Implementing an Object-Oriented Design Pattern › Encoding States and Behavior as Types\n\nWe’ll show you how to rethink the state pattern to get a different set of\ntrade-offs. Rather than encapsulating the states and transitions completely so\nthat outside code has no knowledge of them, we’ll encode the states into\ndifferent types. Consequently, Rust’s type-checking system will prevent\nattempts to use draft posts where only published posts are allowed by issuing a\ncompiler error.\nLet’s consider the first part of `main` in Listing 18-11:\nListing (src/main.rs)\n```rust,ignore\nfn main() {\n let mut post = Post::new();\n\n post.add_text(\"I ate a salad for lunch today\");\n assert_eq!(\"\", post.content());\n}\n```\nWe still enable the creation of new posts in the draft state using `Post::new`\nand the ability to add text to the post’s content. But instead of having a\n`content` method on a draft post that returns an empty string, we’ll make it so\nthat draft posts don’t have the `content` method at all. That way, if we try to\nget a draft post’s content, we’ll get a compiler error telling us the method\ndoesn’t exist. As a result, it will be impossible for us to accidentally\ndisplay draft post content in production because that code won’t even compile.\nListing 18-19 shows the definition of a `Post` struct and a `DraftPost` struct,\nas well as methods on each.\nListing 18-19: A `Post` with a `content` method and a `DraftPost` without a `content` method (src/lib.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Implementing an Object-Oriented Design Pattern", "heading_path": ["Implementing an Object-Oriented Design Pattern", "Encoding States and Behavior as Types"], "path": "ch18-03-oo-design-patterns.md", "url": "https://doc.rust-lang.org/book/ch18-03-oo-design-patterns.html#encoding-states-and-behavior-as-types", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch18-03-oo-design-patterns.md#encoding-states-and-behavior-as-types-16", "text": "The Rust Programming Language › Implementing an Object-Oriented Design Pattern › Encoding States and Behavior as Types\n\n```rust,noplayground\npub struct Post {\n content: String,\n}\n\npub struct DraftPost {\n content: String,\n}\n\nimpl Post {\n pub fn new() -> DraftPost {\n DraftPost {\n content: String::new(),\n }\n }\n\n pub fn content(&self) -> &str {\n &self.content\n }\n}\n\nimpl DraftPost {\n pub fn add_text(&mut self, text: &str) {\n self.content.push_str(text);\n }\n}\n```\nBoth the `Post` and `DraftPost` structs have a private `content` field that\nstores the blog post text. The structs no longer have the `state` field because\nwe’re moving the encoding of the state to the types of the structs. The `Post`\nstruct will represent a published post, and it has a `content` method that\nreturns the `content`.\nWe still have a `Post::new` function, but instead of returning an instance of\n`Post`, it returns an instance of `DraftPost`. Because `content` is private and\nthere aren’t any functions that return `Post`, it’s not possible to create an\ninstance of `Post` right now.\nThe `DraftPost` struct has an `add_text` method, so we can add text to\n`content` as before, but note that `DraftPost` does not have a `content` method\ndefined! So now the program ensures that all posts start as draft posts, and\ndraft posts don’t have their content available for display. Any attempt to get\naround these constraints will result in a compiler error.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Implementing an Object-Oriented Design Pattern", "heading_path": ["Implementing an Object-Oriented Design Pattern", "Encoding States and Behavior as Types"], "path": "ch18-03-oo-design-patterns.md", "url": "https://doc.rust-lang.org/book/ch18-03-oo-design-patterns.html#encoding-states-and-behavior-as-types", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch18-03-oo-design-patterns.md#encoding-states-and-behavior-as-types-17", "text": "The Rust Programming Language › Implementing an Object-Oriented Design Pattern › Encoding States and Behavior as Types\n\nSo, how do we get a published post? We want to enforce the rule that a draft\npost has to be reviewed and approved before it can be published. A post in the\npending review state should still not display any content. Let’s implement\nthese constraints by adding another struct, `PendingReviewPost`, defining the\n`request_review` method on `DraftPost` to return a `PendingReviewPost` and\ndefining an `approve` method on `PendingReviewPost` to return a `Post`, as\nshown in Listing 18-20.\nListing 18-20: A `PendingReviewPost` that gets created by calling `request_review` on `DraftPost` and an `approve` method that turns a `PendingReviewPost` into a published `Post` (src/lib.rs)\n```rust,noplayground\nimpl DraftPost {\n // --snip--\n pub fn request_review(self) -> PendingReviewPost {\n PendingReviewPost {\n content: self.content,\n }\n }\n}\n\npub struct PendingReviewPost {\n content: String,\n}\n\nimpl PendingReviewPost {\n pub fn approve(self) -> Post {\n Post {\n content: self.content,\n }\n }\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Implementing an Object-Oriented Design Pattern", "heading_path": ["Implementing an Object-Oriented Design Pattern", "Encoding States and Behavior as Types"], "path": "ch18-03-oo-design-patterns.md", "url": "https://doc.rust-lang.org/book/ch18-03-oo-design-patterns.html#encoding-states-and-behavior-as-types", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch18-03-oo-design-patterns.md#encoding-states-and-behavior-as-types-18", "text": "The Rust Programming Language › Implementing an Object-Oriented Design Pattern › Encoding States and Behavior as Types\n\nThe `request_review` and `approve` methods take ownership of `self`, thus\nconsuming the `DraftPost` and `PendingReviewPost` instances and transforming\nthem into a `PendingReviewPost` and a published `Post`, respectively. This way,\nwe won’t have any lingering `DraftPost` instances after we’ve called\n`request_review` on them, and so forth. The `PendingReviewPost` struct doesn’t\nhave a `content` method defined on it, so attempting to read its content\nresults in a compiler error, as with `DraftPost`. Because the only way to get a\npublished `Post` instance that does have a `content` method defined is to call\nthe `approve` method on a `PendingReviewPost`, and the only way to get a\n`PendingReviewPost` is to call the `request_review` method on a `DraftPost`,\nwe’ve now encoded the blog post workflow into the type system.\nBut we also have to make some small changes to `main`. The `request_review` and\n`approve` methods return new instances rather than modifying the struct they’re\ncalled on, so we need to add more `let post =` shadowing assignments to save\nthe returned instances. We also can’t have the assertions about the draft and\npending review posts’ contents be empty strings, nor do we need them: We can’t\ncompile code that tries to use the content of posts in those states any longer.\nThe updated code in `main` is shown in Listing 18-21.\nListing 18-21: Modifications to `main` to use the new implementation of the blog post workflow (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Implementing an Object-Oriented Design Pattern", "heading_path": ["Implementing an Object-Oriented Design Pattern", "Encoding States and Behavior as Types"], "path": "ch18-03-oo-design-patterns.md", "url": "https://doc.rust-lang.org/book/ch18-03-oo-design-patterns.html#encoding-states-and-behavior-as-types", "has_code": false, "code_tags": []}} {"id": "book/ch18-03-oo-design-patterns.md#encoding-states-and-behavior-as-types-19", "text": "The Rust Programming Language › Implementing an Object-Oriented Design Pattern › Encoding States and Behavior as Types\n\n```rust,ignore\nuse blog::Post;\n\nfn main() {\n let mut post = Post::new();\n\n post.add_text(\"I ate a salad for lunch today\");\n\n let post = post.request_review();\n\n let post = post.approve();\n\n assert_eq!(\"I ate a salad for lunch today\", post.content());\n}\n```\nThe changes we needed to make to `main` to reassign `post` mean that this\nimplementation doesn’t quite follow the object-oriented state pattern anymore:\nThe transformations between the states are no longer encapsulated entirely\nwithin the `Post` implementation. However, our gain is that invalid states are\nnow impossible because of the type system and the type checking that happens at\ncompile time! This ensures that certain bugs, such as display of the content of\nan unpublished post, will be discovered before they make it to production.\nTry the tasks suggested at the start of this section on the `blog` crate as it\nis after Listing 18-21 to see what you think about the design of this version\nof the code. Note that some of the tasks might be completed already in this\ndesign.\nWe’ve seen that even though Rust is capable of implementing object-oriented\ndesign patterns, other patterns, such as encoding state into the type system,\nare also available in Rust. These patterns have different trade-offs. Although\nyou might be very familiar with object-oriented patterns, rethinking the\nproblem to take advantage of Rust’s features can provide benefits, such as\npreventing some bugs at compile time. Object-oriented patterns won’t always be\nthe best solution in Rust due to certain features, like ownership, that\nobject-oriented languages don’t have.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Implementing an Object-Oriented Design Pattern", "heading_path": ["Implementing an Object-Oriented Design Pattern", "Encoding States and Behavior as Types"], "path": "ch18-03-oo-design-patterns.md", "url": "https://doc.rust-lang.org/book/ch18-03-oo-design-patterns.html#encoding-states-and-behavior-as-types", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch18-03-oo-design-patterns.md#summary-20", "text": "The Rust Programming Language › Summary\n\nRegardless of whether you think Rust is an object-oriented language after\nreading this chapter, you now know that you can use trait objects to get some\nobject-oriented features in Rust. Dynamic dispatch can give your code some\nflexibility in exchange for a bit of runtime performance. You can use this\nflexibility to implement object-oriented patterns that can help your code’s\nmaintainability. Rust also has other features, like ownership, that\nobject-oriented languages don’t have. An object-oriented pattern won’t always\nbe the best way to take advantage of Rust’s strengths, but it is an available\noption.\nNext, we’ll look at patterns, which are another of Rust’s features that enable\nlots of flexibility. We’ve looked at them briefly throughout the book but\nhaven’t seen their full capability yet. Let’s go!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Implementing an Object-Oriented Design Pattern", "heading_path": ["Summary"], "path": "ch18-03-oo-design-patterns.md", "url": "https://doc.rust-lang.org/book/ch18-03-oo-design-patterns.html#summary", "has_code": false, "code_tags": []}} {"id": "book/ch19-00-patterns.md#patterns-and-matching-0", "text": "The Rust Programming Language › Patterns and Matching\n\nPatterns are a special syntax in Rust for matching against the structure of\ntypes, both complex and simple. Using patterns in conjunction with `match`\nexpressions and other constructs gives you more control over a program’s\ncontrol flow. A pattern consists of some combination of the following:\n- Literals\n- Destructured arrays, enums, structs, or tuples\n- Variables\n- Wildcards\n- Placeholders\nSome example patterns include `x`, `(a, 3)`, and `Some(Color::Red)`. In the\ncontexts in which patterns are valid, these components describe the shape of\ndata. Our program then matches values against the patterns to determine whether\nit has the correct shape of data to continue running a particular piece of code.\nTo use a pattern, we compare it to some value. If the pattern matches the\nvalue, we use the value parts in our code. Recall the `match` expressions in\nChapter 6 that used patterns, such as the coin-sorting machine example. If the\nvalue fits the shape of the pattern, we can use the named pieces. If it\ndoesn’t, the code associated with the pattern won’t run.\nThis chapter is a reference on all things related to patterns. We’ll cover the\nvalid places to use patterns, the difference between refutable and irrefutable\npatterns, and the different kinds of pattern syntax that you might see. By the\nend of the chapter, you’ll know how to use patterns to express many concepts in\na clear way.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Patterns and Matching", "heading_path": ["Patterns and Matching"], "path": "ch19-00-patterns.md", "url": "https://doc.rust-lang.org/book/ch19-00-patterns.html#patterns-and-matching", "has_code": false, "code_tags": []}} {"id": "book/ch19-01-all-the-places-for-patterns.md#all-the-places-patterns-can-be-used-0", "text": "The Rust Programming Language › All the Places Patterns Can Be Used\n\nPatterns pop up in a number of places in Rust, and you’ve been using them a lot\nwithout realizing it! This section discusses all the places where patterns are\nvalid.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "All the Places Patterns Can Be Used", "heading_path": ["All the Places Patterns Can Be Used"], "path": "ch19-01-all-the-places-for-patterns.md", "url": "https://doc.rust-lang.org/book/ch19-01-all-the-places-for-patterns.html#all-the-places-patterns-can-be-used", "has_code": false, "code_tags": []}} {"id": "book/ch19-01-all-the-places-for-patterns.md#match-arms-1", "text": "The Rust Programming Language › All the Places Patterns Can Be Used › `match` Arms\n\nAs discussed in Chapter 6, we use patterns in the arms of `match` expressions.\nFormally, `match` expressions are defined as the keyword `match`, a value to\nmatch on, and one or more match arms that consist of a pattern and an\nexpression to run if the value matches that arm’s pattern, like this:\n<pre><code>match <em>VALUE</em> {\n <em>PATTERN</em> => <em>EXPRESSION</em>,\n <em>PATTERN</em> => <em>EXPRESSION</em>,\n <em>PATTERN</em> => <em>EXPRESSION</em>,\n}</code></pre>\nFor example, here’s the `match` expression from Listing 6-5 that matches on an\n`Option<i32>` value in the variable `x`:\n```rust,ignore\nmatch x {\n None => None,\n Some(i) => Some(i + 1),\n}\n```\nThe patterns in this `match` expression are the `None` and `Some(i)` to the\nleft of each arrow.\nOne requirement for `match` expressions is that they need to be exhaustive in\nthe sense that all possibilities for the value in the `match` expression must\nbe accounted for. One way to ensure that you’ve covered every possibility is to\nhave a catch-all pattern for the last arm: For example, a variable name\nmatching any value can never fail and thus covers every remaining case.\nThe particular pattern `_` will match anything, but it never binds to a\nvariable, so it’s often used in the last match arm. The `_` pattern can be\nuseful when you want to ignore any value not specified, for example. We’ll\ncover the `_` pattern in more detail in “Ignoring Values in a\nPattern” later in this chapter.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "All the Places Patterns Can Be Used", "heading_path": ["All the Places Patterns Can Be Used", "`match` Arms"], "path": "ch19-01-all-the-places-for-patterns.md", "url": "https://doc.rust-lang.org/book/ch19-01-all-the-places-for-patterns.html#match-arms", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch19-01-all-the-places-for-patterns.md#let-statements-2", "text": "The Rust Programming Language › All the Places Patterns Can Be Used › `let` Statements\n\nPrior to this chapter, we had only explicitly discussed using patterns with\n`match` and `if let`, but in fact, we’ve used patterns in other places as well,\nincluding in `let` statements. For example, consider this straightforward\nvariable assignment with `let`:\n```rust\nlet x = 5;\n```\nEvery time you’ve used a `let` statement like this you’ve been using patterns,\nalthough you might not have realized it! More formally, a `let` statement looks\nlike this:\n<pre>\n<code>let <em>PATTERN</em> = <em>EXPRESSION</em>;</code>\n</pre>\nIn statements like `let x = 5;` with a variable name in the PATTERN slot, the\nvariable name is just a particularly simple form of a pattern. Rust compares\nthe expression against the pattern and assigns any names it finds. So, in the\n`let x = 5;` example, `x` is a pattern that means “bind what matches here to\nthe variable `x`.” Because the name `x` is the whole pattern, this pattern\neffectively means “bind everything to the variable `x`, whatever the value is.”\nTo see the pattern-matching aspect of `let` more clearly, consider Listing\n19-1, which uses a pattern with `let` to destructure a tuple.\nListing 19-1: Using a pattern to destructure a tuple and create three variables at once\n```rust\n let (x, y, z) = (1, 2, 3);\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "All the Places Patterns Can Be Used", "heading_path": ["All the Places Patterns Can Be Used", "`let` Statements"], "path": "ch19-01-all-the-places-for-patterns.md", "url": "https://doc.rust-lang.org/book/ch19-01-all-the-places-for-patterns.html#let-statements", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch19-01-all-the-places-for-patterns.md#let-statements-3", "text": "The Rust Programming Language › All the Places Patterns Can Be Used › `let` Statements\n\nHere, we match a tuple against a pattern. Rust compares the value `(1, 2, 3)`\nto the pattern `(x, y, z)` and sees that the value matches the pattern—that is,\nit sees that the number of elements is the same in both—so Rust binds `1` to\n`x`, `2` to `y`, and `3` to `z`. You can think of this tuple pattern as nesting\nthree individual variable patterns inside it.\nIf the number of elements in the pattern doesn’t match the number of elements\nin the tuple, the overall type won’t match and we’ll get a compiler error. For\nexample, Listing 19-2 shows an attempt to destructure a tuple with three\nelements into two variables, which won’t work.\nListing 19-2: Incorrectly constructing a pattern whose variables don’t match the number of elements in the tuple\n```rust,ignore,does_not_compile\n let (x, y) = (1, 2, 3);\n```\nAttempting to compile this code results in this type error:\n```console\n$ cargo run\n Compiling patterns v0.1.0 (file:///projects/patterns)\nerror[E0308]: mismatched types\n --> src/main.rs:2:9\n |\n2 | let (x, y) = (1, 2, 3);\n | ^^^^^^ --------- this expression has type `({integer}, {integer}, {integer})`\n | |\n | expected a tuple with 3 elements, found one with 2 elements\n |\n = note: expected tuple `({integer}, {integer}, {integer})`\n found tuple `(_, _)`\n\nFor more information about this error, try `rustc --explain E0308`.\nerror: could not compile `patterns` (bin \"patterns\") due to 1 previous error\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "All the Places Patterns Can Be Used", "heading_path": ["All the Places Patterns Can Be Used", "`let` Statements"], "path": "ch19-01-all-the-places-for-patterns.md", "url": "https://doc.rust-lang.org/book/ch19-01-all-the-places-for-patterns.html#let-statements", "has_code": true, "code_tags": ["console", "rust,ignore,does_not_compile"]}} {"id": "book/ch19-01-all-the-places-for-patterns.md#let-statements-4", "text": "The Rust Programming Language › All the Places Patterns Can Be Used › `let` Statements\n\nTo fix the error, we could ignore one or more of the values in the tuple using\n`_` or `..`, as you’ll see in the “Ignoring Values in a\nPattern” section. If the problem\nis that we have too many variables in the pattern, the solution is to make the\ntypes match by removing variables so that the number of variables equals the\nnumber of elements in the tuple.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "All the Places Patterns Can Be Used", "heading_path": ["All the Places Patterns Can Be Used", "`let` Statements"], "path": "ch19-01-all-the-places-for-patterns.md", "url": "https://doc.rust-lang.org/book/ch19-01-all-the-places-for-patterns.html#let-statements", "has_code": false, "code_tags": []}} {"id": "book/ch19-01-all-the-places-for-patterns.md#conditional-if-let-expressions-5", "text": "The Rust Programming Language › All the Places Patterns Can Be Used › Conditional `if let` Expressions\n\nIn Chapter 6, we discussed how to use `if let` expressions mainly as a shorter\nway to write the equivalent of a `match` that only matches one case.\nOptionally, `if let` can have a corresponding `else` containing code to run if\nthe pattern in the `if let` doesn’t match.\nListing 19-3 shows that it’s also possible to mix and match `if let`, `else\nif`, and `else if let` expressions. Doing so gives us more flexibility than a\n`match` expression in which we can express only one value to compare with the\npatterns. Also, Rust doesn’t require that the conditions in a series of `if\nlet`, `else if`, and `else if let` arms relate to each other.\nThe code in Listing 19-3 determines what color to make your background based on\na series of checks for several conditions. For this example, we’ve created\nvariables with hardcoded values that a real program might receive from user\ninput.\nListing 19-3: Mixing `if let`, `else if`, `else if let`, and `else` (src/main.rs)\n```rust\nfn main() {\n let favorite_color: Option<&str> = None;\n let is_tuesday = false;\n let age: Result<u8, _> = \"34\".parse();\n\n if let Some(color) = favorite_color {\n println!(\"Using your favorite color, {color}, as the background\");\n } else if is_tuesday {\n println!(\"Tuesday is green day!\");\n } else if let Ok(age) = age {\n if age > 30 {\n println!(\"Using purple as the background color\");\n } else {\n println!(\"Using orange as the background color\");\n }\n } else {\n println!(\"Using blue as the background color\");\n }\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "All the Places Patterns Can Be Used", "heading_path": ["All the Places Patterns Can Be Used", "Conditional `if let` Expressions"], "path": "ch19-01-all-the-places-for-patterns.md", "url": "https://doc.rust-lang.org/book/ch19-01-all-the-places-for-patterns.html#conditional-if-let-expressions", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch19-01-all-the-places-for-patterns.md#conditional-if-let-expressions-6", "text": "The Rust Programming Language › All the Places Patterns Can Be Used › Conditional `if let` Expressions\n\nIf the user specifies a favorite color, that color is used as the background.\nIf no favorite color is specified and today is Tuesday, the background color is\ngreen. Otherwise, if the user specifies their age as a string and we can parse\nit as a number successfully, the color is either purple or orange depending on\nthe value of the number. If none of these conditions apply, the background\ncolor is blue.\nThis conditional structure lets us support complex requirements. With the\nhardcoded values we have here, this example will print `Using purple as the\nbackground color`.\nYou can see that `if let` can also introduce new variables that shadow existing\nvariables in the same way that `match` arms can: The line `if let Ok(age) = age`\nintroduces a new `age` variable that contains the value inside the `Ok` variant,\nshadowing the existing `age` variable. This means we need to place the `if age >\n30` condition within that block: We can’t combine these two conditions into `if\nlet Ok(age) = age && age > 30`. The new `age` we want to compare to 30 isn’t\nvalid until the new scope starts with the curly bracket.\nThe downside of using `if let` expressions is that the compiler doesn’t check\nfor exhaustiveness, whereas with `match` expressions it does. If we omitted the\nlast `else` block and therefore missed handling some cases, the compiler would\nnot alert us to the possible logic bug.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "All the Places Patterns Can Be Used", "heading_path": ["All the Places Patterns Can Be Used", "Conditional `if let` Expressions"], "path": "ch19-01-all-the-places-for-patterns.md", "url": "https://doc.rust-lang.org/book/ch19-01-all-the-places-for-patterns.html#conditional-if-let-expressions", "has_code": false, "code_tags": []}} {"id": "book/ch19-01-all-the-places-for-patterns.md#while-let-conditional-loops-7", "text": "The Rust Programming Language › All the Places Patterns Can Be Used › `while let` Conditional Loops\n\nSimilar in construction to `if let`, the `while let` conditional loop allows a\n`while` loop to run for as long as a pattern continues to match. In Listing\n19-4, we show a `while let` loop that waits on messages sent between threads,\nbut in this case checking a `Result` instead of an `Option`.\nListing 19-4: Using a `while let` loop to print values for as long as `rx.recv()` returns `Ok`\n```rust\n let (tx, rx) = std::sync::mpsc::channel();\n std::thread::spawn(move || {\n for val in [1, 2, 3] {\n tx.send(val).unwrap();\n }\n });\n\n while let Ok(value) = rx.recv() {\n println!(\"{value}\");\n }\n```\nThis example prints `1`, `2`, and then `3`. The `recv` method takes the first\nmessage out of the receiver side of the channel and returns an `Ok(value)`. When\nwe first saw `recv` back in Chapter 16, we unwrapped the error directly, or\nwe interacted with it as an iterator using a `for` loop. As Listing 19-4 shows,\nthough, we can also use `while let`, because the `recv` method returns an `Ok`\neach time a message arrives, as long as the sender exists, and then produces an\n`Err` once the sender side disconnects.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "All the Places Patterns Can Be Used", "heading_path": ["All the Places Patterns Can Be Used", "`while let` Conditional Loops"], "path": "ch19-01-all-the-places-for-patterns.md", "url": "https://doc.rust-lang.org/book/ch19-01-all-the-places-for-patterns.html#while-let-conditional-loops", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch19-01-all-the-places-for-patterns.md#for-loops-8", "text": "The Rust Programming Language › All the Places Patterns Can Be Used › `for` Loops\n\nIn a `for` loop, the value that directly follows the keyword `for` is a\npattern. For example, in `for x in y`, the `x` is the pattern. Listing 19-5\ndemonstrates how to use a pattern in a `for` loop to destructure, or break\napart, a tuple as part of the `for` loop.\nListing 19-5: Using a pattern in a `for` loop to destructure a tuple\n```rust\n let v = vec!['a', 'b', 'c'];\n\n for (index, value) in v.iter().enumerate() {\n println!(\"{value} is at index {index}\");\n }\n```\nThe code in Listing 19-5 will print the following:\n```console\n$ cargo run\n Compiling patterns v0.1.0 (file:///projects/patterns)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.52s\n Running `target/debug/patterns`\na is at index 0\nb is at index 1\nc is at index 2\n```\nWe adapt an iterator using the `enumerate` method so that it produces a value\nand the index for that value, placed into a tuple. The first value produced is\nthe tuple `(0, 'a')`. When this value is matched to the pattern `(index,\nvalue)`, index will be `0` and value will be `'a'`, printing the first line of\nthe output.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "All the Places Patterns Can Be Used", "heading_path": ["All the Places Patterns Can Be Used", "`for` Loops"], "path": "ch19-01-all-the-places-for-patterns.md", "url": "https://doc.rust-lang.org/book/ch19-01-all-the-places-for-patterns.html#for-loops", "has_code": true, "code_tags": ["console", "rust"]}} {"id": "book/ch19-01-all-the-places-for-patterns.md#function-parameters-9", "text": "The Rust Programming Language › All the Places Patterns Can Be Used › Function Parameters\n\nFunction parameters can also be patterns. The code in Listing 19-6, which\ndeclares a function named `foo` that takes one parameter named `x` of type\n`i32`, should by now look familiar.\nListing 19-6: A function signature using patterns in the parameters\n```rust\nfn foo(x: i32) {\n // code goes here\n}\n```\nThe `x` part is a pattern! As we did with `let`, we could match a tuple in a\nfunction’s arguments to the pattern. Listing 19-7 splits the values in a tuple\nas we pass it to a function.\nListing 19-7: A function with parameters that destructure a tuple (src/main.rs)\n```rust\nfn print_coordinates(&(x, y): &(i32, i32)) {\n println!(\"Current location: ({x}, {y})\");\n}\n\nfn main() {\n let point = (3, 5);\n print_coordinates(&point);\n}\n```\nThis code prints `Current location: (3, 5)`. The values `&(3, 5)` match the\npattern `&(x, y)`, so `x` is the value `3` and `y` is the value `5`.\nWe can also use patterns in closure parameter lists in the same way as in\nfunction parameter lists because closures are similar to functions, as\ndiscussed in Chapter 13.\nAt this point, you’ve seen several ways to use patterns, but patterns don’t\nwork the same in every place we can use them. In some places, the patterns must\nbe irrefutable; in other circumstances, they can be refutable. We’ll discuss\nthese two concepts next.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "All the Places Patterns Can Be Used", "heading_path": ["All the Places Patterns Can Be Used", "Function Parameters"], "path": "ch19-01-all-the-places-for-patterns.md", "url": "https://doc.rust-lang.org/book/ch19-01-all-the-places-for-patterns.html#function-parameters", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch19-02-refutability.md#refutability-whether-a-pattern-might-fail-to-match-0", "text": "The Rust Programming Language › Refutability: Whether a Pattern Might Fail to Match\n\nPatterns come in two forms: refutable and irrefutable. Patterns that will match\nfor any possible value passed are _irrefutable_. An example would be `x` in the\nstatement `let x = 5;` because `x` matches anything and therefore cannot fail\nto match. Patterns that can fail to match for some possible value are\n_refutable_. An example would be `Some(x)` in the expression `if let Some(x) =\na_value` because if the value in the `a_value` variable is `None` rather than\n`Some`, the `Some(x)` pattern will not match.\nFunction parameters, `let` statements, and `for` loops can only accept\nirrefutable patterns because the program cannot do anything meaningful when\nvalues don’t match. The `if let` and `while let` expressions and the\n`let...else` statement accept refutable and irrefutable patterns, but the\ncompiler warns against irrefutable patterns because, by definition, they’re\nintended to handle possible failure: The functionality of a conditional is in\nits ability to perform differently depending on success or failure.\nIn general, you shouldn’t have to worry about the distinction between refutable\nand irrefutable patterns; however, you do need to be familiar with the concept\nof refutability so that you can respond when you see it in an error message. In\nthose cases, you’ll need to change either the pattern or the construct you’re\nusing the pattern with, depending on the intended behavior of the code.\nLet’s look at an example of what happens when we try to use a refutable pattern\nwhere Rust requires an irrefutable pattern and vice versa. Listing 19-8 shows a\n`let` statement, but for the pattern, we’ve specified `Some(x)`, a refutable\npattern. As you might expect, this code will not compile.\nListing 19-8: Attempting to use a refutable pattern with `let`", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Refutability: Whether a Pattern Might Fail to Match", "heading_path": ["Refutability: Whether a Pattern Might Fail to Match"], "path": "ch19-02-refutability.md", "url": "https://doc.rust-lang.org/book/ch19-02-refutability.html#refutability-whether-a-pattern-might-fail-to-match", "has_code": false, "code_tags": []}} {"id": "book/ch19-02-refutability.md#refutability-whether-a-pattern-might-fail-to-match-1", "text": "The Rust Programming Language › Refutability: Whether a Pattern Might Fail to Match\n\n```rust,ignore,does_not_compile\n let Some(x) = some_option_value;\n```\nIf `some_option_value` were a `None` value, it would fail to match the pattern\n`Some(x)`, meaning the pattern is refutable. However, the `let` statement can\nonly accept an irrefutable pattern because there is nothing valid the code can\ndo with a `None` value. At compile time, Rust will complain that we’ve tried to\nuse a refutable pattern where an irrefutable pattern is required:\n```console\n$ cargo run\n Compiling patterns v0.1.0 (file:///projects/patterns)\nerror[E0005]: refutable pattern in local binding\n --> src/main.rs:3:9\n |\n3 | let Some(x) = some_option_value;\n | ^^^^^^^ pattern `None` not covered\n |\n = note: `let` bindings require an \"irrefutable pattern\", like a `struct` or an `enum` with only one variant\n = note: for more information, visit https://doc.rust-lang.org/book/ch19-02-refutability.html\n = note: the matched value is of type `Option<i32>`\nhelp: you might want to use `let...else` to handle the variant that isn't matched\n |\n3 | let Some(x) = some_option_value else { todo!() };\n | ++++++++++++++++\n\nFor more information about this error, try `rustc --explain E0005`.\nerror: could not compile `patterns` (bin \"patterns\") due to 1 previous error\n```\nBecause we didn’t cover (and couldn’t cover!) every valid value with the\npattern `Some(x)`, Rust rightfully produces a compiler error.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Refutability: Whether a Pattern Might Fail to Match", "heading_path": ["Refutability: Whether a Pattern Might Fail to Match"], "path": "ch19-02-refutability.md", "url": "https://doc.rust-lang.org/book/ch19-02-refutability.html#refutability-whether-a-pattern-might-fail-to-match", "has_code": true, "code_tags": ["console", "rust,ignore,does_not_compile"]}} {"id": "book/ch19-02-refutability.md#refutability-whether-a-pattern-might-fail-to-match-2", "text": "The Rust Programming Language › Refutability: Whether a Pattern Might Fail to Match\n\nIf we have a refutable pattern where an irrefutable pattern is needed, we can\nfix it by changing the code that uses the pattern: Instead of using `let`, we\ncan use `let...else`. Then, if the pattern doesn’t match, the code in the curly\nbrackets will handle the value. Listing 19-9 shows how to fix the code in\nListing 19-8.\nListing 19-9: Using `let...else` and a block with refutable patterns instead of `let`\n```rust\n let Some(x) = some_option_value else {\n return;\n };\n```\nWe’ve given the code an out! This code is perfectly valid, although it means we\ncannot use an irrefutable pattern without receiving a warning. If we give\n`let...else` a pattern that will always match, such as `x`, as shown in Listing\n19-10, the compiler will give a warning.\nListing 19-10: Attempting to use an irrefutable pattern with `let...else`\n```rust\n let x = 5 else {\n return;\n };\n```\nRust complains that it doesn’t make sense to use `let...else` with an\nirrefutable pattern because the `else` will never be reached:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Refutability: Whether a Pattern Might Fail to Match", "heading_path": ["Refutability: Whether a Pattern Might Fail to Match"], "path": "ch19-02-refutability.md", "url": "https://doc.rust-lang.org/book/ch19-02-refutability.html#refutability-whether-a-pattern-might-fail-to-match", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch19-02-refutability.md#refutability-whether-a-pattern-might-fail-to-match-3", "text": "The Rust Programming Language › Refutability: Whether a Pattern Might Fail to Match\n\n```console\n$ cargo run\n Compiling patterns v0.1.0 (file:///projects/patterns)\nwarning: unreachable `else` clause\n --> src/main.rs:2:15\n |\n2 | let x = 5 else {\n | --------- ^^^^\n | |\n | assigning to binding pattern will always succeed\n |\n = note: this pattern always matches, so the else clause is unreachable\n = note: `#[warn(irrefutable_let_patterns)]` on by default\n\nwarning: `patterns` (bin \"patterns\") generated 1 warning\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.39s\n Running `target/debug/patterns`\n```\nFor this reason, match arms must use refutable patterns, except for the last\narm, which should match any remaining values with an irrefutable pattern. Rust\nallows us to use an irrefutable pattern in a `match` with only one arm, but\nthis syntax isn’t particularly useful and could be replaced with a simpler\n`let` statement.\nNow that you know where to use patterns and the difference between refutable\nand irrefutable patterns, let’s cover all the syntax we can use to create\npatterns.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Refutability: Whether a Pattern Might Fail to Match", "heading_path": ["Refutability: Whether a Pattern Might Fail to Match"], "path": "ch19-02-refutability.md", "url": "https://doc.rust-lang.org/book/ch19-02-refutability.html#refutability-whether-a-pattern-might-fail-to-match", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch19-03-pattern-syntax.md#pattern-syntax-0", "text": "The Rust Programming Language › Pattern Syntax\n\nIn this section, we gather all the syntax that is valid in patterns and discuss\nwhy and when you might want to use each one.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Pattern Syntax", "heading_path": ["Pattern Syntax"], "path": "ch19-03-pattern-syntax.md", "url": "https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#pattern-syntax", "has_code": false, "code_tags": []}} {"id": "book/ch19-03-pattern-syntax.md#matching-literals-1", "text": "The Rust Programming Language › Pattern Syntax › Matching Literals\n\nAs you saw in Chapter 6, you can match patterns against literals directly. The\nfollowing code gives some examples:\n```rust\n let x = 1;\n\n match x {\n 1 => println!(\"one\"),\n 2 => println!(\"two\"),\n 3 => println!(\"three\"),\n _ => println!(\"anything\"),\n }\n```\nThis code prints `one` because the value in `x` is `1`. This syntax is useful\nwhen you want your code to take an action if it gets a particular concrete\nvalue.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Pattern Syntax", "heading_path": ["Pattern Syntax", "Matching Literals"], "path": "ch19-03-pattern-syntax.md", "url": "https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#matching-literals", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch19-03-pattern-syntax.md#matching-named-variables-2", "text": "The Rust Programming Language › Pattern Syntax › Matching Named Variables\n\nNamed variables are irrefutable patterns that match any value, and we’ve used\nthem many times in this book. However, there is a complication when you use\nnamed variables in `match`, `if let`, or `while let` expressions. Because each\nof these kinds of expressions starts a new scope, variables declared as part of\na pattern inside these expressions will shadow those with the same name outside\nthe constructs, as is the case with all variables. In Listing 19-11, we declare\na variable named `x` with the value `Some(5)` and a variable `y` with the value\n`10`. We then create a `match` expression on the value `x`. Look at the\npatterns in the match arms and `println!` at the end, and try to figure out\nwhat the code will print before running this code or reading further.\nListing 19-11: A `match` expression with an arm that introduces a new variable which shadows an existing variable `y` (src/main.rs)\n```rust\n let x = Some(5);\n let y = 10;\n\n match x {\n Some(50) => println!(\"Got 50\"),\n Some(y) => println!(\"Matched, y = {y}\"),\n _ => println!(\"Default case, x = {x:?}\"),\n }\n\n println!(\"at the end: x = {x:?}, y = {y}\");\n```\nLet’s walk through what happens when the `match` expression runs. The pattern\nin the first match arm doesn’t match the defined value of `x`, so the code\ncontinues.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Pattern Syntax", "heading_path": ["Pattern Syntax", "Matching Named Variables"], "path": "ch19-03-pattern-syntax.md", "url": "https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#matching-named-variables", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch19-03-pattern-syntax.md#matching-named-variables-3", "text": "The Rust Programming Language › Pattern Syntax › Matching Named Variables\n\nThe pattern in the second match arm introduces a new variable named `y` that\nwill match any value inside a `Some` value. Because we’re in a new scope inside\nthe `match` expression, this is a new `y` variable, not the `y` we declared at\nthe beginning with the value `10`. This new `y` binding will match any value\ninside a `Some`, which is what we have in `x`. Therefore, this new `y` binds to\nthe inner value of the `Some` in `x`. That value is `5`, so the expression for\nthat arm executes and prints `Matched, y = 5`.\nIf `x` had been a `None` value instead of `Some(5)`, the patterns in the first\ntwo arms wouldn’t have matched, so the value would have matched to the\nunderscore. We didn’t introduce the `x` variable in the pattern of the\nunderscore arm, so the `x` in the expression is still the outer `x` that hasn’t\nbeen shadowed. In this hypothetical case, the `match` would print `Default case,\nx = None`.\nWhen the `match` expression is done, its scope ends, and so does the scope of\nthe inner `y`. The last `println!` produces `at the end: x = Some(5), y = 10`.\nTo create a `match` expression that compares the values of the outer `x` and\n`y`, rather than introducing a new variable that shadows the existing `y`\nvariable, we would need to use a match guard conditional instead. We’ll talk\nabout match guards later in the “Adding Conditionals with Match\nGuards” section.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Pattern Syntax", "heading_path": ["Pattern Syntax", "Matching Named Variables"], "path": "ch19-03-pattern-syntax.md", "url": "https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#matching-named-variables", "has_code": false, "code_tags": []}} {"id": "book/ch19-03-pattern-syntax.md#matching-multiple-patterns-4", "text": "The Rust Programming Language › Pattern Syntax › Matching Multiple Patterns\n\nIn `match` expressions, you can match multiple patterns using the `|` syntax,\nwhich is the pattern _or_ operator. For example, in the following code, we match\nthe value of `x` against the match arms, the first of which has an _or_ option,\nmeaning if the value of `x` matches either of the values in that arm, that\narm’s code will run:\n```rust\n let x = 1;\n\n match x {\n 1 | 2 => println!(\"one or two\"),\n 3 => println!(\"three\"),\n _ => println!(\"anything\"),\n }\n```\nThis code prints `one or two`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Pattern Syntax", "heading_path": ["Pattern Syntax", "Matching Multiple Patterns"], "path": "ch19-03-pattern-syntax.md", "url": "https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#matching-multiple-patterns", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch19-03-pattern-syntax.md#matching-ranges-of-values-with--5", "text": "The Rust Programming Language › Pattern Syntax › Matching Ranges of Values with `..=`\n\nThe `..=` syntax allows us to match to an inclusive range of values. In the\nfollowing code, when a pattern matches any of the values within the given\nrange, that arm will execute:\n```rust\n let x = 5;\n\n match x {\n 1..=5 => println!(\"one through five\"),\n _ => println!(\"something else\"),\n }\n```\nIf `x` is `1`, `2`, `3`, `4`, or `5`, the first arm will match. This syntax is\nmore convenient for multiple match values than using the `|` operator to\nexpress the same idea; if we were to use `|`, we would have to specify `1 | 2 |\n3 | 4 | 5`. Specifying a range is much shorter, especially if we want to match,\nsay, any number between 1 and 1,000!\nThe compiler checks that the range isn’t empty at compile time, and because the\nonly types for which Rust can tell if a range is empty or not are `char` and\nnumeric values, ranges are only allowed with numeric or `char` values.\nHere is an example using ranges of `char` values:\n```rust\n let x = 'c';\n\n match x {\n 'a'..='j' => println!(\"early ASCII letter\"),\n 'k'..='z' => println!(\"late ASCII letter\"),\n _ => println!(\"something else\"),\n }\n```\nRust can tell that `'c'` is within the first pattern’s range and prints `early\nASCII letter`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Pattern Syntax", "heading_path": ["Pattern Syntax", "Matching Ranges of Values with `..=`"], "path": "ch19-03-pattern-syntax.md", "url": "https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#matching-ranges-of-values-with-", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch19-03-pattern-syntax.md#structs-6", "text": "The Rust Programming Language › Pattern Syntax › Destructuring to Break Apart Values › Structs\n\nWe can also use patterns to destructure structs, enums, and tuples to use\ndifferent parts of these values. Let’s walk through each value.\nListing 19-12 shows a `Point` struct with two fields, `x` and `y`, that we can\nbreak apart using a pattern with a `let` statement.\nListing 19-12: Destructuring a struct’s fields into separate variables (src/main.rs)\n```rust\nstruct Point {\n x: i32,\n y: i32,\n}\n\nfn main() {\n let p = Point { x: 0, y: 7 };\n\n let Point { x: a, y: b } = p;\n assert_eq!(0, a);\n assert_eq!(7, b);\n}\n```\nThis code creates the variables `a` and `b` that match the values of the `x`\nand `y` fields of the `p` struct. This example shows that the names of the\nvariables in the pattern don’t have to match the field names of the struct.\nHowever, it’s common to match the variable names to the field names to make it\neasier to remember which variables came from which fields. Because of this\ncommon usage, and because writing `let Point { x: x, y: y } = p;` contains a\nlot of duplication, Rust has a shorthand for patterns that match struct fields:\nYou only need to list the name of the struct field, and the variables created\nfrom the pattern will have the same names. Listing 19-13 behaves in the same\nway as the code in Listing 19-12, but the variables created in the `let`\npattern are `x` and `y` instead of `a` and `b`.\nListing 19-13: Destructuring struct fields using struct field shorthand (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Pattern Syntax", "heading_path": ["Pattern Syntax", "Destructuring to Break Apart Values", "Structs"], "path": "ch19-03-pattern-syntax.md", "url": "https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#structs", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch19-03-pattern-syntax.md#structs-7", "text": "The Rust Programming Language › Pattern Syntax › Destructuring to Break Apart Values › Structs\n\n```rust\nstruct Point {\n x: i32,\n y: i32,\n}\n\nfn main() {\n let p = Point { x: 0, y: 7 };\n\n let Point { x, y } = p;\n assert_eq!(0, x);\n assert_eq!(7, y);\n}\n```\nThis code creates the variables `x` and `y` that match the `x` and `y` fields\nof the `p` variable. The outcome is that the variables `x` and `y` contain the\nvalues from the `p` struct.\nWe can also destructure with literal values as part of the struct pattern\nrather than creating variables for all the fields. Doing so allows us to test\nsome of the fields for particular values while creating variables to\ndestructure the other fields.\nIn Listing 19-14, we have a `match` expression that separates `Point` values\ninto three cases: points that lie directly on the `x` axis (which is true when\n`y = 0`), on the `y` axis (`x = 0`), or on neither axis.\nListing 19-14: Destructuring and matching literal values in one pattern (src/main.rs)\n```rust\nfn main() {\n let p = Point { x: 0, y: 7 };\n\n match p {\n Point { x, y: 0 } => println!(\"On the x axis at {x}\"),\n Point { x: 0, y } => println!(\"On the y axis at {y}\"),\n Point { x, y } => {\n println!(\"On neither axis: ({x}, {y})\");\n }\n }\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Pattern Syntax", "heading_path": ["Pattern Syntax", "Destructuring to Break Apart Values", "Structs"], "path": "ch19-03-pattern-syntax.md", "url": "https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#structs", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch19-03-pattern-syntax.md#enums-8", "text": "The Rust Programming Language › Pattern Syntax › Destructuring to Break Apart Values › Enums\n\nThe first arm will match any point that lies on the `x` axis by specifying that\nthe `y` field matches if its value matches the literal `0`. The pattern still\ncreates an `x` variable that we can use in the code for this arm.\nSimilarly, the second arm matches any point on the `y` axis by specifying that\nthe `x` field matches if its value is `0` and creates a variable `y` for the\nvalue of the `y` field. The third arm doesn’t specify any literals, so it\nmatches any other `Point` and creates variables for both the `x` and `y` fields.\nIn this example, the value `p` matches the second arm by virtue of `x`\ncontaining a `0`, so this code will print `On the y axis at 7`.\nRemember that a `match` expression stops checking arms once it has found the\nfirst matching pattern, so even though `Point { x: 0, y: 0 }` is on the `x` axis\nand the `y` axis, this code would only print `On the x axis at 0`.\nWe’ve destructured enums in this book (for example, Listing 6-5 in Chapter 6),\nbut we haven’t yet explicitly discussed that the pattern to destructure an enum\ncorresponds to the way the data stored within the enum is defined. As an\nexample, in Listing 19-15, we use the `Message` enum from Listing 6-2 and write\na `match` with patterns that will destructure each inner value.\nListing 19-15: Destructuring enum variants that hold different kinds of values (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Pattern Syntax", "heading_path": ["Pattern Syntax", "Destructuring to Break Apart Values", "Enums"], "path": "ch19-03-pattern-syntax.md", "url": "https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#enums", "has_code": false, "code_tags": []}} {"id": "book/ch19-03-pattern-syntax.md#enums-9", "text": "The Rust Programming Language › Pattern Syntax › Destructuring to Break Apart Values › Enums\n\n```rust\nenum Message {\n Quit,\n Move { x: i32, y: i32 },\n Write(String),\n ChangeColor(i32, i32, i32),\n}\n\nfn main() {\n let msg = Message::ChangeColor(0, 160, 255);\n\n match msg {\n Message::Quit => {\n println!(\"The Quit variant has no data to destructure.\");\n }\n Message::Move { x, y } => {\n println!(\"Move in the x direction {x} and in the y direction {y}\");\n }\n Message::Write(text) => {\n println!(\"Text message: {text}\");\n }\n Message::ChangeColor(r, g, b) => {\n println!(\"Change color to red {r}, green {g}, and blue {b}\");\n }\n }\n}\n```\nThis code will print `Change color to red 0, green 160, and blue 255`. Try\nchanging the value of `msg` to see the code from the other arms run.\nFor enum variants without any data, like `Message::Quit`, we can’t destructure\nthe value any further. We can only match on the literal `Message::Quit` value,\nand no variables are in that pattern.\nFor struct-like enum variants, such as `Message::Move`, we can use a pattern\nsimilar to the pattern we specify to match structs. After the variant name, we\nplace curly brackets and then list the fields with variables so that we break\napart the pieces to use in the code for this arm. Here we use the shorthand\nform as we did in Listing 19-13.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Pattern Syntax", "heading_path": ["Pattern Syntax", "Destructuring to Break Apart Values", "Enums"], "path": "ch19-03-pattern-syntax.md", "url": "https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#enums", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch19-03-pattern-syntax.md#nested-structs-and-enums-10", "text": "The Rust Programming Language › Pattern Syntax › Destructuring to Break Apart Values › Nested Structs and Enums\n\nFor tuple-like enum variants, like `Message::Write` that holds a tuple with one\nelement and `Message::ChangeColor` that holds a tuple with three elements, the\npattern is similar to the pattern we specify to match tuples. The number of\nvariables in the pattern must match the number of elements in the variant we’re\nmatching.\nSo far, our examples have all been matching structs or enums one level deep,\nbut matching can work on nested items too! For example, we can refactor the\ncode in Listing 19-15 to support RGB and HSV colors in the `ChangeColor`\nmessage, as shown in Listing 19-16.\nListing 19-16: Matching on nested enums\n```rust\nenum Color {\n Rgb(i32, i32, i32),\n Hsv(i32, i32, i32),\n}\n\nenum Message {\n Quit,\n Move { x: i32, y: i32 },\n Write(String),\n ChangeColor(Color),\n}\n\nfn main() {\n let msg = Message::ChangeColor(Color::Hsv(0, 160, 255));\n\n match msg {\n Message::ChangeColor(Color::Rgb(r, g, b)) => {\n println!(\"Change color to red {r}, green {g}, and blue {b}\");\n }\n Message::ChangeColor(Color::Hsv(h, s, v)) => {\n println!(\"Change color to hue {h}, saturation {s}, value {v}\");\n }\n _ => (),\n }\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Pattern Syntax", "heading_path": ["Pattern Syntax", "Destructuring to Break Apart Values", "Nested Structs and Enums"], "path": "ch19-03-pattern-syntax.md", "url": "https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#nested-structs-and-enums", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch19-03-pattern-syntax.md#structs-and-tuples-11", "text": "The Rust Programming Language › Pattern Syntax › Destructuring to Break Apart Values › Structs and Tuples\n\nThe pattern of the first arm in the `match` expression matches a\n`Message::ChangeColor` enum variant that contains a `Color::Rgb` variant; then,\nthe pattern binds to the three inner `i32` values. The pattern of the second\narm also matches a `Message::ChangeColor` enum variant, but the inner enum\nmatches `Color::Hsv` instead. We can specify these complex conditions in one\n`match` expression, even though two enums are involved.\nWe can mix, match, and nest destructuring patterns in even more complex ways.\nThe following example shows a complicated destructure where we nest structs and\ntuples inside a tuple and destructure all the primitive values out:\n```rust\n let ((feet, inches), Point { x, y }) = ((3, 10), Point { x: 3, y: -10 });\n```\nThis code lets us break complex types into their component parts so that we can\nuse the values we’re interested in separately.\nDestructuring with patterns is a convenient way to use pieces of values, such\nas the value from each field in a struct, separately from each other.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Pattern Syntax", "heading_path": ["Pattern Syntax", "Destructuring to Break Apart Values", "Structs and Tuples"], "path": "ch19-03-pattern-syntax.md", "url": "https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#structs-and-tuples", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch19-03-pattern-syntax.md#parts-of-a-value-with-a-nested-_-12", "text": "The Rust Programming Language › Pattern Syntax › Ignoring Values in a Pattern › Parts of a Value with a Nested `_`\n\nYou’ve seen that it’s sometimes useful to ignore values in a pattern, such as\nin the last arm of a `match`, to get a catch-all that doesn’t actually do\nanything but does account for all remaining possible values. There are a few\nways to ignore entire values or parts of values in a pattern: using the `_`\npattern (which you’ve seen), using the `_` pattern within another pattern,\nusing a name that starts with an underscore, or using `..` to ignore remaining\nparts of a value. Let’s explore how and why to use each of these patterns.\nWe’ve used the underscore as a wildcard pattern that will match any value but\nnot bind to the value. This is especially useful as the last arm in a `match`\nexpression, but we can also use it in any pattern, including function\nparameters, as shown in Listing 19-17.\nListing 19-17: Using `_` in a function signature (src/main.rs)\n```rust\nfn foo(_: i32, y: i32) {\n println!(\"This code only uses the y parameter: {y}\");\n}\n\nfn main() {\n foo(3, 4);\n}\n```\nThis code will completely ignore the value `3` passed as the first argument,\nand will print `This code only uses the y parameter: 4`.\nIn most cases when you no longer need a particular function parameter, you\nwould change the signature so that it doesn’t include the unused parameter.\nIgnoring a function parameter can be especially useful in cases when, for\nexample, you’re implementing a trait when you need a certain type signature but\nthe function body in your implementation doesn’t need one of the parameters.\nYou then avoid getting a compiler warning about unused function parameters, as\nyou would if you used a name instead.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Pattern Syntax", "heading_path": ["Pattern Syntax", "Ignoring Values in a Pattern", "Parts of a Value with a Nested `_`"], "path": "ch19-03-pattern-syntax.md", "url": "https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#parts-of-a-value-with-a-nested-_", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch19-03-pattern-syntax.md#parts-of-a-value-with-a-nested-_-13", "text": "The Rust Programming Language › Pattern Syntax › Ignoring Values in a Pattern › Parts of a Value with a Nested `_`\n\nWe can also use `_` inside another pattern to ignore just part of a value, for\nexample, when we want to test for only part of a value but have no use for the\nother parts in the corresponding code we want to run. Listing 19-18 shows code\nresponsible for managing a setting’s value. The business requirements are that\nthe user should not be allowed to overwrite an existing customization of a\nsetting but can unset the setting and give it a value if it is currently unset.\nListing 19-18: Using an underscore within patterns that match `Some` variants when we don’t need to use the value inside the `Some`\n```rust\n let mut setting_value = Some(5);\n let new_setting_value = Some(10);\n\n match (setting_value, new_setting_value) {\n (Some(_), Some(_)) => {\n println!(\"Can't overwrite an existing customized value\");\n }\n _ => {\n setting_value = new_setting_value;\n }\n }\n\n println!(\"setting is {setting_value:?}\");\n```\nThis code will print `Can't overwrite an existing customized value` and then\n`setting is Some(5)`. In the first match arm, we don’t need to match on or use\nthe values inside either `Some` variant, but we do need to test for the case\nwhen `setting_value` and `new_setting_value` are the `Some` variant. In that\ncase, we print the reason for not changing `setting_value`, and it doesn’t get\nchanged.\nIn all other cases (if either `setting_value` or `new_setting_value` is `None`)\nexpressed by the `_` pattern in the second arm, we want to allow\n`new_setting_value` to become `setting_value`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Pattern Syntax", "heading_path": ["Pattern Syntax", "Ignoring Values in a Pattern", "Parts of a Value with a Nested `_`"], "path": "ch19-03-pattern-syntax.md", "url": "https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#parts-of-a-value-with-a-nested-_", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch19-03-pattern-syntax.md#an-unused-variable-by-starting-its-name-with-_-14", "text": "The Rust Programming Language › Pattern Syntax › Ignoring Values in a Pattern › An Unused Variable by Starting Its Name with `_`\n\nWe can also use underscores in multiple places within one pattern to ignore\nparticular values. Listing 19-19 shows an example of ignoring the second and\nfourth values in a tuple of five items.\nListing 19-19: Ignoring multiple parts of a tuple\n```rust\n let numbers = (2, 4, 8, 16, 32);\n\n match numbers {\n (first, _, third, _, fifth) => {\n println!(\"Some numbers: {first}, {third}, {fifth}\");\n }\n }\n```\nThis code will print `Some numbers: 2, 8, 32`, and the values `4` and `16` will\nbe ignored.\nIf you create a variable but don’t use it anywhere, Rust will usually issue a\nwarning because an unused variable could be a bug. However, sometimes it’s\nuseful to be able to create a variable you won’t use yet, such as when you’re\nprototyping or just starting a project. In this situation, you can tell Rust\nnot to warn you about the unused variable by starting the name of the variable\nwith an underscore. In Listing 19-20, we create two unused variables, but when\nwe compile this code, we should only get a warning about one of them.\nListing 19-20: Starting a variable name with an underscore to avoid getting unused variable warnings (src/main.rs)\n```rust\nfn main() {\n let _x = 5;\n let y = 10;\n}\n```\nHere, we get a warning about not using the variable `y`, but we don’t get a\nwarning about not using `_x`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Pattern Syntax", "heading_path": ["Pattern Syntax", "Ignoring Values in a Pattern", "An Unused Variable by Starting Its Name with `_`"], "path": "ch19-03-pattern-syntax.md", "url": "https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#an-unused-variable-by-starting-its-name-with-_", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch19-03-pattern-syntax.md#remaining-parts-of-a-value-with--15", "text": "The Rust Programming Language › Pattern Syntax › Ignoring Values in a Pattern › Remaining Parts of a Value with `..`\n\nNote that there is a subtle difference between using only `_` and using a name\nthat starts with an underscore. The syntax `_x` still binds the value to the\nvariable, whereas `_` doesn’t bind at all. To show a case where this\ndistinction matters, Listing 19-21 will provide us with an error.\nListing 19-21: An unused variable starting with an underscore still binds the value, which might take ownership of the value.\n```rust,ignore,does_not_compile\n let s = Some(String::from(\"Hello!\"));\n\n if let Some(_s) = s {\n println!(\"found a string\");\n }\n\n println!(\"{s:?}\");\n```\nWe’ll receive an error because the `s` value will still be moved into `_s`,\nwhich prevents us from using `s` again. However, using the underscore by itself\ndoesn’t ever bind to the value. Listing 19-22 will compile without any errors\nbecause `s` doesn’t get moved into `_`.\nListing 19-22: Using an underscore does not bind the value.\n```rust\n let s = Some(String::from(\"Hello!\"));\n\n if let Some(_) = s {\n println!(\"found a string\");\n }\n\n println!(\"{s:?}\");\n```\nThis code works just fine because we never bind `s` to anything; it isn’t moved.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Pattern Syntax", "heading_path": ["Pattern Syntax", "Ignoring Values in a Pattern", "Remaining Parts of a Value with `..`"], "path": "ch19-03-pattern-syntax.md", "url": "https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#remaining-parts-of-a-value-with-", "has_code": true, "code_tags": ["rust", "rust,ignore,does_not_compile"]}} {"id": "book/ch19-03-pattern-syntax.md#remaining-parts-of-a-value-with--16", "text": "The Rust Programming Language › Pattern Syntax › Ignoring Values in a Pattern › Remaining Parts of a Value with `..`\n\nWith values that have many parts, we can use the `..` syntax to use specific\nparts and ignore the rest, avoiding the need to list underscores for each\nignored value. The `..` pattern ignores any parts of a value that we haven’t\nexplicitly matched in the rest of the pattern. In Listing 19-23, we have a\n`Point` struct that holds a coordinate in three-dimensional space. In the\n`match` expression, we want to operate only on the `x` coordinate and ignore\nthe values in the `y` and `z` fields.\nListing 19-23: Ignoring all fields of a `Point` except for `x` by using `..`\n```rust\n struct Point {\n x: i32,\n y: i32,\n z: i32,\n }\n\n let origin = Point { x: 0, y: 0, z: 0 };\n\n match origin {\n Point { x, .. } => println!(\"x is {x}\"),\n }\n```\nWe list the `x` value and then just include the `..` pattern. This is quicker\nthan having to list `y: _` and `z: _`, particularly when we’re working with\nstructs that have lots of fields in situations where only one or two fields are\nrelevant.\nThe syntax `..` will expand to as many values as it needs to be. Listing 19-24\nshows how to use `..` with a tuple.\nListing 19-24: Matching only the first and last values in a tuple and ignoring all other values (src/main.rs)\n```rust\nfn main() {\n let numbers = (2, 4, 8, 16, 32);\n\n match numbers {\n (first, .., last) => {\n println!(\"Some numbers: {first}, {last}\");\n }\n }\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Pattern Syntax", "heading_path": ["Pattern Syntax", "Ignoring Values in a Pattern", "Remaining Parts of a Value with `..`"], "path": "ch19-03-pattern-syntax.md", "url": "https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#remaining-parts-of-a-value-with-", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch19-03-pattern-syntax.md#remaining-parts-of-a-value-with--17", "text": "The Rust Programming Language › Pattern Syntax › Ignoring Values in a Pattern › Remaining Parts of a Value with `..`\n\nIn this code, the first and last values are matched with `first` and `last`.\nThe `..` will match and ignore everything in the middle.\nHowever, using `..` must be unambiguous. If it is unclear which values are\nintended for matching and which should be ignored, Rust will give us an error.\nListing 19-25 shows an example of using `..` ambiguously, so it will not\ncompile.\nListing 19-25: An attempt to use `..` in an ambiguous way (src/main.rs)\n```rust,ignore,does_not_compile\nfn main() {\n let numbers = (2, 4, 8, 16, 32);\n\n match numbers {\n (.., second, ..) => {\n println!(\"Some numbers: {second}\")\n },\n }\n}\n```\nWhen we compile this example, we get this error:\n```console\n$ cargo run\n Compiling patterns v0.1.0 (file:///projects/patterns)\nerror: `..` can only be used once per tuple pattern\n --> src/main.rs:5:22\n |\n5 | (.., second, ..) => {\n | -- ^^ can only be used once per tuple pattern\n | |\n | previously used here\n\nerror: could not compile `patterns` (bin \"patterns\") due to 1 previous error\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Pattern Syntax", "heading_path": ["Pattern Syntax", "Ignoring Values in a Pattern", "Remaining Parts of a Value with `..`"], "path": "ch19-03-pattern-syntax.md", "url": "https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#remaining-parts-of-a-value-with-", "has_code": true, "code_tags": ["console", "rust,ignore,does_not_compile"]}} {"id": "book/ch19-03-pattern-syntax.md#remaining-parts-of-a-value-with--18", "text": "The Rust Programming Language › Pattern Syntax › Ignoring Values in a Pattern › Remaining Parts of a Value with `..`\n\nIt’s impossible for Rust to determine how many values in the tuple to ignore\nbefore matching a value with `second` and then how many further values to\nignore thereafter. This code could mean that we want to ignore `2`, bind\n`second` to `4`, and then ignore `8`, `16`, and `32`; or that we want to ignore\n`2` and `4`, bind `second` to `8`, and then ignore `16` and `32`; and so forth.\nThe variable name `second` doesn’t mean anything special to Rust, so we get a\ncompiler error because using `..` in two places like this is ambiguous.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Pattern Syntax", "heading_path": ["Pattern Syntax", "Ignoring Values in a Pattern", "Remaining Parts of a Value with `..`"], "path": "ch19-03-pattern-syntax.md", "url": "https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#remaining-parts-of-a-value-with-", "has_code": false, "code_tags": []}} {"id": "book/ch19-03-pattern-syntax.md#adding-conditionals-with-match-guards-19", "text": "The Rust Programming Language › Pattern Syntax › Adding Conditionals with Match Guards\n\nA _match guard_ is an additional `if` condition, specified after the pattern in\na `match` arm, that must also match for that arm to be chosen. Match guards are\nuseful for expressing more complex ideas than a pattern alone allows. Note,\nhowever, that they are only available in `match` expressions, not `if let` or\n`while let` expressions.\nThe condition can use variables created in the pattern. Listing 19-26 shows a\n`match` where the first arm has the pattern `Some(x)` and also has a match\nguard of `if x % 2 == 0` (which will be `true` if the number is even).\nListing 19-26: Adding a match guard to a pattern\n```rust\n let num = Some(4);\n\n match num {\n Some(x) if x % 2 == 0 => println!(\"The number {x} is even\"),\n Some(x) => println!(\"The number {x} is odd\"),\n None => (),\n }\n```\nThis example will print `The number 4 is even`. When `num` is compared to the\npattern in the first arm, it matches because `Some(4)` matches `Some(x)`. Then,\nthe match guard checks whether the remainder of dividing `x` by 2 is equal to\n0, and because it is, the first arm is selected.\nIf `num` had been `Some(5)` instead, the match guard in the first arm would\nhave been `false` because the remainder of 5 divided by 2 is 1, which is not\nequal to 0. Rust would then go to the second arm, which would match because the\nsecond arm doesn’t have a match guard and therefore matches any `Some` variant.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Pattern Syntax", "heading_path": ["Pattern Syntax", "Adding Conditionals with Match Guards"], "path": "ch19-03-pattern-syntax.md", "url": "https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#adding-conditionals-with-match-guards", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch19-03-pattern-syntax.md#adding-conditionals-with-match-guards-20", "text": "The Rust Programming Language › Pattern Syntax › Adding Conditionals with Match Guards\n\nThere is no way to express the `if x % 2 == 0` condition within a pattern, so\nthe match guard gives us the ability to express this logic. The downside of\nthis additional expressiveness is that the compiler doesn’t try to check for\nexhaustiveness when match guard expressions are involved.\nWhen discussing Listing 19-11, we mentioned that we could use match guards to\nsolve our pattern-shadowing problem. Recall that we created a new variable\ninside the pattern in the `match` expression instead of using the variable\noutside the `match`. That new variable meant we couldn’t test against the value\nof the outer variable. Listing 19-27 shows how we can use a match guard to fix\nthis problem.\nListing 19-27: Using a match guard to test for equality with an outer variable (src/main.rs)\n```rust\nfn main() {\n let x = Some(5);\n let y = 10;\n\n match x {\n Some(50) => println!(\"Got 50\"),\n Some(n) if n == y => println!(\"Matched, n = {n}\"),\n _ => println!(\"Default case, x = {x:?}\"),\n }\n\n println!(\"at the end: x = {x:?}, y = {y}\");\n}\n```\nThis code will now print `Default case, x = Some(5)`. The pattern in the second\nmatch arm doesn’t introduce a new variable `y` that would shadow the outer `y`,\nmeaning we can use the outer `y` in the match guard. Instead of specifying the\npattern as `Some(y)`, which would have shadowed the outer `y`, we specify\n`Some(n)`. This creates a new variable `n` that doesn’t shadow anything because\nthere is no `n` variable outside the `match`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Pattern Syntax", "heading_path": ["Pattern Syntax", "Adding Conditionals with Match Guards"], "path": "ch19-03-pattern-syntax.md", "url": "https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#adding-conditionals-with-match-guards", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch19-03-pattern-syntax.md#adding-conditionals-with-match-guards-21", "text": "The Rust Programming Language › Pattern Syntax › Adding Conditionals with Match Guards\n\nThe match guard `if n == y` is not a pattern and therefore doesn’t introduce new\nvariables. This `y` _is_ the outer `y` rather than a new `y` shadowing it, and\nwe can look for a value that has the same value as the outer `y` by comparing\n`n` to `y`.\nYou can also use the _or_ operator `|` in a match guard to specify multiple\npatterns; the match guard condition will apply to all the patterns. Listing\n19-28 shows the precedence when combining a pattern that uses `|` with a match\nguard. The important part of this example is that the `if y` match guard\napplies to `4`, `5`, _and_ `6`, even though it might look like `if y` only\napplies to `6`.\nListing 19-28: Combining multiple patterns with a match guard\n```rust\n let x = 4;\n let y = false;\n\n match x {\n 4 | 5 | 6 if y => println!(\"yes\"),\n _ => println!(\"no\"),\n }\n```\nThe match condition states that the arm only matches if the value of `x` is\nequal to `4`, `5`, or `6` _and_ if `y` is `true`. When this code runs, the\npattern of the first arm matches because `x` is `4`, but the match guard `if y`\nis `false`, so the first arm is not chosen. The code moves on to the second\narm, which does match, and this program prints `no`. The reason is that the\n`if` condition applies to the whole pattern `4 | 5 | 6`, not just to the last\nvalue `6`. In other words, the precedence of a match guard in relation to a\npattern behaves like this:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Pattern Syntax", "heading_path": ["Pattern Syntax", "Adding Conditionals with Match Guards"], "path": "ch19-03-pattern-syntax.md", "url": "https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#adding-conditionals-with-match-guards", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch19-03-pattern-syntax.md#adding-conditionals-with-match-guards-22", "text": "The Rust Programming Language › Pattern Syntax › Adding Conditionals with Match Guards\n\n```text\n(4 | 5 | 6) if y => ...\n```\nrather than this:\n```text\n4 | 5 | (6 if y) => ...\n```\nAfter running the code, the precedence behavior is evident: If the match guard\nwere applied only to the final value in the list of values specified using the\n`|` operator, the arm would have matched, and the program would have printed\n`yes`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Pattern Syntax", "heading_path": ["Pattern Syntax", "Adding Conditionals with Match Guards"], "path": "ch19-03-pattern-syntax.md", "url": "https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#adding-conditionals-with-match-guards", "has_code": true, "code_tags": ["text"]}} {"id": "book/ch19-03-pattern-syntax.md#using--bindings-23", "text": "The Rust Programming Language › Pattern Syntax › Using `@` Bindings\n\nThe _at_ operator `@` lets us create a variable that holds a value at the same\ntime we’re testing that value for a pattern match. In Listing 19-29, we want to\ntest that a `Message::Hello` `id` field is within the range `3..=7`. We also\nwant to bind the value to the variable `id` so that we can use it in the code\nassociated with the arm.\nListing 19-29: Using `@` to bind to a value in a pattern while also testing it\n```rust\n enum Message {\n Hello { id: i32 },\n }\n\n let msg = Message::Hello { id: 5 };\n\n match msg {\n Message::Hello { id: id @ 3..=7 } => {\n println!(\"Found an id in range: {id}\")\n }\n Message::Hello { id: 10..=12 } => {\n println!(\"Found an id in another range\")\n }\n Message::Hello { id } => println!(\"Found some other id: {id}\"),\n }\n```\nThis example will print `Found an id in range: 5`. By specifying `id @` before\nthe range `3..=7`, we’re capturing whatever value matched the range in a\nvariable named `id` while also testing that the value matched the range pattern.\nIn the second arm, where we only have a range specified in the pattern, the code\nassociated with the arm doesn’t have a variable that contains the actual value\nof the `id` field. The `id` field’s value could have been 10, 11, or 12, but\nthe code that goes with that pattern doesn’t know which it is. The pattern code\nisn’t able to use the value from the `id` field because we haven’t saved the\n`id` value in a variable.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Pattern Syntax", "heading_path": ["Pattern Syntax", "Using `@` Bindings"], "path": "ch19-03-pattern-syntax.md", "url": "https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#using--bindings", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch19-03-pattern-syntax.md#using--bindings-24", "text": "The Rust Programming Language › Pattern Syntax › Using `@` Bindings\n\nIn the last arm, where we’ve specified a variable without a range, we do have\nthe value available to use in the arm’s code in a variable named `id`. The\nreason is that we’ve used the struct field shorthand syntax. But we haven’t\napplied any test to the value in the `id` field in this arm, as we did with the\nfirst two arms: Any value would match this pattern.\nUsing `@` lets us test a value and save it in a variable within one pattern.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Pattern Syntax", "heading_path": ["Pattern Syntax", "Using `@` Bindings"], "path": "ch19-03-pattern-syntax.md", "url": "https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#using--bindings", "has_code": false, "code_tags": []}} {"id": "book/ch19-03-pattern-syntax.md#summary-25", "text": "The Rust Programming Language › Summary\n\nRust’s patterns are very useful in distinguishing between different kinds of\ndata. When used in `match` expressions, Rust ensures that your patterns cover\nevery possible value, or your program won’t compile. Patterns in `let`\nstatements and function parameters make those constructs more useful, enabling\nthe destructuring of values into smaller parts and assigning those parts to\nvariables. We can create simple or complex patterns to suit our needs.\nNext, for the penultimate chapter of the book, we’ll look at some advanced\naspects of a variety of Rust’s features.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Pattern Syntax", "heading_path": ["Summary"], "path": "ch19-03-pattern-syntax.md", "url": "https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html#summary", "has_code": false, "code_tags": []}} {"id": "book/ch20-00-advanced-features.md#advanced-features-0", "text": "The Rust Programming Language › Advanced Features\n\nBy now, you’ve learned the most commonly used parts of the Rust programming\nlanguage. Before we do one more project, in Chapter 21, we’ll look at a few\naspects of the language you might run into every once in a while but may not\nuse every day. You can use this chapter as a reference for when you encounter\nany unknowns. The features covered here are useful in very specific situations.\nAlthough you might not reach for them often, we want to make sure you have a\ngrasp of all the features Rust has to offer.\nIn this chapter, we’ll cover:\n- Unsafe Rust: How to opt out of some of Rust’s guarantees and take\n responsibility for manually upholding those guarantees\n- Advanced traits: Associated types, default type parameters, fully qualified\n syntax, supertraits, and the newtype pattern in relation to traits\n- Advanced types: More about the newtype pattern, type aliases, the never type,\n and dynamically sized types\n- Advanced functions and closures: Function pointers and returning closures\n- Macros: Ways to define code that defines more code at compile time\nIt’s a panoply of Rust features with something for everyone! Let’s dive in!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Features", "heading_path": ["Advanced Features"], "path": "ch20-00-advanced-features.md", "url": "https://doc.rust-lang.org/book/ch20-00-advanced-features.html#advanced-features", "has_code": false, "code_tags": []}} {"id": "book/ch20-01-unsafe-rust.md#unsafe-rust-0", "text": "The Rust Programming Language › Unsafe Rust\n\nAll the code we’ve discussed so far has had Rust’s memory safety guarantees\nenforced at compile time. However, Rust has a second language hidden inside it\nthat doesn’t enforce these memory safety guarantees: It’s called _unsafe Rust_\nand works just like regular Rust but gives us extra superpowers.\nUnsafe Rust exists because, by nature, static analysis is conservative. When\nthe compiler tries to determine whether or not code upholds the guarantees,\nit’s better for it to reject some valid programs than to accept some invalid\nprograms. Although the code _might_ be okay, if the Rust compiler doesn’t have\nenough information to be confident, it will reject the code. In these cases,\nyou can use unsafe code to tell the compiler, “Trust me, I know what I’m\ndoing.” Be warned, however, that you use unsafe Rust at your own risk: If you\nuse unsafe code incorrectly, problems can occur due to memory unsafety, such as\nnull pointer dereferencing.\nAnother reason Rust has an unsafe alter ego is that the underlying computer\nhardware is inherently unsafe. If Rust didn’t let you do unsafe operations, you\ncouldn’t do certain tasks. Rust needs to allow you to do low-level systems\nprogramming, such as directly interacting with the operating system or even\nwriting your own operating system. Working with low-level systems programming\nis one of the goals of the language. Let’s explore what we can do with unsafe\nRust and how to do it.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unsafe Rust", "heading_path": ["Unsafe Rust"], "path": "ch20-01-unsafe-rust.md", "url": "https://doc.rust-lang.org/book/ch20-01-unsafe-rust.html#unsafe-rust", "has_code": false, "code_tags": []}} {"id": "book/ch20-01-unsafe-rust.md#performing-unsafe-superpowers-1", "text": "The Rust Programming Language › Unsafe Rust › Performing Unsafe Superpowers\n\nTo switch to unsafe Rust, use the `unsafe` keyword and then start a new block\nthat holds the unsafe code. You can take five actions in unsafe Rust that you\ncan’t in safe Rust, which we call _unsafe superpowers_. Those superpowers\ninclude the ability to:\n1. Dereference a raw pointer.\n1. Call an unsafe function or method.\n1. Access or modify a mutable static variable.\n1. Implement an unsafe trait.\n1. Access fields of `union`s.\nIt’s important to understand that `unsafe` doesn’t turn off the borrow checker\nor disable any of Rust’s other safety checks: If you use a reference in unsafe\ncode, it will still be checked. The `unsafe` keyword only gives you access to\nthese five features that are then not checked by the compiler for memory\nsafety. You’ll still get some degree of safety inside an unsafe block.\nIn addition, `unsafe` does not mean the code inside the block is necessarily\ndangerous or that it will definitely have memory safety problems: The intent is\nthat as the programmer, you’ll ensure that the code inside an `unsafe` block\nwill access memory in a valid way.\nPeople are fallible and mistakes will happen, but by requiring these five\nunsafe operations to be inside blocks annotated with `unsafe`, you’ll know that\nany errors related to memory safety must be within an `unsafe` block. Keep\n`unsafe` blocks small; you’ll be thankful later when you investigate memory\nbugs.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unsafe Rust", "heading_path": ["Unsafe Rust", "Performing Unsafe Superpowers"], "path": "ch20-01-unsafe-rust.md", "url": "https://doc.rust-lang.org/book/ch20-01-unsafe-rust.html#performing-unsafe-superpowers", "has_code": false, "code_tags": []}} {"id": "book/ch20-01-unsafe-rust.md#performing-unsafe-superpowers-2", "text": "The Rust Programming Language › Unsafe Rust › Performing Unsafe Superpowers\n\nTo isolate unsafe code as much as possible, it’s best to enclose such code\nwithin a safe abstraction and provide a safe API, which we’ll discuss later in\nthe chapter when we examine unsafe functions and methods. Parts of the standard\nlibrary are implemented as safe abstractions over unsafe code that has been\naudited. Wrapping unsafe code in a safe abstraction prevents uses of `unsafe`\nfrom leaking out into all the places that you or your users might want to use\nthe functionality implemented with `unsafe` code, because using a safe\nabstraction is safe.\nLet’s look at each of the five unsafe superpowers in turn. We’ll also look at\nsome abstractions that provide a safe interface to unsafe code.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unsafe Rust", "heading_path": ["Unsafe Rust", "Performing Unsafe Superpowers"], "path": "ch20-01-unsafe-rust.md", "url": "https://doc.rust-lang.org/book/ch20-01-unsafe-rust.html#performing-unsafe-superpowers", "has_code": false, "code_tags": []}} {"id": "book/ch20-01-unsafe-rust.md#dereferencing-a-raw-pointer-3", "text": "The Rust Programming Language › Unsafe Rust › Dereferencing a Raw Pointer\n\nIn Chapter 4, in the “Dangling References”\n section, we mentioned that the compiler ensures that references are always\nvalid. Unsafe Rust has two new types called _raw pointers_ that are similar to\nreferences. As with references, raw pointers can be immutable or mutable and\nare written as `*const T` and `*mut T`, respectively. The asterisk isn’t the\ndereference operator; it’s part of the type name. In the context of raw\npointers, _immutable_ means that the pointer can’t be directly assigned to\nafter being dereferenced.\nDifferent from references and smart pointers, raw pointers:\n- Are allowed to ignore the borrowing rules by having both immutable and\n mutable pointers or multiple mutable pointers to the same location\n- Aren’t guaranteed to point to valid memory\n- Are allowed to be null\n- Don’t implement any automatic cleanup\nBy opting out of having Rust enforce these guarantees, you can give up\nguaranteed safety in exchange for greater performance or the ability to\ninterface with another language or hardware where Rust’s guarantees don’t apply.\nListing 20-1 shows how to create an immutable and a mutable raw pointer.\nListing 20-1: Creating raw pointers with the raw borrow operators\n```rust\n let mut num = 5;\n\n let r1 = &raw const num;\n let r2 = &raw mut num;\n```\nNotice that we don’t include the `unsafe` keyword in this code. We can create\nraw pointers in safe code; we just can’t dereference raw pointers outside an\nunsafe block, as you’ll see in a bit.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unsafe Rust", "heading_path": ["Unsafe Rust", "Dereferencing a Raw Pointer"], "path": "ch20-01-unsafe-rust.md", "url": "https://doc.rust-lang.org/book/ch20-01-unsafe-rust.html#dereferencing-a-raw-pointer", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch20-01-unsafe-rust.md#dereferencing-a-raw-pointer-4", "text": "The Rust Programming Language › Unsafe Rust › Dereferencing a Raw Pointer\n\nWe’ve created raw pointers by using the raw borrow operators: `&raw const num`\ncreates a `*const i32` immutable raw pointer, and `&raw mut num` creates a `*mut\ni32` mutable raw pointer. Because we created them directly from a local\nvariable, we know these particular raw pointers are valid, but we can’t make\nthat assumption about just any raw pointer.\nTo demonstrate this, next we’ll create a raw pointer whose validity we can’t be\nso certain of, using the keyword `as` to cast a value instead of using the raw\nborrow operator. Listing 20-2 shows how to create a raw pointer to an arbitrary\nlocation in memory. Trying to use arbitrary memory is undefined: There might be\ndata at that address or there might not, the compiler might optimize the code\nso that there is no memory access, or the program might terminate with a\nsegmentation fault. Usually, there is no good reason to write code like this,\nespecially in cases where you can use a raw borrow operator instead, but it is\npossible.\nListing 20-2: Creating a raw pointer to an arbitrary memory address\n```rust\n let address = 0x012345usize;\n let r = address as *const i32;\n```\nRecall that we can create raw pointers in safe code, but we can’t dereference\nraw pointers and read the data being pointed to. In Listing 20-3, we use the\ndereference operator `*` on a raw pointer that requires an `unsafe` block.\nListing 20-3: Dereferencing raw pointers within an `unsafe` block\n```rust\n let mut num = 5;\n\n let r1 = &raw const num;\n let r2 = &raw mut num;\n\n unsafe {\n println!(\"r1 is: {}\", *r1);\n println!(\"r2 is: {}\", *r2);\n }\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unsafe Rust", "heading_path": ["Unsafe Rust", "Dereferencing a Raw Pointer"], "path": "ch20-01-unsafe-rust.md", "url": "https://doc.rust-lang.org/book/ch20-01-unsafe-rust.html#dereferencing-a-raw-pointer", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch20-01-unsafe-rust.md#dereferencing-a-raw-pointer-5", "text": "The Rust Programming Language › Unsafe Rust › Dereferencing a Raw Pointer\n\nCreating a pointer does no harm; it’s only when we try to access the value that\nit points at that we might end up dealing with an invalid value.\nNote also that in Listings 20-1 and 20-3, we created `*const i32` and `*mut\ni32` raw pointers that both pointed to the same memory location, where `num` is\nstored. If we instead tried to create an immutable and a mutable reference to\n`num`, the code would not have compiled because Rust’s ownership rules don’t\nallow a mutable reference at the same time as any immutable references. With\nraw pointers, we can create a mutable pointer and an immutable pointer to the\nsame location and change data through the mutable pointer, potentially creating\na data race. Be careful!\nWith all of these dangers, why would you ever use raw pointers? One major use\ncase is when interfacing with C code, as you’ll see in the next section.\nAnother case is when building up safe abstractions that the borrow checker\ndoesn’t understand. We’ll introduce unsafe functions and then look at an\nexample of a safe abstraction that uses unsafe code.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unsafe Rust", "heading_path": ["Unsafe Rust", "Dereferencing a Raw Pointer"], "path": "ch20-01-unsafe-rust.md", "url": "https://doc.rust-lang.org/book/ch20-01-unsafe-rust.html#dereferencing-a-raw-pointer", "has_code": false, "code_tags": []}} {"id": "book/ch20-01-unsafe-rust.md#calling-an-unsafe-function-or-method-6", "text": "The Rust Programming Language › Unsafe Rust › Calling an Unsafe Function or Method\n\nThe second type of operation you can perform in an unsafe block is calling\nunsafe functions. Unsafe functions and methods look exactly like regular\nfunctions and methods, but they have an extra `unsafe` before the rest of the\ndefinition. The `unsafe` keyword in this context indicates the function has\nrequirements we need to uphold when we call this function, because Rust can’t\nguarantee we’ve met these requirements. By calling an unsafe function within an\n`unsafe` block, we’re saying that we’ve read this function’s documentation and\nwe take responsibility for upholding the function’s contracts.\nHere is an unsafe function named `dangerous` that doesn’t do anything in its\nbody:\n```rust\n unsafe fn dangerous() {}\n\n unsafe {\n dangerous();\n }\n```\nWe must call the `dangerous` function within a separate `unsafe` block. If we\ntry to call `dangerous` without the `unsafe` block, we’ll get an error:\n```console\n$ cargo run\n Compiling unsafe-example v0.1.0 (file:///projects/unsafe-example)\nerror[E0133]: call to unsafe function `dangerous` is unsafe and requires unsafe block\n --> src/main.rs:4:5\n |\n4 | dangerous();\n | ^^^^^^^^^^^ call to unsafe function\n |\n = note: consult the function's documentation for information on how to avoid undefined behavior\n\nFor more information about this error, try `rustc --explain E0133`.\nerror: could not compile `unsafe-example` (bin \"unsafe-example\") due to 1 previous error\n```\nWith the `unsafe` block, we’re asserting to Rust that we’ve read the function’s\ndocumentation, we understand how to use it properly, and we’ve verified that\nwe’re fulfilling the contract of the function.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unsafe Rust", "heading_path": ["Unsafe Rust", "Calling an Unsafe Function or Method"], "path": "ch20-01-unsafe-rust.md", "url": "https://doc.rust-lang.org/book/ch20-01-unsafe-rust.html#calling-an-unsafe-function-or-method", "has_code": true, "code_tags": ["console", "rust"]}} {"id": "book/ch20-01-unsafe-rust.md#creating-a-safe-abstraction-over-unsafe-code-7", "text": "The Rust Programming Language › Unsafe Rust › Calling an Unsafe Function or Method › Creating a Safe Abstraction over Unsafe Code\n\nTo perform unsafe operations in the body of an `unsafe` function, you still\nneed to use an `unsafe` block, just as within a regular function, and the\ncompiler will warn you if you forget. This helps us keep `unsafe` blocks as\nsmall as possible, as unsafe operations may not be needed across the whole\nfunction body.\nJust because a function contains unsafe code doesn’t mean we need to mark the\nentire function as unsafe. In fact, wrapping unsafe code in a safe function is\na common abstraction. As an example, let’s study the `split_at_mut` function\nfrom the standard library, which requires some unsafe code. We’ll explore how\nwe might implement it. This safe method is defined on mutable slices: It takes\none slice and makes it two by splitting the slice at the index given as an\nargument. Listing 20-4 shows how to use `split_at_mut`.\nListing 20-4: Using the safe `split_at_mut` function\n```rust\n let mut v = vec![1, 2, 3, 4, 5, 6];\n\n let r = &mut v[..];\n\n let (a, b) = r.split_at_mut(3);\n\n assert_eq!(a, &mut [1, 2, 3]);\n assert_eq!(b, &mut [4, 5, 6]);\n```\nWe can’t implement this function using only safe Rust. An attempt might look\nsomething like Listing 20-5, which won’t compile. For simplicity, we’ll\nimplement `split_at_mut` as a function rather than a method and only for slices\nof `i32` values rather than for a generic type `T`.\nListing 20-5: An attempted implementation of `split_at_mut` using only safe Rust", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unsafe Rust", "heading_path": ["Unsafe Rust", "Calling an Unsafe Function or Method", "Creating a Safe Abstraction over Unsafe Code"], "path": "ch20-01-unsafe-rust.md", "url": "https://doc.rust-lang.org/book/ch20-01-unsafe-rust.html#creating-a-safe-abstraction-over-unsafe-code", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch20-01-unsafe-rust.md#creating-a-safe-abstraction-over-unsafe-code-8", "text": "The Rust Programming Language › Unsafe Rust › Calling an Unsafe Function or Method › Creating a Safe Abstraction over Unsafe Code\n\n```rust,ignore,does_not_compile\nfn split_at_mut(values: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {\n let len = values.len();\n\n assert!(mid <= len);\n\n (&mut values[..mid], &mut values[mid..])\n}\n```\nThis function first gets the total length of the slice. Then, it asserts that\nthe index given as a parameter is within the slice by checking whether it’s\nless than or equal to the length. The assertion means that if we pass an index\nthat is greater than the length to split the slice at, the function will panic\nbefore it attempts to use that index.\nThen, we return two mutable slices in a tuple: one from the start of the\noriginal slice to the `mid` index and another from `mid` to the end of the\nslice.\nWhen we try to compile the code in Listing 20-5, we’ll get an error:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unsafe Rust", "heading_path": ["Unsafe Rust", "Calling an Unsafe Function or Method", "Creating a Safe Abstraction over Unsafe Code"], "path": "ch20-01-unsafe-rust.md", "url": "https://doc.rust-lang.org/book/ch20-01-unsafe-rust.html#creating-a-safe-abstraction-over-unsafe-code", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch20-01-unsafe-rust.md#creating-a-safe-abstraction-over-unsafe-code-9", "text": "The Rust Programming Language › Unsafe Rust › Calling an Unsafe Function or Method › Creating a Safe Abstraction over Unsafe Code\n\n```console\n$ cargo run\n Compiling unsafe-example v0.1.0 (file:///projects/unsafe-example)\nerror[E0499]: cannot borrow `*values` as mutable more than once at a time\n --> src/main.rs:6:31\n |\n1 | fn split_at_mut(values: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {\n | - let's call the lifetime of this reference `'1`\n...\n6 | (&mut values[..mid], &mut values[mid..])\n | --------------------------^^^^^^--------\n | | | |\n | | | second mutable borrow occurs here\n | | first mutable borrow occurs here\n | returning this value requires that `*values` is borrowed for `'1`\n |\n = help: use `.split_at_mut(position)` to obtain two mutable non-overlapping sub-slices\n\nFor more information about this error, try `rustc --explain E0499`.\nerror: could not compile `unsafe-example` (bin \"unsafe-example\") due to 1 previous error\n```\nRust’s borrow checker can’t understand that we’re borrowing different parts of\nthe slice; it only knows that we’re borrowing from the same slice twice.\nBorrowing different parts of a slice is fundamentally okay because the two\nslices aren’t overlapping, but Rust isn’t smart enough to know this. When we\nknow code is okay, but Rust doesn’t, it’s time to reach for unsafe code.\nListing 20-6 shows how to use an `unsafe` block, a raw pointer, and some calls\nto unsafe functions to make the implementation of `split_at_mut` work.\nListing 20-6: Using unsafe code in the implementation of the `split_at_mut` function", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unsafe Rust", "heading_path": ["Unsafe Rust", "Calling an Unsafe Function or Method", "Creating a Safe Abstraction over Unsafe Code"], "path": "ch20-01-unsafe-rust.md", "url": "https://doc.rust-lang.org/book/ch20-01-unsafe-rust.html#creating-a-safe-abstraction-over-unsafe-code", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch20-01-unsafe-rust.md#creating-a-safe-abstraction-over-unsafe-code-10", "text": "The Rust Programming Language › Unsafe Rust › Calling an Unsafe Function or Method › Creating a Safe Abstraction over Unsafe Code\n\n```rust\nuse std::slice;\n\nfn split_at_mut(values: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {\n let len = values.len();\n let ptr = values.as_mut_ptr();\n\n assert!(mid <= len);\n\n unsafe {\n (\n slice::from_raw_parts_mut(ptr, mid),\n slice::from_raw_parts_mut(ptr.add(mid), len - mid),\n )\n }\n}\n```\nRecall from “The Slice Type” section in\nChapter 4 that a slice is a pointer to some data and the length of the slice.\nWe use the `len` method to get the length of a slice and the `as_mut_ptr`\nmethod to access the raw pointer of a slice. In this case, because we have a\nmutable slice to `i32` values, `as_mut_ptr` returns a raw pointer with the type\n`*mut i32`, which we’ve stored in the variable `ptr`.\nWe keep the assertion that the `mid` index is within the slice. Then, we get to\nthe unsafe code: The `slice::from_raw_parts_mut` function takes a raw pointer\nand a length, and it creates a slice. We use this function to create a slice\nthat starts from `ptr` and is `mid` items long. Then, we call the `add` method\non `ptr` with `mid` as an argument to get a raw pointer that starts at `mid`,\nand we create a slice using that pointer and the remaining number of items\nafter `mid` as the length.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unsafe Rust", "heading_path": ["Unsafe Rust", "Calling an Unsafe Function or Method", "Creating a Safe Abstraction over Unsafe Code"], "path": "ch20-01-unsafe-rust.md", "url": "https://doc.rust-lang.org/book/ch20-01-unsafe-rust.html#creating-a-safe-abstraction-over-unsafe-code", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch20-01-unsafe-rust.md#using-extern-functions-to-call-external-code-11", "text": "The Rust Programming Language › Unsafe Rust › Calling an Unsafe Function or Method › Using `extern` Functions to Call External Code\n\nThe function `slice::from_raw_parts_mut` is unsafe because it takes a raw\npointer and must trust that this pointer is valid. The `add` method on raw\npointers is also unsafe because it must trust that the offset location is also\na valid pointer. Therefore, we had to put an `unsafe` block around our calls to\n`slice::from_raw_parts_mut` and `add` so that we could call them. By looking at\nthe code and by adding the assertion that `mid` must be less than or equal to\n`len`, we can tell that all the raw pointers used within the `unsafe` block\nwill be valid pointers to data within the slice. This is an acceptable and\nappropriate use of `unsafe`.\nNote that we don’t need to mark the resultant `split_at_mut` function as\n`unsafe`, and we can call this function from safe Rust. We’ve created a safe\nabstraction to the unsafe code with an implementation of the function that uses\n`unsafe` code in a safe way, because it creates only valid pointers from the\ndata this function has access to.\nIn contrast, the use of `slice::from_raw_parts_mut` in Listing 20-7 would\nlikely crash when the slice is used. This code takes an arbitrary memory\nlocation and creates a slice 10,000 items long.\nListing 20-7: Creating a slice from an arbitrary memory location\n```rust\n use std::slice;\n\n let address = 0x01234usize;\n let r = address as *mut i32;\n\n let values: &[i32] = unsafe { slice::from_raw_parts_mut(r, 10000) };\n```\nWe don’t own the memory at this arbitrary location, and there is no guarantee\nthat the slice this code creates contains valid `i32` values. Attempting to use\n`values` as though it’s a valid slice results in undefined behavior.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unsafe Rust", "heading_path": ["Unsafe Rust", "Calling an Unsafe Function or Method", "Using `extern` Functions to Call External Code"], "path": "ch20-01-unsafe-rust.md", "url": "https://doc.rust-lang.org/book/ch20-01-unsafe-rust.html#using-extern-functions-to-call-external-code", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch20-01-unsafe-rust.md#using-extern-functions-to-call-external-code-12", "text": "The Rust Programming Language › Unsafe Rust › Calling an Unsafe Function or Method › Using `extern` Functions to Call External Code\n\nSometimes your Rust code might need to interact with code written in another\nlanguage. For this, Rust has the keyword `extern` that facilitates the creation\nand use of a _Foreign Function Interface (FFI)_, which is a way for a\nprogramming language to define functions and enable a different (foreign)\nprogramming language to call those functions.\nListing 20-8 demonstrates how to set up an integration with the `abs` function\nfrom the C standard library. Functions declared within `extern` blocks are\ngenerally unsafe to call from Rust code, so `extern` blocks must also be marked\n`unsafe`. The reason is that other languages don’t enforce Rust’s rules and\nguarantees, and Rust can’t check them, so responsibility falls on the\nprogrammer to ensure safety.\nListing 20-8: Declaring and calling an `extern` function defined in another language (src/main.rs)\n```rust\nunsafe extern \"C\" {\n fn abs(input: i32) -> i32;\n}\n\nfn main() {\n unsafe {\n println!(\"Absolute value of -3 according to C: {}\", abs(-3));\n }\n}\n```\nWithin the `unsafe extern \"C\"` block, we list the names and signatures of\nexternal functions from another language we want to call. The `\"C\"` part\ndefines which _application binary interface (ABI)_ the external function uses:\nThe ABI defines how to call the function at the assembly level. The `\"C\"` ABI\nis the most common and follows the C programming language’s ABI. Information\nabout all the ABIs Rust supports is available in the Rust Reference.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unsafe Rust", "heading_path": ["Unsafe Rust", "Calling an Unsafe Function or Method", "Using `extern` Functions to Call External Code"], "path": "ch20-01-unsafe-rust.md", "url": "https://doc.rust-lang.org/book/ch20-01-unsafe-rust.html#using-extern-functions-to-call-external-code", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch20-01-unsafe-rust.md#calling-rust-functions-from-other-languages-13", "text": "The Rust Programming Language › Unsafe Rust › Calling an Unsafe Function or Method › Calling Rust Functions from Other Languages\n\nEvery item declared within an `unsafe extern` block is implicitly unsafe.\nHowever, some FFI functions *are* safe to call. For example, the `abs` function\nfrom C’s standard library does not have any memory safety considerations, and we\nknow it can be called with any `i32`. In cases like this, we can use the `safe`\nkeyword to say that this specific function is safe to call even though it is in\nan `unsafe extern` block. Once we make that change, calling it no longer\nrequires an `unsafe` block, as shown in Listing 20-9.\nListing 20-9: Explicitly marking a function as `safe` within an `unsafe extern` block and calling it safely (src/main.rs)\n```rust\nunsafe extern \"C\" {\n safe fn abs(input: i32) -> i32;\n}\n\nfn main() {\n println!(\"Absolute value of -3 according to C: {}\", abs(-3));\n}\n```\nMarking a function as `safe` does not inherently make it safe! Instead, it is\nlike a promise you are making to Rust that it is safe. It is still your\nresponsibility to make sure that promise is kept!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unsafe Rust", "heading_path": ["Unsafe Rust", "Calling an Unsafe Function or Method", "Calling Rust Functions from Other Languages"], "path": "ch20-01-unsafe-rust.md", "url": "https://doc.rust-lang.org/book/ch20-01-unsafe-rust.html#calling-rust-functions-from-other-languages", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch20-01-unsafe-rust.md#calling-rust-functions-from-other-languages-14", "text": "The Rust Programming Language › Unsafe Rust › Calling an Unsafe Function or Method › Calling Rust Functions from Other Languages\n\nWe can also use `extern` to create an interface that allows other languages to\ncall Rust functions. Instead of creating a whole `extern` block, we add the\n`extern` keyword and specify the ABI to use just before the `fn` keyword for\nthe relevant function. We also need to add an `#[unsafe(no_mangle)]` annotation\nto tell the Rust compiler not to mangle the name of this function. _Mangling_\nis when a compiler changes the name we’ve given a function to a different name\nthat contains more information for other parts of the compilation process to\nconsume but is less human readable. Every programming language compiler mangles\nnames slightly differently, so for a Rust function to be nameable by other\nlanguages, we must disable the Rust compiler’s name mangling. This is unsafe\nbecause there might be name collisions across libraries without the built-in\nmangling, so it is our responsibility to make sure the name we choose is safe\nto export without mangling.\nIn the following example, we make the `call_from_c` function accessible from C\ncode, after it’s compiled to a shared library and linked from C:\n```\n#[unsafe(no_mangle)]\npub extern \"C\" fn call_from_c() {\n println!(\"Just called a Rust function from C!\");\n}\n```\nThis usage of `extern` requires `unsafe` only in the attribute, not on the\n`extern` block.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unsafe Rust", "heading_path": ["Unsafe Rust", "Calling an Unsafe Function or Method", "Calling Rust Functions from Other Languages"], "path": "ch20-01-unsafe-rust.md", "url": "https://doc.rust-lang.org/book/ch20-01-unsafe-rust.html#calling-rust-functions-from-other-languages", "has_code": true, "code_tags": ["(untagged)"]}} {"id": "book/ch20-01-unsafe-rust.md#accessing-or-modifying-a-mutable-static-variable-15", "text": "The Rust Programming Language › Unsafe Rust › Accessing or Modifying a Mutable Static Variable\n\nIn this book, we’ve not yet talked about global variables, which Rust does\nsupport but which can be problematic with Rust’s ownership rules. If two\nthreads are accessing the same mutable global variable, it can cause a data\nrace.\nIn Rust, global variables are called _static_ variables. Listing 20-10 shows an\nexample declaration and use of a static variable with a string slice as a\nvalue.\nListing 20-10: Defining and using an immutable static variable (src/main.rs)\n```rust\nstatic HELLO_WORLD: &str = \"Hello, world!\";\n\nfn main() {\n println!(\"value is: {HELLO_WORLD}\");\n}\n```\nStatic variables are similar to constants, which we discussed in the\n“Declaring Constants” section in Chapter 3. The\nnames of static variables are in `SCREAMING_SNAKE_CASE` by convention. Static\nvariables can only store references with the `'static` lifetime, which means\nthe Rust compiler can figure out the lifetime and we aren’t required to\nannotate it explicitly. Accessing an immutable static variable is safe.\nA subtle difference between constants and immutable static variables is that\nvalues in a static variable have a fixed address in memory. Using the value\nwill always access the same data. Constants, on the other hand, are allowed to\nduplicate their data whenever they’re used. Another difference is that static\nvariables can be mutable. Accessing and modifying mutable static variables is\n_unsafe_. Listing 20-11 shows how to declare, access, and modify a mutable\nstatic variable named `COUNTER`.\nListing 20-11: Reading from or writing to a mutable static variable is unsafe. (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unsafe Rust", "heading_path": ["Unsafe Rust", "Accessing or Modifying a Mutable Static Variable"], "path": "ch20-01-unsafe-rust.md", "url": "https://doc.rust-lang.org/book/ch20-01-unsafe-rust.html#accessing-or-modifying-a-mutable-static-variable", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch20-01-unsafe-rust.md#accessing-or-modifying-a-mutable-static-variable-16", "text": "The Rust Programming Language › Unsafe Rust › Accessing or Modifying a Mutable Static Variable\n\n```rust\nstatic mut COUNTER: u32 = 0;\n\n/// SAFETY: Calling this from more than a single thread at a time is undefined\n/// behavior, so you *must* guarantee you only call it from a single thread at\n/// a time.\nunsafe fn add_to_count(inc: u32) {\n unsafe {\n COUNTER += inc;\n }\n}\n\nfn main() {\n unsafe {\n // SAFETY: This is only called from a single thread in `main`.\n add_to_count(3);\n println!(\"COUNTER: {}\", *(&raw const COUNTER));\n }\n}\n```\nAs with regular variables, we specify mutability using the `mut` keyword. Any\ncode that reads or writes from `COUNTER` must be within an `unsafe` block. The\ncode in Listing 20-11 compiles and prints `COUNTER: 3` as we would expect\nbecause it’s single threaded. Having multiple threads access `COUNTER` would\nlikely result in data races, so it is undefined behavior. Therefore, we need to\nmark the entire function as `unsafe` and document the safety limitation so that\nanyone calling the function knows what they are and are not allowed to do\nsafely.\nWhenever we write an unsafe function, it is idiomatic to write a comment\nstarting with `SAFETY` and explaining what the caller needs to do to call the\nfunction safely. Likewise, whenever we perform an unsafe operation, it is\nidiomatic to write a comment starting with `SAFETY` to explain how the safety\nrules are upheld.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unsafe Rust", "heading_path": ["Unsafe Rust", "Accessing or Modifying a Mutable Static Variable"], "path": "ch20-01-unsafe-rust.md", "url": "https://doc.rust-lang.org/book/ch20-01-unsafe-rust.html#accessing-or-modifying-a-mutable-static-variable", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch20-01-unsafe-rust.md#accessing-or-modifying-a-mutable-static-variable-17", "text": "The Rust Programming Language › Unsafe Rust › Accessing or Modifying a Mutable Static Variable\n\nAdditionally, the compiler will deny by default any attempt to create\nreferences to a mutable static variable through a compiler lint. You must\neither explicitly opt out of that lint’s protections by adding an\n`#[allow(static_mut_refs)]` annotation or access the mutable static variable\nvia a raw pointer created with one of the raw borrow operators. That includes\ncases where the reference is created invisibly, as when it is used in the\n`println!` in this code listing. Requiring references to static mutable\nvariables to be created via raw pointers helps make the safety requirements for\nusing them more obvious.\nWith mutable data that is globally accessible, it’s difficult to ensure that\nthere are no data races, which is why Rust considers mutable static variables\nto be unsafe. Where possible, it’s preferable to use the concurrency techniques\nand thread-safe smart pointers we discussed in Chapter 16 so that the compiler\nchecks that data access from different threads is done safely.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unsafe Rust", "heading_path": ["Unsafe Rust", "Accessing or Modifying a Mutable Static Variable"], "path": "ch20-01-unsafe-rust.md", "url": "https://doc.rust-lang.org/book/ch20-01-unsafe-rust.html#accessing-or-modifying-a-mutable-static-variable", "has_code": false, "code_tags": []}} {"id": "book/ch20-01-unsafe-rust.md#implementing-an-unsafe-trait-18", "text": "The Rust Programming Language › Unsafe Rust › Implementing an Unsafe Trait\n\nWe can use `unsafe` to implement an unsafe trait. A trait is unsafe when at\nleast one of its methods has some invariant that the compiler can’t verify. We\ndeclare that a trait is `unsafe` by adding the `unsafe` keyword before `trait`\nand marking the implementation of the trait as `unsafe` too, as shown in\nListing 20-12.\nListing 20-12: Defining and implementing an unsafe trait\n```rust\nunsafe trait Foo {\n // methods go here\n}\n\nunsafe impl Foo for i32 {\n // method implementations go here\n}\n```\nBy using `unsafe impl`, we’re promising that we’ll uphold the invariants that\nthe compiler can’t verify.\nAs an example, recall the `Send` and `Sync` marker traits we discussed in the\n“Extensible Concurrency with `Send` and `Sync`”\nsection in Chapter 16: The compiler implements these traits automatically if\nour types are composed entirely of other types that implement `Send` and\n`Sync`. If we implement a type that contains a type that does not implement\n`Send` or `Sync`, such as raw pointers, and we want to mark that type as `Send`\nor `Sync`, we must use `unsafe`. Rust can’t verify that our type upholds the\nguarantees that it can be safely sent across threads or accessed from multiple\nthreads; therefore, we need to do those checks manually and indicate as such\nwith `unsafe`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unsafe Rust", "heading_path": ["Unsafe Rust", "Implementing an Unsafe Trait"], "path": "ch20-01-unsafe-rust.md", "url": "https://doc.rust-lang.org/book/ch20-01-unsafe-rust.html#implementing-an-unsafe-trait", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch20-01-unsafe-rust.md#accessing-fields-of-a-union-19", "text": "The Rust Programming Language › Unsafe Rust › Accessing Fields of a Union\n\nThe final action that works only with `unsafe` is accessing fields of a union.\nA *union* is similar to a `struct`, but only one declared field is used in a\nparticular instance at one time. Unions are primarily used to interface with\nunions in C code. Accessing union fields is unsafe because Rust can’t guarantee\nthe type of the data currently being stored in the union instance. You can\nlearn more about unions in the Rust Reference.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unsafe Rust", "heading_path": ["Unsafe Rust", "Accessing Fields of a Union"], "path": "ch20-01-unsafe-rust.md", "url": "https://doc.rust-lang.org/book/ch20-01-unsafe-rust.html#accessing-fields-of-a-union", "has_code": false, "code_tags": []}} {"id": "book/ch20-01-unsafe-rust.md#using-miri-to-check-unsafe-code-20", "text": "The Rust Programming Language › Unsafe Rust › Using Miri to Check Unsafe Code\n\nWhen writing unsafe code, you might want to check that what you have written\nactually is safe and correct. One of the best ways to do that is to use Miri,\nan official Rust tool for detecting undefined behavior. Whereas the borrow\nchecker is a _static_ tool that works at compile time, Miri is a _dynamic_\ntool that works at runtime. It checks your code by running your program, or\nits test suite, and detecting when you violate the rules it understands about\nhow Rust should work.\nUsing Miri requires a nightly build of Rust (which we talk about more in\nAppendix G: How Rust is Made and “Nightly Rust”). You\ncan install both a nightly version of Rust and the Miri tool by typing `rustup\n+nightly component add miri`. This does not change what version of Rust your\nproject uses; it only adds the tool to your system so you can use it when you\nwant to. You can run Miri on a project by typing `cargo +nightly miri run` or\n`cargo +nightly miri test`.\nFor an example of how helpful this can be, consider what happens when we run it\nagainst Listing 20-7.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unsafe Rust", "heading_path": ["Unsafe Rust", "Using Miri to Check Unsafe Code"], "path": "ch20-01-unsafe-rust.md", "url": "https://doc.rust-lang.org/book/ch20-01-unsafe-rust.html#using-miri-to-check-unsafe-code", "has_code": false, "code_tags": []}} {"id": "book/ch20-01-unsafe-rust.md#using-miri-to-check-unsafe-code-21", "text": "The Rust Programming Language › Unsafe Rust › Using Miri to Check Unsafe Code\n\n```console\n$ cargo +nightly miri run\n Compiling unsafe-example v0.1.0 (file:///projects/unsafe-example)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.17s\n Running `file:///home/.rustup/toolchains/nightly/bin/cargo-miri runner target/miri/debug/unsafe-example`\nwarning: integer-to-pointer cast\n --> src/main.rs:5:13\n |\n5 | let r = address as *mut i32;\n | ^^^^^^^^^^^^^^^^^^^ integer-to-pointer cast\n |\n = help: this program is using integer-to-pointer casts or (equivalently) `ptr::with_exposed_provenance`, which means that Miri might miss pointer bugs in this program\n = help: see https://doc.rust-lang.org/nightly/std/ptr/fn.with_exposed_provenance.html for more details on that operation\n = help: to ensure that Miri does not miss bugs in your program, use Strict Provenance APIs (https://doc.rust-lang.org/nightly/std/ptr/index.html#strict-provenance, https://crates.io/crates/sptr) instead\n = help: you can then set `MIRIFLAGS=-Zmiri-strict-provenance` to ensure you are not relying on `with_exposed_provenance` semantics\n = help: alternatively, `MIRIFLAGS=-Zmiri-permissive-provenance` disables this warning\n\nerror: Undefined Behavior: constructing invalid value of type &mut [i32]: encountered a dangling reference (0x1234[noalloc] has no provenance)\n --> src/main.rs:7:35\n |\n7 | let values: &[i32] = unsafe { slice::from_raw_parts_mut(r, 10000) };\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Undefined Behavior occurred here\n |\n = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior\n = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information\n\nnote: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace\n\nerror: aborting due to 1 previous error; 1 warning emitted\n\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unsafe Rust", "heading_path": ["Unsafe Rust", "Using Miri to Check Unsafe Code"], "path": "ch20-01-unsafe-rust.md", "url": "https://doc.rust-lang.org/book/ch20-01-unsafe-rust.html#using-miri-to-check-unsafe-code", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch20-01-unsafe-rust.md#using-miri-to-check-unsafe-code-22", "text": "The Rust Programming Language › Unsafe Rust › Using Miri to Check Unsafe Code\n\nMiri correctly warns us that we’re casting an integer to a pointer, which might\nbe a problem, but Miri can’t determine whether a problem exists because it\ndoesn’t know how the pointer originated. Then, Miri returns an error where\nListing 20-7 has undefined behavior because we have a dangling pointer. Thanks\nto Miri, we now know there is a risk of undefined behavior, and we can think\nabout how to make the code safe. In some cases, Miri can even make\nrecommendations about how to fix errors.\nMiri doesn’t catch everything you might get wrong when writing unsafe code.\nMiri is a dynamic analysis tool, so it only catches problems with code that\nactually gets run. That means you will need to use it in conjunction with good\ntesting techniques to increase your confidence about the unsafe code you have\nwritten. Miri also does not cover every possible way your code can be unsound.\nPut another way: If Miri _does_ catch a problem, you know there’s a bug, but\njust because Miri _doesn’t_ catch a bug doesn’t mean there isn’t a problem. It\ncan catch a lot, though. Try running it on the other examples of unsafe code in\nthis chapter and see what it says!\nYou can learn more about Miri at its GitHub repository.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unsafe Rust", "heading_path": ["Unsafe Rust", "Using Miri to Check Unsafe Code"], "path": "ch20-01-unsafe-rust.md", "url": "https://doc.rust-lang.org/book/ch20-01-unsafe-rust.html#using-miri-to-check-unsafe-code", "has_code": false, "code_tags": []}} {"id": "book/ch20-01-unsafe-rust.md#using-unsafe-code-correctly-23", "text": "The Rust Programming Language › Unsafe Rust › Using Unsafe Code Correctly\n\nUsing `unsafe` to use one of the five superpowers just discussed isn’t wrong or\neven frowned upon, but it is trickier to get `unsafe` code correct because the\ncompiler can’t help uphold memory safety. When you have a reason to use\n`unsafe` code, you can do so, and having the explicit `unsafe` annotation makes\nit easier to track down the source of problems when they occur. Whenever you\nwrite unsafe code, you can use Miri to help you be more confident that the code\nyou have written upholds Rust’s rules.\nFor a much deeper exploration of how to work effectively with unsafe Rust, read\nRust’s official guide for `unsafe`, The Rustonomicon.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Unsafe Rust", "heading_path": ["Unsafe Rust", "Using Unsafe Code Correctly"], "path": "ch20-01-unsafe-rust.md", "url": "https://doc.rust-lang.org/book/ch20-01-unsafe-rust.html#using-unsafe-code-correctly", "has_code": false, "code_tags": []}} {"id": "book/ch20-02-advanced-traits.md#advanced-traits-0", "text": "The Rust Programming Language › Advanced Traits\n\nWe first covered traits in the “Defining Shared Behavior with\nTraits” section in Chapter 10, but we didn’t discuss\nthe more advanced details. Now that you know more about Rust, we can get into\nthe nitty-gritty.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Traits", "heading_path": ["Advanced Traits"], "path": "ch20-02-advanced-traits.md", "url": "https://doc.rust-lang.org/book/ch20-02-advanced-traits.html#advanced-traits", "has_code": false, "code_tags": []}} {"id": "book/ch20-02-advanced-traits.md#defining-traits-with-associated-types-1", "text": "The Rust Programming Language › Advanced Traits › Defining Traits with Associated Types\n\n_Associated types_ connect a type placeholder with a trait such that the trait\nmethod definitions can use these placeholder types in their signatures. The\nimplementor of a trait will specify the concrete type to be used instead of the\nplaceholder type for the particular implementation. That way, we can define a\ntrait that uses some types without needing to know exactly what those types are\nuntil the trait is implemented.\nWe’ve described most of the advanced features in this chapter as being rarely\nneeded. Associated types are somewhere in the middle: They’re used more rarely\nthan features explained in the rest of the book but more commonly than many of\nthe other features discussed in this chapter.\nOne example of a trait with an associated type is the `Iterator` trait that the\nstandard library provides. The associated type is named `Item` and stands in\nfor the type of the values the type implementing the `Iterator` trait is\niterating over. The definition of the `Iterator` trait is as shown in Listing\n20-13.\nListing 20-13: The definition of the `Iterator` trait that has an associated type `Item`\n```rust,noplayground\npub trait Iterator {\n type Item;\n\n fn next(&mut self) -> Option<Self::Item>;\n}\n```\nThe type `Item` is a placeholder, and the `next` method’s definition shows that\nit will return values of type `Option<Self::Item>`. Implementors of the\n`Iterator` trait will specify the concrete type for `Item`, and the `next`\nmethod will return an `Option` containing a value of that concrete type.\nAssociated types might seem like a similar concept to generics, in that the\nlatter allow us to define a function without specifying what types it can\nhandle. To examine the difference between the two concepts, we’ll look at an\nimplementation of the `Iterator` trait on a type named `Counter` that specifies\nthe `Item` type is `u32`:\nListing (src/lib.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Traits", "heading_path": ["Advanced Traits", "Defining Traits with Associated Types"], "path": "ch20-02-advanced-traits.md", "url": "https://doc.rust-lang.org/book/ch20-02-advanced-traits.html#defining-traits-with-associated-types", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch20-02-advanced-traits.md#defining-traits-with-associated-types-2", "text": "The Rust Programming Language › Advanced Traits › Defining Traits with Associated Types\n\n```rust,ignore\nimpl Iterator for Counter {\n type Item = u32;\n\n fn next(&mut self) -> Option<Self::Item> {\n // --snip--\n```\nThis syntax seems comparable to that of generics. So, why not just define the\n`Iterator` trait with generics, as shown in Listing 20-14?\nListing 20-14: A hypothetical definition of the `Iterator` trait using generics\n```rust,noplayground\npub trait Iterator<T> {\n fn next(&mut self) -> Option<T>;\n}\n```\nThe difference is that when using generics, as in Listing 20-14, we must\nannotate the types in each implementation; because we can also implement\n`Iterator<String> for Counter` or any other type, we could have multiple\nimplementations of `Iterator` for `Counter`. In other words, when a trait has a\ngeneric parameter, it can be implemented for a type multiple times, changing\nthe concrete types of the generic type parameters each time. When we use the\n`next` method on `Counter`, we would have to provide type annotations to\nindicate which implementation of `Iterator` we want to use.\nWith associated types, we don’t need to annotate types, because we can’t\nimplement a trait on a type multiple times. In Listing 20-13 with the\ndefinition that uses associated types, we can choose what the type of `Item`\nwill be only once because there can be only one `impl Iterator for Counter`. We\ndon’t have to specify that we want an iterator of `u32` values everywhere we\ncall `next` on `Counter`.\nAssociated types also become part of the trait’s contract: Implementors of the\ntrait must provide a type to stand in for the associated type placeholder.\nAssociated types often have a name that describes how the type will be used,\nand documenting the associated type in the API documentation is a good practice.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Traits", "heading_path": ["Advanced Traits", "Defining Traits with Associated Types"], "path": "ch20-02-advanced-traits.md", "url": "https://doc.rust-lang.org/book/ch20-02-advanced-traits.html#defining-traits-with-associated-types", "has_code": true, "code_tags": ["rust,ignore", "rust,noplayground"]}} {"id": "book/ch20-02-advanced-traits.md#using-default-generic-parameters-and-operator-overloading-3", "text": "The Rust Programming Language › Advanced Traits › Using Default Generic Parameters and Operator Overloading\n\nWhen we use generic type parameters, we can specify a default concrete type for\nthe generic type. This eliminates the need for implementors of the trait to\nspecify a concrete type if the default type works. You specify a default type\nwhen declaring a generic type with the `<PlaceholderType=ConcreteType>` syntax.\nA great example of a situation where this technique is useful is with _operator\noverloading_, in which you customize the behavior of an operator (such as `+`)\nin particular situations.\nRust doesn’t allow you to create your own operators or overload arbitrary\noperators. But you can overload the operations and corresponding traits listed\nin `std::ops` by implementing the traits associated with the operator. For\nexample, in Listing 20-15, we overload the `+` operator to add two `Point`\ninstances together. We do this by implementing the `Add` trait on a `Point`\nstruct.\nListing 20-15: Implementing the `Add` trait to overload the `+` operator for `Point` instances (src/main.rs)\n```rust\nuse std::ops::Add;\n\n#[derive(Debug, Copy, Clone, PartialEq)]\nstruct Point {\n x: i32,\n y: i32,\n}\n\nimpl Add for Point {\n type Output = Point;\n\n fn add(self, other: Point) -> Point {\n Point {\n x: self.x + other.x,\n y: self.y + other.y,\n }\n }\n}\n\nfn main() {\n assert_eq!(\n Point { x: 1, y: 0 } + Point { x: 2, y: 3 },\n Point { x: 3, y: 3 }\n );\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Traits", "heading_path": ["Advanced Traits", "Using Default Generic Parameters and Operator Overloading"], "path": "ch20-02-advanced-traits.md", "url": "https://doc.rust-lang.org/book/ch20-02-advanced-traits.html#using-default-generic-parameters-and-operator-overloading", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch20-02-advanced-traits.md#using-default-generic-parameters-and-operator-overloading-4", "text": "The Rust Programming Language › Advanced Traits › Using Default Generic Parameters and Operator Overloading\n\nThe `add` method adds the `x` values of two `Point` instances and the `y`\nvalues of two `Point` instances to create a new `Point`. The `Add` trait has an\nassociated type named `Output` that determines the type returned from the `add`\nmethod.\nThe default generic type in this code is within the `Add` trait. Here is its\ndefinition:\n```rust\ntrait Add<Rhs=Self> {\n type Output;\n\n fn add(self, rhs: Rhs) -> Self::Output;\n}\n```\nThis code should look generally familiar: a trait with one method and an\nassociated type. The new part is `Rhs=Self`: This syntax is called _default\ntype parameters_. The `Rhs` generic type parameter (short for “right-hand\nside”) defines the type of the `rhs` parameter in the `add` method. If we don’t\nspecify a concrete type for `Rhs` when we implement the `Add` trait, the type\nof `Rhs` will default to `Self`, which will be the type we’re implementing\n`Add` on.\nWhen we implemented `Add` for `Point`, we used the default for `Rhs` because we\nwanted to add two `Point` instances. Let’s look at an example of implementing\nthe `Add` trait where we want to customize the `Rhs` type rather than using the\ndefault.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Traits", "heading_path": ["Advanced Traits", "Using Default Generic Parameters and Operator Overloading"], "path": "ch20-02-advanced-traits.md", "url": "https://doc.rust-lang.org/book/ch20-02-advanced-traits.html#using-default-generic-parameters-and-operator-overloading", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch20-02-advanced-traits.md#using-default-generic-parameters-and-operator-overloading-5", "text": "The Rust Programming Language › Advanced Traits › Using Default Generic Parameters and Operator Overloading\n\nWe have two structs, `Millimeters` and `Meters`, holding values in different\nunits. This thin wrapping of an existing type in another struct is known as the\n_newtype pattern_, which we describe in more detail in the “Implementing\nExternal Traits with the Newtype Pattern” section. We\nwant to add values in millimeters to values in meters and have the\nimplementation of `Add` do the conversion correctly. We can implement `Add` for\n`Millimeters` with `Meters` as the `Rhs`, as shown in Listing 20-16.\nListing 20-16: Implementing the `Add` trait on `Millimeters` to add `Millimeters` and `Meters` (src/lib.rs)\n```rust,noplayground\nuse std::ops::Add;\n\nstruct Millimeters(u32);\nstruct Meters(u32);\n\nimpl Add<Meters> for Millimeters {\n type Output = Millimeters;\n\n fn add(self, other: Meters) -> Millimeters {\n Millimeters(self.0 + (other.0 * 1000))\n }\n}\n```\nTo add `Millimeters` and `Meters`, we specify `impl Add<Meters>` to set the\nvalue of the `Rhs` type parameter instead of using the default of `Self`.\nYou’ll use default type parameters in two main ways:\n1. To extend a type without breaking existing code\n2. To allow customization in specific cases most users won’t need\nThe standard library’s `Add` trait is an example of the second purpose:\nUsually, you’ll add two like types, but the `Add` trait provides the ability to\ncustomize beyond that. Using a default type parameter in the `Add` trait\ndefinition means you don’t have to specify the extra parameter most of the\ntime. In other words, a bit of implementation boilerplate isn’t needed, making\nit easier to use the trait.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Traits", "heading_path": ["Advanced Traits", "Using Default Generic Parameters and Operator Overloading"], "path": "ch20-02-advanced-traits.md", "url": "https://doc.rust-lang.org/book/ch20-02-advanced-traits.html#using-default-generic-parameters-and-operator-overloading", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch20-02-advanced-traits.md#using-default-generic-parameters-and-operator-overloading-6", "text": "The Rust Programming Language › Advanced Traits › Using Default Generic Parameters and Operator Overloading\n\nThe first purpose is similar to the second but in reverse: If you want to add a\ntype parameter to an existing trait, you can give it a default to allow\nextension of the functionality of the trait without breaking the existing\nimplementation code.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Traits", "heading_path": ["Advanced Traits", "Using Default Generic Parameters and Operator Overloading"], "path": "ch20-02-advanced-traits.md", "url": "https://doc.rust-lang.org/book/ch20-02-advanced-traits.html#using-default-generic-parameters-and-operator-overloading", "has_code": false, "code_tags": []}} {"id": "book/ch20-02-advanced-traits.md#disambiguating-between-identically-named-methods-7", "text": "The Rust Programming Language › Advanced Traits › Disambiguating Between Identically Named Methods\n\nNothing in Rust prevents a trait from having a method with the same name as\nanother trait’s method, nor does Rust prevent you from implementing both traits\non one type. It’s also possible to implement a method directly on the type with\nthe same name as methods from traits.\nWhen calling methods with the same name, you’ll need to tell Rust which one you\nwant to use. Consider the code in Listing 20-17 where we’ve defined two traits,\n`Pilot` and `Wizard`, that both have a method called `fly`. We then implement\nboth traits on a type `Human` that already has a method named `fly` implemented\non it. Each `fly` method does something different.\nListing 20-17: 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. (src/main.rs)\n```rust\ntrait Pilot {\n fn fly(&self);\n}\n\ntrait Wizard {\n fn fly(&self);\n}\n\nstruct Human;\n\nimpl Pilot for Human {\n fn fly(&self) {\n println!(\"This is your captain speaking.\");\n }\n}\n\nimpl Wizard for Human {\n fn fly(&self) {\n println!(\"Up!\");\n }\n}\n\nimpl Human {\n fn fly(&self) {\n println!(\"*waving arms furiously*\");\n }\n}\n```\nWhen we call `fly` on an instance of `Human`, the compiler defaults to calling\nthe method that is directly implemented on the type, as shown in Listing 20-18.\nListing 20-18: Calling `fly` on an instance of `Human` (src/main.rs)\n```rust\nfn main() {\n let person = Human;\n person.fly();\n}\n```\nRunning this code will print `*waving arms furiously*`, showing that Rust\ncalled the `fly` method implemented on `Human` directly.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Traits", "heading_path": ["Advanced Traits", "Disambiguating Between Identically Named Methods"], "path": "ch20-02-advanced-traits.md", "url": "https://doc.rust-lang.org/book/ch20-02-advanced-traits.html#disambiguating-between-identically-named-methods", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch20-02-advanced-traits.md#disambiguating-between-identically-named-methods-8", "text": "The Rust Programming Language › Advanced Traits › Disambiguating Between Identically Named Methods\n\nTo call the `fly` methods from either the `Pilot` trait or the `Wizard` trait,\nwe need to use more explicit syntax to specify which `fly` method we mean.\nListing 20-19 demonstrates this syntax.\nListing 20-19: Specifying which trait’s `fly` method we want to call (src/main.rs)\n```rust\nfn main() {\n let person = Human;\n Pilot::fly(&person);\n Wizard::fly(&person);\n person.fly();\n}\n```\nSpecifying the trait name before the method name clarifies to Rust which\nimplementation of `fly` we want to call. We could also write\n`Human::fly(&person)`, which is equivalent to the `person.fly()` that we used\nin Listing 20-19, but this is a bit longer to write if we don’t need to\ndisambiguate.\nRunning this code prints the following:\n```console\n$ cargo run\n Compiling traits-example v0.1.0 (file:///projects/traits-example)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.46s\n Running `target/debug/traits-example`\nThis is your captain speaking.\nUp!\n*waving arms furiously*\n```\nBecause the `fly` method takes a `self` parameter, if we had two _types_ that\nboth implement one _trait_, Rust could figure out which implementation of a\ntrait to use based on the type of `self`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Traits", "heading_path": ["Advanced Traits", "Disambiguating Between Identically Named Methods"], "path": "ch20-02-advanced-traits.md", "url": "https://doc.rust-lang.org/book/ch20-02-advanced-traits.html#disambiguating-between-identically-named-methods", "has_code": true, "code_tags": ["console", "rust"]}} {"id": "book/ch20-02-advanced-traits.md#disambiguating-between-identically-named-methods-9", "text": "The Rust Programming Language › Advanced Traits › Disambiguating Between Identically Named Methods\n\nHowever, associated functions that are not methods don’t have a `self`\nparameter. When there are multiple types or traits that define non-method\nfunctions with the same function name, Rust doesn’t always know which type you\nmean unless you use fully qualified syntax. For example, in Listing 20-20, we\ncreate a trait for an animal shelter that wants to name all baby dogs Spot. We\nmake an `Animal` trait with an associated non-method function `baby_name`. The\n`Animal` trait is implemented for the struct `Dog`, on which we also provide an\nassociated non-method function `baby_name` directly.\nListing 20-20: A trait with an associated function and a type with an associated function of the same name that also implements the trait (src/main.rs)\n```rust\ntrait Animal {\n fn baby_name() -> String;\n}\n\nstruct Dog;\n\nimpl Dog {\n fn baby_name() -> String {\n String::from(\"Spot\")\n }\n}\n\nimpl Animal for Dog {\n fn baby_name() -> String {\n String::from(\"puppy\")\n }\n}\n\nfn main() {\n println!(\"A baby dog is called a {}\", Dog::baby_name());\n}\n```\nWe implement the code for naming all puppies Spot in the `baby_name` associated\nfunction that is defined on `Dog`. The `Dog` type also implements the trait\n`Animal`, which describes characteristics that all animals have. Baby dogs are\ncalled puppies, and that is expressed in the implementation of the `Animal`\ntrait on `Dog` in the `baby_name` function associated with the `Animal` trait.\nIn `main`, we call the `Dog::baby_name` function, which calls the associated\nfunction defined on `Dog` directly. This code prints the following:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Traits", "heading_path": ["Advanced Traits", "Disambiguating Between Identically Named Methods"], "path": "ch20-02-advanced-traits.md", "url": "https://doc.rust-lang.org/book/ch20-02-advanced-traits.html#disambiguating-between-identically-named-methods", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch20-02-advanced-traits.md#disambiguating-between-identically-named-methods-10", "text": "The Rust Programming Language › Advanced Traits › Disambiguating Between Identically Named Methods\n\n```console\n$ cargo run\n Compiling traits-example v0.1.0 (file:///projects/traits-example)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.54s\n Running `target/debug/traits-example`\nA baby dog is called a Spot\n```\nThis output isn’t what we wanted. We want to call the `baby_name` function that\nis part of the `Animal` trait that we implemented on `Dog` so that the code\nprints `A baby dog is called a puppy`. The technique of specifying the trait\nname that we used in Listing 20-19 doesn’t help here; if we change `main` to\nthe code in Listing 20-21, we’ll get a compilation error.\nListing 20-21: Attempting to call the `baby_name` function from the `Animal` trait, but Rust doesn’t know which implementation to use (src/main.rs)\n```rust,ignore,does_not_compile\nfn main() {\n println!(\"A baby dog is called a {}\", Animal::baby_name());\n}\n```\nBecause `Animal::baby_name` doesn’t have a `self` parameter, and there could be\nother types that implement the `Animal` trait, Rust can’t figure out which\nimplementation of `Animal::baby_name` we want. We’ll get this compiler error:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Traits", "heading_path": ["Advanced Traits", "Disambiguating Between Identically Named Methods"], "path": "ch20-02-advanced-traits.md", "url": "https://doc.rust-lang.org/book/ch20-02-advanced-traits.html#disambiguating-between-identically-named-methods", "has_code": true, "code_tags": ["console", "rust,ignore,does_not_compile"]}} {"id": "book/ch20-02-advanced-traits.md#disambiguating-between-identically-named-methods-11", "text": "The Rust Programming Language › Advanced Traits › Disambiguating Between Identically Named Methods\n\n```console\n$ cargo run\n Compiling traits-example v0.1.0 (file:///projects/traits-example)\nerror[E0790]: cannot call associated function on trait without specifying the corresponding `impl` type\n --> src/main.rs:20:43\n |\n 2 | fn baby_name() -> String;\n | ------------------------- `Animal::baby_name` defined here\n...\n20 | println!(\"A baby dog is called a {}\", Animal::baby_name());\n | ^^^^^^^^^^^^^^^^^^^ cannot call associated function of trait\n |\nhelp: use the fully-qualified path to the only available implementation\n |\n20 | println!(\"A baby dog is called a {}\", <Dog as Animal>::baby_name());\n | +++++++ +\n\nFor more information about this error, try `rustc --explain E0790`.\nerror: could not compile `traits-example` (bin \"traits-example\") due to 1 previous error\n```\nTo disambiguate and tell Rust that we want to use the implementation of\n`Animal` for `Dog` as opposed to the implementation of `Animal` for some other\ntype, we need to use fully qualified syntax. Listing 20-22 demonstrates how to\nuse fully qualified syntax.\nListing 20-22: Using fully qualified syntax to specify that we want to call the `baby_name` function from the `Animal` trait as implemented on `Dog` (src/main.rs)\n```rust\nfn main() {\n println!(\"A baby dog is called a {}\", <Dog as Animal>::baby_name());\n}\n```\nWe’re providing Rust with a type annotation within the angle brackets, which\nindicates we want to call the `baby_name` method from the `Animal` trait as\nimplemented on `Dog` by saying that we want to treat the `Dog` type as an\n`Animal` for this function call. This code will now print what we want:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Traits", "heading_path": ["Advanced Traits", "Disambiguating Between Identically Named Methods"], "path": "ch20-02-advanced-traits.md", "url": "https://doc.rust-lang.org/book/ch20-02-advanced-traits.html#disambiguating-between-identically-named-methods", "has_code": true, "code_tags": ["console", "rust"]}} {"id": "book/ch20-02-advanced-traits.md#disambiguating-between-identically-named-methods-12", "text": "The Rust Programming Language › Advanced Traits › Disambiguating Between Identically Named Methods\n\n```console\n$ cargo run\n Compiling traits-example v0.1.0 (file:///projects/traits-example)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.48s\n Running `target/debug/traits-example`\nA baby dog is called a puppy\n```\nIn general, fully qualified syntax is defined as follows:\n```rust,ignore\n<Type as Trait>::function(receiver_if_method, next_arg, ...);\n```\nFor associated functions that aren’t methods, there would not be a `receiver`:\nThere would only be the list of other arguments. You could use fully qualified\nsyntax everywhere that you call functions or methods. However, you’re allowed\nto omit any part of this syntax that Rust can figure out from other information\nin the program. You only need to use this more verbose syntax in cases where\nthere are multiple implementations that use the same name and Rust needs help\nto identify which implementation you want to call.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Traits", "heading_path": ["Advanced Traits", "Disambiguating Between Identically Named Methods"], "path": "ch20-02-advanced-traits.md", "url": "https://doc.rust-lang.org/book/ch20-02-advanced-traits.html#disambiguating-between-identically-named-methods", "has_code": true, "code_tags": ["console", "rust,ignore"]}} {"id": "book/ch20-02-advanced-traits.md#using-supertraits-13", "text": "The Rust Programming Language › Advanced Traits › Using Supertraits\n\nSometimes you might write a trait definition that depends on another trait: For\na type to implement the first trait, you want to require that type to also\nimplement the second trait. You would do this so that your trait definition can\nmake use of the associated items of the second trait. The trait your trait\ndefinition is relying on is called a _supertrait_ of your trait.\nFor example, let’s say we want to make an `OutlinePrint` trait with an\n`outline_print` method that will print a given value formatted so that it’s\nframed in asterisks. That is, given a `Point` struct that implements the\nstandard library trait `Display` to result in `(x, y)`, when we call\n`outline_print` on a `Point` instance that has `1` for `x` and `3` for `y`, it\nshould print the following:\n```text\n**********\n* *\n* (1, 3) *\n* *\n**********\n```\nIn the implementation of the `outline_print` method, we want to use the\n`Display` trait’s functionality. Therefore, we need to specify that the\n`OutlinePrint` trait will work only for types that also implement `Display` and\nprovide the functionality that `OutlinePrint` needs. We can do that in the\ntrait definition by specifying `OutlinePrint: Display`. This technique is\nsimilar to adding a trait bound to the trait. Listing 20-23 shows an\nimplementation of the `OutlinePrint` trait.\nListing 20-23: Implementing the `OutlinePrint` trait that requires the functionality from `Display` (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Traits", "heading_path": ["Advanced Traits", "Using Supertraits"], "path": "ch20-02-advanced-traits.md", "url": "https://doc.rust-lang.org/book/ch20-02-advanced-traits.html#using-supertraits", "has_code": true, "code_tags": ["text"]}} {"id": "book/ch20-02-advanced-traits.md#using-supertraits-14", "text": "The Rust Programming Language › Advanced Traits › Using Supertraits\n\n```rust\nuse std::fmt;\n\ntrait OutlinePrint: fmt::Display {\n fn outline_print(&self) {\n let output = self.to_string();\n let len = output.len();\n println!(\"{}\", \"*\".repeat(len + 4));\n println!(\"*{}*\", \" \".repeat(len + 2));\n println!(\"* {output} *\");\n println!(\"*{}*\", \" \".repeat(len + 2));\n println!(\"{}\", \"*\".repeat(len + 4));\n }\n}\n```\nBecause we’ve specified that `OutlinePrint` requires the `Display` trait, we\ncan use the `to_string` function that is automatically implemented for any type\nthat implements `Display`. If we tried to use `to_string` without adding a\ncolon and specifying the `Display` trait after the trait name, we’d get an\nerror saying that no method named `to_string` was found for the type `&Self` in\nthe current scope.\nLet’s see what happens when we try to implement `OutlinePrint` on a type that\ndoesn’t implement `Display`, such as the `Point` struct:\nListing (src/main.rs)\n```rust,ignore,does_not_compile\nstruct Point {\n x: i32,\n y: i32,\n}\n\nimpl OutlinePrint for Point {}\n```\nWe get an error saying that `Display` is required but not implemented:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Traits", "heading_path": ["Advanced Traits", "Using Supertraits"], "path": "ch20-02-advanced-traits.md", "url": "https://doc.rust-lang.org/book/ch20-02-advanced-traits.html#using-supertraits", "has_code": true, "code_tags": ["rust", "rust,ignore,does_not_compile"]}} {"id": "book/ch20-02-advanced-traits.md#using-supertraits-15", "text": "The Rust Programming Language › Advanced Traits › Using Supertraits\n\n```console\n$ cargo run\n Compiling traits-example v0.1.0 (file:///projects/traits-example)\nerror[E0277]: `Point` doesn't implement `std::fmt::Display`\n --> src/main.rs:20:23\n |\n20 | impl OutlinePrint for Point {}\n | ^^^^^ unsatisfied trait bound\n |\nhelp: the trait `std::fmt::Display` is not implemented for `Point`\n --> src/main.rs:15:1\n |\n15 | struct Point {\n | ^^^^^^^^^^^^\nnote: required by a bound in `OutlinePrint`\n --> src/main.rs:3:21\n |\n 3 | trait OutlinePrint: fmt::Display {\n | ^^^^^^^^^^^^ required by this bound in `OutlinePrint`\n\nerror[E0277]: `Point` doesn't implement `std::fmt::Display`\n --> src/main.rs:24:7\n |\n24 | p.outline_print();\n | ^^^^^^^^^^^^^ unsatisfied trait bound\n |\nhelp: the trait `std::fmt::Display` is not implemented for `Point`\n --> src/main.rs:15:1\n |\n15 | struct Point {\n | ^^^^^^^^^^^^\nnote: required by a bound in `OutlinePrint::outline_print`\n --> src/main.rs:3:21\n |\n 3 | trait OutlinePrint: fmt::Display {\n | ^^^^^^^^^^^^ required by this bound in `OutlinePrint::outline_print`\n 4 | fn outline_print(&self) {\n | ------------- required by a bound in this associated function\n\nFor more information about this error, try `rustc --explain E0277`.\nerror: could not compile `traits-example` (bin \"traits-example\") due to 2 previous errors\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Traits", "heading_path": ["Advanced Traits", "Using Supertraits"], "path": "ch20-02-advanced-traits.md", "url": "https://doc.rust-lang.org/book/ch20-02-advanced-traits.html#using-supertraits", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch20-02-advanced-traits.md#using-supertraits-16", "text": "The Rust Programming Language › Advanced Traits › Using Supertraits\n\nTo fix this, we implement `Display` on `Point` and satisfy the constraint that\n`OutlinePrint` requires, like so:\nListing (src/main.rs)\n```rust\nuse std::fmt;\n\nimpl fmt::Display for Point {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f, \"({}, {})\", self.x, self.y)\n }\n}\n```\nThen, implementing the `OutlinePrint` trait on `Point` will compile\nsuccessfully, and we can call `outline_print` on a `Point` instance to display\nit within an outline of asterisks.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Traits", "heading_path": ["Advanced Traits", "Using Supertraits"], "path": "ch20-02-advanced-traits.md", "url": "https://doc.rust-lang.org/book/ch20-02-advanced-traits.html#using-supertraits", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch20-02-advanced-traits.md#implementing-external-traits-with-the-newtype-pattern-17", "text": "The Rust Programming Language › Advanced Traits › Implementing External Traits with the Newtype Pattern\n\nIn the “Implementing a Trait on a Type”\n section in Chapter 10, we mentioned the orphan rule that states\nwe’re only allowed to implement a trait on a type if either the trait or the\ntype, or both, are local to our crate. It’s possible to get around this\nrestriction using the newtype pattern, which involves creating a new type in a\ntuple struct. (We covered tuple structs in the “Creating Different Types with\nTuple Structs” section in Chapter 5.) The tuple\nstruct will have one field and be a thin wrapper around the type for which we\nwant to implement a trait. Then, the wrapper type is local to our crate, and we\ncan implement the trait on the wrapper. _Newtype_ is a term that originates\nfrom the Haskell programming language. There is no runtime performance penalty\nfor using this pattern, and the wrapper type is elided at compile time.\nAs an example, let’s say we want to implement `Display` on `Vec<T>`, which the\norphan rule prevents us from doing directly because the `Display` trait and the\n`Vec<T>` type are defined outside our crate. We can make a `Wrapper` struct\nthat holds an instance of `Vec<T>`; then, we can implement `Display` on\n`Wrapper` and use the `Vec<T>` value, as shown in Listing 20-24.\nListing 20-24 (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Traits", "heading_path": ["Advanced Traits", "Implementing External Traits with the Newtype Pattern"], "path": "ch20-02-advanced-traits.md", "url": "https://doc.rust-lang.org/book/ch20-02-advanced-traits.html#implementing-external-traits-with-the-newtype-pattern", "has_code": false, "code_tags": []}} {"id": "book/ch20-02-advanced-traits.md#implementing-external-traits-with-the-newtype-pattern-18", "text": "The Rust Programming Language › Advanced Traits › Implementing External Traits with the Newtype Pattern\n\n```rust\nuse std::fmt;\n\nstruct Wrapper(Vec<String>);\n\nimpl fmt::Display for Wrapper {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f, \"[{}]\", self.0.join(\", \"))\n }\n}\n\nfn main() {\n let w = Wrapper(vec![String::from(\"hello\"), String::from(\"world\")]);\n println!(\"w = {w}\");\n}\n```\nThe implementation of `Display` uses `self.0` to access the inner `Vec<T>`\nbecause `Wrapper` is a tuple struct and `Vec<T>` is the item at index 0 in the\ntuple. Then, we can use the functionality of the `Display` trait on `Wrapper`.\nThe downside of using this technique is that `Wrapper` is a new type, so it\ndoesn’t have the methods of the value it’s holding. We would have to implement\nall the methods of `Vec<T>` directly on `Wrapper` such that the methods\ndelegate to `self.0`, which would allow us to treat `Wrapper` exactly like a\n`Vec<T>`. If we wanted the new type to have every method the inner type has,\nimplementing the `Deref` trait on the `Wrapper` to return the inner type would\nbe a solution (we discussed implementing the `Deref` trait in the “Treating\nSmart Pointers Like Regular References”\nsection in Chapter 15). If we didn’t want the `Wrapper` type to have all the\nmethods of the inner type—for example, to restrict the `Wrapper` type’s\nbehavior—we would have to implement just the methods we do want manually.\nThis newtype pattern is also useful even when traits are not involved. Let’s\nswitch focus and look at some advanced ways to interact with Rust’s type system.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Traits", "heading_path": ["Advanced Traits", "Implementing External Traits with the Newtype Pattern"], "path": "ch20-02-advanced-traits.md", "url": "https://doc.rust-lang.org/book/ch20-02-advanced-traits.html#implementing-external-traits-with-the-newtype-pattern", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch20-03-advanced-types.md#advanced-types-0", "text": "The Rust Programming Language › Advanced Types\n\nThe Rust type system has some features that we’ve so far mentioned but haven’t\nyet discussed. We’ll start by discussing newtypes in general as we examine why\nthey are useful as types. Then, we’ll move on to type aliases, a feature\nsimilar to newtypes but with slightly different semantics. We’ll also discuss\nthe `!` type and dynamically sized types.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Types", "heading_path": ["Advanced Types"], "path": "ch20-03-advanced-types.md", "url": "https://doc.rust-lang.org/book/ch20-03-advanced-types.html#advanced-types", "has_code": false, "code_tags": []}} {"id": "book/ch20-03-advanced-types.md#type-safety-and-abstraction-with-the-newtype-pattern-1", "text": "The Rust Programming Language › Advanced Types › Type Safety and Abstraction with the Newtype Pattern\n\nThis section assumes you’ve read the earlier section “Implementing External\nTraits with the Newtype Pattern”. The newtype pattern\nis also useful for tasks beyond those we’ve discussed so far, including\nstatically enforcing that values are never confused and indicating the units of\na value. You saw an example of using newtypes to indicate units in Listing\n20-16: Recall that the `Millimeters` and `Meters` structs wrapped `u32` values\nin a newtype. If we wrote a function with a parameter of type `Millimeters`, we\nwouldn’t be able to compile a program that accidentally tried to call that\nfunction with a value of type `Meters` or a plain `u32`.\nWe can also use the newtype pattern to abstract away some implementation\ndetails of a type: The new type can expose a public API that is different from\nthe API of the private inner type.\nNewtypes can also hide internal implementation. For example, we could provide a\n`People` type to wrap a `HashMap<i32, String>` that stores a person’s ID\nassociated with their name. Code using `People` would only interact with the\npublic API we provide, such as a method to add a name string to the `People`\ncollection; that code wouldn’t need to know that we assign an `i32` ID to names\ninternally. The newtype pattern is a lightweight way to achieve encapsulation\nto hide implementation details, which we discussed in the “Encapsulation that\nHides Implementation\nDetails”\nsection in Chapter 18.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Types", "heading_path": ["Advanced Types", "Type Safety and Abstraction with the Newtype Pattern"], "path": "ch20-03-advanced-types.md", "url": "https://doc.rust-lang.org/book/ch20-03-advanced-types.html#type-safety-and-abstraction-with-the-newtype-pattern", "has_code": false, "code_tags": []}} {"id": "book/ch20-03-advanced-types.md#type-synonyms-and-type-aliases-2", "text": "The Rust Programming Language › Advanced Types › Type Synonyms and Type Aliases\n\nRust provides the ability to declare a _type alias_ to give an existing type\nanother name. For this we use the `type` keyword. For example, we can create\nthe alias `Kilometers` to `i32` like so:\n```rust\n type Kilometers = i32;\n```\nNow the alias `Kilometers` is a _synonym_ for `i32`; unlike the `Millimeters`\nand `Meters` types we created in Listing 20-16, `Kilometers` is not a separate,\nnew type. Values that have the type `Kilometers` will be treated the same as\nvalues of type `i32`:\n```rust\n type Kilometers = i32;\n\n let x: i32 = 5;\n let y: Kilometers = 5;\n\n println!(\"x + y = {}\", x + y);\n```\nBecause `Kilometers` and `i32` are the same type, we can add values of both\ntypes and can pass `Kilometers` values to functions that take `i32`\nparameters. However, using this method, we don’t get the type-checking benefits\nthat we get from the newtype pattern discussed earlier. In other words, if we\nmix up `Kilometers` and `i32` values somewhere, the compiler will not give us\nan error.\nThe main use case for type synonyms is to reduce repetition. For example, we\nmight have a lengthy type like this:\n```rust,ignore\nBox<dyn Fn() + Send + 'static>\n```\nWriting this lengthy type in function signatures and as type annotations all\nover the code can be tiresome and error-prone. Imagine having a project full of\ncode like that in Listing 20-25.\nListing 20-25: Using a long type in many places", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Types", "heading_path": ["Advanced Types", "Type Synonyms and Type Aliases"], "path": "ch20-03-advanced-types.md", "url": "https://doc.rust-lang.org/book/ch20-03-advanced-types.html#type-synonyms-and-type-aliases", "has_code": true, "code_tags": ["rust", "rust,ignore"]}} {"id": "book/ch20-03-advanced-types.md#type-synonyms-and-type-aliases-3", "text": "The Rust Programming Language › Advanced Types › Type Synonyms and Type Aliases\n\n```rust\n let f: Box<dyn Fn() + Send + 'static> = Box::new(|| println!(\"hi\"));\n\n fn takes_long_type(f: Box<dyn Fn() + Send + 'static>) {\n // --snip--\n }\n\n fn returns_long_type() -> Box<dyn Fn() + Send + 'static> {\n // --snip--\n }\n```\nA type alias makes this code more manageable by reducing the repetition. In\nListing 20-26, we’ve introduced an alias named `Thunk` for the verbose type and\ncan replace all uses of the type with the shorter alias `Thunk`.\nListing 20-26: Introducing a type alias, `Thunk`, to reduce repetition\n```rust\n type Thunk = Box<dyn Fn() + Send + 'static>;\n\n let f: Thunk = Box::new(|| println!(\"hi\"));\n\n fn takes_long_type(f: Thunk) {\n // --snip--\n }\n\n fn returns_long_type() -> Thunk {\n // --snip--\n }\n```\nThis code is much easier to read and write! Choosing a meaningful name for a\ntype alias can help communicate your intent as well (_thunk_ is a word for code\nto be evaluated at a later time, so it’s an appropriate name for a closure that\ngets stored).\nType aliases are also commonly used with the `Result<T, E>` type for reducing\nrepetition. Consider the `std::io` module in the standard library. I/O\noperations often return a `Result<T, E>` to handle situations when operations\nfail to work. This library has a `std::io::Error` struct that represents all\npossible I/O errors. Many of the functions in `std::io` will be returning\n`Result<T, E>` where the `E` is `std::io::Error`, such as these functions in\nthe `Write` trait:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Types", "heading_path": ["Advanced Types", "Type Synonyms and Type Aliases"], "path": "ch20-03-advanced-types.md", "url": "https://doc.rust-lang.org/book/ch20-03-advanced-types.html#type-synonyms-and-type-aliases", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch20-03-advanced-types.md#type-synonyms-and-type-aliases-4", "text": "The Rust Programming Language › Advanced Types › Type Synonyms and Type Aliases\n\n```rust,noplayground\nuse std::fmt;\nuse std::io::Error;\n\npub trait Write {\n fn write(&mut self, buf: &[u8]) -> Result<usize, Error>;\n fn flush(&mut self) -> Result<(), Error>;\n\n fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>;\n fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<(), Error>;\n}\n```\nThe `Result<..., Error>` is repeated a lot. As such, `std::io` has this type\nalias declaration:\n```rust,noplayground\ntype Result<T> = std::result::Result<T, std::io::Error>;\n```\nBecause this declaration is in the `std::io` module, we can use the fully\nqualified alias `std::io::Result<T>`; that is, a `Result<T, E>` with the `E`\nfilled in as `std::io::Error`. The `Write` trait function signatures end up\nlooking like this:\n```rust,noplayground\npub trait Write {\n fn write(&mut self, buf: &[u8]) -> Result<usize>;\n fn flush(&mut self) -> Result<()>;\n\n fn write_all(&mut self, buf: &[u8]) -> Result<()>;\n fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()>;\n}\n```\nThe type alias helps in two ways: It makes code easier to write _and_ it gives\nus a consistent interface across all of `std::io`. Because it’s an alias, it’s\njust another `Result<T, E>`, which means we can use any methods that work on\n`Result<T, E>` with it, as well as special syntax like the `?` operator.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Types", "heading_path": ["Advanced Types", "Type Synonyms and Type Aliases"], "path": "ch20-03-advanced-types.md", "url": "https://doc.rust-lang.org/book/ch20-03-advanced-types.html#type-synonyms-and-type-aliases", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch20-03-advanced-types.md#the-never-type-that-never-returns-5", "text": "The Rust Programming Language › Advanced Types › The Never Type That Never Returns\n\nRust has a special type named `!` that’s known in type theory lingo as the\n_empty type_ because it has no values. We prefer to call it the _never type_\nbecause it stands in the place of the return type when a function will never\nreturn. Here is an example:\n```rust,noplayground\nfn bar() -> ! {\n // --snip--\n}\n```\nThis code is read as “the function `bar` returns never.” Functions that return\nnever are called _diverging functions_. We can’t create values of the type `!`,\nso `bar` can never possibly return.\nBut what use is a type you can never create values for? Recall the code from\nListing 2-5, part of the number-guessing game; we’ve reproduced a bit of it\nhere in Listing 20-27.\nListing 20-27: A `match` with an arm that ends in `continue`\n```rust,ignore\n let guess: u32 = match guess.trim().parse() {\n Ok(num) => num,\n Err(_) => continue,\n };\n```\nAt the time, we skipped over some details in this code. In “The `match`\nControl Flow Construct”\nsection in Chapter 6, we discussed that `match` arms must all return the same\ntype. So, for example, the following code doesn’t work:\n```rust,ignore,does_not_compile\n let guess = match guess.trim().parse() {\n Ok(_) => 5,\n Err(_) => \"hello\",\n };\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Types", "heading_path": ["Advanced Types", "The Never Type That Never Returns"], "path": "ch20-03-advanced-types.md", "url": "https://doc.rust-lang.org/book/ch20-03-advanced-types.html#the-never-type-that-never-returns", "has_code": true, "code_tags": ["rust,ignore", "rust,ignore,does_not_compile", "rust,noplayground"]}} {"id": "book/ch20-03-advanced-types.md#the-never-type-that-never-returns-6", "text": "The Rust Programming Language › Advanced Types › The Never Type That Never Returns\n\nThe type of `guess` in this code would have to be an integer _and_ a string,\nand Rust requires that `guess` have only one type. So, what does `continue`\nreturn? How were we allowed to return a `u32` from one arm and have another arm\nthat ends with `continue` in Listing 20-27?\nAs you might have guessed, `continue` has a `!` value. That is, when Rust\ncomputes the type of `guess`, it looks at both match arms, the former with a\nvalue of `u32` and the latter with a `!` value. Because `!` can never have a\nvalue, Rust decides that the type of `guess` is `u32`.\nThe formal way of describing this behavior is that expressions of type `!` can\nbe coerced into any other type. We’re allowed to end this `match` arm with\n`continue` because `continue` doesn’t return a value; instead, it moves control\nback to the top of the loop, so in the `Err` case, we never assign a value to\n`guess`.\nThe never type is useful with the `panic!` macro as well. Recall the `unwrap`\nfunction that we call on `Option<T>` values to produce a value or panic with\nthis definition:\n```rust,ignore\nimpl<T> Option<T> {\n pub fn unwrap(self) -> T {\n match self {\n Some(val) => val,\n None => panic!(\"called `Option::unwrap()` on a `None` value\"),\n }\n }\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Types", "heading_path": ["Advanced Types", "The Never Type That Never Returns"], "path": "ch20-03-advanced-types.md", "url": "https://doc.rust-lang.org/book/ch20-03-advanced-types.html#the-never-type-that-never-returns", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch20-03-advanced-types.md#the-never-type-that-never-returns-7", "text": "The Rust Programming Language › Advanced Types › The Never Type That Never Returns\n\nIn this code, the same thing happens as in the `match` in Listing 20-27: Rust\nsees that `val` has the type `T` and `panic!` has the type `!`, so the result\nof the overall `match` expression is `T`. This code works because `panic!`\ndoesn’t produce a value; it ends the program. In the `None` case, we won’t be\nreturning a value from `unwrap`, so this code is valid.\nOne final expression that has the type `!` is a loop:\n```rust,ignore\n print!(\"forever \");\n\n loop {\n print!(\"and ever \");\n }\n```\nHere, the loop never ends, so `!` is the value of the expression. However, this\nwouldn’t be true if we included a `break`, because the loop would terminate\nwhen it got to the `break`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Types", "heading_path": ["Advanced Types", "The Never Type That Never Returns"], "path": "ch20-03-advanced-types.md", "url": "https://doc.rust-lang.org/book/ch20-03-advanced-types.html#the-never-type-that-never-returns", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch20-03-advanced-types.md#dynamically-sized-types-and-the-sized-trait-8", "text": "The Rust Programming Language › Advanced Types › Dynamically Sized Types and the `Sized` Trait\n\nRust needs to know certain details about its types, such as how much space to\nallocate for a value of a particular type. This leaves one corner of its type\nsystem a little confusing at first: the concept of _dynamically sized types_.\nSometimes referred to as _DSTs_ or _unsized types_, these types let us write\ncode using values whose size we can know only at runtime.\nLet’s dig into the details of a dynamically sized type called `str`, which\nwe’ve been using throughout the book. That’s right, not `&str`, but `str` on\nits own, is a DST. In many cases, such as when storing text entered by a user,\nwe can’t know how long the string is until runtime. That means we can’t create\na variable of type `str`, nor can we take an argument of type `str`. Consider\nthe following code, which does not work:\n```rust,ignore,does_not_compile\n let s1: str = \"Hello there!\";\n let s2: str = \"How's it going?\";\n```\nRust needs to know how much memory to allocate for any value of a particular\ntype, and all values of a type must use the same amount of memory. If Rust\nallowed us to write this code, these two `str` values would need to take up the\nsame amount of space. But they have different lengths: `s1` needs 12 bytes of\nstorage and `s2` needs 15. This is why it’s not possible to create a variable\nholding a dynamically sized type.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Types", "heading_path": ["Advanced Types", "Dynamically Sized Types and the `Sized` Trait"], "path": "ch20-03-advanced-types.md", "url": "https://doc.rust-lang.org/book/ch20-03-advanced-types.html#dynamically-sized-types-and-the-sized-trait", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch20-03-advanced-types.md#dynamically-sized-types-and-the-sized-trait-9", "text": "The Rust Programming Language › Advanced Types › Dynamically Sized Types and the `Sized` Trait\n\nSo, what do we do? In this case, you already know the answer: We make the type\nof `s1` and `s2` string slice (`&str`) rather than `str`. Recall from the\n“String Slices” section in Chapter 4 that the\nslice data structure only stores the starting position and the length of the\nslice. So, although `&T` is a single value that stores the memory address of\nwhere the `T` is located, a string slice is _two_ values: the address of the\n`str` and its length. As such, we can know the size of a string slice value at\ncompile time: It’s twice the length of a `usize`. That is, we always know the\nsize of a string slice, no matter how long the string it refers to is. In\ngeneral, this is the way in which dynamically sized types are used in Rust:\nThey have an extra bit of metadata that stores the size of the dynamic\ninformation. The golden rule of dynamically sized types is that we must always\nput values of dynamically sized types behind a pointer of some kind.\nWe can combine `str` with all kinds of pointers: for example, `Box<str>` or\n`Rc<str>`. In fact, you’ve seen this before but with a different dynamically\nsized type: traits. Every trait is a dynamically sized type we can refer to by\nusing the name of the trait. In the “Using Trait Objects to Abstract over\nShared Behavior”\n section in Chapter 18, we mentioned that to use traits as trait\nobjects, we must put them behind a pointer, such as `&dyn Trait` or `Box<dyn\nTrait>` (`Rc<dyn Trait>` would work too).", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Types", "heading_path": ["Advanced Types", "Dynamically Sized Types and the `Sized` Trait"], "path": "ch20-03-advanced-types.md", "url": "https://doc.rust-lang.org/book/ch20-03-advanced-types.html#dynamically-sized-types-and-the-sized-trait", "has_code": false, "code_tags": []}} {"id": "book/ch20-03-advanced-types.md#dynamically-sized-types-and-the-sized-trait-10", "text": "The Rust Programming Language › Advanced Types › Dynamically Sized Types and the `Sized` Trait\n\nTo work with DSTs, Rust provides the `Sized` trait to determine whether or not\na type’s size is known at compile time. This trait is automatically implemented\nfor everything whose size is known at compile time. In addition, Rust\nimplicitly adds a bound on `Sized` to every generic function. That is, a\ngeneric function definition like this:\n```rust,ignore\nfn generic<T>(t: T) {\n // --snip--\n}\n```\nis actually treated as though we had written this:\n```rust,ignore\nfn generic<T: Sized>(t: T) {\n // --snip--\n}\n```\nBy default, generic functions will work only on types that have a known size at\ncompile time. However, you can use the following special syntax to relax this\nrestriction:\n```rust,ignore\nfn generic<T: ?Sized>(t: &T) {\n // --snip--\n}\n```\nA trait bound on `?Sized` means “`T` may or may not be `Sized`,” and this\nnotation overrides the default that generic types must have a known size at\ncompile time. The `?Trait` syntax with this meaning is only available for\n`Sized`, not any other traits.\nAlso note that we switched the type of the `t` parameter from `T` to `&T`.\nBecause the type might not be `Sized`, we need to use it behind some kind of\npointer. In this case, we’ve chosen a reference.\nNext, we’ll talk about functions and closures!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Types", "heading_path": ["Advanced Types", "Dynamically Sized Types and the `Sized` Trait"], "path": "ch20-03-advanced-types.md", "url": "https://doc.rust-lang.org/book/ch20-03-advanced-types.html#dynamically-sized-types-and-the-sized-trait", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch20-04-advanced-functions-and-closures.md#advanced-functions-and-closures-0", "text": "The Rust Programming Language › Advanced Functions and Closures\n\nThis section explores some advanced features related to functions and closures,\nincluding function pointers and returning closures.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Functions and Closures", "heading_path": ["Advanced Functions and Closures"], "path": "ch20-04-advanced-functions-and-closures.md", "url": "https://doc.rust-lang.org/book/ch20-04-advanced-functions-and-closures.html#advanced-functions-and-closures", "has_code": false, "code_tags": []}} {"id": "book/ch20-04-advanced-functions-and-closures.md#function-pointers-1", "text": "The Rust Programming Language › Advanced Functions and Closures › Function Pointers\n\nWe’ve talked about how to pass closures to functions; you can also pass regular\nfunctions to functions! This technique is useful when you want to pass a\nfunction you’ve already defined rather than defining a new closure. Functions\ncoerce to the type `fn` (with a lowercase _f_), not to be confused with the\n`Fn` closure trait. The `fn` type is called a _function pointer_. Passing\nfunctions with function pointers will allow you to use functions as arguments\nto other functions.\nThe syntax for specifying that a parameter is a function pointer is similar to\nthat of closures, as shown in Listing 20-28, where we’ve defined a function\n`add_one` that adds 1 to its parameter. The function `do_twice` takes two\nparameters: a function pointer to any function that takes an `i32` parameter\nand returns an `i32`, and one `i32` value. The `do_twice` function calls the\nfunction `f` twice, passing it the `arg` value, then adds the two function call\nresults together. The `main` function calls `do_twice` with the arguments\n`add_one` and `5`.\nListing 20-28: Using the `fn` type to accept a function pointer as an argument (src/main.rs)\n```rust\nfn add_one(x: i32) -> i32 {\n x + 1\n}\n\nfn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 {\n f(arg) + f(arg)\n}\n\nfn main() {\n let answer = do_twice(add_one, 5);\n\n println!(\"The answer is: {answer}\");\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Functions and Closures", "heading_path": ["Advanced Functions and Closures", "Function Pointers"], "path": "ch20-04-advanced-functions-and-closures.md", "url": "https://doc.rust-lang.org/book/ch20-04-advanced-functions-and-closures.html#function-pointers", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch20-04-advanced-functions-and-closures.md#function-pointers-2", "text": "The Rust Programming Language › Advanced Functions and Closures › Function Pointers\n\nThis code prints `The answer is: 12`. We specify that the parameter `f` in\n`do_twice` is an `fn` that takes one parameter of type `i32` and returns an\n`i32`. We can then call `f` in the body of `do_twice`. In `main`, we can pass\nthe function name `add_one` as the first argument to `do_twice`.\nUnlike closures, `fn` is a type rather than a trait, so we specify `fn` as the\nparameter type directly rather than declaring a generic type parameter with one\nof the `Fn` traits as a trait bound.\nFunction pointers implement all three of the closure traits (`Fn`, `FnMut`, and\n`FnOnce`), meaning you can always pass a function pointer as an argument for a\nfunction that expects a closure. It’s best to write functions using a generic\ntype and one of the closure traits so that your functions can accept either\nfunctions or closures.\nThat said, one example of where you would want to only accept `fn` and not\nclosures is when interfacing with external code that doesn’t have closures: C\nfunctions can accept functions as arguments, but C doesn’t have closures.\nAs an example of where you could use either a closure defined inline or a named\nfunction, let’s look at a use of the `map` method provided by the `Iterator`\ntrait in the standard library. To use the `map` method to turn a vector of\nnumbers into a vector of strings, we could use a closure, as in Listing 20-29.\nListing 20-29: Using a closure with the `map` method to convert numbers to strings\n```rust\n let list_of_numbers = vec![1, 2, 3];\n let list_of_strings: Vec<String> =\n list_of_numbers.iter().map(|i| i.to_string()).collect();\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Functions and Closures", "heading_path": ["Advanced Functions and Closures", "Function Pointers"], "path": "ch20-04-advanced-functions-and-closures.md", "url": "https://doc.rust-lang.org/book/ch20-04-advanced-functions-and-closures.html#function-pointers", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch20-04-advanced-functions-and-closures.md#function-pointers-3", "text": "The Rust Programming Language › Advanced Functions and Closures › Function Pointers\n\nOr we could name a function as the argument to `map` instead of the closure.\nListing 20-30 shows what this would look like.\nListing 20-30: Using the `String::to_string` function with the `map` method to convert numbers to strings\n```rust\n let list_of_numbers = vec![1, 2, 3];\n let list_of_strings: Vec<String> =\n list_of_numbers.iter().map(ToString::to_string).collect();\n```\nNote that we must use the fully qualified syntax that we talked about in the\n“Advanced Traits” section because there are\nmultiple functions available named `to_string`.\nHere, we’re using the `to_string` function defined in the `ToString` trait,\nwhich the standard library has implemented for any type that implements\n`Display`.\nRecall from the “Enum Values” section in Chapter\n6 that the name of each enum variant that we define also becomes an initializer\nfunction. We can use these initializer functions as function pointers that\nimplement the closure traits, which means we can specify the initializer\nfunctions as arguments for methods that take closures, as seen in Listing 20-31.\nListing 20-31: Using an enum initializer with the `map` method to create a `Status` instance from numbers\n```rust\n enum Status {\n Value(u32),\n Stop,\n }\n\n let list_of_statuses: Vec<Status> = (0u32..20).map(Status::Value).collect();\n```\nHere, we create `Status::Value` instances using each `u32` value in the range\nthat `map` is called on by using the initializer function of `Status::Value`.\nSome people prefer this style and some people prefer to use closures. They\ncompile to the same code, so use whichever style is clearer to you.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Functions and Closures", "heading_path": ["Advanced Functions and Closures", "Function Pointers"], "path": "ch20-04-advanced-functions-and-closures.md", "url": "https://doc.rust-lang.org/book/ch20-04-advanced-functions-and-closures.html#function-pointers", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch20-04-advanced-functions-and-closures.md#returning-closures-4", "text": "The Rust Programming Language › Advanced Functions and Closures › Returning Closures\n\nClosures are represented by traits, which means you can’t return closures\ndirectly. In most cases where you might want to return a trait, you can instead\nuse the concrete type that implements the trait as the return value of the\nfunction. However, you can’t usually do that with closures because they don’t\nhave a concrete type that is returnable; you’re not allowed to use the function\npointer `fn` as a return type if the closure captures any values from its\nscope, for example.\nInstead, you will normally use the `impl Trait` syntax we learned about in\nChapter 10. You can return any function type, using `Fn`, `FnOnce`, and `FnMut`.\nFor example, the code in Listing 20-32 will compile just fine.\nListing 20-32: Returning a closure from a function using the `impl Trait` syntax\n```rust\nfn returns_closure() -> impl Fn(i32) -> i32 {\n |x| x + 1\n}\n```\nHowever, as we noted in the “Inferring and Annotating Closure\nTypes” section in Chapter 13, each closure is\nalso its own distinct type. If you need to work with multiple functions that\nhave the same signature but different implementations, you will need to use a\ntrait object for them. Consider what happens if you write code like that shown\nin Listing 20-33.\nListing 20-33 (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Functions and Closures", "heading_path": ["Advanced Functions and Closures", "Returning Closures"], "path": "ch20-04-advanced-functions-and-closures.md", "url": "https://doc.rust-lang.org/book/ch20-04-advanced-functions-and-closures.html#returning-closures", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch20-04-advanced-functions-and-closures.md#returning-closures-5", "text": "The Rust Programming Language › Advanced Functions and Closures › Returning Closures\n\n```rust,ignore,does_not_compile\nfn main() {\n let handlers = vec![returns_closure(), returns_initialized_closure(123)];\n for handler in handlers {\n let output = handler(5);\n println!(\"{output}\");\n }\n}\n\nfn returns_closure() -> impl Fn(i32) -> i32 {\n |x| x + 1\n}\n\nfn returns_initialized_closure(init: i32) -> impl Fn(i32) -> i32 {\n move |x| x + init\n}\n```\nHere we have two functions, `returns_closure` and `returns_initialized_closure`,\nwhich both return `impl Fn(i32) -> i32`. Notice that the closures that they\nreturn are different, even though they implement the same type. If we try to\ncompile this, Rust lets us know that it won’t work:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Functions and Closures", "heading_path": ["Advanced Functions and Closures", "Returning Closures"], "path": "ch20-04-advanced-functions-and-closures.md", "url": "https://doc.rust-lang.org/book/ch20-04-advanced-functions-and-closures.html#returning-closures", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch20-04-advanced-functions-and-closures.md#returning-closures-6", "text": "The Rust Programming Language › Advanced Functions and Closures › Returning Closures\n\n```text\n$ cargo build\n Compiling functions-example v0.1.0 (file:///projects/functions-example)\nerror[E0308]: mismatched types\n --> src/main.rs:2:44\n |\n 2 | let handlers = vec![returns_closure(), returns_initialized_closure(123)];\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected opaque type, found a different opaque type\n...\n 9 | fn returns_closure() -> impl Fn(i32) -> i32 {\n | ------------------- the expected opaque type\n...\n13 | fn returns_initialized_closure(init: i32) -> impl Fn(i32) -> i32 {\n | ------------------- the found opaque type\n |\n = note: expected opaque type `impl Fn(i32) -> i32`\n found opaque type `impl Fn(i32) -> i32`\n = note: distinct uses of `impl Trait` result in different opaque types\n\nFor more information about this error, try `rustc --explain E0308`.\nerror: could not compile `functions-example` (bin \"functions-example\") due to 1 previous error\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Functions and Closures", "heading_path": ["Advanced Functions and Closures", "Returning Closures"], "path": "ch20-04-advanced-functions-and-closures.md", "url": "https://doc.rust-lang.org/book/ch20-04-advanced-functions-and-closures.html#returning-closures", "has_code": true, "code_tags": ["text"]}} {"id": "book/ch20-04-advanced-functions-and-closures.md#returning-closures-7", "text": "The Rust Programming Language › Advanced Functions and Closures › Returning Closures\n\nThe error message tells us that whenever we return an `impl Trait`, Rust\ncreates a unique _opaque type_, a type where we cannot see into the details of\nwhat Rust constructs for us, nor can we guess the type Rust will generate to\nwrite ourselves. So, even though these functions return closures that implement\nthe same trait, `Fn(i32) -> i32`, the opaque types Rust generates for each are\ndistinct. (This is similar to how Rust produces different concrete types for\ndistinct async blocks even when they have the same output type, as we saw in\n“The `Pin` Type and the `Unpin` Trait” in\nChapter 17.) We have seen a solution to this problem a few times now: We can\nuse a trait object, as in Listing 20-34.\nListing 20-34\n```rust\nfn returns_closure() -> Box<dyn Fn(i32) -> i32> {\n Box::new(|x| x + 1)\n}\n\nfn returns_initialized_closure(init: i32) -> Box<dyn Fn(i32) -> i32> {\n Box::new(move |x| x + init)\n}\n```\nThis code will compile just fine. For more about trait objects, refer to the\nsection “Using Trait Objects To Abstract over Shared\nBehavior” in Chapter 18.\nNext, let’s look at macros!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Advanced Functions and Closures", "heading_path": ["Advanced Functions and Closures", "Returning Closures"], "path": "ch20-04-advanced-functions-and-closures.md", "url": "https://doc.rust-lang.org/book/ch20-04-advanced-functions-and-closures.html#returning-closures", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch20-05-macros.md#macros-0", "text": "The Rust Programming Language › Macros\n\nWe’ve used macros like `println!` throughout this book, but we haven’t fully\nexplored what a macro is and how it works. The term _macro_ refers to a family\nof features in Rust—declarative macros with `macro_rules!` and three kinds of\nprocedural macros:\n- Custom `#[derive]` macros that specify code added with the `derive` attribute\n used on structs and enums\n- Attribute-like macros that define custom attributes usable on any item\n- Function-like macros that look like function calls but operate on the tokens\n specified as their argument\nWe’ll talk about each of these in turn, but first, let’s look at why we even\nneed macros when we already have functions.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Macros", "heading_path": ["Macros"], "path": "ch20-05-macros.md", "url": "https://doc.rust-lang.org/book/ch20-05-macros.html#macros", "has_code": false, "code_tags": []}} {"id": "book/ch20-05-macros.md#the-difference-between-macros-and-functions-1", "text": "The Rust Programming Language › Macros › The Difference Between Macros and Functions\n\nFundamentally, macros are a way of writing code that writes other code, which\nis known as _metaprogramming_. In Appendix C, we discuss the `derive`\nattribute, which generates an implementation of various traits for you. We’ve\nalso used the `println!` and `vec!` macros throughout the book. All of these\nmacros _expand_ to produce more code than the code you’ve written manually.\nMetaprogramming is useful for reducing the amount of code you have to write and\nmaintain, which is also one of the roles of functions. However, macros have\nsome additional powers that functions don’t have.\nA function signature must declare the number and type of parameters the\nfunction has. Macros, on the other hand, can take a variable number of\nparameters: We can call `println!(\"hello\")` with one argument or\n`println!(\"hello {}\", name)` with two arguments. Also, macros are expanded\nbefore the compiler interprets the meaning of the code, so a macro can, for\nexample, implement a trait on a given type. A function can’t, because it gets\ncalled at runtime and a trait needs to be implemented at compile time.\nThe downside to implementing a macro instead of a function is that macro\ndefinitions are more complex than function definitions because you’re writing\nRust code that writes Rust code. Due to this indirection, macro definitions are\ngenerally more difficult to read, understand, and maintain than function\ndefinitions.\nAnother important difference between macros and functions is that you must\ndefine macros or bring them into scope _before_ you call them in a file, as\nopposed to functions you can define anywhere and call anywhere.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Macros", "heading_path": ["Macros", "The Difference Between Macros and Functions"], "path": "ch20-05-macros.md", "url": "https://doc.rust-lang.org/book/ch20-05-macros.html#the-difference-between-macros-and-functions", "has_code": false, "code_tags": []}} {"id": "book/ch20-05-macros.md#declarative-macros-for-general-metaprogramming-2", "text": "The Rust Programming Language › Macros › Declarative Macros for General Metaprogramming\n\nThe most widely used form of macros in Rust is the _declarative macro_. These\nare also sometimes referred to as “macros by example,” “`macro_rules!` macros,”\nor just plain “macros.” At their core, declarative macros allow you to write\nsomething similar to a Rust `match` expression. As discussed in Chapter 6,\n`match` expressions are control structures that take an expression, compare the\nresultant value of the expression to patterns, and then run the code associated\nwith the matching pattern. Macros also compare a value to patterns that are\nassociated with particular code: In this situation, the value is the literal\nRust source code passed to the macro; the patterns are compared with the\nstructure of that source code; and the code associated with each pattern, when\nmatched, replaces the code passed to the macro. This all happens during\ncompilation.\nTo define a macro, you use the `macro_rules!` construct. Let’s explore how to\nuse `macro_rules!` by looking at how the `vec!` macro is defined. Chapter 8\ncovered how we can use the `vec!` macro to create a new vector with particular\nvalues. For example, the following macro creates a new vector containing three\nintegers:\n```rust\nlet v: Vec<u32> = vec![1, 2, 3];\n```\nWe could also use the `vec!` macro to make a vector of two integers or a vector\nof five string slices. We wouldn’t be able to use a function to do the same\nbecause we wouldn’t know the number or type of values up front.\nListing 20-35 shows a slightly simplified definition of the `vec!` macro.\nListing 20-35: A simplified version of the `vec!` macro definition (src/lib.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Macros", "heading_path": ["Macros", "Declarative Macros for General Metaprogramming"], "path": "ch20-05-macros.md", "url": "https://doc.rust-lang.org/book/ch20-05-macros.html#declarative-macros-for-general-metaprogramming", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch20-05-macros.md#declarative-macros-for-general-metaprogramming-3", "text": "The Rust Programming Language › Macros › Declarative Macros for General Metaprogramming\n\n```rust,noplayground\n#[macro_export]\nmacro_rules! vec {\n ( $( $x:expr ),* ) => {\n {\n let mut temp_vec = Vec::new();\n $(\n temp_vec.push($x);\n )*\n temp_vec\n }\n };\n}\n```\nNote: The actual definition of the `vec!` macro in the standard library\nincludes code to pre-allocate the correct amount of memory up front. That code\nis an optimization that we don’t include here, to make the example simpler.\nThe `#[macro_export]` annotation indicates that this macro should be made\navailable whenever the crate in which the macro is defined is brought into\nscope. Without this annotation, the macro can’t be brought into scope.\nWe then start the macro definition with `macro_rules!` and the name of the\nmacro we’re defining _without_ the exclamation mark. The name, in this case\n`vec`, is followed by curly brackets denoting the body of the macro definition.\nThe structure in the `vec!` body is similar to the structure of a `match`\nexpression. Here we have one arm with the pattern `( $( $x:expr ),* )`,\nfollowed by `=>` and the block of code associated with this pattern. If the\npattern matches, the associated block of code will be emitted. Given that this\nis the only pattern in this macro, there is only one valid way to match; any\nother pattern will result in an error. More complex macros will have more than\none arm.\nValid pattern syntax in macro definitions is different from the pattern syntax\ncovered in Chapter 19 because macro patterns are matched against Rust code\nstructure rather than values. Let’s walk through what the pattern pieces in\nListing 20-29 mean; for the full macro pattern syntax, see the Rust\nReference.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Macros", "heading_path": ["Macros", "Declarative Macros for General Metaprogramming"], "path": "ch20-05-macros.md", "url": "https://doc.rust-lang.org/book/ch20-05-macros.html#declarative-macros-for-general-metaprogramming", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch20-05-macros.md#declarative-macros-for-general-metaprogramming-4", "text": "The Rust Programming Language › Macros › Declarative Macros for General Metaprogramming\n\nFirst, we use a set of parentheses to encompass the whole pattern. We use a\ndollar sign (`$`) to declare a variable in the macro system that will contain\nthe Rust code matching the pattern. The dollar sign makes it clear this is a\nmacro variable as opposed to a regular Rust variable. Next comes a set of\nparentheses that captures values that match the pattern within the parentheses\nfor use in the replacement code. Within `$()` is `$x:expr`, which matches any\nRust expression and gives the expression the name `$x`.\nThe comma following `$()` indicates that a literal comma separator character\nmust appear between each instance of the code that matches the code in `$()`.\nThe `*` specifies that the pattern matches zero or more of whatever precedes\nthe `*`.\nWhen we call this macro with `vec![1, 2, 3];`, the `$x` pattern matches three\ntimes with the three expressions `1`, `2`, and `3`.\nNow let’s look at the pattern in the body of the code associated with this arm:\n`temp_vec.push()` within `$()*` is generated for each part that matches `$()`\nin the pattern zero or more times depending on how many times the pattern\nmatches. The `$x` is replaced with each expression matched. When we call this\nmacro with `vec![1, 2, 3];`, the code generated that replaces this macro call\nwill be the following:\n```rust,ignore\n{\n let mut temp_vec = Vec::new();\n temp_vec.push(1);\n temp_vec.push(2);\n temp_vec.push(3);\n temp_vec\n}\n```\nWe’ve defined a macro that can take any number of arguments of any type and can\ngenerate code to create a vector containing the specified elements.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Macros", "heading_path": ["Macros", "Declarative Macros for General Metaprogramming"], "path": "ch20-05-macros.md", "url": "https://doc.rust-lang.org/book/ch20-05-macros.html#declarative-macros-for-general-metaprogramming", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch20-05-macros.md#declarative-macros-for-general-metaprogramming-5", "text": "The Rust Programming Language › Macros › Declarative Macros for General Metaprogramming\n\nTo learn more about how to write macros, consult the online documentation or\nother resources, such as “The Little Book of Rust Macros” started by\nDaniel Keep and continued by Lukas Wirth.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Macros", "heading_path": ["Macros", "Declarative Macros for General Metaprogramming"], "path": "ch20-05-macros.md", "url": "https://doc.rust-lang.org/book/ch20-05-macros.html#declarative-macros-for-general-metaprogramming", "has_code": false, "code_tags": []}} {"id": "book/ch20-05-macros.md#procedural-macros-for-generating-code-from-attributes-6", "text": "The Rust Programming Language › Macros › Procedural Macros for Generating Code from Attributes\n\nThe second form of macros is the procedural macro, which acts more like a\nfunction (and is a type of procedure). _Procedural macros_ accept some code as\nan input, operate on that code, and produce some code as an output rather than\nmatching against patterns and replacing the code with other code as declarative\nmacros do. The three kinds of procedural macros are custom `derive`,\nattribute-like, and function-like, and all work in a similar fashion.\nWhen creating procedural macros, the definitions must reside in their own crate\nwith a special crate type. This is for complex technical reasons that we hope\nto eliminate in the future. In Listing 20-36, we show how to define a\nprocedural macro, where `some_attribute` is a placeholder for using a specific\nmacro variety.\nListing 20-36: An example of defining a procedural macro (src/lib.rs)\n```rust,ignore\nuse proc_macro::TokenStream;\n\n#[some_attribute]\npub fn some_name(input: TokenStream) -> TokenStream {\n}\n```\nThe function that defines a procedural macro takes a `TokenStream` as an input\nand produces a `TokenStream` as an output. The `TokenStream` type is defined by\nthe `proc_macro` crate that is included with Rust and represents a sequence of\ntokens. This is the core of the macro: The source code that the macro is\noperating on makes up the input `TokenStream`, and the code the macro produces\nis the output `TokenStream`. The function also has an attribute attached to it\nthat specifies which kind of procedural macro we’re creating. We can have\nmultiple kinds of procedural macros in the same crate.\nLet’s look at the different kinds of procedural macros. We’ll start with a\ncustom `derive` macro and then explain the small dissimilarities that make the\nother forms different.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Macros", "heading_path": ["Macros", "Procedural Macros for Generating Code from Attributes"], "path": "ch20-05-macros.md", "url": "https://doc.rust-lang.org/book/ch20-05-macros.html#procedural-macros-for-generating-code-from-attributes", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch20-05-macros.md#custom-derive-macros-7", "text": "The Rust Programming Language › Macros › Custom `derive` Macros\n\nLet’s create a crate named `hello_macro` that defines a trait named\n`HelloMacro` with one associated function named `hello_macro`. Rather than\nmaking our users implement the `HelloMacro` trait for each of their types,\nwe’ll provide a procedural macro so that users can annotate their type with\n`#[derive(HelloMacro)]` to get a default implementation of the `hello_macro`\nfunction. The default implementation will print `Hello, Macro! My name is\nTypeName!` where `TypeName` is the name of the type on which this trait has\nbeen defined. In other words, we’ll write a crate that enables another\nprogrammer to write code like Listing 20-37 using our crate.\nListing 20-37: The code a user of our crate will be able to write when using our procedural macro (src/main.rs)\n```rust,ignore,does_not_compile\nuse hello_macro::HelloMacro;\nuse hello_macro_derive::HelloMacro;\n\n#[derive(HelloMacro)]\nstruct Pancakes;\n\nfn main() {\n Pancakes::hello_macro();\n}\n```\nThis code will print `Hello, Macro! My name is Pancakes!` when we’re done. The\nfirst step is to make a new library crate, like this:\n```console\n$ cargo new hello_macro --lib\n```\nNext, in Listing 20-38, we’ll define the `HelloMacro` trait and its associated\nfunction.\nListing 20-38: A simple trait that we will use with the `derive` macro (src/lib.rs)\n```rust,noplayground\npub trait HelloMacro {\n fn hello_macro();\n}\n```\nWe have a trait and its function. At this point, our crate user could implement\nthe trait to achieve the desired functionality, as in Listing 20-39.\nListing 20-39: How it would look if users wrote a manual implementation of the `HelloMacro` trait (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Macros", "heading_path": ["Macros", "Custom `derive` Macros"], "path": "ch20-05-macros.md", "url": "https://doc.rust-lang.org/book/ch20-05-macros.html#custom-derive-macros", "has_code": true, "code_tags": ["console", "rust,ignore,does_not_compile", "rust,noplayground"]}} {"id": "book/ch20-05-macros.md#custom-derive-macros-8", "text": "The Rust Programming Language › Macros › Custom `derive` Macros\n\n```rust,ignore\nuse hello_macro::HelloMacro;\n\nstruct Pancakes;\n\nimpl HelloMacro for Pancakes {\n fn hello_macro() {\n println!(\"Hello, Macro! My name is Pancakes!\");\n }\n}\n\nfn main() {\n Pancakes::hello_macro();\n}\n```\nHowever, they would need to write the implementation block for each type they\nwanted to use with `hello_macro`; we want to spare them from having to do this\nwork.\nAdditionally, we can’t yet provide the `hello_macro` function with default\nimplementation that will print the name of the type the trait is implemented\non: Rust doesn’t have reflection capabilities, so it can’t look up the type’s\nname at runtime. We need a macro to generate code at compile time.\nThe next step is to define the procedural macro. At the time of this writing,\nprocedural macros need to be in their own crate. Eventually, this restriction\nmight be lifted. The convention for structuring crates and macro crates is as\nfollows: For a crate named `foo`, a custom `derive` procedural macro crate is\ncalled `foo_derive`. Let’s start a new crate called `hello_macro_derive` inside\nour `hello_macro` project:\n```console\n$ cargo new hello_macro_derive --lib\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Macros", "heading_path": ["Macros", "Custom `derive` Macros"], "path": "ch20-05-macros.md", "url": "https://doc.rust-lang.org/book/ch20-05-macros.html#custom-derive-macros", "has_code": true, "code_tags": ["console", "rust,ignore"]}} {"id": "book/ch20-05-macros.md#custom-derive-macros-9", "text": "The Rust Programming Language › Macros › Custom `derive` Macros\n\nOur two crates are tightly related, so we create the procedural macro crate\nwithin the directory of our `hello_macro` crate. If we change the trait\ndefinition in `hello_macro`, we’ll have to change the implementation of the\nprocedural macro in `hello_macro_derive` as well. The two crates will need to\nbe published separately, and programmers using these crates will need to add\nboth as dependencies and bring them both into scope. We could instead have the\n`hello_macro` crate use `hello_macro_derive` as a dependency and re-export the\nprocedural macro code. However, the way we’ve structured the project makes it\npossible for programmers to use `hello_macro` even if they don’t want the\n`derive` functionality.\nWe need to declare the `hello_macro_derive` crate as a procedural macro crate.\nWe’ll also need functionality from the `syn` and `quote` crates, as you’ll see\nin a moment, so we need to add them as dependencies. Add the following to the\n_Cargo.toml_ file for `hello_macro_derive`:\nListing (hello_macro_derive/Cargo.toml)\n```toml\n[lib]\nproc-macro = true\n\n[dependencies]\nsyn = \"2.0\"\nquote = \"1.0\"\n```\nTo start defining the procedural macro, place the code in Listing 20-40 into\nyour _src/lib.rs_ file for the `hello_macro_derive` crate. Note that this code\nwon’t compile until we add a definition for the `impl_hello_macro` function.\nListing 20-40: Code that most procedural macro crates will require in order to process Rust code (hello_macro_derive/src/lib.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Macros", "heading_path": ["Macros", "Custom `derive` Macros"], "path": "ch20-05-macros.md", "url": "https://doc.rust-lang.org/book/ch20-05-macros.html#custom-derive-macros", "has_code": true, "code_tags": ["toml"]}} {"id": "book/ch20-05-macros.md#custom-derive-macros-10", "text": "The Rust Programming Language › Macros › Custom `derive` Macros\n\n```rust,ignore,does_not_compile\nuse proc_macro::TokenStream;\nuse quote::quote;\n\n#[proc_macro_derive(HelloMacro)]\npub fn hello_macro_derive(input: TokenStream) -> TokenStream {\n // Construct a representation of Rust code as a syntax tree\n // that we can manipulate.\n let ast = syn::parse(input).unwrap();\n\n // Build the trait implementation.\n impl_hello_macro(&ast)\n}\n```\nNotice that we’ve split the code into the `hello_macro_derive` function, which\nis responsible for parsing the `TokenStream`, and the `impl_hello_macro`\nfunction, which is responsible for transforming the syntax tree: This makes\nwriting a procedural macro more convenient. The code in the outer function\n(`hello_macro_derive` in this case) will be the same for almost every\nprocedural macro crate you see or create. The code you specify in the body of\nthe inner function (`impl_hello_macro` in this case) will be different\ndepending on your procedural macro’s purpose.\nWe’ve introduced three new crates: `proc_macro`, `syn`,\nand `quote`. The `proc_macro` crate comes with Rust,\nso we didn’t need to add that to the dependencies in _Cargo.toml_. The\n`proc_macro` crate is the compiler’s API that allows us to read and manipulate\nRust code from our code.\nThe `syn` crate parses Rust code from a string into a data structure that we\ncan perform operations on. The `quote` crate turns `syn` data structures back\ninto Rust code. These crates make it much simpler to parse any sort of Rust\ncode we might want to handle: Writing a full parser for Rust code is no simple\ntask.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Macros", "heading_path": ["Macros", "Custom `derive` Macros"], "path": "ch20-05-macros.md", "url": "https://doc.rust-lang.org/book/ch20-05-macros.html#custom-derive-macros", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch20-05-macros.md#custom-derive-macros-11", "text": "The Rust Programming Language › Macros › Custom `derive` Macros\n\nThe `hello_macro_derive` function will be called when a user of our library\nspecifies `#[derive(HelloMacro)]` on a type. This is possible because we’ve\nannotated the `hello_macro_derive` function here with `proc_macro_derive` and\nspecified the name `HelloMacro`, which matches our trait name; this is the\nconvention most procedural macros follow.\nThe `hello_macro_derive` function first converts the `input` from a\n`TokenStream` to a data structure that we can then interpret and perform\noperations on. This is where `syn` comes into play. The `parse` function in\n`syn` takes a `TokenStream` and returns a `DeriveInput` struct representing the\nparsed Rust code. Listing 20-41 shows the relevant parts of the `DeriveInput`\nstruct we get from parsing the `struct Pancakes;` string.\nListing 20-41: The `DeriveInput` instance we get when parsing the code that has the macro’s attribute in Listing 20-37\n```rust,ignore\nDeriveInput {\n // --snip--\n\n ident: Ident {\n ident: \"Pancakes\",\n span: #0 bytes(95..103)\n },\n data: Struct(\n DataStruct {\n struct_token: Struct,\n fields: Unit,\n semi_token: Some(\n Semi\n )\n }\n )\n}\n```\nThe fields of this struct show that the Rust code we’ve parsed is a unit struct\nwith the `ident` (_identifier_, meaning the name) of `Pancakes`. There are more\nfields on this struct for describing all sorts of Rust code; check the `syn`\ndocumentation for `DeriveInput` for more information.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Macros", "heading_path": ["Macros", "Custom `derive` Macros"], "path": "ch20-05-macros.md", "url": "https://doc.rust-lang.org/book/ch20-05-macros.html#custom-derive-macros", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch20-05-macros.md#custom-derive-macros-12", "text": "The Rust Programming Language › Macros › Custom `derive` Macros\n\nSoon we’ll define the `impl_hello_macro` function, which is where we’ll build\nthe new Rust code we want to include. But before we do, note that the output\nfor our `derive` macro is also a `TokenStream`. The returned `TokenStream` is\nadded to the code that our crate users write, so when they compile their crate,\nthey’ll get the extra functionality that we provide in the modified\n`TokenStream`.\nYou might have noticed that we’re calling `unwrap` to cause the\n`hello_macro_derive` function to panic if the call to the `syn::parse` function\nfails here. It’s necessary for our procedural macro to panic on errors because\n`proc_macro_derive` functions must return `TokenStream` rather than `Result` to\nconform to the procedural macro API. We’ve simplified this example by using\n`unwrap`; in production code, you should provide more specific error messages\nabout what went wrong by using `panic!` or `expect`.\nNow that we have the code to turn the annotated Rust code from a `TokenStream`\ninto a `DeriveInput` instance, let’s generate the code that implements the\n`HelloMacro` trait on the annotated type, as shown in Listing 20-42.\nListing 20-42: Implementing the `HelloMacro` trait using the parsed Rust code (hello_macro_derive/src/lib.rs)\n```rust,ignore\nfn impl_hello_macro(ast: &syn::DeriveInput) -> TokenStream {\n let name = &ast.ident;\n let generated = quote! {\n impl HelloMacro for #name {\n fn hello_macro() {\n println!(\"Hello, Macro! My name is {}!\", stringify!(#name));\n }\n }\n };\n generated.into()\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Macros", "heading_path": ["Macros", "Custom `derive` Macros"], "path": "ch20-05-macros.md", "url": "https://doc.rust-lang.org/book/ch20-05-macros.html#custom-derive-macros", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch20-05-macros.md#custom-derive-macros-13", "text": "The Rust Programming Language › Macros › Custom `derive` Macros\n\nWe get an `Ident` struct instance containing the name (identifier) of the\nannotated type using `ast.ident`. The struct in Listing 20-41 shows that when\nwe run the `impl_hello_macro` function on the code in Listing 20-37, the\n`ident` we get will have the `ident` field with a value of `\"Pancakes\"`. Thus,\nthe `name` variable in Listing 20-42 will contain an `Ident` struct instance\nthat, when printed, will be the string `\"Pancakes\"`, the name of the struct in\nListing 20-37.\nThe `quote!` macro lets us define the Rust code that we want to return. The\ncompiler expects something different from the direct result of the `quote!`\nmacro’s execution, so we need to convert it to a `TokenStream`. We do this by\ncalling the `into` method, which consumes this intermediate representation and\nreturns a value of the required `TokenStream` type.\nThe `quote!` macro also provides some very cool templating mechanics: We can\nenter `#name`, and `quote!` will replace it with the value in the variable\n`name`. You can even do some repetition similar to the way regular macros work.\nCheck out the `quote` crate’s docs for a thorough introduction.\nWe want our procedural macro to generate an implementation of our `HelloMacro`\ntrait for the type the user annotated, which we can get by using `#name`. The\ntrait implementation has the one function `hello_macro`, whose body contains the\nfunctionality we want to provide: printing `Hello, Macro! My name is` and then\nthe name of the annotated type.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Macros", "heading_path": ["Macros", "Custom `derive` Macros"], "path": "ch20-05-macros.md", "url": "https://doc.rust-lang.org/book/ch20-05-macros.html#custom-derive-macros", "has_code": false, "code_tags": []}} {"id": "book/ch20-05-macros.md#custom-derive-macros-14", "text": "The Rust Programming Language › Macros › Custom `derive` Macros\n\nThe `stringify!` macro used here is built into Rust. It takes a Rust\nexpression, such as `1 + 2`, and at compile time turns the expression into a\nstring literal, such as `\"1 + 2\"`. This is different from `format!` or\n`println!`, which are macros that evaluate the expression and then turn the\nresult into a `String`. There is a possibility that the `#name` input might be\nan expression to print literally, so we use `stringify!`. Using `stringify!`\nalso saves an allocation by converting `#name` to a string literal at compile\ntime.\nAt this point, `cargo build` should complete successfully in both `hello_macro`\nand `hello_macro_derive`. Let’s hook up these crates to the code in Listing\n20-37 to see the procedural macro in action! Create a new binary project in\nyour _projects_ directory using `cargo new pancakes`. We need to add\n`hello_macro` and `hello_macro_derive` as dependencies in the `pancakes`\ncrate’s _Cargo.toml_. If you’re publishing your versions of `hello_macro` and\n`hello_macro_derive` to crates.io, they\nwould be regular dependencies; if not, you can specify them as `path`\ndependencies as follows:\n```toml\n[dependencies]\nhello_macro = { path = \"../hello_macro\" }\nhello_macro_derive = { path = \"../hello_macro/hello_macro_derive\" }\n```\nPut the code in Listing 20-37 into _src/main.rs_, and run `cargo run`: It\nshould print `Hello, Macro! My name is Pancakes!`. The implementation of the\n`HelloMacro` trait from the procedural macro was included without the\n`pancakes` crate needing to implement it; the `#[derive(HelloMacro)]` added the\ntrait implementation.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Macros", "heading_path": ["Macros", "Custom `derive` Macros"], "path": "ch20-05-macros.md", "url": "https://doc.rust-lang.org/book/ch20-05-macros.html#custom-derive-macros", "has_code": true, "code_tags": ["toml"]}} {"id": "book/ch20-05-macros.md#custom-derive-macros-15", "text": "The Rust Programming Language › Macros › Custom `derive` Macros\n\nNext, let’s explore how the other kinds of procedural macros differ from custom\n`derive` macros.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Macros", "heading_path": ["Macros", "Custom `derive` Macros"], "path": "ch20-05-macros.md", "url": "https://doc.rust-lang.org/book/ch20-05-macros.html#custom-derive-macros", "has_code": false, "code_tags": []}} {"id": "book/ch20-05-macros.md#attribute-like-macros-16", "text": "The Rust Programming Language › Macros › Attribute-Like Macros\n\nAttribute-like macros are similar to custom `derive` macros, but instead of\ngenerating code for the `derive` attribute, they allow you to create new\nattributes. They’re also more flexible: `derive` only works for structs and\nenums; attributes can be applied to other items as well, such as functions.\nHere’s an example of using an attribute-like macro. Say you have an attribute\nnamed `route` that annotates functions when using a web application framework:\n```rust,ignore\n#[route(GET, \"/\")]\nfn index() {\n```\nThis `#[route]` attribute would be defined by the framework as a procedural\nmacro. The signature of the macro definition function would look like this:\n```rust,ignore\n#[proc_macro_attribute]\npub fn route(attr: TokenStream, item: TokenStream) -> TokenStream {\n```\nHere, we have two parameters of type `TokenStream`. The first is for the\ncontents of the attribute: the `GET, \"/\"` part. The second is the body of the\nitem the attribute is attached to: in this case, `fn index() {}` and the rest\nof the function’s body.\nOther than that, attribute-like macros work the same way as custom `derive`\nmacros: You create a crate with the `proc-macro` crate type and implement a\nfunction that generates the code you want!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Macros", "heading_path": ["Macros", "Attribute-Like Macros"], "path": "ch20-05-macros.md", "url": "https://doc.rust-lang.org/book/ch20-05-macros.html#attribute-like-macros", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch20-05-macros.md#function-like-macros-17", "text": "The Rust Programming Language › Macros › Function-Like Macros\n\nFunction-like macros define macros that look like function calls. Similarly to\n`macro_rules!` macros, they’re more flexible than functions; for example, they\ncan take an unknown number of arguments. However, `macro_rules!` macros can\nonly be defined using the match-like syntax we discussed in the “Declarative\nMacros for General Metaprogramming” section earlier.\nFunction-like macros take a `TokenStream` parameter, and their definition\nmanipulates that `TokenStream` using Rust code as the other two types of\nprocedural macros do. An example of a function-like macro is an `sql!` macro\nthat might be called like so:\n```rust,ignore\nlet sql = sql!(SELECT * FROM posts WHERE id=1);\n```\nThis macro would parse the SQL statement inside it and check that it’s\nsyntactically correct, which is much more complex processing than a\n`macro_rules!` macro can do. The `sql!` macro would be defined like this:\n```rust,ignore\n#[proc_macro]\npub fn sql(input: TokenStream) -> TokenStream {\n```\nThis definition is similar to the custom `derive` macro’s signature: We receive\nthe tokens that are inside the parentheses and return the code we wanted to\ngenerate.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Macros", "heading_path": ["Macros", "Function-Like Macros"], "path": "ch20-05-macros.md", "url": "https://doc.rust-lang.org/book/ch20-05-macros.html#function-like-macros", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch20-05-macros.md#summary-18", "text": "The Rust Programming Language › Summary\n\nWhew! Now you have some Rust features in your toolbox that you likely won’t use\noften, but you’ll know they’re available in very particular circumstances.\nWe’ve introduced several complex topics so that when you encounter them in\nerror message suggestions or in other people’s code, you’ll be able to\nrecognize these concepts and syntax. Use this chapter as a reference to guide\nyou to solutions.\nNext, we’ll put everything we’ve discussed throughout the book into practice\nand do one more project!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Macros", "heading_path": ["Summary"], "path": "ch20-05-macros.md", "url": "https://doc.rust-lang.org/book/ch20-05-macros.html#summary", "has_code": false, "code_tags": []}} {"id": "book/ch21-00-final-project-a-web-server.md#final-project-building-a-multithreaded-web-server-0", "text": "The Rust Programming Language › Final Project: Building a Multithreaded Web Server\n\nIt’s been a long journey, but we’ve reached the end of the book. In this\nchapter, we’ll build one more project together to demonstrate some of the\nconcepts we covered in the final chapters, as well as recap some earlier\nlessons.\nFor our final project, we’ll make a web server that says “Hello!” and looks like\nFigure 21-1 in a web browser.\nHere is our plan for building the web server:\n1. Learn a bit about TCP and HTTP.\n2. Listen for TCP connections on a socket.\n3. Parse a small number of HTTP requests.\n4. Create a proper HTTP response.\n5. Improve the throughput of our server with a thread pool.\n<img alt=\"Screenshot of a web browser visiting the address 127.0.0.1:8080 displaying a webpage with the text content “Hello! Hi from Rust”\" src=\"img/trpl21-01.png\" class=\"center\" style=\"width: 50%;\" />\n<span class=\"caption\">Figure 21-1: Our final shared project</span>\nBefore we get started, we should mention two details. First, the method we’ll\nuse won’t be the best way to build a web server with Rust. Community members\nhave published a number of production-ready crates available at\ncrates.io that provide more complete web server and\nthread pool implementations than we’ll build. However, our intention in this\nchapter is to help you learn, not to take the easy route. Because Rust is a\nsystems programming language, we can choose the level of abstraction we want to\nwork with and can go to a lower level than is possible or practical in other\nlanguages.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Final Project: Building a Multithreaded Web Server", "heading_path": ["Final Project: Building a Multithreaded Web Server"], "path": "ch21-00-final-project-a-web-server.md", "url": "https://doc.rust-lang.org/book/ch21-00-final-project-a-web-server.html#final-project-building-a-multithreaded-web-server", "has_code": false, "code_tags": []}} {"id": "book/ch21-00-final-project-a-web-server.md#final-project-building-a-multithreaded-web-server-1", "text": "The Rust Programming Language › Final Project: Building a Multithreaded Web Server\n\nSecond, we will not be using async and await here. Building a thread pool is a\nbig enough challenge on its own, without adding in building an async runtime!\nHowever, we will note how async and await might be applicable to some of the\nsame problems we will see in this chapter. Ultimately, as we noted back in\nChapter 17, many async runtimes use thread pools for managing their work.\nWe’ll therefore write the basic HTTP server and thread pool manually so that\nyou can learn the general ideas and techniques behind the crates you might use\nin the future.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Final Project: Building a Multithreaded Web Server", "heading_path": ["Final Project: Building a Multithreaded Web Server"], "path": "ch21-00-final-project-a-web-server.md", "url": "https://doc.rust-lang.org/book/ch21-00-final-project-a-web-server.html#final-project-building-a-multithreaded-web-server", "has_code": false, "code_tags": []}} {"id": "book/ch21-01-single-threaded.md#building-a-single-threaded-web-server-0", "text": "The Rust Programming Language › Building a Single-Threaded Web Server\n\nWe’ll start by getting a single-threaded web server working. Before we begin,\nlet’s look at a quick overview of the protocols involved in building web\nservers. The details of these protocols are beyond the scope of this book, but\na brief overview will give you the information you need.\nThe two main protocols involved in web servers are _Hypertext Transfer\nProtocol_ _(HTTP)_ and _Transmission Control Protocol_ _(TCP)_. Both protocols\nare _request-response_ protocols, meaning a _client_ initiates requests and a\n_server_ listens to the requests and provides a response to the client. The\ncontents of those requests and responses are defined by the protocols.\nTCP is the lower-level protocol that describes the details of how information\ngets from one server to another but doesn’t specify what that information is.\nHTTP builds on top of TCP by defining the contents of the requests and\nresponses. It’s technically possible to use HTTP with other protocols, but in\nthe vast majority of cases, HTTP sends its data over TCP. We’ll work with the\nraw bytes of TCP and HTTP requests and responses.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Building a Single-Threaded Web Server", "heading_path": ["Building a Single-Threaded Web Server"], "path": "ch21-01-single-threaded.md", "url": "https://doc.rust-lang.org/book/ch21-01-single-threaded.html#building-a-single-threaded-web-server", "has_code": false, "code_tags": []}} {"id": "book/ch21-01-single-threaded.md#listening-to-the-tcp-connection-1", "text": "The Rust Programming Language › Building a Single-Threaded Web Server › Listening to the TCP Connection\n\nOur web server needs to listen to a TCP connection, so that’s the first part\nwe’ll work on. The standard library offers a `std::net` module that lets us do\nthis. Let’s make a new project in the usual fashion:\n```console\n$ cargo new hello\n Created binary (application) `hello` project\n$ cd hello\n```\nNow enter the code in Listing 21-1 in _src/main.rs_ to start. This code will\nlisten at the local address `127.0.0.1:7878` for incoming TCP streams. When it\ngets an incoming stream, it will print `Connection established!`.\nListing 21-1: Listening for incoming streams and printing a message when we receive a stream (src/main.rs)\n```rust,no_run\nuse std::net::TcpListener;\n\nfn main() {\n let listener = TcpListener::bind(\"127.0.0.1:7878\").unwrap();\n\n for stream in listener.incoming() {\n let stream = stream.unwrap();\n\n println!(\"Connection established!\");\n }\n}\n```\nUsing `TcpListener`, we can listen for TCP connections at the address\n`127.0.0.1:7878`. In the address, the section before the colon is an IP address\nrepresenting your computer (this is the same on every computer and doesn’t\nrepresent the authors’ computer specifically), and `7878` is the port. We’ve\nchosen this port for two reasons: HTTP isn’t normally accepted on this port, so\nour server is unlikely to conflict with any other web server you might have\nrunning on your machine, and 7878 is _rust_ typed on a telephone.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Building a Single-Threaded Web Server", "heading_path": ["Building a Single-Threaded Web Server", "Listening to the TCP Connection"], "path": "ch21-01-single-threaded.md", "url": "https://doc.rust-lang.org/book/ch21-01-single-threaded.html#listening-to-the-tcp-connection", "has_code": true, "code_tags": ["console", "rust,no_run"]}} {"id": "book/ch21-01-single-threaded.md#listening-to-the-tcp-connection-2", "text": "The Rust Programming Language › Building a Single-Threaded Web Server › Listening to the TCP Connection\n\nThe `bind` function in this scenario works like the `new` function in that it\nwill return a new `TcpListener` instance. The function is called `bind`\nbecause, in networking, connecting to a port to listen to is known as “binding\nto a port.”\nThe `bind` function returns a `Result<T, E>`, which indicates that it’s\npossible for binding to fail, for example, if we ran two instances of our\nprogram and so had two programs listening to the same port. Because we’re\nwriting a basic server just for learning purposes, we won’t worry about\nhandling these kinds of errors; instead, we use `unwrap` to stop the program if\nerrors happen.\nThe `incoming` method on `TcpListener` returns an iterator that gives us a\nsequence of streams (more specifically, streams of type `TcpStream`). A single\n_stream_ represents an open connection between the client and the server.\n_Connection_ is the name for the full request and response process in which a\nclient connects to the server, the server generates a response, and the server\ncloses the connection. As such, we will read from the `TcpStream` to see what\nthe client sent and then write our response to the stream to send data back to\nthe client. Overall, this `for` loop will process each connection in turn and\nproduce a series of streams for us to handle.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Building a Single-Threaded Web Server", "heading_path": ["Building a Single-Threaded Web Server", "Listening to the TCP Connection"], "path": "ch21-01-single-threaded.md", "url": "https://doc.rust-lang.org/book/ch21-01-single-threaded.html#listening-to-the-tcp-connection", "has_code": false, "code_tags": []}} {"id": "book/ch21-01-single-threaded.md#listening-to-the-tcp-connection-3", "text": "The Rust Programming Language › Building a Single-Threaded Web Server › Listening to the TCP Connection\n\nFor now, our handling of the stream consists of calling `unwrap` to terminate\nour program if the stream has any errors; if there aren’t any errors, the\nprogram prints a message. We’ll add more functionality for the success case in\nthe next listing. The reason we might receive errors from the `incoming` method\nwhen a client connects to the server is that we’re not actually iterating over\nconnections. Instead, we’re iterating over _connection attempts_. The\nconnection might not be successful for a number of reasons, many of them\noperating system specific. For example, many operating systems have a limit to\nthe number of simultaneous open connections they can support; new connection\nattempts beyond that number will produce an error until some of the open\nconnections are closed.\nLet’s try running this code! Invoke `cargo run` in the terminal and then load\n_127.0.0.1:7878_ in a web browser. The browser should show an error message\nlike “Connection reset” because the server isn’t currently sending back any\ndata. But when you look at your terminal, you should see several messages that\nwere printed when the browser connected to the server!\n```text\n Running `target/debug/hello`\nConnection established!\nConnection established!\nConnection established!\n```\nSometimes you’ll see multiple messages printed for one browser request; the\nreason might be that the browser is making a request for the page as well as a\nrequest for other resources, like the _favicon.ico_ icon that appears in the\nbrowser tab.\nIt could also be that the browser is trying to connect to the server multiple\ntimes because the server isn’t responding with any data. When `stream` goes out\nof scope and is dropped at the end of the loop, the connection is closed as\npart of the `drop` implementation. Browsers sometimes deal with closed\nconnections by retrying, because the problem might be temporary.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Building a Single-Threaded Web Server", "heading_path": ["Building a Single-Threaded Web Server", "Listening to the TCP Connection"], "path": "ch21-01-single-threaded.md", "url": "https://doc.rust-lang.org/book/ch21-01-single-threaded.html#listening-to-the-tcp-connection", "has_code": true, "code_tags": ["text"]}} {"id": "book/ch21-01-single-threaded.md#listening-to-the-tcp-connection-4", "text": "The Rust Programming Language › Building a Single-Threaded Web Server › Listening to the TCP Connection\n\nBrowsers also sometimes open multiple connections to the server without sending\nany requests so that if they *do* later send requests, those requests can\nhappen more quickly. When this occurs, our server will see each connection,\nregardless of whether there are any requests over that connection. Many\nversions of Chrome-based browsers do this, for example; you can disable that\noptimization by using private browsing mode or using a different browser.\nThe important factor is that we’ve successfully gotten a handle to a TCP\nconnection!\nRemember to stop the program by pressing <kbd>ctrl</kbd>-<kbd>C</kbd> when\nyou’re done running a particular version of the code. Then, restart the program\nby invoking the `cargo run` command after you’ve made each set of code changes\nto make sure you’re running the newest code.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Building a Single-Threaded Web Server", "heading_path": ["Building a Single-Threaded Web Server", "Listening to the TCP Connection"], "path": "ch21-01-single-threaded.md", "url": "https://doc.rust-lang.org/book/ch21-01-single-threaded.html#listening-to-the-tcp-connection", "has_code": false, "code_tags": []}} {"id": "book/ch21-01-single-threaded.md#reading-the-request-5", "text": "The Rust Programming Language › Building a Single-Threaded Web Server › Reading the Request\n\nLet’s implement the functionality to read the request from the browser! To\nseparate the concerns of first getting a connection and then taking some action\nwith the connection, we’ll start a new function for processing connections. In\nthis new `handle_connection` function, we’ll read data from the TCP stream and\nprint it so that we can see the data being sent from the browser. Change the\ncode to look like Listing 21-2.\nListing 21-2: Reading from the `TcpStream` and printing the data (src/main.rs)\n```rust,no_run\nuse std::{\n io::{BufReader, prelude::*},\n net::{TcpListener, TcpStream},\n};\n\nfn main() {\n let listener = TcpListener::bind(\"127.0.0.1:7878\").unwrap();\n\n for stream in listener.incoming() {\n let stream = stream.unwrap();\n\n handle_connection(stream);\n }\n}\n\nfn handle_connection(mut stream: TcpStream) {\n let buf_reader = BufReader::new(&stream);\n let http_request: Vec<_> = buf_reader\n .lines()\n .map(|result| result.unwrap())\n .take_while(|line| !line.is_empty())\n .collect();\n\n println!(\"Request: {http_request:#?}\");\n}\n```\nWe bring `std::io::BufReader` and `std::io::prelude` into scope to get access\nto traits and types that let us read from and write to the stream. In the `for`\nloop in the `main` function, instead of printing a message that says we made a\nconnection, we now call the new `handle_connection` function and pass the\n`stream` to it.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Building a Single-Threaded Web Server", "heading_path": ["Building a Single-Threaded Web Server", "Reading the Request"], "path": "ch21-01-single-threaded.md", "url": "https://doc.rust-lang.org/book/ch21-01-single-threaded.html#reading-the-request", "has_code": true, "code_tags": ["rust,no_run"]}} {"id": "book/ch21-01-single-threaded.md#reading-the-request-6", "text": "The Rust Programming Language › Building a Single-Threaded Web Server › Reading the Request\n\nIn the `handle_connection` function, we create a new `BufReader` instance that\nwraps a reference to the `stream`. The `BufReader` adds buffering by managing\ncalls to the `std::io::Read` trait methods for us.\nWe create a variable named `http_request` to collect the lines of the request\nthe browser sends to our server. We indicate that we want to collect these\nlines in a vector by adding the `Vec<_>` type annotation.\n`BufReader` implements the `std::io::BufRead` trait, which provides the `lines`\nmethod. The `lines` method returns an iterator of `Result<String,\nstd::io::Error>` by splitting the stream of data whenever it sees a newline\nbyte. To get each `String`, we `map` and `unwrap` each `Result`. The `Result`\nmight be an error if the data isn’t valid UTF-8 or if there was a problem\nreading from the stream. Again, a production program should handle these errors\nmore gracefully, but we’re choosing to stop the program in the error case for\nsimplicity.\nThe browser signals the end of an HTTP request by sending two newline\ncharacters in a row, so to get one request from the stream, we take lines until\nwe get a line that is the empty string. Once we’ve collected the lines into the\nvector, we’re printing them out using pretty debug formatting so that we can\ntake a look at the instructions the web browser is sending to our server.\nLet’s try this code! Start the program and make a request in a web browser\nagain. Note that we’ll still get an error page in the browser, but our\nprogram’s output in the terminal will now look similar to this:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Building a Single-Threaded Web Server", "heading_path": ["Building a Single-Threaded Web Server", "Reading the Request"], "path": "ch21-01-single-threaded.md", "url": "https://doc.rust-lang.org/book/ch21-01-single-threaded.html#reading-the-request", "has_code": false, "code_tags": []}} {"id": "book/ch21-01-single-threaded.md#reading-the-request-7", "text": "The Rust Programming Language › Building a Single-Threaded Web Server › Reading the Request\n\n```console\n$ cargo run\n Compiling hello v0.1.0 (file:///projects/hello)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.42s\n Running `target/debug/hello`\nRequest: [\n \"GET / HTTP/1.1\",\n \"Host: 127.0.0.1:7878\",\n \"User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:99.0) Gecko/20100101 Firefox/99.0\",\n \"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\",\n \"Accept-Language: en-US,en;q=0.5\",\n \"Accept-Encoding: gzip, deflate, br\",\n \"DNT: 1\",\n \"Connection: keep-alive\",\n \"Upgrade-Insecure-Requests: 1\",\n \"Sec-Fetch-Dest: document\",\n \"Sec-Fetch-Mode: navigate\",\n \"Sec-Fetch-Site: none\",\n \"Sec-Fetch-User: ?1\",\n \"Cache-Control: max-age=0\",\n]\n```\nDepending on your browser, you might get slightly different output. Now that\nwe’re printing the request data, we can see why we get multiple connections\nfrom one browser request by looking at the path after `GET` in the first line\nof the request. If the repeated connections are all requesting _/_, we know the\nbrowser is trying to fetch _/_ repeatedly because it’s not getting a response\nfrom our program.\nLet’s break down this request data to understand what the browser is asking of\nour program.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Building a Single-Threaded Web Server", "heading_path": ["Building a Single-Threaded Web Server", "Reading the Request"], "path": "ch21-01-single-threaded.md", "url": "https://doc.rust-lang.org/book/ch21-01-single-threaded.html#reading-the-request", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch21-01-single-threaded.md#looking-more-closely-at-an-http-request-8", "text": "The Rust Programming Language › Building a Single-Threaded Web Server › Looking More Closely at an HTTP Request\n\nHTTP is a text-based protocol, and a request takes this format:\n```text\nMethod Request-URI HTTP-Version CRLF\nheaders CRLF\nmessage-body\n```\nThe first line is the _request line_ that holds information about what the\nclient is requesting. The first part of the request line indicates the method\nbeing used, such as `GET` or `POST`, which describes how the client is making\nthis request. Our client used a `GET` request, which means it is asking for\ninformation.\nThe next part of the request line is _/_, which indicates the _uniform resource\nidentifier_ _(URI)_ the client is requesting: A URI is almost, but not quite,\nthe same as a _uniform resource locator_ _(URL)_. The difference between URIs\nand URLs isn’t important for our purposes in this chapter, but the HTTP spec\nuses the term _URI_, so we can just mentally substitute _URL_ for _URI_ here.\nThe last part is the HTTP version the client uses, and then the request line\nends in a CRLF sequence. (_CRLF_ stands for _carriage return_ and _line feed_,\nwhich are terms from the typewriter days!) The CRLF sequence can also be\nwritten as `\\r\\n`, where `\\r` is a carriage return and `\\n` is a line feed. The\n_CRLF sequence_ separates the request line from the rest of the request data.\nNote that when the CRLF is printed, we see a new line start rather than `\\r\\n`.\nLooking at the request line data we received from running our program so far,\nwe see that `GET` is the method, _/_ is the request URI, and `HTTP/1.1` is the\nversion.\nAfter the request line, the remaining lines starting from `Host:` onward are\nheaders. `GET` requests have no body.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Building a Single-Threaded Web Server", "heading_path": ["Building a Single-Threaded Web Server", "Looking More Closely at an HTTP Request"], "path": "ch21-01-single-threaded.md", "url": "https://doc.rust-lang.org/book/ch21-01-single-threaded.html#looking-more-closely-at-an-http-request", "has_code": true, "code_tags": ["text"]}} {"id": "book/ch21-01-single-threaded.md#looking-more-closely-at-an-http-request-9", "text": "The Rust Programming Language › Building a Single-Threaded Web Server › Looking More Closely at an HTTP Request\n\nTry making a request from a different browser or asking for a different\naddress, such as _127.0.0.1:7878/test_, to see how the request data changes.\nNow that we know what the browser is asking for, let’s send back some data!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Building a Single-Threaded Web Server", "heading_path": ["Building a Single-Threaded Web Server", "Looking More Closely at an HTTP Request"], "path": "ch21-01-single-threaded.md", "url": "https://doc.rust-lang.org/book/ch21-01-single-threaded.html#looking-more-closely-at-an-http-request", "has_code": false, "code_tags": []}} {"id": "book/ch21-01-single-threaded.md#writing-a-response-10", "text": "The Rust Programming Language › Building a Single-Threaded Web Server › Writing a Response\n\nWe’re going to implement sending data in response to a client request.\nResponses have the following format:\n```text\nHTTP-Version Status-Code Reason-Phrase CRLF\nheaders CRLF\nmessage-body\n```\nThe first line is a _status line_ that contains the HTTP version used in the\nresponse, a numeric status code that summarizes the result of the request, and\na reason phrase that provides a text description of the status code. After the\nCRLF sequence are any headers, another CRLF sequence, and the body of the\nresponse.\nHere is an example response that uses HTTP version 1.1 and has a status code of\n200, an OK reason phrase, no headers, and no body:\n```text\nHTTP/1.1 200 OK\\r\\n\\r\\n\n```\nThe status code 200 is the standard success response. The text is a tiny\nsuccessful HTTP response. Let’s write this to the stream as our response to a\nsuccessful request! From the `handle_connection` function, remove the\n`println!` that was printing the request data and replace it with the code in\nListing 21-3.\nListing 21-3: Writing a tiny successful HTTP response to the stream (src/main.rs)\n```rust,no_run\nfn handle_connection(mut stream: TcpStream) {\n let buf_reader = BufReader::new(&stream);\n let http_request: Vec<_> = buf_reader\n .lines()\n .map(|result| result.unwrap())\n .take_while(|line| !line.is_empty())\n .collect();\n\n let response = \"HTTP/1.1 200 OK\\r\\n\\r\\n\";\n\n stream.write_all(response.as_bytes()).unwrap();\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Building a Single-Threaded Web Server", "heading_path": ["Building a Single-Threaded Web Server", "Writing a Response"], "path": "ch21-01-single-threaded.md", "url": "https://doc.rust-lang.org/book/ch21-01-single-threaded.html#writing-a-response", "has_code": true, "code_tags": ["rust,no_run", "text"]}} {"id": "book/ch21-01-single-threaded.md#writing-a-response-11", "text": "The Rust Programming Language › Building a Single-Threaded Web Server › Writing a Response\n\nThe first new line defines the `response` variable that holds the success\nmessage’s data. Then, we call `as_bytes` on our `response` to convert the\nstring data to bytes. The `write_all` method on `stream` takes a `&[u8]` and\nsends those bytes directly down the connection. Because the `write_all`\noperation could fail, we use `unwrap` on any error result as before. Again, in\na real application, you would add error handling here.\nWith these changes, let’s run our code and make a request. We’re no longer\nprinting any data to the terminal, so we won’t see any output other than the\noutput from Cargo. When you load _127.0.0.1:7878_ in a web browser, you should\nget a blank page instead of an error. You’ve just handcoded receiving an HTTP\nrequest and sending a response!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Building a Single-Threaded Web Server", "heading_path": ["Building a Single-Threaded Web Server", "Writing a Response"], "path": "ch21-01-single-threaded.md", "url": "https://doc.rust-lang.org/book/ch21-01-single-threaded.html#writing-a-response", "has_code": false, "code_tags": []}} {"id": "book/ch21-01-single-threaded.md#returning-real-html-12", "text": "The Rust Programming Language › Building a Single-Threaded Web Server › Returning Real HTML\n\nLet’s implement the functionality for returning more than a blank page. Create\nthe new file _hello.html_ in the root of your project directory, not in the\n_src_ directory. You can input any HTML you want; Listing 21-4 shows one\npossibility.\nListing 21-4: A sample HTML file to return in a response (hello.html)\n```html\n<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>Hello!\n \n \n

Hello!

\n

Hi from Rust

\n \n\n```\nThis is a minimal HTML5 document with a heading and some text. To return this\nfrom the server when a request is received, we’ll modify `handle_connection` as\nshown in Listing 21-5 to read the HTML file, add it to the response as a body,\nand send it.\nListing 21-5: Sending the contents of *hello.html* as the body of the response (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Building a Single-Threaded Web Server", "heading_path": ["Building a Single-Threaded Web Server", "Returning Real HTML"], "path": "ch21-01-single-threaded.md", "url": "https://doc.rust-lang.org/book/ch21-01-single-threaded.html#returning-real-html", "has_code": true, "code_tags": ["html"]}} {"id": "book/ch21-01-single-threaded.md#returning-real-html-13", "text": "The Rust Programming Language › Building a Single-Threaded Web Server › Returning Real HTML\n\n```rust,no_run\nuse std::{\n fs,\n io::{BufReader, prelude::*},\n net::{TcpListener, TcpStream},\n};\n// --snip--\n\nfn handle_connection(mut stream: TcpStream) {\n let buf_reader = BufReader::new(&stream);\n let http_request: Vec<_> = buf_reader\n .lines()\n .map(|result| result.unwrap())\n .take_while(|line| !line.is_empty())\n .collect();\n\n let status_line = \"HTTP/1.1 200 OK\";\n let contents = fs::read_to_string(\"hello.html\").unwrap();\n let length = contents.len();\n\n let response =\n format!(\"{status_line}\\r\\nContent-Length: {length}\\r\\n\\r\\n{contents}\");\n\n stream.write_all(response.as_bytes()).unwrap();\n}\n```\nWe’ve added `fs` to the `use` statement to bring the standard library’s\nfilesystem module into scope. The code for reading the contents of a file to a\nstring should look familiar; we used it when we read the contents of a file for\nour I/O project in Listing 12-4.\nNext, we use `format!` to add the file’s contents as the body of the success\nresponse. To ensure a valid HTTP response, we add the `Content-Length` header,\nwhich is set to the size of our response body—in this case, the size of\n`hello.html`.\nRun this code with `cargo run` and load _127.0.0.1:7878_ in your browser; you\nshould see your HTML rendered!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Building a Single-Threaded Web Server", "heading_path": ["Building a Single-Threaded Web Server", "Returning Real HTML"], "path": "ch21-01-single-threaded.md", "url": "https://doc.rust-lang.org/book/ch21-01-single-threaded.html#returning-real-html", "has_code": true, "code_tags": ["rust,no_run"]}} {"id": "book/ch21-01-single-threaded.md#returning-real-html-14", "text": "The Rust Programming Language › Building a Single-Threaded Web Server › Returning Real HTML\n\nCurrently, we’re ignoring the request data in `http_request` and just sending\nback the contents of the HTML file unconditionally. That means if you try\nrequesting _127.0.0.1:7878/something-else_ in your browser, you’ll still get\nback this same HTML response. At the moment, our server is very limited and\ndoes not do what most web servers do. We want to customize our responses\ndepending on the request and only send back the HTML file for a well-formed\nrequest to _/_.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Building a Single-Threaded Web Server", "heading_path": ["Building a Single-Threaded Web Server", "Returning Real HTML"], "path": "ch21-01-single-threaded.md", "url": "https://doc.rust-lang.org/book/ch21-01-single-threaded.html#returning-real-html", "has_code": false, "code_tags": []}} {"id": "book/ch21-01-single-threaded.md#validating-the-request-and-selectively-responding-15", "text": "The Rust Programming Language › Building a Single-Threaded Web Server › Validating the Request and Selectively Responding\n\nRight now, our web server will return the HTML in the file no matter what the\nclient requested. Let’s add functionality to check that the browser is\nrequesting _/_ before returning the HTML file and to return an error if the\nbrowser requests anything else. For this we need to modify `handle_connection`,\nas shown in Listing 21-6. This new code checks the content of the request\nreceived against what we know a request for _/_ looks like and adds `if` and\n`else` blocks to treat requests differently.\nListing 21-6: Handling requests to */* differently from other requests (src/main.rs)\n```rust,no_run\n// --snip--\n\nfn handle_connection(mut stream: TcpStream) {\n let buf_reader = BufReader::new(&stream);\n let request_line = buf_reader.lines().next().unwrap().unwrap();\n\n if request_line == \"GET / HTTP/1.1\" {\n let status_line = \"HTTP/1.1 200 OK\";\n let contents = fs::read_to_string(\"hello.html\").unwrap();\n let length = contents.len();\n\n let response = format!(\n \"{status_line}\\r\\nContent-Length: {length}\\r\\n\\r\\n{contents}\"\n );\n\n stream.write_all(response.as_bytes()).unwrap();\n } else {\n // some other request\n }\n}\n```\nWe’re only going to be looking at the first line of the HTTP request, so rather\nthan reading the entire request into a vector, we’re calling `next` to get the\nfirst item from the iterator. The first `unwrap` takes care of the `Option` and\nstops the program if the iterator has no items. The second `unwrap` handles the\n`Result` and has the same effect as the `unwrap` that was in the `map` added in\nListing 21-2.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Building a Single-Threaded Web Server", "heading_path": ["Building a Single-Threaded Web Server", "Validating the Request and Selectively Responding"], "path": "ch21-01-single-threaded.md", "url": "https://doc.rust-lang.org/book/ch21-01-single-threaded.html#validating-the-request-and-selectively-responding", "has_code": true, "code_tags": ["rust,no_run"]}} {"id": "book/ch21-01-single-threaded.md#validating-the-request-and-selectively-responding-16", "text": "The Rust Programming Language › Building a Single-Threaded Web Server › Validating the Request and Selectively Responding\n\nNext, we check the `request_line` to see if it equals the request line of a GET\nrequest to the _/_ path. If it does, the `if` block returns the contents of our\nHTML file.\nIf the `request_line` does _not_ equal the GET request to the _/_ path, it\nmeans we’ve received some other request. We’ll add code to the `else` block in\na moment to respond to all other requests.\nRun this code now and request _127.0.0.1:7878_; you should get the HTML in\n_hello.html_. If you make any other request, such as\n_127.0.0.1:7878/something-else_, you’ll get a connection error like those you\nsaw when running the code in Listing 21-1 and Listing 21-2.\nNow let’s add the code in Listing 21-7 to the `else` block to return a response\nwith the status code 404, which signals that the content for the request was\nnot found. We’ll also return some HTML for a page to render in the browser\nindicating the response to the end user.\nListing 21-7: Responding with status code 404 and an error page if anything other than */* was requested (src/main.rs)\n```rust,no_run\n // --snip--\n } else {\n let status_line = \"HTTP/1.1 404 NOT FOUND\";\n let contents = fs::read_to_string(\"404.html\").unwrap();\n let length = contents.len();\n\n let response = format!(\n \"{status_line}\\r\\nContent-Length: {length}\\r\\n\\r\\n{contents}\"\n );\n\n stream.write_all(response.as_bytes()).unwrap();\n }\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Building a Single-Threaded Web Server", "heading_path": ["Building a Single-Threaded Web Server", "Validating the Request and Selectively Responding"], "path": "ch21-01-single-threaded.md", "url": "https://doc.rust-lang.org/book/ch21-01-single-threaded.html#validating-the-request-and-selectively-responding", "has_code": true, "code_tags": ["rust,no_run"]}} {"id": "book/ch21-01-single-threaded.md#validating-the-request-and-selectively-responding-17", "text": "The Rust Programming Language › Building a Single-Threaded Web Server › Validating the Request and Selectively Responding\n\nHere, our response has a status line with status code 404 and the reason phrase\n`NOT FOUND`. The body of the response will be the HTML in the file _404.html_.\nYou’ll need to create a _404.html_ file next to _hello.html_ for the error\npage; again, feel free to use any HTML you want, or use the example HTML in\nListing 21-8.\nListing 21-8: Sample content for the page to send back with any 404 response (404.html)\n```html\n\n\n \n \n Hello!\n \n \n

Oops!

\n

Sorry, I don't know what you're asking for.

\n \n\n```\nWith these changes, run your server again. Requesting _127.0.0.1:7878_ should\nreturn the contents of _hello.html_, and any other request, like\n_127.0.0.1:7878/foo_, should return the error HTML from _404.html_.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Building a Single-Threaded Web Server", "heading_path": ["Building a Single-Threaded Web Server", "Validating the Request and Selectively Responding"], "path": "ch21-01-single-threaded.md", "url": "https://doc.rust-lang.org/book/ch21-01-single-threaded.html#validating-the-request-and-selectively-responding", "has_code": true, "code_tags": ["html"]}} {"id": "book/ch21-01-single-threaded.md#refactoring-18", "text": "The Rust Programming Language › Building a Single-Threaded Web Server › Refactoring\n\nAt the moment, the `if` and `else` blocks have a lot of repetition: They’re\nboth reading files and writing the contents of the files to the stream. The\nonly differences are the status line and the filename. Let’s make the code more\nconcise by pulling out those differences into separate `if` and `else` lines\nthat will assign the values of the status line and the filename to variables;\nwe can then use those variables unconditionally in the code to read the file\nand write the response. Listing 21-9 shows the resultant code after replacing\nthe large `if` and `else` blocks.\nListing 21-9: Refactoring the `if` and `else` blocks to contain only the code that differs between the two cases (src/main.rs)\n```rust,no_run\n// --snip--\n\nfn handle_connection(mut stream: TcpStream) {\n // --snip--\n\n let (status_line, filename) = if request_line == \"GET / HTTP/1.1\" {\n (\"HTTP/1.1 200 OK\", \"hello.html\")\n } else {\n (\"HTTP/1.1 404 NOT FOUND\", \"404.html\")\n };\n\n let contents = fs::read_to_string(filename).unwrap();\n let length = contents.len();\n\n let response =\n format!(\"{status_line}\\r\\nContent-Length: {length}\\r\\n\\r\\n{contents}\");\n\n stream.write_all(response.as_bytes()).unwrap();\n}\n```\nNow the `if` and `else` blocks only return the appropriate values for the\nstatus line and filename in a tuple; we then use destructuring to assign these\ntwo values to `status_line` and `filename` using a pattern in the `let`\nstatement, as discussed in Chapter 19.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Building a Single-Threaded Web Server", "heading_path": ["Building a Single-Threaded Web Server", "Refactoring"], "path": "ch21-01-single-threaded.md", "url": "https://doc.rust-lang.org/book/ch21-01-single-threaded.html#refactoring", "has_code": true, "code_tags": ["rust,no_run"]}} {"id": "book/ch21-01-single-threaded.md#refactoring-19", "text": "The Rust Programming Language › Building a Single-Threaded Web Server › Refactoring\n\nThe previously duplicated code is now outside the `if` and `else` blocks and\nuses the `status_line` and `filename` variables. This makes it easier to see\nthe difference between the two cases, and it means we have only one place to\nupdate the code if we want to change how the file reading and response writing\nwork. The behavior of the code in Listing 21-9 will be the same as that in\nListing 21-7.\nAwesome! We now have a simple web server in approximately 40 lines of Rust code\nthat responds to one request with a page of content and responds to all other\nrequests with a 404 response.\nCurrently, our server runs in a single thread, meaning it can only serve one\nrequest at a time. Let’s examine how that can be a problem by simulating some\nslow requests. Then, we’ll fix it so that our server can handle multiple\nrequests at once.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Building a Single-Threaded Web Server", "heading_path": ["Building a Single-Threaded Web Server", "Refactoring"], "path": "ch21-01-single-threaded.md", "url": "https://doc.rust-lang.org/book/ch21-01-single-threaded.html#refactoring", "has_code": false, "code_tags": []}} {"id": "book/ch21-02-multithreaded.md#from-a-single-threaded-to-a-multithreaded-server-0", "text": "The Rust Programming Language › From a Single-Threaded to a Multithreaded Server\n\nRight now, the server will process each request in turn, meaning it won’t\nprocess a second connection until the first connection is finished processing.\nIf the server received more and more requests, this serial execution would be\nless and less optimal. If the server receives a request that takes a long time\nto process, subsequent requests will have to wait until the long request is\nfinished, even if the new requests can be processed quickly. We’ll need to fix\nthis, but first we’ll look at the problem in action.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "From Single-Threaded to Multithreaded Server", "heading_path": ["From a Single-Threaded to a Multithreaded Server"], "path": "ch21-02-multithreaded.md", "url": "https://doc.rust-lang.org/book/ch21-02-multithreaded.html#from-a-single-threaded-to-a-multithreaded-server", "has_code": false, "code_tags": []}} {"id": "book/ch21-02-multithreaded.md#simulating-a-slow-request-1", "text": "The Rust Programming Language › From a Single-Threaded to a Multithreaded Server › Simulating a Slow Request\n\nWe’ll look at how a slowly processing request can affect other requests made to\nour current server implementation. Listing 21-10 implements handling a request\nto _/sleep_ with a simulated slow response that will cause the server to sleep\nfor five seconds before responding.\nListing 21-10: Simulating a slow request by sleeping for five seconds (src/main.rs)\n```rust,no_run\nuse std::{\n fs,\n io::{BufReader, prelude::*},\n net::{TcpListener, TcpStream},\n thread,\n time::Duration,\n};\n// --snip--\n\nfn handle_connection(mut stream: TcpStream) {\n // --snip--\n\n let (status_line, filename) = match &request_line[..] {\n \"GET / HTTP/1.1\" => (\"HTTP/1.1 200 OK\", \"hello.html\"),\n \"GET /sleep HTTP/1.1\" => {\n thread::sleep(Duration::from_secs(5));\n (\"HTTP/1.1 200 OK\", \"hello.html\")\n }\n _ => (\"HTTP/1.1 404 NOT FOUND\", \"404.html\"),\n };\n\n // --snip--\n}\n```\nWe switched from `if` to `match` now that we have three cases. We need to\nexplicitly match on a slice of `request_line` to pattern-match against the\nstring literal values; `match` doesn’t do automatic referencing and\ndereferencing, like the equality method does.\nThe first arm is the same as the `if` block from Listing 21-9. The second arm\nmatches a request to _/sleep_. When that request is received, the server will\nsleep for five seconds before rendering the successful HTML page. The third arm\nis the same as the `else` block from Listing 21-9.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "From Single-Threaded to Multithreaded Server", "heading_path": ["From a Single-Threaded to a Multithreaded Server", "Simulating a Slow Request"], "path": "ch21-02-multithreaded.md", "url": "https://doc.rust-lang.org/book/ch21-02-multithreaded.html#simulating-a-slow-request", "has_code": true, "code_tags": ["rust,no_run"]}} {"id": "book/ch21-02-multithreaded.md#simulating-a-slow-request-2", "text": "The Rust Programming Language › From a Single-Threaded to a Multithreaded Server › Simulating a Slow Request\n\nYou can see how primitive our server is: Real libraries would handle the\nrecognition of multiple requests in a much less verbose way!\nStart the server using `cargo run`. Then, open two browser windows: one for\n_http://127.0.0.1:7878_ and the other for _http://127.0.0.1:7878/sleep_. If you\nenter the _/_ URI a few times, as before, you’ll see it respond quickly. But if\nyou enter _/sleep_ and then load _/_, you’ll see that _/_ waits until `sleep`\nhas slept for its full five seconds before loading.\nThere are multiple techniques we could use to avoid requests backing up behind\na slow request, including using async as we did Chapter 17; the one we’ll\nimplement is a thread pool.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "From Single-Threaded to Multithreaded Server", "heading_path": ["From a Single-Threaded to a Multithreaded Server", "Simulating a Slow Request"], "path": "ch21-02-multithreaded.md", "url": "https://doc.rust-lang.org/book/ch21-02-multithreaded.html#simulating-a-slow-request", "has_code": false, "code_tags": []}} {"id": "book/ch21-02-multithreaded.md#improving-throughput-with-a-thread-pool-3", "text": "The Rust Programming Language › From a Single-Threaded to a Multithreaded Server › Improving Throughput with a Thread Pool\n\nA _thread pool_ is a group of spawned threads that are ready and waiting to\nhandle a task. When the program receives a new task, it assigns one of the\nthreads in the pool to the task, and that thread will process the task. The\nremaining threads in the pool are available to handle any other tasks that come\nin while the first thread is processing. When the first thread is done\nprocessing its task, it’s returned to the pool of idle threads, ready to handle\na new task. A thread pool allows you to process connections concurrently,\nincreasing the throughput of your server.\nWe’ll limit the number of threads in the pool to a small number to protect us\nfrom DoS attacks; if we had our program create a new thread for each request as\nit came in, someone making 10 million requests to our server could wreak havoc\nby using up all our server’s resources and grinding the processing of requests\nto a halt.\nRather than spawning unlimited threads, then, we’ll have a fixed number of\nthreads waiting in the pool. Requests that come in are sent to the pool for\nprocessing. The pool will maintain a queue of incoming requests. Each of the\nthreads in the pool will pop off a request from this queue, handle the request,\nand then ask the queue for another request. With this design, we can process up\nto _`N`_ requests concurrently, where _`N`_ is the number of threads. If each\nthread is responding to a long-running request, subsequent requests can still\nback up in the queue, but we’ve increased the number of long-running requests\nwe can handle before reaching that point.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "From Single-Threaded to Multithreaded Server", "heading_path": ["From a Single-Threaded to a Multithreaded Server", "Improving Throughput with a Thread Pool"], "path": "ch21-02-multithreaded.md", "url": "https://doc.rust-lang.org/book/ch21-02-multithreaded.html#improving-throughput-with-a-thread-pool", "has_code": false, "code_tags": []}} {"id": "book/ch21-02-multithreaded.md#spawning-a-thread-for-each-request-4", "text": "The Rust Programming Language › From a Single-Threaded to a Multithreaded Server › Improving Throughput with a Thread Pool › Spawning a Thread for Each Request\n\nThis technique is just one of many ways to improve the throughput of a web\nserver. Other options you might explore are the fork/join model, the\nsingle-threaded async I/O model, and the multithreaded async I/O model. If\nyou’re interested in this topic, you can read more about other solutions and\ntry to implement them; with a low-level language like Rust, all of these\noptions are possible.\nBefore we begin implementing a thread pool, let’s talk about what using the\npool should look like. When you’re trying to design code, writing the client\ninterface first can help guide your design. Write the API of the code so that\nit’s structured in the way you want to call it; then, implement the\nfunctionality within that structure rather than implementing the functionality\nand then designing the public API.\nSimilar to how we used test-driven development in the project in Chapter 12,\nwe’ll use compiler-driven development here. We’ll write the code that calls the\nfunctions we want, and then we’ll look at errors from the compiler to determine\nwhat we should change next to get the code to work. Before we do that, however,\nwe’ll explore the technique we’re not going to use as a starting point.\nFirst, let’s explore how our code might look if it did create a new thread for\nevery connection. As mentioned earlier, this isn’t our final plan due to the\nproblems with potentially spawning an unlimited number of threads, but it is a\nstarting point to get a working multithreaded server first. Then, we’ll add the\nthread pool as an improvement, and contrasting the two solutions will be easier.\nListing 21-11 shows the changes to make to `main` to spawn a new thread to\nhandle each stream within the `for` loop.\nListing 21-11: Spawning a new thread for each stream (src/main.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "From Single-Threaded to Multithreaded Server", "heading_path": ["From a Single-Threaded to a Multithreaded Server", "Improving Throughput with a Thread Pool", "Spawning a Thread for Each Request"], "path": "ch21-02-multithreaded.md", "url": "https://doc.rust-lang.org/book/ch21-02-multithreaded.html#spawning-a-thread-for-each-request", "has_code": false, "code_tags": []}} {"id": "book/ch21-02-multithreaded.md#creating-a-finite-number-of-threads-5", "text": "The Rust Programming Language › From a Single-Threaded to a Multithreaded Server › Improving Throughput with a Thread Pool › Creating a Finite Number of Threads\n\n```rust,no_run\nfn main() {\n let listener = TcpListener::bind(\"127.0.0.1:7878\").unwrap();\n\n for stream in listener.incoming() {\n let stream = stream.unwrap();\n\n thread::spawn(|| {\n handle_connection(stream);\n });\n }\n}\n```\nAs you learned in Chapter 16, `thread::spawn` will create a new thread and then\nrun the code in the closure in the new thread. If you run this code and load\n_/sleep_ in your browser, then _/_ in two more browser tabs, you’ll indeed see\nthat the requests to _/_ don’t have to wait for _/sleep_ to finish. However, as\nwe mentioned, this will eventually overwhelm the system because you’d be making\nnew threads without any limit.\nYou may also recall from Chapter 17 that this is exactly the kind of situation\nwhere async and await really shine! Keep that in mind as we build the thread\npool and think about how things would look different or the same with async.\nWe want our thread pool to work in a similar, familiar way so that switching\nfrom threads to a thread pool doesn’t require large changes to the code that\nuses our API. Listing 21-12 shows the hypothetical interface for a `ThreadPool`\nstruct we want to use instead of `thread::spawn`.\nListing 21-12: Our ideal `ThreadPool` interface (src/main.rs)\n```rust,ignore,does_not_compile\nfn main() {\n let listener = TcpListener::bind(\"127.0.0.1:7878\").unwrap();\n let pool = ThreadPool::new(4);\n\n for stream in listener.incoming() {\n let stream = stream.unwrap();\n\n pool.execute(|| {\n handle_connection(stream);\n });\n }\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "From Single-Threaded to Multithreaded Server", "heading_path": ["From a Single-Threaded to a Multithreaded Server", "Improving Throughput with a Thread Pool", "Creating a Finite Number of Threads"], "path": "ch21-02-multithreaded.md", "url": "https://doc.rust-lang.org/book/ch21-02-multithreaded.html#creating-a-finite-number-of-threads", "has_code": true, "code_tags": ["rust,ignore,does_not_compile", "rust,no_run"]}} {"id": "book/ch21-02-multithreaded.md#building-threadpool-using-compiler-driven-development-6", "text": "The Rust Programming Language › From a Single-Threaded to a Multithreaded Server › Improving Throughput with a Thread Pool › Building `ThreadPool` Using Compiler-Driven Development\n\nWe use `ThreadPool::new` to create a new thread pool with a configurable number\nof threads, in this case four. Then, in the `for` loop, `pool.execute` has a\nsimilar interface as `thread::spawn` in that it takes a closure that the pool\nshould run for each stream. We need to implement `pool.execute` so that it\ntakes the closure and gives it to a thread in the pool to run. This code won’t\nyet compile, but we’ll try so that the compiler can guide us in how to fix it.\nMake the changes in Listing 21-12 to _src/main.rs_, and then let’s use the\ncompiler errors from `cargo check` to drive our development. Here is the first\nerror we get:\n```console\n$ cargo check\n Checking hello v0.1.0 (file:///projects/hello)\nerror[E0433]: cannot find type `ThreadPool` in this scope\n --> src/main.rs:11:16\n |\n11 | let pool = ThreadPool::new(4);\n | ^^^^^^^^^^ use of undeclared type `ThreadPool`\n\nFor more information about this error, try `rustc --explain E0433`.\nerror: could not compile `hello` (bin \"hello\") due to 1 previous error\n```\nGreat! This error tells us we need a `ThreadPool` type or module, so we’ll\nbuild one now. Our `ThreadPool` implementation will be independent of the kind\nof work our web server is doing. So, let’s switch the `hello` crate from a\nbinary crate to a library crate to hold our `ThreadPool` implementation. After\nwe change to a library crate, we could also use the separate thread pool\nlibrary for any work we want to do using a thread pool, not just for serving\nweb requests.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "From Single-Threaded to Multithreaded Server", "heading_path": ["From a Single-Threaded to a Multithreaded Server", "Improving Throughput with a Thread Pool", "Building `ThreadPool` Using Compiler-Driven Development"], "path": "ch21-02-multithreaded.md", "url": "https://doc.rust-lang.org/book/ch21-02-multithreaded.html#building-threadpool-using-compiler-driven-development", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch21-02-multithreaded.md#building-threadpool-using-compiler-driven-development-7", "text": "The Rust Programming Language › From a Single-Threaded to a Multithreaded Server › Improving Throughput with a Thread Pool › Building `ThreadPool` Using Compiler-Driven Development\n\nCreate a _src/lib.rs_ file that contains the following, which is the simplest\ndefinition of a `ThreadPool` struct that we can have for now:\nListing (src/lib.rs)\n```rust,noplayground\npub struct ThreadPool;\n```\nThen, edit the _main.rs_ file to bring `ThreadPool` into scope from the library\ncrate by adding the following code to the top of _src/main.rs_:\nListing (src/main.rs)\n```rust,ignore\nuse hello::ThreadPool;\n```\nThis code still won’t work, but let’s check it again to get the next error that\nwe need to address:\n```console\n$ cargo check\n Checking hello v0.1.0 (file:///projects/hello)\nerror[E0599]: no associated function or constant named `new` found for struct `ThreadPool` in the current scope\n --> src/main.rs:12:28\n |\n12 | let pool = ThreadPool::new(4);\n | ^^^ associated function or constant not found in `ThreadPool`\n\nFor more information about this error, try `rustc --explain E0599`.\nerror: could not compile `hello` (bin \"hello\") due to 1 previous error\n```\nThis error indicates that next we need to create an associated function named\n`new` for `ThreadPool`. We also know that `new` needs to have one parameter\nthat can accept `4` as an argument and should return a `ThreadPool` instance.\nLet’s implement the simplest `new` function that will have those\ncharacteristics:\nListing (src/lib.rs)\n```rust,noplayground\npub struct ThreadPool;\n\nimpl ThreadPool {\n pub fn new(size: usize) -> ThreadPool {\n ThreadPool\n }\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "From Single-Threaded to Multithreaded Server", "heading_path": ["From a Single-Threaded to a Multithreaded Server", "Improving Throughput with a Thread Pool", "Building `ThreadPool` Using Compiler-Driven Development"], "path": "ch21-02-multithreaded.md", "url": "https://doc.rust-lang.org/book/ch21-02-multithreaded.html#building-threadpool-using-compiler-driven-development", "has_code": true, "code_tags": ["console", "rust,ignore", "rust,noplayground"]}} {"id": "book/ch21-02-multithreaded.md#building-threadpool-using-compiler-driven-development-8", "text": "The Rust Programming Language › From a Single-Threaded to a Multithreaded Server › Improving Throughput with a Thread Pool › Building `ThreadPool` Using Compiler-Driven Development\n\nWe chose `usize` as the type of the `size` parameter because we know that a\nnegative number of threads doesn’t make any sense. We also know we’ll use this\n`4` as the number of elements in a collection of threads, which is what the\n`usize` type is for, as discussed in the “Integer Types”\n section in Chapter 3.\nLet’s check the code again:\n```console\n$ cargo check\n Checking hello v0.1.0 (file:///projects/hello)\nerror[E0599]: no method named `execute` found for struct `ThreadPool` in the current scope\n --> src/main.rs:17:14\n |\n17 | pool.execute(|| {\n | -----^^^^^^^ method not found in `ThreadPool`\n\nFor more information about this error, try `rustc --explain E0599`.\nerror: could not compile `hello` (bin \"hello\") due to 1 previous error\n```\nNow the error occurs because we don’t have an `execute` method on `ThreadPool`.\nRecall from the “Creating a Finite Number of\nThreads” section that we\ndecided our thread pool should have an interface similar to `thread::spawn`. In\naddition, we’ll implement the `execute` function so that it takes the closure\nit’s given and gives it to an idle thread in the pool to run.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "From Single-Threaded to Multithreaded Server", "heading_path": ["From a Single-Threaded to a Multithreaded Server", "Improving Throughput with a Thread Pool", "Building `ThreadPool` Using Compiler-Driven Development"], "path": "ch21-02-multithreaded.md", "url": "https://doc.rust-lang.org/book/ch21-02-multithreaded.html#building-threadpool-using-compiler-driven-development", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch21-02-multithreaded.md#building-threadpool-using-compiler-driven-development-9", "text": "The Rust Programming Language › From a Single-Threaded to a Multithreaded Server › Improving Throughput with a Thread Pool › Building `ThreadPool` Using Compiler-Driven Development\n\nWe’ll define the `execute` method on `ThreadPool` to take a closure as a\nparameter. Recall from the “Moving Captured Values Out of\nClosures” in Chapter 13 that we can\ntake closures as parameters with three different traits: `Fn`, `FnMut`, and\n`FnOnce`. We need to decide which kind of closure to use here. We know we’ll\nend up doing something similar to the standard library `thread::spawn`\nimplementation, so we can look at what bounds the signature of `thread::spawn`\nhas on its parameter. The documentation shows us the following:\n```rust,ignore\npub fn spawn(f: F) -> JoinHandle\n where\n F: FnOnce() -> T,\n F: Send + 'static,\n T: Send + 'static,\n```\nThe `F` type parameter is the one we’re concerned with here; the `T` type\nparameter is related to the return value, and we’re not concerned with that. We\ncan see that `spawn` uses `FnOnce` as the trait bound on `F`. This is probably\nwhat we want as well, because we’ll eventually pass the argument we get in\n`execute` to `spawn`. We can be further confident that `FnOnce` is the trait we\nwant to use because the thread for running a request will only execute that\nrequest’s closure one time, which matches the `Once` in `FnOnce`.\nThe `F` type parameter also has the trait bound `Send` and the lifetime bound\n`'static`, which are useful in our situation: We need `Send` to transfer the\nclosure from one thread to another and `'static` because we don’t know how long\nthe thread will take to execute. Let’s create an `execute` method on\n`ThreadPool` that will take a generic parameter of type `F` with these bounds:\nListing (src/lib.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "From Single-Threaded to Multithreaded Server", "heading_path": ["From a Single-Threaded to a Multithreaded Server", "Improving Throughput with a Thread Pool", "Building `ThreadPool` Using Compiler-Driven Development"], "path": "ch21-02-multithreaded.md", "url": "https://doc.rust-lang.org/book/ch21-02-multithreaded.html#building-threadpool-using-compiler-driven-development", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch21-02-multithreaded.md#validating-the-number-of-threads-in-new-10", "text": "The Rust Programming Language › From a Single-Threaded to a Multithreaded Server › Improving Throughput with a Thread Pool › Validating the Number of Threads in `new`\n\n```rust,noplayground\nimpl ThreadPool {\n // --snip--\n pub fn execute(&self, f: F)\n where\n F: FnOnce() + Send + 'static,\n {\n }\n}\n```\nWe still use the `()` after `FnOnce` because this `FnOnce` represents a closure\nthat takes no parameters and returns the unit type `()`. Just like function\ndefinitions, the return type can be omitted from the signature, but even if we\nhave no parameters, we still need the parentheses.\nAgain, this is the simplest implementation of the `execute` method: It does\nnothing, but we’re only trying to make our code compile. Let’s check it again:\n```console\n$ cargo check\n Checking hello v0.1.0 (file:///projects/hello)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.24s\n```\nIt compiles! But note that if you try `cargo run` and make a request in the\nbrowser, you’ll see the errors in the browser that we saw at the beginning of\nthe chapter. Our library isn’t actually calling the closure passed to `execute`\nyet!\nNote: A saying you might hear about languages with strict compilers, such as\nHaskell and Rust, is “If the code compiles, it works.” But this saying is not\nuniversally true. Our project compiles, but it does absolutely nothing! If we\nwere building a real, complete project, this would be a good time to start\nwriting unit tests to check that the code compiles _and_ has the behavior we\nwant.\nConsider: What would be different here if we were going to execute a future\ninstead of a closure?", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "From Single-Threaded to Multithreaded Server", "heading_path": ["From a Single-Threaded to a Multithreaded Server", "Improving Throughput with a Thread Pool", "Validating the Number of Threads in `new`"], "path": "ch21-02-multithreaded.md", "url": "https://doc.rust-lang.org/book/ch21-02-multithreaded.html#validating-the-number-of-threads-in-new", "has_code": true, "code_tags": ["console", "rust,noplayground"]}} {"id": "book/ch21-02-multithreaded.md#validating-the-number-of-threads-in-new-11", "text": "The Rust Programming Language › From a Single-Threaded to a Multithreaded Server › Improving Throughput with a Thread Pool › Validating the Number of Threads in `new`\n\nWe aren’t doing anything with the parameters to `new` and `execute`. Let’s\nimplement the bodies of these functions with the behavior we want. To start,\nlet’s think about `new`. Earlier we chose an unsigned type for the `size`\nparameter because a pool with a negative number of threads makes no sense.\nHowever, a pool with zero threads also makes no sense, yet zero is a perfectly\nvalid `usize`. We’ll add code to check that `size` is greater than zero before\nwe return a `ThreadPool` instance, and we’ll have the program panic if it\nreceives a zero by using the `assert!` macro, as shown in Listing 21-13.\nListing 21-13: Implementing `ThreadPool::new` to panic if `size` is zero (src/lib.rs)\n```rust,noplayground\nimpl ThreadPool {\n /// Create a new ThreadPool.\n ///\n /// The size is the number of threads in the pool.\n ///\n /// # Panics\n ///\n /// The `new` function will panic if the size is zero.\n pub fn new(size: usize) -> ThreadPool {\n assert!(size > 0);\n\n ThreadPool\n }\n\n // --snip--\n}\n```\nWe’ve also added some documentation for our `ThreadPool` with doc comments.\nNote that we followed good documentation practices by adding a section that\ncalls out the situations in which our function can panic, as discussed in\nChapter 14. Try running `cargo doc --open` and clicking the `ThreadPool` struct\nto see what the generated docs for `new` look like!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "From Single-Threaded to Multithreaded Server", "heading_path": ["From a Single-Threaded to a Multithreaded Server", "Improving Throughput with a Thread Pool", "Validating the Number of Threads in `new`"], "path": "ch21-02-multithreaded.md", "url": "https://doc.rust-lang.org/book/ch21-02-multithreaded.html#validating-the-number-of-threads-in-new", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch21-02-multithreaded.md#creating-space-to-store-the-threads-12", "text": "The Rust Programming Language › From a Single-Threaded to a Multithreaded Server › Improving Throughput with a Thread Pool › Creating Space to Store the Threads\n\nInstead of adding the `assert!` macro as we’ve done here, we could change `new`\ninto `build` and return a `Result` like we did with `Config::build` in the I/O\nproject in Listing 12-9. But we’ve decided in this case that trying to create a\nthread pool without any threads should be an unrecoverable error. If you’re\nfeeling ambitious, try to write a function named `build` with the following\nsignature to compare with the `new` function:\n```rust,ignore\npub fn build(size: usize) -> Result {\n```\nNow that we have a way to know we have a valid number of threads to store in\nthe pool, we can create those threads and store them in the `ThreadPool` struct\nbefore returning the struct. But how do we “store” a thread? Let’s take another\nlook at the `thread::spawn` signature:\n```rust,ignore\npub fn spawn(f: F) -> JoinHandle\n where\n F: FnOnce() -> T,\n F: Send + 'static,\n T: Send + 'static,\n```\nThe `spawn` function returns a `JoinHandle`, where `T` is the type that the\nclosure returns. Let’s try using `JoinHandle` too and see what happens. In our\ncase, the closures we’re passing to the thread pool will handle the connection\nand not return anything, so `T` will be the unit type `()`.\nThe code in Listing 21-14 will compile, but it doesn’t create any threads yet.\nWe’ve changed the definition of `ThreadPool` to hold a vector of\n`thread::JoinHandle<()>` instances, initialized the vector with a capacity of\n`size`, set up a `for` loop that will run some code to create the threads, and\nreturned a `ThreadPool` instance containing them.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "From Single-Threaded to Multithreaded Server", "heading_path": ["From a Single-Threaded to a Multithreaded Server", "Improving Throughput with a Thread Pool", "Creating Space to Store the Threads"], "path": "ch21-02-multithreaded.md", "url": "https://doc.rust-lang.org/book/ch21-02-multithreaded.html#creating-space-to-store-the-threads", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch21-02-multithreaded.md#sending-code-from-the-threadpool-to-a-thread-13", "text": "The Rust Programming Language › From a Single-Threaded to a Multithreaded Server › Improving Throughput with a Thread Pool › Sending Code from the `ThreadPool` to a Thread\n\nListing 21-14: Creating a vector for `ThreadPool` to hold the threads (src/lib.rs)\n```rust,ignore,not_desired_behavior\nuse std::thread;\n\npub struct ThreadPool {\n threads: Vec>,\n}\n\nimpl ThreadPool {\n // --snip--\n pub fn new(size: usize) -> ThreadPool {\n assert!(size > 0);\n\n let mut threads = Vec::with_capacity(size);\n\n for _ in 0..size {\n // create some threads and store them in the vector\n }\n\n ThreadPool { threads }\n }\n // --snip--\n}\n```\nWe’ve brought `std::thread` into scope in the library crate because we’re\nusing `thread::JoinHandle` as the type of the items in the vector in\n`ThreadPool`.\nOnce a valid size is received, our `ThreadPool` creates a new vector that can\nhold `size` items. The `with_capacity` function performs the same task as\n`Vec::new` but with an important difference: It pre-allocates space in the\nvector. Because we know we need to store `size` elements in the vector, doing\nthis allocation up front is slightly more efficient than using `Vec::new`,\nwhich resizes itself as elements are inserted.\nWhen you run `cargo check` again, it should succeed.\n", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "From Single-Threaded to Multithreaded Server", "heading_path": ["From a Single-Threaded to a Multithreaded Server", "Improving Throughput with a Thread Pool", "Sending Code from the `ThreadPool` to a Thread"], "path": "ch21-02-multithreaded.md", "url": "https://doc.rust-lang.org/book/ch21-02-multithreaded.html#sending-code-from-the-threadpool-to-a-thread", "has_code": true, "code_tags": ["rust,ignore,not_desired_behavior"]}} {"id": "book/ch21-02-multithreaded.md#sending-code-from-the-threadpool-to-a-thread-14", "text": "The Rust Programming Language › From a Single-Threaded to a Multithreaded Server › Improving Throughput with a Thread Pool › Sending Code from the `ThreadPool` to a Thread\n\nWe left a comment in the `for` loop in Listing 21-14 regarding the creation of\nthreads. Here, we’ll look at how we actually create threads. The standard\nlibrary provides `thread::spawn` as a way to create threads, and\n`thread::spawn` expects to get some code the thread should run as soon as the\nthread is created. However, in our case, we want to create the threads and have\nthem _wait_ for code that we’ll send later. The standard library’s\nimplementation of threads doesn’t include any way to do that; we have to\nimplement it manually.\nWe’ll implement this behavior by introducing a new data structure between the\n`ThreadPool` and the threads that will manage this new behavior. We’ll call\nthis data structure _Worker_, which is a common term in pooling\nimplementations. The `Worker` picks up code that needs to be run and runs the\ncode in its thread.\nThink of people working in the kitchen at a restaurant: The workers wait until\norders come in from customers, and then they’re responsible for taking those\norders and filling them.\nInstead of storing a vector of `JoinHandle<()>` instances in the thread pool,\nwe’ll store instances of the `Worker` struct. Each `Worker` will store a single\n`JoinHandle<()>` instance. Then, we’ll implement a method on `Worker` that will\ntake a closure of code to run and send it to the already running thread for\nexecution. We’ll also give each `Worker` an `id` so that we can distinguish\nbetween the different instances of `Worker` in the pool when logging or\ndebugging.\nHere is the new process that will happen when we create a `ThreadPool`. We’ll\nimplement the code that sends the closure to the thread after we have `Worker`\nset up in this way:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "From Single-Threaded to Multithreaded Server", "heading_path": ["From a Single-Threaded to a Multithreaded Server", "Improving Throughput with a Thread Pool", "Sending Code from the `ThreadPool` to a Thread"], "path": "ch21-02-multithreaded.md", "url": "https://doc.rust-lang.org/book/ch21-02-multithreaded.html#sending-code-from-the-threadpool-to-a-thread", "has_code": false, "code_tags": []}} {"id": "book/ch21-02-multithreaded.md#sending-code-from-the-threadpool-to-a-thread-15", "text": "The Rust Programming Language › From a Single-Threaded to a Multithreaded Server › Improving Throughput with a Thread Pool › Sending Code from the `ThreadPool` to a Thread\n\n1. Define a `Worker` struct that holds an `id` and a `JoinHandle<()>`.\n2. Change `ThreadPool` to hold a vector of `Worker` instances.\n3. Define a `Worker::new` function that takes an `id` number and returns a\n `Worker` instance that holds the `id` and a thread spawned with an empty\n closure.\n4. In `ThreadPool::new`, use the `for` loop counter to generate an `id`, create\n a new `Worker` with that `id`, and store the `Worker` in the vector.\nIf you’re up for a challenge, try implementing these changes on your own before\nlooking at the code in Listing 21-15.\nReady? Here is Listing 21-15 with one way to make the preceding modifications.\nListing 21-15: Modifying `ThreadPool` to hold `Worker` instances instead of holding threads directly (src/lib.rs)\n```rust,noplayground\nuse std::thread;\n\npub struct ThreadPool {\n workers: Vec,\n}\n\nimpl ThreadPool {\n // --snip--\n pub fn new(size: usize) -> ThreadPool {\n assert!(size > 0);\n\n let mut workers = Vec::with_capacity(size);\n\n for id in 0..size {\n workers.push(Worker::new(id));\n }\n\n ThreadPool { workers }\n }\n // --snip--\n}\n\nstruct Worker {\n id: usize,\n thread: thread::JoinHandle<()>,\n}\n\nimpl Worker {\n fn new(id: usize) -> Worker {\n let thread = thread::spawn(|| {});\n\n Worker { id, thread }\n }\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "From Single-Threaded to Multithreaded Server", "heading_path": ["From a Single-Threaded to a Multithreaded Server", "Improving Throughput with a Thread Pool", "Sending Code from the `ThreadPool` to a Thread"], "path": "ch21-02-multithreaded.md", "url": "https://doc.rust-lang.org/book/ch21-02-multithreaded.html#sending-code-from-the-threadpool-to-a-thread", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch21-02-multithreaded.md#sending-requests-to-threads-via-channels-16", "text": "The Rust Programming Language › From a Single-Threaded to a Multithreaded Server › Improving Throughput with a Thread Pool › Sending Requests to Threads via Channels\n\nWe’ve changed the name of the field on `ThreadPool` from `threads` to `workers`\nbecause it’s now holding `Worker` instances instead of `JoinHandle<()>`\ninstances. We use the counter in the `for` loop as an argument to\n`Worker::new`, and we store each new `Worker` in the vector named `workers`.\nExternal code (like our server in _src/main.rs_) doesn’t need to know the\nimplementation details regarding using a `Worker` struct within `ThreadPool`,\nso we make the `Worker` struct and its `new` function private. The\n`Worker::new` function uses the `id` we give it and stores a `JoinHandle<()>`\ninstance that is created by spawning a new thread using an empty closure.\nNote: If the operating system can’t create a thread because there aren’t\nenough system resources, `thread::spawn` will panic. That will cause our\nwhole server to panic, even though the creation of some threads might\nsucceed. For simplicity’s sake, this behavior is fine, but in a production\nthread pool implementation, you’d likely want to use\n`std::thread::Builder` and its\n`spawn` method that returns `Result` instead.\nThis code will compile and will store the number of `Worker` instances we\nspecified as an argument to `ThreadPool::new`. But we’re _still_ not processing\nthe closure that we get in `execute`. Let’s look at how to do that next.\nThe next problem we’ll tackle is that the closures given to `thread::spawn` do\nabsolutely nothing. Currently, we get the closure we want to execute in the\n`execute` method. But we need to give `thread::spawn` a closure to run when we\ncreate each `Worker` during the creation of the `ThreadPool`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "From Single-Threaded to Multithreaded Server", "heading_path": ["From a Single-Threaded to a Multithreaded Server", "Improving Throughput with a Thread Pool", "Sending Requests to Threads via Channels"], "path": "ch21-02-multithreaded.md", "url": "https://doc.rust-lang.org/book/ch21-02-multithreaded.html#sending-requests-to-threads-via-channels", "has_code": false, "code_tags": []}} {"id": "book/ch21-02-multithreaded.md#sending-requests-to-threads-via-channels-17", "text": "The Rust Programming Language › From a Single-Threaded to a Multithreaded Server › Improving Throughput with a Thread Pool › Sending Requests to Threads via Channels\n\nWe want the `Worker` structs that we just created to fetch the code to run from\na queue held in the `ThreadPool` and send that code to its thread to run.\nThe channels we learned about in Chapter 16—a simple way to communicate between\ntwo threads—would be perfect for this use case. We’ll use a channel to function\nas the queue of jobs, and `execute` will send a job from the `ThreadPool` to\nthe `Worker` instances, which will send the job to its thread. Here is the plan:\n1. The `ThreadPool` will create a channel and hold on to the sender.\n2. Each `Worker` will hold on to the receiver.\n3. We’ll create a new `Job` struct that will hold the closures we want to send\n down the channel.\n4. The `execute` method will send the job it wants to execute through the\n sender.\n5. In its thread, the `Worker` will loop over its receiver and execute the\n closures of any jobs it receives.\nLet’s start by creating a channel in `ThreadPool::new` and holding the sender\nin the `ThreadPool` instance, as shown in Listing 21-16. The `Job` struct\ndoesn’t hold anything for now but will be the type of item we’re sending down\nthe channel.\nListing 21-16: Modifying `ThreadPool` to store the sender of a channel that transmits `Job` instances (src/lib.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "From Single-Threaded to Multithreaded Server", "heading_path": ["From a Single-Threaded to a Multithreaded Server", "Improving Throughput with a Thread Pool", "Sending Requests to Threads via Channels"], "path": "ch21-02-multithreaded.md", "url": "https://doc.rust-lang.org/book/ch21-02-multithreaded.html#sending-requests-to-threads-via-channels", "has_code": false, "code_tags": []}} {"id": "book/ch21-02-multithreaded.md#sending-requests-to-threads-via-channels-18", "text": "The Rust Programming Language › From a Single-Threaded to a Multithreaded Server › Improving Throughput with a Thread Pool › Sending Requests to Threads via Channels\n\n```rust,noplayground\nuse std::{sync::mpsc, thread};\n\npub struct ThreadPool {\n workers: Vec,\n sender: mpsc::Sender,\n}\n\nstruct Job;\n\nimpl ThreadPool {\n // --snip--\n pub fn new(size: usize) -> ThreadPool {\n assert!(size > 0);\n\n let (sender, receiver) = mpsc::channel();\n\n let mut workers = Vec::with_capacity(size);\n\n for id in 0..size {\n workers.push(Worker::new(id));\n }\n\n ThreadPool { workers, sender }\n }\n // --snip--\n}\n```\nIn `ThreadPool::new`, we create our new channel and have the pool hold the\nsender. This will successfully compile.\nLet’s try passing a receiver of the channel into each `Worker` as the thread\npool creates the channel. We know we want to use the receiver in the thread that\nthe `Worker` instances spawn, so we’ll reference the `receiver` parameter in the\nclosure. The code in Listing 21-17 won’t quite compile yet.\nListing 21-17: Passing the receiver to each `Worker` (src/lib.rs)\n```rust,ignore,does_not_compile\nimpl ThreadPool {\n // --snip--\n pub fn new(size: usize) -> ThreadPool {\n assert!(size > 0);\n\n let (sender, receiver) = mpsc::channel();\n\n let mut workers = Vec::with_capacity(size);\n\n for id in 0..size {\n workers.push(Worker::new(id, receiver));\n }\n\n ThreadPool { workers, sender }\n }\n // --snip--\n}\n\n// --snip--\n\nimpl Worker {\n fn new(id: usize, receiver: mpsc::Receiver) -> Worker {\n let thread = thread::spawn(|| {\n receiver;\n });\n\n Worker { id, thread }\n }\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "From Single-Threaded to Multithreaded Server", "heading_path": ["From a Single-Threaded to a Multithreaded Server", "Improving Throughput with a Thread Pool", "Sending Requests to Threads via Channels"], "path": "ch21-02-multithreaded.md", "url": "https://doc.rust-lang.org/book/ch21-02-multithreaded.html#sending-requests-to-threads-via-channels", "has_code": true, "code_tags": ["rust,ignore,does_not_compile", "rust,noplayground"]}} {"id": "book/ch21-02-multithreaded.md#sending-requests-to-threads-via-channels-19", "text": "The Rust Programming Language › From a Single-Threaded to a Multithreaded Server › Improving Throughput with a Thread Pool › Sending Requests to Threads via Channels\n\nWe’ve made some small and straightforward changes: We pass the receiver into\n`Worker::new`, and then we use it inside the closure.\nWhen we try to check this code, we get this error:\n```console\n$ cargo check\n Checking hello v0.1.0 (file:///projects/hello)\nerror[E0382]: use of moved value: `receiver`\n --> src/lib.rs:26:42\n |\n21 | let (sender, receiver) = mpsc::channel();\n | -------- move occurs because `receiver` has type `std::sync::mpsc::Receiver`, which does not implement the `Copy` trait\n...\n25 | for id in 0..size {\n | ----------------- inside of this loop\n26 | workers.push(Worker::new(id, receiver));\n | ^^^^^^^^ value moved here, in previous iteration of loop\n |\nnote: consider changing this parameter type in method `new` to borrow instead if owning the value isn't necessary\n --> src/lib.rs:47:33\n |\n47 | fn new(id: usize, receiver: mpsc::Receiver) -> Worker {\n | --- in this method ^^^^^^^^^^^^^^^^^^^ this parameter takes ownership of the value\n\nFor more information about this error, try `rustc --explain E0382`.\nerror: could not compile `hello` (lib) due to 1 previous error\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "From Single-Threaded to Multithreaded Server", "heading_path": ["From a Single-Threaded to a Multithreaded Server", "Improving Throughput with a Thread Pool", "Sending Requests to Threads via Channels"], "path": "ch21-02-multithreaded.md", "url": "https://doc.rust-lang.org/book/ch21-02-multithreaded.html#sending-requests-to-threads-via-channels", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch21-02-multithreaded.md#sending-requests-to-threads-via-channels-20", "text": "The Rust Programming Language › From a Single-Threaded to a Multithreaded Server › Improving Throughput with a Thread Pool › Sending Requests to Threads via Channels\n\nThe code is trying to pass `receiver` to multiple `Worker` instances. This\nwon’t work, as you’ll recall from Chapter 16: The channel implementation that\nRust provides is multiple _producer_, single _consumer_. This means we can’t\njust clone the consuming end of the channel to fix this code. We also don’t\nwant to send a message multiple times to multiple consumers; we want one list\nof messages with multiple `Worker` instances such that each message gets\nprocessed once.\nAdditionally, taking a job off the channel queue involves mutating the\n`receiver`, so the threads need a safe way to share and modify `receiver`;\notherwise, we might get race conditions (as covered in Chapter 16).\nRecall the thread-safe smart pointers discussed in Chapter 16: To share\nownership across multiple threads and allow the threads to mutate the value, we\nneed to use `Arc>`. The `Arc` type will let multiple `Worker` instances\nown the receiver, and `Mutex` will ensure that only one `Worker` gets a job from\nthe receiver at a time. Listing 21-18 shows the changes we need to make.\nListing 21-18: Sharing the receiver among the `Worker` instances using `Arc` and `Mutex` (src/lib.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "From Single-Threaded to Multithreaded Server", "heading_path": ["From a Single-Threaded to a Multithreaded Server", "Improving Throughput with a Thread Pool", "Sending Requests to Threads via Channels"], "path": "ch21-02-multithreaded.md", "url": "https://doc.rust-lang.org/book/ch21-02-multithreaded.html#sending-requests-to-threads-via-channels", "has_code": false, "code_tags": []}} {"id": "book/ch21-02-multithreaded.md#implementing-the-execute-method-21", "text": "The Rust Programming Language › From a Single-Threaded to a Multithreaded Server › Improving Throughput with a Thread Pool › Implementing the `execute` Method\n\n```rust,noplayground\nuse std::{\n sync::{Arc, Mutex, mpsc},\n thread,\n};\n// --snip--\n\nimpl ThreadPool {\n // --snip--\n pub fn new(size: usize) -> ThreadPool {\n assert!(size > 0);\n\n let (sender, receiver) = mpsc::channel();\n\n let receiver = Arc::new(Mutex::new(receiver));\n\n let mut workers = Vec::with_capacity(size);\n\n for id in 0..size {\n workers.push(Worker::new(id, Arc::clone(&receiver)));\n }\n\n ThreadPool { workers, sender }\n }\n\n // --snip--\n}\n\n// --snip--\n\nimpl Worker {\n fn new(id: usize, receiver: Arc>>) -> Worker {\n // --snip--\n }\n}\n```\nIn `ThreadPool::new`, we put the receiver in an `Arc` and a `Mutex`. For each\nnew `Worker`, we clone the `Arc` to bump the reference count so that the\n`Worker` instances can share ownership of the receiver.\nWith these changes, the code compiles! We’re getting there!\nLet’s finally implement the `execute` method on `ThreadPool`. We’ll also change\n`Job` from a struct to a type alias for a trait object that holds the type of\nclosure that `execute` receives. As discussed in the “Type Synonyms and Type\nAliases” section in Chapter 20, type aliases\nallow us to make long types shorter for ease of use. Look at Listing 21-19.\nListing 21-19: Creating a `Job` type alias for a `Box` that holds each closure and then sending the job down the channel (src/lib.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "From Single-Threaded to Multithreaded Server", "heading_path": ["From a Single-Threaded to a Multithreaded Server", "Improving Throughput with a Thread Pool", "Implementing the `execute` Method"], "path": "ch21-02-multithreaded.md", "url": "https://doc.rust-lang.org/book/ch21-02-multithreaded.html#implementing-the-execute-method", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch21-02-multithreaded.md#implementing-the-execute-method-22", "text": "The Rust Programming Language › From a Single-Threaded to a Multithreaded Server › Improving Throughput with a Thread Pool › Implementing the `execute` Method\n\n```rust,noplayground\n// --snip--\n\ntype Job = Box;\n\nimpl ThreadPool {\n // --snip--\n\n pub fn execute(&self, f: F)\n where\n F: FnOnce() + Send + 'static,\n {\n let job = Box::new(f);\n\n self.sender.send(job).unwrap();\n }\n}\n\n// --snip--\n```\nAfter creating a new `Job` instance using the closure we get in `execute`, we\nsend that job down the sending end of the channel. We’re calling `unwrap` on\n`send` for the case that sending fails. This might happen if, for example, we\nstop all our threads from executing, meaning the receiving end has stopped\nreceiving new messages. At the moment, we can’t stop our threads from\nexecuting: Our threads continue executing as long as the pool exists. The\nreason we use `unwrap` is that we know the failure case won’t happen, but the\ncompiler doesn’t know that.\nBut we’re not quite done yet! In the `Worker`, our closure being passed to\n`thread::spawn` still only _references_ the receiving end of the channel.\nInstead, we need the closure to loop forever, asking the receiving end of the\nchannel for a job and running the job when it gets one. Let’s make the change\nshown in Listing 21-20 to `Worker::new`.\nListing 21-20: Receiving and executing the jobs in the `Worker` instance’s thread (src/lib.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "From Single-Threaded to Multithreaded Server", "heading_path": ["From a Single-Threaded to a Multithreaded Server", "Improving Throughput with a Thread Pool", "Implementing the `execute` Method"], "path": "ch21-02-multithreaded.md", "url": "https://doc.rust-lang.org/book/ch21-02-multithreaded.html#implementing-the-execute-method", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch21-02-multithreaded.md#implementing-the-execute-method-23", "text": "The Rust Programming Language › From a Single-Threaded to a Multithreaded Server › Improving Throughput with a Thread Pool › Implementing the `execute` Method\n\n```rust,noplayground\n// --snip--\n\nimpl Worker {\n fn new(id: usize, receiver: Arc>>) -> Worker {\n let thread = thread::spawn(move || {\n loop {\n let job = receiver.lock().unwrap().recv().unwrap();\n\n println!(\"Worker {id} got a job; executing.\");\n\n job();\n }\n });\n\n Worker { id, thread }\n }\n}\n```\nHere, we first call `lock` on the `receiver` to acquire the mutex, and then we\ncall `unwrap` to panic on any errors. Acquiring a lock might fail if the mutex\nis in a _poisoned_ state, which can happen if some other thread panicked while\nholding the lock rather than releasing the lock. In this situation, calling\n`unwrap` to have this thread panic is the correct action to take. Feel free to\nchange this `unwrap` to an `expect` with an error message that is meaningful to\nyou.\nIf we get the lock on the mutex, we call `recv` to receive a `Job` from the\nchannel. A final `unwrap` moves past any errors here as well, which might occur\nif the thread holding the sender has shut down, similar to how the `send`\nmethod returns `Err` if the receiver shuts down.\nThe call to `recv` blocks, so if there is no job yet, the current thread will\nwait until a job becomes available. The `Mutex` ensures that only one\n`Worker` thread at a time is trying to request a job.\nOur thread pool is now in a working state! Give it a `cargo run` and make some\nrequests:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "From Single-Threaded to Multithreaded Server", "heading_path": ["From a Single-Threaded to a Multithreaded Server", "Improving Throughput with a Thread Pool", "Implementing the `execute` Method"], "path": "ch21-02-multithreaded.md", "url": "https://doc.rust-lang.org/book/ch21-02-multithreaded.html#implementing-the-execute-method", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch21-02-multithreaded.md#implementing-the-execute-method-24", "text": "The Rust Programming Language › From a Single-Threaded to a Multithreaded Server › Improving Throughput with a Thread Pool › Implementing the `execute` Method\n\n```console\n$ cargo run\n Compiling hello v0.1.0 (file:///projects/hello)\nwarning: field `workers` is never read\n --> src/lib.rs:7:5\n |\n6 | pub struct ThreadPool {\n | ---------- field in this struct\n7 | workers: Vec,\n | ^^^^^^^\n |\n = note: `#[warn(dead_code)]` on by default\n\nwarning: fields `id` and `thread` are never read\n --> src/lib.rs:48:5\n |\n47 | struct Worker {\n | ------ fields in this struct\n48 | id: usize,\n | ^^\n49 | thread: thread::JoinHandle<()>,\n | ^^^^^^\n\nwarning: `hello` (lib) generated 2 warnings\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 4.91s\n Running `target/debug/hello`\nWorker 0 got a job; executing.\nWorker 2 got a job; executing.\nWorker 1 got a job; executing.\nWorker 3 got a job; executing.\nWorker 0 got a job; executing.\nWorker 2 got a job; executing.\nWorker 1 got a job; executing.\nWorker 3 got a job; executing.\nWorker 0 got a job; executing.\nWorker 2 got a job; executing.\n```\nSuccess! We now have a thread pool that executes connections asynchronously.\nThere are never more than four threads created, so our system won’t get\noverloaded if the server receives a lot of requests. If we make a request to\n_/sleep_, the server will be able to serve other requests by having another\nthread run them.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "From Single-Threaded to Multithreaded Server", "heading_path": ["From a Single-Threaded to a Multithreaded Server", "Improving Throughput with a Thread Pool", "Implementing the `execute` Method"], "path": "ch21-02-multithreaded.md", "url": "https://doc.rust-lang.org/book/ch21-02-multithreaded.html#implementing-the-execute-method", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch21-02-multithreaded.md#implementing-the-execute-method-25", "text": "The Rust Programming Language › From a Single-Threaded to a Multithreaded Server › Improving Throughput with a Thread Pool › Implementing the `execute` Method\n\nNote: If you open _/sleep_ in multiple browser windows simultaneously, they\nmight load one at a time in five-second intervals. Some web browsers execute\nmultiple instances of the same request sequentially for caching reasons. This\nlimitation is not caused by our web server.\nThis is a good time to pause and consider how the code in Listings 21-18, 21-19,\nand 21-20 would be different if we were using futures instead of a closure for\nthe work to be done. What types would change? How would the method signatures be\ndifferent, if at all? What parts of the code would stay the same?\nAfter learning about the `while let` loop in Chapter 17 and Chapter 19, you\nmight be wondering why we didn’t write the `Worker` thread code as shown in\nListing 21-21.\nListing 21-21: An alternative implementation of `Worker::new` using `while let` (src/lib.rs)\n```rust,ignore,not_desired_behavior\n// --snip--\n\nimpl Worker {\n fn new(id: usize, receiver: Arc>>) -> Worker {\n let thread = thread::spawn(move || {\n while let Ok(job) = receiver.lock().unwrap().recv() {\n println!(\"Worker {id} got a job; executing.\");\n\n job();\n }\n });\n\n Worker { id, thread }\n }\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "From Single-Threaded to Multithreaded Server", "heading_path": ["From a Single-Threaded to a Multithreaded Server", "Improving Throughput with a Thread Pool", "Implementing the `execute` Method"], "path": "ch21-02-multithreaded.md", "url": "https://doc.rust-lang.org/book/ch21-02-multithreaded.html#implementing-the-execute-method", "has_code": true, "code_tags": ["rust,ignore,not_desired_behavior"]}} {"id": "book/ch21-02-multithreaded.md#implementing-the-execute-method-26", "text": "The Rust Programming Language › From a Single-Threaded to a Multithreaded Server › Improving Throughput with a Thread Pool › Implementing the `execute` Method\n\nThis code compiles and runs but doesn’t result in the desired threading\nbehavior: A slow request will still cause other requests to wait to be\nprocessed. The reason is somewhat subtle: The `Mutex` struct has no public\n`unlock` method because the ownership of the lock is based on the lifetime of\nthe `MutexGuard` within the `LockResult>` that the `lock`\nmethod returns. At compile time, the borrow checker can then enforce the rule\nthat a resource guarded by a `Mutex` cannot be accessed unless we hold the\nlock. However, this implementation can also result in the lock being held\nlonger than intended if we aren’t mindful of the lifetime of the\n`MutexGuard`.\nThe code in Listing 21-20 that uses `let job =\nreceiver.lock().unwrap().recv().unwrap();` works because with `let`, any\ntemporary values used in the expression on the right-hand side of the equal\nsign are immediately dropped when the `let` statement ends. However, `while\nlet` (and `if let` and `match`) does not drop temporary values until the end of\nthe associated block. In Listing 21-21, the lock remains held for the duration\nof the call to `job()`, meaning other `Worker` instances cannot receive jobs.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "From Single-Threaded to Multithreaded Server", "heading_path": ["From a Single-Threaded to a Multithreaded Server", "Improving Throughput with a Thread Pool", "Implementing the `execute` Method"], "path": "ch21-02-multithreaded.md", "url": "https://doc.rust-lang.org/book/ch21-02-multithreaded.html#implementing-the-execute-method", "has_code": false, "code_tags": []}} {"id": "book/ch21-03-graceful-shutdown-and-cleanup.md#graceful-shutdown-and-cleanup-0", "text": "The Rust Programming Language › Graceful Shutdown and Cleanup\n\nThe code in Listing 21-20 is responding to requests asynchronously through the\nuse of a thread pool, as we intended. We get some warnings about the `workers`,\n`id`, and `thread` fields that we’re not using in a direct way that reminds us\nwe’re not cleaning up anything. When we use the less elegant\nctrl-C method to halt the main thread, all other threads\nare stopped immediately as well, even if they’re in the middle of serving a\nrequest.\nNext, then, we’ll implement the `Drop` trait to call `join` on each of the\nthreads in the pool so that they can finish the requests they’re working on\nbefore closing. Then, we’ll implement a way to tell the threads they should\nstop accepting new requests and shut down. To see this code in action, we’ll\nmodify our server to accept only two requests before gracefully shutting down\nits thread pool.\nOne thing to notice as we go: None of this affects the parts of the code that\nhandle executing the closures, so everything here would be the same if we were\nusing a thread pool for an async runtime.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Graceful Shutdown and Cleanup", "heading_path": ["Graceful Shutdown and Cleanup"], "path": "ch21-03-graceful-shutdown-and-cleanup.md", "url": "https://doc.rust-lang.org/book/ch21-03-graceful-shutdown-and-cleanup.html#graceful-shutdown-and-cleanup", "has_code": false, "code_tags": []}} {"id": "book/ch21-03-graceful-shutdown-and-cleanup.md#implementing-the-drop-trait-on-threadpool-1", "text": "The Rust Programming Language › Graceful Shutdown and Cleanup › Implementing the `Drop` Trait on `ThreadPool`\n\nLet’s start with implementing `Drop` on our thread pool. When the pool is\ndropped, our threads should all join to make sure they finish their work.\nListing 21-22 shows a first attempt at a `Drop` implementation; this code won’t\nquite work yet.\nListing 21-22: Joining each thread when the thread pool goes out of scope (src/lib.rs)\n```rust,ignore,does_not_compile\nimpl Drop for ThreadPool {\n fn drop(&mut self) {\n for worker in &mut self.workers {\n println!(\"Shutting down worker {}\", worker.id);\n\n worker.thread.join().unwrap();\n }\n }\n}\n```\nFirst, we loop through each of the thread pool `workers`. We use `&mut` for this\nbecause `self` is a mutable reference, and we also need to be able to mutate\n`worker`. For each `worker`, we print a message saying that this particular\n`Worker` instance is shutting down, and then we call `join` on that `Worker`\ninstance’s thread. If the call to `join` fails, we use `unwrap` to make Rust\npanic and go into an ungraceful shutdown.\nHere is the error we get when we compile this code:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Graceful Shutdown and Cleanup", "heading_path": ["Graceful Shutdown and Cleanup", "Implementing the `Drop` Trait on `ThreadPool`"], "path": "ch21-03-graceful-shutdown-and-cleanup.md", "url": "https://doc.rust-lang.org/book/ch21-03-graceful-shutdown-and-cleanup.html#implementing-the-drop-trait-on-threadpool", "has_code": true, "code_tags": ["rust,ignore,does_not_compile"]}} {"id": "book/ch21-03-graceful-shutdown-and-cleanup.md#implementing-the-drop-trait-on-threadpool-2", "text": "The Rust Programming Language › Graceful Shutdown and Cleanup › Implementing the `Drop` Trait on `ThreadPool`\n\n```console\n$ cargo check\n Checking hello v0.1.0 (file:///projects/hello)\nerror[E0507]: cannot move out of `worker.thread` which is behind a mutable reference\n --> src/lib.rs:52:13\n |\n52 | worker.thread.join().unwrap();\n | ^^^^^^^^^^^^^ ------ `worker.thread` moved due to this method call\n | |\n | move occurs because `worker.thread` has type `JoinHandle<()>`, which does not implement the `Copy` trait\n |\nnote: `JoinHandle::::join` takes ownership of the receiver `self`, which moves `worker.thread`\n --> /rustc/2d8144b7880597b6e6d3dfd63a9a9efae3f533d3/library/std/src/thread/join_handle.rs:149:16\n\nFor more information about this error, try `rustc --explain E0507`.\nerror: could not compile `hello` (lib) due to 1 previous error\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Graceful Shutdown and Cleanup", "heading_path": ["Graceful Shutdown and Cleanup", "Implementing the `Drop` Trait on `ThreadPool`"], "path": "ch21-03-graceful-shutdown-and-cleanup.md", "url": "https://doc.rust-lang.org/book/ch21-03-graceful-shutdown-and-cleanup.html#implementing-the-drop-trait-on-threadpool", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch21-03-graceful-shutdown-and-cleanup.md#implementing-the-drop-trait-on-threadpool-3", "text": "The Rust Programming Language › Graceful Shutdown and Cleanup › Implementing the `Drop` Trait on `ThreadPool`\n\nThe error tells us we can’t call `join` because we only have a mutable borrow\nof each `worker` and `join` takes ownership of its argument. To solve this\nissue, we need to move the thread out of the `Worker` instance that owns\n`thread` so that `join` can consume the thread. One way to do this is to take\nthe same approach we took in Listing 18-15. If `Worker` held an\n`Option>`, we could call the `take` method on the\n`Option` to move the value out of the `Some` variant and leave a `None` variant\nin its place. In other words, a `Worker` that is running would have a `Some`\nvariant in `thread`, and when we wanted to clean up a `Worker`, we’d replace\n`Some` with `None` so that the `Worker` wouldn’t have a thread to run.\nHowever, the _only_ time this would come up would be when dropping the\n`Worker`. In exchange, we’d have to deal with an\n`Option>` anywhere we accessed `worker.thread`.\nIdiomatic Rust uses `Option` quite a bit, but when you find yourself wrapping\nsomething you know will always be present in an `Option` as a workaround like\nthis, it’s a good idea to look for alternative approaches to make your code\ncleaner and less error-prone.\nIn this case, a better alternative exists: the `Vec::drain` method. It accepts\na range parameter to specify which items to remove from the vector and returns\nan iterator of those items. Passing the `..` range syntax will remove *every*\nvalue from the vector.\nSo, we need to update the `ThreadPool` `drop` implementation like this:\nListing (src/lib.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Graceful Shutdown and Cleanup", "heading_path": ["Graceful Shutdown and Cleanup", "Implementing the `Drop` Trait on `ThreadPool`"], "path": "ch21-03-graceful-shutdown-and-cleanup.md", "url": "https://doc.rust-lang.org/book/ch21-03-graceful-shutdown-and-cleanup.html#implementing-the-drop-trait-on-threadpool", "has_code": false, "code_tags": []}} {"id": "book/ch21-03-graceful-shutdown-and-cleanup.md#implementing-the-drop-trait-on-threadpool-4", "text": "The Rust Programming Language › Graceful Shutdown and Cleanup › Implementing the `Drop` Trait on `ThreadPool`\n\n```rust\nimpl Drop for ThreadPool {\n fn drop(&mut self) {\n for worker in self.workers.drain(..) {\n println!(\"Shutting down worker {}\", worker.id);\n\n worker.thread.join().unwrap();\n }\n }\n}\n```\nThis resolves the compiler error and does not require any other changes to our\ncode. Note that, because drop can be called when panicking, the unwrap\ncould also panic and cause a double panic, which immediately crashes the\nprogram and ends any cleanup in progress. This is fine for an example program,\nbut it isn’t recommended for production code.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Graceful Shutdown and Cleanup", "heading_path": ["Graceful Shutdown and Cleanup", "Implementing the `Drop` Trait on `ThreadPool`"], "path": "ch21-03-graceful-shutdown-and-cleanup.md", "url": "https://doc.rust-lang.org/book/ch21-03-graceful-shutdown-and-cleanup.html#implementing-the-drop-trait-on-threadpool", "has_code": true, "code_tags": ["rust"]}} {"id": "book/ch21-03-graceful-shutdown-and-cleanup.md#signaling-to-the-threads-to-stop-listening-for-jobs-5", "text": "The Rust Programming Language › Graceful Shutdown and Cleanup › Signaling to the Threads to Stop Listening for Jobs\n\nWith all the changes we’ve made, our code compiles without any warnings.\nHowever, the bad news is that this code doesn’t function the way we want it to\nyet. The key is the logic in the closures run by the threads of the `Worker`\ninstances: At the moment, we call `join`, but that won’t shut down the threads,\nbecause they `loop` forever looking for jobs. If we try to drop our\n`ThreadPool` with our current implementation of `drop`, the main thread will\nblock forever, waiting for the first thread to finish.\nTo fix this problem, we’ll need a change in the `ThreadPool` `drop`\nimplementation and then a change in the `Worker` loop.\nFirst, we’ll change the `ThreadPool` `drop` implementation to explicitly drop\nthe `sender` before waiting for the threads to finish. Listing 21-23 shows the\nchanges to `ThreadPool` to explicitly drop `sender`. Unlike with the thread,\nhere we _do_ need to use an `Option` to be able to move `sender` out of\n`ThreadPool` with `Option::take`.\nListing 21-23: Explicitly dropping `sender` before joining the `Worker` threads (src/lib.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Graceful Shutdown and Cleanup", "heading_path": ["Graceful Shutdown and Cleanup", "Signaling to the Threads to Stop Listening for Jobs"], "path": "ch21-03-graceful-shutdown-and-cleanup.md", "url": "https://doc.rust-lang.org/book/ch21-03-graceful-shutdown-and-cleanup.html#signaling-to-the-threads-to-stop-listening-for-jobs", "has_code": false, "code_tags": []}} {"id": "book/ch21-03-graceful-shutdown-and-cleanup.md#signaling-to-the-threads-to-stop-listening-for-jobs-6", "text": "The Rust Programming Language › Graceful Shutdown and Cleanup › Signaling to the Threads to Stop Listening for Jobs\n\n```rust,noplayground,not_desired_behavior\npub struct ThreadPool {\n workers: Vec,\n sender: Option>,\n}\n// --snip--\nimpl ThreadPool {\n pub fn new(size: usize) -> ThreadPool {\n // --snip--\n\n ThreadPool {\n workers,\n sender: Some(sender),\n }\n }\n\n pub fn execute(&self, f: F)\n where\n F: FnOnce() + Send + 'static,\n {\n let job = Box::new(f);\n\n self.sender.as_ref().unwrap().send(job).unwrap();\n }\n}\n\nimpl Drop for ThreadPool {\n fn drop(&mut self) {\n drop(self.sender.take());\n\n for worker in self.workers.drain(..) {\n println!(\"Shutting down worker {}\", worker.id);\n\n worker.thread.join().unwrap();\n }\n }\n}\n```\nDropping `sender` closes the channel, which indicates no more messages will be\nsent. When that happens, all the calls to `recv` that the `Worker` instances do\nin the infinite loop will return an error. In Listing 21-24, we change the\n`Worker` loop to gracefully exit the loop in that case, which means the threads\nwill finish when the `ThreadPool` `drop` implementation calls `join` on them.\nListing 21-24: Explicitly breaking out of the loop when `recv` returns an error (src/lib.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Graceful Shutdown and Cleanup", "heading_path": ["Graceful Shutdown and Cleanup", "Signaling to the Threads to Stop Listening for Jobs"], "path": "ch21-03-graceful-shutdown-and-cleanup.md", "url": "https://doc.rust-lang.org/book/ch21-03-graceful-shutdown-and-cleanup.html#signaling-to-the-threads-to-stop-listening-for-jobs", "has_code": true, "code_tags": ["rust,noplayground,not_desired_behavior"]}} {"id": "book/ch21-03-graceful-shutdown-and-cleanup.md#signaling-to-the-threads-to-stop-listening-for-jobs-7", "text": "The Rust Programming Language › Graceful Shutdown and Cleanup › Signaling to the Threads to Stop Listening for Jobs\n\n```rust,noplayground\nimpl Worker {\n fn new(id: usize, receiver: Arc>>) -> Worker {\n let thread = thread::spawn(move || {\n loop {\n let message = receiver.lock().unwrap().recv();\n\n match message {\n Ok(job) => {\n println!(\"Worker {id} got a job; executing.\");\n\n job();\n }\n Err(_) => {\n println!(\"Worker {id} disconnected; shutting down.\");\n break;\n }\n }\n }\n });\n\n Worker { id, thread }\n }\n}\n```\nTo see this code in action, let’s modify `main` to accept only two requests\nbefore gracefully shutting down the server, as shown in Listing 21-25.\nListing 21-25: Shutting down the server after serving two requests by exiting the loop (src/main.rs)\n```rust,ignore\nfn main() {\n let listener = TcpListener::bind(\"127.0.0.1:7878\").unwrap();\n let pool = ThreadPool::new(4);\n\n for stream in listener.incoming().take(2) {\n let stream = stream.unwrap();\n\n pool.execute(|| {\n handle_connection(stream);\n });\n }\n\n println!(\"Shutting down.\");\n}\n```\nYou wouldn’t want a real-world web server to shut down after serving only two\nrequests. This code just demonstrates that the graceful shutdown and cleanup is\nin working order.\nThe `take` method is defined in the `Iterator` trait and limits the iteration\nto the first two items at most. The `ThreadPool` will go out of scope at the\nend of `main`, and the `drop` implementation will run.\nStart the server with `cargo run` and make three requests. The third request\nshould error, and in your terminal, you should see output similar to this:", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Graceful Shutdown and Cleanup", "heading_path": ["Graceful Shutdown and Cleanup", "Signaling to the Threads to Stop Listening for Jobs"], "path": "ch21-03-graceful-shutdown-and-cleanup.md", "url": "https://doc.rust-lang.org/book/ch21-03-graceful-shutdown-and-cleanup.html#signaling-to-the-threads-to-stop-listening-for-jobs", "has_code": true, "code_tags": ["rust,ignore", "rust,noplayground"]}} {"id": "book/ch21-03-graceful-shutdown-and-cleanup.md#signaling-to-the-threads-to-stop-listening-for-jobs-8", "text": "The Rust Programming Language › Graceful Shutdown and Cleanup › Signaling to the Threads to Stop Listening for Jobs\n\n```console\n$ cargo run\n Compiling hello v0.1.0 (file:///projects/hello)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.41s\n Running `target/debug/hello`\nWorker 0 got a job; executing.\nShutting down.\nShutting down worker 0\nWorker 3 got a job; executing.\nWorker 1 disconnected; shutting down.\nWorker 2 disconnected; shutting down.\nWorker 3 disconnected; shutting down.\nWorker 0 disconnected; shutting down.\nShutting down worker 1\nShutting down worker 2\nShutting down worker 3\n```\nYou might see a different ordering of `Worker` IDs and messages printed. We can\nsee how this code works from the messages: `Worker` instances 0 and 3 got the\nfirst two requests. The server stopped accepting connections after the second\nconnection, and the `Drop` implementation on `ThreadPool` starts executing\nbefore `Worker 3` even starts its job. Dropping the `sender` disconnects all the\n`Worker` instances and tells them to shut down. The `Worker` instances each\nprint a message when they disconnect, and then the thread pool calls `join` to\nwait for each `Worker` thread to finish.\nNotice one interesting aspect of this particular execution: The `ThreadPool`\ndropped the `sender`, and before any `Worker` received an error, we tried to\njoin `Worker 0`. `Worker 0` had not yet gotten an error from `recv`, so the main\nthread blocked, waiting for `Worker 0` to finish. In the meantime, `Worker 3`\nreceived a job and then all threads received an error. When `Worker 0` finished,\nthe main thread waited for the rest of the `Worker` instances to finish. At that\npoint, they had all exited their loops and stopped.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Graceful Shutdown and Cleanup", "heading_path": ["Graceful Shutdown and Cleanup", "Signaling to the Threads to Stop Listening for Jobs"], "path": "ch21-03-graceful-shutdown-and-cleanup.md", "url": "https://doc.rust-lang.org/book/ch21-03-graceful-shutdown-and-cleanup.html#signaling-to-the-threads-to-stop-listening-for-jobs", "has_code": true, "code_tags": ["console"]}} {"id": "book/ch21-03-graceful-shutdown-and-cleanup.md#signaling-to-the-threads-to-stop-listening-for-jobs-9", "text": "The Rust Programming Language › Graceful Shutdown and Cleanup › Signaling to the Threads to Stop Listening for Jobs\n\nCongrats! We’ve now completed our project; we have a basic web server that uses\na thread pool to respond asynchronously. We’re able to perform a graceful\nshutdown of the server, which cleans up all the threads in the pool.\nHere’s the full code for reference:\nListing (src/main.rs)\n```rust,ignore\nuse hello::ThreadPool;\nuse std::{\n fs,\n io::{BufReader, prelude::*},\n net::{TcpListener, TcpStream},\n thread,\n time::Duration,\n};\n\nfn main() {\n let listener = TcpListener::bind(\"127.0.0.1:7878\").unwrap();\n let pool = ThreadPool::new(4);\n\n for stream in listener.incoming().take(2) {\n let stream = stream.unwrap();\n\n pool.execute(|| {\n handle_connection(stream);\n });\n }\n\n println!(\"Shutting down.\");\n}\n\nfn handle_connection(mut stream: TcpStream) {\n let buf_reader = BufReader::new(&stream);\n let request_line = buf_reader.lines().next().unwrap().unwrap();\n\n let (status_line, filename) = match &request_line[..] {\n \"GET / HTTP/1.1\" => (\"HTTP/1.1 200 OK\", \"hello.html\"),\n \"GET /sleep HTTP/1.1\" => {\n thread::sleep(Duration::from_secs(5));\n (\"HTTP/1.1 200 OK\", \"hello.html\")\n }\n _ => (\"HTTP/1.1 404 NOT FOUND\", \"404.html\"),\n };\n\n let contents = fs::read_to_string(filename).unwrap();\n let length = contents.len();\n\n let response =\n format!(\"{status_line}\\r\\nContent-Length: {length}\\r\\n\\r\\n{contents}\");\n\n stream.write_all(response.as_bytes()).unwrap();\n}\n```\nListing (src/lib.rs)", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Graceful Shutdown and Cleanup", "heading_path": ["Graceful Shutdown and Cleanup", "Signaling to the Threads to Stop Listening for Jobs"], "path": "ch21-03-graceful-shutdown-and-cleanup.md", "url": "https://doc.rust-lang.org/book/ch21-03-graceful-shutdown-and-cleanup.html#signaling-to-the-threads-to-stop-listening-for-jobs", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "book/ch21-03-graceful-shutdown-and-cleanup.md#signaling-to-the-threads-to-stop-listening-for-jobs-10", "text": "The Rust Programming Language › Graceful Shutdown and Cleanup › Signaling to the Threads to Stop Listening for Jobs\n\n```rust,noplayground\nuse std::{\n sync::{Arc, Mutex, mpsc},\n thread,\n};\n\npub struct ThreadPool {\n workers: Vec,\n sender: Option>,\n}\n\ntype Job = Box;\n\nimpl ThreadPool {\n /// Create a new ThreadPool.\n ///\n /// The size is the number of threads in the pool.\n ///\n /// # Panics\n ///\n /// The `new` function will panic if the size is zero.\n pub fn new(size: usize) -> ThreadPool {\n assert!(size > 0);\n\n let (sender, receiver) = mpsc::channel();\n\n let receiver = Arc::new(Mutex::new(receiver));\n\n let mut workers = Vec::with_capacity(size);\n\n for id in 0..size {\n workers.push(Worker::new(id, Arc::clone(&receiver)));\n }\n\n ThreadPool {\n workers,\n sender: Some(sender),\n }\n }\n\n pub fn execute(&self, f: F)\n where\n F: FnOnce() + Send + 'static,\n {\n let job = Box::new(f);\n\n self.sender.as_ref().unwrap().send(job).unwrap();\n }\n}\n\nimpl Drop for ThreadPool {\n fn drop(&mut self) {\n drop(self.sender.take());\n\n for worker in &mut self.workers {\n println!(\"Shutting down worker {}\", worker.id);\n\n if let Some(thread) = worker.thread.take() {\n thread.join().unwrap();\n }\n }\n }\n}\n\nstruct Worker {\n id: usize,\n thread: Option>,\n}\n\nimpl Worker {\n fn new(id: usize, receiver: Arc>>) -> Worker {\n let thread = thread::spawn(move || {\n loop {\n let message = receiver.lock().unwrap().recv();\n\n match message {\n Ok(job) => {\n println!(\"Worker {id} got a job; executing.\");\n\n job();\n }\n Err(_) => {\n println!(\"Worker {id} disconnected; shutting down.\");\n break;\n }\n }\n }\n });\n\n Worker {\n id,\n thread: Some(thread),\n }\n }\n}\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Graceful Shutdown and Cleanup", "heading_path": ["Graceful Shutdown and Cleanup", "Signaling to the Threads to Stop Listening for Jobs"], "path": "ch21-03-graceful-shutdown-and-cleanup.md", "url": "https://doc.rust-lang.org/book/ch21-03-graceful-shutdown-and-cleanup.html#signaling-to-the-threads-to-stop-listening-for-jobs", "has_code": true, "code_tags": ["rust,noplayground"]}} {"id": "book/ch21-03-graceful-shutdown-and-cleanup.md#signaling-to-the-threads-to-stop-listening-for-jobs-11", "text": "The Rust Programming Language › Graceful Shutdown and Cleanup › Signaling to the Threads to Stop Listening for Jobs\n\nWe could do more here! If you want to continue enhancing this project, here are\nsome ideas:\n- Add more documentation to `ThreadPool` and its public methods.\n- Add tests of the library’s functionality.\n- Change calls to `unwrap` to more robust error handling.\n- Use `ThreadPool` to perform some task other than serving web requests.\n- Find a thread pool crate on crates.io and implement a\n similar web server using the crate instead. Then, compare its API and\n robustness to the thread pool we implemented.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Graceful Shutdown and Cleanup", "heading_path": ["Graceful Shutdown and Cleanup", "Signaling to the Threads to Stop Listening for Jobs"], "path": "ch21-03-graceful-shutdown-and-cleanup.md", "url": "https://doc.rust-lang.org/book/ch21-03-graceful-shutdown-and-cleanup.html#signaling-to-the-threads-to-stop-listening-for-jobs", "has_code": false, "code_tags": []}} {"id": "book/ch21-03-graceful-shutdown-and-cleanup.md#summary-12", "text": "The Rust Programming Language › Summary\n\nWell done! You’ve made it to the end of the book! We want to thank you for\njoining us on this tour of Rust. You’re now ready to implement your own Rust\nprojects and help with other people’s projects. Keep in mind that there is a\nwelcoming community of other Rustaceans who would love to help you with any\nchallenges you encounter on your Rust journey.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Graceful Shutdown and Cleanup", "heading_path": ["Summary"], "path": "ch21-03-graceful-shutdown-and-cleanup.md", "url": "https://doc.rust-lang.org/book/ch21-03-graceful-shutdown-and-cleanup.html#summary", "has_code": false, "code_tags": []}} {"id": "book/appendix-00.md#appendix-0", "text": "The Rust Programming Language › Appendix\n\nThe following sections contain reference material you may find useful in your\nRust journey.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "Appendix", "heading_path": ["Appendix"], "path": "appendix-00.md", "url": "https://doc.rust-lang.org/book/appendix-00.html#appendix", "has_code": false, "code_tags": []}} {"id": "book/appendix-01-keywords.md#appendix-a-keywords-0", "text": "The Rust Programming Language › Appendix A: Keywords\n\nThe following lists contain keywords that are reserved for current or future\nuse by the Rust language. As such, they cannot be used as identifiers (except\nas raw identifiers, as we discuss in the “Raw\nIdentifiers” section). _Identifiers_ are names\nof functions, variables, parameters, struct fields, modules, crates, constants,\nmacros, static values, attributes, types, traits, or lifetimes.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "A - Keywords", "heading_path": ["Appendix A: Keywords"], "path": "appendix-01-keywords.md", "url": "https://doc.rust-lang.org/book/appendix-01-keywords.html#appendix-a-keywords", "has_code": false, "code_tags": []}} {"id": "book/appendix-01-keywords.md#keywords-currently-in-use-1", "text": "The Rust Programming Language › Appendix A: Keywords › Keywords Currently in Use\n\nThe following is a list of keywords currently in use, with their functionality\ndescribed.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "A - Keywords", "heading_path": ["Appendix A: Keywords", "Keywords Currently in Use"], "path": "appendix-01-keywords.md", "url": "https://doc.rust-lang.org/book/appendix-01-keywords.html#keywords-currently-in-use", "has_code": false, "code_tags": []}} {"id": "book/appendix-01-keywords.md#keywords-currently-in-use-2", "text": "The Rust Programming Language › Appendix A: Keywords › Keywords Currently in Use\n\n- **`as`**: Perform primitive casting, disambiguate the specific trait\n containing an item, or rename items in `use` statements.\n- **`async`**: Return a `Future` instead of blocking the current thread.\n- **`await`**: Suspend execution until the result of a `Future` is ready.\n- **`break`**: Exit a loop immediately.\n- **`const`**: Define constant items or constant raw pointers.\n- **`continue`**: Continue to the next loop iteration.\n- **`crate`**: In a module path, refers to the crate root.\n- **`dyn`**: Dynamic dispatch to a trait object.\n- **`else`**: Fallback for `if` and `if let` control flow constructs.\n- **`enum`**: Define an enumeration.\n- **`extern`**: Link an external function or variable.\n- **`false`**: Boolean false literal.\n- **`fn`**: Define a function or the function pointer type.\n- **`for`**: Loop over items from an iterator, implement a trait, or specify a\n higher ranked lifetime.\n- **`if`**: Branch based on the result of a conditional expression.\n- **`impl`**: Implement inherent or trait functionality.\n- **`in`**: Part of `for` loop syntax.\n- **`let`**: Bind a variable.\n- **`loop`**: Loop unconditionally.\n- **`match`**: Match a value to patterns.\n- **`mod`**: Define a module.\n- **`move`**: Make a closure take ownership of all its captures.\n- **`mut`**: Denote mutability in references, raw pointers, or pattern bindings.\n- **`pub`**: Denote public visibility in struct fields, `impl` blocks, or\n modules.\n- **`ref`**: Bind by reference.\n- **`return`**: Return from function.\n- **`Self`**: A type alias for the type we are defining or implementing.\n- **`self`**: Method subject or current module.\n- **`static`**: Global variable or lifetime lasting the entire program\n execution.\n- **`struct`**: Define a structure.\n- **`super`**: Parent module of the current module.\n- **`trait`**: Define a trait.\n- **`true`**: Boolean true literal.\n- **`type`**: Define a type alias or associated type.\n- **`union`**: Define a union; is a keyword only when\n used in a union declaration.\n- **`unsafe`**: Denote unsafe code, functions, traits, or implementations.\n- **`use`**: Bring symbols into scope.\n- **`where`**: Denote clauses that constrain a type.\n- **`while`**: Loop conditionally based on the result of an expression.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "A - Keywords", "heading_path": ["Appendix A: Keywords", "Keywords Currently in Use"], "path": "appendix-01-keywords.md", "url": "https://doc.rust-lang.org/book/appendix-01-keywords.html#keywords-currently-in-use", "has_code": false, "code_tags": []}} {"id": "book/appendix-01-keywords.md#keywords-reserved-for-future-use-3", "text": "The Rust Programming Language › Appendix A: Keywords › Keywords Reserved for Future Use\n\nThe following keywords do not yet have any functionality but are reserved by\nRust for potential future use:\n- `abstract`\n- `become`\n- `box`\n- `do`\n- `final`\n- `gen`\n- `macro`\n- `override`\n- `priv`\n- `try`\n- `typeof`\n- `unsized`\n- `virtual`\n- `yield`", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "A - Keywords", "heading_path": ["Appendix A: Keywords", "Keywords Reserved for Future Use"], "path": "appendix-01-keywords.md", "url": "https://doc.rust-lang.org/book/appendix-01-keywords.html#keywords-reserved-for-future-use", "has_code": false, "code_tags": []}} {"id": "book/appendix-01-keywords.md#raw-identifiers-4", "text": "The Rust Programming Language › Appendix A: Keywords › Raw Identifiers\n\n_Raw identifiers_ are the syntax that lets you use keywords where they wouldn’t\nnormally be allowed. You use a raw identifier by prefixing a keyword with `r#`.\nFor example, `match` is a keyword. If you try to compile the following function\nthat uses `match` as its name:\nFilename: src/main.rs\n```rust,ignore,does_not_compile\nfn match(needle: &str, haystack: &str) -> bool {\n haystack.contains(needle)\n}\n```\nyou’ll get this error:\n```text\nerror: expected identifier, found keyword `match`\n --> src/main.rs:4:4\n |\n4 | fn match(needle: &str, haystack: &str) -> bool {\n | ^^^^^ expected identifier, found keyword\n```\nThe error shows that you can’t use the keyword `match` as the function\nidentifier. To use `match` as a function name, you need to use the raw\nidentifier syntax, like this:\nFilename: src/main.rs\n```rust\nfn r#match(needle: &str, haystack: &str) -> bool {\n haystack.contains(needle)\n}\n\nfn main() {\n assert!(r#match(\"foo\", \"foobar\"));\n}\n```\nThis code will compile without any errors. Note the `r#` prefix on the function\nname in its definition as well as where the function is called in `main`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "A - Keywords", "heading_path": ["Appendix A: Keywords", "Raw Identifiers"], "path": "appendix-01-keywords.md", "url": "https://doc.rust-lang.org/book/appendix-01-keywords.html#raw-identifiers", "has_code": true, "code_tags": ["rust", "rust,ignore,does_not_compile", "text"]}} {"id": "book/appendix-01-keywords.md#raw-identifiers-5", "text": "The Rust Programming Language › Appendix A: Keywords › Raw Identifiers\n\nRaw identifiers allow you to use any word you choose as an identifier, even if\nthat word happens to be a reserved keyword. This gives us more freedom to choose\nidentifier names, as well as lets us integrate with programs written in a\nlanguage where these words aren’t keywords. In addition, raw identifiers allow\nyou to use libraries written in a different Rust edition than your crate uses.\nFor example, `try` isn’t a keyword in the 2015 edition but is in the 2018, 2021,\nand 2024 editions. If you depend on a library that is written using the 2015\nedition and has a `try` function, you’ll need to use the raw identifier syntax,\n`r#try` in this case, to call that function from your code on later editions.\nSee Appendix E for more information on editions.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "A - Keywords", "heading_path": ["Appendix A: Keywords", "Raw Identifiers"], "path": "appendix-01-keywords.md", "url": "https://doc.rust-lang.org/book/appendix-01-keywords.html#raw-identifiers", "has_code": false, "code_tags": []}} {"id": "book/appendix-02-operators.md#appendix-b-operators-and-symbols-0", "text": "The Rust Programming Language › Appendix B: Operators and Symbols\n\nThis appendix contains a glossary of Rust’s syntax, including operators and\nother symbols that appear by themselves or in the context of paths, generics,\ntrait bounds, macros, attributes, comments, tuples, and brackets.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "B - Operators and Symbols", "heading_path": ["Appendix B: Operators and Symbols"], "path": "appendix-02-operators.md", "url": "https://doc.rust-lang.org/book/appendix-02-operators.html#appendix-b-operators-and-symbols", "has_code": false, "code_tags": []}} {"id": "book/appendix-02-operators.md#operators-1", "text": "The Rust Programming Language › Appendix B: Operators and Symbols › Operators\n\nTable B-1 contains the operators in Rust, an example of how the operator would\nappear in context, a short explanation, and whether that operator is\noverloadable. If an operator is overloadable, the relevant trait to use to\noverload that operator is listed.\nTable B-1: Operators", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "B - Operators and Symbols", "heading_path": ["Appendix B: Operators and Symbols", "Operators"], "path": "appendix-02-operators.md", "url": "https://doc.rust-lang.org/book/appendix-02-operators.html#operators", "has_code": false, "code_tags": []}} {"id": "book/appendix-02-operators.md#operators-2", "text": "The Rust Programming Language › Appendix B: Operators and Symbols › Operators\n\n| Operator | Example | Explanation | Overloadable? |\n| ------------------------- | ------------------------------------------------------- | --------------------------------------------------------------------- | -------------- |\n| `!` | `ident!(...)`, `ident!{...}`, `ident![...]` | Macro expansion | |\n| `!` | `!expr` | Bitwise or logical complement | `Not` |\n| `!=` | `expr != expr` | Nonequality comparison | `PartialEq` |\n| `%` | `expr % expr` | Arithmetic remainder | `Rem` |\n| `%=` | `var %= expr` | Arithmetic remainder and assignment | `RemAssign` |\n| `&` | `&expr`, `&mut expr` | Borrow | |\n| `&` | `&type`, `&mut type`, `&'a type`, `&'a mut type` | Borrowed pointer type | |\n| `&` | `expr & expr` | Bitwise AND | `BitAnd` |\n| `&=` | `var &= expr` | Bitwise AND and assignment | `BitAndAssign` |\n| `&&` | `expr && expr` | Short-circuiting logical AND | |\n| `*` | `expr * expr` | Arithmetic multiplication | `Mul` |\n| `*=` | `var *= expr` | Arithmetic multiplication and assignment | `MulAssign` |\n| `*` | `*expr` | Dereference | `Deref` |\n| `*` | `*const type`, `*mut type` | Raw pointer | |\n| `+` | `trait + trait`, `'a + trait` | Compound type constraint | |\n| `+` | `expr + expr` | Arithmetic addition | `Add` |\n| `+=` | `var += expr` | Arithmetic addition and assignment | `AddAssign` |\n| `,` | `expr, expr` | Argument and element separator | |\n| `-` | `- expr` | Arithmetic negation | `Neg` |\n| `-` | `expr - expr` | Arithmetic subtraction | `Sub` |\n| `-=` | `var -= expr` | Arithmetic subtraction and assignment | `SubAssign` |\n| `->` | `fn(...) -> type`, |...| -> type | Function and closure return type | |\n| `.` | `expr.ident` | Field access | |\n| `.` | `expr.ident(expr, ...)` | Method call | |\n| `.` | `expr.0`, `expr.1`, and so on | Tuple indexing | |\n| `..` | `..`, `expr..`, `..expr`, `expr..expr` | Right-exclusive range literal | `PartialOrd` |\n| `..=` | `..=expr`, `expr..=expr` | Right-inclusive range literal | `PartialOrd` |\n| `..` | `..expr` | Struct literal update syntax | |\n| `..` | `variant(x, ..)`, `struct_type { x, .. }` | “And the rest” pattern binding | |\n| `...` | `expr...expr` | (Deprecated, use `..=` instead) In a pattern: inclusive range pattern | |\n| `/` | `expr / expr` | Arithmetic division | `Div` |\n| `/=` | `var /= expr` | Arithmetic division and assignment | `DivAssign` |\n| `:` | `pat: type`, `ident: type` | Constraints | |\n| `:` | `ident: expr` | Struct field initializer | |\n| `:` | `'a: loop {...}` | Loop label | |\n| `;` | `expr;` | Statement and item terminator | |\n| `;` | `[...; len]` | Part of fixed-size array syntax | |\n| `<<` | `expr << expr` | Left-shift | `Shl` |\n| `<<=` | `var <<= expr` | Left-shift and assignment | `ShlAssign` |\n| `<` | `expr < expr` | Less than comparison | `PartialOrd` |\n| `<=` | `expr <= expr` | Less than or equal to comparison | `PartialOrd` |\n| `=` | `var = expr`, `ident = type` | Assignment/equivalence | |\n| `==` | `expr == expr` | Equality comparison | `PartialEq` |\n| `=>` | `pat => expr` | Part of match arm syntax | |\n| `>` | `expr > expr` | Greater than comparison | `PartialOrd` |\n| `>=` | `expr >= expr` | Greater than or equal to comparison | `PartialOrd` |\n| `>>` | `expr >> expr` | Right-shift | `Shr` |\n| `>>=` | `var >>= expr` | Right-shift and assignment | `ShrAssign` |\n| `@` | `ident @ pat` | Pattern binding | |\n| `^` | `expr ^ expr` | Bitwise exclusive OR | `BitXor` |\n| `^=` | `var ^= expr` | Bitwise exclusive OR and assignment | `BitXorAssign` |\n| | | pat | pat | Pattern alternatives | |\n| | | expr | expr | Bitwise OR | `BitOr` |\n| |= | var |= expr | Bitwise OR and assignment | `BitOrAssign` |\n| || | expr || expr | Short-circuiting logical OR | |\n| `?` | `expr?` | Error propagation | |", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "B - Operators and Symbols", "heading_path": ["Appendix B: Operators and Symbols", "Operators"], "path": "appendix-02-operators.md", "url": "https://doc.rust-lang.org/book/appendix-02-operators.html#operators", "has_code": false, "code_tags": []}} {"id": "book/appendix-02-operators.md#non-operator-symbols-3", "text": "The Rust Programming Language › Appendix B: Operators and Symbols › Non-operator Symbols\n\nThe following tables contain all symbols that don’t function as operators; that\nis, they don’t behave like a function or method call.\nTable B-2 shows symbols that appear on their own and are valid in a variety of\nlocations.\nTable B-2: Stand-alone Syntax\n| Symbol | Explanation |\n| ---------------------------------------------------------------------- | ---------------------------------------------------------------------- |\n| `'ident` | Named lifetime or loop label |\n| Digits immediately followed by `u8`, `i32`, `f64`, `usize`, and so on | Numeric literal of specific type |\n| `\"...\"` | String literal |\n| `r\"...\"`, `r#\"...\"#`, `r##\"...\"##`, and so on | Raw string literal; escape characters not processed |\n| `b\"...\"` | Byte string literal; constructs an array of bytes instead of a string |\n| `br\"...\"`, `br#\"...\"#`, `br##\"...\"##`, and so on | Raw byte string literal; combination of raw and byte string literal |\n| `'...'` | Character literal |\n| `b'...'` | ASCII byte literal |\n| |...| expr | Closure |\n| `!` | Always-empty bottom type for diverging functions |\n| `_` | “Ignored” pattern binding; also used to make integer literals readable |\nTable B-3 shows symbols that appear in the context of a path through the module\nhierarchy to an item.\nTable B-3: Path-Related Syntax", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "B - Operators and Symbols", "heading_path": ["Appendix B: Operators and Symbols", "Non-operator Symbols"], "path": "appendix-02-operators.md", "url": "https://doc.rust-lang.org/book/appendix-02-operators.html#non-operator-symbols", "has_code": false, "code_tags": []}} {"id": "book/appendix-02-operators.md#non-operator-symbols-4", "text": "The Rust Programming Language › Appendix B: Operators and Symbols › Non-operator Symbols\n\n| Symbol | Explanation |\n| --------------------------------------- | -------------------------------------------------------------------------------------------------------------|\n| `ident::ident` | Namespace path |\n| `::path` | Path relative to the crate root (that is, an explicitly absolute path) |\n| `self::path` | Path relative to the current module (that is, an explicitly relative path) |\n| `super::path` | Path relative to the parent of the current module |\n| `type::ident`, `::ident` | Associated constants, functions, and types |\n| `::...` | Associated item for a type that cannot be directly named (for example, `<&T>::...`, `<[T]>::...`, and so on) |\n| `trait::method(...)` | Disambiguating a method call by naming the trait that defines it |\n| `type::method(...)` | Disambiguating a method call by naming the type for which it’s defined |\n| `::method(...)` | Disambiguating a method call by naming the trait and type |\nTable B-4 shows symbols that appear in the context of using generic type\nparameters.\nTable B-4: Generics", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "B - Operators and Symbols", "heading_path": ["Appendix B: Operators and Symbols", "Non-operator Symbols"], "path": "appendix-02-operators.md", "url": "https://doc.rust-lang.org/book/appendix-02-operators.html#non-operator-symbols", "has_code": false, "code_tags": []}} {"id": "book/appendix-02-operators.md#non-operator-symbols-5", "text": "The Rust Programming Language › Appendix B: Operators and Symbols › Non-operator Symbols\n\n| Symbol | Explanation |\n| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `path<...>` | Specifies parameters to a generic type in a type (for example, `Vec`) |\n| `path::<...>`, `method::<...>` | Specifies parameters to a generic type, function, or method in an expression; often referred to as _turbofish_ (for example, `\"42\".parse::()`) |\n| `fn ident<...> ...` | Define generic function |\n| `struct ident<...> ...` | Define generic structure |\n| `enum ident<...> ...` | Define generic enumeration |\n| `impl<...> ...` | Define generic implementation |\n| `for<...> type` | Higher ranked lifetime bounds |\n| `type` | A generic type where one or more associated types have specific assignments (for example, `Iterator`) |\nTable B-5 shows symbols that appear in the context of constraining generic type\nparameters with trait bounds.\nTable B-5: Trait Bound Constraints", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "B - Operators and Symbols", "heading_path": ["Appendix B: Operators and Symbols", "Non-operator Symbols"], "path": "appendix-02-operators.md", "url": "https://doc.rust-lang.org/book/appendix-02-operators.html#non-operator-symbols", "has_code": false, "code_tags": []}} {"id": "book/appendix-02-operators.md#non-operator-symbols-6", "text": "The Rust Programming Language › Appendix B: Operators and Symbols › Non-operator Symbols\n\n| Symbol | Explanation |\n| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |\n| `T: U` | Generic parameter `T` constrained to types that implement `U` |\n| `T: 'a` | Generic type `T` must outlive lifetime `'a` (meaning the type cannot transitively contain any references with lifetimes shorter than `'a`) |\n| `T: 'static` | Generic type `T` contains no borrowed references other than `'static` ones |\n| `'b: 'a` | Generic lifetime `'b` must outlive lifetime `'a` |\n| `T: ?Sized` | Allow generic type parameter to be a dynamically sized type |\n| `'a + trait`, `trait + trait` | Compound type constraint |\nTable B-6 shows symbols that appear in the context of calling or defining\nmacros and specifying attributes on an item.\nTable B-6: Macros and Attributes\n| Symbol | Explanation |\n| ------------------------------------------- | ------------------ |\n| `#[meta]` | Outer attribute |\n| `#![meta]` | Inner attribute |\n| `$ident` | Macro substitution |\n| `$ident:kind` | Macro metavariable |\n| `$(...)...` | Macro repetition |\n| `ident!(...)`, `ident!{...}`, `ident![...]` | Macro invocation |\nTable B-7 shows symbols that create comments.\nTable B-7: Comments", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "B - Operators and Symbols", "heading_path": ["Appendix B: Operators and Symbols", "Non-operator Symbols"], "path": "appendix-02-operators.md", "url": "https://doc.rust-lang.org/book/appendix-02-operators.html#non-operator-symbols", "has_code": false, "code_tags": []}} {"id": "book/appendix-02-operators.md#non-operator-symbols-7", "text": "The Rust Programming Language › Appendix B: Operators and Symbols › Non-operator Symbols\n\n| Symbol | Explanation |\n| ---------- | ----------------------- |\n| `//` | Line comment |\n| `//!` | Inner line doc comment |\n| `///` | Outer line doc comment |\n| `/*...*/` | Block comment |\n| `/*!...*/` | Inner block doc comment |\n| `/**...*/` | Outer block doc comment |\nTable B-8 shows the contexts in which parentheses are used.\nTable B-8: Parentheses\n| Symbol | Explanation |\n| ------------------------ | ------------------------------------------------------------------------------------------- |\n| `()` | Empty tuple (aka unit), both literal and type |\n| `(expr)` | Parenthesized expression |\n| `(expr,)` | Single-element tuple expression |\n| `(type,)` | Single-element tuple type |\n| `(expr, ...)` | Tuple expression |\n| `(type, ...)` | Tuple type |\n| `expr(expr, ...)` | Function call expression; also used to initialize tuple `struct`s and tuple `enum` variants |\nTable B-9 shows the contexts in which curly brackets are used.\nTable B-9: Curly Brackets\n| Context | Explanation |\n| ------------ | ---------------- |\n| `{...}` | Block expression |\n| `Type {...}` | Struct literal |\nTable B-10 shows the contexts in which square brackets are used.\nTable B-10: Square Brackets", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "B - Operators and Symbols", "heading_path": ["Appendix B: Operators and Symbols", "Non-operator Symbols"], "path": "appendix-02-operators.md", "url": "https://doc.rust-lang.org/book/appendix-02-operators.html#non-operator-symbols", "has_code": false, "code_tags": []}} {"id": "book/appendix-02-operators.md#non-operator-symbols-8", "text": "The Rust Programming Language › Appendix B: Operators and Symbols › Non-operator Symbols\n\n| Context | Explanation |\n| -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |\n| `[...]` | Array literal |\n| `[expr; len]` | Array literal containing `len` copies of `expr` |\n| `[type; len]` | Array type containing `len` instances of `type` |\n| `expr[expr]` | Collection indexing; overloadable (`Index`, `IndexMut`) |\n| `expr[..]`, `expr[a..]`, `expr[..b]`, `expr[a..b]` | Collection indexing pretending to be collection slicing, using `Range`, `RangeFrom`, `RangeTo`, or `RangeFull` as the “index” |", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "B - Operators and Symbols", "heading_path": ["Appendix B: Operators and Symbols", "Non-operator Symbols"], "path": "appendix-02-operators.md", "url": "https://doc.rust-lang.org/book/appendix-02-operators.html#non-operator-symbols", "has_code": false, "code_tags": []}} {"id": "book/appendix-03-derivable-traits.md#appendix-c-derivable-traits-0", "text": "The Rust Programming Language › Appendix C: Derivable Traits\n\nIn various places in the book, we’ve discussed the `derive` attribute, which\nyou can apply to a struct or enum definition. The `derive` attribute generates\ncode that will implement a trait with its own default implementation on the\ntype you’ve annotated with the `derive` syntax.\nIn this appendix, we provide a reference of all the traits in the standard\nlibrary that you can use with `derive`. Each section covers:\n- What operators and methods deriving this trait will enable\n- What the implementation of the trait provided by `derive` does\n- What implementing the trait signifies about the type\n- The conditions in which you’re allowed or not allowed to implement the trait\n- Examples of operations that require the trait\nIf you want different behavior from that provided by the `derive` attribute,\nconsult the standard library documentation\nfor each trait for details on how to manually implement them.\nThe traits listed here are the only ones defined by the standard library that\ncan be implemented on your types using `derive`. Other traits defined in the\nstandard library don’t have sensible default behavior, so it’s up to you to\nimplement them in the way that makes sense for what you’re trying to accomplish.\nAn example of a trait that can’t be derived is `Display`, which handles\nformatting for end users. You should always consider the appropriate way to\ndisplay a type to an end user. What parts of the type should an end user be\nallowed to see? What parts would they find relevant? What format of the data\nwould be most relevant to them? The Rust compiler doesn’t have this insight, so\nit can’t provide appropriate default behavior for you.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "C - Derivable Traits", "heading_path": ["Appendix C: Derivable Traits"], "path": "appendix-03-derivable-traits.md", "url": "https://doc.rust-lang.org/book/appendix-03-derivable-traits.html#appendix-c-derivable-traits", "has_code": false, "code_tags": []}} {"id": "book/appendix-03-derivable-traits.md#appendix-c-derivable-traits-1", "text": "The Rust Programming Language › Appendix C: Derivable Traits\n\nThe list of derivable traits provided in this appendix is not comprehensive:\nLibraries can implement `derive` for their own traits, making the list of\ntraits you can use `derive` with truly open ended. Implementing `derive`\ninvolves using a procedural macro, which is covered in the “Custom `derive`\nMacros” section in Chapter 20.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "C - Derivable Traits", "heading_path": ["Appendix C: Derivable Traits"], "path": "appendix-03-derivable-traits.md", "url": "https://doc.rust-lang.org/book/appendix-03-derivable-traits.html#appendix-c-derivable-traits", "has_code": false, "code_tags": []}} {"id": "book/appendix-03-derivable-traits.md#debug-for-programmer-output-2", "text": "The Rust Programming Language › Appendix C: Derivable Traits › `Debug` for Programmer Output\n\nThe `Debug` trait enables debug formatting in format strings, which you\nindicate by adding `:?` within `{}` placeholders.\nThe `Debug` trait allows you to print instances of a type for debugging\npurposes, so you and other programmers using your type can inspect an instance\nat a particular point in a program’s execution.\nThe `Debug` trait is required, for example, in the use of the `assert_eq!`\nmacro. This macro prints the values of instances given as arguments if the\nequality assertion fails so that programmers can see why the two instances\nweren’t equal.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "C - Derivable Traits", "heading_path": ["Appendix C: Derivable Traits", "`Debug` for Programmer Output"], "path": "appendix-03-derivable-traits.md", "url": "https://doc.rust-lang.org/book/appendix-03-derivable-traits.html#debug-for-programmer-output", "has_code": false, "code_tags": []}} {"id": "book/appendix-03-derivable-traits.md#partialeq-and-eq-for-equality-comparisons-3", "text": "The Rust Programming Language › Appendix C: Derivable Traits › `PartialEq` and `Eq` for Equality Comparisons\n\nThe `PartialEq` trait allows you to compare instances of a type to check for\nequality and enables use of the `==` and `!=` operators.\nDeriving `PartialEq` implements the `eq` method. When `PartialEq` is derived on\nstructs, two instances are equal only if _all_ fields are equal, and the\ninstances are not equal if _any_ fields are not equal. When derived on enums,\neach variant is equal to itself and not equal to the other variants.\nThe `PartialEq` trait is required, for example, with the use of the\n`assert_eq!` macro, which needs to be able to compare two instances of a type\nfor equality.\nThe `Eq` trait has no methods. Its purpose is to signal that for every value of\nthe annotated type, the value is equal to itself. The `Eq` trait can only be\napplied to types that also implement `PartialEq`, although not all types that\nimplement `PartialEq` can implement `Eq`. One example of this is floating-point\nnumber types: The implementation of floating-point numbers states that two\ninstances of the not-a-number (`NaN`) value are not equal to each other.\nAn example of when `Eq` is required is for keys in a `HashMap` so that\nthe `HashMap` can tell whether two keys are the same.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "C - Derivable Traits", "heading_path": ["Appendix C: Derivable Traits", "`PartialEq` and `Eq` for Equality Comparisons"], "path": "appendix-03-derivable-traits.md", "url": "https://doc.rust-lang.org/book/appendix-03-derivable-traits.html#partialeq-and-eq-for-equality-comparisons", "has_code": false, "code_tags": []}} {"id": "book/appendix-03-derivable-traits.md#partialord-and-ord-for-ordering-comparisons-4", "text": "The Rust Programming Language › Appendix C: Derivable Traits › `PartialOrd` and `Ord` for Ordering Comparisons\n\nThe `PartialOrd` trait allows you to compare instances of a type for sorting\npurposes. A type that implements `PartialOrd` can be used with the `<`, `>`,\n`<=`, and `>=` operators. You can only apply the `PartialOrd` trait to types\nthat also implement `PartialEq`.\nDeriving `PartialOrd` implements the `partial_cmp` method, which returns an\n`Option` that will be `None` when the values given don’t produce an\nordering. An example of a value that doesn’t produce an ordering, even though\nmost values of that type can be compared, is the `NaN` floating point value.\nCalling `partial_cmp` with any floating-point number and the `NaN`\nfloating-point value will return `None`.\nWhen derived on structs, `PartialOrd` compares two instances by comparing the\nvalue in each field in the order in which the fields appear in the struct\ndefinition. When derived on enums, variants of the enum declared earlier in the\nenum definition are considered less than the variants listed later.\nThe `PartialOrd` trait is required, for example, for the `gen_range` method\nfrom the `rand` crate that generates a random value in the range specified by a\nrange expression.\nThe `Ord` trait allows you to know that for any two values of the annotated\ntype, a valid ordering will exist. The `Ord` trait implements the `cmp` method,\nwhich returns an `Ordering` rather than an `Option` because a valid\nordering will always be possible. You can only apply the `Ord` trait to types\nthat also implement `PartialOrd` and `Eq` (and `Eq` requires `PartialEq`). When\nderived on structs and enums, `cmp` behaves the same way as the derived\nimplementation for `partial_cmp` does with `PartialOrd`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "C - Derivable Traits", "heading_path": ["Appendix C: Derivable Traits", "`PartialOrd` and `Ord` for Ordering Comparisons"], "path": "appendix-03-derivable-traits.md", "url": "https://doc.rust-lang.org/book/appendix-03-derivable-traits.html#partialord-and-ord-for-ordering-comparisons", "has_code": false, "code_tags": []}} {"id": "book/appendix-03-derivable-traits.md#partialord-and-ord-for-ordering-comparisons-5", "text": "The Rust Programming Language › Appendix C: Derivable Traits › `PartialOrd` and `Ord` for Ordering Comparisons\n\nAn example of when `Ord` is required is when storing values in a `BTreeSet`,\na data structure that stores data based on the sort order of the values.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "C - Derivable Traits", "heading_path": ["Appendix C: Derivable Traits", "`PartialOrd` and `Ord` for Ordering Comparisons"], "path": "appendix-03-derivable-traits.md", "url": "https://doc.rust-lang.org/book/appendix-03-derivable-traits.html#partialord-and-ord-for-ordering-comparisons", "has_code": false, "code_tags": []}} {"id": "book/appendix-03-derivable-traits.md#clone-and-copy-for-duplicating-values-6", "text": "The Rust Programming Language › Appendix C: Derivable Traits › `Clone` and `Copy` for Duplicating Values\n\nThe `Clone` trait allows you to explicitly create a deep copy of a value, and\nthe duplication process might involve running arbitrary code and copying heap\ndata. See the “Variables and Data Interacting with\nClone” section in\nChapter 4 for more information on `Clone`.\nDeriving `Clone` implements the `clone` method, which when implemented for the\nwhole type, calls `clone` on each of the parts of the type. This means all the\nfields or values in the type must also implement `Clone` to derive `Clone`.\nAn example of when `Clone` is required is when calling the `to_vec` method on a\nslice. The slice doesn’t own the type instances it contains, but the vector\nreturned from `to_vec` will need to own its instances, so `to_vec` calls\n`clone` on each item. Thus, the type stored in the slice must implement `Clone`.\nThe `Copy` trait allows you to duplicate a value by only copying bits stored on\nthe stack; no arbitrary code is necessary. See the “Stack-Only Data:\nCopy” section in Chapter 4 for more\ninformation on `Copy`.\nThe `Copy` trait doesn’t define any methods to prevent programmers from\noverloading those methods and violating the assumption that no arbitrary code\nis being run. That way, all programmers can assume that copying a value will be\nvery fast.\nYou can derive `Copy` on any type whose parts all implement `Copy`. A type that\nimplements `Copy` must also implement `Clone` because a type that implements\n`Copy` has a trivial implementation of `Clone` that performs the same task as\n`Copy`.\nThe `Copy` trait is rarely required; types that implement `Copy` have\noptimizations available, meaning you don’t have to call `clone`, which makes\nthe code more concise.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "C - Derivable Traits", "heading_path": ["Appendix C: Derivable Traits", "`Clone` and `Copy` for Duplicating Values"], "path": "appendix-03-derivable-traits.md", "url": "https://doc.rust-lang.org/book/appendix-03-derivable-traits.html#clone-and-copy-for-duplicating-values", "has_code": false, "code_tags": []}} {"id": "book/appendix-03-derivable-traits.md#clone-and-copy-for-duplicating-values-7", "text": "The Rust Programming Language › Appendix C: Derivable Traits › `Clone` and `Copy` for Duplicating Values\n\nEverything possible with `Copy` you can also accomplish with `Clone`, but the\ncode might be slower or have to use `clone` in places.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "C - Derivable Traits", "heading_path": ["Appendix C: Derivable Traits", "`Clone` and `Copy` for Duplicating Values"], "path": "appendix-03-derivable-traits.md", "url": "https://doc.rust-lang.org/book/appendix-03-derivable-traits.html#clone-and-copy-for-duplicating-values", "has_code": false, "code_tags": []}} {"id": "book/appendix-03-derivable-traits.md#hash-for-mapping-a-value-to-a-value-of-fixed-size-8", "text": "The Rust Programming Language › Appendix C: Derivable Traits › `Hash` for Mapping a Value to a Value of Fixed Size\n\nThe `Hash` trait allows you to take an instance of a type of arbitrary size and\nmap that instance to a value of fixed size using a hash function. Deriving\n`Hash` implements the `hash` method. The derived implementation of the `hash`\nmethod combines the result of calling `hash` on each of the parts of the type,\nmeaning all fields or values must also implement `Hash` to derive `Hash`.\nAn example of when `Hash` is required is in storing keys in a `HashMap`\nto store data efficiently.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "C - Derivable Traits", "heading_path": ["Appendix C: Derivable Traits", "`Hash` for Mapping a Value to a Value of Fixed Size"], "path": "appendix-03-derivable-traits.md", "url": "https://doc.rust-lang.org/book/appendix-03-derivable-traits.html#hash-for-mapping-a-value-to-a-value-of-fixed-size", "has_code": false, "code_tags": []}} {"id": "book/appendix-03-derivable-traits.md#default-for-default-values-9", "text": "The Rust Programming Language › Appendix C: Derivable Traits › `Default` for Default Values\n\nThe `Default` trait allows you to create a default value for a type. Deriving\n`Default` implements the `default` function. The derived implementation of the\n`default` function calls the `default` function on each part of the type,\nmeaning all fields or values in the type must also implement `Default` to\nderive `Default`.\nThe `Default::default` function is commonly used in combination with the struct\nupdate syntax discussed in the “Creating Instances from Other Instances with\nStruct Update\nSyntax”\n section in Chapter 5. You can customize a few fields of a struct and\nthen set and use a default value for the rest of the fields by using\n`..Default::default()`.\nThe `Default` trait is required when you use the method `unwrap_or_default` on\n`Option` instances, for example. If the `Option` is `None`, the method\n`unwrap_or_default` will return the result of `Default::default` for the type\n`T` stored in the `Option`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "C - Derivable Traits", "heading_path": ["Appendix C: Derivable Traits", "`Default` for Default Values"], "path": "appendix-03-derivable-traits.md", "url": "https://doc.rust-lang.org/book/appendix-03-derivable-traits.html#default-for-default-values", "has_code": false, "code_tags": []}} {"id": "book/appendix-04-useful-development-tools.md#appendix-d-useful-development-tools-0", "text": "The Rust Programming Language › Appendix D: Useful Development Tools\n\nIn this appendix, we talk about some useful development tools that the Rust\nproject provides. We’ll look at automatic formatting, quick ways to apply\nwarning fixes, a linter, and integrating with IDEs.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "D - Useful Development Tools", "heading_path": ["Appendix D: Useful Development Tools"], "path": "appendix-04-useful-development-tools.md", "url": "https://doc.rust-lang.org/book/appendix-04-useful-development-tools.html#appendix-d-useful-development-tools", "has_code": false, "code_tags": []}} {"id": "book/appendix-04-useful-development-tools.md#automatic-formatting-with-rustfmt-1", "text": "The Rust Programming Language › Appendix D: Useful Development Tools › Automatic Formatting with `rustfmt`\n\nThe `rustfmt` tool reformats your code according to the community code style.\nMany collaborative projects use `rustfmt` to prevent arguments about which\nstyle to use when writing Rust: Everyone formats their code using the tool.\nRust installations include `rustfmt` by default, so you should already have the\nprograms `rustfmt` and `cargo-fmt` on your system. These two commands are\nanalogous to `rustc` and `cargo` in that `rustfmt` allows finer grained control\nand `cargo-fmt` understands conventions of a project that uses Cargo. To format\nany Cargo project, enter the following:\n```console\n$ cargo fmt\n```\nRunning this command reformats all the Rust code in the current crate. This\nshould only change the code style, not the code semantics. For more information\non `rustfmt`, see its documentation.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "D - Useful Development Tools", "heading_path": ["Appendix D: Useful Development Tools", "Automatic Formatting with `rustfmt`"], "path": "appendix-04-useful-development-tools.md", "url": "https://doc.rust-lang.org/book/appendix-04-useful-development-tools.html#automatic-formatting-with-rustfmt", "has_code": true, "code_tags": ["console"]}} {"id": "book/appendix-04-useful-development-tools.md#fix-your-code-with-rustfix-2", "text": "The Rust Programming Language › Appendix D: Useful Development Tools › Fix Your Code with `rustfix`\n\nThe `rustfix` tool is included with Rust installations and can automatically\nfix compiler warnings that have a clear way to correct the problem that’s\nlikely what you want. You’ve probably seen compiler warnings before. For\nexample, consider this code:\nFilename: src/main.rs\n```rust\nfn main() {\n let mut x = 42;\n println!(\"{x}\");\n}\n```\nHere, we’re defining the variable `x` as mutable, but we never actually mutate\nit. Rust warns us about that:\n```console\n$ cargo build\n Compiling myprogram v0.1.0 (file:///projects/myprogram)\nwarning: variable does not need to be mutable\n --> src/main.rs:2:9\n |\n2 | let mut x = 0;\n | ----^\n | |\n | help: remove this `mut`\n |\n = note: `#[warn(unused_mut)]` on by default\n```\nThe warning suggests that we remove the `mut` keyword. We can automatically\napply that suggestion using the `rustfix` tool by running the command `cargo\nfix`:\n```console\n$ cargo fix\n Checking myprogram v0.1.0 (file:///projects/myprogram)\n Fixing src/main.rs (1 fix)\n Finished dev [unoptimized + debuginfo] target(s) in 0.59s\n```\nWhen we look at _src/main.rs_ again, we’ll see that `cargo fix` has changed the\ncode:\nFilename: src/main.rs\n```rust\nfn main() {\n let x = 42;\n println!(\"{x}\");\n}\n```\nThe variable `x` is now immutable, and the warning no longer appears.\nYou can also use the `cargo fix` command to transition your code between\ndifferent Rust editions. Editions are covered in Appendix E\n.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "D - Useful Development Tools", "heading_path": ["Appendix D: Useful Development Tools", "Fix Your Code with `rustfix`"], "path": "appendix-04-useful-development-tools.md", "url": "https://doc.rust-lang.org/book/appendix-04-useful-development-tools.html#fix-your-code-with-rustfix", "has_code": true, "code_tags": ["console", "rust"]}} {"id": "book/appendix-04-useful-development-tools.md#more-lints-with-clippy-3", "text": "The Rust Programming Language › Appendix D: Useful Development Tools › More Lints with Clippy\n\nThe Clippy tool is a collection of lints to analyze your code so that you can\ncatch common mistakes and improve your Rust code. Clippy is included with\nstandard Rust installations.\nTo run Clippy’s lints on any Cargo project, enter the following:\n```console\n$ cargo clippy\n```\nFor example, say you write a program that uses an approximation of a\nmathematical constant, such as pi, as this program does:\nListing (src/main.rs)\n```rust\nfn main() {\n let x = 3.1415;\n let r = 8.0;\n println!(\"the area of the circle is {}\", x * r * r);\n}\n```\nRunning `cargo clippy` on this project results in this error:\n```text\nerror: approximate value of `f{32, 64}::consts::PI` found\n --> src/main.rs:2:13\n |\n2 | let x = 3.1415;\n | ^^^^^^\n |\n = note: `#[deny(clippy::approx_constant)]` on by default\n = help: consider using the constant directly\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#approx_constant\n```\nThis error lets you know that Rust already has a more precise `PI` constant\ndefined, and that your program would be more correct if you used the constant\ninstead. You would then change your code to use the `PI` constant.\nThe following code doesn’t result in any errors or warnings from Clippy:\nListing (src/main.rs)\n```rust\nfn main() {\n let x = std::f64::consts::PI;\n let r = 8.0;\n println!(\"the area of the circle is {}\", x * r * r);\n}\n```\nFor more information on Clippy, see its documentation.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "D - Useful Development Tools", "heading_path": ["Appendix D: Useful Development Tools", "More Lints with Clippy"], "path": "appendix-04-useful-development-tools.md", "url": "https://doc.rust-lang.org/book/appendix-04-useful-development-tools.html#more-lints-with-clippy", "has_code": true, "code_tags": ["console", "rust", "text"]}} {"id": "book/appendix-04-useful-development-tools.md#ide-integration-using-rust-analyzer-4", "text": "The Rust Programming Language › Appendix D: Useful Development Tools › IDE Integration Using `rust-analyzer`\n\nTo help with IDE integration, the Rust community recommends using\n`rust-analyzer`. This tool is a set of\ncompiler-centric utilities that speak Language Server Protocol\n, which is a specification for IDEs and programming languages to\ncommunicate with each other. Different clients can use `rust-analyzer`, such as\nthe Rust analyzer plug-in for Visual Studio Code.\nVisit the `rust-analyzer` project’s home page\nfor installation instructions, then install the language server support in your\nparticular IDE. Your IDE will gain capabilities such as autocompletion, jump to\ndefinition, and inline errors.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "D - Useful Development Tools", "heading_path": ["Appendix D: Useful Development Tools", "IDE Integration Using `rust-analyzer`"], "path": "appendix-04-useful-development-tools.md", "url": "https://doc.rust-lang.org/book/appendix-04-useful-development-tools.html#ide-integration-using-rust-analyzer", "has_code": false, "code_tags": []}} {"id": "book/appendix-05-editions.md#appendix-e-editions-0", "text": "The Rust Programming Language › Appendix E: Editions\n\nIn Chapter 1, you saw that `cargo new` adds a bit of metadata to your\n_Cargo.toml_ file about an edition. This appendix talks about what that means!\nThe Rust language and compiler have a six-week release cycle, meaning users get\na constant stream of new features. Other programming languages release larger\nchanges less often; Rust releases smaller updates more frequently. After a\nwhile, all of these tiny changes add up. But from release to release, it can be\ndifficult to look back and say, “Wow, between Rust 1.10 and Rust 1.31, Rust has\nchanged a lot!”\nEvery three years or so, the Rust team produces a new Rust _edition_. Each\nedition brings together the features that have landed into a clear package with\nfully updated documentation and tooling. New editions ship as part of the usual\nsix-week release process.\nEditions serve different purposes for different people:\n- For active Rust users, a new edition brings together incremental changes into\n an easy-to-understand package.\n- For non-users, a new edition signals that some major advancements have\n landed, which might make Rust worth another look.\n- For those developing Rust, a new edition provides a rallying point for the\n project as a whole.\nAt the time of this writing, four Rust editions are available: Rust 2015, Rust\n2018, Rust 2021, and Rust 2024. This book is written using Rust 2024 edition\nidioms.\nThe `edition` key in _Cargo.toml_ indicates which edition the compiler should\nuse for your code. If the key doesn’t exist, Rust uses `2015` as the edition\nvalue for backward compatibility reasons.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "E - Editions", "heading_path": ["Appendix E: Editions"], "path": "appendix-05-editions.md", "url": "https://doc.rust-lang.org/book/appendix-05-editions.html#appendix-e-editions", "has_code": false, "code_tags": []}} {"id": "book/appendix-05-editions.md#appendix-e-editions-1", "text": "The Rust Programming Language › Appendix E: Editions\n\nEach project can opt in to an edition other than the default 2015 edition.\nEditions can contain incompatible changes, such as including a new keyword that\nconflicts with identifiers in code. However, unless you opt in to those\nchanges, your code will continue to compile even as you upgrade the Rust\ncompiler version you use.\nAll Rust compiler versions support any edition that existed prior to that\ncompiler’s release, and they can link crates of any supported editions\ntogether. Edition changes only affect the way the compiler initially parses\ncode. Therefore, if you’re using Rust 2015 and one of your dependencies uses\nRust 2018, your project will compile and be able to use that dependency. The\nopposite situation, where your project uses Rust 2018 and a dependency uses\nRust 2015, works as well.\nTo be clear: Most features will be available on all editions. Developers using\nany Rust edition will continue to see improvements as new stable releases are\nmade. However, in some cases, mainly when new keywords are added, some new\nfeatures might only be available in later editions. You will need to switch\neditions if you want to take advantage of such features.\nFor more details, see _The Rust Edition Guide_. This is a\ncomplete book that enumerates the differences between editions and explains how\nto automatically upgrade your code to a new edition via `cargo fix`.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "E - Editions", "heading_path": ["Appendix E: Editions"], "path": "appendix-05-editions.md", "url": "https://doc.rust-lang.org/book/appendix-05-editions.html#appendix-e-editions", "has_code": false, "code_tags": []}} {"id": "book/appendix-06-translation.md#appendix-f-translations-of-the-book-0", "text": "The Rust Programming Language › Appendix F: Translations of the Book\n\nFor resources in languages other than English. Most are still in progress; see\nthe Translations label to help or let us know about a new translation!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "F - Translations of the Book", "heading_path": ["Appendix F: Translations of the Book"], "path": "appendix-06-translation.md", "url": "https://doc.rust-lang.org/book/appendix-06-translation.html#appendix-f-translations-of-the-book", "has_code": false, "code_tags": []}} {"id": "book/appendix-06-translation.md#appendix-f-translations-of-the-book-1", "text": "The Rust Programming Language › Appendix F: Translations of the Book\n\n- Português (BR)\n- Português (PT)\n- 简体中文: KaiserY/trpl-zh-cn, gnu4cn/rust-lang-Zh_CN\n- 正體中文\n- Українська\n- Español, alternate, Español por RustLangES\n- Русский\n- 한국어\n- 日本語\n- Français\n- Polski\n- Cebuano\n- Tagalog\n- Esperanto\n- ελληνική\n- Svenska\n- Farsi, Persian (FA)\n- Deutsch\n- हिंदी\n- ไทย\n- Danske\n- O'zbek\n- Tiếng Việt\n- Italiano\n- বাংলা", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "F - Translations of the Book", "heading_path": ["Appendix F: Translations of the Book"], "path": "appendix-06-translation.md", "url": "https://doc.rust-lang.org/book/appendix-06-translation.html#appendix-f-translations-of-the-book", "has_code": false, "code_tags": []}} {"id": "book/appendix-07-nightly-rust.md#appendix-g---how-rust-is-made-and-nightly-rust-0", "text": "The Rust Programming Language › Appendix G - How Rust is Made and “Nightly Rust”\n\nThis appendix is about how Rust is made and how that affects you as a Rust\ndeveloper.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "G - How Rust is Made and “Nightly Rust”", "heading_path": ["Appendix G - How Rust is Made and “Nightly Rust”"], "path": "appendix-07-nightly-rust.md", "url": "https://doc.rust-lang.org/book/appendix-07-nightly-rust.html#appendix-g---how-rust-is-made-and-nightly-rust", "has_code": false, "code_tags": []}} {"id": "book/appendix-07-nightly-rust.md#stability-without-stagnation-1", "text": "The Rust Programming Language › Appendix G - How Rust is Made and “Nightly Rust” › Stability Without Stagnation\n\nAs a language, Rust cares a _lot_ about the stability of your code. We want\nRust to be a rock-solid foundation you can build on, and if things were\nconstantly changing, that would be impossible. At the same time, if we can’t\nexperiment with new features, we may not find out important flaws until after\ntheir release, when we can no longer change things.\nOur solution to this problem is what we call “stability without stagnation”,\nand our guiding principle is this: you should never have to fear upgrading to a\nnew version of stable Rust. Each upgrade should be painless, but should also\nbring you new features, fewer bugs, and faster compile times.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "G - How Rust is Made and “Nightly Rust”", "heading_path": ["Appendix G - How Rust is Made and “Nightly Rust”", "Stability Without Stagnation"], "path": "appendix-07-nightly-rust.md", "url": "https://doc.rust-lang.org/book/appendix-07-nightly-rust.html#stability-without-stagnation", "has_code": false, "code_tags": []}} {"id": "book/appendix-07-nightly-rust.md#choo-choo-release-channels-and-riding-the-trains-2", "text": "The Rust Programming Language › Appendix G - How Rust is Made and “Nightly Rust” › Choo, Choo! Release Channels and Riding the Trains\n\nRust development operates on a _train schedule_. That is, all development is\ndone in the main branch of the Rust repository. Releases follow a software\nrelease train model, which has been used by Cisco IOS and other software\nprojects. There are three _release channels_ for Rust:\n- Nightly\n- Beta\n- Stable\nMost Rust developers primarily use the stable channel, but those who want to\ntry out experimental new features may use nightly or beta.\nHere’s an example of how the development and release process works: let’s\nassume that the Rust team is working on the release of Rust 1.5. That release\nhappened in December of 2015, but it will provide us with realistic version\nnumbers. A new feature is added to Rust: a new commit lands on the main\nbranch. Each night, a new nightly version of Rust is produced. Every day is a\nrelease day, and these releases are created by our release infrastructure\nautomatically. So as time passes, our releases look like this, once a night:\n```text\nnightly: * - - * - - *\n```\nEvery six weeks, it’s time to prepare a new release! The `beta` branch of the\nRust repository branches off from the main branch used by nightly. Now,\nthere are two releases:\n```text\nnightly: * - - * - - *\n |\nbeta: *\n```\nMost Rust users do not use beta releases actively, but test against beta in\ntheir CI system to help Rust discover possible regressions. In the meantime,\nthere’s still a nightly release every night:\n```text\nnightly: * - - * - - * - - * - - *\n |\nbeta: *\n```", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "G - How Rust is Made and “Nightly Rust”", "heading_path": ["Appendix G - How Rust is Made and “Nightly Rust”", "Choo, Choo! Release Channels and Riding the Trains"], "path": "appendix-07-nightly-rust.md", "url": "https://doc.rust-lang.org/book/appendix-07-nightly-rust.html#choo-choo-release-channels-and-riding-the-trains", "has_code": true, "code_tags": ["text"]}} {"id": "book/appendix-07-nightly-rust.md#choo-choo-release-channels-and-riding-the-trains-3", "text": "The Rust Programming Language › Appendix G - How Rust is Made and “Nightly Rust” › Choo, Choo! Release Channels and Riding the Trains\n\nLet’s say a regression is found. Good thing we had some time to test the beta\nrelease before the regression snuck into a stable release! The fix is applied\nto the main branch, so that nightly is fixed, and then the fix is backported to\nthe `beta` branch, and a new release of beta is produced:\n```text\nnightly: * - - * - - * - - * - - * - - *\n |\nbeta: * - - - - - - - - *\n```\nSix weeks after the first beta was created, it’s time for a stable release! The\n`stable` branch is produced from the `beta` branch:\n```text\nnightly: * - - * - - * - - * - - * - - * - * - *\n |\nbeta: * - - - - - - - - *\n |\nstable: *\n```\nHooray! Rust 1.5 is done! However, we’ve forgotten one thing: because the six\nweeks have gone by, we also need a new beta of the _next_ version of Rust, 1.6.\nSo after `stable` branches off of `beta`, the next version of `beta` branches\noff of `nightly` again:\n```text\nnightly: * - - * - - * - - * - - * - - * - * - *\n | |\nbeta: * - - - - - - - - * *\n |\nstable: *\n```\nThis is called the “train model” because every six weeks, a release “leaves the\nstation”, but still has to take a journey through the beta channel before it\narrives as a stable release.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "G - How Rust is Made and “Nightly Rust”", "heading_path": ["Appendix G - How Rust is Made and “Nightly Rust”", "Choo, Choo! Release Channels and Riding the Trains"], "path": "appendix-07-nightly-rust.md", "url": "https://doc.rust-lang.org/book/appendix-07-nightly-rust.html#choo-choo-release-channels-and-riding-the-trains", "has_code": true, "code_tags": ["text"]}} {"id": "book/appendix-07-nightly-rust.md#choo-choo-release-channels-and-riding-the-trains-4", "text": "The Rust Programming Language › Appendix G - How Rust is Made and “Nightly Rust” › Choo, Choo! Release Channels and Riding the Trains\n\nRust releases every six weeks, like clockwork. If you know the date of one Rust\nrelease, you can know the date of the next one: it’s six weeks later. A nice\naspect of having releases scheduled every six weeks is that the next train is\ncoming soon. If a feature happens to miss a particular release, there’s no need\nto worry: another one is happening in a short time! This helps reduce pressure\nto sneak possibly unpolished features in close to the release deadline.\nThanks to this process, you can always check out the next build of Rust and\nverify for yourself that it’s easy to upgrade to: if a beta release doesn’t\nwork as expected, you can report it to the team and get it fixed before the\nnext stable release happens! Breakage in a beta release is relatively rare, but\n`rustc` is still a piece of software, and bugs do exist.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "G - How Rust is Made and “Nightly Rust”", "heading_path": ["Appendix G - How Rust is Made and “Nightly Rust”", "Choo, Choo! Release Channels and Riding the Trains"], "path": "appendix-07-nightly-rust.md", "url": "https://doc.rust-lang.org/book/appendix-07-nightly-rust.html#choo-choo-release-channels-and-riding-the-trains", "has_code": false, "code_tags": []}} {"id": "book/appendix-07-nightly-rust.md#maintenance-time-5", "text": "The Rust Programming Language › Appendix G - How Rust is Made and “Nightly Rust” › Maintenance time\n\nThe Rust project supports the most recent stable version. When a new stable\nversion is released, the old version reaches its end of life (EOL). This means\neach version is supported for six weeks.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "G - How Rust is Made and “Nightly Rust”", "heading_path": ["Appendix G - How Rust is Made and “Nightly Rust”", "Maintenance time"], "path": "appendix-07-nightly-rust.md", "url": "https://doc.rust-lang.org/book/appendix-07-nightly-rust.html#maintenance-time", "has_code": false, "code_tags": []}} {"id": "book/appendix-07-nightly-rust.md#unstable-features-6", "text": "The Rust Programming Language › Appendix G - How Rust is Made and “Nightly Rust” › Unstable Features\n\nThere’s one more catch with this release model: unstable features. Rust uses a\ntechnique called “feature flags” to determine what features are enabled in a\ngiven release. If a new feature is under active development, it lands on the\nmain branch, and therefore, in nightly, but behind a _feature flag_. If you, as\na user, wish to try out the work-in-progress feature, you can, but you must be\nusing a nightly release of Rust and annotate your source code with the\nappropriate flag to opt in.\nIf you’re using a beta or stable release of Rust, you can’t use any feature\nflags. This is the key that allows us to get practical use with new features\nbefore we declare them stable forever. Those who wish to opt into the bleeding\nedge can do so, and those who want a rock-solid experience can stick with\nstable and know that their code won’t break. Stability without stagnation.\nThis book only contains information about stable features, as in-progress\nfeatures are still changing, and surely they’ll be different between when this\nbook was written and when they get enabled in stable builds. You can find\ndocumentation for nightly-only features online.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "G - How Rust is Made and “Nightly Rust”", "heading_path": ["Appendix G - How Rust is Made and “Nightly Rust”", "Unstable Features"], "path": "appendix-07-nightly-rust.md", "url": "https://doc.rust-lang.org/book/appendix-07-nightly-rust.html#unstable-features", "has_code": false, "code_tags": []}} {"id": "book/appendix-07-nightly-rust.md#rustup-and-the-role-of-rust-nightly-7", "text": "The Rust Programming Language › Appendix G - How Rust is Made and “Nightly Rust” › Rustup and the Role of Rust Nightly\n\nRustup makes it easy to change between different release channels of Rust, on a\nglobal or per-project basis. By default, you’ll have stable Rust installed. To\ninstall nightly, for example:\n```console\n$ rustup toolchain install nightly\n```\nYou can see all of the _toolchains_ (releases of Rust and associated\ncomponents) you have installed with `rustup` as well. Here’s an example on one\nof your authors’ Windows computer:\n```powershell\nrustup toolchain list\nstable-x86_64-pc-windows-msvc (default)\nbeta-x86_64-pc-windows-msvc\nnightly-x86_64-pc-windows-msvc\n```\nAs you can see, the stable toolchain is the default. Most Rust users use stable\nmost of the time. You might want to use stable most of the time, but use\nnightly on a specific project, because you care about a cutting-edge feature.\nTo do so, you can use `rustup override` in that project’s directory to set the\nnightly toolchain as the one `rustup` should use when you’re in that directory:\n```console\n$ cd ~/projects/needs-nightly\n$ rustup override set nightly\n```\nNow, every time you call `rustc` or `cargo` inside of\n_~/projects/needs-nightly_, `rustup` will make sure that you are using nightly\nRust, rather than your default of stable Rust. This comes in handy when you\nhave a lot of Rust projects!", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "G - How Rust is Made and “Nightly Rust”", "heading_path": ["Appendix G - How Rust is Made and “Nightly Rust”", "Rustup and the Role of Rust Nightly"], "path": "appendix-07-nightly-rust.md", "url": "https://doc.rust-lang.org/book/appendix-07-nightly-rust.html#rustup-and-the-role-of-rust-nightly", "has_code": true, "code_tags": ["console", "powershell"]}} {"id": "book/appendix-07-nightly-rust.md#the-rfc-process-and-teams-8", "text": "The Rust Programming Language › Appendix G - How Rust is Made and “Nightly Rust” › The RFC Process and Teams\n\nSo how do you learn about these new features? Rust’s development model follows\na _Request For Comments (RFC) process_. If you’d like an improvement in Rust,\nyou can write up a proposal, called an RFC.\nAnyone can write RFCs to improve Rust, and the proposals are reviewed and\ndiscussed by the Rust team, which is comprised of many topic subteams. There’s\na full list of the teams on Rust’s website, which includes teams for\neach area of the project: language design, compiler implementation,\ninfrastructure, documentation, and more. The appropriate team reads the\nproposal and the comments, writes some comments of their own, and eventually,\nthere’s consensus to accept or reject the feature.\nIf the feature is accepted, an issue is opened on the Rust repository, and\nsomeone can implement it. The person who implements it very well may not be the\nperson who proposed the feature in the first place! When the implementation is\nready, it lands on the main branch behind a feature gate, as we discussed in\nthe “Unstable Features” section.\nAfter some time, once Rust developers who use nightly releases have been able\nto try out the new feature, team members will discuss the feature, how it’s\nworked out on nightly, and decide if it should make it into stable Rust or not.\nIf the decision is to move forward, the feature gate is removed, and the\nfeature is now considered stable! It rides the trains into a new stable release\nof Rust.", "metadata": {"book": "book", "book_title": "The Rust Programming Language", "part": "The Rust Programming Language", "chapter": "G - How Rust is Made and “Nightly Rust”", "heading_path": ["Appendix G - How Rust is Made and “Nightly Rust”", "The RFC Process and Teams"], "path": "appendix-07-nightly-rust.md", "url": "https://doc.rust-lang.org/book/appendix-07-nightly-rust.html#the-rfc-process-and-teams", "has_code": false, "code_tags": []}} {"id": "nomicon/intro.md#the-rustonomicon-0", "text": "The Rustonomicon › The Rustonomicon\n\n
\nWarning:\nThis book is incomplete.\nDocumenting everything and rewriting outdated parts take a while.\nSee the [issue tracker] to check what's missing/outdated, and if there are any mistakes or ideas that haven't been reported, feel free to open a new issue there.\n
", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Introduction", "heading_path": ["The Rustonomicon"], "path": "intro.md", "url": "https://doc.rust-lang.org/nomicon/intro.html#the-rustonomicon", "has_code": false, "code_tags": []}} {"id": "nomicon/intro.md#the-dark-arts-of-unsafe-rust-1", "text": "The Rustonomicon › The Rustonomicon › The Dark Arts of Unsafe Rust\n\nTHE KNOWLEDGE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF UNLEASHING INDESCRIBABLE HORRORS THAT SHATTER YOUR PSYCHE AND SET YOUR MIND ADRIFT IN THE UNKNOWABLY INFINITE COSMOS.\nThe Rustonomicon digs into all the awful details that you need to understand when writing Unsafe Rust programs.\nShould you wish a long and happy career of writing Rust programs, you should turn back now and forget you ever saw this book.\nIt is not necessary.\nHowever if you intend to write unsafe code — or just want to dig into the guts of the language — this book contains lots of useful information.\nUnlike *The Rust Programming Language*, we will be assuming considerable prior knowledge.\nIn particular, you should be comfortable with basic systems programming and Rust.\nIf you don't feel comfortable with these topics, you should consider reading The Book first.\nThat said, we won't assume you have read it, and we will take care to occasionally give a refresher on the basics where appropriate.\nYou can skip straight to this book if you want; just know that we won't be explaining everything from the ground up.\nThis book exists primarily as a high-level companion to The Reference.\nWhere The Reference exists to detail the syntax and semantics of every part of the language, The Rustonomicon exists to describe how to use those pieces together, and the issues that you will have in doing so.\nThe Reference will tell you the syntax and semantics of references, destructors, and unwinding, but it won't tell you how combining them can lead to exception-safety issues, or how to deal with those issues.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Introduction", "heading_path": ["The Rustonomicon", "The Dark Arts of Unsafe Rust"], "path": "intro.md", "url": "https://doc.rust-lang.org/nomicon/intro.html#the-dark-arts-of-unsafe-rust", "has_code": false, "code_tags": []}} {"id": "nomicon/intro.md#the-dark-arts-of-unsafe-rust-2", "text": "The Rustonomicon › The Rustonomicon › The Dark Arts of Unsafe Rust\n\nIt should be noted that we haven't synced The Rustnomicon and The Reference well, so they may have duplicate content.\nIn general, if the two documents disagree, The Reference should be assumed to be correct (it isn't yet considered normative, it's just better maintained).\nTopics that are within the scope of this book include: the meaning of (un)safety, unsafe primitives provided by the language and standard library, techniques for creating safe abstractions with those unsafe primitives, subtyping and variance, exception-safety (panic/unwind-safety), working with uninitialized memory, type punning, concurrency, interoperating with other languages (FFI), optimization tricks, how constructs lower to compiler/OS/hardware primitives, how to **not** make the memory model people angry, how you're **going** to make the memory model people angry, and more.\nThe Rustonomicon is not a place to exhaustively describe the semantics and guarantees of every single API in the standard library, nor is it a place to exhaustively describe every feature of Rust.\nUnless otherwise noted, Rust code in this book uses the Rust 2024 edition.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Introduction", "heading_path": ["The Rustonomicon", "The Dark Arts of Unsafe Rust"], "path": "intro.md", "url": "https://doc.rust-lang.org/nomicon/intro.html#the-dark-arts-of-unsafe-rust", "has_code": false, "code_tags": []}} {"id": "nomicon/meet-safe-and-unsafe.md#meet-safe-and-unsafe-0", "text": "The Rustonomicon › Meet Safe and Unsafe\n\nsafe and unsafe\nIt would be great to not have to worry about low-level implementation details.\nWho could possibly care how much space the empty tuple occupies? Sadly, it\nsometimes matters and we need to worry about it. The most common reason\ndevelopers start to care about implementation details is performance, but more\nimportantly, these details can become a matter of correctness when interfacing\ndirectly with hardware, operating systems, or other languages.\nWhen implementation details start to matter in a safe programming language,\nprogrammers usually have three options:\n* fiddle with the code to encourage the compiler/runtime to perform an optimization\n* adopt a more unidiomatic or cumbersome design to get the desired implementation\n* rewrite the implementation in a language that lets you deal with those details\nFor that last option, the language programmers tend to use is *C*. This is often\nnecessary to interface with systems that only declare a C interface.\nUnfortunately, C is incredibly unsafe to use (sometimes for good reason),\nand this unsafety is magnified when trying to interoperate with another\nlanguage. Care must be taken to ensure C and the other language agree on\nwhat's happening, and that they don't step on each other's toes.\nSo what does this have to do with Rust?\nWell, unlike C, Rust is a safe programming language.\nBut, like C, Rust is an unsafe programming language.\nMore accurately, Rust *contains* both a safe and unsafe programming language.\nRust can be thought of as a combination of two programming languages: *Safe\nRust* and *Unsafe Rust*. Conveniently, these names mean exactly what they say:\nSafe Rust is Safe. Unsafe Rust is, well, not. In fact, Unsafe Rust lets us\ndo some *really* unsafe things. Things the Rust authors will implore you not to\ndo, but we'll do anyway.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Meet Safe and Unsafe", "heading_path": ["Meet Safe and Unsafe"], "path": "meet-safe-and-unsafe.md", "url": "https://doc.rust-lang.org/nomicon/meet-safe-and-unsafe.html#meet-safe-and-unsafe", "has_code": false, "code_tags": []}} {"id": "nomicon/meet-safe-and-unsafe.md#meet-safe-and-unsafe-1", "text": "The Rustonomicon › Meet Safe and Unsafe\n\nSafe Rust is the *true* Rust programming language. If all you do is write Safe\nRust, you will never have to worry about type-safety or memory-safety. You will\nnever endure a dangling pointer, a use-after-free, or any other kind of\nUndefined Behavior (a.k.a. UB).\nThe standard library also gives you enough utilities out of the box that you'll\nbe able to write high-performance applications and libraries in pure idiomatic\nSafe Rust.\nBut maybe you want to talk to another language. Maybe you're writing a\nlow-level abstraction not exposed by the standard library. Maybe you're\n*writing* the standard library (which is written entirely in Rust). Maybe you\nneed to do something the type-system doesn't understand and just *frob some dang\nbits*. Maybe you need Unsafe Rust.\nUnsafe Rust is exactly like Safe Rust with all the same rules and semantics.\nIt just lets you do some *extra* things that are Definitely Not Safe\n(which we will define in the next section).\nThe value of this separation is that we gain the benefits of using an unsafe\nlanguage like C — low level control over implementation details — without most\nof the problems that come with trying to integrate it with a completely\ndifferent safe language.\nThere are still some problems — most notably, we must become aware of properties\nthat the type system assumes and audit them in any code that interacts with\nUnsafe Rust. That's the purpose of this book: to teach you about these assumptions\nand how to manage them.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Meet Safe and Unsafe", "heading_path": ["Meet Safe and Unsafe"], "path": "meet-safe-and-unsafe.md", "url": "https://doc.rust-lang.org/nomicon/meet-safe-and-unsafe.html#meet-safe-and-unsafe", "has_code": false, "code_tags": []}} {"id": "nomicon/safe-unsafe-meaning.md#how-safe-and-unsafe-interact-0", "text": "The Rustonomicon › How Safe and Unsafe Interact\n\nWhat's the relationship between Safe Rust and Unsafe Rust? How do they\ninteract?\nThe separation between Safe Rust and Unsafe Rust is controlled with the\n`unsafe` keyword, which acts as an interface from one to the other. This is\nwhy we can say Safe Rust is a safe language: all the unsafe parts are kept\nexclusively behind the `unsafe` boundary. If you wish, you can even toss\n`#![forbid(unsafe_code)]` into your code base to statically guarantee that\nyou're only writing Safe Rust.\nThe `unsafe` keyword has two uses: to declare the existence of contracts the\ncompiler can't check, and to declare that a programmer has checked that these\ncontracts have been upheld.\nYou can use `unsafe` to indicate the existence of unchecked contracts on\n_functions_ and _trait declarations_. On functions, `unsafe` means that\nusers of the function must check that function's documentation to ensure\nthey are using it in a way that maintains the contracts the function\nrequires. On trait declarations, `unsafe` means that implementors of the\ntrait must check the trait documentation to ensure their implementation\nmaintains the contracts the trait requires.\nYou can use `unsafe` on a block to declare that all unsafe actions performed\nwithin are verified to uphold the contracts of those operations. For instance,\nthe index passed to `slice::get_unchecked` is in-bounds.\nYou can use `unsafe` on a trait implementation to declare that the implementation\nupholds the trait's contract. For instance, that a type implementing [`Send`] is\nreally safe to move to another thread.\nThe standard library has a number of unsafe functions, including:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "How Safe and Unsafe Interact", "heading_path": ["How Safe and Unsafe Interact"], "path": "safe-unsafe-meaning.md", "url": "https://doc.rust-lang.org/nomicon/safe-unsafe-meaning.html#how-safe-and-unsafe-interact", "has_code": false, "code_tags": []}} {"id": "nomicon/safe-unsafe-meaning.md#how-safe-and-unsafe-interact-1", "text": "The Rustonomicon › How Safe and Unsafe Interact\n\n* `slice::get_unchecked`, which performs unchecked indexing,\n allowing memory safety to be freely violated.\n* `mem::transmute` reinterprets some value as having a given type,\n bypassing type safety in arbitrary ways (see [conversions] for details).\n* Every raw pointer to a sized type has an `offset` method that\n invokes Undefined Behavior if the passed offset is not \"in bounds\".\n* All FFI (Foreign Function Interface) functions are `unsafe` to call because the\n other language can do arbitrary operations that the Rust compiler can't check.\nAs of Rust 1.29.2, the standard library defines the following unsafe traits\n(there are others, but they are not stabilized yet and some of them may never\nbe):\n* [`Send`] is a marker trait (a trait with no API) that promises implementors\n are safe to send (move) to another thread.\n* [`Sync`] is a marker trait that promises threads can safely share implementors\n through a shared reference.\n* [`GlobalAlloc`] allows customizing the memory allocator of the whole program.\nMuch of the Rust standard library also uses Unsafe Rust internally. These\nimplementations have generally been rigorously manually checked, so the Safe Rust\ninterfaces built on top of these implementations can be assumed to be safe.\nThe need for all of this separation boils down to a single fundamental property\nof Safe Rust, the *soundness property*:\n**No matter what, Safe Rust clients can't cause Undefined Behavior.**\nThe design of the safe/unsafe split means that there is an asymmetric trust\nrelationship between Safe and Unsafe Rust. Safe Rust inherently has to\ntrust that any Unsafe Rust it touches has been written correctly.\nOn the other hand, Unsafe Rust cannot trust Safe Rust without care. It can\ntrust Safe Rust it is a client of, but it cannot trust Safe Rust chosen or\nsupplied by its clients.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "How Safe and Unsafe Interact", "heading_path": ["How Safe and Unsafe Interact"], "path": "safe-unsafe-meaning.md", "url": "https://doc.rust-lang.org/nomicon/safe-unsafe-meaning.html#how-safe-and-unsafe-interact", "has_code": false, "code_tags": []}} {"id": "nomicon/safe-unsafe-meaning.md#how-safe-and-unsafe-interact-2", "text": "The Rustonomicon › How Safe and Unsafe Interact\n\nAs an example, Rust has the [`PartialOrd`] and [`Ord`] traits to differentiate\nbetween types which can \"just\" be compared, and those that provide a \"total\"\nordering (which basically means that comparison behaves reasonably).\n[`BTreeMap`] doesn't really make sense for partially-ordered types, and so it\nrequires that its keys implement `Ord`. However, `BTreeMap` has Unsafe Rust code\ninside of its implementation. Because it would be unacceptable for a sloppy `Ord`\nimplementation (which is Safe to write) to cause Undefined Behavior, the Unsafe\ncode in BTreeMap must be written to be robust against `Ord` implementations which\naren't actually total — even though that's the whole point of requiring `Ord`.\nThe Unsafe Rust code just can't trust the Safe Rust code to be written correctly.\nThat said, `BTreeMap` will still behave completely erratically if you feed in\nvalues that don't have a total ordering. It just won't ever cause Undefined\nBehavior.\nOne may wonder, if `BTreeMap` cannot trust `Ord` because it's Safe, why can it\ntrust *any* Safe code? For instance `BTreeMap` relies on integers and slices to\nbe implemented correctly. Those are safe too, right?\nThe difference is one of scope. When `BTreeMap` relies on integers and slices,\nit's relying on one very specific implementation. This is a measured risk that\ncan be weighed against the benefit. In this case there's basically zero risk;\nif integers and slices are broken, *everyone* is broken. Also, they're maintained\nby the same people who maintain `BTreeMap`, so it's easy to keep tabs on them.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "How Safe and Unsafe Interact", "heading_path": ["How Safe and Unsafe Interact"], "path": "safe-unsafe-meaning.md", "url": "https://doc.rust-lang.org/nomicon/safe-unsafe-meaning.html#how-safe-and-unsafe-interact", "has_code": false, "code_tags": []}} {"id": "nomicon/safe-unsafe-meaning.md#how-safe-and-unsafe-interact-3", "text": "The Rustonomicon › How Safe and Unsafe Interact\n\nThe same can be true across crate boundaries. Say crate `foo` depends on crate\n`bar`, then Unsafe Rust in crate `foo` may trust Safe Rust in crate `bar`. This\nis because crate `foo` chose to depend on crate `bar`, and by doing so trusted\ncrate `bar` to be implemented correctly.\nOn the other hand, `BTreeMap`'s key type is generic. Trusting its `Ord`\nimplementation means trusting the `Ord` implementation of arbitrary clients.\nHere the risk is high: someone somewhere is going to make a mistake and mess up\ntheir `Ord` implementation, or even just straight up lie about providing a total\nordering because \"it seems to work\". When that happens, `BTreeMap` needs to be\nprepared.\nThe same logic applies to trusting a closure that's passed to you to behave\ncorrectly.\nThis problem of unbounded generic trust is the problem that `unsafe` traits\nexist to resolve. The `BTreeMap` type could theoretically require that keys\nimplement a new trait called `UnsafeOrd`, rather than `Ord`, that might look\nlike this:\n```rust\nuse std::cmp::Ordering;\n\nunsafe trait UnsafeOrd {\n fn cmp(&self, other: &Self) -> Ordering;\n}\n```\nThen, a type would use `unsafe` to implement `UnsafeOrd`, indicating that\nthey've ensured their implementation maintains whatever contracts the\ntrait expects. In this situation, the Unsafe Rust in the internals of\n`BTreeMap` would be justified in trusting that the key type's `UnsafeOrd`\nimplementation is correct. If it isn't, it's the fault of the unsafe trait\nimplementation, which is consistent with Rust's safety guarantees.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "How Safe and Unsafe Interact", "heading_path": ["How Safe and Unsafe Interact"], "path": "safe-unsafe-meaning.md", "url": "https://doc.rust-lang.org/nomicon/safe-unsafe-meaning.html#how-safe-and-unsafe-interact", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/safe-unsafe-meaning.md#how-safe-and-unsafe-interact-4", "text": "The Rustonomicon › How Safe and Unsafe Interact\n\nThe decision of whether to mark a trait `unsafe` is an API design choice. A\nsafe trait is easier to implement, but any unsafe code that relies on it must\ndefend against incorrect behavior. Marking a trait `unsafe` shifts this\nresponsibility to the implementor. Rust has traditionally avoided marking\ntraits `unsafe` because it makes Unsafe Rust pervasive, which isn't desirable.\n`Send` and `Sync` are marked unsafe because thread safety is a *fundamental\nproperty* that unsafe code can't possibly hope to defend against in the way it\ncould defend against a buggy `Ord` implementation. Similarly, `GlobalAlloc`\nis keeping accounts of all the memory in the program and other things like\n`Box` or `Vec` that build on top of it. If it does something weird (giving the same\nchunk of memory to another request when it is still in use), there's no chance\nto detect that and do anything about it.\nThe decision of whether to mark your own traits `unsafe` depends on the same\nsort of consideration. If `unsafe` code can't reasonably expect to defend\nagainst a broken implementation of the trait, then marking the trait `unsafe` is\na reasonable choice.\nAs an aside, while `Send` and `Sync` are `unsafe` traits, they are *also*\nautomatically implemented for types when such derivations are provably safe\nto do. `Send` is automatically derived for all types composed only of values\nwhose types also implement `Send`. `Sync` is automatically derived for all\ntypes composed only of values whose types also implement `Sync`. This minimizes\nthe pervasive unsafety of making these two traits `unsafe`. And not many people\nare going to *implement* memory allocators (or use them directly, for that\nmatter).", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "How Safe and Unsafe Interact", "heading_path": ["How Safe and Unsafe Interact"], "path": "safe-unsafe-meaning.md", "url": "https://doc.rust-lang.org/nomicon/safe-unsafe-meaning.html#how-safe-and-unsafe-interact", "has_code": false, "code_tags": []}} {"id": "nomicon/safe-unsafe-meaning.md#how-safe-and-unsafe-interact-5", "text": "The Rustonomicon › How Safe and Unsafe Interact\n\nThis is the balance between Safe and Unsafe Rust. The separation is designed to\nmake using Safe Rust as ergonomic as possible, but requires extra effort and\ncare when writing Unsafe Rust. The rest of this book is largely a discussion\nof the sort of care that must be taken, and what contracts Unsafe Rust must uphold.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "How Safe and Unsafe Interact", "heading_path": ["How Safe and Unsafe Interact"], "path": "safe-unsafe-meaning.md", "url": "https://doc.rust-lang.org/nomicon/safe-unsafe-meaning.html#how-safe-and-unsafe-interact", "has_code": false, "code_tags": []}} {"id": "nomicon/what-unsafe-does.md#what-unsafe-rust-can-do-0", "text": "The Rustonomicon › What Unsafe Rust Can Do\n\nThe only things that are different in Unsafe Rust are that you can:\n* Dereference raw pointers\n* Call `unsafe` functions (including C functions, compiler intrinsics, and the raw allocator)\n* Implement `unsafe` traits\n* Access or modify mutable statics\n* Access fields of `union`s\nThat's it. The reason these operations are relegated to Unsafe is that misusing\nany of these things will cause the ever dreaded Undefined Behavior. Invoking\nUndefined Behavior gives the compiler full rights to do arbitrarily bad things\nto your program. You definitely *should not* invoke Undefined Behavior.\nUnlike C, Undefined Behavior is pretty limited in scope in Rust. All the core\nlanguage cares about is preventing the following things:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "What Unsafe Can Do", "heading_path": ["What Unsafe Rust Can Do"], "path": "what-unsafe-does.md", "url": "https://doc.rust-lang.org/nomicon/what-unsafe-does.html#what-unsafe-rust-can-do", "has_code": false, "code_tags": []}} {"id": "nomicon/what-unsafe-does.md#what-unsafe-rust-can-do-1", "text": "The Rustonomicon › What Unsafe Rust Can Do\n\n* Dereferencing (using the `*` operator on) dangling or unaligned pointers (see below)\n* Breaking the pointer aliasing rules\n* Calling a function with the wrong call ABI or unwinding from a function with the wrong unwind ABI.\n* Causing a data race\n* Executing code compiled with target features that the current thread of execution does\n not support\n* Producing invalid values (either alone or as a field of a compound type such\n as `enum`/`struct`/array/tuple):\n * a `bool` that isn't 0 or 1\n * an `enum` with an invalid discriminant\n * a null `fn` pointer\n * a `char` outside the ranges [0x0, 0xD7FF] and [0xE000, 0x10FFFF]\n * a `!` (all values are invalid for this type)\n * an integer (`i*`/`u*`), floating point value (`f*`), or raw pointer read from\n uninitialized memory, or uninitialized memory in a `str`.\n * a reference/`Box` that is dangling, unaligned, or points to an invalid value.\n * a wide reference, `Box`, or raw pointer that has invalid metadata:\n * `dyn Trait` metadata is invalid if it is not a pointer to a vtable for\n `Trait` that matches the actual dynamic trait the pointer or reference points to\n * slice metadata is invalid if the length is not a valid `usize`\n (i.e., it must not be read from uninitialized memory)\n * a type with custom invalid values that is one of those values, such as a\n [`NonNull`] that is null. (Requesting custom invalid values is an unstable\n feature, but some stable libstd types, like `NonNull`, make use of it.)", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "What Unsafe Can Do", "heading_path": ["What Unsafe Rust Can Do"], "path": "what-unsafe-does.md", "url": "https://doc.rust-lang.org/nomicon/what-unsafe-does.html#what-unsafe-rust-can-do", "has_code": false, "code_tags": []}} {"id": "nomicon/what-unsafe-does.md#what-unsafe-rust-can-do-2", "text": "The Rustonomicon › What Unsafe Rust Can Do\n\nFor a more detailed explanation about \"Undefined Behavior\", you may refer to\nthe reference.\n\"Producing\" a value happens any time a value is assigned, passed to a\nfunction/primitive operation or returned from a function/primitive operation.\nA reference/pointer is \"dangling\" if it is null or not all of the bytes it\npoints to are part of the same allocation (so in particular they all have to be\npart of *some* allocation). The span of bytes it points to is determined by the\npointer value and the size of the pointee type. As a consequence, if the span is\nempty, \"dangling\" is the same as \"null\". Note that slices and strings point\nto their entire range, so it's important that the length metadata is never too\nlarge (in particular, allocations and therefore slices and strings cannot be\nbigger than `isize::MAX` bytes). If for some reason this is too cumbersome,\nconsider using raw pointers.\nThat's it. That's all the causes of Undefined Behavior baked into Rust. Of\ncourse, unsafe functions and traits are free to declare arbitrary other\nconstraints that a program must maintain to avoid Undefined Behavior. For\ninstance, the allocator APIs declare that deallocating unallocated memory is\nUndefined Behavior.\nHowever, violations of these constraints generally will just transitively lead to one of\nthe above problems. Some additional constraints may also derive from compiler\nintrinsics that make special assumptions about how code can be optimized. For instance,\nVec and Box make use of intrinsics that require their pointers to be non-null at all times.\nRust is otherwise quite permissive with respect to other dubious operations.\nRust considers it \"safe\" to:\n* Deadlock\n* Have a race condition\n* Leak memory\n* Overflow integers (with the built-in operators such as `+` etc.)\n* Abort the program\n* Delete the production database", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "What Unsafe Can Do", "heading_path": ["What Unsafe Rust Can Do"], "path": "what-unsafe-does.md", "url": "https://doc.rust-lang.org/nomicon/what-unsafe-does.html#what-unsafe-rust-can-do", "has_code": false, "code_tags": []}} {"id": "nomicon/what-unsafe-does.md#what-unsafe-rust-can-do-3", "text": "The Rustonomicon › What Unsafe Rust Can Do\n\nFor more detailed information, you may refer to the reference.\nHowever any program that actually manages to do such a thing is *probably*\nincorrect. Rust provides lots of tools to make these things rare, but\nthese problems are considered impractical to categorically prevent.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "What Unsafe Can Do", "heading_path": ["What Unsafe Rust Can Do"], "path": "what-unsafe-does.md", "url": "https://doc.rust-lang.org/nomicon/what-unsafe-does.html#what-unsafe-rust-can-do", "has_code": false, "code_tags": []}} {"id": "nomicon/working-with-unsafe.md#working-with-unsafe-0", "text": "The Rustonomicon › Working with Unsafe\n\nRust generally only gives us the tools to talk about Unsafe Rust in a scoped and\nbinary manner. Unfortunately, reality is significantly more complicated than\nthat. For instance, consider the following toy function:\n```rust\nfn index(idx: usize, arr: &[u8]) -> Option {\n if idx < arr.len() {\n unsafe {\n Some(*arr.get_unchecked(idx))\n }\n } else {\n None\n }\n}\n```\nThis function is safe and correct. We check that the index is in bounds, and if\nit is, index into the array in an unchecked manner. We say that such a correct\nunsafely implemented function is *sound*, meaning that safe code cannot cause\nUndefined Behavior through it (which, remember, is the single fundamental\nproperty of Safe Rust).\nBut even in such a trivial function, the scope of the unsafe block is\nquestionable. Consider changing the `<` to a `<=`:\n```rust\nfn index(idx: usize, arr: &[u8]) -> Option {\n if idx <= arr.len() {\n unsafe {\n Some(*arr.get_unchecked(idx))\n }\n } else {\n None\n }\n}\n```\nThis program is now *unsound*, Safe Rust can cause Undefined Behavior, and yet\n*we only modified safe code*. This is the fundamental problem of safety: it's\nnon-local. The soundness of our unsafe operations necessarily depends on the\nstate established by otherwise \"safe\" operations.\nSafety is modular in the sense that opting into unsafety doesn't require you\nto consider arbitrary other kinds of badness. For instance, doing an unchecked\nindex into a slice doesn't mean you suddenly need to worry about the slice being\nnull or containing uninitialized memory. Nothing fundamentally changes. However\nsafety *isn't* modular in the sense that programs are inherently stateful and\nyour unsafe operations may depend on arbitrary other state.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Working with Unsafe", "heading_path": ["Working with Unsafe"], "path": "working-with-unsafe.md", "url": "https://doc.rust-lang.org/nomicon/working-with-unsafe.html#working-with-unsafe", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/working-with-unsafe.md#working-with-unsafe-1", "text": "The Rustonomicon › Working with Unsafe\n\nThis non-locality gets much worse when we incorporate actual persistent state.\nConsider a simple implementation of `Vec`:\n```rust\nuse std::ptr;\n\n// Note: This definition is naive. See the chapter on implementing Vec.\npub struct Vec {\n ptr: *mut T,\n len: usize,\n cap: usize,\n}\n\n// Note this implementation does not correctly handle zero-sized types.\n// See the chapter on implementing Vec.\nimpl Vec {\n pub fn push(&mut self, elem: T) {\n if self.len == self.cap {\n // not important for this example\n self.reallocate();\n }\n unsafe {\n ptr::write(self.ptr.add(self.len), elem);\n self.len += 1;\n }\n }\n # fn reallocate(&mut self) { }\n}\n\n```\nThis code is simple enough to reasonably audit and informally verify. Now consider\nadding the following method:\n```rust,ignore\nfn make_room(&mut self) {\n // grow the capacity\n self.cap += 1;\n}\n```\nThis code is 100% Safe Rust but it is also completely unsound. Changing the\ncapacity violates the invariants of Vec (that `cap` reflects the allocated space\nin the Vec). This is not something the rest of Vec can guard against. It *has*\nto trust the capacity field because there's no way to verify it.\nBecause it relies on invariants of a struct field, this `unsafe` code\ndoes more than pollute a whole function: it pollutes a whole *module*.\nGenerally, the only bullet-proof way to limit the scope of unsafe code is at the\nmodule boundary with privacy.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Working with Unsafe", "heading_path": ["Working with Unsafe"], "path": "working-with-unsafe.md", "url": "https://doc.rust-lang.org/nomicon/working-with-unsafe.html#working-with-unsafe", "has_code": true, "code_tags": ["rust", "rust,ignore"]}} {"id": "nomicon/working-with-unsafe.md#working-with-unsafe-2", "text": "The Rustonomicon › Working with Unsafe\n\nHowever this works *perfectly*. The existence of `make_room` is *not* a\nproblem for the soundness of Vec because we didn't mark it as public. Only the\nmodule that defines this function can call it. Also, `make_room` directly\naccesses the private fields of Vec, so it can only be written in the same module\nas Vec.\nIt is therefore possible for us to write a completely safe abstraction that\nrelies on complex invariants. This is *critical* to the relationship between\nSafe Rust and Unsafe Rust.\nWe have already seen that Unsafe code must trust *some* Safe code, but shouldn't\ntrust *generic* Safe code. Privacy is important to unsafe code for similar reasons:\nit prevents us from having to trust all the safe code in the universe from messing\nwith our trusted state.\nSafety lives!", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Working with Unsafe", "heading_path": ["Working with Unsafe"], "path": "working-with-unsafe.md", "url": "https://doc.rust-lang.org/nomicon/working-with-unsafe.html#working-with-unsafe", "has_code": false, "code_tags": []}} {"id": "nomicon/data.md#data-representation-in-rust-0", "text": "The Rustonomicon › Data Representation in Rust\n\nLow-level programming cares a lot about data layout. It's a big deal. It also\npervasively influences the rest of the language, so we're going to start by\ndigging into how data is represented in Rust.\nThis chapter is ideally in agreement with, and rendered redundant by,\nthe Type Layout section of the Reference. When this\nbook was first written, the reference was in complete disrepair, and the\nRustonomicon was attempting to serve as a partial replacement for the reference.\nThis is no longer the case, so this whole chapter can ideally be deleted.\nWe'll keep this chapter around for a bit longer, but ideally you should be\ncontributing any new facts or improvements to the Reference instead.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Data Layout", "heading_path": ["Data Representation in Rust"], "path": "data.md", "url": "https://doc.rust-lang.org/nomicon/data.html#data-representation-in-rust", "has_code": false, "code_tags": []}} {"id": "nomicon/repr-rust.md#reprrust-0", "text": "The Rustonomicon › repr(Rust)\n\nFirst and foremost, all types have an alignment specified in bytes. The\nalignment of a type specifies what addresses are valid to store the value at. A\nvalue with alignment `n` must only be stored at an address that is a multiple of\n`n`. So alignment 2 means you must be stored at an even address, and 1 means\nthat you can be stored anywhere. Alignment is at least 1, and always a power\nof 2.\nPrimitives are usually aligned to their size, although this is\nplatform-specific behavior. For example, on x86 `u64` and `f64` are often\naligned to 4 bytes (32 bits).\nA type's size must always be a multiple of its alignment (Zero being a valid size\nfor any alignment). This ensures that an array of that type may always be indexed\nby offsetting by a multiple of its size. Note that the size and alignment of a\ntype may not be known statically in the case of dynamically sized types.\nRust gives you the following ways to lay out composite data:\n* structs (named product types)\n* tuples (anonymous product types)\n* arrays (homogeneous product types)\n* enums (named sum types -- tagged unions)\n* unions (untagged unions)\nAn enum is said to be *field-less* if none of its variants have associated data.\nBy default, composite structures have an alignment equal to the maximum\nof their fields' alignments. Rust will consequently insert padding where\nnecessary to ensure that all fields are properly aligned and that the overall\ntype's size is a multiple of its alignment. For instance:\n```rust\nstruct A {\n a: u8,\n b: u32,\n c: u16,\n}\n```\nwill be 32-bit aligned on a target that aligns these primitives to their\nrespective sizes. The whole struct will therefore have a size that is a multiple\nof 32-bits. It may become:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "repr(Rust)", "heading_path": ["repr(Rust)"], "path": "repr-rust.md", "url": "https://doc.rust-lang.org/nomicon/repr-rust.html#reprrust", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/repr-rust.md#reprrust-1", "text": "The Rustonomicon › repr(Rust)\n\n```rust\nstruct A {\n a: u8,\n _pad1: [u8; 3], // to align `b`\n b: u32,\n c: u16,\n _pad2: [u8; 2], // to make overall size multiple of 4\n}\n```\nor maybe:\n```rust\nstruct A {\n b: u32,\n c: u16,\n a: u8,\n _pad: u8,\n}\n```\nThere is *no indirection* for these types; all data is stored within the struct,\nas you would expect in C. However with the exception of arrays (which are\ndensely packed and in-order), the layout of data is not specified by default.\nGiven the two following struct definitions:\n```rust\nstruct A {\n a: i32,\n b: u64,\n}\n\nstruct B {\n a: i32,\n b: u64,\n}\n```\nRust *does* guarantee that two instances of A have their data laid out in\nexactly the same way. However Rust *does not* currently guarantee that an\ninstance of A has the same field ordering or padding as an instance of B.\nWith A and B as written, this point would seem to be pedantic, but several other\nfeatures of Rust make it desirable for the language to play with data layout in\ncomplex ways.\nFor instance, consider this struct:\n```rust\nstruct Foo {\n count: u16,\n data1: T,\n data2: U,\n}\n```\nNow consider the monomorphizations of `Foo` and `Foo`. If\nRust lays out the fields in the order specified, we expect it to pad the\nvalues in the struct to satisfy their alignment requirements. So if Rust\ndidn't reorder fields, we would expect it to produce the following:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "repr(Rust)", "heading_path": ["repr(Rust)"], "path": "repr-rust.md", "url": "https://doc.rust-lang.org/nomicon/repr-rust.html#reprrust", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/repr-rust.md#reprrust-2", "text": "The Rustonomicon › repr(Rust)\n\n```rust,ignore\nstruct Foo {\n count: u16,\n data1: u16,\n data2: u32,\n}\n\nstruct Foo {\n count: u16,\n _pad1: u16,\n data1: u32,\n data2: u16,\n _pad2: u16,\n}\n```\nThe latter case quite simply wastes space. An optimal use of space\nrequires different monomorphizations to have *different field orderings*.\nEnums make this consideration even more complicated. Naively, an enum such as:\n```rust\nenum Foo {\n A(u32),\n B(u64),\n C(u8),\n}\n```\nmight be laid out as:\n```rust\nstruct FooRepr {\n data: u64, // this is either a u64, u32, or u8 based on `tag`\n tag: u8, // 0 = A, 1 = B, 2 = C\n}\n```\nAnd indeed this is approximately how it would be laid out (modulo the\nsize and position of `tag`).\nHowever there are several cases where such a representation is inefficient. The\nclassic case of this is Rust's \"null pointer optimization\": an enum consisting\nof a single outer unit variant (e.g. `None`) and a (potentially nested) non-\nnullable pointer variant (e.g. `Some(&T)`) makes the tag unnecessary. A null\npointer can safely be interpreted as the unit (`None`) variant. The net\nresult is that, for example, `size_of::>() == size_of::<&T>()`.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "repr(Rust)", "heading_path": ["repr(Rust)"], "path": "repr-rust.md", "url": "https://doc.rust-lang.org/nomicon/repr-rust.html#reprrust", "has_code": true, "code_tags": ["rust", "rust,ignore"]}} {"id": "nomicon/repr-rust.md#reprrust-3", "text": "The Rustonomicon › repr(Rust)\n\nThere are many types in Rust that are, or contain, non-nullable pointers such as\n`Box`, `Vec`, `String`, `&T`, and `&mut T`. Similarly, one can imagine\nnested enums pooling their tags into a single discriminant, as they are by\ndefinition known to have a limited range of valid values. In principle enums could\nuse fairly elaborate algorithms to store bits throughout nested types with\nforbidden values. As such it is *especially* desirable that\nwe leave enum layout unspecified today.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "repr(Rust)", "heading_path": ["repr(Rust)"], "path": "repr-rust.md", "url": "https://doc.rust-lang.org/nomicon/repr-rust.html#reprrust", "has_code": false, "code_tags": []}} {"id": "nomicon/exotic-sizes.md#exotically-sized-types-0", "text": "The Rustonomicon › Exotically Sized Types\n\nMost of the time, we expect types to have a statically known and positive size.\nThis isn't always the case in Rust.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Exotically Sized Types", "heading_path": ["Exotically Sized Types"], "path": "exotic-sizes.md", "url": "https://doc.rust-lang.org/nomicon/exotic-sizes.html#exotically-sized-types", "has_code": false, "code_tags": []}} {"id": "nomicon/exotic-sizes.md#dynamically-sized-types-dsts-1", "text": "The Rustonomicon › Exotically Sized Types › Dynamically Sized Types (DSTs)\n\nRust supports Dynamically Sized Types (DSTs): types without a statically\nknown size or alignment. On the surface, this is a bit nonsensical: Rust *must*\nknow the size and alignment of something in order to correctly work with it! In\nthis regard, DSTs are not normal types. Since they lack a statically known\nsize, these types can only exist behind a pointer. Any pointer to a\nDST consequently becomes a *wide* pointer consisting of the pointer and the\ninformation that \"completes\" them (more on this below).\nThere are two major DSTs exposed by the language:\n* trait objects: `dyn MyTrait`\n* slices: [`[T]`][slice], [`str`], and others\nA trait object represents some type that implements the traits it specifies.\nThe exact original type is *erased* in favor of runtime reflection\nwith a vtable containing all the information necessary to use the type.\nThe information that completes a trait object pointer is the vtable pointer.\nThe runtime size of the pointee can be dynamically requested from the vtable.\nA slice is simply a view into some contiguous storage -- typically an array or\n`Vec`. The information that completes a slice pointer is just the number of elements\nit points to. The runtime size of the pointee is just the statically known size\nof an element multiplied by the number of elements.\nStructs can actually store a single DST directly as their last field, but this\nmakes them a DST as well:\n```rust\n// Can't be stored on the stack directly\nstruct MySuperSlice {\n info: u32,\n data: [u8],\n}\n```\nUnfortunately, such a type is largely useless without a way to construct it. Currently the\nonly properly supported way to create a custom DST is by making your type generic\nand performing an *unsizing coercion*:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Exotically Sized Types", "heading_path": ["Exotically Sized Types", "Dynamically Sized Types (DSTs)"], "path": "exotic-sizes.md", "url": "https://doc.rust-lang.org/nomicon/exotic-sizes.html#dynamically-sized-types-dsts", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/exotic-sizes.md#dynamically-sized-types-dsts-2", "text": "The Rustonomicon › Exotically Sized Types › Dynamically Sized Types (DSTs)\n\n```rust\nstruct MySuperSliceable {\n info: u32,\n data: T,\n}\n\nfn main() {\n let sized: MySuperSliceable<[u8; 8]> = MySuperSliceable {\n info: 17,\n data: [0; 8],\n };\n\n let dynamic: &MySuperSliceable<[u8]> = &sized;\n\n // prints: \"17 [0, 0, 0, 0, 0, 0, 0, 0]\"\n println!(\"{} {:?}\", dynamic.info, &dynamic.data);\n}\n```\n(Yes, custom DSTs are a largely half-baked feature for now.)", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Exotically Sized Types", "heading_path": ["Exotically Sized Types", "Dynamically Sized Types (DSTs)"], "path": "exotic-sizes.md", "url": "https://doc.rust-lang.org/nomicon/exotic-sizes.html#dynamically-sized-types-dsts", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/exotic-sizes.md#zero-sized-types-zsts-3", "text": "The Rustonomicon › Exotically Sized Types › Zero Sized Types (ZSTs)\n\nRust also allows types to be specified that occupy no space:\n```rust\nstruct Nothing; // No fields = no size\n\n// All fields have no size = no size\nstruct LotsOfNothing {\n foo: Nothing,\n qux: (), // empty tuple has no size\n baz: [u8; 0], // empty array has no size\n}\n```\nOn their own, Zero Sized Types (ZSTs) are, for obvious reasons, pretty useless.\nHowever as with many curious layout choices in Rust, their potential is realized\nin a generic context: Rust largely understands that any operation that produces\nor stores a ZST can be reduced to a no-op. First off, storing it doesn't even\nmake sense -- it doesn't occupy any space. Also there's only one value of that\ntype, so anything that loads it can just produce it from the aether -- which is\nalso a no-op since it doesn't occupy any space.\nOne of the most extreme examples of this is Sets and Maps. Given a\n`Map`, it is common to implement a `Set` as just a thin wrapper\naround `Map`. In many languages, this would necessitate\nallocating space for UselessJunk and doing work to store and load UselessJunk\nonly to discard it. Proving this unnecessary would be a difficult analysis for\nthe compiler.\nHowever in Rust, we can just say that `Set = Map`. Now Rust\nstatically knows that every load and store is useless, and no allocation has any\nsize. The result is that the monomorphized code is basically a custom\nimplementation of a HashSet with none of the overhead that HashMap would have to\nsupport values.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Exotically Sized Types", "heading_path": ["Exotically Sized Types", "Zero Sized Types (ZSTs)"], "path": "exotic-sizes.md", "url": "https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/exotic-sizes.md#zero-sized-types-zsts-4", "text": "The Rustonomicon › Exotically Sized Types › Zero Sized Types (ZSTs)\n\nSafe code need not worry about ZSTs, but *unsafe* code must be careful about the\nconsequence of types with no size. In particular, pointer offsets are no-ops,\nand allocators typically require a non-zero size.\nNote that references to ZSTs (including empty slices), just like all other\nreferences, must be non-null and suitably aligned. However, loading or storing\nthrough a null pointer to a ZST is not undefined behavior, unlike\npointers to other types.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Exotically Sized Types", "heading_path": ["Exotically Sized Types", "Zero Sized Types (ZSTs)"], "path": "exotic-sizes.md", "url": "https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts", "has_code": false, "code_tags": []}} {"id": "nomicon/exotic-sizes.md#empty-types-5", "text": "The Rustonomicon › Exotically Sized Types › Empty Types\n\nRust also enables types to be declared that *cannot even be instantiated*. These\ntypes can only be talked about at the type level, and never at the value level.\nEmpty types can be declared by specifying an enum with no variants:\n```rust\nenum Void {} // No variants = EMPTY\n```\nEmpty types are even more marginal than ZSTs. The primary motivating example for\nan empty type is type-level unreachability. For instance, suppose an API needs to\nreturn a Result in general, but a specific case actually is infallible. It's\nactually possible to communicate this at the type level by returning a\n`Result`. Consumers of the API can confidently unwrap such a Result\nknowing that it's *statically impossible* for this value to be an `Err`, as\nthis would require providing a value of type `Void`.\nIn principle, Rust can do some interesting analyses and optimizations based\non this fact. For instance, `Result` is represented as just `T`,\nbecause the `Err` case doesn't actually exist (strictly speaking, this is only\nan optimization that is not guaranteed, so for example transmuting one into the\nother is still Undefined Behavior).\nThe following also compiles:\n```rust\nenum Void {}\n\nlet res: Result = Ok(0);\n\n// Err doesn't exist anymore, so Ok is actually irrefutable.\nlet Ok(num) = res;\n```\nOne final subtle detail about empty types is that raw pointers to them are\nactually valid to construct, but dereferencing them is Undefined Behavior\nbecause that wouldn't make sense.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Exotically Sized Types", "heading_path": ["Exotically Sized Types", "Empty Types"], "path": "exotic-sizes.md", "url": "https://doc.rust-lang.org/nomicon/exotic-sizes.html#empty-types", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/exotic-sizes.md#empty-types-6", "text": "The Rustonomicon › Exotically Sized Types › Empty Types\n\nWe recommend against modelling C's `void*` type with `*const Void`.\nA lot of people started doing that but quickly ran into trouble because\nRust doesn't really have any safety guards against trying to instantiate\nempty types with unsafe code, and if you do it, it's Undefined Behavior.\nThis was especially problematic because developers had a habit of converting\nraw pointers to references and `&Void` is *also* Undefined Behavior to\nconstruct.\n`*const ()` (or equivalent) works reasonably well for `void*`, and can be made\ninto a reference without any safety problems. It still doesn't prevent you from\ntrying to read or write values, but at least it compiles to a no-op instead\nof Undefined Behavior.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Exotically Sized Types", "heading_path": ["Exotically Sized Types", "Empty Types"], "path": "exotic-sizes.md", "url": "https://doc.rust-lang.org/nomicon/exotic-sizes.html#empty-types", "has_code": false, "code_tags": []}} {"id": "nomicon/exotic-sizes.md#extern-types-7", "text": "The Rustonomicon › Exotically Sized Types › Extern Types\n\nThere is an accepted RFC to add proper types with an unknown size,\ncalled *extern types*, which would let Rust developers model things like C's `void*`\nand other \"declared but never defined\" types more accurately. However as of\nRust 2018, the feature is stuck in limbo over how `size_of_val::()`\nshould behave.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Exotically Sized Types", "heading_path": ["Exotically Sized Types", "Extern Types"], "path": "exotic-sizes.md", "url": "https://doc.rust-lang.org/nomicon/exotic-sizes.html#extern-types", "has_code": false, "code_tags": []}} {"id": "nomicon/other-reprs.md#alternative-representations-0", "text": "The Rustonomicon › Alternative representations\n\nRust allows you to specify alternative data layout strategies from the default.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Other reprs", "heading_path": ["Alternative representations"], "path": "other-reprs.md", "url": "https://doc.rust-lang.org/nomicon/other-reprs.html#alternative-representations", "has_code": false, "code_tags": []}} {"id": "nomicon/other-reprs.md#reprc-1", "text": "The Rustonomicon › Alternative representations › repr(C)\n\nThis is the most important `repr`. It has fairly simple intent: do what C does.\nThe order, size, and alignment of fields is exactly what you would expect from C\nor C++. The type is also passed across `extern \"C\"` function call boundaries the\nsame way C would pass the corresponding type. Any type you expect to pass through an FFI boundary should have\n`repr(C)`, as C is the lingua-franca of the programming world. This is also\nnecessary to soundly do more elaborate tricks with data layout such as\nreinterpreting values as a different type.\nWe strongly recommend using [rust-bindgen] and/or [cbindgen] to manage your FFI\nboundaries for you. The Rust team works closely with those projects to ensure\nthat they work robustly and are compatible with current and future guarantees\nabout type layouts and `repr`s.\nThe interaction of `repr(C)` with Rust's more exotic data layout features must be\nkept in mind. Due to its dual purpose as \"for FFI\" and \"for layout control\",\n`repr(C)` can be applied to types that will be nonsensical or problematic if\npassed through the FFI boundary.\n* ZSTs are still zero-sized, even though this is not a standard behavior in\nC, and is explicitly contrary to the behavior of an empty type in C++, which\nsays they should still consume a byte of space.\n* DST pointers (wide pointers) and tuples are not a concept\n in C, and as such are never FFI-safe.\n* Enums with fields also aren't a concept in C or C++, but a valid bridging\n of the types is defined.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Other reprs", "heading_path": ["Alternative representations", "repr(C)"], "path": "other-reprs.md", "url": "https://doc.rust-lang.org/nomicon/other-reprs.html#reprc", "has_code": false, "code_tags": []}} {"id": "nomicon/other-reprs.md#reprc-2", "text": "The Rustonomicon › Alternative representations › repr(C)\n\n* If `T` is an FFI-safe non-nullable pointer\n type,\n `Option` is guaranteed to have the same layout and ABI as `T` and is\n therefore also FFI-safe. As of this writing, this covers `&`, `&mut`,\n and function pointers, all of which can never be null.\n* Tuple structs are like structs with regards to `repr(C)`, as the only\n difference from a struct is that the fields aren’t named.\n* `repr(C)` is equivalent to one of `repr(u*)` (see the next section) for\nfieldless enums. The chosen size and sign is the default enum size and sign for the target platform's C\napplication binary interface (ABI). Note that enum representation in C is implementation\ndefined, so this is really a \"best guess\". In particular, this may be incorrect\nwhen the C code of interest is compiled with certain flags.\n* Fieldless enums with `repr(C)` or `repr(u*)` still may not be set to an\ninteger value without a corresponding variant, even though this is\npermitted behavior in C or C++. It is undefined behavior to (unsafely)\nconstruct an instance of an enum that does not match one of its\nvariants. (This allows exhaustive matches to continue to be written and\ncompiled as normal.)", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Other reprs", "heading_path": ["Alternative representations", "repr(C)"], "path": "other-reprs.md", "url": "https://doc.rust-lang.org/nomicon/other-reprs.html#reprc", "has_code": false, "code_tags": []}} {"id": "nomicon/other-reprs.md#reprtransparent-3", "text": "The Rustonomicon › Alternative representations › repr(transparent)\n\n`#[repr(transparent)]` can only be used on a struct or single-variant enum that has a single non-zero-sized field (there may be additional zero-sized fields).\nThe effect is that the layout and ABI of the whole struct/enum is guaranteed to be the same as that one field.\nNOTE: There's a `transparent_unions` nightly feature to apply `repr(transparent)` to unions,\nbut it hasn't been stabilized due to design concerns. See the tracking issue for more details.\nThe goal is to make it possible to transmute between the single field and the\nstruct/enum. An example of that is [`UnsafeCell`], which can be transmuted into\nthe type it wraps ([`UnsafeCell`] also uses the unstable no_niche,\nso its ABI is not actually guaranteed to be the same when nested in other types).\nAlso, passing the struct/enum through FFI where the inner field type is expected on\nthe other side is guaranteed to work. In particular, this is necessary for\n`struct Foo(f32)` or `enum Foo { Bar(f32) }` to always have the same ABI as `f32`.\nThis repr is only considered part of the public ABI of a type if either the single\nfield is `pub`, or if its layout is documented in prose. Otherwise, the layout should\nnot be relied upon by other crates.\nMore details are in the RFC 1758 and the RFC 2645.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Other reprs", "heading_path": ["Alternative representations", "repr(transparent)"], "path": "other-reprs.md", "url": "https://doc.rust-lang.org/nomicon/other-reprs.html#reprtransparent", "has_code": false, "code_tags": []}} {"id": "nomicon/other-reprs.md#repru-repri-4", "text": "The Rustonomicon › Alternative representations › repr(u), repr(i)\n\nThese specify the size and sign to make a fieldless enum. If the discriminant overflows\nthe integer it has to fit in, it will produce a compile-time error. You can\nmanually ask Rust to allow this by setting the overflowing element to explicitly\nbe 0. However Rust will not allow you to create an enum where two variants have\nthe same discriminant.\nThe term \"fieldless enum\" only means that the enum doesn't have data in any\nof its variants. A fieldless enum without a `repr` is\nstill a Rust native type, and does not have a stable layout or representation.\nAdding a `repr(u*)`/`repr(i*)` causes it to be treated exactly like the specified\ninteger type for layout purposes (except that the compiler will still exploit its\nknowledge of \"invalid\" values at this type to optimize enum layout, such as when\nthis enum is wrapped in `Option`). Note that the function call ABI for these\ntypes is still in general unspecified, except that across `extern \"C\"` calls they\nare ABI-compatible with C enums of the same sign and size.\nIf the enum has fields, the effect is similar to the effect of `repr(C)`\nin that there is a defined layout of the type. This makes it possible to\npass the enum to C code, or access the type's raw representation and directly\nmanipulate its tag and fields. See the RFC for details.\nThese `repr`s have no effect on a struct.\nAdding an explicit `repr(u*)`, `repr(i*)`, or `repr(C)` to an enum with fields suppresses the null-pointer optimization, like:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Other reprs", "heading_path": ["Alternative representations", "repr(u), repr(i)"], "path": "other-reprs.md", "url": "https://doc.rust-lang.org/nomicon/other-reprs.html#repru-repri", "has_code": false, "code_tags": []}} {"id": "nomicon/other-reprs.md#repru-repri-5", "text": "The Rustonomicon › Alternative representations › repr(u), repr(i)\n\n```rust\nenum MyOption {\n Some(T),\n None,\n}\n\n#[repr(u8)]\nenum MyReprOption {\n Some(T),\n None,\n}\n\nassert_eq!(8, size_of::>());\nassert_eq!(16, size_of::>());\n```\nThis optimization still applies to fieldless enums with an explicit `repr(u*)`, `repr(i*)`, or `repr(C)`.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Other reprs", "heading_path": ["Alternative representations", "repr(u), repr(i)"], "path": "other-reprs.md", "url": "https://doc.rust-lang.org/nomicon/other-reprs.html#repru-repri", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/other-reprs.md#reprpacked-reprpackedn-6", "text": "The Rustonomicon › Alternative representations › repr(packed), repr(packed(n))\n\n`repr(packed(n))` (where `n` is a power of two) forces the type to have an\nalignment of *at most* `n`. Most commonly used without an explicit `n`,\n`repr(packed)` is equivalent to `repr(packed(1))` which forces Rust to strip\nany padding, and only align the type to a byte. This may improve the memory\nfootprint, but will likely have other negative side-effects.\nIn particular, most architectures *strongly* prefer values to be naturally\naligned. This may mean that unaligned loads are penalized (x86), or even fault\n(some ARM chips). For simple cases like directly loading or storing a packed\nfield, the compiler might be able to paper over alignment issues with shifts\nand masks. However if you take a reference to a packed field, it's unlikely\nthat the compiler will be able to emit code to avoid an unaligned load.\nAs this can cause undefined behavior, the lint has been implemented\nand it will become a hard error.\n`repr(packed)/repr(packed(n))` is not to be used lightly. Unless you have\nextreme requirements, this should not be used.\nThis repr is a modifier on `repr(C)` and `repr(Rust)`. For FFI compatibility\nyou most likely always want to be explicit: `repr(C, packed)`.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Other reprs", "heading_path": ["Alternative representations", "repr(packed), repr(packed(n))"], "path": "other-reprs.md", "url": "https://doc.rust-lang.org/nomicon/other-reprs.html#reprpacked-reprpackedn", "has_code": false, "code_tags": []}} {"id": "nomicon/other-reprs.md#repralignn-7", "text": "The Rustonomicon › Alternative representations › repr(align(n))\n\n`repr(align(n))` (where `n` is a power of two) forces the type to have an\nalignment of *at least* `n`.\nThis enables several tricks, like making sure neighboring elements of an array\nnever share the same cache line with each other (which may speed up certain\nkinds of concurrent code).\nThis is a modifier on `repr(C)` and `repr(Rust)`. It is incompatible with\n`repr(packed)`.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Other reprs", "heading_path": ["Alternative representations", "repr(align(n))"], "path": "other-reprs.md", "url": "https://doc.rust-lang.org/nomicon/other-reprs.html#repralignn", "has_code": false, "code_tags": []}} {"id": "nomicon/ownership.md#ownership-and-lifetimes-0", "text": "The Rustonomicon › Ownership and Lifetimes\n\nOwnership is the breakout feature of Rust. It allows Rust to be completely\nmemory-safe and efficient, while avoiding garbage collection. Before getting\ninto the ownership system in detail, we will consider the motivation of this\ndesign.\nWe will assume that you accept that garbage collection (GC) is not always an\noptimal solution, and that it is desirable to manually manage memory in some\ncontexts. If you do not accept this, might I interest you in a different\nlanguage?\nRegardless of your feelings on GC, it is pretty clearly a *massive* boon to\nmaking code safe. You never have to worry about things going away *too soon*\n(although whether you still wanted to be pointing at that thing is a different\nissue...). This is a pervasive problem that C and C++ programs need to deal\nwith. Consider this simple mistake that all of us who have used a non-GC'd\nlanguage have made at one point:\n```rust,compile_fail\nfn as_str(data: &u32) -> &str {\n // compute the string\n let s = format!(\"{}\", data);\n\n // OH NO! We returned a reference to something that\n // exists only in this function!\n // Dangling pointer! Use after free! Alas!\n // (this does not compile in Rust)\n &s\n}\n```\nThis is exactly what Rust's ownership system was built to solve.\nRust knows the scope in which the `&s` lives, and as such can prevent it from\nescaping. However this is a simple case that even a C compiler could plausibly\ncatch. Things get more complicated as code gets bigger and pointers get fed through\nvarious functions. Eventually, a C compiler will fall down and won't be able to\nperform sufficient escape analysis to prove your code unsound. It will consequently\nbe forced to accept your program on the assumption that it is correct.\nThis will never happen to Rust. It's up to the programmer to prove to the\ncompiler that everything is sound.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Ownership", "heading_path": ["Ownership and Lifetimes"], "path": "ownership.md", "url": "https://doc.rust-lang.org/nomicon/ownership.html#ownership-and-lifetimes", "has_code": true, "code_tags": ["rust,compile_fail"]}} {"id": "nomicon/ownership.md#ownership-and-lifetimes-1", "text": "The Rustonomicon › Ownership and Lifetimes\n\nOf course, Rust's story around ownership is much more complicated than just\nverifying that references don't escape the scope of their referent. That's\nbecause ensuring pointers are always valid is much more complicated than this.\nFor instance in this code,\n```rust,compile_fail\nlet mut data = vec![1, 2, 3];\n// get an internal reference\nlet x = &data[0];\n\n// OH NO! `push` causes the backing storage of `data` to be reallocated.\n// Dangling pointer! Use after free! Alas!\n// (this does not compile in Rust)\ndata.push(4);\n\nprintln!(\"{}\", x);\n```\nnaive scope analysis would be insufficient to prevent this bug, because `data`\ndoes in fact live as long as we needed. However it was *changed* while we had\na reference into it. This is why Rust requires any references to freeze the\nreferent and its owners.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Ownership", "heading_path": ["Ownership and Lifetimes"], "path": "ownership.md", "url": "https://doc.rust-lang.org/nomicon/ownership.html#ownership-and-lifetimes", "has_code": true, "code_tags": ["rust,compile_fail"]}} {"id": "nomicon/references.md#references-0", "text": "The Rustonomicon › References\n\nThere are two kinds of references:\n* Shared reference: `&`\n* Mutable reference: `&mut`\nWhich obey the following rules:\n* A reference cannot outlive its referent\n* A mutable reference cannot be aliased\nThat's it. That's the whole model references follow.\nOf course, we should probably define what *aliased* means.\n```text\nerror[E0425]: cannot find value `aliased` in this scope\n --> :2:20\n |\n2 | println!(\"{}\", aliased);\n | ^^^^^^^ not found in this scope\n\nerror: aborting due to previous error\n```\nUnfortunately, Rust hasn't actually defined its aliasing model. 🙀\nWhile we wait for the Rust devs to specify the semantics of their language,\nlet's use the next section to discuss what aliasing is in general, and why it\nmatters.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "References", "heading_path": ["References"], "path": "references.md", "url": "https://doc.rust-lang.org/nomicon/references.html#references", "has_code": true, "code_tags": ["text"]}} {"id": "nomicon/aliasing.md#aliasing-0", "text": "The Rustonomicon › Aliasing\n\nFirst off, let's get some important caveats out of the way:\n* We will be using the broadest possible definition of aliasing for the sake\nof discussion. Rust's definition will probably be more restricted to factor\nin mutations and liveness.\n* We will be assuming a single-threaded, interrupt-free, execution. We will also\nbe ignoring things like memory-mapped hardware. Rust assumes these things\ndon't happen unless you tell it otherwise. For more details, see the\nConcurrency Chapter.\nWith that said, here's our working definition: variables and pointers *alias*\nif they refer to overlapping regions of memory.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Aliasing", "heading_path": ["Aliasing"], "path": "aliasing.md", "url": "https://doc.rust-lang.org/nomicon/aliasing.html#aliasing", "has_code": false, "code_tags": []}} {"id": "nomicon/aliasing.md#why-aliasing-matters-1", "text": "The Rustonomicon › Aliasing › Why Aliasing Matters\n\nSo why should we care about aliasing?\nConsider this simple function:\n```rust\nfn compute(input: &u32, output: &mut u32) {\n if *input > 10 {\n *output = 1;\n }\n if *input > 5 {\n *output *= 2;\n }\n // remember that `output` will be `2` if `input > 10`\n}\n```\nWe would *like* to be able to optimize it to the following function:\n```rust\nfn compute(input: &u32, output: &mut u32) {\n let cached_input = *input; // keep `*input` in a register\n if cached_input > 10 {\n // If the input is greater than 10, the previous code would set the output to 1 and then double it,\n // resulting in an output of 2 (because `>10` implies `>5`).\n // Here, we avoid the double assignment and just set it directly to 2.\n *output = 2;\n } else if cached_input > 5 {\n *output *= 2;\n }\n}\n```\nIn Rust, this optimization should be sound. For almost any other language, it\nwouldn't be (barring global analysis). This is because the optimization relies\non knowing that aliasing doesn't occur, which most languages are fairly liberal\nwith. Specifically, we need to worry about function arguments that make `input`\nand `output` overlap, such as `compute(&x, &mut x)`.\nWith that input, we could get this execution:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Aliasing", "heading_path": ["Aliasing", "Why Aliasing Matters"], "path": "aliasing.md", "url": "https://doc.rust-lang.org/nomicon/aliasing.html#why-aliasing-matters", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/aliasing.md#why-aliasing-matters-2", "text": "The Rustonomicon › Aliasing › Why Aliasing Matters\n\n```rust,ignore\n // input == output == 0xabad1dea\n // *input == *output == 20\nif *input > 10 { // true (*input == 20)\n *output = 1; // also overwrites *input, because they are the same\n}\nif *input > 5 { // false (*input == 1)\n *output *= 2;\n}\n // *input == *output == 1\n```\nOur optimized function would produce `*output == 2` for this input, so the\ncorrectness of our optimization relies on this input being impossible.\nIn Rust we know this input should be impossible because `&mut` isn't allowed to be\naliased. So we can safely reject its possibility and perform this optimization.\nIn most other languages, this input would be entirely possible, and must be considered.\nThis is why alias analysis is important: it lets the compiler perform useful\noptimizations! Some examples:\n* keeping values in registers by proving no pointers access the value's memory\n* eliminating reads by proving some memory hasn't been written to since last we read it\n* eliminating writes by proving some memory is never read before the next write to it\n* moving or reordering reads and writes by proving they don't depend on each other\nThese optimizations also tend to prove the soundness of bigger optimizations\nsuch as loop vectorization, constant propagation, and dead code elimination.\nIn the previous example, we used the fact that `&mut u32` can't be aliased to prove\nthat writes to `*output` can't possibly affect `*input`. This lets us cache `*input`\nin a register, eliminating a read.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Aliasing", "heading_path": ["Aliasing", "Why Aliasing Matters"], "path": "aliasing.md", "url": "https://doc.rust-lang.org/nomicon/aliasing.html#why-aliasing-matters", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/aliasing.md#why-aliasing-matters-3", "text": "The Rustonomicon › Aliasing › Why Aliasing Matters\n\nBy caching this read, we knew that the write in the `> 10` branch couldn't\naffect whether we take the `> 5` branch, allowing us to also eliminate a\nread-modify-write (doubling `*output`) when `*input > 10`.\nThe key thing to remember about alias analysis is that writes are the primary\nhazard for optimizations. That is, the only thing that prevents us\nfrom moving a read to any other part of the program is the possibility of us\nre-ordering it with a write to the same location.\nFor instance, we have no concern for aliasing in the following modified version\nof our function, because we've moved the only write to `*output` to the very\nend of our function. This allows us to freely reorder the reads of `*input` that\noccur before it:\n```rust\nfn compute(input: &u32, output: &mut u32) {\n let mut temp = *output;\n if *input > 10 {\n temp = 1;\n }\n if *input > 5 {\n temp *= 2;\n }\n *output = temp;\n}\n```\nWe're still relying on alias analysis to assume that `input` doesn't alias\n`temp`, but the proof is much simpler: the value of a local variable can't be\naliased by things that existed before it was declared. This is an assumption\nevery language freely makes, and so this version of the function could be\noptimized the way we want in any language.\nThis is why the definition of \"alias\" that Rust will use likely involves some\nnotion of liveness and mutation: we don't actually care if aliasing occurs if\nthere aren't any actual writes to memory happening.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Aliasing", "heading_path": ["Aliasing", "Why Aliasing Matters"], "path": "aliasing.md", "url": "https://doc.rust-lang.org/nomicon/aliasing.html#why-aliasing-matters", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/aliasing.md#why-aliasing-matters-4", "text": "The Rustonomicon › Aliasing › Why Aliasing Matters\n\nOf course, a full aliasing model for Rust must also take into consideration things like\nfunction calls (which may mutate things we don't see), raw pointers (which have\nno aliasing requirements on their own), and UnsafeCell (which lets the referent\nof an `&` be mutated).", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Aliasing", "heading_path": ["Aliasing", "Why Aliasing Matters"], "path": "aliasing.md", "url": "https://doc.rust-lang.org/nomicon/aliasing.html#why-aliasing-matters", "has_code": false, "code_tags": []}} {"id": "nomicon/lifetimes.md#lifetimes-0", "text": "The Rustonomicon › Lifetimes\n\nRust enforces these rules through *lifetimes*. Lifetimes are named\nregions of code that a reference must be valid for. Those regions\nmay be fairly complex, as they correspond to paths of execution\nin the program. There may even be holes in these paths of execution,\nas it's possible to invalidate a reference as long as it's reinitialized\nbefore it's used again. Types which contain references (or pretend to)\nmay also be tagged with lifetimes so that Rust can prevent them from\nbeing invalidated as well.\nIn most of our examples, the lifetimes will coincide with scopes. This is\nbecause our examples are simple. The more complex cases where they don't\ncoincide are described below.\nWithin a function body, Rust generally doesn't let you explicitly name the\nlifetimes involved. This is because it's generally not really necessary\nto talk about lifetimes in a local context; Rust has all the information and\ncan work out everything as optimally as possible. Many anonymous scopes and\ntemporaries that you would otherwise have to write are often introduced to\nmake your code Just Work.\nHowever once you cross the function boundary, you need to start talking about\nlifetimes. Lifetimes are denoted with an apostrophe: `'a`, `'static`. To dip\nour toes with lifetimes, we're going to pretend that we're actually allowed\nto label scopes with lifetimes, and desugar the examples from the start of\nthis chapter.\nOriginally, our examples made use of *aggressive* sugar -- high fructose corn\nsyrup even -- around scopes and lifetimes, because writing everything out\nexplicitly is *extremely noisy*. All Rust code relies on aggressive inference\nand elision of \"obvious\" things.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Lifetimes", "heading_path": ["Lifetimes"], "path": "lifetimes.md", "url": "https://doc.rust-lang.org/nomicon/lifetimes.html#lifetimes", "has_code": false, "code_tags": []}} {"id": "nomicon/lifetimes.md#lifetimes-1", "text": "The Rustonomicon › Lifetimes\n\nOne particularly interesting piece of sugar is that each `let` statement\nimplicitly introduces a scope. For the most part, this doesn't really matter.\nHowever it does matter for variables that refer to each other. As a simple\nexample, let's completely desugar this simple piece of Rust code:\n```rust\nlet x = 0;\nlet y = &x;\nlet z = &y;\n```\nThe borrow checker always tries to minimize the extent of a lifetime, so it will\nlikely desugar to the following:\n```rust,ignore\n// NOTE: `'a: {` and `&'b x` is not valid syntax!\n'a: {\n let x: i32 = 0;\n 'b: {\n // lifetime used is 'b because that's good enough.\n let y: &'b i32 = &'b x;\n 'c: {\n // ditto on 'c\n let z: &'c &'b i32 = &'c y; // \"a reference to a reference to an i32\" (with lifetimes annotated)\n }\n }\n}\n```\nWow. That's... awful. Let's all take a moment to thank Rust for making this easier.\nActually passing references to outer scopes will cause Rust to infer\na larger lifetime:\n```rust\nlet x = 0;\nlet z;\nlet y = &x;\nz = y;\n```\n```rust,ignore\n'a: {\n let x: i32 = 0;\n 'b: {\n let z: &'b i32;\n 'c: {\n // Must use 'b here because the reference to x is\n // being passed to the scope 'b.\n let y: &'b i32 = &'b x;\n z = y;\n }\n }\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Lifetimes", "heading_path": ["Lifetimes"], "path": "lifetimes.md", "url": "https://doc.rust-lang.org/nomicon/lifetimes.html#lifetimes", "has_code": true, "code_tags": ["rust", "rust,ignore"]}} {"id": "nomicon/lifetimes.md#example-references-that-outlive-referents-2", "text": "The Rustonomicon › Lifetimes › Example: references that outlive referents\n\nAlright, let's look at some of those examples from before:\n```rust,compile_fail\nfn as_str(data: &u32) -> &str {\n let s = format!(\"{}\", data);\n &s\n}\n```\ndesugars to:\n```rust,ignore\nfn as_str<'a>(data: &'a u32) -> &'a str {\n 'b: {\n let s = format!(\"{}\", data);\n return &'a s;\n }\n}\n```\nThis signature of `as_str` takes a reference to a u32 with *some* lifetime, and\npromises that it can produce a reference to a str that can live *just as long*.\nAlready we can see why this signature might be trouble. That basically implies\nthat we're going to find a str somewhere in the scope the reference\nto the u32 originated in, or somewhere *even earlier*. That's a bit of a tall\norder.\nWe then proceed to compute the string `s`, and return a reference to it. Since\nthe contract of our function says the reference must outlive `'a`, that's the\nlifetime we infer for the reference. Unfortunately, `s` was defined in the\nscope `'b`, so the only way this is sound is if `'b` contains `'a` -- which is\nclearly false since `'a` must contain the function call itself. We have therefore\ncreated a reference whose lifetime outlives its referent, which is *literally*\nthe first thing we said that references can't do. The compiler rightfully blows\nup in our face.\nTo make this more clear, we can expand the example:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Lifetimes", "heading_path": ["Lifetimes", "Example: references that outlive referents"], "path": "lifetimes.md", "url": "https://doc.rust-lang.org/nomicon/lifetimes.html#example-references-that-outlive-referents", "has_code": true, "code_tags": ["rust,compile_fail", "rust,ignore"]}} {"id": "nomicon/lifetimes.md#example-references-that-outlive-referents-3", "text": "The Rustonomicon › Lifetimes › Example: references that outlive referents\n\n```rust,ignore\nfn as_str<'a>(data: &'a u32) -> &'a str {\n 'b: {\n let s = format!(\"{}\", data);\n return &'a s\n }\n}\n\nfn main() {\n 'c: {\n let x: u32 = 0;\n 'd: {\n // An anonymous scope is introduced because the borrow does not\n // need to last for the whole scope x is valid for. The return\n // of as_str must find a str somewhere before this function\n // call. Obviously not happening.\n println!(\"{}\", as_str::<'d>(&'d x));\n }\n }\n}\n```\nShoot!\nOf course, the right way to write this function is as follows:\n```rust\nfn to_string(data: &u32) -> String {\n format!(\"{}\", data)\n}\n```\nWe must produce an owned value inside the function to return it! The only way\nwe could have returned an `&'a str` would have been if it was in a field of the\n`&'a u32`, which is obviously not the case.\n(Actually we could have also just returned a string literal, which as a global\ncan be considered to reside at the bottom of the stack; though this limits\nour implementation *just a bit*.)", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Lifetimes", "heading_path": ["Lifetimes", "Example: references that outlive referents"], "path": "lifetimes.md", "url": "https://doc.rust-lang.org/nomicon/lifetimes.html#example-references-that-outlive-referents", "has_code": true, "code_tags": ["rust", "rust,ignore"]}} {"id": "nomicon/lifetimes.md#example-aliasing-a-mutable-reference-4", "text": "The Rustonomicon › Lifetimes › Example: aliasing a mutable reference\n\nHow about the other example:\n```rust,compile_fail\nlet mut data = vec![1, 2, 3];\nlet x = &data[0];\ndata.push(4);\nprintln!(\"{}\", x);\n```\n```rust,ignore\n'a: {\n let mut data: Vec = vec![1, 2, 3];\n 'b: {\n // 'b is as big as we need this borrow to be\n // (just need to get to `println!`)\n let x: &'b i32 = Index::index::<'b>(&'b data, 0);\n 'c: {\n // Temporary scope because we don't need the\n // &mut to last any longer.\n Vec::push(&'c mut data, 4);\n }\n println!(\"{}\", x);\n }\n}\n```\nThe problem here is a bit more subtle and interesting. We want Rust to\nreject this program for the following reason: We have a live shared reference `x`\nto a descendant of `data` when we try to take a mutable reference to `data`\nto `push`. This would create an aliased mutable reference, which would\nviolate the *second* rule of references.\nHowever this is *not at all* how Rust reasons that this program is bad. Rust\ndoesn't understand that `x` is a reference to a subpath of `data`. It doesn't\nunderstand `Vec` at all. What it *does* see is that `x` has to live for `'b` in\norder to be printed. The signature of `Index::index` subsequently demands that\nthe reference we take to `data` has to survive for `'b`. When we try to call\n`push`, it then sees us try to make an `&'c mut data`. Rust knows that `'c` is\ncontained within `'b`, and rejects our program because the `&'b data` must still\nbe alive!", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Lifetimes", "heading_path": ["Lifetimes", "Example: aliasing a mutable reference"], "path": "lifetimes.md", "url": "https://doc.rust-lang.org/nomicon/lifetimes.html#example-aliasing-a-mutable-reference", "has_code": true, "code_tags": ["rust,compile_fail", "rust,ignore"]}} {"id": "nomicon/lifetimes.md#example-aliasing-a-mutable-reference-5", "text": "The Rustonomicon › Lifetimes › Example: aliasing a mutable reference\n\nHere we see that the lifetime system is much more coarse than the reference\nsemantics we're actually interested in preserving. For the most part, *that's\ntotally ok*, because it keeps us from spending all day explaining our program\nto the compiler. However it does mean that several programs that are totally\ncorrect with respect to Rust's *true* semantics are rejected because lifetimes\nare too dumb.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Lifetimes", "heading_path": ["Lifetimes", "Example: aliasing a mutable reference"], "path": "lifetimes.md", "url": "https://doc.rust-lang.org/nomicon/lifetimes.html#example-aliasing-a-mutable-reference", "has_code": false, "code_tags": []}} {"id": "nomicon/lifetimes.md#the-area-covered-by-a-lifetime-6", "text": "The Rustonomicon › Lifetimes › The area covered by a lifetime\n\nA reference (sometimes called a *borrow*) is *alive* from the place it is\ncreated to its last use. The borrowed value needs to outlive only borrows that\nare alive. This looks simple, but there are a few subtleties.\nThe following snippet compiles, because after printing `x`, it is no longer\nneeded, so it doesn't matter if it is dangling or aliased (even though the\nvariable `x` *technically* exists to the very end of the scope).\n```rust\nlet mut data = vec![1, 2, 3];\nlet x = &data[0];\nprintln!(\"{}\", x);\n// This is OK, x is no longer needed\ndata.push(4);\n```\nHowever, if the value has a destructor, the destructor is run at the end of the\nscope. And running the destructor is considered a use ‒ obviously the last one.\nSo, this will *not* compile.\n```rust,compile_fail\n#[derive(Debug)]\nstruct X<'a>(&'a i32);\n\nimpl Drop for X<'_> {\n fn drop(&mut self) {}\n}\n\nlet mut data = vec![1, 2, 3];\nlet x = X(&data[0]);\nprintln!(\"{:?}\", x);\ndata.push(4);\n// Here, the destructor is run and therefore this'll fail to compile.\n```\nOne way to convince the compiler that `x` is no longer valid is by using `drop(x)` before `data.push(4)`.\nFurthermore, there might be multiple possible last uses of the borrow, for\nexample in each branch of a condition.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Lifetimes", "heading_path": ["Lifetimes", "The area covered by a lifetime"], "path": "lifetimes.md", "url": "https://doc.rust-lang.org/nomicon/lifetimes.html#the-area-covered-by-a-lifetime", "has_code": true, "code_tags": ["rust", "rust,compile_fail"]}} {"id": "nomicon/lifetimes.md#the-area-covered-by-a-lifetime-7", "text": "The Rustonomicon › Lifetimes › The area covered by a lifetime\n\n```rust\nlet mut data = vec![1, 2, 3];\nlet x = &data[0];\n\nif some_condition() {\n println!(\"{}\", x); // This is the last use of `x` in this branch\n data.push(4); // So we can push here\n} else {\n // There's no use of `x` in here, so effectively the last use is the\n // creation of x at the top of the example.\n data.push(5);\n}\n```\nAnd a lifetime can have a pause in it. Or you might look at it as two distinct\nborrows just being tied to the same local variable. This often happens around\nloops (writing a new value of a variable at the end of the loop and using it for\nthe last time at the top of the next iteration).\n```rust\nlet mut data = vec![1, 2, 3];\n// This mut allows us to change where the reference points to\nlet mut x = &data[0];\n\nprintln!(\"{}\", x); // Last use of this borrow\ndata.push(4);\nx = &data[3]; // We start a new borrow here\nprintln!(\"{}\", x);\n```\nHistorically, Rust kept the borrow alive until the end of scope, so these\nexamples might fail to compile with older compilers. Also, there are still some\ncorner cases where Rust fails to properly shorten the live part of the borrow\nand fails to compile even when it looks like it should. These'll be solved over\ntime.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Lifetimes", "heading_path": ["Lifetimes", "The area covered by a lifetime"], "path": "lifetimes.md", "url": "https://doc.rust-lang.org/nomicon/lifetimes.html#the-area-covered-by-a-lifetime", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/lifetime-mismatch.md#limits-of-lifetimes-0", "text": "The Rustonomicon › Limits of Lifetimes\n\nGiven the following code:\n```rust,compile_fail\n#[derive(Debug)]\nstruct Foo;\n\nimpl Foo {\n fn mutate_and_share(&mut self) -> &Self { &*self }\n fn share(&self) {}\n}\n\nfn main() {\n let mut foo = Foo;\n let loan = foo.mutate_and_share();\n foo.share();\n println!(\"{:?}\", loan);\n}\n```\nOne might expect it to compile. We call `mutate_and_share`, which mutably\nborrows `foo` temporarily, but then returns only a shared reference. Therefore\nwe would expect `foo.share()` to succeed as `foo` shouldn't be mutably borrowed.\nHowever when we try to compile it:\n```text\nerror[E0502]: cannot borrow `foo` as immutable because it is also borrowed as mutable\n --> src/main.rs:12:5\n |\n11 | let loan = foo.mutate_and_share();\n | --- mutable borrow occurs here\n12 | foo.share();\n | ^^^ immutable borrow occurs here\n13 | println!(\"{:?}\", loan);\n```\nWhat happened? Well, we got the exact same reasoning as we did for\nExample 2 in the previous section. We desugar the program and we get\nthe following:\n```rust,ignore\nstruct Foo;\n\nimpl Foo {\n fn mutate_and_share<'a>(&'a mut self) -> &'a Self { &'a *self }\n fn share<'a>(&'a self) {}\n}\n\nfn main() {\n 'b: {\n let mut foo: Foo = Foo;\n 'c: {\n let loan: &'c Foo = Foo::mutate_and_share::<'c>(&'c mut foo);\n 'd: {\n Foo::share::<'d>(&'d foo);\n }\n println!(\"{:?}\", loan);\n }\n }\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Limits of Lifetimes", "heading_path": ["Limits of Lifetimes"], "path": "lifetime-mismatch.md", "url": "https://doc.rust-lang.org/nomicon/lifetime-mismatch.html#limits-of-lifetimes", "has_code": true, "code_tags": ["rust,compile_fail", "rust,ignore", "text"]}} {"id": "nomicon/lifetime-mismatch.md#limits-of-lifetimes-1", "text": "The Rustonomicon › Limits of Lifetimes\n\nThe lifetime system is forced to extend the `&mut foo` to have lifetime `'c`,\ndue to the lifetime of `loan` and `mutate_and_share`'s signature. Then when we\ntry to call `share`, it sees we're trying to alias that `&'c mut foo` and\nblows up in our face!\nThis program is clearly correct according to the reference semantics we actually\ncare about, but the lifetime system is too coarse-grained to handle that.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Limits of Lifetimes", "heading_path": ["Limits of Lifetimes"], "path": "lifetime-mismatch.md", "url": "https://doc.rust-lang.org/nomicon/lifetime-mismatch.html#limits-of-lifetimes", "has_code": false, "code_tags": []}} {"id": "nomicon/lifetime-mismatch.md#improperly-reduced-borrows-2", "text": "The Rustonomicon › Limits of Lifetimes › Improperly reduced borrows\n\nThe following code fails to compile, because Rust sees that a variable, `map`,\nis borrowed twice, and can not infer that the first borrow ceases to be needed\nbefore the second one occurs. This is caused by Rust conservatively falling back\nto using a whole scope for the first borrow. This will eventually get fixed.\n```rust,compile_fail\nfn get_default<'m, K, V>(map: &'m mut HashMap, key: K) -> &'m mut V\nwhere\n K: Clone + Eq + Hash,\n V: Default,\n{\n match map.get_mut(&key) {\n Some(value) => value,\n None => {\n map.insert(key.clone(), V::default());\n map.get_mut(&key).unwrap()\n }\n }\n}\n```\nBecause of the lifetime restrictions imposed, `&mut map`'s lifetime\noverlaps other mutable borrows, resulting in a compile error:\n```text\nerror[E0499]: cannot borrow `*map` as mutable more than once at a time\n --> src/main.rs:12:13\n |\n4 | fn get_default<'m, K, V>(map: &'m mut HashMap, key: K) -> &'m mut V\n | -- lifetime `'m` defined here\n...\n9 | match map.get_mut(&key) {\n | - --- first mutable borrow occurs here\n | _____|\n | |\n10 | | Some(value) => value,\n11 | | None => {\n12 | | map.insert(key.clone(), V::default());\n | | ^^^ second mutable borrow occurs here\n13 | | map.get_mut(&key).unwrap()\n14 | | }\n15 | | }\n | |_____- returning this value requires that `*map` is borrowed for `'m`\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Limits of Lifetimes", "heading_path": ["Limits of Lifetimes", "Improperly reduced borrows"], "path": "lifetime-mismatch.md", "url": "https://doc.rust-lang.org/nomicon/lifetime-mismatch.html#improperly-reduced-borrows", "has_code": true, "code_tags": ["rust,compile_fail", "text"]}} {"id": "nomicon/lifetime-elision.md#lifetime-elision-0", "text": "The Rustonomicon › Lifetime Elision\n\nIn order to make common patterns more ergonomic, Rust allows lifetimes to be\n*elided* in function signatures.\nA *lifetime position* is anywhere you can write a lifetime in a type:\n```rust,ignore\n&'a T\n&'a mut T\nT<'a>\n```\nLifetime positions can appear as either \"input\" or \"output\":\n* For `fn` definitions, `fn` types, and the traits `Fn`, `FnMut`, and `FnOnce`,\n input refers to the types of the formal arguments, while output refers to\n result types. So `fn foo(s: &str) -> (&str, &str)` has elided one lifetime in\n input position and two lifetimes in output position. Note that the input\n positions of a `fn` method definition do not include the lifetimes that occur\n in the method's `impl` header (nor lifetimes that occur in the trait header,\n for a default method).\n* For `impl` headers, all types are input. So `impl Trait<&T> for Struct<&T>`\n has elided two lifetimes in input position, while `impl Struct<&T>` has elided\n one.\nElision rules are as follows:\n* Each elided lifetime in input position becomes a distinct lifetime\n parameter.\n* If there is exactly one input lifetime position (elided or not), that lifetime\n is assigned to *all* elided output lifetimes.\n* If there are multiple input lifetime positions, but one of them is `&self` or\n `&mut self`, the lifetime of `self` is assigned to *all* elided output lifetimes.\n* Otherwise, it is an error to elide an output lifetime.\nExamples:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Lifetime Elision", "heading_path": ["Lifetime Elision"], "path": "lifetime-elision.md", "url": "https://doc.rust-lang.org/nomicon/lifetime-elision.html#lifetime-elision", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/lifetime-elision.md#lifetime-elision-1", "text": "The Rustonomicon › Lifetime Elision\n\n```rust,ignore\nfn print(s: &str); // elided\nfn print<'a>(s: &'a str); // expanded\n\nfn debug(lvl: usize, s: &str); // elided\nfn debug<'a>(lvl: usize, s: &'a str); // expanded\n\nfn substr(s: &str, until: usize) -> &str; // elided\nfn substr<'a>(s: &'a str, until: usize) -> &'a str; // expanded\n\nfn get_str() -> &str; // ILLEGAL\n\nfn frob(s: &str, t: &str) -> &str; // ILLEGAL\n\nfn get_mut(&mut self) -> &mut T; // elided\nfn get_mut<'a>(&'a mut self) -> &'a mut T; // expanded\n\nfn args(&mut self, args: &[T]) -> &mut Command // elided\nfn args<'a, 'b, T: ToCStr>(&'a mut self, args: &'b [T]) -> &'a mut Command // expanded\n\nfn new(buf: &mut [u8]) -> BufWriter; // elided\nfn new(buf: &mut [u8]) -> BufWriter<'_>; // elided (with `rust_2018_idioms`)\nfn new<'a>(buf: &'a mut [u8]) -> BufWriter<'a> // expanded\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Lifetime Elision", "heading_path": ["Lifetime Elision"], "path": "lifetime-elision.md", "url": "https://doc.rust-lang.org/nomicon/lifetime-elision.html#lifetime-elision", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/unbounded-lifetimes.md#unbounded-lifetimes-0", "text": "The Rustonomicon › Unbounded Lifetimes\n\nUnsafe code can often end up producing references or lifetimes out of thin air.\nSuch lifetimes come into the world as *unbounded*. The most common source of\nthis is taking a reference to a dereferenced raw pointer, which produces a\nreference with an unbounded lifetime. Such a lifetime becomes as big as context\ndemands. This is in fact more powerful than simply becoming `'static`, because\nfor instance `&'static &'a T` will fail to typecheck, but the unbound lifetime\nwill perfectly mold into `&'a &'a T` as needed. However for most intents and\npurposes, such an unbounded lifetime can be regarded as `'static`.\nAlmost no reference is `'static`, so this is probably wrong. `transmute` and\n`transmute_copy` are the two other primary offenders. One should endeavor to\nbound an unbounded lifetime as quickly as possible, especially across function\nboundaries.\nGiven a function, any output lifetimes that don't derive from inputs are\nunbounded. For instance:\n```rust,no_run\nfn get_str<'a>(s: *const String) -> &'a str {\n unsafe { &*s }\n}\n\nfn main() {\n let soon_dropped = String::from(\"hello\");\n let dangling = get_str(&soon_dropped);\n drop(soon_dropped);\n println!(\"Invalid str: {}\", dangling); // Invalid str: gӚ_`\n}\n```\nThe easiest way to avoid unbounded lifetimes is to use lifetime elision at the\nfunction boundary. If an output lifetime is elided, then it *must* be bounded by\nan input lifetime. Of course it might be bounded by the *wrong* lifetime, but\nthis will usually just cause a compiler error, rather than allow memory safety\nto be trivially violated.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Unbounded Lifetimes", "heading_path": ["Unbounded Lifetimes"], "path": "unbounded-lifetimes.md", "url": "https://doc.rust-lang.org/nomicon/unbounded-lifetimes.html#unbounded-lifetimes", "has_code": true, "code_tags": ["rust,no_run"]}} {"id": "nomicon/unbounded-lifetimes.md#unbounded-lifetimes-1", "text": "The Rustonomicon › Unbounded Lifetimes\n\nWithin a function, bounding lifetimes is more error-prone. The safest and easiest\nway to bound a lifetime is to return it from a function with a bound lifetime.\nHowever if this is unacceptable, the reference can be placed in a location with\na specific lifetime. Unfortunately it's impossible to name all lifetimes involved\nin a function.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Unbounded Lifetimes", "heading_path": ["Unbounded Lifetimes"], "path": "unbounded-lifetimes.md", "url": "https://doc.rust-lang.org/nomicon/unbounded-lifetimes.html#unbounded-lifetimes", "has_code": false, "code_tags": []}} {"id": "nomicon/hrtb.md#higher-rank-trait-bounds-hrtbs-0", "text": "The Rustonomicon › Higher-Rank Trait Bounds (HRTBs)\n\nRust's `Fn` traits are a little bit magic. For instance, we can write the\nfollowing code:\n```rust\nstruct Closure {\n data: (u8, u16),\n func: F,\n}\n\nimpl Closure\n where F: Fn(&(u8, u16)) -> &u8,\n{\n fn call(&self) -> &u8 {\n (self.func)(&self.data)\n }\n}\n\nfn do_it(data: &(u8, u16)) -> &u8 { &data.0 }\n\nfn main() {\n let clo = Closure { data: (0, 1), func: do_it };\n println!(\"{}\", clo.call());\n}\n```\nIf we try to naively desugar this code in the same way that we did in the\nlifetimes section, we run into some trouble:\n```rust,ignore\n// NOTE: `&'b data.0` and `'x: {` is not valid syntax!\nstruct Closure {\n data: (u8, u16),\n func: F,\n}\n\nimpl Closure\n // where F: Fn(&'??? (u8, u16)) -> &'??? u8,\n{\n fn call<'a>(&'a self) -> &'a u8 {\n (self.func)(&self.data)\n }\n}\n\nfn do_it<'b>(data: &'b (u8, u16)) -> &'b u8 { &'b data.0 }\n\nfn main() {\n 'x: {\n let clo = Closure { data: (0, 1), func: do_it };\n println!(\"{}\", clo.call());\n }\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Higher-Rank Trait Bounds", "heading_path": ["Higher-Rank Trait Bounds (HRTBs)"], "path": "hrtb.md", "url": "https://doc.rust-lang.org/nomicon/hrtb.html#higher-rank-trait-bounds-hrtbs", "has_code": true, "code_tags": ["rust", "rust,ignore"]}} {"id": "nomicon/hrtb.md#higher-rank-trait-bounds-hrtbs-1", "text": "The Rustonomicon › Higher-Rank Trait Bounds (HRTBs)\n\nHow on earth are we supposed to express the lifetimes on `F`'s trait bound? We\nneed to provide some lifetime there, but the lifetime we care about can't be\nnamed until we enter the body of `call`! Also, that isn't some fixed lifetime;\n`call` works with *any* lifetime `&self` happens to have at that point.\nThis job requires The Magic of Higher-Rank Trait Bounds (HRTBs). The way we\ndesugar this is as follows:\n```rust,ignore\nwhere for<'a> F: Fn(&'a (u8, u16)) -> &'a u8,\n```\nAlternatively:\n```rust,ignore\nwhere F: for<'a> Fn(&'a (u8, u16)) -> &'a u8,\n```\n(Where `Fn(a, b, c) -> d` is itself just sugar for the unstable *real* `Fn`\ntrait)\n`for<'a>` can be read as \"for all choices of `'a`\", and basically produces an\n*infinite list* of trait bounds that F must satisfy. Intense. There aren't many\nplaces outside of the `Fn` traits where we encounter HRTBs, and even for\nthose we have a nice magic sugar for the common cases.\nIn summary, we can rewrite the original code more explicitly as:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Higher-Rank Trait Bounds", "heading_path": ["Higher-Rank Trait Bounds (HRTBs)"], "path": "hrtb.md", "url": "https://doc.rust-lang.org/nomicon/hrtb.html#higher-rank-trait-bounds-hrtbs", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/hrtb.md#higher-rank-trait-bounds-hrtbs-2", "text": "The Rustonomicon › Higher-Rank Trait Bounds (HRTBs)\n\n```rust\nstruct Closure {\n data: (u8, u16),\n func: F,\n}\n\nimpl Closure\n where for<'a> F: Fn(&'a (u8, u16)) -> &'a u8,\n{\n fn call(&self) -> &u8 {\n (self.func)(&self.data)\n }\n}\n\nfn do_it(data: &(u8, u16)) -> &u8 { &data.0 }\n\nfn main() {\n let clo = Closure { data: (0, 1), func: do_it };\n println!(\"{}\", clo.call());\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Higher-Rank Trait Bounds", "heading_path": ["Higher-Rank Trait Bounds (HRTBs)"], "path": "hrtb.md", "url": "https://doc.rust-lang.org/nomicon/hrtb.html#higher-rank-trait-bounds-hrtbs", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/subtyping.md#subtyping-and-variance-0", "text": "The Rustonomicon › Subtyping and Variance\n\nRust uses lifetimes to track the relationships between borrows and ownership.\nHowever, a naive implementation of lifetimes would be either too restrictive,\nor permit undefined behavior.\nIn order to allow flexible usage of lifetimes\nwhile also preventing their misuse, Rust uses **subtyping** and **variance**.\nLet's start with an example.\n```rust\n// Note: debug expects two parameters with the *same* lifetime\nfn debug<'a>(a: &'a str, b: &'a str) {\n println!(\"a = {a:?} b = {b:?}\");\n}\n\nfn main() {\n let hello: &'static str = \"hello\";\n {\n let world = String::from(\"world\");\n let world = &world; // 'world has a shorter lifetime than 'static\n debug(hello, world);\n }\n}\n```\nIn a conservative implementation of lifetimes, since `hello` and `world` have different lifetimes,\nwe might see the following error:\n```text\nerror[E0308]: mismatched types\n --> src/main.rs:10:16\n |\n10 | debug(hello, world);\n | ^\n | |\n | expected `&'static str`, found struct `&'world str`\n```\nThis would be rather unfortunate. In this case,\nwhat we want is to accept any type that lives *at least as long* as `'world`.\nLet's try using subtyping with our lifetimes.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Subtyping and Variance", "heading_path": ["Subtyping and Variance"], "path": "subtyping.md", "url": "https://doc.rust-lang.org/nomicon/subtyping.html#subtyping-and-variance", "has_code": true, "code_tags": ["rust", "text"]}} {"id": "nomicon/subtyping.md#subtyping-1", "text": "The Rustonomicon › Subtyping and Variance › Subtyping\n\nSubtyping is the idea that one type can be used in place of another.\nLet's define that `Sub` is a subtype of `Super` (we'll be using the notation `Sub <: Super` throughout this chapter).\nWhat this is suggesting to us is that the set of *requirements* that `Super` defines\nare completely satisfied by `Sub`. `Sub` may then have more requirements.\nNow, in order to use subtyping with lifetimes, we need to define the requirement of a lifetime:\n`'a` defines a region of code.\nNow that we have a defined set of requirements for lifetimes, we can define how they relate to each other:\n`'long <: 'short` if and only if `'long` defines a region of code that **completely contains** `'short`.\n`'long` may define a region larger than `'short`, but that still fits our definition.\nAs we will see throughout the rest of this chapter,\nsubtyping is a lot more complicated and subtle than this,\nbut this simple rule is a very good 99% intuition.\nAnd unless you write unsafe code, the compiler will automatically handle all the corner cases for you.\nBut this is the Rustonomicon. We're writing unsafe code,\nso we need to understand how this stuff really works, and how we can mess it up.\nGoing back to our example above, we can say that `'static <: 'world`.\nFor now, let's also accept the idea that subtypes of lifetimes can be passed through references\n(more on this in Variance),\n_e.g._ `&'static str` is a subtype of `&'world str`, then we can \"downgrade\" `&'static str` into a `&'world str`.\nWith that, the example above will compile:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Subtyping and Variance", "heading_path": ["Subtyping and Variance", "Subtyping"], "path": "subtyping.md", "url": "https://doc.rust-lang.org/nomicon/subtyping.html#subtyping", "has_code": false, "code_tags": []}} {"id": "nomicon/subtyping.md#subtyping-2", "text": "The Rustonomicon › Subtyping and Variance › Subtyping\n\n```rust\nfn debug<'a>(a: &'a str, b: &'a str) {\n println!(\"a = {a:?} b = {b:?}\");\n}\n\nfn main() {\n let hello: &'static str = \"hello\";\n {\n let world = String::from(\"world\");\n let world = &world; // 'world has a shorter lifetime than 'static\n debug(hello, world); // hello silently downgrades from `&'static str` into `&'world str`\n }\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Subtyping and Variance", "heading_path": ["Subtyping and Variance", "Subtyping"], "path": "subtyping.md", "url": "https://doc.rust-lang.org/nomicon/subtyping.html#subtyping", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/subtyping.md#variance-3", "text": "The Rustonomicon › Subtyping and Variance › Variance\n\nAbove, we glossed over the fact that `'static <: 'b` implied that `&'static T <: &'b T`. This uses a property known as _variance_.\nIt's not always as simple as this example, though. To understand that, let's try to extend this example a bit:\n```rust,compile_fail,E0597\nfn assign(input: &mut T, val: T) {\n *input = val;\n}\n\nfn main() {\n let mut hello: &'static str = \"hello\";\n {\n let world = String::from(\"world\");\n assign(&mut hello, &world);\n }\n println!(\"{hello}\"); // use after free 😿\n}\n```\nIn `assign`, we are setting the `hello` reference to point to `world`.\nBut then `world` goes out of scope, before the later use of `hello` in the println!\nThis is a classic use-after-free bug!\nOur first instinct might be to blame the `assign` impl, but there's really nothing wrong here.\nIt shouldn't be surprising that we might want to assign a `T` into a `T`.\nThe problem is that we cannot assume `&'static str` can still be downgraded into `&'world str` to satisfy `T`, once it's behind a `&mut` reference.\nThis means that `&mut &'static str` **cannot** be a *subtype* of `&mut &'world str`,\neven if `'static` is a subtype of `'world`.\nVariance is the concept that Rust borrows to define relationships about subtypes through their generic parameters.\nNOTE: For convenience we will define a generic type `F` so\nthat we can easily talk about `T`. Hopefully this is clear in context.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Subtyping and Variance", "heading_path": ["Subtyping and Variance", "Variance"], "path": "subtyping.md", "url": "https://doc.rust-lang.org/nomicon/subtyping.html#variance", "has_code": true, "code_tags": ["rust,compile_fail,E0597"]}} {"id": "nomicon/subtyping.md#variance-4", "text": "The Rustonomicon › Subtyping and Variance › Variance\n\nThe type `F`'s *variance* is how the subtyping of its inputs affects the\nsubtyping of its outputs. There are three kinds of variance in Rust. Given two\ntypes `Sub` and `Super`, where `Sub` is a subtype of `Super`:\n* `F` is **covariant** if `F` is a subtype of `F` (the subtype property is passed through)\n* `F` is **contravariant** if `F` is a subtype of `F` (the subtype property is \"inverted\")\n* `F` is **invariant** otherwise (no subtyping relationship exists)\nIf we remember from the above examples,\nit was ok for us to treat `&'a T` as a subtype of `&'b T` if `'a <: 'b`,\ntherefore we can say that `&'a T` is *covariant* over `'a`.\nAlso, we saw that it was not ok for us to treat `&mut &'a T` as a subtype of `&mut &'b T`,\ntherefore we can say that `&mut T` is *invariant* over `T`\nHere is a table of some other generic types and their variances:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Subtyping and Variance", "heading_path": ["Subtyping and Variance", "Variance"], "path": "subtyping.md", "url": "https://doc.rust-lang.org/nomicon/subtyping.html#variance", "has_code": false, "code_tags": []}} {"id": "nomicon/subtyping.md#variance-5", "text": "The Rustonomicon › Subtyping and Variance › Variance\n\n| | 'a | T | U |\n|-----------------|:---------:|:-----------------:|:---------:|\n| `&'a T ` | covariant | covariant | |\n| `&'a mut T` | covariant | invariant | |\n| `Box` | | covariant | |\n| `Vec` | | covariant | |\n| `UnsafeCell` | | invariant | |\n| `Cell` | | invariant | |\n| `fn(T) -> U` | | **contra**variant | covariant |\n| `*const T` | | covariant | |\n| `*mut T` | | invariant | |\nSome of these can be explained simply in relation to the others:\n* `Vec` and all other owning pointers and collections follow the same logic as `Box`\n* `Cell` and all other interior mutability types follow the same logic as `UnsafeCell`\n* `UnsafeCell` having interior mutability gives it the same variance properties as `&mut T`\n* `*const T` follows the logic of `&T`\n* `*mut T` follows the logic of `&mut T` (or `UnsafeCell`)\nFor more types, see the \"Variance\" section on the reference.\nNOTE: the *only* source of contravariance in the language is the arguments to\na function, which is why it really doesn't come up much in practice. Invoking\ncontravariance involves higher-order programming with function pointers that\ntake references with specific lifetimes (as opposed to the usual \"any lifetime\",\nwhich gets into higher rank lifetimes, which work independently of subtyping).", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Subtyping and Variance", "heading_path": ["Subtyping and Variance", "Variance"], "path": "subtyping.md", "url": "https://doc.rust-lang.org/nomicon/subtyping.html#variance", "has_code": false, "code_tags": []}} {"id": "nomicon/subtyping.md#variance-6", "text": "The Rustonomicon › Subtyping and Variance › Variance\n\nNow that we have some more formal understanding of variance,\nlet's go through some more examples in more detail.\n```rust,compile_fail,E0597\nfn assign(input: &mut T, val: T) {\n *input = val;\n}\n\nfn main() {\n let mut hello: &'static str = \"hello\";\n {\n let world = String::from(\"world\");\n assign(&mut hello, &world);\n }\n println!(\"{hello}\");\n}\n```\nAnd what do we get when we run this?\n```text\nerror[E0597]: `world` does not live long enough\n --> src/main.rs:9:28\n |\n6 | let mut hello: &'static str = \"hello\";\n | ------------ type annotation requires that `world` is borrowed for `'static`\n...\n9 | assign(&mut hello, &world);\n | ^^^^^^ borrowed value does not live long enough\n10 | }\n | - `world` dropped here while still borrowed\n```\nGood, it doesn't compile! Let's break down what's happening here in detail.\nFirst let's look at the `assign` function:\n```rust\nfn assign(input: &mut T, val: T) {\n *input = val;\n}\n```\nAll it does is take a mutable reference and a value and overwrite the referent with it.\nWhat's important about this function is that it creates a type equality constraint. It\nclearly says in its signature the referent and the value must be the *exact same* type.\nMeanwhile, in the caller we pass in `&mut &'static str` and `&'world str`.\nBecause `&mut T` is invariant over `T`, the compiler concludes it can't apply any subtyping\nto the first argument, and so `T` must be exactly `&'static str`.\nThis is counter to the `&T` case:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Subtyping and Variance", "heading_path": ["Subtyping and Variance", "Variance"], "path": "subtyping.md", "url": "https://doc.rust-lang.org/nomicon/subtyping.html#variance", "has_code": true, "code_tags": ["rust", "rust,compile_fail,E0597", "text"]}} {"id": "nomicon/subtyping.md#variance-7", "text": "The Rustonomicon › Subtyping and Variance › Variance\n\n```rust\nfn debug(a: T, b: T) {\n println!(\"a = {a:?} b = {b:?}\");\n}\n```\nwhere similarly `a` and `b` must have the same type `T`.\nBut since `&'a T` *is* covariant over `'a`, we are allowed to perform subtyping.\nSo the compiler decides that `&'static str` can become `&'b str` if and only if\n`&'static str` is a subtype of `&'b str`, which will hold if `'static <: 'b`.\nThis is true, so the compiler is happy to continue compiling this code.\nAs it turns out, the argument for why it's ok for Box (and Vec, HashMap, etc.) to be covariant is pretty similar to the argument for why it's ok for lifetimes to be covariant: as soon as you try to stuff them in something like a mutable reference, they inherit invariance and you're prevented from doing anything bad.\nHowever Box makes it easier to focus on the by-value aspect of references that we partially glossed over.\nUnlike a lot of languages which allow values to be freely aliased at all times, Rust has a very strict rule: if you're allowed to mutate or move a value, you are guaranteed to be the only one with access to it.\nConsider the following code:\n```rust,ignore\nlet hello: Box<&'static str> = Box::new(\"hello\");\n\nlet mut world: Box<&'b str>;\nworld = hello;\n```\nThere is no problem at all with the fact that we have forgotten that `hello` was alive for `'static`,\nbecause as soon as we moved `hello` to a variable that only knew it was alive for `'b`,\n**we destroyed the only thing in the universe that remembered it lived for longer**!\nOnly one thing left to explain: function pointers.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Subtyping and Variance", "heading_path": ["Subtyping and Variance", "Variance"], "path": "subtyping.md", "url": "https://doc.rust-lang.org/nomicon/subtyping.html#variance", "has_code": true, "code_tags": ["rust", "rust,ignore"]}} {"id": "nomicon/subtyping.md#variance-8", "text": "The Rustonomicon › Subtyping and Variance › Variance\n\nTo see why `fn(T) -> U` should be covariant over `U`, consider the following signature:\n```rust,ignore\nfn get_str() -> &'a str;\n```\nThis function claims to produce a `str` bound by some lifetime `'a`. As such, it is perfectly valid to\nprovide a function with the following signature instead:\n```rust,ignore\nfn get_static() -> &'static str;\n```\nSo when the function is called, all its caller is expecting is a `&str` which lives at least the lifetime of `'a`,\nit doesn't matter if the value actually lives longer.\nHowever, the same logic does not apply to *arguments*. Consider trying to satisfy:\n```rust,ignore\nfn store_ref(&'a str);\n```\nwith:\n```rust,ignore\nfn store_static(&'static str);\n```\nThe first function can accept any string reference as long as it lives at least for `'a`,\nbut the second cannot accept a string reference that lives for any duration less than `'static`,\nwhich would cause a conflict.\nCovariance doesn't work here. But if we flip it around, it actually *does*\nwork! If we need a function that can handle `&'static str`, a function that can handle *any* reference lifetime\nwill surely work fine.\nLet's see this in practice", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Subtyping and Variance", "heading_path": ["Subtyping and Variance", "Variance"], "path": "subtyping.md", "url": "https://doc.rust-lang.org/nomicon/subtyping.html#variance", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/subtyping.md#variance-9", "text": "The Rustonomicon › Subtyping and Variance › Variance\n\n```rust,compile_fail\nthread_local! {\n pub static StaticVecs: RefCell> = RefCell::new(Vec::new());\n}\n\n/// saves the input given into a thread local `Vec<&'static str>`\nfn store(input: &'static str) {\n StaticVecs.with_borrow_mut(|v| v.push(input));\n}\n\n/// Calls the function with it's input (must have the same lifetime!)\nfn demo<'a>(input: &'a str, f: fn(&'a str)) {\n f(input);\n}\n\nfn main() {\n demo(\"hello\", store); // \"hello\" is 'static. Can call `store` fine\n\n {\n let smuggle = String::from(\"smuggle\");\n\n // `&smuggle` is not static. If we were to call `store` with `&smuggle`,\n // we would have pushed an invalid lifetime into the `StaticVecs`.\n // Therefore, `fn(&'static str)` cannot be a subtype of `fn(&'a str)`\n demo(&smuggle, store);\n }\n\n // use after free 😿\n StaticVecs.with_borrow(|v| println!(\"{v:?}\"));\n}\n```\nAnd that's why function types, unlike anything else in the language, are\n**contra**variant over their arguments.\nNow, this is all well and good for the types the standard library provides, but\nhow is variance determined for types that *you* define? A struct, informally\nspeaking, inherits the variance of its fields. If a struct `MyType`\nhas a generic argument `A` that is used in a field `a`, then MyType's variance\nover `A` is exactly `a`'s variance over `A`.\nHowever if `A` is used in multiple fields:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Subtyping and Variance", "heading_path": ["Subtyping and Variance", "Variance"], "path": "subtyping.md", "url": "https://doc.rust-lang.org/nomicon/subtyping.html#variance", "has_code": true, "code_tags": ["rust,compile_fail"]}} {"id": "nomicon/subtyping.md#variance-10", "text": "The Rustonomicon › Subtyping and Variance › Variance\n\n* If all uses of `A` are covariant, then MyType is covariant over `A`\n* If all uses of `A` are contravariant, then MyType is contravariant over `A`\n* Otherwise, MyType is invariant over `A`\n```rust\nuse std::cell::Cell;\n\nstruct MyType<'a, 'b, A: 'a, B: 'b, C, D, E, F, G, H, In, Out, Mixed> {\n a: &'a A, // covariant over 'a and A\n b: &'b mut B, // covariant over 'b and invariant over B\n\n c: *const C, // covariant over C\n d: *mut D, // invariant over D\n\n e: E, // covariant over E\n f: Vec, // covariant over F\n g: Cell, // invariant over G\n\n h1: H, // would also be covariant over H except...\n h2: Cell, // invariant over H, because invariance wins all conflicts\n\n i: fn(In) -> Out, // contravariant over In, covariant over Out\n\n k1: fn(Mixed) -> usize, // would be contravariant over Mixed except..\n k2: Mixed, // invariant over Mixed, because invariance wins all conflicts\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Subtyping and Variance", "heading_path": ["Subtyping and Variance", "Variance"], "path": "subtyping.md", "url": "https://doc.rust-lang.org/nomicon/subtyping.html#variance", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/dropck.md#drop-check-0", "text": "The Rustonomicon › Drop Check\n\nWe have seen how lifetimes provide us some fairly simple rules for ensuring\nthat we never read dangling references. However up to this point we have only ever\ninteracted with the _outlives_ relationship in an inclusive manner. That is,\nwhen we talked about `'a: 'b`, it was ok for `'a` to live _exactly_ as long as\n`'b`. At first glance, this seems to be a meaningless distinction. Nothing ever\ngets dropped at the same time as another, right? This is why we used the\nfollowing desugaring of `let` statements:\n```rust,ignore\nlet x;\nlet y;\n```\ndesugaring to:\n```rust,ignore\n{\n let x;\n {\n let y;\n }\n}\n```\nThere are some more complex situations which are not possible to desugar using\nscopes, but the order is still defined ‒ variables are dropped in the reverse\norder of their definition, fields of structs and tuples in order of their\ndefinition. There are some more details about order of drop in RFC 1857.\nLet's do this:\n```rust,ignore\nlet tuple = (vec![], vec![]);\n```\nThe left vector is dropped first. But does it mean the right one strictly\noutlives it in the eyes of the borrow checker? The answer to this question is\n_no_. The borrow checker could track fields of tuples separately, but it would\nstill be unable to decide what outlives what in case of vector elements, which\nare dropped manually via pure-library code the borrow checker doesn't\nunderstand.\nSo why do we care? We care because if the type system isn't careful, it could\naccidentally make dangling pointers. Consider the following simple program:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Drop Check", "heading_path": ["Drop Check"], "path": "dropck.md", "url": "https://doc.rust-lang.org/nomicon/dropck.html#drop-check", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/dropck.md#drop-check-1", "text": "The Rustonomicon › Drop Check\n\n```rust\nstruct Inspector<'a>(&'a u8);\n\nstruct World<'a> {\n inspector: Option>,\n days: Box,\n}\n\nfn main() {\n let mut world = World {\n inspector: None,\n days: Box::new(1),\n };\n world.inspector = Some(Inspector(&world.days));\n}\n```\nThis program is totally sound and compiles today. The fact that `days` does not\nstrictly outlive `inspector` doesn't matter. As long as the `inspector` is\nalive, so is `days`.\nHowever if we add a destructor, the program will no longer compile!\n```rust,compile_fail\nstruct Inspector<'a>(&'a u8);\n\nimpl<'a> Drop for Inspector<'a> {\n fn drop(&mut self) {\n println!(\"I was only {} days from retirement!\", self.0);\n }\n}\n\nstruct World<'a> {\n inspector: Option>,\n days: Box,\n}\n\nfn main() {\n let mut world = World {\n inspector: None,\n days: Box::new(1),\n };\n world.inspector = Some(Inspector(&world.days));\n // Let's say `days` happens to get dropped first.\n // Then when Inspector is dropped, it will try to read free'd memory!\n}\n```\n```text\nerror[E0597]: `world.days` does not live long enough\n --> src/main.rs:19:38\n |\n19 | world.inspector = Some(Inspector(&world.days));\n | ^^^^^^^^^^^ borrowed value does not live long enough\n...\n22 | }\n | -\n | |\n | `world.days` dropped here while still borrowed\n | borrow might be used here, when `world` is dropped and runs the destructor for type `World<'_>`\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Drop Check", "heading_path": ["Drop Check"], "path": "dropck.md", "url": "https://doc.rust-lang.org/nomicon/dropck.html#drop-check", "has_code": true, "code_tags": ["rust", "rust,compile_fail", "text"]}} {"id": "nomicon/dropck.md#drop-check-2", "text": "The Rustonomicon › Drop Check\n\nYou can try changing the order of fields or use a tuple instead of the struct,\nit'll still not compile.\nImplementing `Drop` lets the `Inspector` execute some arbitrary code during its\ndeath. This means it can potentially observe that types that are supposed to\nlive as long as it does actually were destroyed first.\nInterestingly, only generic types need to worry about this. If they aren't\ngeneric, then the only lifetimes they can harbor are `'static`, which will truly\nlive _forever_. This is why this problem is referred to as _sound generic drop_.\nSound generic drop is enforced by the _drop checker_. As of this writing, some\nof the finer details of how the drop checker (also called dropck) validates\ntypes is totally up in the air. However The Big Rule is the subtlety that we\nhave focused on this whole section:\n**For a generic type to soundly implement drop, its generics arguments must\nstrictly outlive it.**\nObeying this rule is (usually) necessary to satisfy the borrow\nchecker; obeying it is sufficient but not necessary to be\nsound. That is, if your type obeys this rule then it's definitely\nsound to drop.\nThe reason that it is not always necessary to satisfy the above rule\nis that some Drop implementations will not access borrowed data even\nthough their type gives them the capability for such access, or because we know\nthe specific drop order and the borrowed data is still fine even if the borrow\nchecker doesn't know that.\nFor example, this variant of the above `Inspector` example will never\naccess borrowed data:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Drop Check", "heading_path": ["Drop Check"], "path": "dropck.md", "url": "https://doc.rust-lang.org/nomicon/dropck.html#drop-check", "has_code": false, "code_tags": []}} {"id": "nomicon/dropck.md#drop-check-3", "text": "The Rustonomicon › Drop Check\n\n```rust,compile_fail\nstruct Inspector<'a>(&'a u8, &'static str);\n\nimpl<'a> Drop for Inspector<'a> {\n fn drop(&mut self) {\n println!(\"Inspector(_, {}) knows when *not* to inspect.\", self.1);\n }\n}\n\nstruct World<'a> {\n inspector: Option>,\n days: Box,\n}\n\nfn main() {\n let mut world = World {\n inspector: None,\n days: Box::new(1),\n };\n world.inspector = Some(Inspector(&world.days, \"gadget\"));\n // Let's say `days` happens to get dropped first.\n // Even when Inspector is dropped, its destructor will not access the\n // borrowed `days`.\n}\n```\nLikewise, this variant will also never access borrowed data:\n```rust,compile_fail\nstruct Inspector(T, &'static str);\n\nimpl Drop for Inspector {\n fn drop(&mut self) {\n println!(\"Inspector(_, {}) knows when *not* to inspect.\", self.1);\n }\n}\n\nstruct World {\n inspector: Option>,\n days: Box,\n}\n\nfn main() {\n let mut world = World {\n inspector: None,\n days: Box::new(1),\n };\n world.inspector = Some(Inspector(&world.days, \"gadget\"));\n // Let's say `days` happens to get dropped first.\n // Even when Inspector is dropped, its destructor will not access the\n // borrowed `days`.\n}\n```\nHowever, _both_ of the above variants are rejected by the borrow\nchecker during the analysis of `fn main`, saying that `days` does not\nlive long enough.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Drop Check", "heading_path": ["Drop Check"], "path": "dropck.md", "url": "https://doc.rust-lang.org/nomicon/dropck.html#drop-check", "has_code": true, "code_tags": ["rust,compile_fail"]}} {"id": "nomicon/dropck.md#drop-check-4", "text": "The Rustonomicon › Drop Check\n\nThe reason is that the borrow checking analysis of `main` does not\nknow about the internals of each `Inspector`'s `Drop` implementation. As\nfar as the borrow checker knows while it is analyzing `main`, the body\nof an inspector's destructor might access that borrowed data.\nTherefore, the drop checker forces all borrowed data in a value to\nstrictly outlive that value.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Drop Check", "heading_path": ["Drop Check"], "path": "dropck.md", "url": "https://doc.rust-lang.org/nomicon/dropck.html#drop-check", "has_code": false, "code_tags": []}} {"id": "nomicon/dropck.md#an-escape-hatch-5", "text": "The Rustonomicon › Drop Check › An Escape Hatch\n\nThe precise rules that govern drop checking may be less restrictive in\nthe future.\nThe current analysis is deliberately conservative; it forces all\nborrowed data in a value to outlive that value, which is certainly sound.\nFuture versions of the language may make the analysis more precise, to\nreduce the number of cases where sound code is rejected as unsafe.\nThis would help address cases such as the two `Inspector`s above that\nknow not to inspect during destruction.\nIn the meantime, there is an unstable attribute that one can use to\nassert (unsafely) that a generic type's destructor is _guaranteed_ to\nnot access any expired data, even if its type gives it the capability\nto do so.\nThat attribute is called `may_dangle` and was introduced in RFC 1327.\nTo deploy it on the `Inspector` from above, we would write:\n```rust\n#![feature(dropck_eyepatch)]\n\nstruct Inspector<'a>(&'a u8, &'static str);\n\nunsafe impl<#[may_dangle] 'a> Drop for Inspector<'a> {\n fn drop(&mut self) {\n println!(\"Inspector(_, {}) knows when *not* to inspect.\", self.1);\n }\n}\n\nstruct World<'a> {\n days: Box,\n inspector: Option>,\n}\n\nfn main() {\n let mut world = World {\n inspector: None,\n days: Box::new(1),\n };\n world.inspector = Some(Inspector(&world.days, \"gadget\"));\n}\n```\nUse of this attribute requires the `Drop` impl to be marked `unsafe` because the\ncompiler is not checking the implicit assertion that no potentially expired data\n(e.g. `self.0` above) is accessed.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Drop Check", "heading_path": ["Drop Check", "An Escape Hatch"], "path": "dropck.md", "url": "https://doc.rust-lang.org/nomicon/dropck.html#an-escape-hatch", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/dropck.md#an-escape-hatch-6", "text": "The Rustonomicon › Drop Check › An Escape Hatch\n\nThe attribute can be applied to any number of lifetime and type parameters. In\nthe following example, we assert that we access no data behind a reference of\nlifetime `'b` and that the only uses of `T` will be moves or drops, but omit\nthe attribute from `'a` and `U`, because we do access data with that lifetime\nand that type:\n```rust\n#![feature(dropck_eyepatch)]\nuse std::fmt::Display;\n\nstruct Inspector<'a, 'b, T, U: Display>(&'a u8, &'b u8, T, U);\n\nunsafe impl<'a, #[may_dangle] 'b, #[may_dangle] T, U: Display> Drop for Inspector<'a, 'b, T, U> {\n fn drop(&mut self) {\n println!(\"Inspector({}, _, _, {})\", self.0, self.3);\n }\n}\n```\nIt is sometimes obvious that no such access can occur, like the case above.\nHowever, when dealing with a generic type parameter, such access can\noccur indirectly. Examples of such indirect access are:\n- invoking a callback,\n- via a trait method call.\n(Future changes to the language, such as impl specialization, may add\nother avenues for such indirect access.)\nHere is an example of invoking a callback:\n```rust\nstruct Inspector(T, &'static str, Box fn(&'r T) -> String>);\n\nimpl Drop for Inspector {\n fn drop(&mut self) {\n // The `self.2` call could access a borrow e.g. if `T` is `&'a _`.\n println!(\"Inspector({}, {}) unwittingly inspects expired data.\",\n (self.2)(&self.0), self.1);\n }\n}\n```\nHere is an example of a trait method call:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Drop Check", "heading_path": ["Drop Check", "An Escape Hatch"], "path": "dropck.md", "url": "https://doc.rust-lang.org/nomicon/dropck.html#an-escape-hatch", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/dropck.md#an-escape-hatch-7", "text": "The Rustonomicon › Drop Check › An Escape Hatch\n\n```rust\nuse std::fmt;\n\nstruct Inspector(T, &'static str);\n\nimpl Drop for Inspector {\n fn drop(&mut self) {\n // There is a hidden call to `::fmt` below, which\n // could access a borrow e.g. if `T` is `&'a _`\n println!(\"Inspector({}, {}) unwittingly inspects expired data.\",\n self.0, self.1);\n }\n}\n```\nAnd of course, all of these accesses could be further hidden within\nsome other method invoked by the destructor, rather than being written\ndirectly within it.\nIn all of the above cases where the `&'a u8` is accessed in the\ndestructor, adding the `#[may_dangle]`\nattribute makes the type vulnerable to misuse that the borrow\nchecker will not catch, inviting havoc. It is better to avoid adding\nthe attribute.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Drop Check", "heading_path": ["Drop Check", "An Escape Hatch"], "path": "dropck.md", "url": "https://doc.rust-lang.org/nomicon/dropck.html#an-escape-hatch", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/dropck.md#a-related-side-note-about-drop-order-8", "text": "The Rustonomicon › Drop Check › A related side note about drop order\n\nWhile the drop order of fields inside a struct is defined, relying on it is\nfragile and subtle. When the order matters, it is better to use the\n[`ManuallyDrop`] wrapper.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Drop Check", "heading_path": ["Drop Check", "A related side note about drop order"], "path": "dropck.md", "url": "https://doc.rust-lang.org/nomicon/dropck.html#a-related-side-note-about-drop-order", "has_code": false, "code_tags": []}} {"id": "nomicon/dropck.md#is-that-all-about-drop-checker-9", "text": "The Rustonomicon › Drop Check › Is that all about drop checker?\n\nIt turns out that when writing unsafe code, we generally don't need to\nworry at all about doing the right thing for the drop checker. However there\nis one special case that you need to worry about, which we will look at in\nthe next section.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Drop Check", "heading_path": ["Drop Check", "Is that all about drop checker?"], "path": "dropck.md", "url": "https://doc.rust-lang.org/nomicon/dropck.html#is-that-all-about-drop-checker", "has_code": false, "code_tags": []}} {"id": "nomicon/phantom-data.md#phantomdata-0", "text": "The Rustonomicon › PhantomData\n\nWhen working with unsafe code, we can often end up in a situation where\ntypes or lifetimes are logically associated with a struct, but not actually\npart of a field. This most commonly occurs with lifetimes. For instance, the\n`Iter` for `&'a [T]` is (approximately) defined as follows:\n```rust,compile_fail\nstruct Iter<'a, T: 'a> {\n ptr: *const T,\n end: *const T,\n}\n```\nHowever because `'a` is unused within the struct's body, it's *unbounded*.\nBecause of the troubles this has historically caused,\nunbounded lifetimes and types are *forbidden* in struct definitions.\nTherefore we must somehow refer to these types in the body.\nCorrectly doing this is necessary to have correct variance and drop checking.\nWe do this using `PhantomData`, which is a special marker type. `PhantomData`\nconsumes no space, but simulates a field of the given type for the purpose of\nstatic analysis. This was deemed to be less error-prone than explicitly telling\nthe type-system the kind of variance that you want, while also providing other\nuseful things such as auto traits and the information needed by drop check.\nIter logically contains a bunch of `&'a T`s, so this is exactly what we tell\nthe `PhantomData` to simulate:\n```rust\nuse std::marker;\n\nstruct Iter<'a, T: 'a> {\n ptr: *const T,\n end: *const T,\n _marker: marker::PhantomData<&'a T>,\n}\n```\nand that's it. The lifetime will be bounded, and your iterator will be covariant\nover `'a` and `T`. Everything Just Works.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "PhantomData", "heading_path": ["PhantomData"], "path": "phantom-data.md", "url": "https://doc.rust-lang.org/nomicon/phantom-data.html#phantomdata", "has_code": true, "code_tags": ["rust", "rust,compile_fail"]}} {"id": "nomicon/phantom-data.md#generic-parameters-and-drop-checking-1", "text": "The Rustonomicon › PhantomData › Generic parameters and drop-checking\n\nIn the past, there used to be another thing to take into consideration.\nThis very documentation used to say:\nAnother important example is Vec, which is (approximately) defined as follows:\n```rust\nstruct Vec {\n data: *const T, // *const for variance!\n len: usize,\n cap: usize,\n}\n```\nUnlike the previous example, it *appears* that everything is exactly as we\nwant. Every generic argument to Vec shows up in at least one field.\nGood to go!\nNope.\nThe drop checker will generously determine that `Vec` does not own any values\nof type T. This will in turn make it conclude that it doesn't need to worry\nabout Vec dropping any T's in its destructor for determining drop check\nsoundness. This will in turn allow people to create unsoundness using\nVec's destructor.\nIn order to tell the drop checker that we *do* own values of type T, and\ntherefore may drop some T's when *we* drop, we must add an extra `PhantomData`\nsaying exactly that:\n```rust\nuse std::marker;\n\nstruct Vec {\n data: *const T, // *const for variance!\n len: usize,\n cap: usize,\n _owns_T: marker::PhantomData,\n}\n```\nBut ever since RFC 1238,\n**this is no longer true nor necessary**.\nIf you were to write:\n```rust\nstruct Vec {\n data: *const T, // `*const` for variance!\n len: usize,\n cap: usize,\n}\n\nimpl Drop for Vec { /* … */ }\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "PhantomData", "heading_path": ["PhantomData", "Generic parameters and drop-checking"], "path": "phantom-data.md", "url": "https://doc.rust-lang.org/nomicon/phantom-data.html#generic-parameters-and-drop-checking", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/phantom-data.md#generic-parameters-and-drop-checking-2", "text": "The Rustonomicon › PhantomData › Generic parameters and drop-checking\n\nthen the existence of that `impl Drop for Vec` makes it so Rust will consider\nthat that `Vec` _owns_ values of type `T` (more precisely: may use values of type `T`\nin its `Drop` implementation), and Rust will thus not allow them to _dangle_ should a\n`Vec` be dropped.\nWhen a type already has a `Drop impl`, **adding an extra `_owns_T: PhantomData` field\nis thus _superfluous_ and accomplishes nothing**, dropck-wise (it still affects variance\nand auto-traits).\n - (advanced edge case: if the type containing the `PhantomData` has no `Drop` impl at all,\n but still has drop glue (by having _another_ field with drop glue), then the\n dropck/`#[may_dangle]` considerations mentioned herein do apply as well: a `PhantomData`\n field will then require `T` to be droppable whenever the containing type goes out of scope).\n___\nBut this situation can sometimes lead to overly restrictive code. That's why the\nstandard library uses an unstable and `unsafe` attribute to opt back into the old\n\"unchecked\" drop-checking behavior, that this very documentation warned about: the\n`#[may_dangle]` attribute.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "PhantomData", "heading_path": ["PhantomData", "Generic parameters and drop-checking"], "path": "phantom-data.md", "url": "https://doc.rust-lang.org/nomicon/phantom-data.html#generic-parameters-and-drop-checking", "has_code": false, "code_tags": []}} {"id": "nomicon/phantom-data.md#an-exception-the-special-case-of-the-standard-library-and-its-unstable-may_dangle-3", "text": "The Rustonomicon › PhantomData › Generic parameters and drop-checking › An exception: the special case of the standard library and its unstable `#[may_dangle]`\n\nThis section can be skipped if you are only writing your own library code; but if you are\ncurious about what the standard library does with the actual `Vec` definition, you'll notice\nthat it still needs to use a `_owns_T: PhantomData` field for soundness.\n
Click here to see why\nConsider the following example:\n```rust\nfn main() {\n let mut v: Vec<&str> = Vec::new();\n let s: String = \"Short-lived\".into();\n v.push(&s);\n drop(s);\n} // <- `v` is dropped here\n```\nwith a classical `impl Drop for Vec {` definition, the above [is denied].\nIndeed, in this case we have a `Vec` vector of `'s`-lived references\nto `str`ings, but in the case of `let s: String`, it is dropped before the `Vec` is, and\nthus `'s` **is expired** by the time the `Vec` is dropped, and the\n`impl<'s> Drop for Vec<&'s str> {` is used.\nThis means that if such `Drop` were to be used, it would be dealing with an _expired_, or\n_dangling_ lifetime `'s`. But this is contrary to Rust principles, where by default all\nRust references involved in a function signature are non-dangling and valid to dereference.\nHence why Rust has to conservatively deny this snippet.\nAnd yet, in the case of the real `Vec`, the `Drop` impl does not care about `&'s str`,\n_since it has no drop glue of its own_: it only wants to deallocate the backing buffer.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "PhantomData", "heading_path": ["PhantomData", "Generic parameters and drop-checking", "An exception: the special case of the standard library and its unstable `#[may_dangle]`"], "path": "phantom-data.md", "url": "https://doc.rust-lang.org/nomicon/phantom-data.html#an-exception-the-special-case-of-the-standard-library-and-its-unstable-may_dangle", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/phantom-data.md#an-exception-the-special-case-of-the-standard-library-and-its-unstable-may_dangle-4", "text": "The Rustonomicon › PhantomData › Generic parameters and drop-checking › An exception: the special case of the standard library and its unstable `#[may_dangle]`\n\nIn other words, it would be nice if the above snippet was somehow accepted, by special\ncasing `Vec`, or by relying on some special property of `Vec`: `Vec` could try to\n_promise not to use the `&'s str`s it holds when being dropped_.\nThis is the kind of `unsafe` promise that can be expressed with `#[may_dangle]`:\n```rust ,ignore\nunsafe impl<#[may_dangle] 's> Drop for Vec<&'s str> { /* … */ }\n```\nor, more generally:\n```rust ,ignore\nunsafe impl<#[may_dangle] T> Drop for Vec { /* … */ }\n```\nis the `unsafe` way to opt out of this conservative assumption that Rust's drop\nchecker makes about type parameters of a dropped instance not being allowed to dangle.\nAnd when this is done, such as in the standard library, we need to be careful in the\ncase where `T` has drop glue of its own. In this instance, imagine replacing the\n`&'s str`s with a `struct PrintOnDrop<'s> /* = */ (&'s str);` which would have a\n`Drop` impl wherein the inner `&'s str` would be dereferenced and printed to the screen.\nIndeed, `Drop for Vec {`, before deallocating the backing buffer, does have to transitively\ndrop each `T` item when it has drop glue; in the case of `PrintOnDrop<'s>`, it means that\n`Drop for Vec>` has to transitively drop the `PrintOnDrop<'s>`s elements before\ndeallocating the backing buffer.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "PhantomData", "heading_path": ["PhantomData", "Generic parameters and drop-checking", "An exception: the special case of the standard library and its unstable `#[may_dangle]`"], "path": "phantom-data.md", "url": "https://doc.rust-lang.org/nomicon/phantom-data.html#an-exception-the-special-case-of-the-standard-library-and-its-unstable-may_dangle", "has_code": true, "code_tags": ["rust ,ignore"]}} {"id": "nomicon/phantom-data.md#an-exception-the-special-case-of-the-standard-library-and-its-unstable-may_dangle-5", "text": "The Rustonomicon › PhantomData › Generic parameters and drop-checking › An exception: the special case of the standard library and its unstable `#[may_dangle]`\n\nSo when we said that `'s` `#[may_dangle]`, it was an excessively loose statement. We'd rather want\nto say: \"`'s` may dangle provided it not be involved in some transitive drop glue\". Or, more generally,\n\"`T` may dangle provided it not be involved in some transitive drop glue\". This \"exception to the\nexception\" is a pervasive situation whenever **we own a `T`**. That's why Rust's `#[may_dangle]` is\nsmart enough to know of this opt-out, and will thus be disabled _when the generic parameter is held\nin an owned fashion_ by the fields of the struct.\nHence why the standard library ends up with:\n```rust\n// we pinky-swear not to use `T` when dropping a `Vec`…\nunsafe impl<#[may_dangle] T> Drop for Vec {\n fn drop(&mut self) {\n unsafe {\n if mem::needs_drop::() {\n /* … except here, that is, … */\n ptr::drop_in_place::<[T]>(/* … */);\n }\n // …\n dealloc(/* … */)\n // …\n }\n }\n}\n\nstruct Vec {\n // … except for the fact that a `Vec` owns `T` items and\n // may thus be dropping `T` items on drop!\n _owns_T: core::marker::PhantomData,\n\n ptr: *const T, // `*const` for variance (but this does not express ownership of a `T` *per se*)\n len: usize,\n cap: usize,\n}\n```\n
\n___\nRaw pointers that own an allocation is such a pervasive pattern that the\nstandard library made a utility for itself called `Unique` which:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "PhantomData", "heading_path": ["PhantomData", "Generic parameters and drop-checking", "An exception: the special case of the standard library and its unstable `#[may_dangle]`"], "path": "phantom-data.md", "url": "https://doc.rust-lang.org/nomicon/phantom-data.html#an-exception-the-special-case-of-the-standard-library-and-its-unstable-may_dangle", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/phantom-data.md#an-exception-the-special-case-of-the-standard-library-and-its-unstable-may_dangle-6", "text": "The Rustonomicon › PhantomData › Generic parameters and drop-checking › An exception: the special case of the standard library and its unstable `#[may_dangle]`\n\n* wraps a `*const T` for variance\n* includes a `PhantomData`\n* auto-derives `Send`/`Sync` as if T was contained\n* marks the pointer as `NonZero` for the null-pointer optimization", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "PhantomData", "heading_path": ["PhantomData", "Generic parameters and drop-checking", "An exception: the special case of the standard library and its unstable `#[may_dangle]`"], "path": "phantom-data.md", "url": "https://doc.rust-lang.org/nomicon/phantom-data.html#an-exception-the-special-case-of-the-standard-library-and-its-unstable-may_dangle", "has_code": false, "code_tags": []}} {"id": "nomicon/phantom-data.md#table-of-phantomdata-patterns-7", "text": "The Rustonomicon › PhantomData › Table of `PhantomData` patterns\n\nHere’s a table of all the wonderful ways `PhantomData` could be used:\n| Phantom type | variance of `'a` | variance of `T` | `Send`/`Sync`
(or lack thereof) | dangling `'a` or `T` in drop glue
(_e.g._, `#[may_dangle] Drop`) |\n|-----------------------------|:----------------:|:-----------------:|:-----------------------------------------:|:------------------------------------------------:|\n| `PhantomData` | - | **cov**ariant | inherited | disallowed (\"owns `T`\") |\n| `PhantomData<&'a T>` | **cov**ariant | **cov**ariant | `Send + Sync`
requires
`T : Sync` | allowed |\n| `PhantomData<&'a mut T>` | **cov**ariant | **inv**ariant | inherited | allowed |\n| `PhantomData<*const T>` | - | **cov**ariant | `!Send + !Sync` | allowed |\n| `PhantomData<*mut T>` | - | **inv**ariant | `!Send + !Sync` | allowed |\n| `PhantomData` | - | **contra**variant | `Send + Sync` | allowed |\n| `PhantomData T>` | - | **cov**ariant | `Send + Sync` | allowed |\n| `PhantomData T>` | - | **inv**ariant | `Send + Sync` | allowed |\n| `PhantomData>` | **inv**ariant | - | `Send + !Sync` | allowed |", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "PhantomData", "heading_path": ["PhantomData", "Table of `PhantomData` patterns"], "path": "phantom-data.md", "url": "https://doc.rust-lang.org/nomicon/phantom-data.html#table-of-phantomdata-patterns", "has_code": false, "code_tags": []}} {"id": "nomicon/phantom-data.md#table-of-phantomdata-patterns-8", "text": "The Rustonomicon › PhantomData › Table of `PhantomData` patterns\n\n- Note: opting out of the `Unpin` auto-trait requires the dedicated [`PhantomPinned`] type instead.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "PhantomData", "heading_path": ["PhantomData", "Table of `PhantomData` patterns"], "path": "phantom-data.md", "url": "https://doc.rust-lang.org/nomicon/phantom-data.html#table-of-phantomdata-patterns", "has_code": false, "code_tags": []}} {"id": "nomicon/borrow-splitting.md#splitting-borrows-0", "text": "The Rustonomicon › Splitting Borrows\n\nThe mutual exclusion property of mutable references can be very limiting when\nworking with a composite structure. The borrow checker (a.k.a. borrowck)\nunderstands some basic stuff, but will fall over pretty easily. It does\nunderstand structs sufficiently to know that it's possible to borrow disjoint\nfields of a struct simultaneously. So this works today:\n```rust\nstruct Foo {\n a: i32,\n b: i32,\n c: i32,\n}\n\nlet mut x = Foo {a: 0, b: 0, c: 0};\nlet a = &mut x.a;\nlet b = &mut x.b;\nlet c = &x.c;\n*b += 1;\nlet c2 = &x.c;\n*a += 10;\nprintln!(\"{} {} {} {}\", a, b, c, c2);\n```\nHowever borrowck doesn't understand arrays or slices in any way, so this doesn't\nwork:\n```rust,compile_fail\nlet mut x = [1, 2, 3];\nlet a = &mut x[0];\nlet b = &mut x[1];\nprintln!(\"{} {}\", a, b);\n```\n```text\nerror[E0499]: cannot borrow `x[..]` as mutable more than once at a time\n --> src/lib.rs:4:18\n |\n3 | let a = &mut x[0];\n | ---- first mutable borrow occurs here\n4 | let b = &mut x[1];\n | ^^^^ second mutable borrow occurs here\n5 | println!(\"{} {}\", a, b);\n6 | }\n | - first borrow ends here\n\nerror: aborting due to previous error\n```\nWhile it was plausible that borrowck could understand this simple case, it's\npretty clearly hopeless for borrowck to understand disjointness in general\ncontainer types like a tree, especially if distinct keys actually *do* map\nto the same value.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Splitting Borrows", "heading_path": ["Splitting Borrows"], "path": "borrow-splitting.md", "url": "https://doc.rust-lang.org/nomicon/borrow-splitting.html#splitting-borrows", "has_code": true, "code_tags": ["rust", "rust,compile_fail", "text"]}} {"id": "nomicon/borrow-splitting.md#splitting-borrows-1", "text": "The Rustonomicon › Splitting Borrows\n\nIn order to \"teach\" borrowck that what we're doing is ok, we need to drop down\nto unsafe code. For instance, mutable slices expose a `split_at_mut` function\nthat consumes the slice and returns two mutable slices. One for everything to\nthe left of the index, and one for everything to the right. Intuitively we know\nthis is safe because the slices don't overlap, and therefore alias. However\nthe implementation requires some unsafety:\n```rust\npub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {\n let len = self.len();\n let ptr = self.as_mut_ptr();\n\n unsafe {\n assert!(mid <= len);\n\n (from_raw_parts_mut(ptr, mid),\n from_raw_parts_mut(ptr.add(mid), len - mid))\n }\n}\n```\nThis is actually a bit subtle. So as to avoid ever making two `&mut`'s to the\nsame value, we explicitly construct brand-new slices through raw pointers.\nHowever more subtle is how iterators that yield mutable references work.\nThe iterator trait is defined as follows:\n```rust\ntrait Iterator {\n type Item;\n\n fn next(&mut self) -> Option;\n}\n```\nGiven this definition, Self::Item has *no* connection to `self`. This means that\nwe can call `next` several times in a row, and hold onto all the results\n*concurrently*. This is perfectly fine for by-value iterators, which have\nexactly these semantics. It's also actually fine for shared references, as they\nadmit arbitrarily many references to the same thing (although the iterator needs\nto be a separate object from the thing being shared).\nBut mutable references make this a mess. At first glance, they might seem\ncompletely incompatible with this API, as it would produce multiple mutable\nreferences to the same object!", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Splitting Borrows", "heading_path": ["Splitting Borrows"], "path": "borrow-splitting.md", "url": "https://doc.rust-lang.org/nomicon/borrow-splitting.html#splitting-borrows", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/borrow-splitting.md#splitting-borrows-2", "text": "The Rustonomicon › Splitting Borrows\n\nHowever it actually *does* work, exactly because iterators are one-shot objects.\nEverything an IterMut yields will be yielded at most once, so we don't\nactually ever yield multiple mutable references to the same piece of data.\nPerhaps surprisingly, mutable iterators don't require unsafe code to be\nimplemented for many types!\nFor instance here's a singly linked list:\n```rust\ntype Link = Option>>;\n\nstruct Node {\n elem: T,\n next: Link,\n}\n\npub struct LinkedList {\n head: Link,\n}\n\npub struct IterMut<'a, T: 'a>(Option<&'a mut Node>);\n\nimpl LinkedList {\n fn iter_mut(&mut self) -> IterMut {\n IterMut(self.head.as_mut().map(|node| &mut **node))\n }\n}\n\nimpl<'a, T> Iterator for IterMut<'a, T> {\n type Item = &'a mut T;\n\n fn next(&mut self) -> Option {\n self.0.take().map(|node| {\n self.0 = node.next.as_mut().map(|node| &mut **node);\n &mut node.elem\n })\n }\n}\n```\nHere's a mutable slice:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Splitting Borrows", "heading_path": ["Splitting Borrows"], "path": "borrow-splitting.md", "url": "https://doc.rust-lang.org/nomicon/borrow-splitting.html#splitting-borrows", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/borrow-splitting.md#splitting-borrows-3", "text": "The Rustonomicon › Splitting Borrows\n\n```rust\nuse std::mem;\n\npub struct IterMut<'a, T: 'a>(&'a mut[T]);\n\nimpl<'a, T> Iterator for IterMut<'a, T> {\n type Item = &'a mut T;\n\n fn next(&mut self) -> Option {\n let slice = mem::take(&mut self.0);\n if slice.is_empty() { return None; }\n\n let (l, r) = slice.split_at_mut(1);\n self.0 = r;\n l.get_mut(0)\n }\n}\n\nimpl<'a, T> DoubleEndedIterator for IterMut<'a, T> {\n fn next_back(&mut self) -> Option {\n let slice = mem::take(&mut self.0);\n if slice.is_empty() { return None; }\n\n let new_len = slice.len() - 1;\n let (l, r) = slice.split_at_mut(new_len);\n self.0 = l;\n r.get_mut(0)\n }\n}\n```\nAnd here's a binary tree:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Splitting Borrows", "heading_path": ["Splitting Borrows"], "path": "borrow-splitting.md", "url": "https://doc.rust-lang.org/nomicon/borrow-splitting.html#splitting-borrows", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/borrow-splitting.md#splitting-borrows-4", "text": "The Rustonomicon › Splitting Borrows\n\n```rust\nuse std::collections::VecDeque;\n\ntype Link = Option>>;\n\nstruct Node {\n elem: T,\n left: Link,\n right: Link,\n}\n\npub struct Tree {\n root: Link,\n}\n\nstruct NodeIterMut<'a, T: 'a> {\n elem: Option<&'a mut T>,\n left: Option<&'a mut Node>,\n right: Option<&'a mut Node>,\n}\n\nenum State<'a, T: 'a> {\n Elem(&'a mut T),\n Node(&'a mut Node),\n}\n\npub struct IterMut<'a, T: 'a>(VecDeque>);\n\nimpl Tree {\n pub fn iter_mut(&mut self) -> IterMut {\n let mut deque = VecDeque::new();\n if let Some(root) = self.root.as_mut() {\n deque.push_front(root.iter_mut());\n }\n IterMut(deque)\n }\n}\n\nimpl Node {\n pub fn iter_mut(&mut self) -> NodeIterMut {\n NodeIterMut {\n elem: Some(&mut self.elem),\n left: self.left.as_deref_mut(),\n right: self.right.as_deref_mut(),\n }\n }\n}\n\nimpl<'a, T> Iterator for NodeIterMut<'a, T> {\n type Item = State<'a, T>;\n\n fn next(&mut self) -> Option {\n self.left.take().map(State::Node).or_else(|| {\n self.elem\n .take()\n .map(State::Elem)\n .or_else(|| self.right.take().map(State::Node))\n })\n }\n}\n\nimpl<'a, T> DoubleEndedIterator for NodeIterMut<'a, T> {\n fn next_back(&mut self) -> Option {\n self.right.take().map(State::Node).or_else(|| {\n self.elem\n .take()\n .map(State::Elem)\n .or_else(|| self.left.take().map(State::Node))\n })\n }\n}\n\nimpl<'a, T> Iterator for IterMut<'a, T> {\n type Item = &'a mut T;\n fn next(&mut self) -> Option {\n loop {\n match self.0.front_mut().and_then(Iterator::next) {\n Some(State::Elem(elem)) => return Some(elem),\n Some(State::Node(node)) => self.0.push_front(node.iter_mut()),\n None => {\n self.0.pop_front()?;\n }\n }\n }\n }\n}\n\nimpl<'a, T> DoubleEndedIterator for IterMut<'a, T> {\n fn next_back(&mut self) -> Option {\n loop {\n match self.0.back_mut().and_then(DoubleEndedIterator::next_back) {\n Some(State::Elem(elem)) => return Some(elem),\n Some(State::Node(node)) => self.0.push_back(node.iter_mut()),\n None => {\n self.0.pop_back()?;\n }\n }\n }\n }\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Splitting Borrows", "heading_path": ["Splitting Borrows"], "path": "borrow-splitting.md", "url": "https://doc.rust-lang.org/nomicon/borrow-splitting.html#splitting-borrows", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/borrow-splitting.md#splitting-borrows-5", "text": "The Rustonomicon › Splitting Borrows\n\nAll of these are completely safe and work on stable Rust! This ultimately\nfalls out of the simple struct case we saw before: Rust understands that you\ncan safely split a mutable reference into subfields. We can then encode\npermanently consuming a reference via Options (or in the case of slices,\nreplacing with an empty slice).", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Splitting Borrows", "heading_path": ["Splitting Borrows"], "path": "borrow-splitting.md", "url": "https://doc.rust-lang.org/nomicon/borrow-splitting.html#splitting-borrows", "has_code": false, "code_tags": []}} {"id": "nomicon/conversions.md#type-conversions-0", "text": "The Rustonomicon › Type Conversions\n\nAt the end of the day, everything is just a pile of bits somewhere, and type\nsystems are just there to help us use those bits right. There are two common\nproblems with typing bits: needing to reinterpret those exact bits as a\ndifferent type, and needing to change the bits to have equivalent meaning for\na different type. Because Rust encourages encoding important properties in the\ntype system, these problems are incredibly pervasive. As such, Rust\nconsequently gives you several ways to solve them.\nFirst we'll look at the ways that Safe Rust gives you to reinterpret values.\nThe most trivial way to do this is to just destructure a value into its\nconstituent parts and then build a new type out of them. e.g.\n```rust\nstruct Foo {\n x: u32,\n y: u16,\n}\n\nstruct Bar {\n a: u32,\n b: u16,\n}\n\nfn reinterpret(foo: Foo) -> Bar {\n let Foo { x, y } = foo;\n Bar { a: x, b: y }\n}\n```\nBut this is, at best, annoying. For common conversions, Rust provides\nmore ergonomic alternatives.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Type Conversions", "heading_path": ["Type Conversions"], "path": "conversions.md", "url": "https://doc.rust-lang.org/nomicon/conversions.html#type-conversions", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/coercions.md#coercions-0", "text": "The Rustonomicon › Coercions\n\nTypes can implicitly be coerced to change in certain contexts.\nThese changes are generally just *weakening* of types, largely focused around pointers and lifetimes.\nThey mostly exist to make Rust \"just work\" in more cases, and are largely harmless.\nFor an exhaustive list of all the types of coercions, see the [Coercion types] section on the reference.\nNote that we do not perform coercions when matching traits (except for receivers, see the next page).\nIf there is an `impl` for some type `U` and `T` coerces to `U`, that does not constitute an implementation for `T`.\nFor example, the following will not type check, even though it is OK to coerce `t` to `&T` and there is an `impl` for `&T`:\n```rust,compile_fail\ntrait Trait {}\n\nfn foo(t: X) {}\n\nimpl<'a> Trait for &'a i32 {}\n\nfn main() {\n let t: &mut i32 = &mut 0;\n foo(t);\n}\n```\nwhich fails like as follows:\n```text\nerror[E0277]: the trait bound `&mut i32: Trait` is not satisfied\n --> src/main.rs:9:9\n |\n3 | fn foo(t: X) {}\n | ----- required by this bound in `foo`\n...\n9 | foo(t);\n | ^ the trait `Trait` is not implemented for `&mut i32`\n |\n = help: the following implementations were found:\n <&'a i32 as Trait>\n = note: `Trait` is implemented for `&i32`, but not for `&mut i32`\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Coercions", "heading_path": ["Coercions"], "path": "coercions.md", "url": "https://doc.rust-lang.org/nomicon/coercions.html#coercions", "has_code": true, "code_tags": ["rust,compile_fail", "text"]}} {"id": "nomicon/dot-operator.md#the-dot-operator-0", "text": "The Rustonomicon › The Dot Operator\n\nThe dot operator will perform a lot of magic to convert types.\nIt will perform auto-referencing, auto-dereferencing, and coercion until types\nmatch.\nThe detailed mechanics of method lookup are defined here,\nbut here is a brief overview that outlines the main steps.\nSuppose we have a function `foo` that has a receiver (a `self`, `&self` or\n`&mut self` parameter).\nIf we call `value.foo()`, the compiler needs to determine what type `Self` is before\nit can call the correct implementation of the function.\nFor this example, we will say that `value` has type `T`.\nWe will use fully-qualified syntax to be more clear about exactly which\ntype we are calling a function on.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "The Dot Operator", "heading_path": ["The Dot Operator"], "path": "dot-operator.md", "url": "https://doc.rust-lang.org/nomicon/dot-operator.html#the-dot-operator", "has_code": false, "code_tags": []}} {"id": "nomicon/dot-operator.md#the-dot-operator-1", "text": "The Rustonomicon › The Dot Operator\n\n- First, the compiler checks if it can call `T::foo(value)` directly.\nThis is called a \"by value\" method call.\n- If it can't call this function (for example, if the function has the wrong type\nor a trait isn't implemented for `Self`), then the compiler tries to add in an\nautomatic reference.\nThis means that the compiler tries `<&T>::foo(value)` and `<&mut T>::foo(value)`.\nThis is called an \"autoref\" method call.\n- If none of these candidates worked, it dereferences `T` and tries again.\nThis uses the `Deref` trait - if `T: Deref` then it tries again with\ntype `U` instead of `T`.\nIf it can't dereference `T`, it can also try _unsizing_ `T`.\nThis just means that if `T` has a size parameter known at compile time, it \"forgets\"\nit for the purpose of resolving methods.\nFor instance, this unsizing step can convert `[i32; 2]` into `[i32]` by \"forgetting\"\nthe size of the array.\nHere is an example of the method lookup algorithm:\n```rust,ignore\nlet array: Rc> = ...;\nlet first_entry = array[0];\n```\nHow does the compiler actually compute `array[0]` when the array is behind so\nmany indirections?\nFirst, `array[0]` is really just syntax sugar for the `Index` trait -\nthe compiler will convert `array[0]` into `array.index(0)`.\nNow, the compiler checks to see if `array` implements `Index`, so that it can call\nthe function.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "The Dot Operator", "heading_path": ["The Dot Operator"], "path": "dot-operator.md", "url": "https://doc.rust-lang.org/nomicon/dot-operator.html#the-dot-operator", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/dot-operator.md#the-dot-operator-2", "text": "The Rustonomicon › The Dot Operator\n\nThen, the compiler checks if `Rc>` implements `Index`, but it\ndoes not, and neither do `&Rc>` or `&mut Rc>`.\nSince none of these worked, the compiler dereferences the `Rc>` into\n`Box<[T; 3]>` and tries again.\n`Box<[T; 3]>`, `&Box<[T; 3]>`, and `&mut Box<[T; 3]>` do not implement `Index`,\nso it dereferences again.\n`[T; 3]` and its autorefs also do not implement `Index`.\nIt can't dereference `[T; 3]`, so the compiler unsizes it, giving `[T]`.\nFinally, `[T]` implements `Index`, so it can now call the actual `index` function.\nConsider the following more complicated example of the dot operator at work:\n```rust\nfn do_stuff(value: &T) {\n let cloned = value.clone();\n}\n```\nWhat type is `cloned`?\nFirst, the compiler checks if it can call by value.\nThe type of `value` is `&T`, and so the `clone` function has signature\n`fn clone(&T) -> T`.\nIt knows that `T: Clone`, so the compiler finds that `cloned: T`.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "The Dot Operator", "heading_path": ["The Dot Operator"], "path": "dot-operator.md", "url": "https://doc.rust-lang.org/nomicon/dot-operator.html#the-dot-operator", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/dot-operator.md#the-dot-operator-3", "text": "The Rustonomicon › The Dot Operator\n\nWhat would happen if the `T: Clone` restriction was removed? It would not be able\nto call by value, since there is no implementation of `Clone` for `T`.\nSo the compiler tries to call by autoref.\nIn this case, the function has the signature `fn clone(&&T) -> &T` since\n`Self = &T`.\nThe compiler sees that `&T: Clone`, and then deduces that `cloned: &T`.\nHere is another example where the autoref behavior is used to create some subtle\neffects:\n```rust\n#[derive(Clone)]\nstruct Container(Arc);\n\nfn clone_containers(foo: &Container, bar: &Container) {\n let foo_cloned = foo.clone();\n let bar_cloned = bar.clone();\n}\n```\nWhat types are `foo_cloned` and `bar_cloned`?\nWe know that `Container: Clone`, so the compiler calls `clone` by value to give\n`foo_cloned: Container`.\nHowever, `bar_cloned` actually has type `&Container`.\nSurely this doesn't make sense - we added `#[derive(Clone)]` to `Container`, so it\nmust implement `Clone`!\nLooking closer, the code generated by the `derive` macro is (roughly):\n```rust,ignore\nimpl Clone for Container where T: Clone {\n fn clone(&self) -> Self {\n Self(Arc::clone(&self.0))\n }\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "The Dot Operator", "heading_path": ["The Dot Operator"], "path": "dot-operator.md", "url": "https://doc.rust-lang.org/nomicon/dot-operator.html#the-dot-operator", "has_code": true, "code_tags": ["rust", "rust,ignore"]}} {"id": "nomicon/dot-operator.md#the-dot-operator-4", "text": "The Rustonomicon › The Dot Operator\n\nThe derived `Clone` implementation is only defined where `T: Clone`,\nso there is no implementation for `Container: Clone` for a generic `T`.\nThe compiler then looks to see if `&Container` implements `Clone`, which it does.\nSo it deduces that `clone` is called by autoref, and so `bar_cloned` has type\n`&Container`.\nWe can fix this by implementing `Clone` manually without requiring `T: Clone`:\n```rust,ignore\nimpl Clone for Container {\n fn clone(&self) -> Self {\n Self(Arc::clone(&self.0))\n }\n}\n```\nNow, the type checker deduces that `bar_cloned: Container`.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "The Dot Operator", "heading_path": ["The Dot Operator"], "path": "dot-operator.md", "url": "https://doc.rust-lang.org/nomicon/dot-operator.html#the-dot-operator", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/casts.md#casts-0", "text": "The Rustonomicon › Casts\n\nCasts are a superset of coercions: every coercion can be explicitly invoked via a cast.\nHowever some conversions require a cast.\nWhile coercions are pervasive and largely harmless, these \"true casts\" are rare and potentially dangerous.\nAs such, casts must be explicitly invoked using the `as` keyword: `expr as Type`.\nYou can find an exhaustive list of all the true casts and casting semantics on the reference.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Casts", "heading_path": ["Casts"], "path": "casts.md", "url": "https://doc.rust-lang.org/nomicon/casts.html#casts", "has_code": false, "code_tags": []}} {"id": "nomicon/casts.md#safety-of-casting-1", "text": "The Rustonomicon › Casts › Safety of casting\n\nTrue casts generally revolve around raw pointers and the primitive numeric types.\nEven though they're dangerous, these casts are infallible at runtime.\nIf a cast triggers some subtle corner case no indication will be given that this occurred.\nThe cast will simply succeed.\nThat said, casts must be valid at the type level, or else they will be prevented statically.\nFor instance, `7u8 as bool` will not compile.\nThat said, casts aren't `unsafe` because they generally can't violate memory safety *on their own*.\nFor instance, converting an integer to a raw pointer can very easily lead to terrible things.\nHowever the act of creating the pointer itself is safe, because actually using a raw pointer is already marked as `unsafe`.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Casts", "heading_path": ["Casts", "Safety of casting"], "path": "casts.md", "url": "https://doc.rust-lang.org/nomicon/casts.html#safety-of-casting", "has_code": false, "code_tags": []}} {"id": "nomicon/casts.md#lengths-when-casting-raw-slices-2", "text": "The Rustonomicon › Casts › Some notes about casting › Lengths when casting raw slices\n\nNote that lengths are not adjusted when casting raw slices; `*const [u16] as *const [u8]` creates a slice that only includes half of the original memory.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Casts", "heading_path": ["Casts", "Some notes about casting", "Lengths when casting raw slices"], "path": "casts.md", "url": "https://doc.rust-lang.org/nomicon/casts.html#lengths-when-casting-raw-slices", "has_code": false, "code_tags": []}} {"id": "nomicon/casts.md#transitivity-3", "text": "The Rustonomicon › Casts › Some notes about casting › Transitivity\n\nCasting is not transitive, that is, even if `e as U1 as U2` is a valid expression, `e as U2` is not necessarily so.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Casts", "heading_path": ["Casts", "Some notes about casting", "Transitivity"], "path": "casts.md", "url": "https://doc.rust-lang.org/nomicon/casts.html#transitivity", "has_code": false, "code_tags": []}} {"id": "nomicon/transmutes.md#transmutes-0", "text": "The Rustonomicon › Transmutes\n\nGet out of our way type system! We're going to reinterpret these bits or die\ntrying! Even though this book is all about doing things that are unsafe, I\nreally can't emphasize enough that you should deeply think about finding Another Way\nthan the operations covered in this section. This is really, truly, the most\nhorribly unsafe thing you can do in Rust. The guardrails here are dental floss.\n`mem::transmute` takes a value of type `T` and reinterprets\nit to have type `U`. The only restriction is that the `T` and `U` are verified\nto have the same size. The ways to cause Undefined Behavior with this are mind\nboggling.\n* First and foremost, creating an instance of *any* type with an invalid state\n is going to cause arbitrary chaos that can't really be predicted. Do not\n transmute `3` to `bool`. Even if you never *do* anything with the `bool`. Just\n don't.\n* Transmute has an overloaded return type. If you do not specify the return type\n it may produce a surprising type to satisfy inference.\n* Transmuting an `&` to `&mut` is Undefined Behavior. While certain usages may\n *appear* safe, note that the Rust optimizer is free to assume that a shared\n reference won't change through its lifetime and thus such transmutation will\n run afoul of those assumptions. So:\n * Transmuting an `&` to `&mut` is *always* Undefined Behavior.\n * No you can't do it.\n * No you're not special.\n* Transmuting to a reference without an explicitly provided lifetime\n produces an [unbounded lifetime].", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Transmutes", "heading_path": ["Transmutes"], "path": "transmutes.md", "url": "https://doc.rust-lang.org/nomicon/transmutes.html#transmutes", "has_code": false, "code_tags": []}} {"id": "nomicon/transmutes.md#transmutes-1", "text": "The Rustonomicon › Transmutes\n\n* When transmuting between different compound types, you have to make sure they\n are laid out the same way! If layouts differ, the wrong fields are going to\n get filled with the wrong data, which will make you unhappy and can also be\n Undefined Behavior (see above).\n So how do you know if the layouts are the same? For `repr(C)` types and\n `repr(transparent)` types, layout is precisely defined. But for your\n run-of-the-mill `repr(Rust)`, it is not. Even different instances of the same\n generic type can have wildly different layout. `Vec` and `Vec`\n *might* have their fields in the same order, or they might not. The details of\n what exactly is and is not guaranteed for data layout are still being worked\n out over at the UCG WG.\n`mem::transmute_copy` somehow manages to be *even more*\nwildly unsafe than this. It copies `size_of` bytes out of an `&T` and\ninterprets them as a `U`. The size check that `mem::transmute` has is gone (as\nit may be valid to copy out a prefix), though it is Undefined Behavior for `U`\nto be larger than `T`.\nAlso of course you can get all of the functionality of these functions using raw\npointer casts or `union`s, but without any of the lints or other basic sanity\nchecks. Raw pointer casts and `union`s do not magically avoid the above rules.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Transmutes", "heading_path": ["Transmutes"], "path": "transmutes.md", "url": "https://doc.rust-lang.org/nomicon/transmutes.html#transmutes", "has_code": false, "code_tags": []}} {"id": "nomicon/uninitialized.md#working-with-uninitialized-memory-0", "text": "The Rustonomicon › Working With Uninitialized Memory\n\nAll runtime-allocated memory in a Rust program begins its life as\n*uninitialized*. In this state the value of the memory is an indeterminate pile\nof bits that may or may not even reflect a valid state for the type that is\nsupposed to inhabit that location of memory. Attempting to interpret this memory\nas a value of *any* type will cause Undefined Behavior. Do Not Do This.\nRust provides mechanisms to work with uninitialized memory in checked (safe) and\nunchecked (unsafe) ways.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Uninitialized Memory", "heading_path": ["Working With Uninitialized Memory"], "path": "uninitialized.md", "url": "https://doc.rust-lang.org/nomicon/uninitialized.html#working-with-uninitialized-memory", "has_code": false, "code_tags": []}} {"id": "nomicon/checked-uninit.md#checked-uninitialized-memory-0", "text": "The Rustonomicon › Checked Uninitialized Memory\n\nLike C, all stack variables in Rust are uninitialized until a value is\nexplicitly assigned to them. Unlike C, Rust statically prevents you from ever\nreading them until you do:\n```rust,compile_fail\nfn main() {\n let x: i32;\n println!(\"{}\", x);\n}\n```\n```text\n |\n3 | println!(\"{}\", x);\n | ^ use of possibly uninitialized `x`\n```\nThis is based off of a basic branch analysis: every branch must assign a value\nto `x` before it is first used. For short, we also say that \"`x` is init\" or\n\"`x` is uninit\".\nInterestingly, Rust doesn't require the variable\nto be mutable to perform a delayed initialization if every branch assigns\nexactly once. However the analysis does not take advantage of constant analysis\nor anything like that. So this compiles:\n```rust\nfn main() {\n let x: i32;\n\n if true {\n x = 1;\n } else {\n x = 2;\n }\n\n println!(\"{}\", x);\n}\n```\nbut this doesn't:\n```rust,compile_fail\nfn main() {\n let x: i32;\n if true {\n x = 1;\n }\n println!(\"{}\", x);\n}\n```\n```text\n |\n6 | println!(\"{}\", x);\n | ^ use of possibly uninitialized `x`\n```\nwhile this does:\n```rust\nfn main() {\n let x: i32;\n if true {\n x = 1;\n println!(\"{}\", x);\n }\n // Don't care that there are branches where it's not initialized\n // since we don't use the value in those branches\n}\n```\nOf course, while the analysis doesn't consider actual values, it does\nhave a relatively sophisticated understanding of dependencies and control\nflow. For instance, this works:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Checked", "heading_path": ["Checked Uninitialized Memory"], "path": "checked-uninit.md", "url": "https://doc.rust-lang.org/nomicon/checked-uninit.html#checked-uninitialized-memory", "has_code": true, "code_tags": ["rust", "rust,compile_fail", "text"]}} {"id": "nomicon/checked-uninit.md#checked-uninitialized-memory-1", "text": "The Rustonomicon › Checked Uninitialized Memory\n\n```rust\nlet x: i32;\n\nloop {\n // Rust doesn't understand that this branch will be taken unconditionally,\n // because it relies on actual values.\n if true {\n // But it does understand that it will only be taken once because\n // we unconditionally break out of it. Therefore `x` doesn't\n // need to be marked as mutable.\n x = 0;\n break;\n }\n}\n// It also knows that it's impossible to get here without reaching the break.\n// And therefore that `x` must be initialized here!\nprintln!(\"{}\", x);\n```\nIf a value is moved out of a variable, that variable becomes logically\nuninitialized if the type of the value isn't Copy. That is:\n```rust\nfn main() {\n let x = 0;\n let y = Box::new(0);\n let z1 = x; // x is still valid because i32 is Copy\n let z2 = y; // y is now logically uninitialized because Box isn't Copy\n}\n```\nHowever reassigning `y` in this example *would* require `y` to be marked as\nmutable, as a Safe Rust program could observe that the value of `y` changed:\n```rust\nfn main() {\n let mut y = Box::new(0);\n let z = y; // y is now logically uninitialized because Box isn't Copy\n y = Box::new(1); // reinitialize y\n}\n```\nOtherwise it's like `y` is a brand new variable.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Checked", "heading_path": ["Checked Uninitialized Memory"], "path": "checked-uninit.md", "url": "https://doc.rust-lang.org/nomicon/checked-uninit.html#checked-uninitialized-memory", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/drop-flags.md#drop-flags-0", "text": "The Rustonomicon › Drop Flags\n\nThe examples in the previous section introduce an interesting problem for Rust.\nWe have seen that it's possible to conditionally initialize, deinitialize, and\nreinitialize locations of memory totally safely. For Copy types, this isn't\nparticularly notable since they're just a random pile of bits. However types\nwith destructors are a different story: Rust needs to know whether to call a\ndestructor whenever a variable is assigned to, or a variable goes out of scope.\nHow can it do this with conditional initialization?\nNote that this is not a problem that all assignments need worry about. In\nparticular, assigning through a dereference unconditionally drops, and assigning\nin a `let` unconditionally doesn't drop:\n```rust\nlet mut x = Box::new(0); // let makes a fresh variable, so never need to drop\nlet y = &mut x;\n*y = Box::new(1); // Deref assumes the referent is initialized, so always drops\n```\nThis is only a problem when overwriting a previously initialized variable or\none of its subfields.\nIt turns out that Rust actually tracks whether a type should be dropped or not\n*at runtime*. As a variable becomes initialized and uninitialized, a *drop flag*\nfor that variable is toggled. When a variable might need to be dropped, this\nflag is evaluated to determine if it should be dropped.\nOf course, it is often the case that a value's initialization state can be\nstatically known at every point in the program. If this is the case, then the\ncompiler can theoretically generate more efficient code! For instance, straight-\nline code has such *static drop semantics*:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Drop Flags", "heading_path": ["Drop Flags"], "path": "drop-flags.md", "url": "https://doc.rust-lang.org/nomicon/drop-flags.html#drop-flags", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/drop-flags.md#drop-flags-1", "text": "The Rustonomicon › Drop Flags\n\n```rust\nlet mut x = Box::new(0); // x was uninit; just overwrite.\nlet mut y = x; // y was uninit; just overwrite and make x uninit.\nx = Box::new(0); // x was uninit; just overwrite.\ny = x; // y was init; Drop y, overwrite it, and make x uninit!\n // y goes out of scope; y was init; Drop y!\n // x goes out of scope; x was uninit; do nothing.\n```\nSimilarly, branched code where all branches have the same behavior with respect\nto initialization has static drop semantics:\n```rust\nlet mut x = Box::new(0); // x was uninit; just overwrite.\nif condition {\n drop(x) // x gets moved out; make x uninit.\n} else {\n println!(\"{}\", x);\n drop(x) // x gets moved out; make x uninit.\n}\nx = Box::new(0); // x was uninit; just overwrite.\n // x goes out of scope; x was init; Drop x!\n```\nHowever code like this *requires* runtime information to correctly Drop:\n```rust\nlet x;\nif condition {\n x = Box::new(0); // x was uninit; just overwrite.\n println!(\"{}\", x);\n}\n // x goes out of scope; x might be uninit;\n // check the flag!\n```\nOf course, in this case it's trivial to retrieve static drop semantics:\n```rust\nif condition {\n let x = Box::new(0);\n println!(\"{}\", x);\n}\n```\nThe drop flags are tracked on the stack.\nIn old Rust versions, drop flags were stashed in a hidden field of types that implement `Drop`.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Drop Flags", "heading_path": ["Drop Flags"], "path": "drop-flags.md", "url": "https://doc.rust-lang.org/nomicon/drop-flags.html#drop-flags", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/unchecked-uninit.md#unchecked-uninitialized-memory-0", "text": "The Rustonomicon › Unchecked Uninitialized Memory\n\nOne interesting exception to this rule is working with arrays. Safe Rust doesn't\npermit you to partially initialize an array. When you initialize an array, you\ncan either set every value to the same thing with `let x = [val; N]`, or you can\nspecify each member individually with `let x = [val1, val2, val3]`.\nUnfortunately this is pretty rigid, especially if you need to initialize your\narray in a more incremental or dynamic way.\nUnsafe Rust gives us a powerful tool to handle this problem:\n[`MaybeUninit`]. This type can be used to handle memory that has not been fully\ninitialized yet.\nWith `MaybeUninit`, we can initialize an array element by element as follows:\n```rust\nuse std::mem::{self, MaybeUninit};\n\n// Size of the array is hard-coded but easy to change (meaning, changing just\n// the constant is sufficient). This means we can't use [a, b, c] syntax to\n// initialize the array, though, as we would have to keep that in sync\n// with `SIZE`!\nconst SIZE: usize = 10;\n\nlet x = {\n // Create an uninitialized array of `MaybeUninit`.\n let mut x = [const { MaybeUninit::uninit() }; SIZE];\n\n // Dropping a `MaybeUninit` does nothing. Thus using raw pointer\n // assignment instead of `ptr::write` does not cause the old\n // uninitialized value to be dropped.\n // Exception safety is not a concern because Box can't panic\n for i in 0..SIZE {\n x[i] = MaybeUninit::new(Box::new(i as u32));\n }\n\n // Everything is initialized. Transmute the array to the\n // initialized type.\n unsafe { mem::transmute::<_, [Box; SIZE]>(x) }\n};\n\nprintln!(\"{x:?}\");\n```\nThis code proceeds in three steps:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Unchecked", "heading_path": ["Unchecked Uninitialized Memory"], "path": "unchecked-uninit.md", "url": "https://doc.rust-lang.org/nomicon/unchecked-uninit.html#unchecked-uninitialized-memory", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/unchecked-uninit.md#unchecked-uninitialized-memory-1", "text": "The Rustonomicon › Unchecked Uninitialized Memory\n\n1. Create an array of `MaybeUninit`.\n2. Initialize the array. The subtle aspect of this is that usually, when we use\n `=` to assign to a value that the Rust type checker considers to already be\n initialized (like `x[i]`), the old value stored on the left-hand side gets\n dropped. This would be a disaster. However, in this case, the type of the\n left-hand side is `MaybeUninit>`, and dropping that does not do\n anything! See below for some more discussion of this `drop` issue.\n3. Finally, we have to change the type of our array to remove the\n `MaybeUninit`. With current stable Rust, this requires a `transmute`.\n This transmute is legal because in memory, `MaybeUninit` looks the same as `T`.\n However, note that in general, `Container>>` does *not* look\n the same as `Container`! Imagine if `Container` was `Option`, and `T` was\n `bool`, then `Option` exploits that `bool` only has two valid values,\n but `Option>` cannot do that because the `bool` does not\n have to be initialized.\n So, it depends on `Container` whether transmuting away the `MaybeUninit` is\n allowed. For arrays, it is (and eventually the standard library will\n acknowledge that by providing appropriate methods).\nIt's worth spending a bit more time on the loop in the middle, and in particular\nthe assignment operator and its interaction with `drop`. If we wrote something like:\n```rust,ignore\n*x[i].as_mut_ptr() = Box::new(i as u32); // WRONG!\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Unchecked", "heading_path": ["Unchecked Uninitialized Memory"], "path": "unchecked-uninit.md", "url": "https://doc.rust-lang.org/nomicon/unchecked-uninit.html#unchecked-uninitialized-memory", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/unchecked-uninit.md#unchecked-uninitialized-memory-2", "text": "The Rustonomicon › Unchecked Uninitialized Memory\n\nwe would actually overwrite a `Box`, leading to `drop` of uninitialized\ndata, which would cause much sadness and pain.\nThe correct alternative, if for some reason we cannot use `MaybeUninit::new`, is\nto use the [`ptr`] module. In particular, it provides three functions that allow\nus to assign bytes to a location in memory without dropping the old value:\n[`write`], [`copy`], and [`copy_nonoverlapping`].\n* `ptr::write(ptr, val)` takes a `val` and moves it into the address pointed\n to by `ptr`.\n* `ptr::copy(src, dest, count)` copies the bits that `count` T items would occupy\n from src to dest. (this is equivalent to C's memmove -- note that the argument\n order is reversed!)\n* `ptr::copy_nonoverlapping(src, dest, count)` does what `copy` does, but a\n little faster on the assumption that the two ranges of memory don't overlap.\n (this is equivalent to C's memcpy -- note that the argument order is reversed!)\nIt should go without saying that these functions, if misused, will cause serious\nhavoc or just straight up Undefined Behavior. The only requirement of these\nfunctions *themselves* is that the locations you want to read and write\nare allocated and properly aligned. However, the ways writing arbitrary bits to\narbitrary locations of memory can break things are basically uncountable!\nIt's worth noting that you don't need to worry about `ptr::write`-style\nshenanigans with types which don't implement `Drop` or contain `Drop` types,\nbecause Rust knows not to try to drop them. This is what we relied on in the\nabove example.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Unchecked", "heading_path": ["Unchecked Uninitialized Memory"], "path": "unchecked-uninit.md", "url": "https://doc.rust-lang.org/nomicon/unchecked-uninit.html#unchecked-uninitialized-memory", "has_code": false, "code_tags": []}} {"id": "nomicon/unchecked-uninit.md#unchecked-uninitialized-memory-3", "text": "The Rustonomicon › Unchecked Uninitialized Memory\n\nHowever when working with uninitialized memory you need to be ever-vigilant for\nRust trying to drop values you make like this before they're fully initialized.\nEvery control path through that variable's scope must initialize the value\nbefore it ends, if it has a destructor.\n*This includes code panicking*. `MaybeUninit` helps a bit\nhere, because it does not implicitly drop its content - but all this really\nmeans in case of a panic is that instead of a double-free of the not yet\ninitialized parts, you end up with a memory leak of the already initialized\nparts.\nNote that, to use the `ptr` methods, you need to first obtain a *raw pointer* to\nthe data you want to initialize. It is illegal to construct a *reference* to\nuninitialized data, which implies that you have to be careful when obtaining\nsaid raw pointer:\n* For an array of `T`, you can use `base_ptr.add(idx)` where `base_ptr: *mut T`\nto compute the address of array index `idx`. This relies on\nhow arrays are laid out in memory.\n* For a struct, however, in general we do not know how it is laid out, and we\nalso cannot use `&mut base_ptr.field` as that would be creating a\nreference. So, you must carefully use the raw reference syntax. This creates\na raw pointer to the field without creating an intermediate reference:\n```rust\nuse std::{ptr, mem::MaybeUninit};\n\nstruct Demo {\n field: bool,\n}\n\nlet mut uninit = MaybeUninit::::uninit();\n// `&uninit.as_mut().field` would create a reference to an uninitialized `bool`,\n// and thus be Undefined Behavior!\nlet f1_ptr = unsafe { &raw mut (*uninit.as_mut_ptr()).field };\nunsafe { f1_ptr.write(true); }\n\nlet init = unsafe { uninit.assume_init() };\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Unchecked", "heading_path": ["Unchecked Uninitialized Memory"], "path": "unchecked-uninit.md", "url": "https://doc.rust-lang.org/nomicon/unchecked-uninit.html#unchecked-uninitialized-memory", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/unchecked-uninit.md#unchecked-uninitialized-memory-4", "text": "The Rustonomicon › Unchecked Uninitialized Memory\n\nOne last remark: when reading old Rust code, you might stumble upon the\ndeprecated `mem::uninitialized` function. That function used to be the only way\nto deal with uninitialized memory on the stack, but it turned out to be\nimpossible to properly integrate with the rest of the language. Always use\n`MaybeUninit` instead in new code, and port old code over when you get the\nopportunity.\nAnd that's about it for working with uninitialized memory! Basically nothing\nanywhere expects to be handed uninitialized memory, so if you're going to pass\nit around at all, be sure to be *really* careful.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Unchecked", "heading_path": ["Unchecked Uninitialized Memory"], "path": "unchecked-uninit.md", "url": "https://doc.rust-lang.org/nomicon/unchecked-uninit.html#unchecked-uninitialized-memory", "has_code": false, "code_tags": []}} {"id": "nomicon/obrm.md#the-perils-of-ownership-based-resource-management-obrm-0", "text": "The Rustonomicon › The Perils Of Ownership Based Resource Management (OBRM)\n\nOBRM (AKA RAII: Resource Acquisition Is Initialization) is something you'll\ninteract with a lot in Rust. Especially if you use the standard library.\nRoughly speaking the pattern is as follows: to acquire a resource, you create an\nobject that manages it. To release the resource, you simply destroy the object,\nand it cleans up the resource for you. The most common \"resource\" this pattern\nmanages is simply *memory*. `Box`, `Rc`, and basically everything in\n`std::collections` is a convenience to enable correctly managing memory. This is\nparticularly important in Rust because we have no pervasive GC to rely on for\nmemory management. Which is the point, really: Rust is about control. However we\nare not limited to just memory. Pretty much every other system resource like a\nthread, file, or socket is exposed through this kind of API.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Ownership Based Resource Management", "heading_path": ["The Perils Of Ownership Based Resource Management (OBRM)"], "path": "obrm.md", "url": "https://doc.rust-lang.org/nomicon/obrm.html#the-perils-of-ownership-based-resource-management-obrm", "has_code": false, "code_tags": []}} {"id": "nomicon/constructors.md#constructors-0", "text": "The Rustonomicon › Constructors\n\nThere is exactly one way to create an instance of a user-defined type: name it,\nand initialize all its fields at once:\n```rust\nstruct Foo {\n a: u8,\n b: u32,\n c: bool,\n}\n\nenum Bar {\n X(u32),\n Y(bool),\n}\n\nstruct Unit;\n\nlet foo = Foo { a: 0, b: 1, c: false };\nlet bar = Bar::X(0);\nlet empty = Unit;\n```\nThat's it. Every other way you make an instance of a type is just calling a\ntotally vanilla function that does some stuff and eventually bottoms out to The\nOne True Constructor.\nUnlike C++, Rust does not come with a slew of built-in kinds of constructor.\nThere are no Copy, Default, Assignment, Move, or whatever constructors. The\nreasons for this are varied, but it largely boils down to Rust's philosophy of\n*being explicit*.\nMove constructors are meaningless in Rust because we don't enable types to\n\"care\" about their location in memory. Every type must be ready for it to be\nblindly memcopied to somewhere else in memory. This means pure on-the-stack-but-\nstill-movable intrusive linked lists are simply not happening in Rust (safely).", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Constructors", "heading_path": ["Constructors"], "path": "constructors.md", "url": "https://doc.rust-lang.org/nomicon/constructors.html#constructors", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/constructors.md#constructors-1", "text": "The Rustonomicon › Constructors\n\nAssignment and copy constructors similarly don't exist because move semantics\nare the only semantics in Rust. At most `x = y` just moves the bits of y into\nthe x variable. Rust does provide two facilities for providing C++'s copy-\noriented semantics: `Copy` and `Clone`. Clone is our moral equivalent of a copy\nconstructor, but it's never implicitly invoked. You have to explicitly call\n`clone` on an element you want to be cloned. Copy is a special case of Clone\nwhere the implementation is just \"copy the bits\". Copy types *are* implicitly\ncloned whenever they're moved, but because of the definition of Copy this just\nmeans not treating the old copy as uninitialized -- a no-op.\nWhile Rust provides a `Default` trait for specifying the moral equivalent of a\ndefault constructor, it's incredibly rare for this trait to be used. This is\nbecause variables aren't implicitly initialized. Default is basically\nonly useful for generic programming. In concrete contexts, a type will provide a\nstatic `new` method for any kind of \"default\" constructor. This has no relation\nto `new` in other languages and has no special meaning. It's just a naming\nconvention.\nTODO: talk about \"placement new\"?", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Constructors", "heading_path": ["Constructors"], "path": "constructors.md", "url": "https://doc.rust-lang.org/nomicon/constructors.html#constructors", "has_code": false, "code_tags": []}} {"id": "nomicon/destructors.md#destructors-0", "text": "The Rustonomicon › Destructors\n\nWhat the language *does* provide is full-blown automatic destructors through the\n`Drop` trait, which provides the following method:\n```rust,ignore\nfn drop(&mut self);\n```\nThis method gives the type time to somehow finish what it was doing.\n**After `drop` is run, Rust will recursively try to drop all of the fields\nof `self`.**\nThis is a convenience feature so that you don't have to write \"destructor\nboilerplate\" to drop children. If a struct has no special logic for being\ndropped other than dropping its children, then it means `Drop` doesn't need to\nbe implemented at all!\n**There is no stable way to prevent this behavior in Rust 1.0.**\nNote that taking `&mut self` means that even if you could suppress recursive\nDrop, Rust will prevent you from e.g. moving fields out of self. For most types,\nthis is totally fine.\nFor instance, a custom implementation of `Box` might write `Drop` like this:\n```rust\n#![feature(ptr_internals, allocator_api)]\n\nuse std::alloc::{Allocator, Global, GlobalAlloc, Layout};\nuse std::mem;\nuse std::ptr::{drop_in_place, NonNull, Unique};\n\nstruct Box{ ptr: Unique }\n\nimpl Drop for Box {\n fn drop(&mut self) {\n unsafe {\n drop_in_place(self.ptr.as_ptr());\n let c: NonNull = self.ptr.into();\n Global.deallocate(c.cast(), Layout::new::())\n }\n }\n}\n```\nand this works fine because when Rust goes to drop the `ptr` field it just sees\na [Unique] that has no actual `Drop` implementation. Similarly nothing can\nuse-after-free the `ptr` because when drop exits, it becomes inaccessible.\nHowever this wouldn't work:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Destructors", "heading_path": ["Destructors"], "path": "destructors.md", "url": "https://doc.rust-lang.org/nomicon/destructors.html#destructors", "has_code": true, "code_tags": ["rust", "rust,ignore"]}} {"id": "nomicon/destructors.md#destructors-1", "text": "The Rustonomicon › Destructors\n\n```rust\n#![feature(allocator_api, ptr_internals)]\n\nuse std::alloc::{Allocator, Global, GlobalAlloc, Layout};\nuse std::ptr::{drop_in_place, Unique, NonNull};\nuse std::mem;\n\nstruct Box{ ptr: Unique }\n\nimpl Drop for Box {\n fn drop(&mut self) {\n unsafe {\n drop_in_place(self.ptr.as_ptr());\n let c: NonNull = self.ptr.into();\n Global.deallocate(c.cast(), Layout::new::());\n }\n }\n}\n\nstruct SuperBox { my_box: Box }\n\nimpl Drop for SuperBox {\n fn drop(&mut self) {\n unsafe {\n // Hyper-optimized: deallocate the box's contents for it\n // without `drop`ing the contents\n let c: NonNull = self.my_box.ptr.into();\n Global.deallocate(c.cast::(), Layout::new::());\n }\n }\n}\n```\nAfter we deallocate the `box`'s ptr in SuperBox's destructor, Rust will\nhappily proceed to tell the box to Drop itself and everything will blow up with\nuse-after-frees and double-frees.\nNote that the recursive drop behavior applies to all structs and enums\nregardless of whether they implement Drop. Therefore something like\n```rust\nstruct Boxy {\n data1: Box,\n data2: Box,\n info: u32,\n}\n```\nwill have the destructors of its `data1` and `data2` fields called whenever it \"would\" be\ndropped, even though it itself doesn't implement Drop. We say that such a type\n*needs Drop*, even though it is not itself Drop.\nSimilarly,\n```rust\nenum Link {\n Next(Box),\n None,\n}\n```\nwill have its inner Box field dropped if and only if an instance stores the\nNext variant.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Destructors", "heading_path": ["Destructors"], "path": "destructors.md", "url": "https://doc.rust-lang.org/nomicon/destructors.html#destructors", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/destructors.md#destructors-2", "text": "The Rustonomicon › Destructors\n\nIn general this works really nicely because you don't need to worry about\nadding/removing drops when you refactor your data layout. Still there's\ncertainly many valid use cases for needing to do trickier things with\ndestructors.\nThe classic safe solution to overriding recursive drop and allowing moving out\nof Self during `drop` is to use an Option:\n```rust\n#![feature(allocator_api, ptr_internals)]\n\nuse std::alloc::{Allocator, GlobalAlloc, Global, Layout};\nuse std::ptr::{drop_in_place, Unique, NonNull};\nuse std::mem;\n\nstruct Box{ ptr: Unique }\n\nimpl Drop for Box {\n fn drop(&mut self) {\n unsafe {\n drop_in_place(self.ptr.as_ptr());\n let c: NonNull = self.ptr.into();\n Global.deallocate(c.cast(), Layout::new::());\n }\n }\n}\n\nstruct SuperBox { my_box: Option> }\n\nimpl Drop for SuperBox {\n fn drop(&mut self) {\n unsafe {\n // Hyper-optimized: deallocate the box's contents for it\n // without `drop`ing the contents. Need to set the `box`\n // field as `None` to prevent Rust from trying to Drop it.\n let my_box = self.my_box.take().unwrap();\n let c: NonNull = my_box.ptr.into();\n Global.deallocate(c.cast(), Layout::new::());\n mem::forget(my_box);\n }\n }\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Destructors", "heading_path": ["Destructors"], "path": "destructors.md", "url": "https://doc.rust-lang.org/nomicon/destructors.html#destructors", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/destructors.md#destructors-3", "text": "The Rustonomicon › Destructors\n\nHowever this has fairly odd semantics: you are saying that a field that *should*\nalways be Some *may* be None, just because of what happens in the destructor. Of\ncourse this conversely makes a lot of sense: you can call arbitrary methods on\nself during the destructor, and this should prevent you from ever doing so after\ndeinitializing the field. Not that it will prevent you from producing any other\narbitrarily invalid state in there.\nOn balance this is an ok choice. Certainly what you should reach for by default.\nHowever, in the future we expect there to be a first-class way to announce that\na field shouldn't be automatically dropped.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Destructors", "heading_path": ["Destructors"], "path": "destructors.md", "url": "https://doc.rust-lang.org/nomicon/destructors.html#destructors", "has_code": false, "code_tags": []}} {"id": "nomicon/leaking.md#leaking-0", "text": "The Rustonomicon › Leaking\n\nOwnership-based resource management is intended to simplify composition. You\nacquire resources when you create the object, and you release the resources when\nit gets destroyed. Since destruction is handled for you, it means you can't\nforget to release the resources, and it happens as soon as possible! Surely this\nis perfect and all of our problems are solved.\nEverything is terrible and we have new and exotic problems to try to solve.\nMany people like to believe that Rust eliminates resource leaks. In practice,\nthis is basically true. You would be surprised to see a Safe Rust program\nleak resources in an uncontrolled way.\nHowever from a theoretical perspective this is absolutely not the case, no\nmatter how you look at it. In the strictest sense, \"leaking\" is so abstract as\nto be unpreventable. It's quite trivial to initialize a collection at the start\nof a program, fill it with tons of objects with destructors, and then enter an\ninfinite event loop that never refers to it. The collection will sit around\nuselessly, holding on to its precious resources until the program terminates (at\nwhich point all those resources would have been reclaimed by the OS anyway).\nWe may consider a more restricted form of leak: failing to drop a value that is\nunreachable. Rust also doesn't prevent this. In fact Rust *has a function for\ndoing this*: `mem::forget`. This function consumes the value it is passed *and\nthen doesn't run its destructor*.\nIn the past `mem::forget` was marked as unsafe as a sort of lint against using\nit, since failing to call a destructor is generally not a well-behaved thing to\ndo (though useful for some special unsafe code). However this was generally\ndetermined to be an untenable stance to take: there are many ways to fail to\ncall a destructor in safe code. The most famous example is creating a cycle of\nreference-counted pointers using interior mutability.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Leaking", "heading_path": ["Leaking"], "path": "leaking.md", "url": "https://doc.rust-lang.org/nomicon/leaking.html#leaking", "has_code": false, "code_tags": []}} {"id": "nomicon/leaking.md#leaking-1", "text": "The Rustonomicon › Leaking\n\nIt is reasonable for safe code to assume that destructor leaks do not happen, as\nany program that leaks destructors is probably wrong. However *unsafe* code\ncannot rely on destructors to be run in order to be safe. For most types this\ndoesn't matter: if you leak the destructor then the type is by definition\ninaccessible, so it doesn't matter, right? For instance, if you leak a `Box`\nthen you waste some memory but that's hardly going to violate memory-safety.\nHowever where we must be careful with destructor leaks are *proxy* types. These\nare types which manage access to a distinct object, but don't actually own it.\nProxy objects are quite rare. Proxy objects you'll need to care about are even\nrarer. However we'll focus on three interesting examples in the standard\nlibrary:\n* `vec::Drain`\n* `Rc`\n* `thread::scoped::JoinGuard`", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Leaking", "heading_path": ["Leaking"], "path": "leaking.md", "url": "https://doc.rust-lang.org/nomicon/leaking.html#leaking", "has_code": false, "code_tags": []}} {"id": "nomicon/leaking.md#drain-2", "text": "The Rustonomicon › Leaking › Drain\n\n`drain` is a collections API that moves data out of the container without\nconsuming the container. This enables us to reuse the allocation of a `Vec`\nafter claiming ownership over all of its contents. It produces an iterator\n(Drain) that returns the contents of the Vec by-value.\nNow, consider Drain in the middle of iteration: some values have been moved out,\nand others haven't. This means that part of the Vec is now full of logically\nuninitialized data! We could backshift all the elements in the Vec every time we\nremove a value, but this would have pretty catastrophic performance\nconsequences.\nInstead, we would like Drain to fix the Vec's backing storage when it is\ndropped. It should run itself to completion, backshift any elements that weren't\nremoved (drain supports subranges), and then fix Vec's `len`. It's even\nunwinding-safe! Easy!\nNow consider the following:\n```rust,ignore\nlet mut vec = vec![Box::new(0); 4];\n\n{\n // start draining, vec can no longer be accessed\n let mut drainer = vec.drain(..);\n\n // pull out two elements and immediately drop them\n drainer.next();\n drainer.next();\n\n // get rid of drainer, but don't call its destructor\n mem::forget(drainer);\n}\n\n// Oops, vec[0] was dropped, we're reading a pointer into free'd memory!\nprintln!(\"{}\", vec[0]);\n```\nThis is pretty clearly Not Good. Unfortunately, we're kind of stuck between a\nrock and a hard place: maintaining consistent state at every step has an\nenormous cost (and would negate any benefits of the API). Failing to maintain\nconsistent state gives us Undefined Behavior in safe code (making the API\nunsound).", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Leaking", "heading_path": ["Leaking", "Drain"], "path": "leaking.md", "url": "https://doc.rust-lang.org/nomicon/leaking.html#drain", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/leaking.md#drain-3", "text": "The Rustonomicon › Leaking › Drain\n\nSo what can we do? Well, we can pick a trivially consistent state: set the Vec's\nlen to be 0 when we start the iteration, and fix it up if necessary in the\ndestructor. That way, if everything executes like normal we get the desired\nbehavior with minimal overhead. But if someone has the *audacity* to\nmem::forget us in the middle of the iteration, all that does is *leak even more*\n(and possibly leave the Vec in an unexpected but otherwise consistent state).\nSince we've accepted that mem::forget is safe, this is definitely safe. We call\nleaks causing more leaks a *leak amplification*.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Leaking", "heading_path": ["Leaking", "Drain"], "path": "leaking.md", "url": "https://doc.rust-lang.org/nomicon/leaking.html#drain", "has_code": false, "code_tags": []}} {"id": "nomicon/leaking.md#rc-4", "text": "The Rustonomicon › Leaking › Rc\n\nRc is an interesting case because at first glance it doesn't appear to be a\nproxy value at all. After all, it manages the data it points to, and dropping\nall the Rcs for a value will drop that value. Leaking an Rc doesn't seem like it\nwould be particularly dangerous. It will leave the refcount permanently\nincremented and prevent the data from being freed or dropped, but that seems\njust like Box, right?\nNope.\nLet's consider a simplified implementation of Rc:\n```rust,ignore\nstruct Rc {\n ptr: *mut RcBox,\n}\n\nstruct RcBox {\n data: T,\n ref_count: usize,\n}\n\nimpl Rc {\n fn new(data: T) -> Self {\n unsafe {\n // Wouldn't it be nice if heap::allocate worked like this?\n let ptr = heap::allocate::>();\n ptr::write(ptr, RcBox {\n data,\n ref_count: 1,\n });\n Rc { ptr }\n }\n }\n\n fn clone(&self) -> Self {\n unsafe {\n (*self.ptr).ref_count += 1;\n }\n Rc { ptr: self.ptr }\n }\n}\n\nimpl Drop for Rc {\n fn drop(&mut self) {\n unsafe {\n (*self.ptr).ref_count -= 1;\n if (*self.ptr).ref_count == 0 {\n // drop the data and then free it\n ptr::read(self.ptr);\n heap::deallocate(self.ptr);\n }\n }\n }\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Leaking", "heading_path": ["Leaking", "Rc"], "path": "leaking.md", "url": "https://doc.rust-lang.org/nomicon/leaking.html#rc", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/leaking.md#rc-5", "text": "The Rustonomicon › Leaking › Rc\n\nThis code contains an implicit and subtle assumption: `ref_count` can fit in a\n`usize`, because there can't be more than `usize::MAX` Rcs in memory. However\nthis itself assumes that the `ref_count` accurately reflects the number of Rcs\nin memory, which we know is false with `mem::forget`. Using `mem::forget` we can\noverflow the `ref_count`, and then get it down to 0 with outstanding Rcs. Then\nwe can happily use-after-free the inner data. Bad Bad Not Good.\nThis can be solved by just checking the `ref_count` and doing *something*. The\nstandard library's stance is to just abort, because your program has become\nhorribly degenerate. Also *oh my gosh* it's such a ridiculous corner case.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Leaking", "heading_path": ["Leaking", "Rc"], "path": "leaking.md", "url": "https://doc.rust-lang.org/nomicon/leaking.html#rc", "has_code": false, "code_tags": []}} {"id": "nomicon/leaking.md#threadscopedjoinguard-6", "text": "The Rustonomicon › Leaking › thread::scoped::JoinGuard\n\nNote: This API has already been removed from std, for more information\nyou may refer issue #24292.\nThis section remains here because we think this example is still\nimportant, regardless of whether it is part of std or not.\nThe thread::scoped API intended to allow threads to be spawned that reference\ndata on their parent's stack without any synchronization over that data by\nensuring the parent joins the thread before any of the shared data goes out\nof scope.\n```rust,ignore\npub fn scoped<'a, F>(f: F) -> JoinGuard<'a>\n where F: FnOnce() + Send + 'a\n```\nHere `f` is some closure for the other thread to execute. Saying that\n`F: Send + 'a` is saying that it closes over data that lives for `'a`, and it\neither owns that data or the data was Sync (implying `&data` is Send).\nBecause JoinGuard has a lifetime, it keeps all the data it closes over\nborrowed in the parent thread. This means the JoinGuard can't outlive\nthe data that the other thread is working on. When the JoinGuard *does* get\ndropped it blocks the parent thread, ensuring the child terminates before any\nof the closed-over data goes out of scope in the parent.\nUsage looked like:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Leaking", "heading_path": ["Leaking", "thread::scoped::JoinGuard"], "path": "leaking.md", "url": "https://doc.rust-lang.org/nomicon/leaking.html#threadscopedjoinguard", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/leaking.md#threadscopedjoinguard-7", "text": "The Rustonomicon › Leaking › thread::scoped::JoinGuard\n\n```rust,ignore\nlet mut data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\n{\n let mut guards = vec![];\n for x in &mut data {\n // Move the mutable reference into the closure, and execute\n // it on a different thread. The closure has a lifetime bound\n // by the lifetime of the mutable reference `x` we store in it.\n // The guard that is returned is in turn assigned the lifetime\n // of the closure, so it also mutably borrows `data` as `x` did.\n // This means we cannot access `data` until the guard goes away.\n let guard = thread::scoped(move || {\n *x *= 2;\n });\n // store the thread's guard for later\n guards.push(guard);\n }\n // All guards are dropped here, forcing the threads to join\n // (this thread blocks here until the others terminate).\n // Once the threads join, the borrow expires and the data becomes\n // accessible again in this thread.\n}\n// data is definitely mutated here.\n```\nIn principle, this totally works! Rust's ownership system perfectly ensures it!\n...except it relies on a destructor being called to be safe.\n```rust,ignore\nlet mut data = Box::new(0);\n{\n let guard = thread::scoped(|| {\n // This is at best a data race. At worst, it's also a use-after-free.\n *data += 1;\n });\n // Because the guard is forgotten, expiring the loan without blocking this\n // thread.\n mem::forget(guard);\n}\n// So the Box is dropped here while the scoped thread may or may not be trying\n// to access it.\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Leaking", "heading_path": ["Leaking", "thread::scoped::JoinGuard"], "path": "leaking.md", "url": "https://doc.rust-lang.org/nomicon/leaking.html#threadscopedjoinguard", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/leaking.md#threadscopedjoinguard-8", "text": "The Rustonomicon › Leaking › thread::scoped::JoinGuard\n\nDang. Here the destructor running was pretty fundamental to the API, and it had\nto be scrapped in favor of a completely different design.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Leaking", "heading_path": ["Leaking", "thread::scoped::JoinGuard"], "path": "leaking.md", "url": "https://doc.rust-lang.org/nomicon/leaking.html#threadscopedjoinguard", "has_code": false, "code_tags": []}} {"id": "nomicon/unwinding.md#unwinding-0", "text": "The Rustonomicon › Unwinding\n\nRust has a *tiered* error-handling scheme:\n* If something might reasonably be absent, Option is used.\n* If something goes wrong and can reasonably be handled, Result is used.\n* If something goes wrong and cannot reasonably be handled, the thread panics.\n* If something catastrophic happens, the program aborts.\nOption and Result are overwhelmingly preferred in most situations, especially\nsince they can be promoted into a panic or abort at the API user's discretion.\nPanics cause the thread to halt normal execution and unwind its stack, calling\ndestructors as if every function instantly returned.\nAs of 1.0, Rust is of two minds when it comes to panics. In the long-long-ago,\nRust was much more like Erlang. Like Erlang, Rust had lightweight tasks,\nand tasks were intended to kill themselves with a panic when they reached an\nuntenable state. Unlike an exception in Java or C++, a panic could not be\ncaught at any time. Panics could only be caught by the owner of the task, at which\npoint they had to be handled or *that* task would itself panic.\nUnwinding was important to this story because if a task's\ndestructors weren't called, it would cause memory and other system resources to\nleak. Since tasks were expected to die during normal execution, this would make\nRust very poor for long-running systems!\nAs the Rust we know today came to be, this style of programming grew out of\nfashion in the push for less-and-less abstraction. Light-weight tasks were\nkilled in the name of heavy-weight OS threads. Still, on stable Rust as of 1.0\npanics can only be caught by the parent thread. This means catching a panic\nrequires spinning up an entire OS thread! This unfortunately stands in conflict\nto Rust's philosophy of zero-cost abstractions.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Unwinding", "heading_path": ["Unwinding"], "path": "unwinding.md", "url": "https://doc.rust-lang.org/nomicon/unwinding.html#unwinding", "has_code": false, "code_tags": []}} {"id": "nomicon/unwinding.md#unwinding-1", "text": "The Rustonomicon › Unwinding\n\nThere is an API called [`catch_unwind`] that enables catching a panic\nwithout spawning a thread. Still, we would encourage you to only do this\nsparingly. In particular, Rust's current unwinding implementation is heavily\noptimized for the \"doesn't unwind\" case. If a program doesn't unwind, there\nshould be no runtime cost for the program being *ready* to unwind. As a\nconsequence, actually unwinding will be more expensive than in e.g. Java.\nDon't build your programs to unwind under normal circumstances. Ideally, you\nshould only panic for programming errors or *extreme* problems.\nRust's unwinding strategy is not specified to be fundamentally compatible\nwith any other language's unwinding. As such, unwinding into Rust from another\nlanguage, or unwinding into another language from Rust is Undefined Behavior.\nYou must *absolutely* catch any panics at the FFI boundary! What you do at that\npoint is up to you, but *something* must be done. If you fail to do this,\nat best, your application will crash and burn. At worst, your application *won't*\ncrash and burn, and will proceed with completely clobbered state.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Unwinding", "heading_path": ["Unwinding"], "path": "unwinding.md", "url": "https://doc.rust-lang.org/nomicon/unwinding.html#unwinding", "has_code": false, "code_tags": []}} {"id": "nomicon/exception-safety.md#exception-safety-0", "text": "The Rustonomicon › Exception Safety\n\nAlthough programs should use unwinding sparingly, there's a lot of code that\n*can* panic. If you unwrap a None, index out of bounds, or divide by 0, your\nprogram will panic. On debug builds, every arithmetic operation can panic\nif it overflows. Unless you are very careful and tightly control what code runs,\npretty much everything can unwind, and you need to be ready for it.\nBeing ready for unwinding is often referred to as *exception safety*\nin the broader programming world. In Rust, there are two levels of exception\nsafety that one may concern themselves with:\n* In unsafe code, we *must* be exception safe to the point of not violating\n memory safety. We'll call this *minimal* exception safety.\n* In safe code, it is *good* to be exception safe to the point of your program\n doing the right thing. We'll call this *maximal* exception safety.\nAs is the case in many places in Rust, Unsafe code must be ready to deal with\nbad Safe code when it comes to unwinding. Code that transiently creates\nunsound states must be careful that a panic does not cause that state to be\nused. Generally this means ensuring that only non-panicking code is run while\nthese states exist, or making a guard that cleans up the state in the case of\na panic. This does not necessarily mean that the state a panic witnesses is a\nfully coherent state. We need only guarantee that it's a *safe* state.\nMost Unsafe code is leaf-like, and therefore fairly easy to make exception-safe.\nIt controls all the code that runs, and most of that code can't panic. However\nit is not uncommon for Unsafe code to work with arrays of temporarily\nuninitialized data while repeatedly invoking caller-provided code. Such code\nneeds to be careful and consider exception safety.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Exception Safety", "heading_path": ["Exception Safety"], "path": "exception-safety.md", "url": "https://doc.rust-lang.org/nomicon/exception-safety.html#exception-safety", "has_code": false, "code_tags": []}} {"id": "nomicon/exception-safety.md#vecpush_all-1", "text": "The Rustonomicon › Exception Safety › Vec::push_all\n\n`Vec::push_all` is a temporary hack to get extending a Vec by a slice reliably\nefficient without specialization. Here's a simple implementation:\n```rust,ignore\nimpl Vec {\n fn push_all(&mut self, to_push: &[T]) {\n self.reserve(to_push.len());\n unsafe {\n let end_ptr = self.as_mut_ptr().add(self.len());\n\n // can't overflow because we just reserved this\n self.set_len(self.len() + to_push.len());\n\n for (i, x) in to_push.iter().enumerate() {\n end_ptr.add(i).write(x.clone());\n }\n }\n }\n}\n```\nWe bypass `push` in order to avoid redundant capacity and `len` checks on the\nVec that we definitely know has capacity. The logic is totally correct, except\nthere's a subtle problem with our code: it's not exception-safe! `set_len`,\n`add`, and `write` are all fine; `clone` is the panic bomb we over-looked.\nClone is completely out of our control, and is totally free to panic. If it\ndoes, our function will exit early with the length of the Vec set too large. If\nthe Vec is looked at or dropped, uninitialized memory will be read!\nThe fix in this case is fairly simple. If we want to guarantee that the values\nwe *did* clone are dropped, we can set the `len` every loop iteration. If we\njust want to guarantee that uninitialized memory can't be observed, we can set\nthe `len` after the loop.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Exception Safety", "heading_path": ["Exception Safety", "Vec::push_all"], "path": "exception-safety.md", "url": "https://doc.rust-lang.org/nomicon/exception-safety.html#vecpush_all", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/exception-safety.md#binaryheapsift_up-2", "text": "The Rustonomicon › Exception Safety › BinaryHeap::sift_up\n\nBubbling an element up a heap is a bit more complicated than extending a Vec.\nThe pseudocode is as follows:\n```text\nbubble_up(heap, index):\n while index != 0 && heap[index] < heap[parent(index)]:\n heap.swap(index, parent(index))\n index = parent(index)\n```\nA literal transcription of this code to Rust is totally fine, but has an annoying\nperformance characteristic: the `self` element is swapped over and over again\nuselessly. We would rather have the following:\n```text\nbubble_up(heap, index):\n let elem = heap[index]\n while index != 0 && elem < heap[parent(index)]:\n heap[index] = heap[parent(index)]\n index = parent(index)\n heap[index] = elem\n```\nThis code ensures that each element is copied as little as possible (it is in\nfact necessary that elem be copied twice in general). However it now exposes\nsome exception safety trouble! At all times, there exists two copies of one\nvalue. If we panic in this function something will be double-dropped.\nUnfortunately, we also don't have full control of the code: that comparison is\nuser-defined!\nUnlike Vec, the fix isn't as easy here. One option is to break the user-defined\ncode and the unsafe code into two separate phases:\n```text\nbubble_up(heap, index):\n let end_index = index;\n while end_index != 0 && heap[index] < heap[parent(end_index)]:\n end_index = parent(end_index)\n\n let elem = heap[index]\n while index != end_index:\n heap[index] = heap[parent(index)]\n index = parent(index)\n heap[index] = elem\n```\nIf the user-defined code blows up, that's no problem anymore, because we haven't\nactually touched the state of the heap yet. Once we do start messing with the\nheap, we're working with only data and functions that we trust, so there's no\nconcern of panics.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Exception Safety", "heading_path": ["Exception Safety", "BinaryHeap::sift_up"], "path": "exception-safety.md", "url": "https://doc.rust-lang.org/nomicon/exception-safety.html#binaryheapsift_up", "has_code": true, "code_tags": ["text"]}} {"id": "nomicon/exception-safety.md#binaryheapsift_up-3", "text": "The Rustonomicon › Exception Safety › BinaryHeap::sift_up\n\nPerhaps you're not happy with this design. Surely it's cheating! And we have\nto do the complex heap traversal *twice*! Alright, let's bite the bullet. Let's\nintermix untrusted and unsafe code *for reals*.\nIf Rust had `try` and `finally` like in Java, we could do the following:\n```text\nbubble_up(heap, index):\n let elem = heap[index]\n try:\n        while index != 0 && elem < heap[parent(index)]:\n heap[index] = heap[parent(index)]\n index = parent(index)\n finally:\n heap[index] = elem\n```\nThe basic idea is simple: if the comparison panics, we just toss the loose\nelement in the logically uninitialized index and bail out. Anyone who observes\nthe heap will see a potentially *inconsistent* heap, but at least it won't\ncause any double-drops! If the algorithm terminates normally, then this\noperation happens to coincide precisely with how we finish up regardless.\nSadly, Rust has no such construct, so we're going to need to roll our own! The\nway to do this is to store the algorithm's state in a separate struct with a\ndestructor for the \"finally\" logic. Whether we panic or not, that destructor\nwill run and clean up after us.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Exception Safety", "heading_path": ["Exception Safety", "BinaryHeap::sift_up"], "path": "exception-safety.md", "url": "https://doc.rust-lang.org/nomicon/exception-safety.html#binaryheapsift_up", "has_code": true, "code_tags": ["text"]}} {"id": "nomicon/exception-safety.md#binaryheapsift_up-4", "text": "The Rustonomicon › Exception Safety › BinaryHeap::sift_up\n\n```rust,ignore\nstruct Hole<'a, T: 'a> {\n data: &'a mut [T],\n /// `elt` is always `Some` from new until drop.\n elt: Option,\n pos: usize,\n}\n\nimpl<'a, T> Hole<'a, T> {\n fn new(data: &'a mut [T], pos: usize) -> Self {\n unsafe {\n let elt = ptr::read(&data[pos]);\n Hole {\n data,\n elt: Some(elt),\n pos,\n }\n }\n }\n\n fn pos(&self) -> usize { self.pos }\n\n fn removed(&self) -> &T { self.elt.as_ref().unwrap() }\n\n fn get(&self, index: usize) -> &T { &self.data[index] }\n\n unsafe fn move_to(&mut self, index: usize) {\n let index_ptr: *const _ = &self.data[index];\n let hole_ptr = &mut self.data[self.pos];\n ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);\n self.pos = index;\n }\n}\n\nimpl<'a, T> Drop for Hole<'a, T> {\n fn drop(&mut self) {\n // fill the hole again\n unsafe {\n let pos = self.pos;\n ptr::write(&mut self.data[pos], self.elt.take().unwrap());\n }\n }\n}\n\nimpl BinaryHeap {\n fn sift_up(&mut self, pos: usize) {\n unsafe {\n // Take out the value at `pos` and create a hole.\n let mut hole = Hole::new(&mut self.data, pos);\n\n while hole.pos() != 0 {\n let parent = parent(hole.pos());\n if hole.removed() <= hole.get(parent) { break }\n hole.move_to(parent);\n }\n // Hole will be unconditionally filled here; panic or not!\n }\n }\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Exception Safety", "heading_path": ["Exception Safety", "BinaryHeap::sift_up"], "path": "exception-safety.md", "url": "https://doc.rust-lang.org/nomicon/exception-safety.html#binaryheapsift_up", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/poisoning.md#poisoning-0", "text": "The Rustonomicon › Poisoning\n\nAlthough all unsafe code *must* ensure it has minimal exception safety, not all\ntypes ensure *maximal* exception safety. Even if the type does, your code may\nascribe additional meaning to it. For instance, an integer is certainly\nexception-safe, but has no semantics on its own. It's possible that code that\npanics could fail to correctly update the integer, producing an inconsistent\nprogram state.\nThis is *usually* fine, because anything that witnesses an exception is about\nto get destroyed. For instance, if you send a Vec to another thread and that\nthread panics, it doesn't matter if the Vec is in a weird state. It will be\ndropped and go away forever. However some types are especially good at smuggling\nvalues across the panic boundary.\nThese types may choose to explicitly *poison* themselves if they witness a panic.\nPoisoning doesn't entail anything in particular. Generally it just means\npreventing normal usage from proceeding. The most notable example of this is the\nstandard library's Mutex type. A Mutex will poison itself if one of its\nMutexGuards (the thing it returns when a lock is obtained) is dropped during a\npanic. Any future attempts to lock the Mutex will return an `Err` or panic.\nMutex poisons not for true safety in the sense that Rust normally cares about. It\npoisons as a safety-guard against blindly using the data that comes out of a Mutex\nthat has witnessed a panic while locked. The data in such a Mutex was likely in the\nmiddle of being modified, and as such may be in an inconsistent or incomplete state.\nIt is important to note that one cannot violate memory safety with such a type\nif it is correctly written. After all, it must be minimally exception-safe!", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Poisoning", "heading_path": ["Poisoning"], "path": "poisoning.md", "url": "https://doc.rust-lang.org/nomicon/poisoning.html#poisoning", "has_code": false, "code_tags": []}} {"id": "nomicon/poisoning.md#poisoning-1", "text": "The Rustonomicon › Poisoning\n\nHowever if the Mutex contained, say, a BinaryHeap that does not actually have the\nheap property, it's unlikely that any code that uses it will do\nwhat the author intended. As such, the program should not proceed normally.\nStill, if you're double-plus-sure that you can do *something* with the value,\nthe Mutex exposes a method to get the lock anyway. It *is* safe, after all.\nJust maybe nonsense.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Poisoning", "heading_path": ["Poisoning"], "path": "poisoning.md", "url": "https://doc.rust-lang.org/nomicon/poisoning.html#poisoning", "has_code": false, "code_tags": []}} {"id": "nomicon/concurrency.md#concurrency-and-parallelism-0", "text": "The Rustonomicon › Concurrency and Parallelism\n\nRust as a language doesn't *really* have an opinion on how to do concurrency or\nparallelism. The standard library exposes OS threads and blocking sys-calls\nbecause everyone has those, and they're uniform enough that you can provide\nan abstraction over them in a relatively uncontroversial way. Message passing,\ngreen threads, and async APIs are all diverse enough that any abstraction over\nthem tends to involve trade-offs that we weren't willing to commit to for 1.0.\nHowever the way Rust models concurrency makes it relatively easy to design your own\nconcurrency paradigm as a library and have everyone else's code Just Work\nwith yours. Just require the right lifetimes and Send and Sync where appropriate\nand you're off to the races. Or rather, off to the... not... having... races.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Concurrency", "heading_path": ["Concurrency and Parallelism"], "path": "concurrency.md", "url": "https://doc.rust-lang.org/nomicon/concurrency.html#concurrency-and-parallelism", "has_code": false, "code_tags": []}} {"id": "nomicon/races.md#data-races-and-race-conditions-0", "text": "The Rustonomicon › Data Races and Race Conditions\n\nSafe Rust guarantees an absence of data races, which are defined as:\n* two or more threads concurrently accessing a location of memory\n* one or more of them is a write\n* one or more of them is unsynchronized\nA data race has Undefined Behavior, and is therefore impossible to perform in\nSafe Rust. Data races are prevented *mostly* through Rust's ownership system alone:\nit's impossible to alias a mutable reference, so it's impossible to perform a\ndata race. Interior mutability makes this more complicated, which is largely why\nwe have the Send and Sync traits (see the next section for more on this).\n**However Rust does not prevent general race conditions.**\nThis is mathematically impossible in situations where you do not control the\nscheduler, which is true for the normal OS environment. If you do control\npreemption, it _can be_ possible to prevent general races - this technique is\nused by frameworks such as RTIC. However,\nactually having control over scheduling is a very uncommon case.\nFor this reason, it is considered \"safe\" for Rust to get deadlocked or do\nsomething nonsensical with incorrect synchronization: this is known as a general\nrace condition or resource race. Obviously such a program isn't very good, but\nRust of course cannot prevent all logic errors.\nIn any case, a race condition cannot violate memory safety in a Rust program on\nits own. Only in conjunction with some other unsafe code can a race condition\nactually violate memory safety. For instance, a correct program looks like this:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Races", "heading_path": ["Data Races and Race Conditions"], "path": "races.md", "url": "https://doc.rust-lang.org/nomicon/races.html#data-races-and-race-conditions", "has_code": false, "code_tags": []}} {"id": "nomicon/races.md#data-races-and-race-conditions-1", "text": "The Rustonomicon › Data Races and Race Conditions\n\n```rust,no_run\nuse std::thread;\nuse std::sync::atomic::{AtomicUsize, Ordering};\nuse std::sync::Arc;\n\nlet data = vec![1, 2, 3, 4];\n// Arc so that the memory the AtomicUsize is stored in still exists for\n// the other thread to increment, even if we completely finish executing\n// before it. Rust won't compile the program without it, because of the\n// lifetime requirements of thread::spawn!\nlet idx = Arc::new(AtomicUsize::new(0));\nlet other_idx = idx.clone();\n\n// `move` captures other_idx by-value, moving it into this thread\nthread::spawn(move || {\n // It's ok to mutate idx because this value\n // is an atomic, so it can't cause a Data Race.\n other_idx.fetch_add(10, Ordering::SeqCst);\n});\n\n// Index with the value loaded from the atomic. This is safe because we\n// read the atomic memory only once, and then pass a copy of that value\n// to the Vec's indexing implementation. This indexing will be correctly\n// bounds checked, and there's no chance of the value getting changed\n// in the middle. However our program may panic if the thread we spawned\n// managed to increment before this ran. A race condition because correct\n// program execution (panicking is rarely correct) depends on order of\n// thread execution.\nprintln!(\"{}\", data[idx.load(Ordering::SeqCst)]);\n```\nWe can cause a race condition to violate memory safety if we instead do the bound\ncheck in advance, and then unsafely access the data with an unchecked value:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Races", "heading_path": ["Data Races and Race Conditions"], "path": "races.md", "url": "https://doc.rust-lang.org/nomicon/races.html#data-races-and-race-conditions", "has_code": true, "code_tags": ["rust,no_run"]}} {"id": "nomicon/races.md#data-races-and-race-conditions-2", "text": "The Rustonomicon › Data Races and Race Conditions\n\n```rust,no_run\nuse std::thread;\nuse std::sync::atomic::{AtomicUsize, Ordering};\nuse std::sync::Arc;\n\nlet data = vec![1, 2, 3, 4];\n\nlet idx = Arc::new(AtomicUsize::new(0));\nlet other_idx = idx.clone();\n\n// `move` captures other_idx by-value, moving it into this thread\nthread::spawn(move || {\n // It's ok to mutate idx because this value\n // is an atomic, so it can't cause a Data Race.\n other_idx.fetch_add(10, Ordering::SeqCst);\n});\n\nif idx.load(Ordering::SeqCst) < data.len() {\n unsafe {\n // Incorrectly loading the idx after we did the bounds check.\n // It could have changed. This is a race condition, *and dangerous*\n // because we decided to do `get_unchecked`, which is `unsafe`.\n println!(\"{}\", data.get_unchecked(idx.load(Ordering::SeqCst)));\n }\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Races", "heading_path": ["Data Races and Race Conditions"], "path": "races.md", "url": "https://doc.rust-lang.org/nomicon/races.html#data-races-and-race-conditions", "has_code": true, "code_tags": ["rust,no_run"]}} {"id": "nomicon/send-and-sync.md#send-and-sync-0", "text": "The Rustonomicon › Send and Sync\n\nNot everything obeys inherited mutability, though. Some types allow you to\nhave multiple aliases of a location in memory while mutating it. Unless these types use\nsynchronization to manage this access, they are absolutely not thread-safe. Rust\ncaptures this through the `Send` and `Sync` traits.\n* A type is Send if it is safe to send it to another thread.\n* A type is Sync if it is safe to share between threads (T is Sync if and only if `&T` is Send).\nSend and Sync are fundamental to Rust's concurrency story. As such, a\nsubstantial amount of special tooling exists to make them work right. First and\nforemost, they're [unsafe traits]. This means that they are unsafe to\nimplement, and other unsafe code can assume that they are correctly\nimplemented. Since they're *marker traits* (they have no associated items like\nmethods), correctly implemented simply means that they have the intrinsic\nproperties an implementor should have. Incorrectly implementing Send or Sync can\ncause Undefined Behavior.\nSend and Sync are also automatically derived traits. This means that, unlike\nevery other trait, if a type is composed entirely of Send or Sync types, then it\nis Send or Sync. Almost all primitives are Send and Sync, and as a consequence\npretty much all types you'll ever interact with are Send and Sync.\nMajor exceptions include:\n* raw pointers are neither Send nor Sync (because they have no safety guards).\n* `UnsafeCell` isn't Sync (and therefore `Cell` and `RefCell` aren't).\n* `Rc` isn't Send or Sync (because the refcount is shared and unsynchronized).", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Send and Sync", "heading_path": ["Send and Sync"], "path": "send-and-sync.md", "url": "https://doc.rust-lang.org/nomicon/send-and-sync.html#send-and-sync", "has_code": false, "code_tags": []}} {"id": "nomicon/send-and-sync.md#send-and-sync-1", "text": "The Rustonomicon › Send and Sync\n\n`Rc` and `UnsafeCell` are very fundamentally not thread-safe: they enable\nunsynchronized shared mutable state. However raw pointers are, strictly\nspeaking, marked as thread-unsafe as more of a *lint*. Doing anything useful\nwith a raw pointer requires dereferencing it, which is already unsafe. In that\nsense, one could argue that it would be \"fine\" for them to be marked as thread\nsafe.\nHowever it's important that they aren't thread-safe to prevent types that\ncontain them from being automatically marked as thread-safe. These types have\nnon-trivial untracked ownership, and it's unlikely that their author was\nnecessarily thinking hard about thread safety. In the case of `Rc`, we have a nice\nexample of a type that contains a `*mut` that is definitely not thread-safe.\nTypes that aren't automatically derived can simply implement them if desired:\n```rust\nstruct MyBox(*mut u8);\n\nunsafe impl Send for MyBox {}\nunsafe impl Sync for MyBox {}\n```\nIn the *incredibly rare* case that a type is inappropriately automatically\nderived to be Send or Sync, then one can also unimplement Send and Sync:\n```rust\n#![feature(negative_impls)]\n\n// I have some magic semantics for some synchronization primitive!\nstruct SpecialThreadToken(u8);\n\nimpl !Send for SpecialThreadToken {}\nimpl !Sync for SpecialThreadToken {}\n```\nNote that *in and of itself* it is impossible to incorrectly derive Send and\nSync. Only types that are ascribed special meaning by other unsafe code can\npossibly cause trouble by being incorrectly Send or Sync.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Send and Sync", "heading_path": ["Send and Sync"], "path": "send-and-sync.md", "url": "https://doc.rust-lang.org/nomicon/send-and-sync.html#send-and-sync", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/send-and-sync.md#send-and-sync-2", "text": "The Rustonomicon › Send and Sync\n\nMost uses of raw pointers should be encapsulated behind a sufficient abstraction\nthat Send and Sync can be derived. For instance all of Rust's standard\ncollections are Send and Sync (when they contain Send and Sync types) in spite\nof their pervasive use of raw pointers to manage allocations and complex ownership.\nSimilarly, most iterators into these collections are Send and Sync because they\nlargely behave like an `&` or `&mut` into the collection.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Send and Sync", "heading_path": ["Send and Sync"], "path": "send-and-sync.md", "url": "https://doc.rust-lang.org/nomicon/send-and-sync.html#send-and-sync", "has_code": false, "code_tags": []}} {"id": "nomicon/send-and-sync.md#example-3", "text": "The Rustonomicon › Send and Sync › Example\n\n`Box` is implemented as its own special intrinsic type by the\ncompiler for various reasons, but we can implement something\nwith similar-ish behavior ourselves to see an example of when it is sound to\nimplement Send and Sync. Let's call it a `Carton`.\nWe start by writing code to take a value allocated on the stack and transfer it\nto the heap.\n```rust\nuse std::{\n mem::{align_of, size_of},\n ptr,\n cmp::max,\n};\n\nstruct Carton(ptr::NonNull);\n\nimpl Carton {\n pub fn new(value: T) -> Self {\n // Allocate enough memory on the heap to store one T.\n assert_ne!(size_of::(), 0, \"Zero-sized types are out of the scope of this example\");\n let mut memptr: *mut T = ptr::null_mut();\n unsafe {\n let ret = libc::posix_memalign(\n (&mut memptr as *mut *mut T).cast(),\n max(align_of::(), size_of::()),\n size_of::()\n );\n assert_eq!(ret, 0, \"Failed to allocate or invalid alignment\");\n };\n\n // NonNull is just a wrapper that enforces that the pointer isn't null.\n let ptr = {\n // Safety: memptr is dereferenceable because we created it from a\n // reference and have exclusive access.\n ptr::NonNull::new(memptr)\n .expect(\"Guaranteed non-null if posix_memalign returns 0\")\n };\n\n // Move value from the stack to the location we allocated on the heap.\n unsafe {\n // Safety: If non-null, posix_memalign gives us a ptr that is valid\n // for writes and properly aligned.\n ptr.as_ptr().write(value);\n }\n\n Self(ptr)\n }\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Send and Sync", "heading_path": ["Send and Sync", "Example"], "path": "send-and-sync.md", "url": "https://doc.rust-lang.org/nomicon/send-and-sync.html#example", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/send-and-sync.md#example-4", "text": "The Rustonomicon › Send and Sync › Example\n\nThis isn't very useful, because once our users give us a value they have no way\nto access it. `Box` implements `Deref` and\n`DerefMut` so that you can access the inner value. Let's do\nthat.\n```rust\nuse std::ops::{Deref, DerefMut};\n\nimpl Deref for Carton {\n type Target = T;\n\n fn deref(&self) -> &Self::Target {\n unsafe {\n // Safety: The pointer is aligned, initialized, and dereferenceable\n // by the logic in [`Self::new`]. We require readers to borrow the\n // Carton, and the lifetime of the return value is elided to the\n // lifetime of the input. This means the borrow checker will\n // enforce that no one can mutate the contents of the Carton until\n // the reference returned is dropped.\n self.0.as_ref()\n }\n }\n}\n\nimpl DerefMut for Carton {\n fn deref_mut(&mut self) -> &mut Self::Target {\n unsafe {\n // Safety: The pointer is aligned, initialized, and dereferenceable\n // by the logic in [`Self::new`]. We require writers to mutably\n // borrow the Carton, and the lifetime of the return value is\n // elided to the lifetime of the input. This means the borrow\n // checker will enforce that no one else can access the contents\n // of the Carton until the mutable reference returned is dropped.\n self.0.as_mut()\n }\n }\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Send and Sync", "heading_path": ["Send and Sync", "Example"], "path": "send-and-sync.md", "url": "https://doc.rust-lang.org/nomicon/send-and-sync.html#example", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/send-and-sync.md#example-5", "text": "The Rustonomicon › Send and Sync › Example\n\nFinally, let's think about whether our `Carton` is Send and Sync. Something can\nsafely be Send unless it shares mutable state with something else without\nenforcing exclusive access to it. Each `Carton` has a unique pointer, so\nwe're good.\n```rust\n// Safety: No one besides us has the raw pointer, so we can safely transfer the\n// Carton to another thread if T can be safely transferred.\nunsafe impl Send for Carton where T: Send {}\n```\nWhat about Sync? For `Carton` to be Sync we have to enforce that you can't\nwrite to something stored in a `&Carton` while that same something could be read\nor written to from another `&Carton`. Since you need an `&mut Carton` to\nwrite to the pointer, and the borrow checker enforces that mutable\nreferences must be exclusive, there are no soundness issues making `Carton`\nsync either.\n```rust\n// Safety: Since there exists a public way to go from a `&Carton` to a `&T`\n// in an unsynchronized fashion (such as `Deref`), then `Carton` can't be\n// `Sync` if `T` isn't.\n// Conversely, `Carton` itself does not use any interior mutability whatsoever:\n// all the mutations are performed through an exclusive reference (`&mut`). This\n// means it suffices that `T` be `Sync` for `Carton` to be `Sync`:\nunsafe impl Sync for Carton where T: Sync {}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Send and Sync", "heading_path": ["Send and Sync", "Example"], "path": "send-and-sync.md", "url": "https://doc.rust-lang.org/nomicon/send-and-sync.html#example", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/send-and-sync.md#example-6", "text": "The Rustonomicon › Send and Sync › Example\n\nWhen we assert our type is Send and Sync we usually need to enforce that every\ncontained type is Send and Sync. When writing custom types that behave like\nstandard library types we can assert that we have the same requirements.\nFor example, the following code asserts that a Carton is Send if the same\nsort of Box would be Send, which in this case is the same as saying T is Send.\n```rust\nunsafe impl Send for Carton where Box: Send {}\n```\nRight now `Carton` has a memory leak, as it never frees the memory it allocates.\nOnce we fix that we have a new requirement we have to ensure we meet to be Send:\nwe need to know `free` can be called on a pointer that was yielded by an\nallocation done on another thread. We can check this is true in the docs for\n`libc::free`.\n```rust\nimpl Drop for Carton {\n fn drop(&mut self) {\n unsafe {\n libc::free(self.0.as_ptr().cast());\n }\n }\n}\n```\nA nice example where this does not happen is with a MutexGuard: notice how\nit is not Send. The implementation of MutexGuard\nuses libraries that require you to ensure you\ndon't try to free a lock that you acquired in a different thread. If you were\nable to Send a MutexGuard to another thread the destructor would run in the\nthread you sent it to, violating the requirement. MutexGuard can still be Sync\nbecause all you can send to another thread is an `&MutexGuard` and dropping a\nreference does nothing.\nTODO: better explain what can or can't be Send or Sync. Sufficient to appeal\nonly to data races?", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Send and Sync", "heading_path": ["Send and Sync", "Example"], "path": "send-and-sync.md", "url": "https://doc.rust-lang.org/nomicon/send-and-sync.html#example", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/atomics.md#atomics-0", "text": "The Rustonomicon › Atomics\n\nRust pretty blatantly just inherits the memory model for atomics from C++20. This is not\ndue to this model being particularly excellent or easy to understand. Indeed,\nthis model is quite complex and known to have several flaws.\nRather, it is a pragmatic concession to the fact that *everyone* is pretty bad\nat modeling atomics. At the very least, we can benefit from existing tooling and\nresearch around the C/C++ memory model.\n(You'll often see this model referred to as \"C/C++11\" or just \"C11\". C just copies\nthe C++ memory model; and C++11 was the first version of the model but it has\nreceived some bugfixes since then.)\nTrying to fully explain the model in this book is fairly hopeless. It's defined\nin terms of madness-inducing causality graphs that require a full book to\nproperly understand in a practical way. If you want all the nitty-gritty\ndetails, you should check out the C++ specification.\nStill, we'll try to cover the basics and some of the problems Rust developers\nface.\nThe C++ memory model is fundamentally about trying to bridge the gap between the\nsemantics we want, the optimizations compilers want, and the inconsistent chaos\nour hardware wants. *We* would like to just write programs and have them do\nexactly what we said but, you know, fast. Wouldn't that be great?", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Atomics", "heading_path": ["Atomics"], "path": "atomics.md", "url": "https://doc.rust-lang.org/nomicon/atomics.html#atomics", "has_code": false, "code_tags": []}} {"id": "nomicon/atomics.md#compiler-reordering-1", "text": "The Rustonomicon › Atomics › Compiler Reordering\n\nCompilers fundamentally want to be able to do all sorts of complicated\ntransformations to reduce data dependencies and eliminate dead code. In\nparticular, they may radically change the actual order of events, or make events\nnever occur! If we write something like:\n```rust,ignore\nx = 1;\ny = 3;\nx = 2;\n```\nThe compiler may conclude that it would be best if your program did:\n```rust,ignore\nx = 2;\ny = 3;\n```\nThis has inverted the order of events and completely eliminated one event.\nFrom a single-threaded perspective this is completely unobservable: after all\nthe statements have executed we are in exactly the same state. But if our\nprogram is multi-threaded, we may have been relying on `x` to actually be\nassigned to 1 before `y` was assigned. We would like the compiler to be\nable to make these kinds of optimizations, because they can seriously improve\nperformance. On the other hand, we'd also like to be able to depend on our\nprogram *doing the thing we said*.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Atomics", "heading_path": ["Atomics", "Compiler Reordering"], "path": "atomics.md", "url": "https://doc.rust-lang.org/nomicon/atomics.html#compiler-reordering", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/atomics.md#hardware-reordering-2", "text": "The Rustonomicon › Atomics › Hardware Reordering\n\nOn the other hand, even if the compiler totally understood what we wanted and\nrespected our wishes, our hardware might instead get us in trouble. Trouble\ncomes from CPUs in the form of memory hierarchies. There is indeed a global\nshared memory space somewhere in your hardware, but from the perspective of each\nCPU core it is *so very far away* and *so very slow*. Each CPU would rather work\nwith its local cache of the data and only go through all the anguish of\ntalking to shared memory only when it doesn't actually have that memory in\ncache.\nAfter all, that's the whole point of the cache, right? If every read from the\ncache had to run back to shared memory to double check that it hadn't changed,\nwhat would the point be? The end result is that the hardware doesn't guarantee\nthat events that occur in some order on *one* thread, occur in the same\norder on *another* thread. To guarantee this, we must issue special instructions\nto the CPU telling it to be a bit less smart.\nFor instance, say we convince the compiler to emit this logic:\n```text\ninitial state: x = 0, y = 1\n\nTHREAD 1 THREAD 2\ny = 3; if x == 1 {\nx = 1; y *= 2;\n }\n```\nIdeally this program has 2 possible final states:\n* `y = 3`: (thread 2 did the check before thread 1 completed)\n* `y = 6`: (thread 2 did the check after thread 1 completed)\nHowever there's a third potential state that the hardware enables:\n* `y = 2`: (thread 2 saw `x = 1`, but not `y = 3`, and then overwrote `y = 3`)", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Atomics", "heading_path": ["Atomics", "Hardware Reordering"], "path": "atomics.md", "url": "https://doc.rust-lang.org/nomicon/atomics.html#hardware-reordering", "has_code": true, "code_tags": ["text"]}} {"id": "nomicon/atomics.md#hardware-reordering-3", "text": "The Rustonomicon › Atomics › Hardware Reordering\n\nIt's worth noting that different kinds of CPU provide different guarantees. It\nis common to separate hardware into two categories: strongly-ordered and weakly-ordered.\nMost notably x86/64 provides strong ordering guarantees, while ARM\nprovides weak ordering guarantees. This has two consequences for concurrent\nprogramming:\n* Asking for stronger guarantees on strongly-ordered hardware may be cheap or\n even free because they already provide strong guarantees unconditionally.\n Weaker guarantees may only yield performance wins on weakly-ordered hardware.\n* Asking for guarantees that are too weak on strongly-ordered hardware is\n more likely to *happen* to work, even though your program is strictly\n incorrect. If possible, concurrent algorithms should be tested on\n weakly-ordered hardware.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Atomics", "heading_path": ["Atomics", "Hardware Reordering"], "path": "atomics.md", "url": "https://doc.rust-lang.org/nomicon/atomics.html#hardware-reordering", "has_code": false, "code_tags": []}} {"id": "nomicon/atomics.md#data-accesses-4", "text": "The Rustonomicon › Atomics › Data Accesses\n\nThe C++ memory model attempts to bridge the gap by allowing us to talk about the\n*causality* of our program. Generally, this is by establishing a *happens\nbefore* relationship between parts of the program and the threads that are\nrunning them. This gives the hardware and compiler room to optimize the program\nmore aggressively where a strict happens-before relationship isn't established,\nbut forces them to be more careful where one is established. The way we\ncommunicate these relationships are through *data accesses* and *atomic\naccesses*.\nData accesses are the bread-and-butter of the programming world. They are\nfundamentally unsynchronized and compilers are free to aggressively optimize\nthem. In particular, data accesses are free to be reordered by the compiler on\nthe assumption that the program is single-threaded. The hardware is also free to\npropagate the changes made in data accesses to other threads as lazily and\ninconsistently as it wants. Most critically, data accesses are how data races\nhappen. Data accesses are very friendly to the hardware and compiler, but as\nwe've seen they offer *awful* semantics to try to write synchronized code with.\nActually, that's too weak.\n**It is literally impossible to write correct synchronized code using only data\naccesses.**\nAtomic accesses are how we tell the hardware and compiler that our program is\nmulti-threaded. Each atomic access can be marked with an *ordering* that\nspecifies what kind of relationship it establishes with other accesses. In\npractice, this boils down to telling the compiler and hardware certain things\nthey *can't* do. For the compiler, this largely revolves around re-ordering of\ninstructions. For the hardware, this largely revolves around how writes are\npropagated to other threads. The set of orderings Rust exposes are:\n* Sequentially Consistent (SeqCst)\n* Release\n* Acquire\n* Relaxed\n(Note: We explicitly do not expose the C++ *consume* ordering)", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Atomics", "heading_path": ["Atomics", "Data Accesses"], "path": "atomics.md", "url": "https://doc.rust-lang.org/nomicon/atomics.html#data-accesses", "has_code": false, "code_tags": []}} {"id": "nomicon/atomics.md#data-accesses-5", "text": "The Rustonomicon › Atomics › Data Accesses\n\nTODO: negative reasoning vs positive reasoning? TODO: \"can't forget to\nsynchronize\"", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Atomics", "heading_path": ["Atomics", "Data Accesses"], "path": "atomics.md", "url": "https://doc.rust-lang.org/nomicon/atomics.html#data-accesses", "has_code": false, "code_tags": []}} {"id": "nomicon/atomics.md#sequentially-consistent-6", "text": "The Rustonomicon › Atomics › Sequentially Consistent\n\nSequentially Consistent is the most powerful of all, implying the restrictions\nof all other orderings. Intuitively, a sequentially consistent operation\ncannot be reordered: all accesses on one thread that happen before and after a\nSeqCst access stay before and after it. A data-race-free program that uses\nonly sequentially consistent atomics and data accesses has the very nice\nproperty that there is a single global execution of the program's instructions\nthat all threads agree on. This execution is also particularly nice to reason\nabout: it's just an interleaving of each thread's individual executions. This\ndoes not hold if you start using the weaker atomic orderings.\nThe relative developer-friendliness of sequential consistency doesn't come for\nfree. Even on strongly-ordered platforms sequential consistency involves\nemitting memory fences.\nIn practice, sequential consistency is rarely necessary for program correctness.\nHowever sequential consistency is definitely the right choice if you're not\nconfident about the other memory orders. Having your program run a bit slower\nthan it needs to is certainly better than it running incorrectly! It's also\nmechanically trivial to downgrade atomic operations to have a weaker\nconsistency later on. Just change `SeqCst` to `Relaxed` and you're done! Of\ncourse, proving that this transformation is *correct* is a whole other matter.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Atomics", "heading_path": ["Atomics", "Sequentially Consistent"], "path": "atomics.md", "url": "https://doc.rust-lang.org/nomicon/atomics.html#sequentially-consistent", "has_code": false, "code_tags": []}} {"id": "nomicon/atomics.md#acquire-release-7", "text": "The Rustonomicon › Atomics › Acquire-Release\n\nAcquire and Release are largely intended to be paired. Their names hint at their\nuse case: they're perfectly suited for acquiring and releasing locks, and\nensuring that critical sections don't overlap.\nIntuitively, an acquire access ensures that every access after it stays after\nit. However operations that occur before an acquire are free to be reordered to\noccur after it. Similarly, a release access ensures that every access before it\nstays before it. However operations that occur after a release are free to be\nreordered to occur before it.\nWhen thread A releases a location in memory and then thread B subsequently\nacquires *the same* location in memory, causality is established. Every write\n(including non-atomic and relaxed atomic writes) that happened before A's\nrelease will be observed by B after its acquisition. However no causality is\nestablished with any other threads. Similarly, no causality is established\nif A and B access *different* locations in memory.\nBasic use of release-acquire is therefore simple: you acquire a location of\nmemory to begin the critical section, and then release that location to end it.\nFor instance, a simple spinlock might look like:\n```rust\nuse std::sync::Arc;\nuse std::sync::atomic::{AtomicBool, Ordering};\nuse std::thread;\n\nfn main() {\n let lock = Arc::new(AtomicBool::new(false)); // value answers \"am I locked?\"\n\n // ... distribute lock to threads somehow ...\n\n // Try to acquire the lock by setting it to true\n while lock.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed).is_err() { }\n // broke out of the loop, so we successfully acquired the lock!\n\n // ... scary data accesses ...\n\n // ok we're done, release the lock\n lock.store(false, Ordering::Release);\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Atomics", "heading_path": ["Atomics", "Acquire-Release"], "path": "atomics.md", "url": "https://doc.rust-lang.org/nomicon/atomics.html#acquire-release", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/atomics.md#acquire-release-8", "text": "The Rustonomicon › Atomics › Acquire-Release\n\nOn strongly-ordered platforms most accesses have release or acquire semantics,\nmaking release and acquire often totally free. This is not the case on\nweakly-ordered platforms.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Atomics", "heading_path": ["Atomics", "Acquire-Release"], "path": "atomics.md", "url": "https://doc.rust-lang.org/nomicon/atomics.html#acquire-release", "has_code": false, "code_tags": []}} {"id": "nomicon/atomics.md#relaxed-9", "text": "The Rustonomicon › Atomics › Relaxed\n\nRelaxed accesses are the absolute weakest. They can be freely re-ordered and\nprovide no happens-before relationship. Still, relaxed operations are still\natomic. That is, they don't count as data accesses and any read-modify-write\noperations done to them occur atomically. Relaxed operations are appropriate for\nthings that you definitely want to happen, but don't particularly otherwise care\nabout. For instance, incrementing a counter can be safely done by multiple\nthreads using a relaxed `fetch_add` if you're not using the counter to\nsynchronize any other accesses.\nThere's rarely a benefit in making an operation relaxed on strongly-ordered\nplatforms, since they usually provide release-acquire semantics anyway. However\nrelaxed operations can be cheaper on weakly-ordered platforms.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Atomics", "heading_path": ["Atomics", "Relaxed"], "path": "atomics.md", "url": "https://doc.rust-lang.org/nomicon/atomics.html#relaxed", "has_code": false, "code_tags": []}} {"id": "nomicon/vec/vec.md#example-implementing-vec-0", "text": "The Rustonomicon › Example: Implementing Vec\n\nTo bring everything together, we're going to write `std::Vec` from scratch.\nWe will limit ourselves to stable Rust. In particular we won't use any\nintrinsics that could make our code a little bit nicer or efficient because\nintrinsics are permanently unstable. Although many intrinsics *do* become\nstabilized elsewhere (`std::ptr` and `std::mem` consist of many intrinsics).\nUltimately this means our implementation may not take advantage of all\npossible optimizations, though it will be by no means *naive*. We will\ndefinitely get into the weeds over nitty-gritty details, even\nwhen the problem doesn't *really* merit it.\nYou wanted advanced. We're gonna go advanced.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Implementing Vec", "heading_path": ["Example: Implementing Vec"], "path": "vec/vec.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec.html#example-implementing-vec", "has_code": false, "code_tags": []}} {"id": "nomicon/vec/vec-layout.md#layout-0", "text": "The Rustonomicon › Layout\n\nFirst off, we need to come up with the struct layout. A Vec has three parts:\na pointer to the allocation, the size of the allocation, and the number of\nelements that have been initialized.\nNaively, this means we just want this design:\n```rust,ignore\npub struct Vec {\n ptr: *mut T,\n cap: usize,\n len: usize,\n}\n```\nAnd indeed this would compile. Unfortunately, it would be too strict. The\ncompiler will give us too strict variance. So a `&Vec<&'static str>`\ncouldn't be used where a `&Vec<&'a str>` was expected. See the chapter\non ownership and lifetimes for all the details on variance.\nAs we saw in the ownership chapter, the standard library uses `Unique` in place of\n`*mut T` when it has a raw pointer to an allocation that it owns. Unique is unstable,\nso we'd like to not use it if possible, though.\nAs a recap, Unique is a wrapper around a raw pointer that declares that:\n* We are covariant over `T`\n* We may own a value of type `T` (this is not relevant for our example here, but see \n the chapter on PhantomData on why the real `std::vec::Vec` needs this)\n* We are Send/Sync if `T` is Send/Sync\n* Our pointer is never null (so `Option>` is null-pointer-optimized)", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Layout", "heading_path": ["Layout"], "path": "vec/vec-layout.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-layout.html#layout", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/vec/vec-layout.md#layout-1", "text": "The Rustonomicon › Layout\n\nWe can implement all of the above requirements in stable Rust. To do this, instead\nof using `Unique` we will use `NonNull`, another wrapper around a\nraw pointer, which gives us two of the above properties, namely it is covariant\nover `T` and is declared to never be null. By implementing Send/Sync if `T` is,\nwe get the same results as using `Unique`:\n```rust\nuse std::ptr::NonNull;\n\npub struct Vec {\n ptr: NonNull,\n cap: usize,\n len: usize,\n}\n\nunsafe impl Send for Vec {}\nunsafe impl Sync for Vec {}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Layout", "heading_path": ["Layout"], "path": "vec/vec-layout.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-layout.html#layout", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/vec/vec-alloc.md#allocating-memory-0", "text": "The Rustonomicon › Allocating Memory\n\nUsing `NonNull` throws a wrench in an important feature of Vec (and indeed all of\nthe std collections): creating an empty Vec doesn't actually allocate at all. This\nis not the same as allocating a zero-sized memory block, which is not allowed by\nthe global allocator (it results in undefined behavior!). So if we can't allocate,\nbut also can't put a null pointer in `ptr`, what do we do in `Vec::new`? Well, we\njust put some other garbage in there!\nThis is perfectly fine because we already have `cap == 0` as our sentinel for no\nallocation. We don't even need to handle it specially in almost any code because\nwe usually need to check if `cap > len` or `len > 0` anyway. The recommended\nRust value to put here is `mem::align_of::()`. `NonNull` provides a convenience\nfor this: `NonNull::dangling()`. There are quite a few places where we'll\nwant to use `dangling` because there's no real allocation to talk about but\n`null` would make the compiler do bad things.\nSo:\n```rust,ignore\nuse std::mem;\n\nimpl Vec {\n pub fn new() -> Self {\n assert!(mem::size_of::() != 0, \"We're not ready to handle ZSTs\");\n Vec {\n ptr: NonNull::dangling(),\n len: 0,\n cap: 0,\n }\n }\n}\n```\nI slipped in that assert there because zero-sized types will require some\nspecial handling throughout our code, and I want to defer the issue for now.\nWithout this assert, some of our early drafts will do some Very Bad Things.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Allocating", "heading_path": ["Allocating Memory"], "path": "vec/vec-alloc.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-alloc.html#allocating-memory", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/vec/vec-alloc.md#allocating-memory-1", "text": "The Rustonomicon › Allocating Memory\n\nNext we need to figure out what to actually do when we *do* want space. For that,\nwe use the global allocation functions `alloc`, `realloc`,\nand `dealloc` which are available in stable Rust in\n`std::alloc`. These functions are expected to become deprecated in\nfavor of the methods of `std::alloc::Global` after this type is stabilized.\nWe'll also need a way to handle out-of-memory (OOM) conditions. The standard\nlibrary provides a function `alloc::handle_alloc_error`,\nwhich will abort the program in a platform-specific manner.\nThe reason we abort and don't panic is because unwinding can cause allocations\nto happen, and that seems like a bad thing to do when your allocator just came\nback with \"hey I don't have any more memory\".\nOf course, this is a bit silly since most platforms don't actually run out of\nmemory in a conventional way. Your operating system will probably kill the\napplication by another means if you legitimately start using up all the memory.\nThe most likely way we'll trigger OOM is by just asking for ludicrous quantities\nof memory at once (e.g. half the theoretical address space). As such it's\n*probably* fine to panic and nothing bad will happen. Still, we're trying to be\nlike the standard library as much as possible, so we'll just kill the whole\nprogram.\nOkay, now we can write growing. Roughly, we want to have this logic:\n```text\nif cap == 0:\n allocate()\n cap = 1\nelse:\n reallocate()\n cap *= 2\n```\nBut Rust's only supported allocator API is so low level that we'll need to do a\nfair bit of extra work. We also need to guard against some special\nconditions that can occur with really large allocations or empty allocations.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Allocating", "heading_path": ["Allocating Memory"], "path": "vec/vec-alloc.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-alloc.html#allocating-memory", "has_code": true, "code_tags": ["text"]}} {"id": "nomicon/vec/vec-alloc.md#allocating-memory-2", "text": "The Rustonomicon › Allocating Memory\n\nIn particular, `ptr::offset` will cause us a lot of trouble, because it has\nthe semantics of LLVM's GEP inbounds instruction. If you're fortunate enough to\nnot have dealt with this instruction, here's the basic story with GEP: alias\nanalysis, alias analysis, alias analysis. It's super important to an optimizing\ncompiler to be able to reason about data dependencies and aliasing.\nAs a simple example, consider the following fragment of code:\n```rust,ignore\n*x *= 7;\n*y *= 3;\n```\nIf the compiler can prove that `x` and `y` point to different locations in\nmemory, the two operations can in theory be executed in parallel (by e.g.\nloading them into different registers and working on them independently).\nHowever the compiler can't do this in general because if x and y point to\nthe same location in memory, the operations need to be done to the same value,\nand they can't just be merged afterwards.\nWhen you use GEP inbounds, you are specifically telling LLVM that the offsets\nyou're about to do are within the bounds of a single \"allocated\" entity. The\nultimate payoff being that LLVM can assume that if two pointers are known to\npoint to two disjoint objects, all the offsets of those pointers are *also*\nknown to not alias (because you won't just end up in some random place in\nmemory). LLVM is heavily optimized to work with GEP offsets, and inbounds\noffsets are the best of all, so it's important that we use them as much as\npossible.\nSo that's what GEP's about, how can it cause us trouble?", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Allocating", "heading_path": ["Allocating Memory"], "path": "vec/vec-alloc.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-alloc.html#allocating-memory", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/vec/vec-alloc.md#allocating-memory-3", "text": "The Rustonomicon › Allocating Memory\n\nThe first problem is that we index into arrays with unsigned integers, but\nGEP (and as a consequence `ptr::offset`) takes a signed integer. This means\nthat half of the seemingly valid indices into an array will overflow GEP and\nactually go in the wrong direction! As such we must limit all allocations to\n`isize::MAX` elements. This actually means we only need to worry about\nbyte-sized objects, because e.g. `> isize::MAX` `u16`s will truly exhaust all of\nthe system's memory. However in order to avoid subtle corner cases where someone\nreinterprets some array of `< isize::MAX` objects as bytes, std limits all\nallocations to `isize::MAX` bytes.\nOn all 64-bit targets that Rust currently supports we're artificially limited\nto significantly less than all 64 bits of the address space (modern x64\nplatforms only expose 48-bit addressing), so we can rely on just running out of\nmemory first. However on 32-bit targets, particularly those with extensions to\nuse more of the address space (PAE x86 or x32), it's theoretically possible to\nsuccessfully allocate more than `isize::MAX` bytes of memory.\nHowever since this is a tutorial, we're not going to be particularly optimal\nhere, and just unconditionally check, rather than use clever platform-specific\n`cfg`s.\nThe other corner-case we need to worry about is empty allocations. There will\nbe two kinds of empty allocations we need to worry about: `cap = 0` for all T,\nand `cap > 0` for zero-sized types.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Allocating", "heading_path": ["Allocating Memory"], "path": "vec/vec-alloc.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-alloc.html#allocating-memory", "has_code": false, "code_tags": []}} {"id": "nomicon/vec/vec-alloc.md#allocating-memory-4", "text": "The Rustonomicon › Allocating Memory\n\nThese cases are tricky because they come\ndown to what LLVM means by \"allocated\". LLVM's notion of an\nallocation is significantly more abstract than how we usually use it. Because\nLLVM needs to work with different languages' semantics and custom allocators,\nit can't really intimately understand allocation. Instead, the main idea behind\nallocation is \"doesn't overlap with other stuff\". That is, heap allocations,\nstack allocations, and globals don't randomly overlap. Yep, it's about alias\nanalysis. As such, Rust can technically play a bit fast and loose with the notion of\nan allocation as long as it's *consistent*.\nGetting back to the empty allocation case, there are a couple of places where\nwe want to offset by 0 as a consequence of generic code. The question is then:\nis it consistent to do so? For zero-sized types, we have concluded that it is\nindeed consistent to do a GEP inbounds offset by an arbitrary number of\nelements. This is a runtime no-op because every element takes up no space,\nand it's fine to pretend that there's infinite zero-sized types allocated\nat `0x01`. No allocator will ever allocate that address, because they won't\nallocate `0x00` and they generally allocate to some minimal alignment higher\nthan a byte. Also generally the whole first page of memory is\nprotected from being allocated anyway (a whole 4k, on many platforms).\nHowever what about for positive-sized types? That one's a bit trickier. In\nprinciple, you can argue that offsetting by 0 gives LLVM no information: either\nthere's an element before the address or after it, but it can't know which.\nHowever we've chosen to conservatively assume that it may do bad things. As\nsuch we will guard against this case explicitly.\n*Phew*\nOk with all the nonsense out of the way, let's actually allocate some memory:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Allocating", "heading_path": ["Allocating Memory"], "path": "vec/vec-alloc.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-alloc.html#allocating-memory", "has_code": false, "code_tags": []}} {"id": "nomicon/vec/vec-alloc.md#allocating-memory-5", "text": "The Rustonomicon › Allocating Memory\n\n```rust,ignore\nuse std::alloc::{self, Layout};\n\nimpl Vec {\n fn grow(&mut self) {\n let (new_cap, new_layout) = if self.cap == 0 {\n (1, Layout::array::(1))\n } else {\n // This can't overflow since self.cap <= isize::MAX.\n let new_cap = 2 * self.cap;\n (new_cap, Layout::array::(new_cap))\n };\n\n // `Layout::array` checks that the number of bytes allocated is\n // in 1..=isize::MAX and will error otherwise. An allocation of\n // 0 bytes isn't possible thanks to the above condition.\n let new_layout = new_layout.expect(\"Allocation too large\");\n\n let new_ptr = if self.cap == 0 {\n unsafe { alloc::alloc(new_layout) }\n } else {\n let old_layout = Layout::array::(self.cap).unwrap();\n let old_ptr = self.ptr.as_ptr() as *mut u8;\n unsafe { alloc::realloc(old_ptr, old_layout, new_layout.size()) }\n };\n\n // If allocation fails, `new_ptr` will be null, in which case we abort.\n self.ptr = match NonNull::new(new_ptr as *mut T) {\n Some(p) => p,\n None => alloc::handle_alloc_error(new_layout),\n };\n self.cap = new_cap;\n }\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Allocating", "heading_path": ["Allocating Memory"], "path": "vec/vec-alloc.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-alloc.html#allocating-memory", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/vec/vec-push-pop.md#push-and-pop-0", "text": "The Rustonomicon › Push and Pop\n\nAlright. We can initialize. We can allocate. Let's actually implement some\nfunctionality! Let's start with `push`. All it needs to do is check if we're\nfull to grow, unconditionally write to the next index, and then increment our\nlength.\nTo do the write we have to be careful not to evaluate the memory we want to write\nto. At worst, it's truly uninitialized memory from the allocator. At best it's the\nbits of some old value we popped off. Either way, we can't just index to the memory\nand dereference it, because that will evaluate the memory as a valid instance of\nT. Worse, `foo[idx] = x` will try to call `drop` on the old value of `foo[idx]`!\nThe correct way to do this is with `ptr::write`, which just blindly overwrites the\ntarget address with the bits of the value we provide. No evaluation involved.\nFor `push`, if the old len (before push was called) is 0, then we want to write\nto the 0th index. So we should offset by the old len.\n```rust,ignore\npub fn push(&mut self, elem: T) {\n if self.len == self.cap { self.grow(); }\n\n unsafe {\n ptr::write(self.ptr.as_ptr().add(self.len), elem);\n }\n\n // Can't fail, we'll OOM first.\n self.len += 1;\n}\n```\nEasy! How about `pop`? Although this time the index we want to access is\ninitialized, Rust won't just let us dereference the location of memory to move\nthe value out, because that would leave the memory uninitialized! For this we\nneed `ptr::read`, which just copies out the bits from the target address and\ninterprets it as a value of type T. This will leave the memory at this address\nlogically uninitialized, even though there is in fact a perfectly good instance\nof T there.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Push and Pop", "heading_path": ["Push and Pop"], "path": "vec/vec-push-pop.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-push-pop.html#push-and-pop", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/vec/vec-push-pop.md#push-and-pop-1", "text": "The Rustonomicon › Push and Pop\n\nFor `pop`, if the old len is 1, for example, we want to read out of the 0th\nindex. So we should offset by the new len.\n```rust,ignore\npub fn pop(&mut self) -> Option {\n if self.len == 0 {\n None\n } else {\n self.len -= 1;\n unsafe {\n Some(ptr::read(self.ptr.as_ptr().add(self.len)))\n }\n }\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Push and Pop", "heading_path": ["Push and Pop"], "path": "vec/vec-push-pop.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-push-pop.html#push-and-pop", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/vec/vec-dealloc.md#deallocating-0", "text": "The Rustonomicon › Deallocating\n\nNext we should implement Drop so that we don't massively leak tons of resources.\nThe easiest way is to just call `pop` until it yields None, and then deallocate\nour buffer. Note that calling `pop` is unneeded if `T: !Drop`. In theory we can\nask Rust if `T` `needs_drop` and omit the calls to `pop`. However in practice\nLLVM is *really* good at removing simple side-effect free code like this, so I\nwouldn't bother unless you notice it's not being stripped (in this case it is).\nWe must not call `alloc::dealloc` when `self.cap == 0`, as in this case we\nhaven't actually allocated any memory.\n```rust,ignore\nimpl Drop for Vec {\n fn drop(&mut self) {\n if self.cap != 0 {\n while let Some(_) = self.pop() { }\n let layout = Layout::array::(self.cap).unwrap();\n unsafe {\n alloc::dealloc(self.ptr.as_ptr() as *mut u8, layout);\n }\n }\n }\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Deallocating", "heading_path": ["Deallocating"], "path": "vec/vec-dealloc.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-dealloc.html#deallocating", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/vec/vec-deref.md#deref-0", "text": "The Rustonomicon › Deref\n\nAlright! We've got a decent minimal stack implemented. We can push, we can\npop, and we can clean up after ourselves. However there's a whole mess of\nfunctionality we'd reasonably want. In particular, we have a proper array, but\nnone of the slice functionality. That's actually pretty easy to solve: we can\nimplement `Deref`. This will magically make our Vec coerce to, and\nbehave like, a slice in all sorts of conditions.\nAll we need is `slice::from_raw_parts`. It will correctly handle empty slices\nfor us. Later once we set up zero-sized type support it will also Just Work\nfor those too.\n```rust,ignore\nuse std::ops::Deref;\n\nimpl Deref for Vec {\n type Target = [T];\n fn deref(&self) -> &[T] {\n unsafe {\n std::slice::from_raw_parts(self.ptr.as_ptr(), self.len)\n }\n }\n}\n```\nAnd let's do DerefMut too:\n```rust,ignore\nuse std::ops::DerefMut;\n\nimpl DerefMut for Vec {\n fn deref_mut(&mut self) -> &mut [T] {\n unsafe {\n std::slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len)\n }\n }\n}\n```\nNow we have `len`, `first`, `last`, indexing, slicing, sorting, `iter`,\n`iter_mut`, and all other sorts of bells and whistles provided by slice. Sweet!", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Deref", "heading_path": ["Deref"], "path": "vec/vec-deref.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-deref.html#deref", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/vec/vec-insert-remove.md#insert-and-remove-0", "text": "The Rustonomicon › Insert and Remove\n\nSomething *not* provided by slice is `insert` and `remove`, so let's do those\nnext.\nInsert needs to shift all the elements at the target index to the right by one.\nTo do this we need to use `ptr::copy`, which is our version of C's `memmove`.\nThis copies some chunk of memory from one location to another, correctly\nhandling the case where the source and destination overlap (which will\ndefinitely happen here).\nIf we insert at index `i`, we want to shift the `[i .. len]` to `[i+1 .. len+1]`\nusing the old len.\n```rust,ignore\npub fn insert(&mut self, index: usize, elem: T) {\n // Note: `<=` because it's valid to insert after everything\n // which would be equivalent to push.\n assert!(index <= self.len, \"index out of bounds\");\n if self.len == self.cap { self.grow(); }\n\n unsafe {\n // ptr::copy(src, dest, len): \"copy from src to dest len elems\"\n ptr::copy(\n self.ptr.as_ptr().add(index),\n self.ptr.as_ptr().add(index + 1),\n self.len - index,\n );\n ptr::write(self.ptr.as_ptr().add(index), elem);\n }\n\n self.len += 1;\n}\n```\nRemove behaves in the opposite manner. We need to shift all the elements from\n`[i+1 .. len + 1]` to `[i .. len]` using the *new* len.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Insert and Remove", "heading_path": ["Insert and Remove"], "path": "vec/vec-insert-remove.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-insert-remove.html#insert-and-remove", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/vec/vec-insert-remove.md#insert-and-remove-1", "text": "The Rustonomicon › Insert and Remove\n\n```rust,ignore\npub fn remove(&mut self, index: usize) -> T {\n // Note: `<` because it's *not* valid to remove after everything\n assert!(index < self.len, \"index out of bounds\");\n unsafe {\n self.len -= 1;\n let result = ptr::read(self.ptr.as_ptr().add(index));\n ptr::copy(\n self.ptr.as_ptr().add(index + 1),\n self.ptr.as_ptr().add(index),\n self.len - index,\n );\n result\n }\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Insert and Remove", "heading_path": ["Insert and Remove"], "path": "vec/vec-insert-remove.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-insert-remove.html#insert-and-remove", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/vec/vec-into-iter.md#intoiter-0", "text": "The Rustonomicon › IntoIter\n\nLet's move on to writing iterators. `iter` and `iter_mut` have already been\nwritten for us thanks to The Magic of Deref. However there's two interesting\niterators that Vec provides that slices can't: `into_iter` and `drain`.\nIntoIter consumes the Vec by-value, and can consequently yield its elements\nby-value. In order to enable this, IntoIter needs to take control of Vec's\nallocation.\nIntoIter needs to be DoubleEnded as well, to enable reading from both ends.\nReading from the back could just be implemented as calling `pop`, but reading\nfrom the front is harder. We could call `remove(0)` but that would be insanely\nexpensive. Instead we're going to just use ptr::read to copy values out of\neither end of the Vec without mutating the buffer at all.\nTo do this we're going to use a very common C idiom for array iteration. We'll\nmake two pointers; one that points to the start of the array, and one that\npoints to one-element past the end. When we want an element from one end, we'll\nread out the value pointed to at that end and move the pointer over by one. When\nthe two pointers are equal, we know we're done.\nNote that the order of read and offset are reversed for `next` and `next_back`\nFor `next_back` the pointer is always after the element it wants to read next,\nwhile for `next` the pointer is always at the element it wants to read next.\nTo see why this is, consider the case where every element but one has been\nyielded.\nThe array looks like this:\n```text\n S E\n[X, X, X, O, X, X, X]\n```\nIf E pointed directly at the element it wanted to yield next, it would be\nindistinguishable from the case where there are no more elements to yield.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "IntoIter", "heading_path": ["IntoIter"], "path": "vec/vec-into-iter.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-into-iter.html#intoiter", "has_code": true, "code_tags": ["text"]}} {"id": "nomicon/vec/vec-into-iter.md#intoiter-1", "text": "The Rustonomicon › IntoIter\n\nAlthough we don't actually care about it during iteration, we also need to hold\nonto the Vec's allocation information in order to free it once IntoIter is\ndropped.\nSo we're going to use the following struct:\n```rust,ignore\npub struct IntoIter {\n buf: NonNull,\n cap: usize,\n start: *const T,\n end: *const T,\n}\n```\nAnd this is what we end up with for initialization:\n```rust,ignore\nimpl IntoIterator for Vec {\n type Item = T;\n type IntoIter = IntoIter;\n fn into_iter(self) -> IntoIter {\n // Make sure not to drop Vec since that would free the buffer\n let vec = ManuallyDrop::new(self);\n\n // Can't destructure Vec since it's Drop\n let ptr = vec.ptr;\n let cap = vec.cap;\n let len = vec.len;\n\n IntoIter {\n buf: ptr,\n cap,\n start: ptr.as_ptr(),\n end: if cap == 0 {\n // can't offset off this pointer, it's not allocated!\n ptr.as_ptr()\n } else {\n unsafe { ptr.as_ptr().add(len) }\n },\n }\n }\n}\n```\nHere's iterating forward:\n```rust,ignore\nimpl Iterator for IntoIter {\n type Item = T;\n fn next(&mut self) -> Option {\n if self.start == self.end {\n None\n } else {\n unsafe {\n let result = ptr::read(self.start);\n self.start = self.start.offset(1);\n Some(result)\n }\n }\n }\n\n fn size_hint(&self) -> (usize, Option) {\n let len = (self.end as usize - self.start as usize)\n / mem::size_of::();\n (len, Some(len))\n }\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "IntoIter", "heading_path": ["IntoIter"], "path": "vec/vec-into-iter.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-into-iter.html#intoiter", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/vec/vec-into-iter.md#intoiter-2", "text": "The Rustonomicon › IntoIter\n\nAnd here's iterating backwards.\n```rust,ignore\nimpl DoubleEndedIterator for IntoIter {\n fn next_back(&mut self) -> Option {\n if self.start == self.end {\n None\n } else {\n unsafe {\n self.end = self.end.offset(-1);\n Some(ptr::read(self.end))\n }\n }\n }\n}\n```\nBecause IntoIter takes ownership of its allocation, it needs to implement Drop\nto free it. However it also wants to implement Drop to drop any elements it\ncontains that weren't yielded.\n```rust,ignore\nimpl Drop for IntoIter {\n fn drop(&mut self) {\n if self.cap != 0 {\n // drop any remaining elements\n for _ in &mut *self {}\n let layout = Layout::array::(self.cap).unwrap();\n unsafe {\n alloc::dealloc(self.buf.as_ptr() as *mut u8, layout);\n }\n }\n }\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "IntoIter", "heading_path": ["IntoIter"], "path": "vec/vec-into-iter.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-into-iter.html#intoiter", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/vec/vec-raw.md#rawvec-0", "text": "The Rustonomicon › RawVec\n\nWe've actually reached an interesting situation here: we've duplicated the logic\nfor specifying a buffer and freeing its memory in Vec and IntoIter. Now that\nwe've implemented it and identified *actual* logic duplication, this is a good\ntime to perform some logic compression.\nWe're going to abstract out the `(ptr, cap)` pair and give them the logic for\nallocating, growing, and freeing:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "RawVec", "heading_path": ["RawVec"], "path": "vec/vec-raw.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-raw.html#rawvec", "has_code": false, "code_tags": []}} {"id": "nomicon/vec/vec-raw.md#rawvec-1", "text": "The Rustonomicon › RawVec\n\n```rust,ignore\nstruct RawVec {\n ptr: NonNull,\n cap: usize,\n}\n\nunsafe impl Send for RawVec {}\nunsafe impl Sync for RawVec {}\n\nimpl RawVec {\n fn new() -> Self {\n assert!(mem::size_of::() != 0, \"TODO: implement ZST support\");\n RawVec {\n ptr: NonNull::dangling(),\n cap: 0,\n }\n }\n\n fn grow(&mut self) {\n // This can't overflow because we ensure self.cap <= isize::MAX.\n let new_cap = if self.cap == 0 { 1 } else { 2 * self.cap };\n\n // Layout::array checks that the number of bytes is <= usize::MAX,\n // but this is redundant since old_layout.size() <= isize::MAX,\n // so the `unwrap` should never fail.\n let new_layout = Layout::array::(new_cap).unwrap();\n\n // Ensure that the new allocation doesn't exceed `isize::MAX` bytes.\n assert!(new_layout.size() <= isize::MAX as usize, \"Allocation too large\");\n\n let new_ptr = if self.cap == 0 {\n unsafe { alloc::alloc(new_layout) }\n } else {\n let old_layout = Layout::array::(self.cap).unwrap();\n let old_ptr = self.ptr.as_ptr() as *mut u8;\n unsafe { alloc::realloc(old_ptr, old_layout, new_layout.size()) }\n };\n\n // If allocation fails, `new_ptr` will be null, in which case we abort.\n self.ptr = match NonNull::new(new_ptr as *mut T) {\n Some(p) => p,\n None => alloc::handle_alloc_error(new_layout),\n };\n self.cap = new_cap;\n }\n}\n\nimpl Drop for RawVec {\n fn drop(&mut self) {\n if self.cap != 0 {\n let layout = Layout::array::(self.cap).unwrap();\n unsafe {\n alloc::dealloc(self.ptr.as_ptr() as *mut u8, layout);\n }\n }\n }\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "RawVec", "heading_path": ["RawVec"], "path": "vec/vec-raw.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-raw.html#rawvec", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/vec/vec-raw.md#rawvec-2", "text": "The Rustonomicon › RawVec\n\nAnd change Vec as follows:\n```rust,ignore\npub struct Vec {\n buf: RawVec,\n len: usize,\n}\n\nimpl Vec {\n fn ptr(&self) -> *mut T {\n self.buf.ptr.as_ptr()\n }\n\n fn cap(&self) -> usize {\n self.buf.cap\n }\n\n pub fn new() -> Self {\n Vec {\n buf: RawVec::new(),\n len: 0,\n }\n }\n\n // push/pop/insert/remove largely unchanged:\n // * `self.ptr.as_ptr() -> self.ptr()`\n // * `self.cap -> self.cap()`\n // * `self.grow() -> self.buf.grow()`\n}\n\nimpl Drop for Vec {\n fn drop(&mut self) {\n while let Some(_) = self.pop() {}\n // deallocation is handled by RawVec\n }\n}\n```\nAnd finally we can really simplify IntoIter:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "RawVec", "heading_path": ["RawVec"], "path": "vec/vec-raw.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-raw.html#rawvec", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/vec/vec-raw.md#rawvec-3", "text": "The Rustonomicon › RawVec\n\n```rust,ignore\npub struct IntoIter {\n _buf: RawVec, // we don't actually care about this. Just need it to live.\n start: *const T,\n end: *const T,\n}\n\n// next and next_back literally unchanged since they never referred to the buf\n\nimpl Drop for IntoIter {\n fn drop(&mut self) {\n // only need to ensure all our elements are read;\n // buffer will clean itself up afterwards.\n for _ in &mut *self {}\n }\n}\n\nimpl IntoIterator for Vec {\n type Item = T;\n type IntoIter = IntoIter;\n fn into_iter(self) -> IntoIter {\n // need to use ptr::read to unsafely move the buf out since it's\n // not Copy, and Vec implements Drop (so we can't destructure it).\n let buf = unsafe { ptr::read(&self.buf) };\n let len = self.len;\n mem::forget(self);\n\n IntoIter {\n start: buf.ptr.as_ptr(),\n end: if buf.cap == 0 {\n // can't offset off of a pointer unless it's part of an allocation\n buf.ptr.as_ptr()\n } else {\n unsafe { buf.ptr.as_ptr().add(len) }\n },\n _buf: buf,\n }\n }\n}\n```\nMuch better.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "RawVec", "heading_path": ["RawVec"], "path": "vec/vec-raw.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-raw.html#rawvec", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/vec/vec-drain.md#drain-0", "text": "The Rustonomicon › Drain\n\nLet's move on to Drain. Drain is largely the same as IntoIter, except that\ninstead of consuming the Vec, it borrows the Vec and leaves its allocation\nuntouched. For now we'll only implement the \"basic\" full-range version.\n```rust,ignore\nuse std::marker::PhantomData;\n\nstruct Drain<'a, T: 'a> {\n // Need to bound the lifetime here, so we do it with `&'a mut Vec`\n // because that's semantically what we contain. We're \"just\" calling\n // `pop()` and `remove(0)`.\n vec: PhantomData<&'a mut Vec>,\n start: *const T,\n end: *const T,\n}\n\nimpl<'a, T> Iterator for Drain<'a, T> {\n type Item = T;\n fn next(&mut self) -> Option {\n if self.start == self.end {\n None\n```\n-- wait, this is seeming familiar. Let's do some more compression. Both\nIntoIter and Drain have the exact same structure, let's just factor it out.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Drain", "heading_path": ["Drain"], "path": "vec/vec-drain.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-drain.html#drain", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/vec/vec-drain.md#drain-1", "text": "The Rustonomicon › Drain\n\n```rust,ignore\nstruct RawValIter {\n start: *const T,\n end: *const T,\n}\n\nimpl RawValIter {\n // unsafe to construct because it has no associated lifetimes.\n // This is necessary to store a RawValIter in the same struct as\n // its actual allocation. OK since it's a private implementation\n // detail.\n unsafe fn new(slice: &[T]) -> Self {\n RawValIter {\n start: slice.as_ptr(),\n end: if slice.len() == 0 {\n // if `len = 0`, then this is not actually allocated memory.\n // Need to avoid offsetting because that will give wrong\n // information to LLVM via GEP.\n slice.as_ptr()\n } else {\n slice.as_ptr().add(slice.len())\n }\n }\n }\n}\n\n// Iterator and DoubleEndedIterator impls identical to IntoIter.\n```\nAnd IntoIter becomes the following:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Drain", "heading_path": ["Drain"], "path": "vec/vec-drain.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-drain.html#drain", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/vec/vec-drain.md#drain-2", "text": "The Rustonomicon › Drain\n\n```rust,ignore\npub struct IntoIter {\n _buf: RawVec, // we don't actually care about this. Just need it to live.\n iter: RawValIter,\n}\n\nimpl Iterator for IntoIter {\n type Item = T;\n fn next(&mut self) -> Option { self.iter.next() }\n fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() }\n}\n\nimpl DoubleEndedIterator for IntoIter {\n fn next_back(&mut self) -> Option { self.iter.next_back() }\n}\n\nimpl Drop for IntoIter {\n fn drop(&mut self) {\n for _ in &mut *self {}\n }\n}\n\nimpl IntoIterator for Vec {\n type Item = T;\n type IntoIter = IntoIter;\n fn into_iter(self) -> IntoIter {\n unsafe {\n let iter = RawValIter::new(&self);\n\n let buf = ptr::read(&self.buf);\n mem::forget(self);\n\n IntoIter {\n iter,\n _buf: buf,\n }\n }\n }\n}\n```\nNote that I've left a few quirks in this design to make upgrading Drain to work\nwith arbitrary subranges a bit easier. In particular we *could* have RawValIter\ndrain itself on drop, but that won't work right for a more complex Drain.\nWe also take a slice to simplify Drain initialization.\nAlright, now Drain is really easy:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Drain", "heading_path": ["Drain"], "path": "vec/vec-drain.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-drain.html#drain", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/vec/vec-drain.md#drain-3", "text": "The Rustonomicon › Drain\n\n```rust,ignore\nuse std::marker::PhantomData;\n\npub struct Drain<'a, T: 'a> {\n vec: PhantomData<&'a mut Vec>,\n iter: RawValIter,\n}\n\nimpl<'a, T> Iterator for Drain<'a, T> {\n type Item = T;\n fn next(&mut self) -> Option { self.iter.next() }\n fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() }\n}\n\nimpl<'a, T> DoubleEndedIterator for Drain<'a, T> {\n fn next_back(&mut self) -> Option { self.iter.next_back() }\n}\n\nimpl<'a, T> Drop for Drain<'a, T> {\n fn drop(&mut self) {\n for _ in &mut *self {}\n }\n}\n\nimpl Vec {\n pub fn drain(&mut self) -> Drain {\n let iter = unsafe { RawValIter::new(&self) };\n\n // this is a mem::forget safety thing. If Drain is forgotten, we just\n // leak the whole Vec's contents. Also we need to do this *eventually*\n // anyway, so why not do it now?\n self.len = 0;\n\n Drain {\n iter,\n vec: PhantomData,\n }\n }\n}\n```\nFor more details on the `mem::forget` problem, see the\nsection on leaks.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Drain", "heading_path": ["Drain"], "path": "vec/vec-drain.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-drain.html#drain", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/vec/vec-zsts.md#handling-zero-sized-types-0", "text": "The Rustonomicon › Handling Zero-Sized Types\n\nIt's time. We're going to fight the specter that is zero-sized types. Safe Rust\n*never* needs to care about this, but Vec is very intensive on raw pointers and\nraw allocations, which are exactly the two things that care about\nzero-sized types. We need to be careful of two things:\n* The raw allocator API has undefined behavior if you pass in 0 for an\n allocation size.\n* raw pointer offsets are no-ops for zero-sized types, which will break our\n C-style pointer iterator.\nThankfully we abstracted out pointer-iterators and allocating handling into\n`RawValIter` and `RawVec` respectively. How mysteriously convenient.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Handling Zero-Sized Types", "heading_path": ["Handling Zero-Sized Types"], "path": "vec/vec-zsts.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-zsts.html#handling-zero-sized-types", "has_code": false, "code_tags": []}} {"id": "nomicon/vec/vec-zsts.md#allocating-zero-sized-types-1", "text": "The Rustonomicon › Handling Zero-Sized Types › Allocating Zero-Sized Types\n\nSo if the allocator API doesn't support zero-sized allocations, what on earth\ndo we store as our allocation? `NonNull::dangling()` of course! Almost every operation\nwith a ZST is a no-op since ZSTs have exactly one value, and therefore no state needs\nto be considered to store or load them. This actually extends to `ptr::read` and\n`ptr::write`: they won't actually look at the pointer at all. As such we never need\nto change the pointer.\nNote however that our previous reliance on running out of memory before overflow is\nno longer valid with zero-sized types. We must explicitly guard against capacity\noverflow for zero-sized types.\nDue to our current architecture, all this means is writing 3 guards, one in each\nmethod of `RawVec`.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Handling Zero-Sized Types", "heading_path": ["Handling Zero-Sized Types", "Allocating Zero-Sized Types"], "path": "vec/vec-zsts.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-zsts.html#allocating-zero-sized-types", "has_code": false, "code_tags": []}} {"id": "nomicon/vec/vec-zsts.md#allocating-zero-sized-types-2", "text": "The Rustonomicon › Handling Zero-Sized Types › Allocating Zero-Sized Types\n\n```rust,ignore\nimpl RawVec {\n fn new() -> Self {\n // This branch should be stripped at compile time.\n let cap = if mem::size_of::() == 0 { usize::MAX } else { 0 };\n\n // `NonNull::dangling()` doubles as \"unallocated\" and \"zero-sized allocation\"\n RawVec {\n ptr: NonNull::dangling(),\n cap,\n }\n }\n\n fn grow(&mut self) {\n // since we set the capacity to usize::MAX when T has size 0,\n // getting to here necessarily means the Vec is overfull.\n assert!(mem::size_of::() != 0, \"capacity overflow\");\n\n let (new_cap, new_layout) = if self.cap == 0 {\n (1, Layout::array::(1).unwrap())\n } else {\n // This can't overflow because we ensure self.cap <= isize::MAX.\n let new_cap = 2 * self.cap;\n\n // `Layout::array` checks that the number of bytes is <= usize::MAX,\n // but this is redundant since old_layout.size() <= isize::MAX,\n // so the `unwrap` should never fail.\n let new_layout = Layout::array::(new_cap).unwrap();\n (new_cap, new_layout)\n };\n\n // Ensure that the new allocation doesn't exceed `isize::MAX` bytes.\n assert!(new_layout.size() <= isize::MAX as usize, \"Allocation too large\");\n\n let new_ptr = if self.cap == 0 {\n unsafe { alloc::alloc(new_layout) }\n } else {\n let old_layout = Layout::array::(self.cap).unwrap();\n let old_ptr = self.ptr.as_ptr() as *mut u8;\n unsafe { alloc::realloc(old_ptr, old_layout, new_layout.size()) }\n };\n\n // If allocation fails, `new_ptr` will be null, in which case we abort.\n self.ptr = match NonNull::new(new_ptr as *mut T) {\n Some(p) => p,\n None => alloc::handle_alloc_error(new_layout),\n };\n self.cap = new_cap;\n }\n}\n\nimpl Drop for RawVec {\n fn drop(&mut self) {\n let elem_size = mem::size_of::();\n\n if self.cap != 0 && elem_size != 0 {\n unsafe {\n alloc::dealloc(\n self.ptr.as_ptr() as *mut u8,\n Layout::array::(self.cap).unwrap(),\n );\n }\n }\n }\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Handling Zero-Sized Types", "heading_path": ["Handling Zero-Sized Types", "Allocating Zero-Sized Types"], "path": "vec/vec-zsts.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-zsts.html#allocating-zero-sized-types", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/vec/vec-zsts.md#allocating-zero-sized-types-3", "text": "The Rustonomicon › Handling Zero-Sized Types › Allocating Zero-Sized Types\n\nThat's it. We support pushing and popping zero-sized types now. Our iterators\n(that aren't provided by slice Deref) are still busted, though.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Handling Zero-Sized Types", "heading_path": ["Handling Zero-Sized Types", "Allocating Zero-Sized Types"], "path": "vec/vec-zsts.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-zsts.html#allocating-zero-sized-types", "has_code": false, "code_tags": []}} {"id": "nomicon/vec/vec-zsts.md#iterating-zero-sized-types-4", "text": "The Rustonomicon › Handling Zero-Sized Types › Iterating Zero-Sized Types\n\nZero-sized offsets are no-ops. This means that our current design will always\ninitialize `start` and `end` as the same value, and our iterators will yield\nnothing. The current solution to this is to cast the pointers to integers,\nincrement, and then cast them back:\n```rust,ignore\nimpl RawValIter {\n unsafe fn new(slice: &[T]) -> Self {\n RawValIter {\n start: slice.as_ptr(),\n end: if mem::size_of::() == 0 {\n ((slice.as_ptr() as usize) + slice.len()) as *const _\n } else if slice.len() == 0 {\n slice.as_ptr()\n } else {\n slice.as_ptr().add(slice.len())\n },\n }\n }\n}\n```\nNow we have a different bug. Instead of our iterators not running at all, our\niterators now run *forever*. We need to do the same trick in our iterator impls.\nAlso, our size_hint computation code will divide by 0 for ZSTs. Since we'll\nbasically be treating the two pointers as if they point to bytes, we'll just\nmap size 0 to divide by 1. Here's what `next` will be:\n```rust,ignore\nfn next(&mut self) -> Option {\n if self.start == self.end {\n None\n } else {\n unsafe {\n let result = ptr::read(self.start);\n self.start = if mem::size_of::() == 0 {\n (self.start as usize + 1) as *const _\n } else {\n self.start.offset(1)\n };\n Some(result)\n }\n }\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Handling Zero-Sized Types", "heading_path": ["Handling Zero-Sized Types", "Iterating Zero-Sized Types"], "path": "vec/vec-zsts.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-zsts.html#iterating-zero-sized-types", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/vec/vec-zsts.md#iterating-zero-sized-types-5", "text": "The Rustonomicon › Handling Zero-Sized Types › Iterating Zero-Sized Types\n\nDo you see the \"bug\"? No one else did! The original author only noticed the\nproblem when linking to this page years later. This code is kind of dubious\nbecause abusing the iterator pointers to be *counters* makes them unaligned!\nOur *one job* when using ZSTs is to keep pointers aligned! *forehead slap*\nRaw pointers don't need to be aligned at all times, so the basic trick of\nusing pointers as counters is *fine*, but they *should* definitely be aligned\nwhen passed to `ptr::read`! This is *possibly* needless pedantry\nbecause `ptr::read` is a noop for a ZST, but let's be a *little* more\nresponsible and read from `NonNull::dangling` on the ZST path.\n(Alternatively you could call `read_unaligned` on the ZST path. Either is fine,\nbecause either way we're making up a value from nothing and it all compiles\nto doing nothing.)", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Handling Zero-Sized Types", "heading_path": ["Handling Zero-Sized Types", "Iterating Zero-Sized Types"], "path": "vec/vec-zsts.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-zsts.html#iterating-zero-sized-types", "has_code": false, "code_tags": []}} {"id": "nomicon/vec/vec-zsts.md#iterating-zero-sized-types-6", "text": "The Rustonomicon › Handling Zero-Sized Types › Iterating Zero-Sized Types\n\n```rust,ignore\nimpl Iterator for RawValIter {\n type Item = T;\n fn next(&mut self) -> Option {\n if self.start == self.end {\n None\n } else {\n unsafe {\n if mem::size_of::() == 0 {\n self.start = (self.start as usize + 1) as *const _;\n Some(ptr::read(NonNull::::dangling().as_ptr()))\n } else {\n let old_ptr = self.start;\n self.start = self.start.offset(1);\n Some(ptr::read(old_ptr))\n }\n }\n }\n }\n\n fn size_hint(&self) -> (usize, Option) {\n let elem_size = mem::size_of::();\n let len = (self.end as usize - self.start as usize)\n / if elem_size == 0 { 1 } else { elem_size };\n (len, Some(len))\n }\n}\n\nimpl DoubleEndedIterator for RawValIter {\n fn next_back(&mut self) -> Option {\n if self.start == self.end {\n None\n } else {\n unsafe {\n if mem::size_of::() == 0 {\n self.end = (self.end as usize - 1) as *const _;\n Some(ptr::read(NonNull::::dangling().as_ptr()))\n } else {\n self.end = self.end.offset(-1);\n Some(ptr::read(self.end))\n }\n }\n }\n }\n}\n```\nAnd that's it. Iteration works!", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Handling Zero-Sized Types", "heading_path": ["Handling Zero-Sized Types", "Iterating Zero-Sized Types"], "path": "vec/vec-zsts.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-zsts.html#iterating-zero-sized-types", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/vec/vec-zsts.md#iterating-zero-sized-types-7", "text": "The Rustonomicon › Handling Zero-Sized Types › Iterating Zero-Sized Types\n\nOne last thing we need to consider is that when our vector is dropped, it deallocates the memory that was allocated while it was alive. With ZSTs, we didn't allocate any memory; in fact, we never do. So, right now, our code has unsoundness: we're still trying to deallocate a `NonNull::dangling()` pointer that we use to simulate the ZST in our vector. This means we'd cause undefined behavior if we tried to deallocate something we never allocated (obviously, and for good reasons). To fix this, in our `RawVec`'s `Drop` trait, we're going to tweak it to ensure we only deallocate types that are sized.\n```rust,ignore\nimpl Drop for RawVec {\n fn drop(&mut self) {\n println!(\"RawVec Drop called, deallocating memory\");\n if self.cap != 0 && std::mem::size_of::() > 0 {\n let layout = std::alloc::Layout::array::(self.cap).unwrap();\n unsafe {\n std::alloc::dealloc(self.ptr.as_ptr() as *mut _, layout);\n }\n }\n }\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Handling Zero-Sized Types", "heading_path": ["Handling Zero-Sized Types", "Iterating Zero-Sized Types"], "path": "vec/vec-zsts.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-zsts.html#iterating-zero-sized-types", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/vec/vec-final.md#the-final-code-0", "text": "The Rustonomicon › The Final Code\n\n```rust\nuse std::alloc::{self, Layout};\nuse std::marker::PhantomData;\nuse std::mem;\nuse std::ops::{Deref, DerefMut};\nuse std::ptr::{self, NonNull};\n\nstruct RawVec {\n ptr: NonNull,\n cap: usize,\n}\n\nunsafe impl Send for RawVec {}\nunsafe impl Sync for RawVec {}\n\nimpl RawVec {\n fn new() -> Self {\n // !0 is usize::MAX. This branch should be stripped at compile time.\n let cap = if mem::size_of::() == 0 { !0 } else { 0 };\n\n // `NonNull::dangling()` doubles as \"unallocated\" and \"zero-sized allocation\"\n RawVec {\n ptr: NonNull::dangling(),\n cap,\n }\n }\n\n fn grow(&mut self) {\n // since we set the capacity to usize::MAX when T has size 0,\n // getting to here necessarily means the Vec is overfull.\n assert!(mem::size_of::() != 0, \"capacity overflow\");\n\n let (new_cap, new_layout) = if self.cap == 0 {\n (1, Layout::array::(1))\n } else {\n // This can't overflow since self.cap <= isize::MAX.\n let new_cap = 2 * self.cap;\n (new_cap, Layout::array::(new_cap))\n };\n\n // `Layout::array` checks that the number of bytes allocated is\n // in 1..=isize::MAX and will error otherwise. An allocation of\n // 0 bytes isn't possible thanks to the above condition.\n let new_layout = new_layout.expect(\"Allocation too large\");\n\n let new_ptr = if self.cap == 0 {\n unsafe { alloc::alloc(new_layout) }\n } else {\n let old_layout = Layout::array::(self.cap).unwrap();\n let old_ptr = self.ptr.as_ptr() as *mut u8;\n unsafe { alloc::realloc(old_ptr, old_layout, new_layout.size()) }\n };\n\n // If allocation fails, `new_ptr` will be null, in which case we abort.\n self.ptr = match NonNull::new(new_ptr as *mut T) {\n Some(p) => p,\n None => alloc::handle_alloc_error(new_layout),\n };\n self.cap = new_cap;\n }\n}\n\nimpl Drop for RawVec {\n fn drop(&mut self) {\n let elem_size = mem::size_of::();\n\n if self.cap != 0 && elem_size != 0 {\n unsafe {\n alloc::dealloc(\n self.ptr.as_ptr() as *mut u8,\n Layout::array::(self.cap).unwrap(),\n );\n }\n }\n }\n}\n\npub struct Vec {\n buf: RawVec,\n len: usize,\n}\n\nimpl Vec {\n fn ptr(&self) -> *mut T {\n self.buf.ptr.as_ptr()\n }\n\n fn cap(&self) -> usize {\n self.buf.cap\n }\n\n pub fn new() -> Self {\n Vec {\n buf: RawVec::new(),\n len: 0,\n }\n }\n pub fn push(&mut self, elem: T) {\n if self.len == self.cap() {\n self.buf.grow();\n }\n\n unsafe {\n ptr::write(self.ptr().add(self.len), elem);\n }\n\n // Can't overflow, we'll OOM first.\n self.len += 1;\n }\n\n pub fn pop(&mut self) -> Option {\n if self.len == 0 {\n None\n } else {\n self.len -= 1;\n unsafe { Some(ptr::read(self.ptr().add(self.len))) }\n }\n }\n\n pub fn insert(&mut self, index: usize, elem: T) {\n assert!(index <= self.len, \"index out of bounds\");\n if self.len == self.cap() {\n self.buf.grow();\n }\n\n unsafe {\n ptr::copy(\n self.ptr().add(index),\n self.ptr().add(index + 1),\n self.len - index,\n );\n ptr::write(self.ptr().add(index), elem);\n }\n\n self.len += 1;\n }\n\n pub fn remove(&mut self, index: usize) -> T {\n assert!(index < self.len, \"index out of bounds\");\n\n self.len -= 1;\n\n unsafe {\n let result = ptr::read(self.ptr().add(index));\n ptr::copy(\n self.ptr().add(index + 1),\n self.ptr().add(index),\n self.len - index,\n );\n result\n }\n }\n\n pub fn drain(&mut self) -> Drain {\n let iter = unsafe { RawValIter::new(&self) };\n\n // this is a mem::forget safety thing. If Drain is forgotten, we just\n // leak the whole Vec's contents. Also we need to do this *eventually*\n // anyway, so why not do it now?\n self.len = 0;\n\n Drain {\n iter,\n vec: PhantomData,\n }\n }\n}\n\nimpl Drop for Vec {\n fn drop(&mut self) {\n while let Some(_) = self.pop() {}\n // deallocation is handled by RawVec\n }\n}\n\nimpl Deref for Vec {\n type Target = [T];\n fn deref(&self) -> &[T] {\n unsafe { std::slice::from_raw_parts(self.ptr(), self.len) }\n }\n}\n\nimpl DerefMut for Vec {\n fn deref_mut(&mut self) -> &mut [T] {\n unsafe { std::slice::from_raw_parts_mut(self.ptr(), self.len) }\n }\n}\n\nimpl IntoIterator for Vec {\n type Item = T;\n type IntoIter = IntoIter;\n fn into_iter(self) -> IntoIter {\n let (iter, buf) = unsafe {\n (RawValIter::new(&self), ptr::read(&self.buf))\n };\n\n mem::forget(self);\n\n IntoIter {\n iter,\n _buf: buf,\n }\n }\n}\n\nstruct RawValIter {\n start: *const T,\n end: *const T,\n}\n\nimpl RawValIter {\n unsafe fn new(slice: &[T]) -> Self {\n RawValIter {\n start: slice.as_ptr(),\n end: if mem::size_of::() == 0 {\n ((slice.as_ptr() as usize) + slice.len()) as *const _\n } else if slice.len() == 0 {\n slice.as_ptr()\n } else {\n slice.as_ptr().add(slice.len())\n },\n }\n }\n}\n\nimpl Iterator for RawValIter {\n type Item = T;\n fn next(&mut self) -> Option {\n if self.start == self.end {\n None\n } else {\n unsafe {\n if mem::size_of::() == 0 {\n self.start = (self.start as usize + 1) as *const _;\n Some(ptr::read(NonNull::::dangling().as_ptr()))\n } else {\n let old_ptr = self.start;\n self.start = self.start.offset(1);\n Some(ptr::read(old_ptr))\n }\n }\n }\n }\n\n fn size_hint(&self) -> (usize, Option) {\n let elem_size = mem::size_of::();\n let len = (self.end as usize - self.start as usize)\n / if elem_size == 0 { 1 } else { elem_size };\n (len, Some(len))\n }\n}\n\nimpl DoubleEndedIterator for RawValIter {\n fn next_back(&mut self) -> Option {\n if self.start == self.end {\n None\n } else {\n unsafe {\n if mem::size_of::() == 0 {\n self.end = (self.end as usize - 1) as *const _;\n Some(ptr::read(NonNull::::dangling().as_ptr()))\n } else {\n self.end = self.end.offset(-1);\n Some(ptr::read(self.end))\n }\n }\n }\n }\n}\n\npub struct IntoIter {\n _buf: RawVec, // we don't actually care about this. Just need it to live.\n iter: RawValIter,\n}\n\nimpl Iterator for IntoIter {\n type Item = T;\n fn next(&mut self) -> Option {\n self.iter.next()\n }\n fn size_hint(&self) -> (usize, Option) {\n self.iter.size_hint()\n }\n}\n\nimpl DoubleEndedIterator for IntoIter {\n fn next_back(&mut self) -> Option {\n self.iter.next_back()\n }\n}\n\nimpl Drop for IntoIter {\n fn drop(&mut self) {\n for _ in &mut *self {}\n }\n}\n\npub struct Drain<'a, T: 'a> {\n vec: PhantomData<&'a mut Vec>,\n iter: RawValIter,\n}\n\nimpl<'a, T> Iterator for Drain<'a, T> {\n type Item = T;\n fn next(&mut self) -> Option {\n self.iter.next()\n }\n fn size_hint(&self) -> (usize, Option) {\n self.iter.size_hint()\n }\n}\n\nimpl<'a, T> DoubleEndedIterator for Drain<'a, T> {\n fn next_back(&mut self) -> Option {\n self.iter.next_back()\n }\n}\n\nimpl<'a, T> Drop for Drain<'a, T> {\n fn drop(&mut self) {\n // pre-drain the iter\n for _ in &mut *self {}\n }\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Final Code", "heading_path": ["The Final Code"], "path": "vec/vec-final.md", "url": "https://doc.rust-lang.org/nomicon/vec/vec-final.html#the-final-code", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/arc-mutex/arc-and-mutex.md#implementing-arc-and-mutex-0", "text": "The Rustonomicon › Implementing Arc and Mutex\n\nKnowing the theory is all fine and good, but the *best* way to understand\nsomething is to use it. To better understand atomics and interior mutability,\nwe'll be implementing versions of the standard library's `Arc` and `Mutex` types.\nTODO: Write `Mutex` chapters.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Implementing Arc and Mutex", "heading_path": ["Implementing Arc and Mutex"], "path": "arc-mutex/arc-and-mutex.md", "url": "https://doc.rust-lang.org/nomicon/arc-mutex/arc-and-mutex.html#implementing-arc-and-mutex", "has_code": false, "code_tags": []}} {"id": "nomicon/arc-mutex/arc.md#implementing-arc-0", "text": "The Rustonomicon › Implementing Arc\n\nIn this section, we'll be implementing a simpler version of `std::sync::Arc`.\nSimilarly to the implementation of `Vec` we made earlier, we won't be\ntaking advantage of as many optimizations, intrinsics, or unstable code as the\nstandard library may.\nThis implementation is loosely based on the standard library's implementation\n(technically taken from `alloc::sync` in 1.49, as that's where it's actually\nimplemented), but it will not support weak references at the moment as they\nmake the implementation slightly more complex.\nPlease note that this section is very work-in-progress at the moment.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Arc", "heading_path": ["Implementing Arc"], "path": "arc-mutex/arc.md", "url": "https://doc.rust-lang.org/nomicon/arc-mutex/arc.html#implementing-arc", "has_code": false, "code_tags": []}} {"id": "nomicon/arc-mutex/arc-layout.md#layout-0", "text": "The Rustonomicon › Layout\n\nLet's start by making the layout for our implementation of `Arc`.\nAn `Arc` provides thread-safe shared ownership of a value of type `T`,\nallocated in the heap. Sharing implies immutability in Rust, so we don't need to\ndesign anything that manages access to that value, right? Although interior\nmutability types like Mutex allow Arc's users to create shared mutability, Arc\nitself doesn't need to concern itself with these issues.\nHowever there _is_ one place where Arc needs to concern itself with mutation:\ndestruction. When all the owners of the Arc go away, we need to be able to\n`drop` its contents and free its allocation. So we need a way for an owner to\nknow if it's the _last_ owner, and the simplest way to do that is with a count\nof the owners -- Reference Counting.\nUnfortunately, this reference count is inherently shared mutable state, so Arc\n_does_ need to think about synchronization. We _could_ use a Mutex for this, but\nthat's overkill. Instead, we'll use atomics. And since everyone already needs a\npointer to the T's allocation, we might as well put the reference count in that\nsame allocation.\nNaively, it would look something like this:\n```rust\nuse std::sync::atomic;\n\npub struct Arc {\n ptr: *mut ArcInner,\n}\n\npub struct ArcInner {\n rc: atomic::AtomicUsize,\n data: T,\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Layout", "heading_path": ["Layout"], "path": "arc-mutex/arc-layout.md", "url": "https://doc.rust-lang.org/nomicon/arc-mutex/arc-layout.html#layout", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/arc-mutex/arc-layout.md#layout-1", "text": "The Rustonomicon › Layout\n\nThis would compile, however it would be incorrect. First of all, the compiler\nwill give us too strict variance. For example, an `Arc<&'static str>` couldn't\nbe used where an `Arc<&'a str>` was expected. More importantly, it will give\nincorrect ownership information to the drop checker, as it will assume we don't\nown any values of type `T`. As this is a structure providing shared ownership of\na value, at some point there will be an instance of this structure that entirely\nowns its data. See the chapter on ownership and lifetimes for\nall the details on variance and drop check.\nTo fix the first problem, we can use `NonNull`. Note that `NonNull` is a\nwrapper around a raw pointer that declares that:\n* We are covariant over `T`\n* Our pointer is never null\nTo fix the second problem, we can include a `PhantomData` marker containing an\n`ArcInner`. This will tell the drop checker that we have some notion of\nownership of a value of `ArcInner` (which itself contains some `T`).\nWith these changes we get our final structure:\n```rust\nuse std::marker::PhantomData;\nuse std::ptr::NonNull;\nuse std::sync::atomic::AtomicUsize;\n\npub struct Arc {\n ptr: NonNull>,\n phantom: PhantomData>,\n}\n\npub struct ArcInner {\n rc: AtomicUsize,\n data: T,\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Layout", "heading_path": ["Layout"], "path": "arc-mutex/arc-layout.md", "url": "https://doc.rust-lang.org/nomicon/arc-mutex/arc-layout.html#layout", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/arc-mutex/arc-base.md#base-code-0", "text": "The Rustonomicon › Base Code\n\nNow that we've decided the layout for our implementation of `Arc`, let's create\nsome basic code.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Base Code", "heading_path": ["Base Code"], "path": "arc-mutex/arc-base.md", "url": "https://doc.rust-lang.org/nomicon/arc-mutex/arc-base.html#base-code", "has_code": false, "code_tags": []}} {"id": "nomicon/arc-mutex/arc-base.md#constructing-the-arc-1", "text": "The Rustonomicon › Base Code › Constructing the Arc\n\nWe'll first need a way to construct an `Arc`.\nThis is pretty simple, as we just need to box the `ArcInner` and get a\n`NonNull` pointer to it.\n```rust,ignore\nimpl Arc {\n pub fn new(data: T) -> Arc {\n // We start the reference count at 1, as that first reference is the\n // current pointer.\n let boxed = Box::new(ArcInner {\n rc: AtomicUsize::new(1),\n data,\n });\n Arc {\n // It is okay to call `.unwrap()` here as we get a pointer from\n // `Box::into_raw` which is guaranteed to not be null.\n ptr: NonNull::new(Box::into_raw(boxed)).unwrap(),\n phantom: PhantomData,\n }\n }\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Base Code", "heading_path": ["Base Code", "Constructing the Arc"], "path": "arc-mutex/arc-base.md", "url": "https://doc.rust-lang.org/nomicon/arc-mutex/arc-base.html#constructing-the-arc", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/arc-mutex/arc-base.md#send-and-sync-2", "text": "The Rustonomicon › Base Code › Send and Sync\n\nSince we're building a concurrency primitive, we'll need to be able to send it\nacross threads. Thus, we can implement the `Send` and `Sync` marker traits. For\nmore information on these, see the section on `Send` and\n`Sync`.\nThis is okay because:\n* You can only get a mutable reference to the value inside an `Arc` if and only\n if it is the only `Arc` referencing that data (which only happens in `Drop`)\n* We use atomics for the shared mutable reference counting\n```rust,ignore\nunsafe impl Send for Arc {}\nunsafe impl Sync for Arc {}\n```\nWe need to have the bound `T: Sync + Send` because if we did not provide those\nbounds, it would be possible to share values that are thread-unsafe across a\nthread boundary via an `Arc`, which could possibly cause data races or\nunsoundness.\nFor example, if those bounds were not present, `Arc>` would be `Sync` or\n`Send`, meaning that you could clone the `Rc` out of the `Arc` to send it across\na thread (without creating an entirely new `Rc`), which would create data races\nas `Rc` is not thread-safe.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Base Code", "heading_path": ["Base Code", "Send and Sync"], "path": "arc-mutex/arc-base.md", "url": "https://doc.rust-lang.org/nomicon/arc-mutex/arc-base.html#send-and-sync", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/arc-mutex/arc-base.md#getting-the-arcinner-3", "text": "The Rustonomicon › Base Code › Getting the `ArcInner`\n\nTo dereference the `NonNull` pointer into a `&T`, we can call\n`NonNull::as_ref`. This is unsafe, unlike the typical `as_ref` function, so we\nmust call it like this:\n```rust,ignore\nunsafe { self.ptr.as_ref() }\n```\nWe'll be using this snippet a few times in this code (usually with an associated\n`let` binding).\nThis unsafety is okay because while this `Arc` is alive, we're guaranteed that\nthe inner pointer is valid.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Base Code", "heading_path": ["Base Code", "Getting the `ArcInner`"], "path": "arc-mutex/arc-base.md", "url": "https://doc.rust-lang.org/nomicon/arc-mutex/arc-base.html#getting-the-arcinner", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/arc-mutex/arc-base.md#deref-4", "text": "The Rustonomicon › Base Code › Deref\n\nAlright. Now we can make `Arc`s (and soon will be able to clone and destroy them correctly), but how do we get\nto the data inside?\nWhat we need now is an implementation of `Deref`.\nWe'll need to import the trait:\n```rust,ignore\nuse std::ops::Deref;\n```\nAnd here's the implementation:\n```rust,ignore\nimpl Deref for Arc {\n type Target = T;\n\n fn deref(&self) -> &T {\n let inner = unsafe { self.ptr.as_ref() };\n &inner.data\n }\n}\n```\nPretty simple, eh? This simply dereferences the `NonNull` pointer to the\n`ArcInner`, then gets a reference to the data inside.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Base Code", "heading_path": ["Base Code", "Deref"], "path": "arc-mutex/arc-base.md", "url": "https://doc.rust-lang.org/nomicon/arc-mutex/arc-base.html#deref", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/arc-mutex/arc-base.md#code-5", "text": "The Rustonomicon › Base Code › Code\n\nHere's all the code from this section:\n```rust,ignore\nuse std::ops::Deref;\n\nimpl Arc {\n pub fn new(data: T) -> Arc {\n // We start the reference count at 1, as that first reference is the\n // current pointer.\n let boxed = Box::new(ArcInner {\n rc: AtomicUsize::new(1),\n data,\n });\n Arc {\n // It is okay to call `.unwrap()` here as we get a pointer from\n // `Box::into_raw` which is guaranteed to not be null.\n ptr: NonNull::new(Box::into_raw(boxed)).unwrap(),\n phantom: PhantomData,\n }\n }\n}\n\nunsafe impl Send for Arc {}\nunsafe impl Sync for Arc {}\n\n\nimpl Deref for Arc {\n type Target = T;\n\n fn deref(&self) -> &T {\n let inner = unsafe { self.ptr.as_ref() };\n &inner.data\n }\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Base Code", "heading_path": ["Base Code", "Code"], "path": "arc-mutex/arc-base.md", "url": "https://doc.rust-lang.org/nomicon/arc-mutex/arc-base.html#code", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/arc-mutex/arc-clone.md#cloning-0", "text": "The Rustonomicon › Cloning\n\nNow that we've got some basic code set up, we'll need a way to clone the `Arc`.\nBasically, we need to:\n1. Increment the atomic reference count\n2. Construct a new instance of the `Arc` from the inner pointer\nFirst, we need to get access to the `ArcInner`:\n```rust,ignore\nlet inner = unsafe { self.ptr.as_ref() };\n```\nWe can update the atomic reference count as follows:\n```rust,ignore\nlet old_rc = inner.rc.fetch_add(1, Ordering::???);\n```\nBut what ordering should we use here? We don't really have any code that will\nneed atomic synchronization when cloning, as we do not modify the internal value\nwhile cloning. Thus, we can use a Relaxed ordering here, which implies no\nhappens-before relationship but is atomic. When `Drop`ping the Arc, however,\nwe'll need to atomically synchronize when decrementing the reference count. This\nis described more in the section on the `Drop` implementation for\n`Arc`. For more information on atomic relationships and Relaxed\nordering, see the section on atomics.\nThus, the code becomes this:\n```rust,ignore\nlet old_rc = inner.rc.fetch_add(1, Ordering::Relaxed);\n```\nWe'll need to add another import to use `Ordering`:\n```rust\nuse std::sync::atomic::Ordering;\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Cloning", "heading_path": ["Cloning"], "path": "arc-mutex/arc-clone.md", "url": "https://doc.rust-lang.org/nomicon/arc-mutex/arc-clone.html#cloning", "has_code": true, "code_tags": ["rust", "rust,ignore"]}} {"id": "nomicon/arc-mutex/arc-clone.md#cloning-1", "text": "The Rustonomicon › Cloning\n\nHowever, we have one problem with this implementation right now. What if someone\ndecides to `mem::forget` a bunch of Arcs? The code we have written so far (and\nwill write) assumes that the reference count accurately portrays how many Arcs\nare in memory, but with `mem::forget` this is false. Thus, when more and more\nArcs are cloned from this one without them being `Drop`ped and the reference\ncount being decremented, we can overflow! This will cause use-after-free which\nis **INCREDIBLY BAD!**\nTo handle this, we need to check that the reference count does not go over some\narbitrary value (below `usize::MAX`, as we're storing the reference count as an\n`AtomicUsize`), and do *something*.\nThe standard library's implementation decides to just abort the program (as it\nis an incredibly unlikely case in normal code and if it happens, the program is\nprobably incredibly degenerate) if the reference count reaches `isize::MAX`\n(about half of `usize::MAX`) on any thread, on the assumption that there are\nprobably not about 2 billion threads (or about **9 quintillion** on some 64-bit\nmachines) incrementing the reference count at once. This is what we'll do.\nIt's pretty simple to implement this behavior:\n```rust,ignore\nif old_rc >= isize::MAX as usize {\n std::process::abort();\n}\n```\nThen, we need to return a new instance of the `Arc`:\n```rust,ignore\nSelf {\n ptr: self.ptr,\n phantom: PhantomData\n}\n```\nNow, let's wrap this all up inside the `Clone` implementation:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Cloning", "heading_path": ["Cloning"], "path": "arc-mutex/arc-clone.md", "url": "https://doc.rust-lang.org/nomicon/arc-mutex/arc-clone.html#cloning", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/arc-mutex/arc-clone.md#cloning-2", "text": "The Rustonomicon › Cloning\n\n```rust,ignore\nuse std::sync::atomic::Ordering;\n\nimpl Clone for Arc {\n fn clone(&self) -> Arc {\n let inner = unsafe { self.ptr.as_ref() };\n // Using a relaxed ordering is alright here as we don't need any atomic\n // synchronization here as we're not modifying or accessing the inner\n // data.\n let old_rc = inner.rc.fetch_add(1, Ordering::Relaxed);\n\n if old_rc >= isize::MAX as usize {\n std::process::abort();\n }\n\n Self {\n ptr: self.ptr,\n phantom: PhantomData,\n }\n }\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Cloning", "heading_path": ["Cloning"], "path": "arc-mutex/arc-clone.md", "url": "https://doc.rust-lang.org/nomicon/arc-mutex/arc-clone.html#cloning", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/arc-mutex/arc-drop.md#dropping-0", "text": "The Rustonomicon › Dropping\n\nWe now need a way to decrease the reference count and drop the data once it is\nlow enough, otherwise the data will live forever on the heap.\nTo do this, we can implement `Drop`.\nBasically, we need to:\n1. Decrement the reference count\n2. If there is only one reference remaining to the data, then:\n3. Atomically fence the data to prevent reordering of the use and deletion of\n the data\n4. Drop the inner data\nFirst, we'll need to get access to the `ArcInner`:\n```rust,ignore\nlet inner = unsafe { self.ptr.as_ref() };\n```\nNow, we need to decrement the reference count. To streamline our code, we can\nalso return if the returned value from `fetch_sub` (the value of the reference\ncount before decrementing it) is not equal to `1` (which happens when we are not\nthe last reference to the data).\n```rust,ignore\nif inner.rc.fetch_sub(1, Ordering::Release) != 1 {\n return;\n}\n```\nWe then need to create an atomic fence to prevent reordering of the use of the\ndata and deletion of the data. As described in the standard library's\nimplementation of `Arc`:\nThis fence is needed to prevent reordering of use of the data and deletion of\nthe data. Because it is marked `Release`, the decreasing of the reference\ncount synchronizes with this `Acquire` fence. This means that use of the data\nhappens before decreasing the reference count, which happens before this\nfence, which happens before the deletion of the data.\nAs explained in the Boost documentation,", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Dropping", "heading_path": ["Dropping"], "path": "arc-mutex/arc-drop.md", "url": "https://doc.rust-lang.org/nomicon/arc-mutex/arc-drop.html#dropping", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/arc-mutex/arc-drop.md#dropping-1", "text": "The Rustonomicon › Dropping\n\nIt is important to enforce any possible access to the object in one\nthread (through an existing reference) to *happen before* deleting\nthe object in a different thread. This is achieved by a \"release\"\noperation after dropping a reference (any access to the object\nthrough this reference must obviously happened before), and an\n\"acquire\" operation before deleting the object.\nIn particular, while the contents of an Arc are usually immutable, it's\npossible to have interior writes to something like a `Mutex`. Since a Mutex\nis not acquired when it is deleted, we can't rely on its synchronization logic\nto make writes in thread A visible to a destructor running in thread B.\nAlso note that the Acquire fence here could probably be replaced with an\nAcquire load, which could improve performance in highly-contended situations.\nSee [2].\nTo do this, we do the following:\n```rust\nuse std::sync::atomic;\natomic::fence(Ordering::Acquire);\n```\nFinally, we can drop the data itself. We use `Box::from_raw` to drop the boxed\n`ArcInner` and its data. This takes a `*mut T` and not a `NonNull`, so we\nmust convert using `NonNull::as_ptr`.\n```rust,ignore\nunsafe { Box::from_raw(self.ptr.as_ptr()); }\n```\nThis is safe as we know we have the last pointer to the `ArcInner` and that its\npointer is valid.\nNow, let's wrap this all up inside the `Drop` implementation:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Dropping", "heading_path": ["Dropping"], "path": "arc-mutex/arc-drop.md", "url": "https://doc.rust-lang.org/nomicon/arc-mutex/arc-drop.html#dropping", "has_code": true, "code_tags": ["rust", "rust,ignore"]}} {"id": "nomicon/arc-mutex/arc-drop.md#dropping-2", "text": "The Rustonomicon › Dropping\n\n```rust,ignore\nimpl Drop for Arc {\n fn drop(&mut self) {\n let inner = unsafe { self.ptr.as_ref() };\n if inner.rc.fetch_sub(1, Ordering::Release) != 1 {\n return;\n }\n // This fence is needed to prevent reordering of the use and deletion\n // of the data.\n atomic::fence(Ordering::Acquire);\n // This is safe as we know we have the last pointer to the `ArcInner`\n // and that its pointer is valid.\n unsafe { Box::from_raw(self.ptr.as_ptr()); }\n }\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Dropping", "heading_path": ["Dropping"], "path": "arc-mutex/arc-drop.md", "url": "https://doc.rust-lang.org/nomicon/arc-mutex/arc-drop.html#dropping", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/arc-mutex/arc-final.md#final-code-0", "text": "The Rustonomicon › Final Code\n\nHere's the final code, with some added comments and re-ordered imports:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Final Code", "heading_path": ["Final Code"], "path": "arc-mutex/arc-final.md", "url": "https://doc.rust-lang.org/nomicon/arc-mutex/arc-final.html#final-code", "has_code": false, "code_tags": []}} {"id": "nomicon/arc-mutex/arc-final.md#final-code-1", "text": "The Rustonomicon › Final Code\n\n```rust\nuse std::marker::PhantomData;\nuse std::ops::Deref;\nuse std::ptr::NonNull;\nuse std::sync::atomic::{self, AtomicUsize, Ordering};\n\npub struct Arc {\n ptr: NonNull>,\n phantom: PhantomData>,\n}\n\npub struct ArcInner {\n rc: AtomicUsize,\n data: T,\n}\n\nimpl Arc {\n pub fn new(data: T) -> Arc {\n // We start the reference count at 1, as that first reference is the\n // current pointer.\n let boxed = Box::new(ArcInner {\n rc: AtomicUsize::new(1),\n data,\n });\n Arc {\n // It is okay to call `.unwrap()` here as we get a pointer from\n // `Box::into_raw` which is guaranteed to not be null.\n ptr: NonNull::new(Box::into_raw(boxed)).unwrap(),\n phantom: PhantomData,\n }\n }\n}\n\nunsafe impl Send for Arc {}\nunsafe impl Sync for Arc {}\n\nimpl Deref for Arc {\n type Target = T;\n\n fn deref(&self) -> &T {\n let inner = unsafe { self.ptr.as_ref() };\n &inner.data\n }\n}\n\nimpl Clone for Arc {\n fn clone(&self) -> Arc {\n let inner = unsafe { self.ptr.as_ref() };\n // Using a relaxed ordering is alright here as we don't need any atomic\n // synchronization here as we're not modifying or accessing the inner\n // data.\n let old_rc = inner.rc.fetch_add(1, Ordering::Relaxed);\n\n if old_rc >= isize::MAX as usize {\n std::process::abort();\n }\n\n Self {\n ptr: self.ptr,\n phantom: PhantomData,\n }\n }\n}\n\nimpl Drop for Arc {\n fn drop(&mut self) {\n let inner = unsafe { self.ptr.as_ref() };\n if inner.rc.fetch_sub(1, Ordering::Release) != 1 {\n return;\n }\n // This fence is needed to prevent reordering of the use and deletion\n // of the data.\n atomic::fence(Ordering::Acquire);\n // This is safe as we know we have the last pointer to the `ArcInner`\n // and that its pointer is valid.\n unsafe { Box::from_raw(self.ptr.as_ptr()); }\n }\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Final Code", "heading_path": ["Final Code"], "path": "arc-mutex/arc-final.md", "url": "https://doc.rust-lang.org/nomicon/arc-mutex/arc-final.html#final-code", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/ffi.md#introduction-0", "text": "The Rustonomicon › Foreign Function Interface › Introduction\n\nThis guide will use the snappy\ncompression/decompression library as an introduction to writing bindings for\nforeign code. Rust is currently unable to call directly into a C++ library, but\nsnappy includes a C interface (documented in\n`snappy-c.h`).", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "Introduction"], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#introduction", "has_code": false, "code_tags": []}} {"id": "nomicon/ffi.md#a-note-about-libc-1", "text": "The Rustonomicon › Foreign Function Interface › A note about libc\n\nMany of these examples use the `libc` crate, which provides various\ntype definitions for C types, among other things. If you’re trying out these\nexamples yourself, you’ll need to add `libc` to your `Cargo.toml`:\n```toml\n[dependencies]\nlibc = \"0.2.0\"\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "A note about libc"], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#a-note-about-libc", "has_code": true, "code_tags": ["toml"]}} {"id": "nomicon/ffi.md#prepare-the-build-script-2", "text": "The Rustonomicon › Foreign Function Interface › Prepare the build script\n\nBecause snappy is a static library by default, so there is no stdc++ linked in the output artifact. \nIn order to use this foreign library in Rust, we have to manually specify that we want to link stdc++ std to our project.\nThe easiest way to do this is by setting up a build script.\nFirst edit `Cargo.toml`, inside `package` add `build = \"build.rs\"`:\n```toml\n[package]\n...\nbuild = \"build.rs\"\n```\nThen create a new file at the root of your workspace, named `build.rs`:\n```rust\n// build.rs\nfn main() {\n println!(\"cargo:rustc-link-lib=dylib=stdc++\"); // This line may be unnecessary for some environments.\n println!(\"cargo:rustc-link-search=\");\n}\n```\nFor more information, please read The Cargo Book - build script.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "Prepare the build script"], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#prepare-the-build-script", "has_code": true, "code_tags": ["rust", "toml"]}} {"id": "nomicon/ffi.md#calling-foreign-functions-3", "text": "The Rustonomicon › Foreign Function Interface › Calling foreign functions\n\nThe following is a minimal example of calling a foreign function which will\ncompile if snappy is installed:\n```rust,ignore\nuse libc::size_t;\n\n#[link(name = \"snappy\")]\nunsafe extern \"C\" {\n fn snappy_max_compressed_length(source_length: size_t) -> size_t;\n}\n\nfn main() {\n let x = unsafe { snappy_max_compressed_length(100) };\n println!(\"max compressed length of a 100 byte buffer: {}\", x);\n}\n```\nThe `extern` block is a list of function signatures in a foreign library, in\nthis case with the platform's C ABI. The `#[link(...)]` attribute is used to\ninstruct the linker to link against the snappy library so the symbols can be\nresolved.\nForeign functions are assumed to be unsafe so calls to them need to be wrapped\nwith `unsafe {}` as a promise to the compiler that everything contained within\ntruly is safe. C libraries often expose interfaces that aren't thread-safe, and\nalmost any function that takes a pointer argument isn't valid for all possible\ninputs since the pointer could be dangling, and raw pointers fall outside of\nRust's safe memory model.\nWhen declaring the argument types to a foreign function, the Rust compiler\ncannot check if the declaration is correct, so specifying it correctly is part\nof keeping the binding correct at runtime.\nThe `extern` block can be extended to cover the entire snappy API:", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "Calling foreign functions"], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#calling-foreign-functions", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/ffi.md#calling-foreign-functions-4", "text": "The Rustonomicon › Foreign Function Interface › Calling foreign functions\n\n```rust,ignore\nuse libc::{c_int, size_t};\n\n#[link(name = \"snappy\")]\nunsafe extern \"C\" {\n fn snappy_compress(input: *const u8,\n input_length: size_t,\n compressed: *mut u8,\n compressed_length: *mut size_t) -> c_int;\n fn snappy_uncompress(compressed: *const u8,\n compressed_length: size_t,\n uncompressed: *mut u8,\n uncompressed_length: *mut size_t) -> c_int;\n fn snappy_max_compressed_length(source_length: size_t) -> size_t;\n fn snappy_uncompressed_length(compressed: *const u8,\n compressed_length: size_t,\n result: *mut size_t) -> c_int;\n fn snappy_validate_compressed_buffer(compressed: *const u8,\n compressed_length: size_t) -> c_int;\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "Calling foreign functions"], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#calling-foreign-functions", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/ffi.md#creating-a-safe-interface-5", "text": "The Rustonomicon › Foreign Function Interface › Creating a safe interface\n\nThe raw C API needs to be wrapped to provide memory safety and make use of higher-level concepts\nlike vectors. A library can choose to expose only the safe, high-level interface and hide the unsafe\ninternal details.\nWrapping the functions which expect buffers involves using the `slice::raw` module to manipulate Rust's\nvectors as pointers to memory. Rust's vectors are guaranteed to be a contiguous block of memory. The\nlength is the number of elements currently contained, and the capacity is the total size in elements of\nthe allocated memory. The length is less than or equal to the capacity.\n```rust,ignore\npub fn validate_compressed_buffer(src: &[u8]) -> bool {\n unsafe {\n snappy_validate_compressed_buffer(src.as_ptr(), src.len() as size_t) == 0\n }\n}\n```\nThe `validate_compressed_buffer` wrapper above makes use of an `unsafe` block, but it makes the\nguarantee that calling it is safe for all inputs by leaving off `unsafe` from the function\nsignature.\nThe `snappy_compress` and `snappy_uncompress` functions are more complex, since a buffer has to be\nallocated to hold the output too.\nThe `snappy_max_compressed_length` function can be used to allocate a vector with the maximum\nrequired capacity to hold the compressed output. The vector can then be passed to the\n`snappy_compress` function as an output parameter. An output parameter is also passed to retrieve\nthe true length after compression for setting the length.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "Creating a safe interface"], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#creating-a-safe-interface", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/ffi.md#creating-a-safe-interface-6", "text": "The Rustonomicon › Foreign Function Interface › Creating a safe interface\n\n```rust,ignore\npub fn compress(src: &[u8]) -> Vec {\n unsafe {\n let srclen = src.len() as size_t;\n let psrc = src.as_ptr();\n\n let mut dstlen = snappy_max_compressed_length(srclen);\n let mut dst = Vec::with_capacity(dstlen as usize);\n let pdst = dst.as_mut_ptr();\n\n snappy_compress(psrc, srclen, pdst, &mut dstlen);\n dst.set_len(dstlen as usize);\n dst\n }\n}\n```\nDecompression is similar, because snappy stores the uncompressed size as part of the compression\nformat and `snappy_uncompressed_length` will retrieve the exact buffer size required.\n```rust,ignore\npub fn uncompress(src: &[u8]) -> Option> {\n unsafe {\n let srclen = src.len() as size_t;\n let psrc = src.as_ptr();\n\n let mut dstlen: size_t = 0;\n snappy_uncompressed_length(psrc, srclen, &mut dstlen);\n\n let mut dst = Vec::with_capacity(dstlen as usize);\n let pdst = dst.as_mut_ptr();\n\n if snappy_uncompress(psrc, srclen, pdst, &mut dstlen) == 0 {\n dst.set_len(dstlen as usize);\n Some(dst)\n } else {\n None // SNAPPY_INVALID_INPUT\n }\n }\n}\n```\nThen, we can add some tests to show how to use them.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "Creating a safe interface"], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#creating-a-safe-interface", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/ffi.md#creating-a-safe-interface-7", "text": "The Rustonomicon › Foreign Function Interface › Creating a safe interface\n\n```rust,ignore\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn valid() {\n let d = vec![0xde, 0xad, 0xd0, 0x0d];\n let c: &[u8] = &compress(&d);\n assert!(validate_compressed_buffer(c));\n assert!(uncompress(c) == Some(d));\n }\n\n #[test]\n fn invalid() {\n let d = vec![0, 0, 0, 0];\n assert!(!validate_compressed_buffer(&d));\n assert!(uncompress(&d).is_none());\n }\n\n #[test]\n fn empty() {\n let d = vec![];\n assert!(!validate_compressed_buffer(&d));\n assert!(uncompress(&d).is_none());\n let c = compress(&d);\n assert!(validate_compressed_buffer(&c));\n assert!(uncompress(&c) == Some(d));\n }\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "Creating a safe interface"], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#creating-a-safe-interface", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/ffi.md#destructors-8", "text": "The Rustonomicon › Foreign Function Interface › Destructors\n\nForeign libraries often hand off ownership of resources to the calling code.\nWhen this occurs, we must use Rust's destructors to provide safety and guarantee\nthe release of these resources (especially in the case of a panic).\nFor more information about destructors, see the Drop trait.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "Destructors"], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#destructors", "has_code": false, "code_tags": []}} {"id": "nomicon/ffi.md#calling-rust-code-from-c-9", "text": "The Rustonomicon › Foreign Function Interface › Calling Rust code from C\n\nYou may wish to compile Rust code in a way that can be called from C.\nThis is fairly easy, but requires a few things.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "Calling Rust code from C"], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#calling-rust-code-from-c", "has_code": false, "code_tags": []}} {"id": "nomicon/ffi.md#rust-side-10", "text": "The Rustonomicon › Foreign Function Interface › Calling Rust code from C › Rust side\n\nFirst, we assume you have a lib crate named as `rust_from_c`.\n`lib.rs` should have Rust code as following:\n```rust\n#[unsafe(no_mangle)]\npub extern \"C\" fn hello_from_rust() {\n println!(\"Hello from Rust!\");\n}\n```\nThe `extern \"C\"` makes this function adhere to the C calling convention, as discussed below in \"[Foreign Calling Conventions]\".\nThe `no_mangle` attribute turns off Rust's name mangling, so that it has a well defined symbol to link to.\nThen, to compile Rust code as a shared library that can be called from C, add the following to your `Cargo.toml`:\n```toml\n[lib]\ncrate-type = [\"cdylib\"]\n```\n(NOTE: We could also use the `staticlib` crate type but it also requires tweaking some linking flags.)\nRun `cargo build` and you're ready to go on the Rust side.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "Calling Rust code from C", "Rust side"], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#rust-side", "has_code": true, "code_tags": ["rust", "toml"]}} {"id": "nomicon/ffi.md#c-side-11", "text": "The Rustonomicon › Foreign Function Interface › Calling Rust code from C › C side\n\nWe'll create a C file to call the `hello_from_rust` function and compile it by `gcc`.\nC file should look like:\n```c\nextern void hello_from_rust();\n\nint main(void) {\n hello_from_rust();\n return 0;\n}\n```\nWe name the file as `call_rust.c` and place it on the crate root.\nRun the following to compile:\n```sh\ngcc call_rust.c -o call_rust -lrust_from_c -L./target/debug\n```\n`-l` and `-L` tell gcc to find our Rust library.\nFinally, we can call Rust code from C with `LD_LIBRARY_PATH` specified:\n```sh\n$ LD_LIBRARY_PATH=./target/debug ./call_rust\nHello from Rust!\n```\nThat's it!\nFor a more realistic example, check the [`cbindgen`].", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "Calling Rust code from C", "C side"], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#c-side", "has_code": true, "code_tags": ["c", "sh"]}} {"id": "nomicon/ffi.md#callbacks-from-c-code-to-rust-functions-12", "text": "The Rustonomicon › Foreign Function Interface › Callbacks from C code to Rust functions\n\nSome external libraries require the usage of callbacks to report back their\ncurrent state or intermediate data to the caller.\nIt is possible to pass functions defined in Rust to an external library.\nThe requirement for this is that the callback function is marked as `extern`\nwith the correct calling convention to make it callable from C code.\nThe callback function can then be sent through a registration call\nto the C library and afterwards be invoked from there.\nA basic example is:\nRust code:\n```rust,no_run\nextern fn callback(a: i32) {\n println!(\"I'm called from C with value {0}\", a);\n}\n\n#[link(name = \"extlib\")]\nunsafe extern \"C\" {\n fn register_callback(cb: extern fn(i32)) -> i32;\n fn trigger_callback();\n}\n\nfn main() {\n unsafe {\n register_callback(callback);\n trigger_callback(); // Triggers the callback.\n }\n}\n```\nC code:\n```c\ntypedef void (*rust_callback)(int32_t);\nrust_callback cb;\n\nint32_t register_callback(rust_callback callback) {\n cb = callback;\n return 1;\n}\n\nvoid trigger_callback() {\n cb(7); // Will call callback(7) in Rust.\n}\n```\nIn this example Rust's `main()` will call `trigger_callback()` in C,\nwhich would, in turn, call back to `callback()` in Rust.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "Callbacks from C code to Rust functions"], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#callbacks-from-c-code-to-rust-functions", "has_code": true, "code_tags": ["c", "rust,no_run"]}} {"id": "nomicon/ffi.md#targeting-callbacks-to-rust-objects-13", "text": "The Rustonomicon › Foreign Function Interface › Targeting callbacks to Rust objects\n\nThe former example showed how a global function can be called from C code.\nHowever it is often desired that the callback is targeted to a special\nRust object. This could be the object that represents the wrapper for the\nrespective C object.\nThis can be achieved by passing a raw pointer to the object down to the\nC library. The C library can then include the pointer to the Rust object in\nthe notification. This will allow the callback to unsafely access the\nreferenced Rust object.\nRust code:\n```rust,no_run\nstruct RustObject {\n a: i32,\n // Other members...\n}\n\nunsafe extern \"C\" fn callback(target: *mut RustObject, a: i32) {\n println!(\"I'm called from C with value {0}\", a);\n unsafe {\n // Update the value in RustObject with the value received from the callback:\n (*target).a = a;\n }\n}\n\n#[link(name = \"extlib\")]\nunsafe extern \"C\" {\n fn register_callback(target: *mut RustObject,\n cb: unsafe extern \"C\" fn(*mut RustObject, i32)) -> i32;\n fn trigger_callback();\n}\n\nfn main() {\n // Create the object that will be referenced in the callback:\n let mut rust_object = Box::new(RustObject { a: 5 });\n\n unsafe {\n register_callback(&mut *rust_object, callback);\n trigger_callback();\n }\n}\n```\nC code:\n```c\ntypedef void (*rust_callback)(void*, int32_t);\nvoid* cb_target;\nrust_callback cb;\n\nint32_t register_callback(void* callback_target, rust_callback callback) {\n cb_target = callback_target;\n cb = callback;\n return 1;\n}\n\nvoid trigger_callback() {\n cb(cb_target, 7); // Will call callback(&rustObject, 7) in Rust.\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "Targeting callbacks to Rust objects"], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#targeting-callbacks-to-rust-objects", "has_code": true, "code_tags": ["c", "rust,no_run"]}} {"id": "nomicon/ffi.md#asynchronous-callbacks-14", "text": "The Rustonomicon › Foreign Function Interface › Asynchronous callbacks\n\nIn the previously given examples the callbacks are invoked as a direct reaction\nto a function call to the external C library.\nThe control over the current thread is switched from Rust to C to Rust for the\nexecution of the callback, but in the end the callback is executed on the\nsame thread that called the function which triggered the callback.\nThings get more complicated when the external library spawns its own threads\nand invokes callbacks from there.\nIn these cases access to Rust data structures inside the callbacks is\nespecially unsafe and proper synchronization mechanisms must be used.\nBesides classical synchronization mechanisms like mutexes, one possibility in\nRust is to use channels (in `std::sync::mpsc`) to forward data from the C\nthread that invoked the callback into a Rust thread.\nIf an asynchronous callback targets a special object in the Rust address space\nit is also absolutely necessary that no more callbacks are performed by the\nC library after the respective Rust object gets destroyed.\nThis can be achieved by unregistering the callback in the object's\ndestructor and designing the library in a way that guarantees that no\ncallback will be performed after deregistration.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "Asynchronous callbacks"], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#asynchronous-callbacks", "has_code": false, "code_tags": []}} {"id": "nomicon/ffi.md#linking-15", "text": "The Rustonomicon › Foreign Function Interface › Linking\n\nThe `link` attribute on `extern` blocks provides the basic building block for\ninstructing rustc how it will link to native libraries. There are two accepted\nforms of the link attribute today:\n* `#[link(name = \"foo\")]`\n* `#[link(name = \"foo\", kind = \"bar\")]`\nIn both of these cases, `foo` is the name of the native library that we're\nlinking to, and in the second case `bar` is the type of native library that the\ncompiler is linking to. There are currently three known types of native\nlibraries:\n* Dynamic - `#[link(name = \"readline\")]`\n* Static - `#[link(name = \"my_build_dependency\", kind = \"static\")]`\n* Frameworks - `#[link(name = \"CoreFoundation\", kind = \"framework\")]`\nNote that frameworks are only available on macOS targets.\nThe different `kind` values are meant to differentiate how the native library\nparticipates in linkage. From a linkage perspective, the Rust compiler creates\ntwo flavors of artifacts: partial (rlib/staticlib) and final (dylib/binary).\nNative dynamic library and framework dependencies are propagated to the final\nartifact boundary, while static library dependencies are not propagated at\nall, because the static libraries are integrated directly into the subsequent\nartifact.\nA few examples of how this model can be used are:\n* A native build dependency. Sometimes some C/C++ glue is needed when writing\n some Rust code, but distribution of the C/C++ code in a library format is\n a burden. In this case, the code will be archived into `libfoo.a` and then the\n Rust crate would declare a dependency via `#[link(name = \"foo\", kind =\n \"static\")]`.\n Regardless of the flavor of output for the crate, the native static library\n will be included in the output, meaning that distribution of the native static\n library is not necessary.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "Linking"], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#linking", "has_code": false, "code_tags": []}} {"id": "nomicon/ffi.md#linking-16", "text": "The Rustonomicon › Foreign Function Interface › Linking\n\n* A normal dynamic dependency. Common system libraries (like `readline`) are\n available on a large number of systems, and often a static copy of these\n libraries cannot be found. When this dependency is included in a Rust crate,\n partial targets (like rlibs) will not link to the library, but when the rlib\n is included in a final target (like a binary), the native library will be\n linked in.\nOn macOS, frameworks behave with the same semantics as a dynamic library.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "Linking"], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#linking", "has_code": false, "code_tags": []}} {"id": "nomicon/ffi.md#unsafe-blocks-17", "text": "The Rustonomicon › Foreign Function Interface › Unsafe blocks\n\nSome operations, like dereferencing raw pointers or calling functions that have been marked\nunsafe are only allowed inside unsafe blocks. Unsafe blocks isolate unsafety and are a promise to\nthe compiler that the unsafety does not leak out of the block.\nUnsafe functions, on the other hand, advertise it to the world. An unsafe function is written like\nthis:\n```rust\nunsafe fn kaboom(ptr: *const i32) -> i32 { *ptr }\n```\nThis function can only be called from an `unsafe` block or another `unsafe` function.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "Unsafe blocks"], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#unsafe-blocks", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/ffi.md#accessing-foreign-globals-18", "text": "The Rustonomicon › Foreign Function Interface › Accessing foreign globals\n\nForeign APIs often export a global variable which could do something like track\nglobal state. In order to access these variables, you declare them in `extern`\nblocks with the `static` keyword:\n```rust,ignore\n#[link(name = \"readline\")]\nunsafe extern \"C\" {\n static rl_readline_version: libc::c_int;\n}\n\nfn main() {\n println!(\"You have readline version {} installed.\",\n unsafe { rl_readline_version as i32 });\n}\n```\nAlternatively, you may need to alter global state provided by a foreign\ninterface. To do this, statics can be declared with `mut` so we can mutate\nthem.\n```rust,ignore\nuse std::ffi::CString;\nuse std::ptr;\n\n#[link(name = \"readline\")]\nunsafe extern \"C\" {\n static mut rl_prompt: *const libc::c_char;\n}\n\nfn main() {\n let prompt = CString::new(\"[my-awesome-shell] $\").unwrap();\n unsafe {\n rl_prompt = prompt.as_ptr();\n\n println!(\"{:?}\", rl_prompt);\n\n rl_prompt = ptr::null();\n }\n}\n```\nNote that all interaction with a `static mut` is unsafe, both reading and\nwriting. Dealing with global mutable state requires a great deal of care.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "Accessing foreign globals"], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#accessing-foreign-globals", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/ffi.md#foreign-calling-conventions-19", "text": "The Rustonomicon › Foreign Function Interface › Foreign calling conventions\n\nMost foreign code exposes a C ABI, and Rust uses the platform's C calling convention by default when\ncalling foreign functions. Some foreign functions, most notably the Windows API, use other calling\nconventions. Rust provides a way to tell the compiler which convention to use:\n```rust,ignore\n#[cfg(all(target_os = \"win32\", target_arch = \"x86\"))]\n#[link(name = \"kernel32\")]\n#[allow(non_snake_case)]\nunsafe extern \"stdcall\" {\n fn SetEnvironmentVariableA(n: *const u8, v: *const u8) -> libc::c_int;\n}\n```\nThis applies to the entire `extern` block. The list of supported ABI constraints\nare:\n* `stdcall`\n* `aapcs`\n* `cdecl`\n* `fastcall`\n* `thiscall`\n* `vectorcall`\nThis is currently hidden behind the `abi_vectorcall` gate and is subject to change.\n* `Rust`\n* `system`\n* `C`\n* `win64`\n* `sysv64`\nMost of the ABIs in this list are self-explanatory, but the `system` ABI may\nseem a little odd. This constraint selects whatever the appropriate ABI is for\ninteroperating with the target's libraries. For example, on win32 with a x86\narchitecture, this means that the abi used would be `stdcall`. On x86_64,\nhowever, windows uses the `C` calling convention, so `C` would be used. This\nmeans that in our previous example, we could have used `extern \"system\" { ... }`\nto define a block for all windows systems, not only x86 ones.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "Foreign calling conventions"], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#foreign-calling-conventions", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "nomicon/ffi.md#interoperability-with-foreign-code-20", "text": "The Rustonomicon › Foreign Function Interface › Interoperability with foreign code\n\nRust guarantees that the layout of a `struct` is compatible with the platform's\nrepresentation in C only if the `#[repr(C)]` attribute is applied to it.\n`#[repr(C, packed)]` can be used to lay out struct members without padding.\n`#[repr(C)]` can also be applied to an enum.\nRust's owned boxes (`Box`) use non-nullable pointers as handles which point\nto the contained object. However, they should not be manually created because\nthey are managed by internal allocators. References can safely be assumed to be\nnon-nullable pointers directly to the type. However, breaking the borrow\nchecking or mutability rules is not guaranteed to be safe, so prefer using raw\npointers (`*`) if that's needed because the compiler can't make as many\nassumptions about them.\nVectors and strings share the same basic memory layout, and utilities are\navailable in the `vec` and `str` modules for working with C APIs. However,\nstrings are not terminated with `\\0`. If you need a NUL-terminated string for\ninteroperability with C, you should use the `CString` type in the `std::ffi`\nmodule.\nThe `libc` crate on crates.io includes type aliases and function\ndefinitions for the C standard library in the `libc` module, and Rust links\nagainst `libc` and `libm` by default.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "Interoperability with foreign code"], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#interoperability-with-foreign-code", "has_code": false, "code_tags": []}} {"id": "nomicon/ffi.md#variadic-functions-21", "text": "The Rustonomicon › Foreign Function Interface › Variadic functions\n\nIn C, functions can be 'variadic', meaning they accept a variable number of arguments. This can\nbe achieved in Rust by specifying `...` within the argument list of a foreign function declaration:\n```no_run\nunsafe extern \"C\" {\n fn foo(x: i32, ...);\n}\n\nfn main() {\n unsafe {\n foo(10, 20, 30, 40, 50);\n }\n}\n```\nNormal Rust functions can *not* be variadic:\n```rust,compile_fail\n// This will not compile\n\nfn foo(x: i32, ...) {}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "Variadic functions"], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#variadic-functions", "has_code": true, "code_tags": ["no_run", "rust,compile_fail"]}} {"id": "nomicon/ffi.md#the-nullable-pointer-optimization-22", "text": "The Rustonomicon › Foreign Function Interface › The \"nullable pointer optimization\"\n\nCertain Rust types are defined to never be `null`. This includes references (`&T`,\n`&mut T`), boxes (`Box`), and function pointers (`extern \"abi\" fn()`). When\ninterfacing with C, pointers that might be `null` are often used, which would seem to\nrequire some messy `transmute`s and/or unsafe code to handle conversions to/from Rust types.\nHowever, trying to construct/work with these invalid values **is undefined behavior**,\nso you should use the following workaround instead.\nAs a special case, an `enum` is eligible for the \"nullable pointer optimization\" if it contains\nexactly two variants, one of which contains no data and the other contains a field of one of the\nnon-nullable types listed above. This means no extra space is required for a discriminant; rather,\nthe empty variant is represented by putting a `null` value into the non-nullable field. This is\ncalled an \"optimization\", but unlike other optimizations it is guaranteed to apply to eligible\ntypes.\nThe most common type that takes advantage of the nullable pointer optimization is `Option`,\nwhere `None` corresponds to `null`. So `Option c_int>` is a correct way\nto represent a nullable function pointer using the C ABI (corresponding to the C type\n`int (*)(int)`).\nHere is a contrived example. Let's say some C library has a facility for registering a\ncallback, which gets called in certain situations. The callback is passed a function pointer\nand an integer and it is supposed to run the function with the integer as a parameter. So\nwe have function pointers flying across the FFI boundary in both directions.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "The \"nullable pointer optimization\""], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#the-nullable-pointer-optimization", "has_code": false, "code_tags": []}} {"id": "nomicon/ffi.md#the-nullable-pointer-optimization-23", "text": "The Rustonomicon › Foreign Function Interface › The \"nullable pointer optimization\"\n\n```rust,ignore\nuse libc::c_int;\n\nunsafe extern \"C\" {\n /// Registers the callback.\n fn register(cb: Option c_int>, c_int) -> c_int>);\n}\n\n/// This fairly useless function receives a function pointer and an integer\n/// from C, and returns the result of calling the function with the integer.\n/// In case no function is provided, it squares the integer by default.\nextern \"C\" fn apply(process: Option c_int>, int: c_int) -> c_int {\n match process {\n Some(f) => f(int),\n None => int * int\n }\n}\n\nfn main() {\n unsafe {\n register(Some(apply));\n }\n}\n```\nAnd the code on the C side looks like this:\n```c\nvoid register(int (*f)(int (*)(int), int)) {\n ...\n}\n```\nNo `transmute` required!", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "The \"nullable pointer optimization\""], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#the-nullable-pointer-optimization", "has_code": true, "code_tags": ["c", "rust,ignore"]}} {"id": "nomicon/ffi.md#ffi-and-unwinding-24", "text": "The Rustonomicon › Foreign Function Interface › FFI and unwinding\n\nIt’s important to be mindful of unwinding when working with FFI. Most\nABI strings come in two variants, one with an `-unwind` suffix and one without.\nThe `Rust` ABI always permits unwinding, so there is no `Rust-unwind` ABI.\nIf you expect Rust `panic`s or foreign (e.g. C++) exceptions to cross an FFI\nboundary, that boundary must use the appropriate `-unwind` ABI string.\nConversely, if you do not expect unwinding to cross an ABI boundary, use one of\nthe non-`unwind` ABI strings.\nNote: Compiling with `panic=abort` will still cause `panic!` to immediately\nabort the process, regardless of which ABI is specified by the function that\n`panic`s.\nIf an unwinding operation does encounter an ABI boundary that is\nnot permitted to unwind, the behavior depends on the source of the unwinding\n(Rust `panic` or a foreign exception):\n* `panic` will cause the process to safely abort.\n* A foreign exception entering Rust will cause undefined behavior.\nNote that the interaction of `catch_unwind` with foreign exceptions **is\nundefined**, as is the interaction of `panic` with foreign exception-catching\nmechanisms (notably C++'s `try`/`catch`).", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "FFI and unwinding"], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#ffi-and-unwinding", "has_code": false, "code_tags": []}} {"id": "nomicon/ffi.md#rust-panic-with-c-unwind-25", "text": "The Rustonomicon › Foreign Function Interface › FFI and unwinding › Rust `panic` with `\"C-unwind\"`\n\n```rust,ignore\n#[unsafe(no_mangle)]\nunsafe extern \"C-unwind\" fn example() {\n panic!(\"Uh oh\");\n}\n```\nThis function (when compiled with `panic=unwind`) is permitted to unwind C++\nstack frames.\n```text\n[Rust function with `catch_unwind`, which stops the unwinding]\n |\n ...\n |\n[C++ frames]\n | ^\n | (calls) | (unwinding\n v | goes this\n[Rust function `example`] | way)\n | |\n +--- rust function panics --+\n```\nIf the C++ frames have objects, their destructors will be called.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "FFI and unwinding", "Rust `panic` with `\"C-unwind\"`"], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#rust-panic-with-c-unwind", "has_code": true, "code_tags": ["rust,ignore", "text"]}} {"id": "nomicon/ffi.md#c-throw-with-c-unwind-26", "text": "The Rustonomicon › Foreign Function Interface › FFI and unwinding › C++ `throw` with `\"C-unwind\"`\n\n```rust,ignore\n#[link(...)]\nunsafe extern \"C-unwind\" {\n // A C++ function that may throw an exception\n fn may_throw();\n}\n\n#[unsafe(no_mangle)]\nunsafe extern \"C-unwind\" fn rust_passthrough() {\n let b = Box::new(5);\n unsafe { may_throw(); }\n println!(\"{:?}\", &b);\n}\n```\nA C++ function with a `try` block may invoke `rust_passthrough` and `catch` an\nexception thrown by `may_throw`.\n```text\n[C++ function with `try` block that invokes `rust_passthrough`]\n |\n ...\n |\n[Rust function `rust_passthrough`]\n | ^\n | (calls) | (unwinding\n v | goes this\n[C++ function `may_throw`] | way)\n | |\n +--- C++ function throws ----+\n```\nIf `may_throw` does throw an exception, `b` will be dropped. Otherwise, `5`\nwill be printed.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "FFI and unwinding", "C++ `throw` with `\"C-unwind\"`"], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#c-throw-with-c-unwind", "has_code": true, "code_tags": ["rust,ignore", "text"]}} {"id": "nomicon/ffi.md#panic-can-be-stopped-at-an-abi-boundary-27", "text": "The Rustonomicon › Foreign Function Interface › FFI and unwinding › `panic` can be stopped at an ABI boundary\n\n```rust\n#[unsafe(no_mangle)]\nextern \"C\" fn assert_nonzero(input: u32) {\n assert!(input != 0)\n}\n```\nIf `assert_nonzero` is called with the argument `0`, the runtime is guaranteed\nto (safely) abort the process, whether or not compiled with `panic=abort`.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "FFI and unwinding", "`panic` can be stopped at an ABI boundary"], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#panic-can-be-stopped-at-an-abi-boundary", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/ffi.md#catching-panic-preemptively-28", "text": "The Rustonomicon › Foreign Function Interface › FFI and unwinding › Catching `panic` preemptively\n\nIf you are writing Rust code that may panic, and you don't wish to abort the\nprocess if it panics, you must use [`catch_unwind`]:\n```rust\nuse std::panic::catch_unwind;\n\n#[unsafe(no_mangle)]\npub extern \"C\" fn oh_no() -> i32 {\n let result = catch_unwind(|| {\n panic!(\"Oops!\");\n });\n match result {\n Ok(_) => 0,\n Err(_) => 1,\n }\n}\n\nfn main() {}\n```\nPlease note that [`catch_unwind`] will only catch unwinding panics, not\nthose that abort the process. See the documentation of [`catch_unwind`]\nfor more information.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "FFI and unwinding", "Catching `panic` preemptively"], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#catching-panic-preemptively", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/ffi.md#representing-opaque-structs-29", "text": "The Rustonomicon › Foreign Function Interface › Representing opaque structs\n\nSometimes, a C library wants to provide a pointer to something, but not let you know the internal details of the thing it wants.\nA stable and simple way is to use a `void *` argument:\n```c\nvoid foo(void *arg);\nvoid bar(void *arg);\n```\nWe can represent this in Rust with the `c_void` type:\n```rust,ignore\nunsafe extern \"C\" {\n pub fn foo(arg: *mut libc::c_void);\n pub fn bar(arg: *mut libc::c_void);\n}\n```\nThis is a perfectly valid way of handling the situation. However, we can do a bit\nbetter. To solve this, some C libraries will instead create a `struct`, where\nthe details and memory layout of the struct are private. This gives some amount\nof type safety. These structures are called ‘opaque’. Here’s an example, in C:\n```c\nstruct Foo; /* Foo is a structure, but its contents are not part of the public interface */\nstruct Bar;\nvoid foo(struct Foo *arg);\nvoid bar(struct Bar *arg);\n```\nTo do this in Rust, let’s create our own opaque types:\n```rust\n#[repr(C)]\npub struct Foo {\n _data: (),\n _marker:\n core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>,\n}\n#[repr(C)]\npub struct Bar {\n _data: (),\n _marker:\n core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>,\n}\n\nunsafe extern \"C\" {\n pub fn foo(arg: *mut Foo);\n pub fn bar(arg: *mut Bar);\n}\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "Representing opaque structs"], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#representing-opaque-structs", "has_code": true, "code_tags": ["c", "rust", "rust,ignore"]}} {"id": "nomicon/ffi.md#representing-opaque-structs-30", "text": "The Rustonomicon › Foreign Function Interface › Representing opaque structs\n\nBy including at least one private field and no constructor,\nwe create an opaque type that we can't instantiate outside of this module.\n(A struct with no field could be instantiated by anyone.)\nWe also want to use this type in FFI, so we have to add `#[repr(C)]`.\nThe marker ensures the compiler does not mark the struct as `Send`, `Sync`, and\n`Unpin`. (`*mut u8` is not `Send` or `Sync`, `PhantomPinned` is not `Unpin`)\nBut because our `Foo` and `Bar` types are\ndifferent, we’ll get type safety between the two of them, so we cannot\naccidentally pass a pointer to `Foo` to `bar()`.\nNotice that it is a really bad idea to use an empty enum as FFI type.\nThe compiler relies on empty enums being uninhabited, so handling values of type\n`&Empty` is a huge footgun and can lead to buggy program behavior (by triggering\nundefined behavior).\n**NOTE:** The simplest way would use \"extern types\".\nBut it's currently (as of June 2021) unstable and has some unresolved questions, see the RFC page and the tracking issue for more details.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "FFI", "heading_path": ["Foreign Function Interface", "Representing opaque structs"], "path": "ffi.md", "url": "https://doc.rust-lang.org/nomicon/ffi.html#representing-opaque-structs", "has_code": false, "code_tags": []}} {"id": "nomicon/beneath-std.md#beneath-std-0", "text": "The Rustonomicon › Beneath `std`\n\nThis section documents features that are normally provided by the `std` crate and\nthat `#![no_std]` developers have to deal with (i.e. provide) to build\n`#![no_std]` binary crates.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Beneath `std`", "heading_path": ["Beneath `std`"], "path": "beneath-std.md", "url": "https://doc.rust-lang.org/nomicon/beneath-std.html#beneath-std", "has_code": false, "code_tags": []}} {"id": "nomicon/beneath-std.md#using-libc-1", "text": "The Rustonomicon › Beneath `std` › Using `libc`\n\nIn order to build a `#[no_std]` executable we will need `libc` as a dependency.\nWe can specify this using our `Cargo.toml` file:\n```toml\n[dependencies]\nlibc = { version = \"0.2.146\", default-features = false }\n```\nNote that the default features have been disabled. This is a critical step -\n**the default features of `libc` include the `std` crate and so must be\ndisabled.**\nAlternatively, we can use the unstable `rustc_private` private feature together\nwith an `extern crate libc;` declaration as shown in the examples below. Note that\nwindows-msvc targets do not require a libc, and correspondingly there is no `libc`\ncrate in their sysroot. We do not need the `extern crate libc;` below, and having it\non a windows-msvc target would be a compile error.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Beneath `std`", "heading_path": ["Beneath `std`", "Using `libc`"], "path": "beneath-std.md", "url": "https://doc.rust-lang.org/nomicon/beneath-std.html#using-libc", "has_code": true, "code_tags": ["toml"]}} {"id": "nomicon/beneath-std.md#writing-an-executable-without-std-2", "text": "The Rustonomicon › Beneath `std` › Writing an executable without `std`\n\nWe will probably need a nightly version of the compiler to produce\na `#![no_std]` executable because on many platforms, we have to provide the\n`eh_personality` [lang item], which is unstable.\nYou will need to define a symbol for the entry point that is suitable for your target. For example, `main`, `_start`, `WinMain`, or whatever starting point is relevant for your target.\nAdditionally, you need to use the `#![no_main]` attribute to prevent the compiler from attempting to generate an entry point itself.\nAdditionally, it's required to define a panic handler function.\n```rust\n#![feature(lang_items, core_intrinsics, rustc_private)]\n#![allow(internal_features)]\n#![no_std]\n#![no_main]\n\n// Necessary for `panic = \"unwind\"` builds on cfg(unix) platforms.\n#![feature(panic_unwind)]\nextern crate unwind;\n\n// Pull in the system libc library for what crt0.o likely requires.\n#[cfg(not(windows))]\nextern crate libc;\n\nuse core::ffi::{c_char, c_int};\nuse core::panic::PanicInfo;\n\n// Entry point for this program.\n#[unsafe(no_mangle)] // ensure that this symbol is included in the output as `main`\nextern \"C\" fn main(_argc: c_int, _argv: *const *const c_char) -> c_int {\n 0\n}\n\n// These functions are used by the compiler, but not for an empty program like this.\n// They are normally provided by `std`.\n#[lang = \"eh_personality\"]\nfn rust_eh_personality() {}\n#[panic_handler]\nfn panic_handler(_info: &PanicInfo) -> ! { core::intrinsics::abort() }\n```", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Beneath `std`", "heading_path": ["Beneath `std`", "Writing an executable without `std`"], "path": "beneath-std.md", "url": "https://doc.rust-lang.org/nomicon/beneath-std.html#writing-an-executable-without-std", "has_code": true, "code_tags": ["rust"]}} {"id": "nomicon/beneath-std.md#writing-an-executable-without-std-3", "text": "The Rustonomicon › Beneath `std` › Writing an executable without `std`\n\nIf you are working with a target that doesn't have binary releases of the\nstandard library available via rustup (this probably means you are building the\n`core` crate yourself) and need compiler-rt intrinsics (i.e. you are probably\ngetting linker errors when building an executable:\n``undefined reference to `__aeabi_memcpy'``), you need to manually link to the\n[`compiler_builtins` crate] to get those intrinsics and solve the linker errors.", "metadata": {"book": "nomicon", "book_title": "The Rustonomicon", "part": "Summary", "chapter": "Beneath `std`", "heading_path": ["Beneath `std`", "Writing an executable without `std`"], "path": "beneath-std.md", "url": "https://doc.rust-lang.org/nomicon/beneath-std.html#writing-an-executable-without-std", "has_code": false, "code_tags": []}} {"id": "reference/introduction.md#introduction-0", "text": "The Rust Reference › Introduction\n\nThis book is the primary reference for the Rust programming language.\nFor known bugs and omissions in this book, see our [GitHub issues]. If you see a case where the compiler behavior and the text here do not agree, file an issue so we can think about which is correct.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Introduction", "heading_path": ["Introduction"], "path": "introduction.md", "url": "https://doc.rust-lang.org/reference/introduction.html#introduction", "has_code": false, "code_tags": []}} {"id": "reference/introduction.md#rust-releases-1", "text": "The Rust Reference › Introduction › Rust releases\n\nRust has a new language release every six weeks.\nThe first stable release of the language was Rust 1.0.0, followed by Rust 1.1.0 and so on.\nTools (`rustc`, `cargo`, etc.) and documentation ([Standard library], this book, etc.) are released with the language release.\nThe latest release of this book, matching the latest Rust version, can always be found at .\nPrior versions can be found by adding the Rust version before the \"reference\" directory.\nFor example, the Reference for Rust 1.49.0 is located at .", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Introduction", "heading_path": ["Introduction", "Rust releases"], "path": "introduction.md", "url": "https://doc.rust-lang.org/reference/introduction.html#rust-releases", "has_code": false, "code_tags": []}} {"id": "reference/introduction.md#what-the-reference-is-not-2", "text": "The Rust Reference › Introduction › What The Reference is not\n\nThis book does not serve as an introduction to the language.\nBackground familiarity with the language is assumed.\nA separate [book] is available to help acquire such background familiarity.\nThis book also does not serve as a reference to the [standard library] included in the language distribution.\nThose libraries are documented separately by extracting documentation attributes from their source code.\nMany 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.\nSimilarly, this book does not usually document the specifics of `rustc` as a tool or of Cargo.\n`rustc` has its own book.\nCargo has a book that contains a reference.\nThere are a few pages such as [linkage] that still describe how `rustc` works.\nThis book also only serves as a reference to what is available in stable Rust.\nFor unstable features being worked on, see the [Unstable Book].\nRust compilers, including `rustc`, will perform optimizations.\nThe reference does not specify what optimizations are allowed or disallowed.\nInstead, think of the compiled program as a black box.\nYou can only probe by running it, feeding it input and observing its output.\nEverything that happens that way must conform to what the reference says.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Introduction", "heading_path": ["Introduction", "What The Reference is not"], "path": "introduction.md", "url": "https://doc.rust-lang.org/reference/introduction.html#what-the-reference-is-not", "has_code": false, "code_tags": []}} {"id": "reference/introduction.md#how-to-use-this-book-3", "text": "The Rust Reference › Introduction › How to use this book\n\nThis book does not assume you are reading this book sequentially.\nEach 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.\nThere are two main ways to read this document.\nThe first is to answer a specific question.\nIf you know which chapter answers that question, you can jump to that chapter in the table of contents.\nOtherwise, you can press `s` or click the magnifying glass on the top bar to search for keywords related to your question.\nFor example, say you wanted to know when a temporary value created in a let statement is dropped.\nIf you didn't already know that the [lifetime of temporaries] is defined in the [expressions chapter], you could search \"temporary let\" and the first search result will take you to that section.\nThe second is to generally improve your knowledge of a facet of the language.\nIn that case, just browse the table of contents until you see something you want to know more about, and just start reading.\nIf a link looks interesting, click it, and read about that section.\nThat said, there is no wrong way to read this book. Read it however you feel helps you best.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Introduction", "heading_path": ["Introduction", "How to use this book"], "path": "introduction.md", "url": "https://doc.rust-lang.org/reference/introduction.html#how-to-use-this-book", "has_code": false, "code_tags": []}} {"id": "reference/introduction.md#conventions-4", "text": "The Rust Reference › Introduction › How to use this book › Conventions\n\nLike all technical books, this book has certain conventions in how it displays information.\nThese conventions are documented here.\n* Statements that define a term contain that term in *italics*.\n Whenever that term is used outside of that chapter, it is usually a link to the section that has this definition.\n An *example term* is an example of a term being defined.\n* The main text describes the latest stable edition. Differences to previous editions are separated in edition blocks:\n[!EDITION-2018]\nBefore the 2018 edition, the behavior was this. As of the 2018 edition, the behavior is that.\n* Notes that contain useful information about the state of the book or point out useful, but mostly out of scope, information are in note blocks.\nThis is an example note.\n* Example blocks show an example that demonstrates some rule or points out some interesting aspect. Some examples may have hidden lines which can be viewed by clicking the eye icon that appears when hovering or tapping the example.\nThis is a code example.\n```rust\nprintln!(\"hello world\");\n```\n* Warnings that show unsound behavior in the language or possibly confusing interactions of language features are in a special warning box.\nThis is an example warning.\n* Code snippets inline in the text are inside `` tags.\n Longer code examples are in a syntax highlighted box that has controls for copying, executing, and showing hidden lines in the top right corner.\n```rust\n # // This is a hidden line.\n fn main() {\n println!(\"This is a code example\");\n }\n```\n All examples are written for the latest edition unless otherwise stated.\n* The grammar and lexical productions are described in the [Notation] chapter.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Introduction", "heading_path": ["Introduction", "How to use this book", "Conventions"], "path": "introduction.md", "url": "https://doc.rust-lang.org/reference/introduction.html#conventions", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/introduction.md#conventions-5", "text": "The Rust Reference › Introduction › How to use this book › Conventions\n\n* Rule identifiers appear before each language rule enclosed in square brackets. These identifiers provide a way to refer to and link to a specific rule in the language (e.g.). The rule identifier uses periods to separate sections from most general to most specific ([destructors.scope.nesting.function-body] for example). On narrow screens, the rule name will collapse to display `[*]`.\n The rule name can be clicked to link to that rule.\nThe organization of the rules is currently in flux. For the time being, these identifier names are not stable between releases, and links to these rules may fail if they are changed. We intend to stabilize these once the organization has settled so that links to the rule names will not break between releases.\n* Rules that have associated tests will include a `Tests` link below them (on narrow screens, the link is `[T]`). Clicking the link will pop up a list of tests, which can be clicked to view the test. For example, see [input.encoding.utf8].\n Linking rules to tests is an ongoing effort. See the Test summary chapter for an overview.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Introduction", "heading_path": ["Introduction", "How to use this book", "Conventions"], "path": "introduction.md", "url": "https://doc.rust-lang.org/reference/introduction.html#conventions", "has_code": false, "code_tags": []}} {"id": "reference/introduction.md#contributing-6", "text": "The Rust Reference › Introduction › Contributing\n\nWe welcome contributions of all kinds.\nYou can contribute to this book by opening an issue or sending a pull request to [the Rust Reference repository].\nIf 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] or ask about it in the `t-lang/doc` stream on [Zulip].\nKnowing what people use this book for the most helps direct our attention to making those sections the best that they can be.\nAnd of course, if you see anything that is wrong or is non-normative but not specifically called out as such, please also [file an issue].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Introduction", "heading_path": ["Introduction", "Contributing"], "path": "introduction.md", "url": "https://doc.rust-lang.org/reference/introduction.html#contributing", "has_code": false, "code_tags": []}} {"id": "reference/notation.md#grammar-0", "text": "The Rust Reference › Notation › Grammar\n\nThe following notations are used by the *Lexer* and *Syntax* grammar snippets:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Notation", "heading_path": ["Notation", "Grammar"], "path": "notation.md", "url": "https://doc.rust-lang.org/reference/notation.html#grammar", "has_code": false, "code_tags": []}} {"id": "reference/notation.md#grammar-1", "text": "The Rust Reference › Notation › Grammar\n\n| Notation | Examples | Meaning |\n|-------------------|-------------------------------|-------------------------------------------|\n| CAPITAL | KW_IF, INTEGER_LITERAL | A token produced by the lexer |\n| _ItalicCamelCase_ | _LetStatement_, _Item_ | A syntactical production |\n| `string` | `x`, `while`, `*` | The exact character(s) |\n| x? | `pub`? | An optional item |\n| x\\* | _OuterAttribute_\\* | 0 or more of x |\n| x+ | _MacroMatch_+ | 1 or more of x |\n| xa..b | HEX_DIGIT1..6 | a to b repetitions of x, exclusive of b |\n| xa..=b | HEX_DIGIT1..=5 | a to b repetitions of x, inclusive of b |\n| xn:a..=b | `#`n:1..=255 | a to b repetitions of x (inclusive of b), with the count bound to the name n |\n| xn | `#`n | x repeated the number of times bound to n by a previous labeled repetition |\n| Rule1 Rule2 | `fn` _Name_ _Parameters_ | Sequence of rules in order |\n| \\| | `u8` \\| `u16`, Block \\| Item | Either one or another |\n| ! | !COMMENT | Matches if the expression does not follow, without consuming any input |\n| \\[ ] | \\[`b` `B`] | Any of the characters listed |\n| \\[ - ] | \\[`a`-`z`] | Any of the characters in the range |\n| ~\\[ ] | ~\\[`b` `B`] | Any characters, except those listed |\n| ~`string` | ~`\\n`, ~`*/` | Any characters, except this sequence |\n| ( ) | (`,` _Parameter_)? | Groups items |\n| ^ | `b'` ^ ASCII_FOR_CHAR | The rest of the sequence must match or parsing fails unconditionally ([hard cut operator]) |\n| U+xxxx..xxxxxx | U+0060 | A single Unicode character |\n| \\ | \\ | An English description of what should be matched |\n| Rule suffix | IDENTIFIER_OR_KEYWORD _except `crate`_ | A modification to the previous rule |\n| // Comment. | // Single line comment. | A comment extending to the end of the line. |", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Notation", "heading_path": ["Notation", "Grammar"], "path": "notation.md", "url": "https://doc.rust-lang.org/reference/notation.html#grammar", "has_code": false, "code_tags": []}} {"id": "reference/notation.md#grammar-2", "text": "The Rust Reference › Notation › Grammar\n\nSequences have a higher precedence than `|` alternation.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Notation", "heading_path": ["Notation", "Grammar"], "path": "notation.md", "url": "https://doc.rust-lang.org/reference/notation.html#grammar", "has_code": false, "code_tags": []}} {"id": "reference/notation.md#the-hard-cut-operator-3", "text": "The Rust Reference › Notation › Grammar › The hard cut operator\n\nThe grammar uses ordered alternation: the parser tries alternatives left to right and takes the first that matches. If an alternative fails partway through a sequence, the parser normally backtracks and tries the next alternative. The cut operator (`^`) prevents this. Once every expression to the left of `^` in a sequence has matched, the rest of the sequence must match or parsing fails unconditionally.\nMizushima et al. introduced cut operators to parsing expression grammars. In the PEG literature, a *soft cut* prevents backtracking only within the immediately enclosing ordered choice --- outer choices can still recover. A *hard cut* prevents all backtracking past the cut point; failure is definitive. The `^` used in this grammar is a hard cut.\nThe hard cut operator is necessary because some tokens in Rust begin with a prefix that is itself a valid token. For example, `c\"` begins a C string literal, but `c` alone is a valid identifier. Without the cut, if `c\"\\0\"` failed to lex as a C string literal (because null bytes are not allowed in C strings), the parser could backtrack and lex it as two tokens: the identifier `c` and the string literal `\"\\0\"`. The [cut after `c\"`] prevents this --- once the opening delimiter is recognized, the parser cannot go back. The same reasoning applies to [byte literals], [byte string literals], [raw string literals], and other literals with prefixes that are themselves valid tokens.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Notation", "heading_path": ["Notation", "Grammar", "The hard cut operator"], "path": "notation.md", "url": "https://doc.rust-lang.org/reference/notation.html#the-hard-cut-operator", "has_code": false, "code_tags": []}} {"id": "reference/notation.md#string-table-productions-4", "text": "The Rust Reference › Notation › Grammar › String table productions\n\nSome rules in the grammar — notably [unary operators], [binary\noperators], and [keywords] — are given in a simplified form: as a listing\nof printable strings. These cases form a subset of the rules regarding the\ntoken rule, and are assumed to be the result of a lexical-analysis\nphase feeding the parser, driven by a DFA, operating over the disjunction of all such string table\nentries.\nWhen such a string in `monospace` font occurs inside the grammar,\nit is an implicit reference to a single member of such a string table\nproduction. See [tokens] for more information.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Notation", "heading_path": ["Notation", "Grammar", "String table productions"], "path": "notation.md", "url": "https://doc.rust-lang.org/reference/notation.html#string-table-productions", "has_code": false, "code_tags": []}} {"id": "reference/notation.md#grammar-visualizations-5", "text": "The Rust Reference › Notation › Grammar › Grammar visualizations\n\nBelow each grammar block is a button to toggle the display of a [syntax diagram]. A square element is a non-terminal rule, and a rounded rectangle is a terminal.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Notation", "heading_path": ["Notation", "Grammar", "Grammar visualizations"], "path": "notation.md", "url": "https://doc.rust-lang.org/reference/notation.html#grammar-visualizations", "has_code": false, "code_tags": []}} {"id": "reference/input-format.md#input-format-0", "text": "The Rust Reference › Input format\n\n```grammar,lexer\nCHAR -> [U+0000-U+D7FF U+E000-U+10FFFF] // a Unicode scalar value\n\nASCII -> [U+0000-U+007F]\n\nNUL -> U+0000\n\nEOF -> !CHAR // End of file or input\n```\nThis chapter describes how a source file is interpreted as a sequence of tokens.\nSee [Crates and source files] for a description of how programs are organised into files.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Input format", "heading_path": ["Input format"], "path": "input-format.md", "url": "https://doc.rust-lang.org/reference/input-format.html#input-format", "has_code": true, "code_tags": ["grammar,lexer"]}} {"id": "reference/input-format.md#source-encoding-1", "text": "The Rust Reference › Input format › Source encoding\n\nEach source file is interpreted as a sequence of Unicode characters encoded in UTF-8.\nIt is an error if the file is not valid UTF-8.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Input format", "heading_path": ["Input format", "Source encoding"], "path": "input-format.md", "url": "https://doc.rust-lang.org/reference/input-format.html#source-encoding", "has_code": false, "code_tags": []}} {"id": "reference/input-format.md#byte-order-mark-removal-2", "text": "The Rust Reference › Input format › Byte order mark removal\n\nIf the first character in the sequence is `U+FEFF` ([BYTE ORDER MARK]), it is removed.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Input format", "heading_path": ["Input format", "Byte order mark removal"], "path": "input-format.md", "url": "https://doc.rust-lang.org/reference/input-format.html#byte-order-mark-removal", "has_code": false, "code_tags": []}} {"id": "reference/input-format.md#crlf-normalization-3", "text": "The Rust Reference › Input format › CRLF normalization\n\nEach pair of characters `U+000D` (CR) immediately followed by `U+000A` (LF) is replaced by a single `U+000A` (LF). This happens once, not repeatedly, so after the normalization, there can still exist `U+000D` (CR) immediately followed by `U+000A` (LF) in the input (e.g. if the raw input contained \"CR CR LF LF\").\nOther occurrences of the character `U+000D` (CR) are left in place (they are treated as [whitespace]).", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Input format", "heading_path": ["Input format", "CRLF normalization"], "path": "input-format.md", "url": "https://doc.rust-lang.org/reference/input-format.html#crlf-normalization", "has_code": false, "code_tags": []}} {"id": "reference/input-format.md#shebang-removal-4", "text": "The Rust Reference › Input format › Shebang removal\n\nIf a [shebang] is present, it is removed from the input sequence (and is therefore ignored).", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Input format", "heading_path": ["Input format", "Shebang removal"], "path": "input-format.md", "url": "https://doc.rust-lang.org/reference/input-format.html#shebang-removal", "has_code": false, "code_tags": []}} {"id": "reference/input-format.md#tokenization-5", "text": "The Rust Reference › Input format › Tokenization\n\nThe resulting sequence of characters is then converted into tokens as described in the remainder of this chapter.\nThe standard library [`include!`] macro applies the following transformations to the file it reads:\n- Byte order mark removal.\n- CRLF normalization.\n- Shebang removal when invoked in an item context (as opposed to expression or statement contexts).\nThe [`include_str!`] and [`include_bytes!`] macros do not apply these transformations.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Input format", "heading_path": ["Input format", "Tokenization"], "path": "input-format.md", "url": "https://doc.rust-lang.org/reference/input-format.html#tokenization", "has_code": false, "code_tags": []}} {"id": "reference/shebang.md#shebang-0", "text": "The Rust Reference › Shebang\n\nA *[shebang]* is an optional line that is typically used in Unix-like systems to specify an interpreter for executing the file.\n```rust,ignore\n#!/usr/bin/env rustx\n\nfn main() {\n println!(\"Hello!\");\n}\n```\n```grammar,lexer\n@root SHEBANG ->\n `#!` !((WHITESPACE | LINE_COMMENT | BLOCK_COMMENT)* `[`)\n ~LF* (LF | EOF)\n```\nThe shebang starts with the characters `#!` and extends through the first `U+000A` (LF) or through EOF if no LF is present. If the `#!` characters are followed by `[` (ignoring any intervening [comments] or [whitespace]), the line is not considered a shebang (to avoid ambiguity with an [inner attribute]).\nThe shebang may appear immediately at the start of the file or after the optional [byte order mark].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Shebang", "heading_path": ["Shebang"], "path": "shebang.md", "url": "https://doc.rust-lang.org/reference/shebang.html#shebang", "has_code": true, "code_tags": ["grammar,lexer", "rust,ignore"]}} {"id": "reference/keywords.md#keywords-0", "text": "The Rust Reference › Keywords\n\nRust divides keywords into three categories:\n* strict\n* reserved\n* weak", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Keywords", "heading_path": ["Keywords"], "path": "keywords.md", "url": "https://doc.rust-lang.org/reference/keywords.html#keywords", "has_code": false, "code_tags": []}} {"id": "reference/keywords.md#strict-keywords-1", "text": "The Rust Reference › Keywords › Strict keywords\n\nThese keywords can only be used in their correct contexts. They cannot be used as the names of:\n* [Items]\n* [Variables] and function parameters\n* Fields and [variants]\n* [Type parameters]\n* Lifetime parameters or [loop labels]\n* [Macros] or [attributes]\n* [Macro placeholders]\n* [Crates]\nThe following keywords are in all editions:\n- `_`\n- `as`\n- `async`\n- `await`\n- `break`\n- `const`\n- `continue`\n- `crate`\n- `dyn`\n- `else`\n- `enum`\n- `extern`\n- `false`\n- `fn`\n- `for`\n- `if`\n- `impl`\n- `in`\n- `let`\n- `loop`\n- `match`\n- `mod`\n- `move`\n- `mut`\n- `pub`\n- `ref`\n- `return`\n- `self`\n- `Self`\n- `static`\n- `struct`\n- `super`\n- `trait`\n- `true`\n- `type`\n- `unsafe`\n- `use`\n- `where`\n- `while`\n[!EDITION-2018]\nThe following keywords were added in the 2018 edition:\n- `async`\n- `await`\n- `dyn`", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Keywords", "heading_path": ["Keywords", "Strict keywords"], "path": "keywords.md", "url": "https://doc.rust-lang.org/reference/keywords.html#strict-keywords", "has_code": false, "code_tags": []}} {"id": "reference/keywords.md#reserved-keywords-2", "text": "The Rust Reference › Keywords › Reserved keywords\n\nThese 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.\n- `abstract`\n- `become`\n- `box`\n- `do`\n- `final`\n- `gen`\n- `macro`\n- `override`\n- `priv`\n- `try`\n- `typeof`\n- `unsized`\n- `virtual`\n- `yield`\n[!EDITION-2018]\nThe `try` keyword was added as a reserved keyword in the 2018 edition.\n[!EDITION-2024]\nThe `gen` keyword was added as a reserved keyword in the 2024 edition.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Keywords", "heading_path": ["Keywords", "Reserved keywords"], "path": "keywords.md", "url": "https://doc.rust-lang.org/reference/keywords.html#reserved-keywords", "has_code": false, "code_tags": []}} {"id": "reference/keywords.md#weak-keywords-3", "text": "The Rust Reference › Keywords › Weak keywords\n\nThese keywords have special meaning only in certain contexts. For example, it is possible to declare a variable or method with the name `union`.\n- `'static`\n- `macro_rules`\n- `raw`\n- `safe`\n- `union`\n* `macro_rules` is used to create custom [macros].\n* `union` is used to declare a [union] and is only a keyword when used in a union declaration.\n* `'static` is used for the static lifetime and cannot be used as a [generic lifetime parameter] or [loop label]\n```compile_fail\n // error[E0262]: invalid lifetime parameter name: `'static`\n fn invalid_lifetime_parameter<'static>(s: &'static str) -> &'static str { s }\n```\n* `safe` is used for functions and statics, which has meaning in [external blocks].\n* `raw` is used for [raw borrow operators], and is only a keyword when matching a raw borrow operator form (such as `&raw const expr` or `&raw mut expr`).\n[!EDITION-2018]\nIn the 2015 edition, [`dyn`] is a keyword when used in a type position followed by a path that does not start with `::` or `<`, a lifetime, a question mark, a `for` keyword or an opening parenthesis.\nBeginning in the 2018 edition, `dyn` has been promoted to a strict keyword.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Keywords", "heading_path": ["Keywords", "Weak keywords"], "path": "keywords.md", "url": "https://doc.rust-lang.org/reference/keywords.html#weak-keywords", "has_code": true, "code_tags": ["compile_fail"]}} {"id": "reference/identifiers.md#identifiers-0", "text": "The Rust Reference › Identifiers\n\n```grammar,lexer\nIDENTIFIER_OR_KEYWORD -> ( XID_Start | `_` ) XID_Continue*\n\nXID_Start -> <`XID_Start` defined by Unicode>\n\nXID_Continue -> <`XID_Continue` defined by Unicode>\n\nRAW_IDENTIFIER -> `r#` IDENTIFIER_OR_KEYWORD\n\nNON_KEYWORD_IDENTIFIER -> IDENTIFIER_OR_KEYWORD _except a strict or reserved keyword_\n\nIDENTIFIER -> NON_KEYWORD_IDENTIFIER | RAW_IDENTIFIER\n\nRESERVED_RAW_IDENTIFIER ->\n `r#` (`_` | `crate` | `self` | `Self` | `super`) !XID_Continue\n```\nIdentifiers follow the specification in Unicode Standard Annex #31 for Unicode version 17.0, with the additions described below. Some examples of identifiers:\n* `foo`\n* `_identifier`\n* `r#true`\n* `Москва`\n* `東京`\nThe profile used from UAX #31 is:\n* Start := [`XID_Start`], plus the underscore character (U+005F)\n* Continue := [`XID_Continue`]\n* Medial := empty\nIdentifiers starting with an underscore are typically used to indicate an identifier that is intentionally unused, and will silence the unused warning in `rustc`.\nIdentifiers may not be a [strict] or [reserved] keyword without the `r#` prefix described below in raw identifiers.\nZero width non-joiner (ZWNJ U+200C) and zero width joiner (ZWJ U+200D) characters are not allowed in identifiers.\nIdentifiers are restricted to the ASCII subset of [`XID_Start`] and [`XID_Continue`] in the following situations:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Identifiers", "heading_path": ["Identifiers"], "path": "identifiers.md", "url": "https://doc.rust-lang.org/reference/identifiers.html#identifiers", "has_code": true, "code_tags": ["grammar,lexer"]}} {"id": "reference/identifiers.md#identifiers-1", "text": "The Rust Reference › Identifiers\n\n* [`extern crate`] declarations (except the [AsClause] identifier)\n* External crate names referenced in a [path]\n* [Module] names loaded from the filesystem without a [`path` attribute]\n* [`no_mangle`] attributed items\n* Item names in [external blocks]", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Identifiers", "heading_path": ["Identifiers"], "path": "identifiers.md", "url": "https://doc.rust-lang.org/reference/identifiers.html#identifiers", "has_code": false, "code_tags": []}} {"id": "reference/identifiers.md#normalization-2", "text": "The Rust Reference › Identifiers › Normalization\n\nIdentifiers are normalized using Normalization Form C (NFC) as defined in Unicode Standard Annex #15. Two identifiers are equal if their NFC forms are equal.\nProcedural and declarative macros receive normalized identifiers in their input.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Identifiers", "heading_path": ["Identifiers", "Normalization"], "path": "identifiers.md", "url": "https://doc.rust-lang.org/reference/identifiers.html#normalization", "has_code": false, "code_tags": []}} {"id": "reference/identifiers.md#raw-identifiers-3", "text": "The Rust Reference › Identifiers › Raw identifiers\n\nA 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.)\nUnlike a normal identifier, a raw identifier may be any strict or reserved keyword except the ones listed above for `RAW_IDENTIFIER`.\nIt is an error to use the [RESERVED_RAW_IDENTIFIER] token.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Identifiers", "heading_path": ["Identifiers", "Raw identifiers"], "path": "identifiers.md", "url": "https://doc.rust-lang.org/reference/identifiers.html#raw-identifiers", "has_code": false, "code_tags": []}} {"id": "reference/comments.md#comments-0", "text": "The Rust Reference › Comments\n\n```grammar,lexer\n@root COMMENT ->\n LINE_COMMENT\n | INNER_LINE_DOC\n | OUTER_LINE_DOC\n | INNER_BLOCK_DOC\n | OUTER_BLOCK_DOC\n | BLOCK_COMMENT\n\nLINE_COMMENT ->\n `//` (~[`/` `!` LF] | `//`) ~LF*\n | `//` EOF\n | `//` _immediately followed by LF_\n\nBLOCK_COMMENT ->\n `/*` ^\n ( BLOCK_COMMENT_OR_DOC | (!`*/` CHAR) )*\n `*/`\n\nINNER_LINE_DOC ->\n `//!` ^ LINE_DOC_COMMENT_CONTENT (LF | EOF)\n\nLINE_DOC_COMMENT_CONTENT -> (!CR ~LF)*\n\nINNER_BLOCK_DOC ->\n `/*!` ^ ( BLOCK_COMMENT_OR_DOC | BLOCK_CHAR )* `*/`\n\nOUTER_LINE_DOC ->\n `///` ^ LINE_DOC_COMMENT_CONTENT (LF | EOF)\n\nOUTER_BLOCK_DOC ->\n `/**` ![`*` `/`]\n ^\n ( ~`*` | BLOCK_COMMENT_OR_DOC )\n ( BLOCK_COMMENT_OR_DOC | BLOCK_CHAR )*\n `*/`\n\nBLOCK_CHAR -> (!(`*/` | CR) CHAR)\n\nBLOCK_COMMENT_OR_DOC ->\n INNER_BLOCK_DOC\n | OUTER_BLOCK_DOC\n | BLOCK_COMMENT\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Comments", "heading_path": ["Comments"], "path": "comments.md", "url": "https://doc.rust-lang.org/reference/comments.html#comments", "has_code": true, "code_tags": ["grammar,lexer"]}} {"id": "reference/comments.md#non-doc-comments-1", "text": "The Rust Reference › Comments › Non-doc comments\n\nComments follow the general C++ style of line (`//`) and block (`/* ... */`) comment forms. Nested block comments are supported.\nNon-doc comments are interpreted as a form of whitespace.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Comments", "heading_path": ["Comments", "Non-doc comments"], "path": "comments.md", "url": "https://doc.rust-lang.org/reference/comments.html#non-doc-comments", "has_code": false, "code_tags": []}} {"id": "reference/comments.md#doc-comments-2", "text": "The Rust Reference › Comments › Doc comments\n\nLine doc comments beginning with exactly _three_ slashes (`///`), and block doc comments (`/** ... */`), both outer doc comments, are interpreted as a special syntax for [`doc` attributes].\nThat 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 \"]`. They must therefore appear before something that accepts an outer attribute.\nLine comments beginning with `//!` and block comments `/*! ... */` are doc comments that apply to the parent of the comment, rather than the item that follows.\nThat 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.\nThe character `U+000D` (CR) is not allowed in doc comments.\nIt is conventional for doc comments to contain Markdown, as expected by `rustdoc`. However, the comment syntax does not respect any internal Markdown. ``/** `glob = \"*/*.rs\";` */`` terminates the comment at the first `*/`, and the remaining code would cause a syntax error. This slightly limits the content of block doc comments compared to line doc comments.\nThe sequence `U+000D` (CR) immediately followed by `U+000A` (LF) would have been previously transformed into a single `U+000A` (LF).", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Comments", "heading_path": ["Comments", "Doc comments"], "path": "comments.md", "url": "https://doc.rust-lang.org/reference/comments.html#doc-comments", "has_code": false, "code_tags": []}} {"id": "reference/comments.md#examples-3", "text": "The Rust Reference › Comments › Examples\n\n```rust\n//! A doc comment that applies to the implicit anonymous module of this crate\n\npub mod outer_module {\n\n //! - Inner line doc\n //!! - Still an inner line doc (but with a bang at the beginning)\n\n /*! - Inner block doc */\n /*!! - Still an inner block doc (but with a bang at the beginning) */\n\n // - Only a comment\n /// - Outer line doc (exactly 3 slashes)\n //// - Only a comment\n\n /* - Only a comment */\n /** - Outer block doc (exactly) 2 asterisks */\n /*** - Only a comment */\n\n pub mod inner_module {}\n\n pub mod nested_comments {\n /* In Rust /* we can /* nest comments */ */ */\n\n // All three types of block comments can contain or be nested inside\n // any other type:\n\n /* /* */ /** */ /*! */ */\n /*! /* */ /** */ /*! */ */\n /** /* */ /** */ /*! */ */\n pub mod dummy_item {}\n }\n\n pub mod degenerate_cases {\n // empty inner line doc\n //!\n\n // empty inner block doc\n /*!*/\n\n // empty line comment\n //\n\n // empty outer line doc\n ///\n\n // empty block comment\n /**/\n\n pub mod dummy_item {}\n\n // empty 2-asterisk block isn't a doc block, it is a block comment\n /***/\n\n }\n\n /* The next one isn't allowed because outer doc comments\n require an item that will receive the doc */\n\n /// Where is my item?\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Comments", "heading_path": ["Comments", "Examples"], "path": "comments.md", "url": "https://doc.rust-lang.org/reference/comments.html#examples", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/whitespace.md#whitespace-0", "text": "The Rust Reference › Whitespace\n\n```grammar,lexer\nWHITESPACE ->\n U+0009 // Horizontal tab, `'\\t'`\n | U+000A // Line feed, `'\\n'`\n | U+000B // Vertical tab\n | U+000C // Form feed\n | U+000D // Carriage return, `'\\r'`\n | U+0020 // Space, `' '`\n | U+0085 // Next line\n | U+200E // Left-to-right mark\n | U+200F // Right-to-left mark\n | U+2028 // Line separator\n | U+2029 // Paragraph separator\n\nTAB -> U+0009 // Horizontal tab, `'\\t'`\n\nLF -> U+000A // Line feed, `'\\n'`\n\nCR -> U+000D // Carriage return, `'\\r'`\n```\nWhitespace is any non-empty string containing only characters that have the [`Pattern_White_Space`] Unicode property.\nRust is a \"free-form\" language, meaning that all forms of whitespace serve only to separate _tokens_ in the grammar, and have no semantic significance.\nA Rust program has identical meaning if each whitespace element is replaced with any other legal whitespace element, such as a single space character.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Whitespace", "heading_path": ["Whitespace"], "path": "whitespace.md", "url": "https://doc.rust-lang.org/reference/whitespace.html#whitespace", "has_code": true, "code_tags": ["grammar,lexer"]}} {"id": "reference/tokens.md#tokens-0", "text": "The Rust Reference › Tokens\n\n```grammar,lexer\nToken ->\n RESERVED_TOKEN\n | RAW_IDENTIFIER\n | CHAR_LITERAL\n | STRING_LITERAL\n | RAW_STRING_LITERAL\n | BYTE_LITERAL\n | BYTE_STRING_LITERAL\n | RAW_BYTE_STRING_LITERAL\n | C_STRING_LITERAL\n | RAW_C_STRING_LITERAL\n | FLOAT_LITERAL\n | INTEGER_LITERAL\n | LIFETIME_TOKEN\n | PUNCTUATION\n | IDENTIFIER_OR_KEYWORD\n```\nTokens 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:\n* [Keywords]\n* Identifiers\n* Literals\n* Lifetimes\n* Punctuation\n* Delimiters\nWithin this documentation's grammar, \"simple\" tokens are given in [string table production] form, and appear in `monospace` font.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tokens", "heading_path": ["Tokens"], "path": "tokens.md", "url": "https://doc.rust-lang.org/reference/tokens.html#tokens", "has_code": true, "code_tags": ["grammar,lexer"]}} {"id": "reference/tokens.md#literals-1", "text": "The Rust Reference › Tokens › Literals\n\nLiterals are tokens used in [literal expressions].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tokens", "heading_path": ["Tokens", "Literals"], "path": "tokens.md", "url": "https://doc.rust-lang.org/reference/tokens.html#literals", "has_code": false, "code_tags": []}} {"id": "reference/tokens.md#characters-and-strings-2", "text": "The Rust Reference › Tokens › Literals › Examples › Characters and strings\n\n| | Example | `#` sets[^nsets] | Characters | Escapes |\n|----------------------------------------------|-----------------|------------|-------------|---------------------|\n| Character | `'H'` | 0 | All Unicode | Quote & ASCII & Unicode |\n| String | `\"hello\"` | 0 | All Unicode | Quote & ASCII & Unicode |\n| Raw string | `r#\"hello\"#` | <256 | All Unicode | `N/A` |\n| Byte | `b'H'` | 0 | All ASCII | Quote & Byte |\n| Byte string | `b\"hello\"` | 0 | All ASCII | Quote & Byte |\n| Raw byte string | `br#\"hello\"#` | <256 | All ASCII | `N/A` |\n| C string | `c\"hello\"` | 0 | All Unicode | Quote & Byte & Unicode |\n| Raw C string | `cr#\"hello\"#` | <256 | All Unicode | `N/A` |", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tokens", "heading_path": ["Tokens", "Literals", "Examples", "Characters and strings"], "path": "tokens.md", "url": "https://doc.rust-lang.org/reference/tokens.html#characters-and-strings", "has_code": false, "code_tags": []}} {"id": "reference/tokens.md#suffixes-3", "text": "The Rust Reference › Tokens › Literals › Examples › Suffixes\n\n[^nsets]: The number of `#`s on each side of the same literal must be equivalent.\n| | Name |\n|---|------|\n| `\\x41` | 7-bit character code (exactly 2 hex digits, up to 0x7F) |\n| `\\n` | Newline |\n| `\\r` | Carriage return |\n| `\\t` | Tab |\n| `\\\\` | Backslash |\n| `\\0` | Null |\n| | Name |\n|---|------|\n| `\\x7F` | 8-bit character code (exactly 2 hex digits) |\n| `\\n` | Newline |\n| `\\r` | Carriage return |\n| `\\t` | Tab |\n| `\\\\` | Backslash |\n| `\\0` | Null |\n| | Name |\n|---|------|\n| `\\u{7FFF}` | 24-bit Unicode character code (up to 6 hex digits) |\n| | Name |\n|---|------|\n| `\\'` | Single quote |\n| `\\\"` | Double quote |\n| Number literals[^nl] | Example | Exponentiation |\n|----------------------------------------|---------|----------------|\n| Decimal integer | `98_222` | `N/A` |\n| Hex integer | `0xff` | `N/A` |\n| Octal integer | `0o77` | `N/A` |\n| Binary integer | `0b1111_0000` | `N/A` |\n| Floating-point | `123.0E+77` | `Optional` |\n[^nl]: All number literals allow `_` as a visual separator: `1_234.0E+18f64`", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tokens", "heading_path": ["Tokens", "Literals", "Examples", "Suffixes"], "path": "tokens.md", "url": "https://doc.rust-lang.org/reference/tokens.html#suffixes", "has_code": false, "code_tags": []}} {"id": "reference/tokens.md#suffixes-4", "text": "The Rust Reference › Tokens › Literals › Examples › Suffixes\n\nA suffix is a sequence of characters following (without intervening whitespace) the primary part of a literal of the same form as a non-raw identifier or keyword.\n```grammar,lexer\nSUFFIX ->\n `_` ^ XID_Continue+\n | XID_Start XID_Continue*\n```\nAny kind of literal (string, integer, etc.) with any suffix is valid as a token.\nA 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.\n```rust\nmacro_rules! blackhole { ($tt:tt) => () }\nmacro_rules! blackhole_lit { ($l:literal) => () }\n\nblackhole!(\"string\"suffix); // OK\nblackhole_lit!(1suffix); // OK\n```\nHowever, 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.\n| Integer | Floating-point |\n|---------|----------------|\n| `u8`, `i8`, `u16`, `i16`, `u32`, `i32`, `u64`, `i64`, `u128`, `i128`, `usize`, `isize` | `f32`, `f64` |", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tokens", "heading_path": ["Tokens", "Literals", "Examples", "Suffixes"], "path": "tokens.md", "url": "https://doc.rust-lang.org/reference/tokens.html#suffixes", "has_code": true, "code_tags": ["grammar,lexer", "rust"]}} {"id": "reference/tokens.md#string-literals-5", "text": "The Rust Reference › Tokens › Literals › Character and string literals › String literals\n\n```grammar,lexer\nCHAR_LITERAL ->\n `'`\n ( ~[`'` `\\` LF CR TAB] | QUOTE_ESCAPE | ASCII_ESCAPE | UNICODE_ESCAPE )\n `'` SUFFIX?\n\nQUOTE_ESCAPE -> `\\'` | `\\\"`\n\nASCII_ESCAPE ->\n `\\x` OCT_DIGIT HEX_DIGIT\n | `\\n` | `\\r` | `\\t` | `\\\\` | `\\0`\n\nUNICODE_ESCAPE ->\n `\\u{` ( HEX_DIGIT `_`* ){1..=6} _valid hex char value_ `}`[^valid-hex-char]\n```\n[^valid-hex-char]: See [lex.token.literal.char-escape.unicode].\nA _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 (`\\`).\n```grammar,lexer\nSTRING_LITERAL ->\n `\"` (\n ~[`\"` `\\` CR]\n | QUOTE_ESCAPE\n | ASCII_ESCAPE\n | UNICODE_ESCAPE\n | STRING_CONTINUE\n )* `\"` SUFFIX?\n\nSTRING_CONTINUE -> `\\` LF\n```\nA _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 (`\\`).", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tokens", "heading_path": ["Tokens", "Literals", "Character and string literals", "String literals"], "path": "tokens.md", "url": "https://doc.rust-lang.org/reference/tokens.html#string-literals", "has_code": true, "code_tags": ["grammar,lexer"]}} {"id": "reference/tokens.md#character-escapes-6", "text": "The Rust Reference › Tokens › Literals › Character and string literals › Character escapes\n\nLine-breaks, represented by the character `U+000A` (LF), are allowed in string literals. The character `U+000D` (CR) may not appear in a string literal. When an unescaped `U+005C` character (`\\`) occurs immediately before a line break, the line break does not appear in the string represented by the token. See [String continuation escapes] for details.\nSome 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:\n* 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.\n* 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. The value must be a valid Unicode scalar value.\n* 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tokens", "heading_path": ["Tokens", "Literals", "Character and string literals", "Character escapes"], "path": "tokens.md", "url": "https://doc.rust-lang.org/reference/tokens.html#character-escapes", "has_code": false, "code_tags": []}} {"id": "reference/tokens.md#raw-string-literals-7", "text": "The Rust Reference › Tokens › Literals › Character and string literals › Raw string literals\n\n* The _null escape_ is the character `U+0030` (`0`) and denotes the Unicode value `U+0000` (NUL).\n* The _backslash escape_ is the character `U+005C` (`\\`) which must be escaped in order to denote itself.\n```grammar,lexer\nRAW_STRING_LITERAL ->\n `r` `\"` ^ RAW_STRING_CONTENT `\"` SUFFIX?\n | `r` `#`{n:1..=255} ^ `\"` RAW_STRING_CONTENT_HASHED `\"` `#`{n} SUFFIX?\n\nRAW_STRING_CONTENT -> (!`\"` ~CR )*\n\nRAW_STRING_CONTENT_HASHED -> (!(`\"` `#`{n}) ~CR )*\n```\nRaw 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.\nThe _raw string body_ can contain any sequence of Unicode characters other than `U+000D` (CR). It 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.\nAll 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.\nExamples for string literals:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tokens", "heading_path": ["Tokens", "Literals", "Character and string literals", "Raw string literals"], "path": "tokens.md", "url": "https://doc.rust-lang.org/reference/tokens.html#raw-string-literals", "has_code": true, "code_tags": ["grammar,lexer"]}} {"id": "reference/tokens.md#raw-string-literals-8", "text": "The Rust Reference › Tokens › Literals › Character and string literals › Raw string literals\n\n```rust\n\"foo\"; r\"foo\"; // foo\n\"\\\"foo\\\"\"; r#\"\"foo\"\"#; // \"foo\"\n\n\"foo #\\\"# bar\";\nr##\"foo #\"# bar\"##; // foo #\"# bar\n\n\"\\x52\"; \"R\"; r\"R\"; // R\n\"\\\\x52\"; r\"\\x52\"; // \\x52\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tokens", "heading_path": ["Tokens", "Literals", "Character and string literals", "Raw string literals"], "path": "tokens.md", "url": "https://doc.rust-lang.org/reference/tokens.html#raw-string-literals", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/tokens.md#byte-string-literals-9", "text": "The Rust Reference › Tokens › Literals › Byte and byte string literals › Byte string literals\n\n```grammar,lexer\nBYTE_LITERAL ->\n `b'` ^ ( ASCII_FOR_CHAR | BYTE_ESCAPE ) `'` SUFFIX?\n\nASCII_FOR_CHAR -> ![`'` `\\` LF CR TAB] ASCII\n\nBYTE_ESCAPE ->\n `\\x` HEX_DIGIT HEX_DIGIT\n | `\\n` | `\\r` | `\\t` | `\\\\` | `\\0` | `\\'` | `\\\"`\n```\nA _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_.\n```grammar,lexer\nBYTE_STRING_LITERAL ->\n `b\"` ^ ( ASCII_FOR_STRING | BYTE_ESCAPE | STRING_CONTINUE )* `\"` SUFFIX?\n\nASCII_FOR_STRING -> ![`\"` `\\` CR] ASCII\n```\nA 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tokens", "heading_path": ["Tokens", "Literals", "Byte and byte string literals", "Byte string literals"], "path": "tokens.md", "url": "https://doc.rust-lang.org/reference/tokens.html#byte-string-literals", "has_code": true, "code_tags": ["grammar,lexer"]}} {"id": "reference/tokens.md#raw-byte-string-literals-10", "text": "The Rust Reference › Tokens › Literals › Byte and byte string literals › Raw byte string literals\n\nLine-breaks, represented by the character `U+000A` (LF), are allowed in byte string literals. The character `U+000D` (CR) may not appear in a byte string literal. When an unescaped `U+005C` character (`\\`) occurs immediately before a line break, the line break does not appear in the string represented by the token. See [String continuation escapes] for details.\nSome 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:\n* 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.\n* 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.\n* The _null escape_ is the character `U+0030` (`0`) and denotes the byte value `0x00` (ASCII NUL).\n* The _backslash escape_ is the character `U+005C` (`\\`) which must be escaped in order to denote its ASCII encoding `0x5C`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tokens", "heading_path": ["Tokens", "Literals", "Byte and byte string literals", "Raw byte string literals"], "path": "tokens.md", "url": "https://doc.rust-lang.org/reference/tokens.html#raw-byte-string-literals", "has_code": false, "code_tags": []}} {"id": "reference/tokens.md#raw-byte-string-literals-11", "text": "The Rust Reference › Tokens › Literals › Byte and byte string literals › Raw byte string literals\n\n```grammar,lexer\nRAW_BYTE_STRING_LITERAL ->\n `br` `\"` ^ RAW_BYTE_STRING_CONTENT `\"` SUFFIX?\n | `br` `#`{n:1..=255} ^ `\"` RAW_BYTE_STRING_CONTENT_HASHED `\"` `#`{n} SUFFIX?\n\nRAW_BYTE_STRING_CONTENT -> (!`\"` ASCII_FOR_RAW )*\n\nRAW_BYTE_STRING_CONTENT_HASHED -> (!(`\"` `#`{n}) ASCII_FOR_RAW )*\n\nASCII_FOR_RAW -> !CR ASCII\n```\nRaw 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.\nThe _raw string body_ can contain any sequence of ASCII characters other than `U+000D` (CR). It 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.\nAll 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.\nExamples for byte string literals:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tokens", "heading_path": ["Tokens", "Literals", "Byte and byte string literals", "Raw byte string literals"], "path": "tokens.md", "url": "https://doc.rust-lang.org/reference/tokens.html#raw-byte-string-literals", "has_code": true, "code_tags": ["grammar,lexer"]}} {"id": "reference/tokens.md#raw-byte-string-literals-12", "text": "The Rust Reference › Tokens › Literals › Byte and byte string literals › Raw byte string literals\n\n```rust\nb\"foo\"; br\"foo\"; // foo\nb\"\\\"foo\\\"\"; br#\"\"foo\"\"#; // \"foo\"\n\nb\"foo #\\\"# bar\";\nbr##\"foo #\"# bar\"##; // foo #\"# bar\n\nb\"\\x52\"; b\"R\"; br\"R\"; // R\nb\"\\\\x52\"; br\"\\x52\"; // \\x52\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tokens", "heading_path": ["Tokens", "Literals", "Byte and byte string literals", "Raw byte string literals"], "path": "tokens.md", "url": "https://doc.rust-lang.org/reference/tokens.html#raw-byte-string-literals", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/tokens.md#c-string-literals-13", "text": "The Rust Reference › Tokens › Literals › C string and raw C string literals › C string literals\n\n```grammar,lexer\nC_STRING_LITERAL ->\n `c\"` ^ (\n ~[`\"` `\\` CR NUL]\n | BYTE_ESCAPE _except `\\0` or `\\x00`_\n | UNICODE_ESCAPE _except `\\u{0}`, `\\u{00}`, …, `\\u{000000}`_\n | STRING_CONTINUE\n )* `\"` SUFFIX?\n```\nA _C string literal_ is a sequence of Unicode characters and _escapes_, preceded by the characters `U+0063` (`c`) 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 C string literal can be a _raw C string literal_, defined below.\nC strings are implicitly terminated by byte `0x00`, so the C string literal `c\"\"` is equivalent to manually constructing a `&CStr` from the byte string literal `b\"\\x00\"`. Other than the implicit terminator, byte `0x00` is not permitted within a C string.\nLine-breaks, represented by the character `U+000A` (LF), are allowed in C string literals. The character `U+000D` (CR) may not appear in a C string literal. When an unescaped `U+005C` character (`\\`) occurs immediately before a line break, the line break does not appear in the string represented by the token. See [String continuation escapes] for details.\nSome additional _escapes_ are available in non-raw C string literals. An escape starts with a `U+005C` (`\\`) and continues with one of the following forms:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tokens", "heading_path": ["Tokens", "Literals", "C string and raw C string literals", "C string literals"], "path": "tokens.md", "url": "https://doc.rust-lang.org/reference/tokens.html#c-string-literals", "has_code": true, "code_tags": ["grammar,lexer"]}} {"id": "reference/tokens.md#raw-c-string-literals-14", "text": "The Rust Reference › Tokens › Literals › C string and raw C string literals › Raw C string literals\n\n* 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.\n* 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, encoded as UTF-8.\n* 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.\n* The _backslash escape_ is the character `U+005C` (`\\`) which must be escaped in order to denote its ASCII encoding `0x5C`.\nA C string represents bytes with no defined encoding, but a C string literal may contain Unicode characters above `U+007F`. Such characters will be replaced with the bytes of that character's UTF-8 representation.\nThe following C string literals are equivalent:\n```rust\nc\"æ\"; // LATIN SMALL LETTER AE (U+00E6)\nc\"\\u{00E6}\";\nc\"\\xC3\\xA6\";\n```\n[!EDITION-2021]\nC string literals are accepted in the 2021 edition or later. In earlier editions the token `c\"\"` is lexed as `c \"\"`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tokens", "heading_path": ["Tokens", "Literals", "C string and raw C string literals", "Raw C string literals"], "path": "tokens.md", "url": "https://doc.rust-lang.org/reference/tokens.html#raw-c-string-literals", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/tokens.md#raw-c-string-literals-15", "text": "The Rust Reference › Tokens › Literals › C string and raw C string literals › Raw C string literals\n\n```grammar,lexer\nRAW_C_STRING_LITERAL ->\n `cr` `\"` ^ RAW_C_STRING_CONTENT `\"` SUFFIX?\n | `cr` `#`{n:1..=255} ^ `\"` RAW_C_STRING_CONTENT_HASHED `\"` `#`{n} SUFFIX?\n\nRAW_C_STRING_CONTENT -> (!`\"` ~[CR NUL] )*\n\nRAW_C_STRING_CONTENT_HASHED -> (!(`\"` `#`{n}) ~[CR NUL] )*\n```\nRaw C string literals do not process any escapes. They start with the character `U+0063` (`c`), followed by `U+0072` (`r`), followed by fewer than 256 of the character `U+0023` (`#`), and a `U+0022` (double-quote) character.\nThe _raw C string body_ can contain any sequence of Unicode characters other than `U+0000` (NUL) and `U+000D` (CR). It 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.\nAll characters contained in the raw C string body represent themselves in UTF-8 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 C string literal) or `U+005C` (`\\`) do not have any special meaning.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tokens", "heading_path": ["Tokens", "Literals", "C string and raw C string literals", "Raw C string literals"], "path": "tokens.md", "url": "https://doc.rust-lang.org/reference/tokens.html#raw-c-string-literals", "has_code": true, "code_tags": ["grammar,lexer"]}} {"id": "reference/tokens.md#examples-for-c-string-and-raw-c-string-literals-16", "text": "The Rust Reference › Tokens › Literals › C string and raw C string literals › Examples for C string and raw C string literals\n\n[!EDITION-2021]\nRaw C string literals are accepted in the 2021 edition or later. In earlier editions the token `cr\"\"` is lexed as `cr \"\"`, and `cr#\"\"#` is lexed as `cr #\"\"#` (which is non-grammatical).\n```rust\nc\"foo\"; cr\"foo\"; // foo\nc\"\\\"foo\\\"\"; cr#\"\"foo\"\"#; // \"foo\"\n\nc\"foo #\\\"# bar\";\ncr##\"foo #\"# bar\"##; // foo #\"# bar\n\nc\"\\x52\"; c\"R\"; cr\"R\"; // R\nc\"\\\\x52\"; cr\"\\x52\"; // \\x52\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tokens", "heading_path": ["Tokens", "Literals", "C string and raw C string literals", "Examples for C string and raw C string literals"], "path": "tokens.md", "url": "https://doc.rust-lang.org/reference/tokens.html#examples-for-c-string-and-raw-c-string-literals", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/tokens.md#integer-literals-17", "text": "The Rust Reference › Tokens › Literals › Number literals › Integer literals\n\nA _number literal_ is either an _integer literal_ or a _floating-point literal_. The grammar for recognizing the two kinds of literals is mixed.\n```grammar,lexer\nINTEGER_LITERAL ->\n ( BIN_LITERAL | OCT_LITERAL | HEX_LITERAL | DEC_LITERAL )\n ^ !RESERVED_FLOAT SUFFIX?\n\nDEC_LITERAL -> DEC_DIGIT (DEC_DIGIT|`_`)*\n\nBIN_LITERAL -> `0b` ^ `_`* BIN_DIGIT (BIN_DIGIT|`_`)* ![`e` `E` `2`-`9`]\n\nOCT_LITERAL -> `0o` ^ `_`* OCT_DIGIT (OCT_DIGIT|`_`)* ![`e` `E` `8`-`9`]\n\nHEX_LITERAL -> `0x` ^ `_`* HEX_DIGIT (HEX_DIGIT|`_`)*\n\nBIN_DIGIT -> [`0`-`1`]\n\nOCT_DIGIT -> [`0`-`7`]\n\nDEC_DIGIT -> [`0`-`9`]\n\nHEX_DIGIT -> [`0`-`9` `a`-`f` `A`-`F`]\n\nRESERVED_FLOAT -> `.` !(`.` | `_` | XID_Start)\n```\nAn _integer literal_ has one of four forms:\n* A _decimal literal_ starts with a *decimal digit* and continues with any mixture of *decimal digits* and _underscores_.\n* 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.\n* 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tokens", "heading_path": ["Tokens", "Literals", "Number literals", "Integer literals"], "path": "tokens.md", "url": "https://doc.rust-lang.org/reference/tokens.html#integer-literals", "has_code": true, "code_tags": ["grammar,lexer"]}} {"id": "reference/tokens.md#integer-literals-18", "text": "The Rust Reference › Tokens › Literals › Number literals › Integer literals\n\n* 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.\nLike 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 [Integer literal expressions] for the effect of these suffixes.\nExamples of integer literals which are accepted as literal expressions:\n```rust\n123;\n123i32;\n123u32;\n123_u32;\n\n0xff;\n0xff_u8;\n0x01_f32; // integer 7986, not floating-point 1.0\n0x01_e3; // integer 483, not floating-point 1000.0\n\n0o70;\n0o70_i16;\n\n0b1111_1111_1001_0000;\n0b1111_1111_1001_0000i64;\n0b________1;\n\n0usize;\n\n// These are too big for their type, but are accepted as literal expressions.\n128_i8;\n256_u8;\n\n// This is an integer literal, accepted as a floating-point literal expression.\n5f32;\n```\nNote that `-1i8`, for example, is analyzed as two tokens: `-` followed by `1i8`.\nExamples of integer literals which are not accepted as literal expressions:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tokens", "heading_path": ["Tokens", "Literals", "Number literals", "Integer literals"], "path": "tokens.md", "url": "https://doc.rust-lang.org/reference/tokens.html#integer-literals", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/tokens.md#tuple-index-19", "text": "The Rust Reference › Tokens › Literals › Number literals › Tuple index\n\n```rust\n0invalidSuffix;\n123AFB43;\n0b010a;\n0xAB_CD_EF_GH;\n0b1111_f32;\n```\nCertain integer literal forms are invalid. To avoid ambiguity, the tokenizer rejects them rather than splitting them into separate tokens.\n```rust,compile_fail\n0b0102; // This is not `0b010` followed by `2`.\n0o1279; // This is not `0o127` followed by `9`.\n0x80.0; // This is not `0x80` followed by `.` and `0`.\n0b101e; // This is not a suffixed literal or `0b101` followed by `e`.\n0b; // This is not an integer literal or `0` followed by `b`.\n0b_; // This is not an integer literal or `0` followed by `b_`.\n2em; // This is not a suffixed literal or `2` followed by `em`.\n2.0em; // This is not a suffixed literal or `2.0` followed by `em`.\n```\nIt is an error to have an unsuffixed binary or octal literal followed without intervening whitespace by a decimal digit outside the range for its radix.\nIt is an error to have an unsuffixed binary, octal, or hexadecimal literal followed without intervening whitespace by a period character (subject to the same restrictions on what may follow the period as in floating-point literals).\nIt is an error to have an unsuffixed binary or octal literal followed without intervening whitespace by the character `e` or `E`.\nIt is an error for a radix prefix to not be followed, after any optional leading underscores, by at least one valid digit for its radix.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tokens", "heading_path": ["Tokens", "Literals", "Number literals", "Tuple index"], "path": "tokens.md", "url": "https://doc.rust-lang.org/reference/tokens.html#tuple-index", "has_code": true, "code_tags": ["rust", "rust,compile_fail"]}} {"id": "reference/tokens.md#floating-point-literals-20", "text": "The Rust Reference › Tokens › Literals › Number literals › Floating-point literals\n\n```grammar,lexer\nTUPLE_INDEX -> DEC_LITERAL | BIN_LITERAL | OCT_LITERAL | HEX_LITERAL\n```\nA tuple index is used to refer to the fields of [tuples], [tuple structs], and [tuple enum variants].\nTuple 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.\nTuple indices may not include any suffixes (such as `usize`).\n```rust,compile_fail\nlet example = (\"dog\", \"cat\", \"horse\");\nlet dog = example.0;\nlet cat = example.1;\n// The following examples are invalid.\nlet cat = example.01; // ERROR no field named `01`\nlet horse = example.0b10; // ERROR no field named `0b10`\nlet unicorn = example.0usize; // ERROR suffixes on a tuple index are invalid\nlet underscore = example.0_0; // ERROR no field `0_0` on type `(&str, &str, &str)`\n```\n```grammar,lexer\nFLOAT_LITERAL ->\n DEC_LITERAL (`.` DEC_LITERAL)? FLOAT_EXPONENT SUFFIX?\n | DEC_LITERAL `.` DEC_LITERAL SUFFIX?\n | DEC_LITERAL `.` !(`.` | `_` | XID_Start)\n\nFLOAT_EXPONENT ->\n (`e`|`E`) ^ (`+`|`-`)? `_`* DEC_DIGIT (DEC_DIGIT|`_`)*\n```\nA _floating-point literal_ has one of two forms:\n* A _decimal literal_ followed by a period character `U+002E` (`.`). This is optionally followed by another decimal literal, with an optional _exponent_.\n* A single _decimal literal_ followed by an _exponent_.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tokens", "heading_path": ["Tokens", "Literals", "Number literals", "Floating-point literals"], "path": "tokens.md", "url": "https://doc.rust-lang.org/reference/tokens.html#floating-point-literals", "has_code": true, "code_tags": ["grammar,lexer", "rust,compile_fail"]}} {"id": "reference/tokens.md#floating-point-literals-21", "text": "The Rust Reference › Tokens › Literals › Number literals › Floating-point literals\n\nLike 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 [Floating-point literal expressions] for the effect of these suffixes.\nExamples of floating-point literals which are accepted as literal expressions:\n```rust\n123.0f64;\n0.1f64;\n0.1f32;\n12E+99_f64;\nlet x: f64 = 2.;\n```\nThis 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`.\nNote that `-1.0`, for example, is analyzed as two tokens: `-` followed by `1.0`.\nExamples of floating-point literals which are not accepted as literal expressions:\n```rust\n2.0f80;\n2e5f80;\n2e5e6;\n2.0e5e6;\n1.3e10u64;\n```\nIt is an error for a floating-point literal to have an exponent with no digits.\n```rust,compile_fail\n2e; // This is not a floating-point literal or `2` followed by `e`.\n2.0e; // This is not a floating-point literal or `2.0` followed by `e`.\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tokens", "heading_path": ["Tokens", "Literals", "Number literals", "Floating-point literals"], "path": "tokens.md", "url": "https://doc.rust-lang.org/reference/tokens.html#floating-point-literals", "has_code": true, "code_tags": ["rust", "rust,compile_fail"]}} {"id": "reference/tokens.md#lifetimes-and-loop-labels-22", "text": "The Rust Reference › Tokens › Lifetimes and loop labels\n\n```grammar,lexer\nLIFETIME_TOKEN ->\n RAW_LIFETIME\n | `'` IDENTIFIER_OR_KEYWORD !`'`\n\nLIFETIME_OR_LABEL ->\n RAW_LIFETIME\n | `'` NON_KEYWORD_IDENTIFIER !`'`\n\nRAW_LIFETIME ->\n `'r#` ^ IDENTIFIER_OR_KEYWORD !`'`\n\nRESERVED_RAW_LIFETIME -> `'r#` (`_` | `crate` | `self` | `Self` | `super`) !(`'` | XID_Continue)\n```\nLifetime parameters and [loop labels] use LIFETIME_OR_LABEL tokens. Any LIFETIME_TOKEN will be accepted by the lexer, and for example, can be used in macros.\nA raw lifetime is like a normal lifetime, but its identifier is prefixed by `r#`. (Note that the `r#` prefix is not included as part of the actual lifetime.)\nUnlike a normal lifetime, a raw lifetime may be any strict or reserved keyword except the ones listed above for `RAW_LIFETIME`.\nIt is an error to use the [RESERVED_RAW_LIFETIME] token.\n[!EDITION-2021]\nRaw lifetimes are accepted in the 2021 edition or later. In earlier editions the token `'r#lt` is lexed as `'r # lt`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tokens", "heading_path": ["Tokens", "Lifetimes and loop labels"], "path": "tokens.md", "url": "https://doc.rust-lang.org/reference/tokens.html#lifetimes-and-loop-labels", "has_code": true, "code_tags": ["grammar,lexer"]}} {"id": "reference/tokens.md#punctuation-23", "text": "The Rust Reference › Tokens › Punctuation\n\nPunctuation tokens are used as operators, separators, and other parts of the grammar.\n```grammar,lexer\nPUNCTUATION ->\n `...`\n | `..=`\n | `<<=`\n | `>>=`\n | `!=`\n | `%=`\n | `&&`\n | `&=`\n | `*=`\n | `+=`\n | `-=`\n | `->`\n | `..`\n | `/=`\n | `::`\n | `<-`\n | `<<`\n | `<=`\n | `==`\n | `=>`\n | `>=`\n | `>>`\n | `^=`\n | `|=`\n | `||`\n | `!`\n | `#`\n | `$`\n | `%`\n | `&`\n | `(`\n | `)`\n | `*`\n | `+`\n | `,`\n | `-`\n | `.`\n | `/`\n | `:`\n | `;`\n | `<`\n | `=`\n | `>`\n | `?`\n | `@`\n | `[`\n | `]`\n | `^`\n | `{`\n | `|`\n | `}`\n | `~`\n```\nSee the [syntax index] for links to how punctuation characters are used.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tokens", "heading_path": ["Tokens", "Punctuation"], "path": "tokens.md", "url": "https://doc.rust-lang.org/reference/tokens.html#punctuation", "has_code": true, "code_tags": ["grammar,lexer"]}} {"id": "reference/tokens.md#delimiters-24", "text": "The Rust Reference › Tokens › Delimiters\n\nBracket 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]. The three types of brackets are:\n| Bracket | Type |\n|---------|-----------------|\n| `{` `}` | Curly braces |\n| `[` `]` | Square brackets |\n| `(` `)` | Parentheses |", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tokens", "heading_path": ["Tokens", "Delimiters"], "path": "tokens.md", "url": "https://doc.rust-lang.org/reference/tokens.html#delimiters", "has_code": false, "code_tags": []}} {"id": "reference/tokens.md#reserved-tokens-25", "text": "The Rust Reference › Tokens › Reserved tokens\n\nSeveral token forms are reserved for future use or to avoid confusion. It is an error for the source input to match one of these forms.\n```grammar,lexer\nRESERVED_TOKEN ->\n RESERVED_GUARDED_STRING_LITERAL\n | RESERVED_POUNDS\n | RESERVED_RAW_IDENTIFIER\n | RESERVED_RAW_LIFETIME\n | RESERVED_TOKEN_DOUBLE_QUOTE\n | RESERVED_TOKEN_LIFETIME\n | RESERVED_TOKEN_POUND\n | RESERVED_TOKEN_SINGLE_QUOTE\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tokens", "heading_path": ["Tokens", "Reserved tokens"], "path": "tokens.md", "url": "https://doc.rust-lang.org/reference/tokens.html#reserved-tokens", "has_code": true, "code_tags": ["grammar,lexer"]}} {"id": "reference/tokens.md#reserved-prefixes-26", "text": "The Rust Reference › Tokens › Reserved prefixes\n\n```grammar,lexer\nRESERVED_TOKEN_DOUBLE_QUOTE ->\n IDENTIFIER_OR_KEYWORD _except `b` or `c` or `r` or `br` or `cr`_ `\"`\n\nRESERVED_TOKEN_SINGLE_QUOTE ->\n IDENTIFIER_OR_KEYWORD _except `b`_ `'`\n\nRESERVED_TOKEN_POUND ->\n IDENTIFIER_OR_KEYWORD _except `r` or `br` or `cr`_ `#`\n\nRESERVED_TOKEN_LIFETIME ->\n `'` IDENTIFIER_OR_KEYWORD _except `r`_ `#`\n```\nSome lexical forms known as _reserved prefixes_ are reserved for future use.\nSource input which would otherwise be lexically interpreted as a non-raw identifier (or a keyword) which is immediately followed by a `#`, `'`, or `\"` character (without intervening whitespace) is identified as a reserved prefix.\nNote that raw identifiers, raw string literals, and raw byte string literals may contain a `#` character but are not interpreted as containing a reserved prefix.\nSimilarly the `r`, `b`, `br`, `c`, and `cr` prefixes used in raw string literals, byte literals, byte string literals, raw byte string literals, C string literals, and raw C string literals are not interpreted as reserved prefixes.\nSource input which would otherwise be lexically interpreted as a non-raw lifetime (or a keyword) which is immediately followed by a `#` character (without intervening whitespace) is identified as a reserved lifetime prefix.\n[!EDITION-2021]\nStarting with the 2021 edition, reserved prefixes are reported as an error by the lexer (in particular, they cannot be passed to macros).\nBefore 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).", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tokens", "heading_path": ["Tokens", "Reserved prefixes"], "path": "tokens.md", "url": "https://doc.rust-lang.org/reference/tokens.html#reserved-prefixes", "has_code": true, "code_tags": ["grammar,lexer"]}} {"id": "reference/tokens.md#reserved-prefixes-27", "text": "The Rust Reference › Tokens › Reserved prefixes\n\nExamples accepted in all editions:\n```rust\nmacro_rules! lexes {($($_:tt)*) => {}}\nlexes!{a #foo}\nlexes!{continue 'foo}\nlexes!{match \"...\" {}}\nlexes!{r#let#foo} // three tokens: r#let # foo\nlexes!{'prefix #lt}\n```\nExamples accepted before the 2021 edition but rejected later:\n```rust,edition2018\nmacro_rules! lexes {($($_:tt)*) => {}}\nlexes!{a#foo}\nlexes!{continue'foo}\nlexes!{match\"...\" {}}\nlexes!{'prefix#lt}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tokens", "heading_path": ["Tokens", "Reserved prefixes"], "path": "tokens.md", "url": "https://doc.rust-lang.org/reference/tokens.html#reserved-prefixes", "has_code": true, "code_tags": ["rust", "rust,edition2018"]}} {"id": "reference/tokens.md#reserved-guards-28", "text": "The Rust Reference › Tokens › Reserved guards\n\n```grammar,lexer\nRESERVED_GUARDED_STRING_LITERAL -> `#`+ STRING_LITERAL\n\nRESERVED_POUNDS -> `#`{2..}\n```\nThe reserved guards are syntax reserved for future use, and will generate a compile error if used.\nThe *reserved guarded string literal* is a token of one or more `U+0023` (`#`) immediately followed by a [STRING_LITERAL].\nThe *reserved pounds* is a token of two or more `U+0023` (`#`).\n[!EDITION-2024]\nBefore the 2024 edition, reserved guards are accepted by the lexer and interpreted as multiple tokens. For example, the `#\"foo\"#` form is interpreted as three tokens. `##` is interpreted as two tokens.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tokens", "heading_path": ["Tokens", "Reserved guards"], "path": "tokens.md", "url": "https://doc.rust-lang.org/reference/tokens.html#reserved-guards", "has_code": true, "code_tags": ["grammar,lexer"]}} {"id": "reference/macros.md#macros-0", "text": "The Rust Reference › Macros\n\nThe 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!(...)`.\nThere are two ways to define new macros:\n* [Macros by example] define new syntax in a higher-level, declarative way.\n* [Procedural macros] define function-like macros, custom derives, and custom attributes using functions that operate on input tokens.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macros", "heading_path": ["Macros"], "path": "macros.md", "url": "https://doc.rust-lang.org/reference/macros.html#macros", "has_code": false, "code_tags": []}} {"id": "reference/macros.md#macro-invocation-1", "text": "The Rust Reference › Macros › Macro invocation\n\n```grammar,macros\nMacroInvocation ->\n SimplePath `!` DelimTokenTree\n\nDelimTokenTree ->\n `(` TokenTree* `)`\n | `[` TokenTree* `]`\n | `{` TokenTree* `}`\n\nTokenTree ->\n Token _except delimiters_ | DelimTokenTree\n\nMacroInvocationSemi ->\n SimplePath `!` `(` TokenTree* `)` `;`\n | SimplePath `!` `[` TokenTree* `]` `;`\n | SimplePath `!` `{` TokenTree* `}`\n```\nA 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:\n* [Expressions] and [statements]\n* [Patterns]\n* [Types]\n* [Items] including [associated items]\n* [`macro_rules`] transcribers\n* [External blocks]\nWhen 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] are never allowed before a macro invocation or [`macro_rules`] definition.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macros", "heading_path": ["Macros", "Macro invocation"], "path": "macros.md", "url": "https://doc.rust-lang.org/reference/macros.html#macro-invocation", "has_code": true, "code_tags": ["grammar,macros"]}} {"id": "reference/macros.md#macro-invocation-2", "text": "The Rust Reference › Macros › Macro invocation\n\n```rust\n// Used as an expression.\nlet x = vec![1,2,3];\n\n// Used as a statement.\nprintln!(\"Hello!\");\n\n// Used in a pattern.\nmacro_rules! pat {\n ($i:ident) => (Some($i))\n}\n\nif let pat!(x) = Some(1) {\n assert_eq!(x, 1);\n}\n\n// Used in a type.\nmacro_rules! Tuple {\n { $A:ty, $B:ty } => { ($A, $B) };\n}\n\ntype N2 = Tuple!(i32, i32);\n\n// Used as an item.\nthread_local!(static FOO: RefCell = RefCell::new(1));\n\n// Used as an associated item.\nmacro_rules! const_maker {\n ($t:ty, $v:tt) => { const CONST: $t = $v; };\n}\ntrait T {\n const_maker!{i32, 7}\n}\n\n// Macro calls within macros.\nmacro_rules! example {\n () => { println!(\"Macro call in a macro!\") };\n}\n// Outer macro `example` is expanded, then inner macro `println` is expanded.\nexample!();\n```\nMacros invocations can be resolved via two kinds of scopes:\n- Textual Scope\n - Textual scope `macro_rules`\n- Path-based scope\n - Path-based scope `macro_rules`\n - [Procedural macros]", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macros", "heading_path": ["Macros", "Macro invocation"], "path": "macros.md", "url": "https://doc.rust-lang.org/reference/macros.html#macro-invocation", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/macros-by-example.md#macros-by-example-0", "text": "The Rust Reference › Macros by example\n\n```grammar,macros\nMacroRulesDefinition ->\n `macro_rules` `!` IDENTIFIER MacroRulesDef\n\nMacroRulesDef ->\n `(` MacroRules `)` `;`\n | `[` MacroRules `]` `;`\n | `{` MacroRules `}`\n\nMacroRules ->\n MacroRule ( `;` MacroRule )* `;`?\n\nMacroRule ->\n MacroMatcher `=>` MacroTranscriber\n\nMacroMatcher ->\n `(` MacroMatch* `)`\n | `[` MacroMatch* `]`\n | `{` MacroMatch* `}`\n\nMacroMatch ->\n Token _except `$` and delimiters_\n | MacroMatcher\n | `$` ( IDENTIFIER_OR_KEYWORD _except `crate`_ | RAW_IDENTIFIER ) `:` MacroFragSpec\n | `$` `(` MacroMatch+ `)` MacroRepSep? MacroRepOp\n\nMacroFragSpec ->\n `block` | `expr` | `expr_2021` | `ident` | `item` | `lifetime` | `literal`\n | `meta` | `pat` | `pat_param` | `path` | `stmt` | `tt` | `ty` | `vis`\n\nMacroRepSep -> Token _except delimiters and [MacroRepOp]_\n\nMacroRepOp -> `*` | `+` | `?`\n\nMacroTranscriber -> DelimTokenTree\n```\n`macro_rules` allows users to define syntax extension in a declarative way. We call such extensions \"macros by example\" or simply \"macros\".", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macros by example", "heading_path": ["Macros by example"], "path": "macros-by-example.md", "url": "https://doc.rust-lang.org/reference/macros-by-example.html#macros-by-example", "has_code": true, "code_tags": ["grammar,macros"]}} {"id": "reference/macros-by-example.md#macros-by-example-1", "text": "The Rust Reference › Macros by example\n\nEach 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macros by example", "heading_path": ["Macros by example"], "path": "macros-by-example.md", "url": "https://doc.rust-lang.org/reference/macros-by-example.html#macros-by-example", "has_code": false, "code_tags": []}} {"id": "reference/macros-by-example.md#transcribing-2", "text": "The Rust Reference › Macros by example › Transcribing\n\nWhen 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.\nWhen 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:\n```rust,compile_fail\nmacro_rules! ambiguity {\n ($($i:ident)* $j:ident) => { };\n}\n\nambiguity!(error); // Error: local ambiguity\n```\nIn both the matcher and the transcriber, the `$` token is used to invoke special behaviours from the macro engine (described below in [Metavariables] and [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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macros by example", "heading_path": ["Macros by example", "Transcribing"], "path": "macros-by-example.md", "url": "https://doc.rust-lang.org/reference/macros-by-example.html#transcribing", "has_code": true, "code_tags": ["rust,compile_fail"]}} {"id": "reference/macros-by-example.md#forwarding-a-matched-fragment-3", "text": "The Rust Reference › Macros by example › Transcribing › Forwarding a matched fragment\n\nWhen 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:\n```rust,compile_fail\nmacro_rules! foo {\n ($l:expr) => { bar!($l); }\n// ERROR: ^^ no rules expected this token in macro call\n}\n\nmacro_rules! bar {\n (3) => {}\n}\n\nfoo!(3);\n```\nThe following illustrates how tokens can be directly matched after matching a `tt` fragment:\n```rust\n// compiles OK\nmacro_rules! foo {\n ($l:tt) => { bar!($l); }\n}\n\nmacro_rules! bar {\n (3) => {}\n}\n\nfoo!(3);\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macros by example", "heading_path": ["Macros by example", "Transcribing", "Forwarding a matched fragment"], "path": "macros-by-example.md", "url": "https://doc.rust-lang.org/reference/macros-by-example.html#forwarding-a-matched-fragment", "has_code": true, "code_tags": ["rust", "rust,compile_fail"]}} {"id": "reference/macros-by-example.md#metavariables-4", "text": "The Rust Reference › Macros by example › Metavariables\n\nIn the matcher, `$` _name_ `:` _fragment-specifier_ matches a Rust syntax fragment of the kind specified and binds it to the metavariable `$`_name_.\nValid fragment specifiers are:\n * `block`: a [BlockExpressionNoInnerAttributes]\n * `expr`: an [Expression]\n * `expr_2021`: an [Expression] except [UnderscoreExpression] and [ConstBlockExpression] (see [macro.decl.meta.edition2024])\n * `ident`: an [IDENTIFIER_OR_KEYWORD] except `_`, [RAW_IDENTIFIER], or [`$crate`]\n * `item`: an [Item]\n * `lifetime`: a [LIFETIME_TOKEN]\n * `literal`: matches `-`?[LiteralExpression]\n * `meta`: an [Attr], the contents of an attribute\n * `pat`: a [Pattern] (see [macro.decl.meta.edition2021])\n * `pat_param`: a [PatternNoTopAlt]\n * `path`: a [TypePath]\n * `stmt`: a Statement without the trailing semicolon (except for item statements that require semicolons)\n * `tt`: a [TokenTree] (a single [token] or tokens in matching delimiters `()`, `[]`, or `{}`)\n * `ty`: a Type\n * `vis`: a possibly empty [Visibility] qualifier\nIn 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. Metavariables can be transcribed more than once or not at all.\nThe keyword metavariable [`$crate`] can be used to refer to the current crate.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macros by example", "heading_path": ["Macros by example", "Metavariables"], "path": "macros-by-example.md", "url": "https://doc.rust-lang.org/reference/macros-by-example.html#metavariables", "has_code": false, "code_tags": []}} {"id": "reference/macros-by-example.md#metavariables-5", "text": "The Rust Reference › Macros by example › Metavariables\n\n[!EDITION-2021]\nStarting with the 2021 edition, `pat` fragment-specifiers match top-level or-patterns (that is, they accept [Pattern]).\nBefore the 2021 edition, they match exactly the same fragments as `pat_param` (that is, they accept [PatternNoTopAlt]).\nThe relevant edition is the one in effect for the `macro_rules!` definition.\n[!EDITION-2024]\nBefore the 2024 edition, `expr` fragment specifiers do not match [UnderscoreExpression] or [ConstBlockExpression] at the top level. They are allowed within subexpressions.\nThe `expr_2021` fragment specifier exists to maintain backwards compatibility with editions before 2024.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macros by example", "heading_path": ["Macros by example", "Metavariables"], "path": "macros-by-example.md", "url": "https://doc.rust-lang.org/reference/macros-by-example.html#metavariables", "has_code": false, "code_tags": []}} {"id": "reference/macros-by-example.md#repetitions-6", "text": "The Rust Reference › Macros by example › Repetitions\n\nIn 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.\nThe 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.\nThe repetition operators are:\n- `*` --- indicates any number of repetitions.\n- `+` --- indicates any number but at least one.\n- `?` --- indicates an optional fragment with zero or one occurrence.\nSince `?` represents at most one occurrence, it cannot be used with a separator.\nThe 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.\nDuring transcription, additional restrictions apply to repetitions so that the compiler knows how to expand them properly:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macros by example", "heading_path": ["Macros by example", "Repetitions"], "path": "macros-by-example.md", "url": "https://doc.rust-lang.org/reference/macros-by-example.html#repetitions", "has_code": false, "code_tags": []}} {"id": "reference/macros-by-example.md#repetitions-7", "text": "The Rust Reference › Macros by example › Repetitions\n\n1. 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.\n2. 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macros by example", "heading_path": ["Macros by example", "Repetitions"], "path": "macros-by-example.md", "url": "https://doc.rust-lang.org/reference/macros-by-example.html#repetitions", "has_code": false, "code_tags": []}} {"id": "reference/macros-by-example.md#scoping-exporting-and-importing-8", "text": "The Rust Reference › Macros by example › Scoping, exporting, and importing\n\nFor 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.\nWhen 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.\n```rust,ignore\nuse lazy_static::lazy_static; // Path-based import.\n\nmacro_rules! lazy_static { // Textual definition.\n (lazy) => {};\n}\n\nlazy_static!{lazy} // Textual lookup finds our macro first.\nself::lazy_static!{} // Path-based lookup ignores our macro, finds imported one.\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macros by example", "heading_path": ["Macros by example", "Scoping, exporting, and importing"], "path": "macros-by-example.md", "url": "https://doc.rust-lang.org/reference/macros-by-example.html#scoping-exporting-and-importing", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "reference/macros-by-example.md#textual-scope-9", "text": "The Rust Reference › Macros by example › Scoping, exporting, and importing › Textual scope\n\nTextual 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:\n```rust,ignore\n//// src/lib.rs\nmod has_macro {\n // m!{} // Error: m is not in scope.\n\n macro_rules! m {\n () => {};\n }\n m!{} // OK: appears after declaration of m.\n\n mod uses_macro;\n}\n\n// m!{} // Error: m is not in scope.\n\n//// src/has_macro/uses_macro.rs\n\nm!{} // OK: appears after declaration of m in src/lib.rs\n```\nIt 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.\n```rust\nmacro_rules! m {\n (1) => {};\n}\n\nm!(1);\n\nmod inner {\n m!(1);\n\n macro_rules! m {\n (2) => {};\n }\n // m!(1); // Error: no rule matches '1'\n m!(2);\n\n macro_rules! m {\n (3) => {};\n }\n m!(3);\n}\n\nm!(1);\n```\nMacros can be declared and used locally inside functions as well, and work similarly:\n```rust\nfn foo() {\n // m!(); // Error: m is not in scope.\n macro_rules! m {\n () => {};\n }\n m!();\n}\n\n// m!(); // Error: m is not in scope.\n```\nTextual scope name bindings for macros shadow path-based scope bindings to macros.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macros by example", "heading_path": ["Macros by example", "Scoping, exporting, and importing", "Textual scope"], "path": "macros-by-example.md", "url": "https://doc.rust-lang.org/reference/macros-by-example.html#textual-scope", "has_code": true, "code_tags": ["rust", "rust,ignore"]}} {"id": "reference/macros-by-example.md#textual-scope-10", "text": "The Rust Reference › Macros by example › Scoping, exporting, and importing › Textual scope\n\n```rust\nmacro_rules! m2 {\n () => {\n println!(\"m2\");\n };\n}\n\n// Resolves to path-based candidate from use declaration below.\nm!(); // prints \"m2\\n\"\n\n// Introduce second candidate for `m` with textual scope.\n//\n// This shadows path-based candidate from below for the rest of this\n// example.\nmacro_rules! m {\n () => {\n println!(\"m\");\n };\n}\n\n// Introduce `m2` macro as path-based candidate.\n//\n// This item is in scope for this entire example, not just below the\n// use declaration.\nuse m2 as m;\n\n// Resolves to the textual macro candidate from above the use\n// declaration.\nm!(); // prints \"m\\n\"\n```\nFor areas where shadowing is not allowed, see [name resolution ambiguities].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macros by example", "heading_path": ["Macros by example", "Scoping, exporting, and importing", "Textual scope"], "path": "macros-by-example.md", "url": "https://doc.rust-lang.org/reference/macros-by-example.html#textual-scope", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/macros-by-example.md#path-based-scope-11", "text": "The Rust Reference › Macros by example › Scoping, exporting, and importing › Path-based scope\n\nBy default, a macro has no path-based scope. Macros can gain path-based scope in two ways:\n- [Use declaration re-export]\n- [`macro_export`]\nMacros can be re-exported to give them path-based scope from a module other than the crate root.\n```rust\nmac::m!(); // OK: Path-based lookup finds `m` in the mac module.\n\nmod mac {\n // Introduce macro `m` with textual scope.\n macro_rules! m {\n () => {};\n }\n\n // Reexport with path-based scope from within `m`'s textual scope.\n pub(crate) use m;\n}\n```\nMacros have an implicit visibility of `pub(crate)`. `#[macro_export]` changes the implicit visibility to `pub`.\n```rust\n// Implicit visibility is `pub(crate)`.\nmacro_rules! private_m {\n () => {};\n}\n\n// Implicit visibility is `pub`.\n#[macro_export]\nmacro_rules! pub_m {\n () => {};\n}\n\npub(crate) use private_m as private_macro; // OK.\npub use pub_m as pub_macro; // OK.\n```\n```rust,compile_fail,E0364\npub use private_m; // ERROR: `private_m` is only public within\n // the crate and cannot be re-exported outside.\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macros by example", "heading_path": ["Macros by example", "Scoping, exporting, and importing", "Path-based scope"], "path": "macros-by-example.md", "url": "https://doc.rust-lang.org/reference/macros-by-example.html#path-based-scope", "has_code": true, "code_tags": ["rust", "rust,compile_fail,E0364"]}} {"id": "reference/macros-by-example.md#the-macro_use-attribute-12", "text": "The Rust Reference › Macros by example › Scoping, exporting, and importing › The `macro_use` attribute\n\nThe *`macro_use` attribute* has two purposes: it may be used on modules to extend the scope of macros defined within them, and it may be used on `extern crate` to import macros from another crate into the [`macro_use` prelude].\n```rust\n#[macro_use]\nmod inner {\n macro_rules! m {\n () => {};\n }\n}\nm!();\n```\n```rust,ignore\n#[macro_use]\nextern crate log;\n```\nWhen used on modules, the `macro_use` attribute uses the [MetaWord] syntax.\nWhen used on `extern crate`, it uses the [MetaWord] and [MetaListIdents] syntaxes. For more on how these syntaxes may be used, see [macro.decl.scope.macro_use.prelude].\nThe `macro_use` attribute may be applied to modules or `extern crate`.\n`rustc` ignores use in other positions but lints against it. This may become an error in the future.\nThe `macro_use` attribute may not be used on [`extern crate self`].\nThe `macro_use` attribute may be used any number of times on a form.\nMultiple instances of `macro_use` in the [MetaListIdents] syntax may be specified. The union of all specified macros will be imported.\nOn modules, `rustc` lints against any [MetaWord] `macro_use` attributes following the first.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macros by example", "heading_path": ["Macros by example", "Scoping, exporting, and importing", "The `macro_use` attribute"], "path": "macros-by-example.md", "url": "https://doc.rust-lang.org/reference/macros-by-example.html#the-macro_use-attribute", "has_code": true, "code_tags": ["rust", "rust,ignore"]}} {"id": "reference/macros-by-example.md#the-macro_use-attribute-13", "text": "The Rust Reference › Macros by example › Scoping, exporting, and importing › The `macro_use` attribute\n\nOn `extern crate`, `rustc` lints against any `macro_use` attributes that have no effect due to not importing any macros not already imported by another `macro_use` attribute. If two or more [MetaListIdents] `macro_use` attributes import the same macro, the first is linted against. If any [MetaWord] `macro_use` attributes are present, all [MetaListIdents] `macro_use` attributes are linted against. If two or more [MetaWord] `macro_use` attributes are present, the ones following the first are linted against.\nWhen `macro_use` is used on a module, the module's macro scope extends beyond the module's lexical scope.\n```rust\n#[macro_use]\nmod inner {\n macro_rules! m {\n () => {};\n }\n}\nm!(); // OK\n```\nSpecifying `macro_use` on an `extern crate` declaration in the crate root imports exported macros from that crate.\nMacros imported this way are imported into the [`macro_use` prelude], not textually, which means that they can be shadowed by any other name. Macros imported by `macro_use` can be used before the import statement.\n`rustc` currently prefers the last macro imported in case of conflict. Don't rely on this. This behavior is unusual, as imports in Rust are generally order-independent. This behavior of `macro_use` may change in the future.\nFor details, see Rust issue #148025.\nWhen using the [MetaWord] syntax, all exported macros are imported. When using the [MetaListIdents] syntax, only the specified macros are imported.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macros by example", "heading_path": ["Macros by example", "Scoping, exporting, and importing", "The `macro_use` attribute"], "path": "macros-by-example.md", "url": "https://doc.rust-lang.org/reference/macros-by-example.html#the-macro_use-attribute", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/macros-by-example.md#the-macro_use-attribute-14", "text": "The Rust Reference › Macros by example › Scoping, exporting, and importing › The `macro_use` attribute\n\n```rust,ignore\n#[macro_use(lazy_static)] // Or `#[macro_use]` to import all macros.\nextern crate lazy_static;\n\nlazy_static!{}\n// self::lazy_static!{} // ERROR: lazy_static is not defined in `self`.\n```\nMacros to be imported with `macro_use` must be exported with `macro_export`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macros by example", "heading_path": ["Macros by example", "Scoping, exporting, and importing", "The `macro_use` attribute"], "path": "macros-by-example.md", "url": "https://doc.rust-lang.org/reference/macros-by-example.html#the-macro_use-attribute", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "reference/macros-by-example.md#the-macro_export-attribute-15", "text": "The Rust Reference › Macros by example › Scoping, exporting, and importing › The `macro_export` attribute\n\nThe *`macro_export` attribute* exports the macro from the crate and makes it available in the root of the crate for path-based resolution.\n```rust\nself::m!();\n// ^^^^ OK: Path-based lookup finds `m` in the current module.\nm!(); // As above.\n\nmod inner {\n super::m!();\n crate::m!();\n}\n\nmod mac {\n #[macro_export]\n macro_rules! m {\n () => {};\n }\n}\n```\nThe `macro_export` attribute uses the [MetaWord] and [MetaListIdents] syntaxes. With the [MetaListIdents] syntax, it accepts a single `local_inner_macros` value.\nThe `macro_export` attribute may be applied to `macro_rules` definitions.\n`rustc` ignores use in other positions but lints against it. This may become an error in the future.\nOnly the first use of `macro_export` on a macro has effect.\n`rustc` lints against any use following the first.\nBy default, macros only have textual scope and cannot be resolved by path. When the `macro_export` attribute is used, the macro is made available in the crate root and can be referred to by its path.\nWithout `macro_export`, macros only have textual scope, so path-based resolution of the macro fails.\n```rust,compile_fail,E0433\nmacro_rules! m {\n () => {};\n}\nself::m!(); // ERROR\ncrate::m!(); // ERROR\n```\nWith `macro_export`, path-based resolution works.\n```rust\n#[macro_export]\nmacro_rules! m {\n () => {};\n}\nself::m!(); // OK\ncrate::m!(); // OK\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macros by example", "heading_path": ["Macros by example", "Scoping, exporting, and importing", "The `macro_export` attribute"], "path": "macros-by-example.md", "url": "https://doc.rust-lang.org/reference/macros-by-example.html#the-macro_export-attribute", "has_code": true, "code_tags": ["rust", "rust,compile_fail,E0433"]}} {"id": "reference/macros-by-example.md#the-macro_export-attribute-16", "text": "The Rust Reference › Macros by example › Scoping, exporting, and importing › The `macro_export` attribute\n\nThe `macro_export` attribute causes a macro to be exported from the crate root so that it can be referred to in other crates by path.\nGiven the following in a `log` crate:\n```rust\n#[macro_export]\nmacro_rules! warn {\n ($message:expr) => { eprintln!(\"WARN: {}\", $message) };\n}\n```\nFrom another crate, you can refer to the macro by path:\n```rust,ignore\nfn main() {\n log::warn!(\"example warning\");\n}\n```\n`macro_export` allows the use of `macro_use` on an `extern crate` to import the macro into the [`macro_use` prelude].\nGiven the following in a `log` crate:\n```rust\n#[macro_export]\nmacro_rules! warn {\n ($message:expr) => { eprintln!(\"WARN: {}\", $message) };\n}\n```\nUsing `macro_use` in a dependent crate allows you to use the macro from the prelude:\n```rust,ignore\n#[macro_use]\nextern crate log;\n\npub mod util {\n pub fn do_thing() {\n // Resolved via macro prelude.\n warn!(\"example warning\");\n }\n}\n```\nAdding `local_inner_macros` to the `macro_export` attribute causes all single-segment macro invocations in the macro definition to have an implicit `$crate::` prefix.\nThis 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.\n```rust\n#[macro_export(local_inner_macros)]\nmacro_rules! helped {\n () => { helper!() } // Automatically converted to $crate::helper!().\n}\n\n#[macro_export]\nmacro_rules! helper {\n () => { () }\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macros by example", "heading_path": ["Macros by example", "Scoping, exporting, and importing", "The `macro_export` attribute"], "path": "macros-by-example.md", "url": "https://doc.rust-lang.org/reference/macros-by-example.html#the-macro_export-attribute", "has_code": true, "code_tags": ["rust", "rust,ignore"]}} {"id": "reference/macros-by-example.md#hygiene-17", "text": "The Rust Reference › Macros by example › Hygiene\n\nMacros by example have _mixed-site hygiene_. This means that [loop labels], [block labels], and local variables are looked up at the macro definition site while other symbols are looked up at the macro invocation site. For example:\n```rust\nlet x = 1;\nfn func() {\n unreachable!(\"this is never called\")\n}\n\nmacro_rules! check {\n () => {\n assert_eq!(x, 1); // Uses `x` from the definition site.\n func(); // Uses `func` from the invocation site.\n };\n}\n\n{\n let x = 2;\n fn func() { /* does not panic */ }\n check!();\n}\n```\nLabels and local variables defined in macro expansion are not shared between invocations, so this code doesn’t compile:\n```rust,compile_fail,E0425\nmacro_rules! m {\n (define) => {\n let x = 1;\n };\n (refer) => {\n dbg!(x);\n };\n}\n\nm!(define);\nm!(refer);\n```\nA special case is the `$crate` metavariable. It refers to the crate defining the macro, and can be used at the start of the path to look up items or macros which are not in scope at the invocation site.\n```rust,ignore\n//// Definitions in the `helper_macro` crate.\n#[macro_export]\nmacro_rules! helped {\n // () => { helper!() } // This might lead to an error due to 'helper' not being in scope.\n () => { $crate::helper!() }\n}\n\n#[macro_export]\nmacro_rules! helper {\n () => { () }\n}\n\n//// Usage in another crate.\n// Note that `helper_macro::helper` is not imported!\nuse helper_macro::helped;\n\nfn unit() {\n helped!();\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macros by example", "heading_path": ["Macros by example", "Hygiene"], "path": "macros-by-example.md", "url": "https://doc.rust-lang.org/reference/macros-by-example.html#hygiene", "has_code": true, "code_tags": ["rust", "rust,compile_fail,E0425", "rust,ignore"]}} {"id": "reference/macros-by-example.md#hygiene-18", "text": "The Rust Reference › Macros by example › Hygiene\n\nNote that, because `$crate` refers to the current crate, it must be used with a fully qualified module path when referring to non-macro items:\n```rust\npub mod inner {\n #[macro_export]\n macro_rules! call_foo {\n () => { $crate::inner::foo() };\n }\n\n pub fn foo() {}\n}\n```\nAdditionally, 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.\n```rust\n#[macro_export]\nmacro_rules! call_foo {\n () => { $crate::foo() };\n}\n\nfn foo() {}\n```\nPrior to Rust 1.30, `$crate` and `local_inner_macros` were unsupported. They were added alongside path-based imports of macros, 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macros by example", "heading_path": ["Macros by example", "Hygiene"], "path": "macros-by-example.md", "url": "https://doc.rust-lang.org/reference/macros-by-example.html#hygiene", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/macros-by-example.md#follow-set-ambiguity-restrictions-19", "text": "The Rust Reference › Macros by example › Follow-set ambiguity restrictions\n\nThe 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.\nIn 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.\nAs 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:\n * `expr` and `stmt` may only be followed by one of: `=>`, `,`, or `;`.\n * `pat_param` may only be followed by one of: `=>`, `,`, `=`, `|`, `if`, or `in`.\n * `pat` may only be followed by one of: `=>`, `,`, `=`, `if`, or `in`.\n * `path` and `ty` may only be followed by one of: `=>`, `,`, `=`, `|`, `;`, `:`, `>`, `>>`, `[`, `{`, `as`, `where`, or a macro variable of `block` fragment specifier.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macros by example", "heading_path": ["Macros by example", "Follow-set ambiguity restrictions"], "path": "macros-by-example.md", "url": "https://doc.rust-lang.org/reference/macros-by-example.html#follow-set-ambiguity-restrictions", "has_code": false, "code_tags": []}} {"id": "reference/macros-by-example.md#follow-set-ambiguity-restrictions-20", "text": "The Rust Reference › Macros by example › Follow-set ambiguity restrictions\n\n* `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.\n * All other fragment specifiers have no restrictions.\n[!EDITION-2021]\nBefore the 2021 edition, `pat` may also be followed by `|`.\nWhen repetitions are involved, then the rules apply to every possible number of expansions, taking separators into account. This means:\n * If the repetition includes a separator, that separator must be able to follow the contents of the repetition.\n * If the repetition can repeat multiple times (`*` or `+`), then the contents must be able to follow themselves.\n * 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.\n * If the repetition can match zero times (`*` or `?`), then whatever comes after must be able to follow whatever comes before.\nFor more detail, see the [formal specification].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macros by example", "heading_path": ["Macros by example", "Follow-set ambiguity restrictions"], "path": "macros-by-example.md", "url": "https://doc.rust-lang.org/reference/macros-by-example.html#follow-set-ambiguity-restrictions", "has_code": false, "code_tags": []}} {"id": "reference/procedural-macros.md#procedural-macros-0", "text": "The Rust Reference › Procedural macros\n\n*Procedural macros* allow creating syntax extensions as execution of a function. Procedural macros come in one of three flavors:\n* [Function-like macros] - `custom!(...)`\n* [Derive macros] - `#[derive(CustomDerive)]`\n* [Attribute macros] - `#[CustomAttribute]`\nProcedural 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.\nProcedural macros must be defined in the root of a crate with the [crate type] of `proc-macro`. The macros may not be used from the crate where they are defined, and can only be used when imported in another crate.\nWhen using Cargo, Procedural macro crates are defined with the `proc-macro` key in your manifest:\n```toml\n[lib]\nproc-macro = true\n```\nAs 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.\nProcedural 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] have.\nProcedural macros have two ways of reporting errors. The first is to panic. The second is to emit a [`compile_error`] macro invocation.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Procedural macros", "heading_path": ["Procedural macros"], "path": "procedural-macros.md", "url": "https://doc.rust-lang.org/reference/procedural-macros.html#procedural-macros", "has_code": true, "code_tags": ["toml"]}} {"id": "reference/procedural-macros.md#the-proc_macro-crate-1", "text": "The Rust Reference › Procedural macros › The `proc_macro` crate\n\nProcedural macro crates almost always will link to the compiler-provided [`proc_macro` crate]. The `proc_macro` crate provides types required for writing procedural macros and facilities to make it easier.\nThis crate primarily contains a [`TokenStream`] 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` 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`, is cheap to clone.\nAll 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Procedural macros", "heading_path": ["Procedural macros", "The `proc_macro` crate"], "path": "procedural-macros.md", "url": "https://doc.rust-lang.org/reference/procedural-macros.html#the-proc_macro-crate", "has_code": false, "code_tags": []}} {"id": "reference/procedural-macros.md#procedural-macro-hygiene-2", "text": "The Rust Reference › Procedural macros › Procedural macro hygiene\n\nProcedural 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.\nMacro 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`).", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Procedural macros", "heading_path": ["Procedural macros", "Procedural macro hygiene"], "path": "procedural-macros.md", "url": "https://doc.rust-lang.org/reference/procedural-macros.html#procedural-macro-hygiene", "has_code": false, "code_tags": []}} {"id": "reference/procedural-macros.md#the-proc_macro-attribute-3", "text": "The Rust Reference › Procedural macros › The `proc_macro` attribute\n\nThe *`proc_macro` attribute* defines a function-like procedural macro.\nThis macro definition ignores its input and emits a function `answer` into its scope.\n```rust,ignore\nextern crate proc_macro;\nuse proc_macro::TokenStream;\n\n#[proc_macro]\npub fn make_answer(_item: TokenStream) -> TokenStream {\n \"fn answer() -> u32 { 42 }\".parse().unwrap()\n}\n```\nWe can use it in a binary crate to print \"42\" to standard output.\n```rust,ignore\nextern crate proc_macro_examples;\nuse proc_macro_examples::make_answer;\n\nmake_answer!();\n\nfn main() {\n println!(\"{}\", answer());\n}\n```\nThe `proc_macro` attribute uses the [MetaWord] syntax.\nThe `proc_macro` attribute may only be applied to a `pub` function of type `fn(TokenStream) -> TokenStream` where [`TokenStream`] comes from the [`proc_macro` crate]. It must have the \"Rust\" ABI. No other function qualifiers are allowed. It must be located in the root of the crate.\nThe `proc_macro` attribute may only be specified once on a function.\nThe `proc_macro` attribute publicly defines the macro in the [macro namespace] in the root of the crate with the same name as the function.\nA function-like macro invocation of a function-like procedural macro will pass what is inside the delimiters of the macro invocation as the input [`TokenStream`] argument and replace the entire macro invocation with the output [`TokenStream`] of the function.\nFunction-like procedural macros may be invoked in any macro invocation position, which includes:\n- [Statements]\n- [Expressions]\n- [Patterns]\n- [Type expressions]\n- [Item] positions, including items in [`extern` blocks]\n- Inherent and trait [implementations]\n- [Trait definitions]", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Procedural macros", "heading_path": ["Procedural macros", "The `proc_macro` attribute"], "path": "procedural-macros.md", "url": "https://doc.rust-lang.org/reference/procedural-macros.html#the-proc_macro-attribute", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "reference/procedural-macros.md#the-proc_macro_derive-attribute-4", "text": "The Rust Reference › Procedural macros › The `proc_macro_derive` attribute\n\nApplying the *`proc_macro_derive` [attribute]* to a function defines a *derive macro* that can be invoked by the [`derive` attribute]. These macros are given the token stream of a [struct], [enum], or [union] definition and can emit new [items] after it. They can also declare and use [derive macro helper attributes].\nThis derive macro ignores its input and appends tokens that define a function.\n```rust,ignore\nextern crate proc_macro;\nuse proc_macro::TokenStream;\n\n#[proc_macro_derive(AnswerFn)]\npub fn derive_answer_fn(_item: TokenStream) -> TokenStream {\n \"fn answer() -> u32 { 42 }\".parse().unwrap()\n}\n```\nTo use it, we might write:\n```rust,ignore\nextern crate proc_macro_examples;\nuse proc_macro_examples::AnswerFn;\n\n#[derive(AnswerFn)]\nstruct Struct;\n\nfn main() {\n assert_eq!(42, answer());\n}\n```\nThe syntax for the `proc_macro_derive` attribute is:\n```grammar,attributes\n@root ProcMacroDeriveAttribute ->\n `proc_macro_derive` `(` DeriveMacroName ( `,` DeriveMacroAttributes )? `,`? `)`\n\nDeriveMacroName -> IDENTIFIER\n\nDeriveMacroAttributes ->\n `attributes` `(` ( IDENTIFIER (`,` IDENTIFIER)* `,`?)? `)`\n```\nThe name of the derive macro is given by [DeriveMacroName]. The optional `attributes` argument is described in [macro.proc.derive.attributes].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Procedural macros", "heading_path": ["Procedural macros", "The `proc_macro_derive` attribute"], "path": "procedural-macros.md", "url": "https://doc.rust-lang.org/reference/procedural-macros.html#the-proc_macro_derive-attribute", "has_code": true, "code_tags": ["grammar,attributes", "rust,ignore"]}} {"id": "reference/procedural-macros.md#the-proc_macro_derive-attribute-5", "text": "The Rust Reference › Procedural macros › The `proc_macro_derive` attribute\n\nThe `proc_macro_derive` attribute may only be applied to a `pub` function with the Rust ABI defined in the root of the crate with a type of `fn(TokenStream) -> TokenStream` where [`TokenStream`] comes from the [`proc_macro` crate]. The function may be `const` and may use `extern` to explicitly specify the Rust ABI, but it may not use any other qualifiers (e.g. it may not be `async` or `unsafe`).\nThe `proc_macro_derive` attribute may be used only once on a function.\nThe `proc_macro_derive` attribute publicly defines the derive macro in the [macro namespace] in the root of the crate.\nThe input [`TokenStream`] is the token stream of the item to which the `derive` attribute is applied. The output [`TokenStream`] must be a (possibly empty) set of items. These items are appended following the input item within the same [module] or [block].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Procedural macros", "heading_path": ["Procedural macros", "The `proc_macro_derive` attribute"], "path": "procedural-macros.md", "url": "https://doc.rust-lang.org/reference/procedural-macros.html#the-proc_macro_derive-attribute", "has_code": false, "code_tags": []}} {"id": "reference/procedural-macros.md#derive-macro-helper-attributes-6", "text": "The Rust Reference › Procedural macros › The `proc_macro_derive` attribute › Derive macro helper attributes\n\nDerive macros can declare *derive macro helper attributes* to be used within the scope of the [item] to which the derive macro is applied. These [attributes] are [inert]. While their purpose is to be used by the macro that declared them, they can be seen by any macro.\nA helper attribute for a derive macro is declared by adding its identifier to the `attributes` list in the `proc_macro_derive` attribute.\nThis declares a helper attribute and then ignores it.\n```rust,ignore\n#[proc_macro_derive(WithHelperAttr, attributes(helper))]\npub fn derive_with_helper_attr(_item: TokenStream) -> TokenStream {\n TokenStream::new()\n}\n```\nTo use it, we might write:\n```rust,ignore\n#[derive(WithHelperAttr)]\nstruct Struct {\n #[helper] field: (),\n}\n```\nWhen a derive macro invocation is applied to an item, the helper attributes introduced by that derive macro become in scope 1) for attributes that are applied to that item and are applied lexically after the derive macro invocation and 2) for attributes that are applied to fields and variants inside of the item.\nrustc currently allows derive helpers to be used before the macro that introduces them. Such derive helpers used out of order may not shadow other attribute macros. This behavior is deprecated and slated for removal.\n```rust,ignore\n#[helper] // Deprecated, hard error in the future.\n#[derive(WithHelperAttr)]\nstruct Struct {\n field: (),\n}\n```\nFor more details, see Rust issue #79202.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Procedural macros", "heading_path": ["Procedural macros", "The `proc_macro_derive` attribute", "Derive macro helper attributes"], "path": "procedural-macros.md", "url": "https://doc.rust-lang.org/reference/procedural-macros.html#derive-macro-helper-attributes", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "reference/procedural-macros.md#the-proc_macro_attribute-attribute-7", "text": "The Rust Reference › Procedural macros › The `proc_macro_attribute` attribute\n\nThe *`proc_macro_attribute` attribute* defines an *attribute macro* which can be used as an outer attribute.\nThis attribute macro takes the input stream and emits it as-is, effectively being a no-op attribute.\n```rust,ignore\n\n#[proc_macro_attribute]\npub fn return_as_is(_attr: TokenStream, item: TokenStream) -> TokenStream {\n item\n}\n```\nThis shows, in the output of the compiler, the stringified [`TokenStream`s] that attribute macros see.\n```rust,ignore\n// my-macro/src/lib.rs\n#[proc_macro_attribute]\npub fn show_streams(attr: TokenStream, item: TokenStream) -> TokenStream {\n println!(\"attr: \\\"{attr}\\\"\");\n println!(\"item: \\\"{item}\\\"\");\n item\n}\n```\n```rust,ignore\n// src/lib.rs\nextern crate my_macro;\n\nuse my_macro::show_streams;\n\n// Example: Basic function.\n#[show_streams]\nfn invoke1() {}\n// out: attr: \"\"\n// out: item: \"fn invoke1() {}\"\n\n// Example: Attribute with input.\n#[show_streams(bar)]\nfn invoke2() {}\n// out: attr: \"bar\"\n// out: item: \"fn invoke2() {}\"\n\n// Example: Multiple tokens in the input.\n#[show_streams(multiple => tokens)]\nfn invoke3() {}\n// out: attr: \"multiple => tokens\"\n// out: item: \"fn invoke3() {}\"\n\n// Example: Delimiters in the input.\n#[show_streams { delimiters }]\nfn invoke4() {}\n// out: attr: \"delimiters\"\n// out: item: \"fn invoke4() {}\"\n```\nThe `proc_macro_attribute` attribute uses the [MetaWord] syntax.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Procedural macros", "heading_path": ["Procedural macros", "The `proc_macro_attribute` attribute"], "path": "procedural-macros.md", "url": "https://doc.rust-lang.org/reference/procedural-macros.html#the-proc_macro_attribute-attribute", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "reference/procedural-macros.md#the-proc_macro_attribute-attribute-8", "text": "The Rust Reference › Procedural macros › The `proc_macro_attribute` attribute\n\nThe `proc_macro_attribute` attribute may only be applied to a `pub` function of type `fn(TokenStream, TokenStream) -> TokenStream` where [`TokenStream`] comes from the [`proc_macro` crate]. It must have the \"Rust\" ABI. No other function qualifiers are allowed. It must be located in the root of the crate.\nThe `proc_macro_attribute` attribute may only be specified once on a function.\nThe `proc_macro_attribute` attribute defines the attribute in the [macro namespace] in the root of the crate with the same name as the function.\nAttribute macros can only be used on:\n- [Items]\n- Items in [`extern` blocks]\n- Inherent and trait [implementations]\n- [Trait definitions]\nFor any [outline modules] present in the macro's input, only the tokens of the module declaration are passed; the file contents of the module are not loaded or included in the input.\nThe first [`TokenStream`] parameter is the delimited token tree following the attribute's name but not including the outer delimiters. If the applied attribute contains only the attribute name or the attribute name followed by empty delimiters, the [`TokenStream`] is empty.\nThe second [`TokenStream`] is the rest of the [item], including other [attributes] on the [item].\nThe item to which the attribute is applied is replaced by the zero or more items in the returned [`TokenStream`].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Procedural macros", "heading_path": ["Procedural macros", "The `proc_macro_attribute` attribute"], "path": "procedural-macros.md", "url": "https://doc.rust-lang.org/reference/procedural-macros.html#the-proc_macro_attribute-attribute", "has_code": false, "code_tags": []}} {"id": "reference/procedural-macros.md#declarative-macro-tokens-and-procedural-macro-tokens-9", "text": "The Rust Reference › Procedural macros › Declarative macro tokens and procedural macro tokens\n\nDeclarative `macro_rules` macros and procedural macros use similar, but different definitions for tokens (or rather [`TokenTree`s].)\nToken trees in `macro_rules` (corresponding to `tt` matchers) are defined as\n- Delimited groups (`(...)`, `{...}`, etc)\n- All operators supported by the language, both single-character and multi-character ones (`+`, `+=`).\n - Note that this set doesn't include the single quote `'`.\n- Literals (`\"string\"`, `1`, etc)\n - Note that negation (e.g. `-1`) is never a part of such literal tokens, but a separate operator token.\n- Identifiers, including keywords (`ident`, `r#ident`, `fn`)\n- Lifetimes (`'ident`)\n- 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)\nToken trees in procedural macros are defined as\n- Delimited groups (`(...)`, `{...}`, etc)\n- 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)\n- Literals (`\"string\"`, `1`, etc)\n - Negation (e.g. `-1`) is supported as a part of integer and floating point literals.\n- Identifiers, including keywords (`ident`, `r#ident`, `fn`)\nMismatches 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Procedural macros", "heading_path": ["Procedural macros", "Declarative macro tokens and procedural macro tokens"], "path": "procedural-macros.md", "url": "https://doc.rust-lang.org/reference/procedural-macros.html#declarative-macro-tokens-and-procedural-macro-tokens", "has_code": false, "code_tags": []}} {"id": "reference/procedural-macros.md#declarative-macro-tokens-and-procedural-macro-tokens-10", "text": "The Rust Reference › Procedural macros › Declarative macro tokens and procedural macro tokens\n\nWhen passed to a proc-macro\n- All multi-character operators are broken into single characters.\n- Lifetimes are broken into a `'` character and an identifier.\n- The keyword metavariable [`$crate`] is passed as a single identifier.\n- All other metavariable substitutions are represented as their underlying token streams.\n - Such token streams may be wrapped into delimited groups ([`Group`]) with implicit delimiters ([`Delimiter::None`]) when it's necessary for preserving parsing priorities.\n - `tt` and `ident` substitutions are never wrapped into such groups and always represented as their underlying token trees.\nWhen emitted from a proc macro\n- Punctuation characters are glued into multi-character operators when applicable.\n- Single quotes `'` joined with identifiers are glued into lifetimes.\n- Negative literals are converted into two tokens (the `-` and the literal) possibly wrapped into a delimited group ([`Group`]) with implicit delimiters ([`Delimiter::None`]) when it's necessary for preserving parsing priorities.\nNote 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Procedural macros", "heading_path": ["Procedural macros", "Declarative macro tokens and procedural macro tokens"], "path": "procedural-macros.md", "url": "https://doc.rust-lang.org/reference/procedural-macros.html#declarative-macro-tokens-and-procedural-macro-tokens", "has_code": false, "code_tags": []}} {"id": "reference/crates-and-source-files.md#crates-and-source-files-0", "text": "The Rust Reference › Crates and source files\n\n```grammar,items\n@root Crate ->\n InnerAttribute*\n Item*\n```\nAlthough 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.\nRust's semantics obey a *phase distinction* between compile-time and run-time.[^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.\nThe 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.[^cratesourcefile]\nA _crate_ is a unit of compilation and linking, as well as versioning, distribution, and runtime loading. A crate contains a _tree_ of nested [module] 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] denoting its location within the crate's module tree.\nThe 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`.\nA 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 item in a referencing source file, or by the name of the crate itself.\nEvery source file is a module, but not every module needs its own source file: module definitions can be nested within one file.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Crates and source files", "heading_path": ["Crates and source files"], "path": "crates-and-source-files.md", "url": "https://doc.rust-lang.org/reference/crates-and-source-files.html#crates-and-source-files", "has_code": true, "code_tags": ["grammar,items"]}} {"id": "reference/crates-and-source-files.md#crates-and-source-files-1", "text": "The Rust Reference › Crates and source files\n\nEach source file contains a sequence of zero or more [Item] 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.\nThe anonymous crate module can have additional attributes that apply to the crate as a whole.\nThe file's contents may be preceded by a [shebang].\n```rust\n// Specify the crate name.\n#![crate_name = \"projx\"]\n\n// Specify the type of output artifact.\n#![crate_type = \"lib\"]\n\n// Turn on a warning.\n// This can be done in any module, not just the anonymous crate module.\n#![warn(non_camel_case_types)]\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Crates and source files", "heading_path": ["Crates and source files"], "path": "crates-and-source-files.md", "url": "https://doc.rust-lang.org/reference/crates-and-source-files.html#crates-and-source-files", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/crates-and-source-files.md#main-functions-2", "text": "The Rust Reference › Crates and source files › Main functions\n\nA crate that contains a `main` [function] can be compiled to an executable.\nIf a `main` function is present, it must take no arguments, must not declare any [trait or lifetime bounds], must not have any [where clauses], and its return type must implement the [`Termination`] trait.\n```rust\nfn main() {}\n```\n```rust\nfn main() -> ! {\n std::process::exit(0);\n}\n```\n```rust\nfn main() -> impl std::process::Termination {\n std::process::ExitCode::SUCCESS\n}\n```\nThe `main` function may be an import, e.g. from an external crate or from the current one.\n```rust\nmod foo {\n pub fn bar() {\n println!(\"Hello, world!\");\n }\n}\nuse foo::bar as main;\n```\nTypes with implementations of [`Termination`] in the standard library include:\n* `()`\n* [`!`]\n* [`Infallible`]\n* [`ExitCode`]\n* `Result where T: Termination, E: Debug`", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Crates and source files", "heading_path": ["Crates and source files", "Main functions"], "path": "crates-and-source-files.md", "url": "https://doc.rust-lang.org/reference/crates-and-source-files.html#main-functions", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/crates-and-source-files.md#uncaught-foreign-unwinding-3", "text": "The Rust Reference › Crates and source files › Main functions › Uncaught foreign unwinding\n\nWhen a \"foreign\" unwind (e.g. an exception thrown from C++ code, or a `panic!` in Rust code using a different panic handler) propagates beyond the `main` function, the process will be safely terminated. This may take the form of an abort, in which case it is not guaranteed that any `Drop` calls will be executed, and the error output may be less informative than if the runtime had been terminated by a \"native\" Rust `panic`.\nFor more information, see the panic documentation.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Crates and source files", "heading_path": ["Crates and source files", "Main functions", "Uncaught foreign unwinding"], "path": "crates-and-source-files.md", "url": "https://doc.rust-lang.org/reference/crates-and-source-files.html#uncaught-foreign-unwinding", "has_code": false, "code_tags": []}} {"id": "reference/crates-and-source-files.md#the-no_main-attribute-4", "text": "The Rust Reference › Crates and source files › Main functions › The `no_main` attribute\n\nThe *`no_main` [attribute]* 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`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Crates and source files", "heading_path": ["Crates and source files", "Main functions", "The `no_main` attribute"], "path": "crates-and-source-files.md", "url": "https://doc.rust-lang.org/reference/crates-and-source-files.html#the-no_main-attribute", "has_code": false, "code_tags": []}} {"id": "reference/crates-and-source-files.md#the-crate_name-attribute-5", "text": "The Rust Reference › Crates and source files › The `crate_name` attribute\n\nThe *`crate_name` [attribute]* may be applied at the crate level to specify the name of the crate with the [MetaNameValueStr] syntax.\n```rust\n#![crate_name = \"mycrate\"]\n```\nThe crate name must not be empty, and must only contain [Unicode alphanumeric] or `_` (U+005F) characters.\n[^phase-distinction]: 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.\n[^cratesourcefile]: 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Crates and source files", "heading_path": ["Crates and source files", "The `crate_name` attribute"], "path": "crates-and-source-files.md", "url": "https://doc.rust-lang.org/reference/crates-and-source-files.html#the-crate_name-attribute", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/conditional-compilation.md#conditional-compilation-0", "text": "The Rust Reference › Conditional compilation\n\n```grammar,configuration\nConfigurationPredicate ->\n ConfigurationOption\n | ConfigurationAll\n | ConfigurationAny\n | ConfigurationNot\n | `true`\n | `false`\n\nConfigurationOption ->\n IDENTIFIER ( `=` ( STRING_LITERAL | RAW_STRING_LITERAL ) )?\n\nConfigurationAll ->\n `all` `(` ConfigurationPredicateList? `)`\n\nConfigurationAny ->\n `any` `(` ConfigurationPredicateList? `)`\n\nConfigurationNot ->\n `not` `(` ConfigurationPredicate `)`\n\nConfigurationPredicateList ->\n ConfigurationPredicate (`,` ConfigurationPredicate)* `,`?\n```\n*Conditionally compiled source code* is source code that is compiled only under certain conditions.\nSource code can be made conditionally compiled using the [`cfg`] and [`cfg_attr`] [attributes] and the built-in [`cfg!`] and [`cfg_select!`] [macros].\nWhether to compile can depend on the target architecture of the compiled crate, arbitrary values passed to the compiler, and other things further described below.\nEach form of conditional compilation takes a _configuration predicate_ that evaluates to true or false. The predicate is one of the following:\n* A configuration option. The predicate is true if the option is set, and false if it is unset.\n* `all()` with a comma-separated list of configuration predicates. It is true if all of the given predicates are true, or if the list is empty.\n* `any()` with a comma-separated list of configuration predicates. It is true if at least one of the given predicates is true. If there are no predicates, it is false.\n* `not()` with a configuration predicate. It is true if its predicate is false and false if its predicate is true.\n* `true` or `false` literals, which are always true or false respectively.\n_Configuration options_ are either names or key-value pairs, and are either set or unset.\nNames are written as a single identifier, such as `unix`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Conditional compilation", "heading_path": ["Conditional compilation"], "path": "conditional-compilation.md", "url": "https://doc.rust-lang.org/reference/conditional-compilation.html#conditional-compilation", "has_code": true, "code_tags": ["grammar,configuration"]}} {"id": "reference/conditional-compilation.md#conditional-compilation-1", "text": "The Rust Reference › Conditional compilation\n\nKey-value pairs are written as an identifier, `=`, and then a string, such as `target_arch = \"x86_64\"`.\nWhitespace around the `=` is ignored, so `foo=\"bar\"` and `foo = \"bar\"` are equivalent.\nKeys do not need to be unique. For example, both `feature = \"std\"` and `feature = \"serde\"` can be set at the same time.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Conditional compilation", "heading_path": ["Conditional compilation"], "path": "conditional-compilation.md", "url": "https://doc.rust-lang.org/reference/conditional-compilation.html#conditional-compilation", "has_code": false, "code_tags": []}} {"id": "reference/conditional-compilation.md#set-configuration-options-2", "text": "The Rust Reference › Conditional compilation › Set configuration options\n\nWhich configuration options are set is determined statically during the compilation of the crate.\nSome options are _compiler-set_ based on data about the compilation.\nOther options are _arbitrarily-set_ based on input passed to the compiler outside of the code.\nIt is not possible to set a configuration option from within the source code of the crate being compiled.\nFor `rustc`, arbitrary-set configuration options are set using the [`--cfg`] flag. Configuration values for a specified target can be displayed with `rustc --print cfg --target $TARGET`.\nConfiguration options with the key `feature` are a convention used by Cargo for specifying compile-time options and optional dependencies.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Conditional compilation", "heading_path": ["Conditional compilation", "Set configuration options"], "path": "conditional-compilation.md", "url": "https://doc.rust-lang.org/reference/conditional-compilation.html#set-configuration-options", "has_code": false, "code_tags": []}} {"id": "reference/conditional-compilation.md#target_arch-3", "text": "The Rust Reference › Conditional compilation › Set configuration options › `target_arch`\n\nKey-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.\nExample values:\n* `\"x86\"`\n* `\"x86_64\"`\n* `\"mips\"`\n* `\"powerpc\"`\n* `\"powerpc64\"`\n* `\"arm\"`\n* `\"aarch64\"`", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Conditional compilation", "heading_path": ["Conditional compilation", "Set configuration options", "`target_arch`"], "path": "conditional-compilation.md", "url": "https://doc.rust-lang.org/reference/conditional-compilation.html#target_arch", "has_code": false, "code_tags": []}} {"id": "reference/conditional-compilation.md#target_feature-4", "text": "The Rust Reference › Conditional compilation › Set configuration options › `target_feature`\n\nKey-value option set for each platform feature available for the current compilation target.\nExample values:\n* `\"avx\"`\n* `\"avx2\"`\n* `\"crt-static\"`\n* `\"rdrand\"`\n* `\"sse\"`\n* `\"sse2\"`\n* `\"sse4.1\"`\nSee the [`target_feature` attribute] for more details on the available features.\nAn additional feature of `crt-static` is available to the `target_feature` option to indicate that a [static C runtime] is available.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Conditional compilation", "heading_path": ["Conditional compilation", "Set configuration options", "`target_feature`"], "path": "conditional-compilation.md", "url": "https://doc.rust-lang.org/reference/conditional-compilation.html#target_feature", "has_code": false, "code_tags": []}} {"id": "reference/conditional-compilation.md#target_os-5", "text": "The Rust Reference › Conditional compilation › Set configuration options › `target_os`\n\nKey-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.\nExample values:\n* `\"windows\"`\n* `\"macos\"`\n* `\"ios\"`\n* `\"linux\"`\n* `\"android\"`\n* `\"freebsd\"`\n* `\"dragonfly\"`\n* `\"openbsd\"`\n* `\"netbsd\"`\n* `\"none\"` (typical for embedded targets)", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Conditional compilation", "heading_path": ["Conditional compilation", "Set configuration options", "`target_os`"], "path": "conditional-compilation.md", "url": "https://doc.rust-lang.org/reference/conditional-compilation.html#target_os", "has_code": false, "code_tags": []}} {"id": "reference/conditional-compilation.md#target_family-6", "text": "The Rust Reference › Conditional compilation › Set configuration options › `target_family`\n\nKey-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.\nExample values:\n* `\"unix\"`\n* `\"windows\"`\n* `\"wasm\"`\n* Both `\"unix\"` and `\"wasm\"`", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Conditional compilation", "heading_path": ["Conditional compilation", "Set configuration options", "`target_family`"], "path": "conditional-compilation.md", "url": "https://doc.rust-lang.org/reference/conditional-compilation.html#target_family", "has_code": false, "code_tags": []}} {"id": "reference/conditional-compilation.md#unix-and-windows-7", "text": "The Rust Reference › Conditional compilation › Set configuration options › `unix` and `windows`\n\n`unix` is set if `target_family = \"unix\"` is set.\n`windows` is set if `target_family = \"windows\"` is set.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Conditional compilation", "heading_path": ["Conditional compilation", "Set configuration options", "`unix` and `windows`"], "path": "conditional-compilation.md", "url": "https://doc.rust-lang.org/reference/conditional-compilation.html#unix-and-windows", "has_code": false, "code_tags": []}} {"id": "reference/conditional-compilation.md#target_env-8", "text": "The Rust Reference › Conditional compilation › Set configuration options › `target_env`\n\nKey-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\"`.\nExample values:\n* `\"\"`\n* `\"gnu\"`\n* `\"msvc\"`\n* `\"musl\"`\n* `\"sgx\"`\n* `\"sim\"`\n* `\"macabi\"`", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Conditional compilation", "heading_path": ["Conditional compilation", "Set configuration options", "`target_env`"], "path": "conditional-compilation.md", "url": "https://doc.rust-lang.org/reference/conditional-compilation.html#target_env", "has_code": false, "code_tags": []}} {"id": "reference/conditional-compilation.md#target_abi-9", "text": "The Rust Reference › Conditional compilation › Set configuration options › `target_abi`\n\nKey-value option set to further disambiguate the target with information about the target ABI.\nFor 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.\nExample values:\n* `\"\"`\n* `\"llvm\"`\n* `\"eabihf\"`\n* `\"abi64\"`", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Conditional compilation", "heading_path": ["Conditional compilation", "Set configuration options", "`target_abi`"], "path": "conditional-compilation.md", "url": "https://doc.rust-lang.org/reference/conditional-compilation.html#target_abi", "has_code": false, "code_tags": []}} {"id": "reference/conditional-compilation.md#target_endian-10", "text": "The Rust Reference › Conditional compilation › Set configuration options › `target_endian`\n\nKey-value option set once with either a value of \"little\" or \"big\" depending on the endianness of the target's CPU.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Conditional compilation", "heading_path": ["Conditional compilation", "Set configuration options", "`target_endian`"], "path": "conditional-compilation.md", "url": "https://doc.rust-lang.org/reference/conditional-compilation.html#target_endian", "has_code": false, "code_tags": []}} {"id": "reference/conditional-compilation.md#target_pointer_width-11", "text": "The Rust Reference › Conditional compilation › Set configuration options › `target_pointer_width`\n\nKey-value option set once with the target's pointer width in bits.\nExample values:\n* `\"16\"`\n* `\"32\"`\n* `\"64\"`", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Conditional compilation", "heading_path": ["Conditional compilation", "Set configuration options", "`target_pointer_width`"], "path": "conditional-compilation.md", "url": "https://doc.rust-lang.org/reference/conditional-compilation.html#target_pointer_width", "has_code": false, "code_tags": []}} {"id": "reference/conditional-compilation.md#target_vendor-12", "text": "The Rust Reference › Conditional compilation › Set configuration options › `target_vendor`\n\nKey-value option set once with the vendor of the target.\nExample values:\n* `\"apple\"`\n* `\"fortanix\"`\n* `\"pc\"`\n* `\"unknown\"`", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Conditional compilation", "heading_path": ["Conditional compilation", "Set configuration options", "`target_vendor`"], "path": "conditional-compilation.md", "url": "https://doc.rust-lang.org/reference/conditional-compilation.html#target_vendor", "has_code": false, "code_tags": []}} {"id": "reference/conditional-compilation.md#target_has_atomic-13", "text": "The Rust Reference › Conditional compilation › Set configuration options › `target_has_atomic`\n\nKey-value option set for each bit width that the target supports atomic loads, stores, and compare-and-swap operations.\nWhen this cfg is present, all of the stable [`core::sync::atomic`] APIs are available for the relevant atomic width.\nPossible values:\n* `\"8\"`\n* `\"16\"`\n* `\"32\"`\n* `\"64\"`\n* `\"128\"`\n* `\"ptr\"`", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Conditional compilation", "heading_path": ["Conditional compilation", "Set configuration options", "`target_has_atomic`"], "path": "conditional-compilation.md", "url": "https://doc.rust-lang.org/reference/conditional-compilation.html#target_has_atomic", "has_code": false, "code_tags": []}} {"id": "reference/conditional-compilation.md#target_has_atomic_primitive_alignment-14", "text": "The Rust Reference › Conditional compilation › Set configuration options › `target_has_atomic_primitive_alignment`\n\nKey-value option set for each bit width where the atomic type has the same alignment as the corresponding integer type.\nThe alignment is usually the same for a given bit width. However, on some targets such as 32-bit x86, 64-bit atomic types such as `AtomicI64` have an alignment of 8 bytes while `i64` is only aligned to 4 bytes. In this situation, `target_has_atomic_primitive_alignment = \"64\"` is not set.\nPossible values:\n* `\"8\"`\n* `\"16\"`\n* `\"32\"`\n* `\"64\"`\n* `\"128\"`\n* `\"ptr\"`", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Conditional compilation", "heading_path": ["Conditional compilation", "Set configuration options", "`target_has_atomic_primitive_alignment`"], "path": "conditional-compilation.md", "url": "https://doc.rust-lang.org/reference/conditional-compilation.html#target_has_atomic_primitive_alignment", "has_code": false, "code_tags": []}} {"id": "reference/conditional-compilation.md#test-15", "text": "The Rust Reference › Conditional compilation › Set configuration options › `test`\n\nEnabled when compiling the test harness. Done with `rustc` by using the [`--test`] flag. See [Testing] for more on testing support.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Conditional compilation", "heading_path": ["Conditional compilation", "Set configuration options", "`test`"], "path": "conditional-compilation.md", "url": "https://doc.rust-lang.org/reference/conditional-compilation.html#test", "has_code": false, "code_tags": []}} {"id": "reference/conditional-compilation.md#debug_assertions-16", "text": "The Rust Reference › Conditional compilation › Set configuration options › `debug_assertions`\n\nEnabled 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!`] macro.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Conditional compilation", "heading_path": ["Conditional compilation", "Set configuration options", "`debug_assertions`"], "path": "conditional-compilation.md", "url": "https://doc.rust-lang.org/reference/conditional-compilation.html#debug_assertions", "has_code": false, "code_tags": []}} {"id": "reference/conditional-compilation.md#proc_macro-17", "text": "The Rust Reference › Conditional compilation › Set configuration options › `proc_macro`\n\nSet when the crate being compiled is being compiled with the `proc_macro` [crate type].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Conditional compilation", "heading_path": ["Conditional compilation", "Set configuration options", "`proc_macro`"], "path": "conditional-compilation.md", "url": "https://doc.rust-lang.org/reference/conditional-compilation.html#proc_macro", "has_code": false, "code_tags": []}} {"id": "reference/conditional-compilation.md#panic-18", "text": "The Rust Reference › Conditional compilation › Set configuration options › `panic`\n\nKey-value option set depending on the [panic strategy]. Note that more values may be added in the future.\nExample values:\n* `\"abort\"`\n* `\"unwind\"`", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Conditional compilation", "heading_path": ["Conditional compilation", "Set configuration options", "`panic`"], "path": "conditional-compilation.md", "url": "https://doc.rust-lang.org/reference/conditional-compilation.html#panic", "has_code": false, "code_tags": []}} {"id": "reference/conditional-compilation.md#the-cfg-attribute-19", "text": "The Rust Reference › Conditional compilation › Forms of conditional compilation › The `cfg` attribute\n\nThe *`cfg` [attribute]* conditionally includes the form to which it is attached based on a configuration predicate.\n```rust\n// The function is only included in the build when compiling for macOS\n#[cfg(target_os = \"macos\")]\nfn macos_only() {\n // ...\n}\n\n// This function is only included when either foo or bar is defined\n#[cfg(any(foo, bar))]\nfn needs_foo_or_bar() {\n // ...\n}\n\n// This function is only included when compiling for a unixish OS with a 32-bit\n// architecture\n#[cfg(all(unix, target_pointer_width = \"32\"))]\nfn on_32bit_unix() {\n // ...\n}\n\n// This function is only included when foo is not defined\n#[cfg(not(foo))]\nfn needs_not_foo() {\n // ...\n}\n\n// This function is only included when the panic strategy is set to unwind\n#[cfg(panic = \"unwind\")]\nfn when_unwinding() {\n // ...\n}\n```\nThe syntax for the `cfg` attribute is:\n```grammar,configuration\n@root CfgAttribute -> `cfg` `(` ConfigurationPredicate `)`\n```\nThe `cfg` attribute may be used anywhere attributes are allowed.\nThe `cfg` attribute may be used any number of times on a form. The form to which the attributes are attached will not be included if any of the `cfg` predicates are false except as described in [cfg.attr.crate-level-attrs].\nIf the predicates are true, the form is rewritten to not have the `cfg` attributes on it. If any predicate is false, the form is removed from the source code.\nWhen a crate-level `cfg` has a false predicate, the crate itself still exists. Any crate attributes preceding the `cfg` are kept, and any crate attributes following the `cfg` are removed as well as removing all of the following crate contents.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Conditional compilation", "heading_path": ["Conditional compilation", "Forms of conditional compilation", "The `cfg` attribute"], "path": "conditional-compilation.md", "url": "https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg-attribute", "has_code": true, "code_tags": ["grammar,configuration", "rust"]}} {"id": "reference/conditional-compilation.md#the-cfg-attribute-20", "text": "The Rust Reference › Conditional compilation › Forms of conditional compilation › The `cfg` attribute\n\nThe behavior of not removing the preceding attributes allows you to do things such as include `#![no_std]` to avoid linking `std` even if a `#![cfg(...)]` has otherwise removed the contents of the crate. For example:\n```rust,ignore\n// This `no_std` attribute is kept even though the crate-level `cfg`\n// attribute is false.\n#![no_std]\n#![cfg(false)]\n\n// This function is not included.\npub fn example() {}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Conditional compilation", "heading_path": ["Conditional compilation", "Forms of conditional compilation", "The `cfg` attribute"], "path": "conditional-compilation.md", "url": "https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg-attribute", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "reference/conditional-compilation.md#the-cfg_attr-attribute-21", "text": "The Rust Reference › Conditional compilation › Forms of conditional compilation › The `cfg_attr` attribute\n\nThe *`cfg_attr` [attribute]* conditionally includes attributes based on a configuration predicate.\nThe following module will either be found at `linux.rs` or `windows.rs` based on the target.\n```rust,ignore\n#[cfg_attr(target_os = \"linux\", path = \"linux.rs\")]\n#[cfg_attr(windows, path = \"windows.rs\")]\nmod os;\n```\nThe syntax for the `cfg_attr` attribute is:\n```grammar,configuration\n@root CfgAttrAttribute -> `cfg_attr` `(` ConfigurationPredicate `,` CfgAttrs? `)`\n\nCfgAttrs -> Attr (`,` Attr)* `,`?\n```\nThe `cfg_attr` attribute may be used anywhere attributes are allowed.\nThe `cfg_attr` attribute may be used any number of times on a form.\nThe [`crate_type`] and [`crate_name`] attributes cannot be used with `cfg_attr`.\nWhen the configuration predicate is true, `cfg_attr` expands out to the attributes listed after the predicate.\nZero, one, or more attributes may be listed. Multiple attributes will each be expanded into separate attributes.\n```rust,ignore\n#[cfg_attr(feature = \"magic\", sparkles, crackles)]\nfn bewitched() {}\n\n// When the `magic` feature flag is enabled, the above will expand to:\n#[sparkles]\n#[crackles]\nfn bewitched() {}\n```\nThe `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)]`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Conditional compilation", "heading_path": ["Conditional compilation", "Forms of conditional compilation", "The `cfg_attr` attribute"], "path": "conditional-compilation.md", "url": "https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg_attr-attribute", "has_code": true, "code_tags": ["grammar,configuration", "rust,ignore"]}} {"id": "reference/conditional-compilation.md#the-cfg-macro-22", "text": "The Rust Reference › Conditional compilation › Forms of conditional compilation › The `cfg` macro\n\nThe 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.\nFor example:\n```rust\nlet machine_kind = if cfg!(unix) {\n \"unix\"\n} else if cfg!(windows) {\n \"windows\"\n} else {\n \"unknown\"\n};\n\nprintln!(\"I'm running on a {} machine!\", machine_kind);\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Conditional compilation", "heading_path": ["Conditional compilation", "Forms of conditional compilation", "The `cfg` macro"], "path": "conditional-compilation.md", "url": "https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg-macro", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/conditional-compilation.md#the-cfg_select-macro-23", "text": "The Rust Reference › Conditional compilation › Forms of conditional compilation › The `cfg_select` macro\n\nThe built-in `cfg_select!` macro can be used to select code at compile-time based on multiple configuration predicates.\n```rust\ncfg_select! {\n unix => {\n fn foo() { /* unix specific functionality */ }\n }\n target_pointer_width = \"32\" => {\n fn foo() { /* non-unix, 32-bit functionality */ }\n }\n _ => {\n fn foo() { /* fallback implementation */ }\n }\n}\n\nlet is_unix_str = cfg_select! {\n unix => \"unix\",\n _ => \"not unix\",\n};\n```\n```grammar,configuration\n@root CfgSelect -> CfgSelectArms?\n\nCfgSelectArms ->\n CfgSelectConfigurationPredicate `=>`\n (\n `{` ^ TokenTree `}` `,`? CfgSelectArms?\n | ExpressionWithBlockNoAttrs `,`? CfgSelectArms?\n | ExpressionWithoutBlockNoAttrs ( `,` CfgSelectArms? )?\n )\n\nCfgSelectConfigurationPredicate ->\n ConfigurationPredicate | `_`\n```\n`cfg_select` expands to the payload of the first arm whose configuration predicate evaluates to true.\nIf the entire payload is wrapped in curly braces, the braces are removed during expansion.\nThe configuration predicate `_` always evaluates to true.\nIt is a compile error if none of the predicates evaluate to true.\nEach right-hand side must be a syntactically valid expansion for the position in which the macro is invoked.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Conditional compilation", "heading_path": ["Conditional compilation", "Forms of conditional compilation", "The `cfg_select` macro"], "path": "conditional-compilation.md", "url": "https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg_select-macro", "has_code": true, "code_tags": ["grammar,configuration", "rust"]}} {"id": "reference/items.md#items-0", "text": "The Rust Reference › Items\n\n```grammar,items\nItem ->\n OuterAttribute* ( VisItem | MacroItem )\n\nVisItem ->\n Visibility?\n (\n Module\n | ExternCrate\n | UseDeclaration\n | Function\n | TypeAlias\n | Struct\n | Enumeration\n | Union\n | ConstantItem\n | StaticItem\n | Trait\n | Implementation\n | ExternBlock\n )\n\nMacroItem ->\n MacroInvocationSemi\n | MacroRulesDefinition\n```\nAn _item_ is a component of a crate. Items are organized within a crate by a nested set of [modules]. Every crate has a single \"outermost\" anonymous module; all further items within the crate have [paths] within the module tree of the crate.\nItems are entirely determined at compile-time, generally remain fixed during execution, and may reside in read-only memory.\nThere are several kinds of items:\n* [modules]\n* [`extern crate` declarations]\n* [`use` declarations]\n* [function definitions]\n* [type alias definitions]\n* [struct definitions]\n* [enumeration definitions]\n* [union definitions]\n* [constant items]\n* [static items]\n* [trait definitions]\n* [implementations]\n* [`extern` blocks]\nItems may be declared in the [root of the crate], a module, or a [block expression].\nA subset of items, called [associated items], may be declared in [traits] and [implementations].\nA subset of items, called external items, may be declared in [`extern` blocks].\nItems may be defined in any order, with the exception of [`macro_rules`] which has its own scoping behavior.\n[Name resolution] of item names allows items to be defined before or after where the item is referred to in the module or block.\nSee [item scopes] for information on the scoping rules of items.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Items", "heading_path": ["Items"], "path": "items.md", "url": "https://doc.rust-lang.org/reference/items.html#items", "has_code": true, "code_tags": ["grammar,items"]}} {"id": "reference/items/modules.md#modules-0", "text": "The Rust Reference › Modules\n\n```grammar,items\nModule ->\n `unsafe`? `mod` IDENTIFIER `;`\n | `unsafe`? `mod` IDENTIFIER `{`\n InnerAttribute*\n Item*\n `}`\n```\nA module is a container for zero or more [items].\nA _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.\nModules can nest arbitrarily.\nAn example of a module:\n```rust\nmod math {\n type Complex = (f64, f64);\n fn sin(f: f64) -> f64 {\n /* ... */\n }\n fn cos(f: f64) -> f64 {\n /* ... */\n }\n fn tan(f: f64) -> f64 {\n /* ... */\n }\n}\n```\nModules are defined in the [type namespace] of the module or block where they are located.\nIt is an error to define multiple items with the same name in the same namespace within a module. See the [scopes chapter] for more details on restrictions and shadowing behavior.\nThe `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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Modules", "heading_path": ["Modules"], "path": "items/modules.md", "url": "https://doc.rust-lang.org/reference/items/modules.html#modules", "has_code": true, "code_tags": ["grammar,items", "rust"]}} {"id": "reference/items/modules.md#module-source-filenames-1", "text": "The Rust Reference › Modules › Module source filenames\n\nA 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].\nAncestor 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:\nModule Path | Filesystem Path | File Contents\n------------------------- | --------------- | -------------\n`crate` | `lib.rs` | `mod util;`\n`crate::util` | `util.rs` | `mod config;`\n`crate::util::config` | `util/config.rs` |\nModule 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`.\nPrior 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Modules", "heading_path": ["Modules", "Module source filenames"], "path": "items/modules.md", "url": "https://doc.rust-lang.org/reference/items/modules.html#module-source-filenames", "has_code": false, "code_tags": []}} {"id": "reference/items/modules.md#the-path-attribute-2", "text": "The Rust Reference › Modules › Module source filenames › The `path` attribute\n\nThe directories and files used for loading external file modules can be influenced with the `path` attribute.\nFor `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:\n```rust,ignore\n#[path = \"foo.rs\"]\nmod c;\n```\nSource File | `c`'s File Location | `c`'s Module Path\n-------------- | ------------------- | ----------------------\n`src/a/b.rs` | `src/a/foo.rs` | `crate::a::b::c`\n`src/a/mod.rs` | `src/a/foo.rs` | `crate::a::c`\nFor `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:\n```rust,ignore\nmod inline {\n #[path = \"other.rs\"]\n mod inner;\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Modules", "heading_path": ["Modules", "Module source filenames", "The `path` attribute"], "path": "items/modules.md", "url": "https://doc.rust-lang.org/reference/items/modules.html#the-path-attribute", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "reference/items/modules.md#the-path-attribute-3", "text": "The Rust Reference › Modules › Module source filenames › The `path` attribute\n\nSource File | `inner`'s File Location | `inner`'s Module Path\n-------------- | --------------------------| ----------------------------\n`src/a/b.rs` | `src/a/b/inline/other.rs` | `crate::a::b::inline::inner`\n`src/a/mod.rs` | `src/a/inline/other.rs` | `crate::a::inline::inner`\nAn 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):\n```rust,ignore\n#[path = \"thread_files\"]\nmod thread {\n // Load the `local_data` module from `thread_files/tls.rs` relative to\n // this source file's directory.\n #[path = \"tls.rs\"]\n mod local_data;\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Modules", "heading_path": ["Modules", "Module source filenames", "The `path` attribute"], "path": "items/modules.md", "url": "https://doc.rust-lang.org/reference/items/modules.html#the-path-attribute", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "reference/items/modules.md#attributes-on-modules-4", "text": "The Rust Reference › Modules › Attributes on modules\n\nModules, 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.\nThe built-in attributes that have meaning on a module are [`cfg`], [`deprecated`], [`doc`], [the lint check attributes], [`path`], and [`no_implicit_prelude`]. Modules also accept macro attributes.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Modules", "heading_path": ["Modules", "Attributes on modules"], "path": "items/modules.md", "url": "https://doc.rust-lang.org/reference/items/modules.html#attributes-on-modules", "has_code": false, "code_tags": []}} {"id": "reference/items/extern-crates.md#extern-crate-declarations-0", "text": "The Rust Reference › Extern crate declarations\n\n```grammar,items\nExternCrate -> `extern` `crate` CrateRef AsClause? `;`\n\nCrateRef -> IDENTIFIER | `self`\n\nAsClause -> `as` ( IDENTIFIER | `_` )\n```\nAn _`extern crate` declaration_ specifies a dependency on an external crate.\nThe external crate is then bound into the declaring scope as the given [identifier] in the [type namespace].\nAdditionally, if the `extern crate` appears in the crate root, then the crate name is also added to the [extern prelude], making it automatically in scope in all modules.\nThe `as` clause can be used to bind the imported crate to a different name.\nThe 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] 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] given in the `extern crate` declaration.\nThe `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.\nThree examples of `extern crate` declarations:\n```rust,ignore\nextern crate pcre;\n\nextern crate std; // equivalent to: extern crate std as std;\n\nextern crate std as ruststd; // linking to 'std' under another name\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Extern crates", "heading_path": ["Extern crate declarations"], "path": "items/extern-crates.md", "url": "https://doc.rust-lang.org/reference/items/extern-crates.html#extern-crate-declarations", "has_code": true, "code_tags": ["grammar,items", "rust,ignore"]}} {"id": "reference/items/extern-crates.md#extern-crate-declarations-1", "text": "The Rust Reference › Extern crate declarations\n\nWhen 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] for more details).\nHere is an example:\n```rust,ignore\n// Importing the Cargo package hello-world\nextern crate hello_world; // hyphen replaced with an underscore\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Extern crates", "heading_path": ["Extern crate declarations"], "path": "items/extern-crates.md", "url": "https://doc.rust-lang.org/reference/items/extern-crates.html#extern-crate-declarations", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "reference/items/extern-crates.md#underscore-imports-2", "text": "The Rust Reference › Extern crate declarations › Underscore imports\n\nAn 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.\nThe [`macro_use` attribute] works as usual and imports the macro names into the [`macro_use` prelude].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Extern crates", "heading_path": ["Extern crate declarations", "Underscore imports"], "path": "items/extern-crates.md", "url": "https://doc.rust-lang.org/reference/items/extern-crates.html#underscore-imports", "has_code": false, "code_tags": []}} {"id": "reference/items/extern-crates.md#the-no_link-attribute-3", "text": "The Rust Reference › Extern crate declarations › The `no_link` attribute\n\nThe *`no_link` attribute* may be applied to an `extern crate` item to prevent linking the crate.\nThis is helpful, e.g., when only the macros of a crate are needed.\n```rust,ignore\n#[no_link]\nextern crate other_crate;\n\nother_crate::some_macro!();\n```\nThe `no_link` attribute uses the [MetaWord] syntax.\nThe `no_link` attribute may only be applied to an `extern crate` declaration.\n`rustc` ignores use in other positions but lints against it. This may become an error in the future.\nOnly the first use of `no_link` on an `extern crate` declaration has effect.\n`rustc` lints against any use following the first. This may become an error in the future.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Extern crates", "heading_path": ["Extern crate declarations", "The `no_link` attribute"], "path": "items/extern-crates.md", "url": "https://doc.rust-lang.org/reference/items/extern-crates.html#the-no_link-attribute", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "reference/items/use-declarations.md#use-declarations-0", "text": "The Rust Reference › Use declarations\n\n```grammar,items\nUseDeclaration -> `use` UseTree `;`\n\nUseTree ->\n (SimplePath? `::`)? `*`\n | (SimplePath? `::`)? `{` (UseTree ( `,` UseTree )* `,`?)? `}`\n | SimplePath ( `as` ( IDENTIFIER | `_` ) )?\n```\nA _use declaration_ creates one or more local name bindings synonymous with some other [path]. 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], usually at the top. A `use` declaration is also sometimes called an _import_, or, if it is public, a _re-export_.\nUse declarations support a number of convenient shortcuts:\n* Simultaneously binding a list of paths with a common prefix, using the brace syntax `use a::b::{c, d, e::f, g::h::i};`\n* 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};`\n* 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}`.\n* Binding all paths matching a given prefix, using the asterisk wildcard syntax `use a::b::*;`.\n* Nesting groups of the previous features multiple times, such as `use a::b::{self as ab, c, d::{*, e::f}};`\nAn example of `use` declarations:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Use declarations", "heading_path": ["Use declarations"], "path": "items/use-declarations.md", "url": "https://doc.rust-lang.org/reference/items/use-declarations.html#use-declarations", "has_code": true, "code_tags": ["grammar,items"]}} {"id": "reference/items/use-declarations.md#use-declarations-1", "text": "The Rust Reference › Use declarations\n\n```rust\nuse std::collections::hash_map::{self, HashMap};\n\nfn foo(_: T){}\nfn bar(map1: HashMap, map2: hash_map::HashMap){}\n\nfn main() {\n // use declarations can also exist inside of functions\n use std::option::Option::{Some, None};\n\n // Equivalent to 'foo(vec![std::option::Option::Some(1.0f64),\n // std::option::Option::None]);'\n foo(vec![Some(1.0f64), None]);\n\n // Both `hash_map` and `HashMap` are in scope.\n let map1 = HashMap::new();\n let map2 = hash_map::HashMap::new();\n bar(map1, map2);\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Use declarations", "heading_path": ["Use declarations"], "path": "items/use-declarations.md", "url": "https://doc.rust-lang.org/reference/items/use-declarations.html#use-declarations", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/use-declarations.md#use-visibility-2", "text": "The Rust Reference › Use declarations › `use` Visibility\n\nLike 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.\nIf a sequence of such redirections form a cycle or cannot be resolved unambiguously, they represent a compile-time error.\nAn example of re-exporting:\n```rust\nmod quux {\n pub use self::foo::{bar, baz};\n pub mod foo {\n pub fn bar() {}\n pub fn baz() {}\n }\n}\n\nfn main() {\n quux::bar();\n quux::baz();\n}\n```\nIn this example, the module `quux` re-exports two public names defined in `foo`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Use declarations", "heading_path": ["Use declarations", "`use` Visibility"], "path": "items/use-declarations.md", "url": "https://doc.rust-lang.org/reference/items/use-declarations.html#use-visibility", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/use-declarations.md#use-paths-3", "text": "The Rust Reference › Use declarations › `use` Paths\n\nThe [paths] that are allowed in a `use` item follow the [SimplePath] grammar and are similar to the paths that may be used in an expression. They may create bindings for:\n* Nameable [items]\n* [Enum variants]\n* [Built-in types]\n* [Attributes]\n* [Derive macros]\n* [`macro_rules`]\nThey cannot import [associated items], [generic parameters], [local variables], paths with [`Self`], or [tool attributes]. More restrictions are described below.\n`use` will create bindings for all [namespaces] from the imported entities, with the exception that a `self` import will only import from the type namespace (as described below). For example, the following illustrates creating bindings for the same name in two namespaces:\n```rust\nmod stuff {\n pub struct Foo(pub i32);\n}\n\n// Imports the `Foo` type and the `Foo` constructor.\nuse stuff::Foo;\n\nfn example() {\n let ctor = Foo; // Uses `Foo` from the value namespace.\n let x: Foo = ctor(123); // Uses `Foo` From the type namespace.\n}\n```\n[!EDITION-2018]\nIn the 2015 edition, `use` paths are relative to the crate root. For example:\n```rust,edition2015\nmod foo {\n pub mod example { pub mod iter {} }\n pub mod baz { pub fn foobaz() {} }\n}\nmod bar {\n // Resolves `foo` from the crate root.\n use foo::example::iter;\n // The `::` prefix explicitly resolves `foo`\n // from the crate root.\n use ::foo::baz::foobaz;\n}\n\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Use declarations", "heading_path": ["Use declarations", "`use` Paths"], "path": "items/use-declarations.md", "url": "https://doc.rust-lang.org/reference/items/use-declarations.html#use-paths", "has_code": true, "code_tags": ["rust", "rust,edition2015"]}} {"id": "reference/items/use-declarations.md#use-paths-4", "text": "The Rust Reference › Use declarations › `use` Paths\n\nThe 2015 edition does not allow use declarations to reference the [extern prelude]. Thus, [`extern crate`] 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Use declarations", "heading_path": ["Use declarations", "`use` Paths"], "path": "items/use-declarations.md", "url": "https://doc.rust-lang.org/reference/items/use-declarations.html#use-paths", "has_code": false, "code_tags": []}} {"id": "reference/items/use-declarations.md#as-renames-5", "text": "The Rust Reference › Use declarations › `as` renames\n\nThe `as` keyword can be used to change the name of an imported entity. For example:\n```rust\n// Creates a non-public alias `bar` for the function `foo`.\nuse inner::foo as bar;\n\nmod inner {\n pub fn foo() {}\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Use declarations", "heading_path": ["Use declarations", "`as` renames"], "path": "items/use-declarations.md", "url": "https://doc.rust-lang.org/reference/items/use-declarations.html#as-renames", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/use-declarations.md#brace-syntax-6", "text": "The Rust Reference › Use declarations › Brace syntax\n\nBraces can be used in the last segment of the path to import multiple entities from the previous segment, or, if there are no previous segments, from the current scope. Braces can be nested, creating a tree of paths, where each grouping of segments is logically combined with its parent to create a full path.\n```rust\n// Creates bindings to:\n// - `std::collections::BTreeSet`\n// - `std::collections::hash_map`\n// - `std::collections::hash_map::HashMap`\nuse std::collections::{BTreeSet, hash_map::{self, HashMap}};\n```\nAn empty brace does not import anything, though the leading path is validated that it is accessible.\n[!EDITION-2018]\nIn the 2015 edition, paths are relative to the crate root, so an import such as `use {foo, bar};` will import the names `foo` and `bar` from the crate root, whereas starting in 2018, those names are relative to the current scope.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Use declarations", "heading_path": ["Use declarations", "Brace syntax"], "path": "items/use-declarations.md", "url": "https://doc.rust-lang.org/reference/items/use-declarations.html#brace-syntax", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/use-declarations.md#self-imports-7", "text": "The Rust Reference › Use declarations › `self` imports\n\nThe keyword `self` may be used within [brace syntax] to create a binding of the parent entity under its own name.\n```rust\nmod stuff {\n pub fn foo() {}\n pub fn bar() {}\n}\nmod example {\n // Creates a binding for `stuff` and `foo`.\n use crate::stuff::{self, foo};\n pub fn baz() {\n foo();\n stuff::bar();\n }\n}\n```\n`self` may also be used as the first segment of a path. The use of `self` as the first segment and inside a `use` brace is logically the same; it means the current module of the parent segment, or the current module if there is no parent segment. See [`self`] in the paths chapter for more information on the meaning of a leading `self`.\n`self` may appear as the last segment of a `use` path, preceded by `::`. A path of the form `P::self` is equivalent to `P::{self}`, and `P::self as name` is equivalent to `P::{self as name}`.\n```rust\nmod m {\n pub enum E { V1, V2 }\n}\nuse m::self as _; // Equivalent to `use m::{self as _};`.\nuse m::E::self; // Equivalent to `use m::E::{self};`.\n```\nSee [paths.qualifiers.mod-self.trailing] for restrictions on the preceding path.\nWhen `self` is used within [brace syntax], the path preceding the brace group must resolve to a [module], [enumeration], or [trait].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Use declarations", "heading_path": ["Use declarations", "`self` imports"], "path": "items/use-declarations.md", "url": "https://doc.rust-lang.org/reference/items/use-declarations.html#self-imports", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/use-declarations.md#self-imports-8", "text": "The Rust Reference › Use declarations › `self` imports\n\n```rust\nmod m {\n pub enum E { V1, V2 }\n pub trait Tr { fn f(&self); }\n}\nuse m::{self as _}; // OK: Modules can be parents of `self`.\nuse m::E::{self, V1}; // OK: Enums can be parents of `self`.\nuse m::Tr::{self}; // OK: Traits can be parents of `self`.\n```\n```rust,compile_fail,E0432\nstruct S {}\nuse S::{self as _}; // ERROR: Structs cannot be parents of `self`.\n```\n`self` only creates a binding from the [type namespace] of the parent entity. For example, in the following, only the `foo` mod is imported:\n```rust,compile_fail\nmod bar {\n pub mod foo {}\n pub fn foo() {}\n}\n\n// This only imports the module `foo`. The function `foo` lives in\n// the value namespace and is not imported.\nuse bar::foo::{self};\n\nfn main() {\n foo(); //~ ERROR `foo` is a module\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Use declarations", "heading_path": ["Use declarations", "`self` imports"], "path": "items/use-declarations.md", "url": "https://doc.rust-lang.org/reference/items/use-declarations.html#self-imports", "has_code": true, "code_tags": ["rust", "rust,compile_fail", "rust,compile_fail,E0432"]}} {"id": "reference/items/use-declarations.md#glob-imports-9", "text": "The Rust Reference › Use declarations › Glob imports\n\nThe `*` character may be used as the last segment of a `use` path to import all importable entities from the entity of the preceding segment. For example:\n```rust\n// Creates a non-public alias to `bar`.\nuse foo::*;\n\nmod foo {\n fn i_am_private() {}\n enum Example {\n V1,\n V2,\n }\n pub fn bar() {\n // Creates local aliases to `V1` and `V2`\n // of the `Example` enum.\n use Example::*;\n let x = V1;\n }\n}\n```\nItems and named imports are allowed to shadow names from glob imports in the same [namespace]. That is, if there is a name already defined by another item in the same namespace, the glob import will be shadowed. For example:\n```rust\n// This creates a binding to the `clashing::Foo` tuple struct\n// constructor, but does not import its type because that would\n// conflict with the `Foo` struct defined here.\n//\n// Note that the order of definition here is unimportant.\nuse clashing::*;\nstruct Foo {\n field: f32,\n}\n\nfn do_stuff() {\n // Uses the constructor from `clashing::Foo`.\n let f1 = Foo(123);\n // The struct expression uses the type from\n // the `Foo` struct defined above.\n let f2 = Foo { field: 1.0 };\n // `Bar` is also in scope due to the glob import.\n let z = Bar {};\n}\n\nmod clashing {\n pub struct Foo(pub i32);\n pub struct Bar {}\n}\n```\nFor areas where shadowing is not allowed, see [name resolution ambiguities].\n`*` cannot be used as the first or intermediate segments.\n`*` cannot be used to import a module's contents into itself (such as `use self::*;`).", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Use declarations", "heading_path": ["Use declarations", "Glob imports"], "path": "items/use-declarations.md", "url": "https://doc.rust-lang.org/reference/items/use-declarations.html#glob-imports", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/use-declarations.md#glob-imports-10", "text": "The Rust Reference › Use declarations › Glob imports\n\n[!EDITION-2018]\nIn the 2015 edition, paths are relative to the crate root, so an import such as `use *;` is valid, and it means to import everything from the crate root. This cannot be used in the crate root itself.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Use declarations", "heading_path": ["Use declarations", "Glob imports"], "path": "items/use-declarations.md", "url": "https://doc.rust-lang.org/reference/items/use-declarations.html#glob-imports", "has_code": false, "code_tags": []}} {"id": "reference/items/use-declarations.md#underscore-imports-11", "text": "The Rust Reference › Use declarations › Underscore imports\n\nItems 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.\n```rust\nmod foo {\n pub trait Zoo {\n fn zoo(&self) {}\n }\n\n impl Zoo for T {}\n}\n\nuse self::foo::Zoo as _;\nstruct Zoo; // Underscore import avoids name conflict with this item.\n\nfn main() {\n let z = Zoo;\n z.zoo();\n}\n```\nAsterisk glob imports will import items imported with `_` in their unnameable form.\nThe 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:\n```rust\nmacro_rules! m {\n ($item: item) => { $item $item }\n}\n\nm!(use std as _;);\n// This expands to:\n// use std as _;\n// use std as _;\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Use declarations", "heading_path": ["Use declarations", "Underscore imports"], "path": "items/use-declarations.md", "url": "https://doc.rust-lang.org/reference/items/use-declarations.html#underscore-imports", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/use-declarations.md#restrictions-12", "text": "The Rust Reference › Use declarations › Restrictions\n\nThe following rules are restrictions for valid `use` declarations.\nWhen using `crate` to import the current crate, you must use `as` to define the binding name.\n```rust\nuse crate as root;\nuse crate::{self as root2};\n\n// Not allowed:\n// use crate;\n// use crate::{self};\n```\nWhen using [`$crate`] in a macro transcriber to import the current crate, you must use `as` to define the binding name.\n```rust\nmacro_rules! import_crate_root {\n () => {\n use $crate as my_crate;\n use $crate::{self as my_crate2};\n };\n}\n```\nWhen using `self` to import the current module, you must use `as` to define the binding name.\n```rust\nuse {self as this_module};\nuse self as this_module2;\nuse self::{self as this_module3};\n\n// Not allowed:\n// use {self};\n// use self;\n// use self::{self};\n```\nWhen using `super` to import a parent module, you must use `as` to define the binding name.\n```rust\nmod a {\n mod b {\n use super as parent;\n use super::{self as parent2};\n use self::super as parent3;\n use super::super as grandparent;\n use super::super::{self as grandparent2};\n\n // Not allowed:\n // use super;\n // use super::{self};\n // use self::super;\n // use super::super;\n // use super::super::{self};\n }\n}\n```\n`::` as the [extern prelude] cannot be imported.\n```rust,edition2018,compile_fail\nuse ::{self as root}; //~ Error\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Use declarations", "heading_path": ["Use declarations", "Restrictions"], "path": "items/use-declarations.md", "url": "https://doc.rust-lang.org/reference/items/use-declarations.html#restrictions", "has_code": true, "code_tags": ["rust", "rust,edition2018,compile_fail"]}} {"id": "reference/items/use-declarations.md#restrictions-13", "text": "The Rust Reference › Use declarations › Restrictions\n\n[!EDITION-2018]\nIn the 2015 edition, the prefix `::` refers to the crate root, so `use ::{self as root};` is allowed because it is same as `use crate::{self as root};`. Starting with the 2018 edition the `::` prefix refers to the extern prelude, which cannot be directly imported.\n```rust,edition2015\nuse ::{self as root}; //~ Ok\n```\nAs with any item definition, `use` imports cannot create duplicate bindings of the same name in the same namespace in a module or block.\n`use` paths cannot refer to enum variants through a [type alias].\n```rust,compile_fail\nenum MyEnum {\n MyVariant\n}\ntype TypeAlias = MyEnum;\n\nuse MyEnum::MyVariant; //~ OK\nuse TypeAlias::MyVariant; //~ ERROR\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Use declarations", "heading_path": ["Use declarations", "Restrictions"], "path": "items/use-declarations.md", "url": "https://doc.rust-lang.org/reference/items/use-declarations.html#restrictions", "has_code": true, "code_tags": ["rust,compile_fail", "rust,edition2015"]}} {"id": "reference/items/functions.md#functions-0", "text": "The Rust Reference › Functions\n\n```grammar,items\nFunction ->\n FunctionQualifiers `fn` IDENTIFIER GenericParams?\n `(` FunctionParameters? `)`\n FunctionReturnType? WhereClause?\n ( BlockExpression | `;` )\n\nFunctionQualifiers -> `const`? `async`?[^async-edition] ItemSafety?[^extern-qualifiers] (`extern` Abi?)?\n\nItemSafety -> `safe`[^extern-safe] | `unsafe`\n\nAbi -> STRING_LITERAL | RAW_STRING_LITERAL\n\nFunctionParameters ->\n SelfParam `,`?\n | (SelfParam `,`)? FunctionParam (`,` FunctionParam)* `,`?\n\nSelfParam -> OuterAttribute* ( ShorthandSelf | TypedSelf )\n\nShorthandSelf -> (`&` | `&` Lifetime)? `mut`? `self`\n\nTypedSelf -> `mut`? `self` `:` Type\n\nFunctionParam -> OuterAttribute* ( FunctionParamPattern | `...` | Type[^fn-param-2015] )\n\nFunctionParamPattern -> PatternNoTopAlt `:` ( Type | `...` )\n\nFunctionReturnType -> `->` Type\n```\n[^async-edition]: The `async` qualifier is not allowed in the 2015 edition.\n[^extern-safe]: The `safe` function qualifier is only allowed semantically within `extern` blocks.\n[^extern-qualifiers]: *Relevant to editions earlier than Rust 2024*: Within `extern` blocks, the `safe` or `unsafe` function qualifier is only allowed when the `extern` is qualified as `unsafe`.\n[^fn-param-2015]: Function parameters with only a type are only allowed in an associated function of a [trait item] in the 2015 edition.\nA _function_ consists of a [block] (that's the _body_ of the function), along with a name, a set of parameters, and an output type. Other than a name, all these are optional.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Functions", "heading_path": ["Functions"], "path": "items/functions.md", "url": "https://doc.rust-lang.org/reference/items/functions.html#functions", "has_code": true, "code_tags": ["grammar,items"]}} {"id": "reference/items/functions.md#functions-1", "text": "The Rust Reference › Functions\n\nFunctions are declared with the keyword `fn` which defines the given name in the [value namespace] of the module or block where it is located.\nFunctions may declare a set of *input* *variables* as parameters, through which the caller passes arguments into the function, and the *output* *type* of the value the function will return to its caller on completion.\nIf the output type is not explicitly stated, it is the [unit type].\nWhen referred to, a _function_ yields a first-class *value* of the corresponding [zero-sized] [*function item type*], which when called evaluates to a direct call to the function.\nFor example, this is a simple function:\n```rust\nfn answer_to_life_the_universe_and_everything() -> i32 {\n return 42;\n}\n```\nThe `safe` function is semantically only allowed when used in an [`extern` block].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Functions", "heading_path": ["Functions"], "path": "items/functions.md", "url": "https://doc.rust-lang.org/reference/items/functions.html#functions", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/functions.md#function-parameters-2", "text": "The Rust Reference › Functions › Function parameters\n\nFunction parameters are irrefutable [patterns], so any pattern that is valid in an else-less `let` binding is also valid as a parameter:\n```rust\nfn first((value, _): (i32, i32)) -> i32 { value }\n```\nIf the first parameter is a [SelfParam], this indicates that the function is a [method].\nFunctions with a self parameter may only appear as an [associated function] in a [trait] or [implementation].\nA parameter with the `...` token indicates a [variadic function], and may only be used as the last parameter of an [external block] function. The variadic parameter may have an optional identifier, such as `args: ...`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Functions", "heading_path": ["Functions", "Function parameters"], "path": "items/functions.md", "url": "https://doc.rust-lang.org/reference/items/functions.html#function-parameters", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/functions.md#function-body-3", "text": "The Rust Reference › Functions › Function body\n\nThe body block of a function is conceptually wrapped in another block that first binds the argument patterns and then `return`s the value of the function's body. 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.\nFor example, the function above behaves as if it was written as:\n```rust,ignore\n// argument_0 is the actual first argument passed from the caller\nlet (value, _) = argument_0;\nreturn {\n value\n};\n```\nFunctions without a body block are terminated with a semicolon. This form may only appear in a [trait] or [external block].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Functions", "heading_path": ["Functions", "Function body"], "path": "items/functions.md", "url": "https://doc.rust-lang.org/reference/items/functions.html#function-body", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "reference/items/functions.md#generic-functions-4", "text": "The Rust Reference › Functions › Generic functions\n\nA _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.\n```rust\n// foo is generic over A and B\n\nfn foo(x: A, y: B) {\n```\nInside the function signature and body, the name of the type parameter can be used as a type name.\n[Trait] bounds can be specified for type parameters to allow methods from that trait to be called on values of that type. This is specified using the `where` syntax:\n```rust\nfn foo(x: T) where T: Debug {\n```\nWhen a generic function is referenced, its type is instantiated based on the context of the reference. For example, calling the `foo` function here:\n```rust\nuse std::fmt::Debug;\n\nfn foo(x: &[T]) where T: Debug {\n // details elided\n}\n\nfoo(&[1, 2]);\n```\nwill instantiate type parameter `T` with `i32`.\nThe type parameters can also be explicitly supplied in a trailing [path] 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::() == 4`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Functions", "heading_path": ["Functions", "Generic functions"], "path": "items/functions.md", "url": "https://doc.rust-lang.org/reference/items/functions.html#generic-functions", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/functions.md#extern-function-qualifier-5", "text": "The Rust Reference › Functions › Extern function qualifier\n\nThe `extern` function qualifier allows providing function _definitions_ that can be called with a particular ABI:\n```rust,ignore\nextern \"ABI\" fn foo() { /* ... */ }\n```\nThese are often used in combination with [external block] items which provide function _declarations_ that can be used to call functions without providing their _definition_:\n```rust,ignore\nunsafe extern \"ABI\" {\n unsafe fn foo(); /* no body */\n safe fn bar(); /* no body */\n}\nunsafe { foo() };\nbar();\n```\nWhen `\"extern\" Abi?*` is omitted from `FunctionQualifiers` in function items, the ABI `\"Rust\"` is assigned. For example:\n```rust\nfn foo() {}\n```\nis equivalent to:\n```rust\nextern \"Rust\" fn foo() {}\n```\nFunctions 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:\n```rust\n// Declares a function with the \"C\" ABI\nextern \"C\" fn new_i32() -> i32 { 0 }\n\n// Declares a function with the \"stdcall\" ABI\nextern \"stdcall\" fn new_i32_stdcall() -> i32 { 0 }\n```\nJust as with [external block], when the `extern` keyword is used and the `\"ABI\"` is omitted, the ABI used defaults to `\"C\"`. That is, this:\n```rust\nextern fn new_i32() -> i32 { 0 }\nlet fptr: extern fn() -> i32 = new_i32;\n```\nis equivalent to:\n```rust\nextern \"C\" fn new_i32() -> i32 { 0 }\nlet fptr: extern \"C\" fn() -> i32 = new_i32;\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Functions", "heading_path": ["Functions", "Extern function qualifier"], "path": "items/functions.md", "url": "https://doc.rust-lang.org/reference/items/functions.html#extern-function-qualifier", "has_code": true, "code_tags": ["rust", "rust,ignore"]}} {"id": "reference/items/functions.md#unwinding-6", "text": "The Rust Reference › Functions › Extern function qualifier › Unwinding\n\nMost ABI strings come in two variants, one with an `-unwind` suffix and one without. The `Rust` ABI always permits unwinding, so there is no `Rust-unwind` ABI. The choice of ABI, together with the runtime [panic handler], determines the behavior when unwinding out of a function.\nThe table below indicates the behavior of an unwinding operation reaching each type of ABI boundary (function declaration or definition using the corresponding ABI string). Note that the Rust runtime is not affected by, and cannot have an effect on, any unwinding that occurs entirely within another language's runtime, that is, unwinds that are thrown and caught without reaching a Rust ABI boundary.\nThe `panic`-unwind column refers to [panicking] via the `panic!` macro and similar standard library mechanisms, as well as to any other Rust operations that cause a panic, such as out-of-bounds array indexing or integer overflow.\nThe \"unwinding\" ABI category refers to `\"Rust\"` (the implicit ABI of Rust functions not marked `extern`), `\"C-unwind\"`, and any other ABI with `-unwind` in its name. The \"non-unwinding\" ABI category refers to all other ABI strings, including `\"C\"` and `\"stdcall\"`.\nNative unwinding is defined per-target. On targets that support throwing and catching C++ exceptions, it refers to the mechanism used to implement this feature. Some platforms implement a form of unwinding referred to as \"forced unwinding\"; `longjmp` on Windows and `pthread_exit` in `glibc` are implemented this way. Forced unwinding is explicitly excluded from the \"Native unwind\" column in the table.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Functions", "heading_path": ["Functions", "Extern function qualifier", "Unwinding"], "path": "items/functions.md", "url": "https://doc.rust-lang.org/reference/items/functions.html#unwinding", "has_code": false, "code_tags": []}} {"id": "reference/items/functions.md#unwinding-7", "text": "The Rust Reference › Functions › Extern function qualifier › Unwinding\n\n| panic runtime | ABI | `panic`-unwind | Native unwind (unforced) |\n| -------------- | ------------ | ------------------------------------- | ----------------------- |\n| `panic=unwind` | unwinding | unwind | unwind |\n| `panic=unwind` | non-unwinding | abort (see notes below) | [undefined behavior] |\n| `panic=abort` | unwinding | `panic` aborts without unwinding | abort |\n| `panic=abort` | non-unwinding | `panic` aborts without unwinding | [undefined behavior] |\nWith `panic=unwind`, when a `panic` is turned into an abort by a non-unwinding ABI boundary, either no destructors (`Drop` calls) will run, or all destructors up until the ABI boundary will run. It is unspecified which of those two behaviors will happen.\nFor other considerations and limitations regarding unwinding across FFI boundaries, see the relevant section in the Panic documentation.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Functions", "heading_path": ["Functions", "Extern function qualifier", "Unwinding"], "path": "items/functions.md", "url": "https://doc.rust-lang.org/reference/items/functions.html#unwinding", "has_code": false, "code_tags": []}} {"id": "reference/items/functions.md#const-functions-8", "text": "The Rust Reference › Functions › Const functions\n\nSee [const functions] for the definition of const functions.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Functions", "heading_path": ["Functions", "Const functions"], "path": "items/functions.md", "url": "https://doc.rust-lang.org/reference/items/functions.html#const-functions", "has_code": false, "code_tags": []}} {"id": "reference/items/functions.md#async-functions-9", "text": "The Rust Reference › Functions › Async functions\n\nFunctions may be qualified as async, and this can also be combined with the `unsafe` qualifier:\n```rust\nasync fn regular_example() { }\nasync unsafe fn unsafe_example() { }\n```\nAsync functions do no work when called: instead, they capture their arguments into a future. When polled, that future will execute the function's body.\nAn async function is roughly equivalent to a function that returns [`impl Future`] and with an `async move` block as its body:\n```rust\n// Source\nasync fn example(x: &str) -> usize {\n x.len()\n}\n```\nis roughly equivalent to:\n```rust\n// Desugared\nfn example<'a>(x: &'a str) -> impl Future + 'a {\n async move { x.len() }\n}\n```\nThe actual desugaring is more complex:\n- 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`.\n- The `async move` block 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.\nFor more information on the effect of async, see `async` blocks.\n[!EDITION-2018]\nAsync functions are only available beginning with Rust 2018.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Functions", "heading_path": ["Functions", "Async functions"], "path": "items/functions.md", "url": "https://doc.rust-lang.org/reference/items/functions.html#async-functions", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/functions.md#combining-async-and-unsafe-10", "text": "The Rust Reference › Functions › Async functions › Combining `async` and `unsafe`\n\nIt 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:\n```rust\n// Returns a future that, when awaited, dereferences `x`.\n//\n// Soundness condition: `x` must be safe to dereference until\n// the resulting future is complete.\nasync unsafe fn unsafe_example(x: *const i32) -> i32 {\n *x\n}\n\nasync fn safe_example() {\n // An `unsafe` block is required to invoke the function initially:\n let p = 22;\n let future = unsafe { unsafe_example(&p) };\n\n // But no `unsafe` block required here. This will\n // read the value of `p`:\n let q = future.await;\n}\n```\nNote 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.\nUnsafe 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Functions", "heading_path": ["Functions", "Async functions", "Combining `async` and `unsafe`"], "path": "items/functions.md", "url": "https://doc.rust-lang.org/reference/items/functions.html#combining-async-and-unsafe", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/functions.md#attributes-on-functions-11", "text": "The Rust Reference › Functions › Attributes on functions\n\nOuter attributes are allowed on functions. Inner attributes are allowed directly after the `{` inside its body [block].\nThis example shows an inner attribute on a function. The function is documented with just the word \"Example\".\n```rust\nfn documented() {\n #![doc = \"Example\"]\n}\n```\nExcept for lints, it is idiomatic to only use outer attributes on function items.\nThe attributes that have meaning on a function are:\n- [`cfg_attr`]\n- [`cfg`]\n- [`cold`]\n- [`deprecated`]\n- [`doc`]\n- [`export_name`]\n- [`inline`]\n- [`link_section`]\n- [`must_use`]\n- [`no_mangle`]\n- [Lint check attributes]\n- [Procedural macro attributes]\n- [Testing attributes]", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Functions", "heading_path": ["Functions", "Attributes on functions"], "path": "items/functions.md", "url": "https://doc.rust-lang.org/reference/items/functions.html#attributes-on-functions", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/functions.md#attributes-on-function-parameters-12", "text": "The Rust Reference › Functions › Attributes on function parameters\n\nOuter attributes are allowed on function parameters and the permitted [built-in attributes] are restricted to `cfg`, `cfg_attr`, `allow`, `warn`, `deny`, and `forbid`.\n```rust\nfn len(\n #[cfg(windows)] slice: &[u16],\n #[cfg(not(windows))] slice: &[u8],\n) -> usize {\n slice.len()\n}\n```\nInert 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`.\nFor 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.\n```rust,ignore\n#[some_proc_macro_attribute]\nfn foo_oof(#[some_inert_attribute] arg: u8) {\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Functions", "heading_path": ["Functions", "Attributes on function parameters"], "path": "items/functions.md", "url": "https://doc.rust-lang.org/reference/items/functions.html#attributes-on-function-parameters", "has_code": true, "code_tags": ["rust", "rust,ignore"]}} {"id": "reference/items/type-aliases.md#type-aliases-0", "text": "The Rust Reference › Type aliases\n\n```grammar,items\nTypeAlias ->\n `type` IDENTIFIER GenericParams? ( `:` Bounds? )?\n WhereClause?\n ( `=` Type WhereClause?)? `;`\n```\nA _type alias_ defines a new name for an existing [type] in the [type namespace] of the module or block where it is located. Type aliases are declared with the keyword `type`. Every value has a single, specific type, but may implement several different traits, and may be compatible with several different type constraints.\nFor example, the following defines the type `Point` as a synonym for the type `(u8, u8)`, the type of pairs of unsigned 8 bit integers:\n```rust\ntype Point = (u8, u8);\nlet p: Point = (41, 68);\n```\nA type alias to a tuple-struct or unit-struct cannot be used to qualify that type's constructor:\n```rust,compile_fail\nstruct MyStruct(u32);\n\nuse MyStruct as UseAlias;\ntype TypeAlias = MyStruct;\n\nlet _ = UseAlias(5); // OK\nlet _ = TypeAlias(5); // Doesn't work\n```\nA type alias, when not used as an [associated type], must include a Type and may not include [Bounds].\nA type alias, when used as an [associated type] in a [trait], must not include a Type specification but may include [Bounds].\nA type alias, when used as an [associated type] in a [trait impl], must include a Type specification and may not include [Bounds].\nWhere clauses before the equals sign on a type alias in a [trait impl] (like `type TypeAlias where T: Foo = Bar`) are deprecated. Where clauses after the equals sign (like `type TypeAlias = Bar where T: Foo`) are preferred.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type aliases", "heading_path": ["Type aliases"], "path": "items/type-aliases.md", "url": "https://doc.rust-lang.org/reference/items/type-aliases.html#type-aliases", "has_code": true, "code_tags": ["grammar,items", "rust", "rust,compile_fail"]}} {"id": "reference/items/structs.md#structs-0", "text": "The Rust Reference › Structs\n\n```grammar,items\nStruct ->\n StructStruct\n | TupleStruct\n\nStructStruct ->\n `struct` IDENTIFIER GenericParams? WhereClause? ( `{` StructFields? `}` | `;` )\n\nTupleStruct ->\n `struct` IDENTIFIER GenericParams? `(` TupleFields? `)` WhereClause? `;`\n\nStructFields -> StructField (`,` StructField)* `,`?\n\nStructField -> OuterAttribute* Visibility? IDENTIFIER `:` Type\n\nTupleFields -> TupleField (`,` TupleField)* `,`?\n\nTupleField -> OuterAttribute* Visibility? Type\n```\nA _struct_ is a nominal [struct type] defined with the keyword `struct`.\nA struct declaration defines the given name in the [type namespace] of the module or block where it is located.\nAn example of a `struct` item and its use:\n```rust\nstruct Point {x: i32, y: i32}\nlet p = Point {x: 10, y: 11};\nlet px: i32 = p.x;\n```\nA _tuple struct_ is a nominal [tuple type], and is also defined with the keyword `struct`. In addition to defining a type, it also defines a constructor of the same name in the [value namespace]. The constructor is a function which can be called to create a new instance of the struct. For example:\n```rust\nstruct Point(i32, i32);\nlet p = Point(10, 11);\nlet px: i32 = match p { Point(x, _) => x };\n```\nA _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:\n```rust\nstruct Cookie;\nlet c = [Cookie, Cookie {}, Cookie, Cookie {}];\n```\nis equivalent to", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Structs", "heading_path": ["Structs"], "path": "items/structs.md", "url": "https://doc.rust-lang.org/reference/items/structs.html#structs", "has_code": true, "code_tags": ["grammar,items", "rust"]}} {"id": "reference/items/structs.md#structs-1", "text": "The Rust Reference › Structs\n\n```rust\nstruct Cookie {}\nconst Cookie: Cookie = Cookie {};\nlet c = [Cookie, Cookie {}, Cookie, Cookie {}];\n```\nThe precise memory layout of a struct is not specified. One can specify a particular layout using the [`repr` attribute].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Structs", "heading_path": ["Structs"], "path": "items/structs.md", "url": "https://doc.rust-lang.org/reference/items/structs.html#structs", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/enumerations.md#enumerations-0", "text": "The Rust Reference › Enumerations\n\n```grammar,items\nEnumeration ->\n `enum` IDENTIFIER GenericParams? WhereClause? `{` EnumVariants? `}`\n\nEnumVariants -> EnumVariant ( `,` EnumVariant )* `,`?\n\nEnumVariant ->\n OuterAttribute* Visibility?\n IDENTIFIER ( EnumVariantTuple | EnumVariantStruct )? EnumVariantDiscriminant?\n\nEnumVariantTuple -> `(` TupleFields? `)`\n\nEnumVariantStruct -> `{` StructFields? `}`\n\nEnumVariantDiscriminant -> `=` Expression\n```\nAn *enumeration*, also referred to as an *enum*, is a simultaneous definition of a nominal [enumerated type] as well as a set of *constructors*, that can be used to create or pattern-match values of the corresponding enumerated type.\nEnumerations are declared with the keyword `enum`.\nThe `enum` declaration defines the enumeration type in the [type namespace] of the module or block where it is located.\nAn example of an `enum` item and its use:\n```rust\nenum Animal {\n Dog,\n Cat,\n}\n\nlet mut a: Animal = Animal::Dog;\na = Animal::Cat;\n```\nEnum constructors can have either named or unnamed fields:\n```rust\nenum Animal {\n Dog(String, f64),\n Cat { name: String, weight: f64 },\n}\n\nlet mut a: Animal = Animal::Dog(\"Cocoa\".to_string(), 37.2);\na = Animal::Cat { name: \"Spotty\".to_string(), weight: 2.7 };\n```\nIn this example, `Cat` is a _struct-like enum variant_, whereas `Dog` is simply called an enum variant.\nAn enum where no constructors contain fields is called a *field-less enum*. For example, this is a fieldless enum:\n```rust\nenum Fieldless {\n Tuple(),\n Struct{},\n Unit,\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Enumerations", "heading_path": ["Enumerations"], "path": "items/enumerations.md", "url": "https://doc.rust-lang.org/reference/items/enumerations.html#enumerations", "has_code": true, "code_tags": ["grammar,items", "rust"]}} {"id": "reference/items/enumerations.md#enumerations-1", "text": "The Rust Reference › Enumerations\n\nIf a field-less enum only contains unit variants, the enum is called an *unit-only enum*. For example:\n```rust\nenum Enum {\n Foo = 3,\n Bar = 2,\n Baz = 1,\n}\n```\nVariant constructors are similar to [struct] definitions, and can be referenced by a path from the enumeration name, including in [use declarations].\nEach variant defines its type in the [type namespace], though that type cannot be used as a type specifier. Tuple-like and unit-like variants also define a constructor in the [value namespace].\nA struct-like variant can be instantiated with a [struct expression].\nA tuple-like variant can be instantiated with a [call expression] or a [struct expression].\nA unit-like variant can be instantiated with a [path expression] or a [struct expression]. For example:\n```rust\nenum Examples {\n UnitLike,\n TupleLike(i32),\n StructLike { value: i32 },\n}\n\nuse Examples::*; // Creates aliases to all variants.\nlet x = UnitLike; // Path expression of the const item.\nlet x = UnitLike {}; // Struct expression.\nlet y = TupleLike(123); // Call expression.\nlet y = TupleLike { 0: 123 }; // Struct expression using integer field names.\nlet z = StructLike { value: 123 }; // Struct expression.\n```\n", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Enumerations", "heading_path": ["Enumerations"], "path": "items/enumerations.md", "url": "https://doc.rust-lang.org/reference/items/enumerations.html#enumerations", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/enumerations.md#discriminants-2", "text": "The Rust Reference › Enumerations › Discriminants\n\nEach enum instance has a _discriminant_: an integer logically associated to it that is used to determine which variant it holds.\nUnder the [`Rust` 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Enumerations", "heading_path": ["Enumerations", "Discriminants"], "path": "items/enumerations.md", "url": "https://doc.rust-lang.org/reference/items/enumerations.html#discriminants", "has_code": false, "code_tags": []}} {"id": "reference/items/enumerations.md#restrictions-3", "text": "The Rust Reference › Enumerations › Discriminants › Assigning discriminant values › Restrictions\n\nIn two circumstances, the discriminant of a variant may be explicitly set by following the variant name with `=` and a [constant expression]:\n1. if the enumeration is \"[unit-only]\".\n2. if a [primitive representation] is used. For example:\n```rust\n #[repr(u8)]\n enum Enum {\n Unit = 3,\n Tuple(u16),\n Struct {\n a: u8,\n b: u16,\n } = 1,\n }\n```\nIf 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.\n```rust\nenum Foo {\n Bar, // 0\n Baz = 123, // 123\n Quux, // 124\n}\n\nlet baz_discriminant = Foo::Baz as u32;\nassert_eq!(baz_discriminant, 123);\n```\nIt is an error when two variants share the same discriminant.\n```rust,compile_fail\nenum SharedDiscriminantError {\n SharedA = 1,\n SharedB = 1,\n}\n\nenum SharedDiscriminantError2 {\n Zero, // 0\n One, // 1\n OneToo = 1, // 1 (collision with previous!)\n}\n```\nIt is also an error to have an unspecified discriminant where the previous discriminant is the maximum value for the size of the discriminant.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Enumerations", "heading_path": ["Enumerations", "Discriminants", "Assigning discriminant values", "Restrictions"], "path": "items/enumerations.md", "url": "https://doc.rust-lang.org/reference/items/enumerations.html#restrictions", "has_code": true, "code_tags": ["rust", "rust,compile_fail"]}} {"id": "reference/items/enumerations.md#restrictions-4", "text": "The Rust Reference › Enumerations › Discriminants › Assigning discriminant values › Restrictions\n\n```rust,compile_fail\n#[repr(u8)]\nenum OverflowingDiscriminantError {\n Max = 255,\n MaxPlusOne, // Would be 256, but that overflows the enum.\n}\n\n#[repr(u8)]\nenum OverflowingDiscriminantError2 {\n MaxMinusOne = 254, // 254\n Max, // 255\n MaxPlusOne, // Would be 256, but that overflows the enum.\n}\n```\nExplicit enum discriminant initializers may not use generic parameters from the enclosing enum.\n```rust,compile_fail\n#[repr(u32)]\nenum E<'a, T, const N: u32> {\n Lifetime(&'a T) = {\n let a: &'a (); // ERROR.\n 1\n },\n Type(T) = {\n let x: T; // ERROR.\n 2\n },\n Const = N, // ERROR.\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Enumerations", "heading_path": ["Enumerations", "Discriminants", "Assigning discriminant values", "Restrictions"], "path": "items/enumerations.md", "url": "https://doc.rust-lang.org/reference/items/enumerations.html#restrictions", "has_code": true, "code_tags": ["rust,compile_fail"]}} {"id": "reference/items/enumerations.md#pointer-casting-5", "text": "The Rust Reference › Enumerations › Discriminants › Accessing discriminant › Pointer casting\n\n[`std::mem::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.\nIf an enumeration is [unit-only] (with no tuple and struct variants), then its discriminant can be directly accessed with a [numeric cast]; e.g.:\n```rust\nenum Enum {\n Foo,\n Bar,\n Baz,\n}\n\nassert_eq!(0, Enum::Foo as isize);\nassert_eq!(1, Enum::Bar as isize);\nassert_eq!(2, Enum::Baz as isize);\n```\n[Field-less enums] can be cast if they do not have explicit discriminants, or where only unit variants are explicit.\n```rust\nenum Fieldless {\n Tuple(),\n Struct{},\n Unit,\n}\n\nassert_eq!(0, Fieldless::Tuple() as isize);\nassert_eq!(1, Fieldless::Struct{} as isize);\nassert_eq!(2, Fieldless::Unit as isize);\n\n#[repr(u8)]\nenum FieldlessWithDiscriminants {\n First = 10,\n Tuple(),\n Second = 20,\n Struct{},\n Unit,\n}\n\nassert_eq!(10, FieldlessWithDiscriminants::First as u8);\nassert_eq!(11, FieldlessWithDiscriminants::Tuple() as u8);\nassert_eq!(20, FieldlessWithDiscriminants::Second as u8);\nassert_eq!(21, FieldlessWithDiscriminants::Struct{} as u8);\nassert_eq!(22, FieldlessWithDiscriminants::Unit as u8);\n```\nIf the enumeration specifies a [primitive representation], then the discriminant may be reliably accessed via unsafe pointer casting:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Enumerations", "heading_path": ["Enumerations", "Discriminants", "Accessing discriminant", "Pointer casting"], "path": "items/enumerations.md", "url": "https://doc.rust-lang.org/reference/items/enumerations.html#pointer-casting", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/enumerations.md#pointer-casting-6", "text": "The Rust Reference › Enumerations › Discriminants › Accessing discriminant › Pointer casting\n\n```rust\n#[repr(u8)]\nenum Enum {\n Unit,\n Tuple(bool),\n Struct{a: bool},\n}\n\nimpl Enum {\n fn discriminant(&self) -> u8 {\n unsafe { *(self as *const Self as *const u8) }\n }\n}\n\nlet unit_like = Enum::Unit;\nlet tuple_like = Enum::Tuple(true);\nlet struct_like = Enum::Struct{a: false};\n\nassert_eq!(0, unit_like.discriminant());\nassert_eq!(1, tuple_like.discriminant());\nassert_eq!(2, struct_like.discriminant());\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Enumerations", "heading_path": ["Enumerations", "Discriminants", "Accessing discriminant", "Pointer casting"], "path": "items/enumerations.md", "url": "https://doc.rust-lang.org/reference/items/enumerations.html#pointer-casting", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/enumerations.md#zero-variant-enums-7", "text": "The Rust Reference › Enumerations › Zero-variant enums\n\nEnums with zero variants are known as *zero-variant enums*. As they have no valid values, they cannot be instantiated.\n```rust\nenum ZeroVariants {}\n```\nZero-variant enums are equivalent to the [never type], but they cannot be coerced into other types.\n```rust,compile_fail\nlet x: ZeroVariants = panic!();\nlet y: u32 = x; // mismatched type error\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Enumerations", "heading_path": ["Enumerations", "Zero-variant enums"], "path": "items/enumerations.md", "url": "https://doc.rust-lang.org/reference/items/enumerations.html#zero-variant-enums", "has_code": true, "code_tags": ["rust", "rust,compile_fail"]}} {"id": "reference/items/enumerations.md#variant-visibility-8", "text": "The Rust Reference › Enumerations › Variant visibility\n\nEnum variants syntactically allow a [Visibility] 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.\n```rust\nmacro_rules! mac_variant {\n ($vis:vis $name:ident) => {\n enum $name {\n $vis Unit,\n\n $vis Tuple(u8, u16),\n\n $vis Struct { f: u8 },\n }\n }\n}\n\n// Empty `vis` is allowed.\nmac_variant! { E }\n\n// This is allowed, since it is removed before being validated.\n#[cfg(false)]\nenum E {\n pub U,\n pub(crate) T(u8),\n pub(super) T { f: String },\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Enumerations", "heading_path": ["Enumerations", "Variant visibility"], "path": "items/enumerations.md", "url": "https://doc.rust-lang.org/reference/items/enumerations.html#variant-visibility", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/unions.md#unions-0", "text": "The Rust Reference › Unions\n\n```grammar,items\nUnion ->\n `union` IDENTIFIER GenericParams? WhereClause? `{` StructFields? `}`\n```\nA union declaration uses the same syntax as a struct declaration, except with `union` in place of `struct`.\nA union declaration defines the given name in the [type namespace] of the module or block where it is located.\n```rust\n#[repr(C)]\nunion MyUnion {\n f1: u32,\n f2: f32,\n}\n```\nThe 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.\nUnion field types are restricted to the following subset of types:\n- `Copy` types\n- References (`&T` and `&mut T` for arbitrary `T`)\n- `ManuallyDrop` (for arbitrary `T`)\n- Tuples and arrays containing only allowed union field types\nThis 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.\nUnions without any fields are not accepted by the compiler, but can be accepted by macros.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Unions", "heading_path": ["Unions"], "path": "items/unions.md", "url": "https://doc.rust-lang.org/reference/items/unions.html#unions", "has_code": true, "code_tags": ["grammar,items", "rust"]}} {"id": "reference/items/unions.md#initialization-of-a-union-1", "text": "The Rust Reference › Unions › Initialization of a union\n\nA 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:\n```rust\nlet u = MyUnion { f1: 1 };\n```\nThe 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:\n```rust\nlet f = unsafe { u.f1 };\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Unions", "heading_path": ["Unions", "Initialization of a union"], "path": "items/unions.md", "url": "https://doc.rust-lang.org/reference/items/unions.html#initialization-of-a-union", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/unions.md#reading-and-writing-union-fields-2", "text": "The Rust Reference › Unions › Reading and writing union fields\n\nUnions 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.\nReading a union field reads the bits of the union at the field's type.\nFields might have a non-zero offset (except when [the C representation] is used); in that case the bits starting at the offset of the fields are read\nIt 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]. For example, reading the value `3` from a field of the [boolean type] is undefined behavior. Effectively, writing to and then reading from a union with [the C representation] is analogous to a [`transmute`] from the type used for writing to the type used for reading.\nConsequently, all reads of union fields have to be placed in `unsafe` blocks:\n```rust\nunsafe {\n let f = u.f1;\n}\n```\nCommonly, code using unions will provide safe wrappers around unsafe union field accesses.\nIn 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.)", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Unions", "heading_path": ["Unions", "Reading and writing union fields"], "path": "items/unions.md", "url": "https://doc.rust-lang.org/reference/items/unions.html#reading-and-writing-union-fields", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/unions.md#pattern-matching-on-unions-3", "text": "The Rust Reference › Unions › Pattern matching on unions\n\nAnother way to access union fields is to use pattern matching.\nPattern matching on union fields uses the same syntax as struct patterns, except that the pattern must specify exactly one field.\nSince pattern matching is like reading the union with a particular field, it has to be placed in `unsafe` blocks as well.\n```rust\nfn f(u: MyUnion) {\n unsafe {\n match u {\n MyUnion { f1: 10 } => { println!(\"ten\"); }\n MyUnion { f2 } => { println!(\"{}\", f2); }\n }\n }\n}\n```\nThe order in which the subpatterns of a pattern are tested is not specified. A union field named in a pattern may be read even when the pattern as a whole does not match. Reading a union field is undefined behavior unless it holds a valid value of its type (see [items.union.fields.validity]). Nothing else in the pattern can be relied on to prevent the read.\nIn particular, when implementing a C-style tagged union, avoid matching the tag and the corresponding union field within a single pattern: the union field may be read even when the tag does not match.\nTo read a union field only when a condition holds, test the condition and read the field in separate steps whose evaluation order is specified. For a C tagged union, match on the tag first and read the union field within the matched arm:\n```rust\n#[repr(u32)]\nenum Tag { I, F }\n\n#[repr(C)]\nunion U {\n i: i32,\n f: f32,\n}\n\n#[repr(C)]\nstruct Value {\n tag: Tag,\n u: U,\n}\n\nfn is_zero(v: Value) -> bool {\n match v.tag {\n Tag::I => unsafe { v.u.i == 0 },\n Tag::F => unsafe { v.u.f == 0.0 },\n }\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Unions", "heading_path": ["Unions", "Pattern matching on unions"], "path": "items/unions.md", "url": "https://doc.rust-lang.org/reference/items/unions.html#pattern-matching-on-unions", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/unions.md#references-to-union-fields-4", "text": "The Rust Reference › Unions › References to union fields\n\nSince union fields share common storage, gaining write access to one field of a union can give write access to all its remaining fields.\nBorrow 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.\n```rust,compile_fail\n// ERROR: cannot borrow `u` (via `u.f2`) as mutable more than once at a time\nfn test() {\n let mut u = MyUnion { f1: 1 };\n unsafe {\n let b1 = &mut u.f1;\n// ---- first mutable borrow occurs here (via `u.f1`)\n let b2 = &mut u.f2;\n// ^^^^ second mutable borrow occurs here (via `u.f2`)\n *b1 = 5;\n }\n// - first borrow ends here\n assert_eq!(unsafe { u.f1 }, 5);\n}\n```\nAs 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).", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Unions", "heading_path": ["Unions", "References to union fields"], "path": "items/unions.md", "url": "https://doc.rust-lang.org/reference/items/unions.html#references-to-union-fields", "has_code": true, "code_tags": ["rust,compile_fail"]}} {"id": "reference/items/constant-items.md#constant-items-0", "text": "The Rust Reference › Constant items\n\n```grammar,items\nConstantItem ->\n `const` ( IDENTIFIER | `_` ) `:` Type ( `=` Expression )? `;`\n```\nA *constant item* is an optionally named _[constant value]_ which is not associated with a specific memory location in the program.\nConstants are essentially inlined wherever they are used, meaning that they are copied directly into the relevant context when used. This includes use of constants from external crates, and non-[`Copy`] types. References to the same constant are not necessarily guaranteed to refer to the same memory address.\nThe constant declaration defines the constant value in the [value namespace] of the module or block where it is located.\nConstants must be explicitly typed. The type must have a `'static` lifetime: any references in the initializer must have `'static` lifetimes. References in the type of a constant default to `'static` lifetime; see [static lifetime elision].\nA reference to a constant will have `'static` lifetime if the constant value is eligible for [promotion]; otherwise, a temporary will be created.\n```rust\nconst BIT1: u32 = 1 << 0;\nconst BIT2: u32 = 1 << 1;\n\nconst BITS: [u32; 2] = [BIT1, BIT2];\nconst STRING: &'static str = \"bitstring\";\n\nstruct BitsNStrings<'a> {\n mybits: [u32; 2],\n mystring: &'a str,\n}\n\nconst BITS_N_STRINGS: BitsNStrings<'static> = BitsNStrings {\n mybits: BITS,\n mystring: STRING,\n};\n```\nThe constant expression may only be omitted in a [trait definition].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Constant items", "heading_path": ["Constant items"], "path": "items/constant-items.md", "url": "https://doc.rust-lang.org/reference/items/constant-items.html#constant-items", "has_code": true, "code_tags": ["grammar,items", "rust"]}} {"id": "reference/items/constant-items.md#constants-with-destructors-1", "text": "The Rust Reference › Constant items › Constants with destructors\n\nConstants can contain destructors. Destructors are run when the value goes out of scope.\n```rust\nstruct TypeWithDestructor(i32);\n\nimpl Drop for TypeWithDestructor {\n fn drop(&mut self) {\n println!(\"Dropped. Held {}.\", self.0);\n }\n}\n\nconst ZERO_WITH_DESTRUCTOR: TypeWithDestructor = TypeWithDestructor(0);\n\nfn create_and_drop_zero_with_destructor() {\n let x = ZERO_WITH_DESTRUCTOR;\n // x gets dropped at end of function, calling drop.\n // prints \"Dropped. Held 0.\".\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Constant items", "heading_path": ["Constant items", "Constants with destructors"], "path": "items/constant-items.md", "url": "https://doc.rust-lang.org/reference/items/constant-items.html#constants-with-destructors", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/constant-items.md#unnamed-constant-2", "text": "The Rust Reference › Constant items › Unnamed constant\n\nUnlike an [associated constant], a [free] constant may be unnamed by using an underscore instead of the name. For example:\n```rust\nconst _: () = { struct _SameNameTwice; };\n\n// OK although it is the same name as above:\nconst _: () = { struct _SameNameTwice; };\n```\nAs with [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:\n```rust\nmacro_rules! m {\n ($item: item) => { $item $item }\n}\n\nm!(const _: () = (););\n// This expands to:\n// const _: () = ();\n// const _: () = ();\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Constant items", "heading_path": ["Constant items", "Unnamed constant"], "path": "items/constant-items.md", "url": "https://doc.rust-lang.org/reference/items/constant-items.html#unnamed-constant", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/constant-items.md#evaluation-3", "text": "The Rust Reference › Constant items › Evaluation\n\nFree constants are always evaluated at compile-time to surface panics. This happens even within an unused function:\n```rust,compile_fail\n// Compile-time panic\nconst PANIC: () = std::unimplemented!();\n\nfn unused_generic_function() {\n // A failing compile-time assertion\n const _: () = assert!(usize::BITS == 0);\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Constant items", "heading_path": ["Constant items", "Evaluation"], "path": "items/constant-items.md", "url": "https://doc.rust-lang.org/reference/items/constant-items.html#evaluation", "has_code": true, "code_tags": ["rust,compile_fail"]}} {"id": "reference/items/static-items.md#static-items-0", "text": "The Rust Reference › Static items\n\n```grammar,items\nStaticItem ->\n ItemSafety?[^extern-safety] `static` `mut`? IDENTIFIER `:` Type ( `=` Expression )? `;`\n```\n[^extern-safety]: The `safe` and `unsafe` function qualifiers are only allowed semantically within `extern` blocks.\nA *static item* is similar to a [constant], except that it represents an allocation in the program that is initialized with the initializer expression. All references and raw pointers to the static refer to the same allocation.\nStatic items have the `static` lifetime, which outlives all other lifetimes in a Rust program. Static items do not call [`drop`] at the end of the program.\nIf the `static` has a size of at least 1 byte, this allocation is disjoint from all other such `static` allocations as well as heap allocations and stack-allocated variables. However, the storage of immutable `static` items can overlap with allocations that do not themselves have a unique address, such as [promoteds] and `const` items.\nThe static declaration defines a static value in the [value namespace] of the module or block where it is located.\nThe static initializer is a [constant expression] evaluated at compile time. Static initializers may refer to and read from other statics. When reading from mutable statics, they read the initial value of that static.\nNon-`mut` static items that contain a type that is not [interior mutable] may be placed in read-only memory.\nAll access to a static is safe, but there are a number of restrictions on statics:\n* The type must have the `Sync` trait bound to allow thread-safe access.\nThe initializer expression must be omitted in an [external block], and must be provided for free static items.\nThe `safe` and `unsafe` qualifiers are semantically only allowed when used in an [external block].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Static items", "heading_path": ["Static items"], "path": "items/static-items.md", "url": "https://doc.rust-lang.org/reference/items/static-items.html#static-items", "has_code": true, "code_tags": ["grammar,items"]}} {"id": "reference/items/static-items.md#statics--generics-1", "text": "The Rust Reference › Static items › Statics & generics\n\nA 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.\nThis code:\n```rust\nuse std::sync::atomic::{AtomicUsize, Ordering};\n\ntrait Tr {\n fn default_impl() {\n static COUNTER: AtomicUsize = AtomicUsize::new(0);\n println!(\"default_impl: counter was {}\", COUNTER.fetch_add(1, Ordering::Relaxed));\n }\n\n fn blanket_impl();\n}\n\nstruct Ty1 {}\nstruct Ty2 {}\n\nimpl Tr for T {\n fn blanket_impl() {\n static COUNTER: AtomicUsize = AtomicUsize::new(0);\n println!(\"blanket_impl: counter was {}\", COUNTER.fetch_add(1, Ordering::Relaxed));\n }\n}\n\nfn main() {\n ::default_impl();\n ::default_impl();\n ::blanket_impl();\n ::blanket_impl();\n}\n```\nprints\n```text\ndefault_impl: counter was 0\ndefault_impl: counter was 1\nblanket_impl: counter was 0\nblanket_impl: counter was 1\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Static items", "heading_path": ["Static items", "Statics & generics"], "path": "items/static-items.md", "url": "https://doc.rust-lang.org/reference/items/static-items.html#statics--generics", "has_code": true, "code_tags": ["rust", "text"]}} {"id": "reference/items/static-items.md#mutable-statics-2", "text": "The Rust Reference › Static items › Mutable statics\n\nIf 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.\nFor 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.\nMutable 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.\n```rust\n\nstatic mut LEVELS: u32 = 0;\n\n// This violates the idea of no shared state, and this doesn't internally\n// protect against races, so this function is `unsafe`\nunsafe fn bump_levels_unsafe() -> u32 {\n unsafe {\n let ret = LEVELS;\n LEVELS += 1;\n return ret;\n }\n}\n\n// As an alternative to `bump_levels_unsafe`, this function is safe, assuming\n// that we have an atomic_add function which returns the old value. This\n// function is safe only if no other code accesses the static in a non-atomic\n// fashion. If such accesses are possible (such as in `bump_levels_unsafe`),\n// then this would need to be `unsafe` to indicate to the caller that they\n// must still guard against concurrent access.\nfn bump_levels_safe() -> u32 {\n unsafe {\n return atomic_add(&raw mut LEVELS, 1);\n }\n}\n```\nMutable statics have the same restrictions as normal statics, except that the type does not have to implement the `Sync` trait.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Static items", "heading_path": ["Static items", "Mutable statics"], "path": "items/static-items.md", "url": "https://doc.rust-lang.org/reference/items/static-items.html#mutable-statics", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/static-items.md#using-statics-or-consts-3", "text": "The Rust Reference › Static items › Using statics or consts\n\nIt 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:\n* Large amounts of data are being stored.\n* The single-address property of statics is required.\n* Interior mutability is required.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Static items", "heading_path": ["Static items", "Using statics or consts"], "path": "items/static-items.md", "url": "https://doc.rust-lang.org/reference/items/static-items.html#using-statics-or-consts", "has_code": false, "code_tags": []}} {"id": "reference/items/traits.md#traits-0", "text": "The Rust Reference › Traits\n\n```grammar,items\nTrait ->\n `unsafe`? `trait` IDENTIFIER GenericParams? ( `:` Bounds? )? WhereClause?\n `{`\n InnerAttribute*\n AssociatedItem*\n `}`\n```\nA _trait_ describes an abstract interface that types can implement. This interface consists of [associated items], which come in three varieties:\n- functions\n- types\n- constants\nThe trait declaration defines a trait in the [type namespace] of the module or block where it is located.\nAssociated items are defined as members of the trait within their respective namespaces. Associated types are defined in the type namespace. Associated constants and associated functions are defined in the value namespace.\nAll 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.\nTraits are implemented for specific types through separate [implementations].\nTrait 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 equal 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.\n```rust\n// Examples of associated trait items with and without definitions.\ntrait Example {\n const CONST_NO_DEFAULT: i32;\n const CONST_WITH_DEFAULT: i32 = 99;\n type TypeNoDefault;\n fn method_without_default(&self);\n fn method_with_default(&self) {}\n}\n```\nTrait functions are not allowed to be [`const`].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Traits", "heading_path": ["Traits"], "path": "items/traits.md", "url": "https://doc.rust-lang.org/reference/items/traits.html#traits", "has_code": true, "code_tags": ["grammar,items", "rust"]}} {"id": "reference/items/traits.md#trait-bounds-1", "text": "The Rust Reference › Traits › Trait bounds\n\nGeneric items may use traits as [bounds] on their type parameters.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Traits", "heading_path": ["Traits", "Trait bounds"], "path": "items/traits.md", "url": "https://doc.rust-lang.org/reference/items/traits.html#trait-bounds", "has_code": false, "code_tags": []}} {"id": "reference/items/traits.md#generic-traits-2", "text": "The Rust Reference › Traits › Generic traits\n\nType 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].\n```rust\ntrait Seq {\n fn len(&self) -> u32;\n fn elt_at(&self, n: u32) -> T;\n fn iter(&self, f: F) where F: Fn(T);\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Traits", "heading_path": ["Traits", "Generic traits"], "path": "items/traits.md", "url": "https://doc.rust-lang.org/reference/items/traits.html#generic-traits", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/traits.md#dyn-compatibility-3", "text": "The Rust Reference › Traits › Dyn compatibility\n\nA dyn-compatible trait can be the base trait of a [trait object]. A trait is *dyn compatible* if it has the following qualities:\n* All [supertraits] must also be dyn compatible.\n* `Sized` must not be a supertrait. In other words, it must not require `Self: Sized`.\n* It must not have any associated constants.\n* It must not have any associated types with generics.\n* All associated functions must either be dispatchable from a trait object or be explicitly non-dispatchable:\n * Dispatchable functions must:\n * Not have any type parameters (although lifetime parameters are allowed).\n * Be a [method] that does not use `Self` except in the type of the receiver.\n * Have a receiver with one of the following types:\n * `&Self` (i.e. `&self`)\n * `&mut Self` (i.e `&mut self`)\n * [`Box`]\n * [`Rc`]\n * [`Arc`]\n * [`Pin

`] where `P` is one of the types above\n * Not have an opaque return type; that is,\n * Not be an `async fn` (which has a hidden `Future` type).\n * Not have a return position `impl Trait` type (`fn example(&self) -> impl Trait`).\n * Not have a `where Self: Sized` bound (receiver type of `Self` (i.e. `self`) implies this).\n * Explicitly non-dispatchable functions require:\n * Have a `where Self: Sized` bound (receiver type of `Self` (i.e. `self`) implies this).\n* The [`AsyncFn`], [`AsyncFnMut`], and [`AsyncFnOnce`] traits are not dyn-compatible.\nThis concept was formerly known as *object safety*.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Traits", "heading_path": ["Traits", "Dyn compatibility"], "path": "items/traits.md", "url": "https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility", "has_code": false, "code_tags": []}} {"id": "reference/items/traits.md#dyn-compatibility-4", "text": "The Rust Reference › Traits › Dyn compatibility\n\n```rust\n// Examples of dyn compatible methods.\ntrait TraitMethods {\n fn by_ref(self: &Self) {}\n fn by_ref_mut(self: &mut Self) {}\n fn by_box(self: Box) {}\n fn by_rc(self: Rc) {}\n fn by_arc(self: Arc) {}\n fn by_pin(self: Pin<&Self>) {}\n fn with_lifetime<'a>(self: &'a Self) {}\n fn nested_pin(self: Pin>) {}\n}\n```\n```rust,compile_fail\n// This trait is dyn compatible, but these methods cannot be dispatched on a trait object.\ntrait NonDispatchable {\n // Non-methods cannot be dispatched.\n fn foo() where Self: Sized {}\n // Self type isn't known until runtime.\n fn returns(&self) -> Self where Self: Sized;\n // `other` may be a different concrete type of the receiver.\n fn param(&self, other: Self) where Self: Sized {}\n // Generics are not compatible with vtables.\n fn typed(&self, x: T) where Self: Sized {}\n}\n\nstruct S;\nimpl NonDispatchable for S {\n fn returns(&self) -> Self where Self: Sized { S }\n}\nlet obj: Box = Box::new(S);\nobj.returns(); // ERROR: cannot call with Self return\nobj.param(S); // ERROR: cannot call with Self parameter\nobj.typed(1); // ERROR: cannot call with generic type\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Traits", "heading_path": ["Traits", "Dyn compatibility"], "path": "items/traits.md", "url": "https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility", "has_code": true, "code_tags": ["rust", "rust,compile_fail"]}} {"id": "reference/items/traits.md#dyn-compatibility-5", "text": "The Rust Reference › Traits › Dyn compatibility\n\n```rust,compile_fail\n// Examples of dyn-incompatible traits.\ntrait DynIncompatible {\n const CONST: i32 = 1; // ERROR: cannot have associated const\n\n fn foo() {} // ERROR: associated function without Sized\n fn returns(&self) -> Self; // ERROR: Self in return type\n fn typed(&self, x: T) {} // ERROR: has generic type parameters\n fn nested(self: Rc>) {} // ERROR: nested receiver cannot be dispatched on\n}\n\nstruct S;\nimpl DynIncompatible for S {\n fn returns(&self) -> Self { S }\n}\nlet obj: Box = Box::new(S); // ERROR\n```\n```rust,compile_fail\n// `Self: Sized` traits are dyn-incompatible.\ntrait TraitWithSize where Self: Sized {}\n\nstruct S;\nimpl TraitWithSize for S {}\nlet obj: Box = Box::new(S); // ERROR\n```\n```rust,compile_fail\n// Dyn-incompatible if `Self` is a type argument.\ntrait Super {}\ntrait WithSelf: Super where Self: Sized {}\n\nstruct S;\nimpl Super for S {}\nimpl WithSelf for S {}\nlet obj: Box = Box::new(S); // ERROR: cannot use `Self` type parameter\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Traits", "heading_path": ["Traits", "Dyn compatibility"], "path": "items/traits.md", "url": "https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility", "has_code": true, "code_tags": ["rust,compile_fail"]}} {"id": "reference/items/traits.md#supertraits-6", "text": "The Rust Reference › Traits › Supertraits\n\n**Supertraits** are traits that are required to be implemented for a type to implement a specific trait. Furthermore, anywhere a generic or [trait object] is bounded by a trait, it has access to the associated items of its supertraits.\nSupertraits 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.\nThe trait with a supertrait is called a **subtrait** of its supertrait.\nThe following is an example of declaring `Shape` to be a supertrait of `Circle`.\n```rust\ntrait Shape { fn area(&self) -> f64; }\ntrait Circle: Shape { fn radius(&self) -> f64; }\n```\nAnd the following is the same example, except using [where clauses].\n```rust\ntrait Shape { fn area(&self) -> f64; }\ntrait Circle where Self: Shape { fn radius(&self) -> f64; }\n```\nThis next example gives `radius` a default implementation using the `area` function from `Shape`.\n```rust\ntrait Circle where Self: Shape {\n fn radius(&self) -> f64 {\n // A = pi * r^2\n // so algebraically,\n // r = sqrt(A / pi)\n (self.area() / std::f64::consts::PI).sqrt()\n }\n}\n```\nThis next example calls a supertrait method on a generic parameter.\n```rust\nfn print_area_and_radius(c: C) {\n // Here we call the area method from the supertrait `Shape` of `Circle`.\n println!(\"Area: {}\", c.area());\n println!(\"Radius: {}\", c.radius());\n}\n```\nSimilarly, here is an example of calling supertrait methods on trait objects.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Traits", "heading_path": ["Traits", "Supertraits"], "path": "items/traits.md", "url": "https://doc.rust-lang.org/reference/items/traits.html#supertraits", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/traits.md#supertraits-7", "text": "The Rust Reference › Traits › Supertraits\n\n```rust\nlet circle = Box::new(circle) as Box;\nlet nonsense = circle.radius() * circle.area();\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Traits", "heading_path": ["Traits", "Supertraits"], "path": "items/traits.md", "url": "https://doc.rust-lang.org/reference/items/traits.html#supertraits", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/traits.md#unsafe-traits-8", "text": "The Rust Reference › Traits › Unsafe traits\n\nTraits items that begin with the `unsafe` keyword indicate that *implementing* the trait may be [unsafe]. It is safe to use a correctly implemented unsafe trait. The [trait implementation] must also begin with the `unsafe` keyword.\n[`Sync`] and [`Send`] are examples of unsafe traits.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Traits", "heading_path": ["Traits", "Unsafe traits"], "path": "items/traits.md", "url": "https://doc.rust-lang.org/reference/items/traits.html#unsafe-traits", "has_code": false, "code_tags": []}} {"id": "reference/items/traits.md#parameter-patterns-9", "text": "The Rust Reference › Traits › Parameter patterns\n\nParameters in associated functions without a body only allow [IDENTIFIER] or `_` wild card patterns, as well as the form allowed by [SelfParam]. `mut` [IDENTIFIER] is currently allowed, but it is deprecated and will become a hard error in the future.\n```rust\ntrait T {\n fn f1(&self);\n fn f2(x: Self, _: i32);\n}\n```\n```rust,compile_fail,E0642\ntrait T {\n fn f2(&x: &i32); // ERROR: patterns aren't allowed in functions without bodies\n}\n```\nParameters in associated functions with a body only allow irrefutable patterns.\n```rust\ntrait T {\n fn f1((a, b): (i32, i32)) {} // OK: is irrefutable\n}\n```\n```rust,compile_fail,E0005\ntrait T {\n fn f1(123: i32) {} // ERROR: pattern is refutable\n fn f2(Some(x): Option) {} // ERROR: pattern is refutable\n}\n```\n[!EDITION-2018]\nPrior to the 2018 edition, the pattern for an associated function parameter is optional:\n```rust,edition2015\n// 2015 Edition\ntrait T {\n fn f(i32); // OK: parameter identifiers are not required\n}\n```\nBeginning in the 2018 edition, patterns are no longer optional.\n[!EDITION-2018]\nPrior to the 2018 edition, parameters in associated functions with a body are limited to the following kinds of patterns:\n* [IDENTIFIER]\n* `mut` [IDENTIFIER]\n* `_`\n* `&` [IDENTIFIER]\n* `&&` [IDENTIFIER]", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Traits", "heading_path": ["Traits", "Parameter patterns"], "path": "items/traits.md", "url": "https://doc.rust-lang.org/reference/items/traits.html#parameter-patterns", "has_code": true, "code_tags": ["rust", "rust,compile_fail,E0005", "rust,compile_fail,E0642", "rust,edition2015"]}} {"id": "reference/items/traits.md#parameter-patterns-10", "text": "The Rust Reference › Traits › Parameter patterns\n\n```rust,edition2015,compile_fail,E0642\n// 2015 Edition\ntrait T {\n fn f1((a, b): (i32, i32)) {} // ERROR: pattern not allowed\n}\n```\nBeginning in 2018, all irrefutable patterns are allowed as described in [items.traits.params.patterns-with-body].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Traits", "heading_path": ["Traits", "Parameter patterns"], "path": "items/traits.md", "url": "https://doc.rust-lang.org/reference/items/traits.html#parameter-patterns", "has_code": true, "code_tags": ["rust,edition2015,compile_fail,E0642"]}} {"id": "reference/items/traits.md#item-visibility-11", "text": "The Rust Reference › Traits › Item visibility\n\nTrait items syntactically allow a [Visibility] 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.\n```rust\nmacro_rules! create_method {\n ($vis:vis $name:ident) => {\n $vis fn $name(&self) {}\n };\n}\n\ntrait T1 {\n // Empty `vis` is allowed.\n create_method! { method_of_t1 }\n}\n\nstruct S;\n\nimpl S {\n // Visibility is allowed here.\n create_method! { pub method_of_s }\n}\n\nimpl T1 for S {}\n\nfn main() {\n let s = S;\n s.method_of_t1();\n s.method_of_s();\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Traits", "heading_path": ["Traits", "Item visibility"], "path": "items/traits.md", "url": "https://doc.rust-lang.org/reference/items/traits.html#item-visibility", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/implementations.md#implementations-0", "text": "The Rust Reference › Implementations\n\n```grammar,items\nImplementation -> InherentImpl | TraitImpl\n\nInherentImpl ->\n `impl` GenericParams? Type WhereClause? `{`\n InnerAttribute*\n AssociatedItem*\n `}`\n\nTraitImpl ->\n `unsafe`? `impl` GenericParams? `!`? TypePath `for` Type\n WhereClause?\n `{`\n InnerAttribute*\n AssociatedItem*\n `}`\n```\nAn _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.\nThere are two types of implementations:\n- inherent implementations\n- [trait] implementations", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Implementations", "heading_path": ["Implementations"], "path": "items/implementations.md", "url": "https://doc.rust-lang.org/reference/items/implementations.html#implementations", "has_code": true, "code_tags": ["grammar,items"]}} {"id": "reference/items/implementations.md#inherent-implementations-1", "text": "The Rust Reference › Implementations › Inherent implementations\n\nAn 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.\nThe nominal type is called the _implementing type_ and the associable items are the _associated items_ to the implementing type.\nInherent implementations associate the contained items to the implementing type.\nInherent implementations can contain [associated functions] (including [methods]) and [associated constants].\nThey cannot contain associated type aliases.\nThe [path] to an associated item is any path to the implementing type, followed by the associated item's identifier as the final path component.\nA type can also have multiple inherent implementations. An implementing type must be defined within the same crate as the original type definition.\n``` rust\npub mod color {\n pub struct Color(pub u8, pub u8, pub u8);\n\n impl Color {\n pub const WHITE: Color = Color(255, 255, 255);\n }\n}\n\nmod values {\n use super::color::Color;\n impl Color {\n pub fn red() -> Color {\n Color(255, 0, 0)\n }\n }\n}\n\npub use self::color::Color;\nfn main() {\n // Actual path to the implementing type and impl in the same module.\n color::Color::WHITE;\n\n // Impl blocks in different modules are still accessed through a path to the type.\n color::Color::red();\n\n // Re-exported paths to the implementing type also work.\n Color::red();\n\n // Does not work, because use in `values` is not pub.\n // values::Color::red();\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Implementations", "heading_path": ["Implementations", "Inherent implementations"], "path": "items/implementations.md", "url": "https://doc.rust-lang.org/reference/items/implementations.html#inherent-implementations", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/implementations.md#trait-implementations-2", "text": "The Rust Reference › Implementations › Trait implementations\n\nA _trait implementation_ is defined like an inherent implementation except that the optional generic type declarations are followed by a [trait], followed by the keyword `for`, followed by a path to a nominal type.\nThe trait is known as the _implemented trait_. The implementing type implements the implemented trait.\nA 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.\nThe 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.\n[Unsafe traits] require the trait implementation to begin with the `unsafe` keyword.\n```rust\nstruct Circle {\n radius: f64,\n center: Point,\n}\n\nimpl Copy for Circle {}\n\nimpl Clone for Circle {\n fn clone(&self) -> Circle { *self }\n}\n\nimpl Shape for Circle {\n fn draw(&self, s: Surface) { do_draw_circle(s, *self); }\n fn bounding_box(&self) -> BoundingBox {\n let r = self.radius;\n BoundingBox {\n x: self.center.x - r,\n y: self.center.y - r,\n width: 2.0 * r,\n height: 2.0 * r,\n }\n }\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Implementations", "heading_path": ["Implementations", "Trait implementations"], "path": "items/implementations.md", "url": "https://doc.rust-lang.org/reference/items/implementations.html#trait-implementations", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/implementations.md#orphan-rules-3", "text": "The Rust Reference › Implementations › Trait implementations › Trait implementation coherence › Orphan rules\n\nA trait implementation is considered incoherent if either the orphan rules check fails or there are overlapping implementation instances.\nTwo 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. \nThe *orphan rule* states that a trait implementation is only allowed if either the trait or at least one of the types in the implementation is defined in the current crate. It prevents conflicting trait implementations across different crates and is key to ensuring coherence.\nAn orphan implementation is one that implements a foreign trait for a foreign type. If these were freely allowed, two crates could implement the same trait for the same type in incompatible ways, creating a situation where adding or updating a dependency could break compilation due to conflicting implementations.\nThe orphan rule enables library authors to add new implementations to their traits without fear that they'll break downstream code. Without these restrictions, a library couldn't add an implementation like `impl MyTrait for T` without potentially conflicting with downstream implementations.\nGiven `impl Trait for T0`, an `impl` is valid only if at least one of the following is true:\n- `Trait` is a [local trait]\n- All of\n - At least one of the types `T0..=Tn` must be a [local type]. Let `Ti` be the first such type.\n - No [uncovered type] parameters `P1..=Pn` may appear in `T0..Ti` (excluding `Ti`)\nOnly the appearance of *uncovered* type parameters is restricted.\nNote that for the purposes of coherence, [fundamental types] are special. The `T` in `Box` is not considered covered, and `Box` is considered local.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Implementations", "heading_path": ["Implementations", "Trait implementations", "Trait implementation coherence", "Orphan rules"], "path": "items/implementations.md", "url": "https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules", "has_code": false, "code_tags": []}} {"id": "reference/items/implementations.md#generic-implementations-4", "text": "The Rust Reference › Implementations › Generic implementations\n\nAn implementation can take [generic parameters], which can be used in the rest of the implementation. Implementation parameters are written directly after the `impl` keyword.\n```rust\nimpl Seq for Vec {\n /* ... */\n}\nimpl Seq for u32 {\n /* Treat the integer as a sequence of bits */\n}\n```\nGeneric parameters *constrain* an implementation if the parameter appears at least once in one of:\n* The implemented trait, if it has one\n* The implementing type\n* As an [associated type] in the [bounds] of a type that contains another parameter that constrains the implementation\nType and const parameters must always constrain the implementation. Lifetimes must constrain the implementation if the lifetime is used in an associated type.\nExamples of constraining situations:\n```rust\n// T constrains by being an argument to GenericTrait.\nimpl GenericTrait for i32 { /* ... */ }\n\n// T constrains by being an argument to GenericStruct\nimpl Trait for GenericStruct { /* ... */ }\n\n// Likewise, N constrains by being an argument to ConstGenericStruct\nimpl Trait for ConstGenericStruct { /* ... */ }\n\n// T constrains by being in an associated type in a bound for type `U` which is\n// itself a generic parameter constraining the trait.\nimpl GenericTrait for u32 where U: HasAssocType { /* ... */ }\n\n// Like previous, except the type is `(U, isize)`. `U` appears inside the type\n// that includes `T`, and is not the type itself.\nimpl GenericStruct where (U, isize): HasAssocType { /* ... */ }\n```\nExamples of non-constraining situations:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Implementations", "heading_path": ["Implementations", "Generic implementations"], "path": "items/implementations.md", "url": "https://doc.rust-lang.org/reference/items/implementations.html#generic-implementations", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/implementations.md#generic-implementations-5", "text": "The Rust Reference › Implementations › Generic implementations\n\n```rust,compile_fail\n// The rest of these are errors, since they have type or const parameters that\n// do not constrain.\n\n// T does not constrain since it does not appear at all.\nimpl Struct { /* ... */ }\n\n// N does not constrain for the same reason.\nimpl Struct { /* ... */ }\n\n// Usage of T inside the implementation does not constrain the impl.\nimpl Struct {\n fn uses_t(t: &T) { /* ... */ }\n}\n\n// T is used as an associated type in the bounds for U, but U does not constrain.\nimpl Struct where U: HasAssocType { /* ... */ }\n\n// T is used in the bounds, but not as an associated type, so it does not constrain.\nimpl GenericTrait for u32 where U: GenericTrait {}\n```\nExample of an allowed unconstraining lifetime parameter:\n```rust\nimpl<'a> Struct {}\n```\nExample of a disallowed unconstraining lifetime parameter:\n```rust,compile_fail\nimpl<'a> HasAssocType for Struct {\n type Ty = &'a Struct;\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Implementations", "heading_path": ["Implementations", "Generic implementations"], "path": "items/implementations.md", "url": "https://doc.rust-lang.org/reference/items/implementations.html#generic-implementations", "has_code": true, "code_tags": ["rust", "rust,compile_fail"]}} {"id": "reference/items/implementations.md#attributes-on-implementations-6", "text": "The Rust Reference › Implementations › Attributes on implementations\n\nImplementations may contain outer [attributes] before the `impl` keyword and inner [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`], [`deprecated`], [`doc`], and [the lint check attributes].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Implementations", "heading_path": ["Implementations", "Attributes on implementations"], "path": "items/implementations.md", "url": "https://doc.rust-lang.org/reference/items/implementations.html#attributes-on-implementations", "has_code": false, "code_tags": []}} {"id": "reference/items/external-blocks.md#external-blocks-0", "text": "The Rust Reference › External blocks\n\n```grammar,items\nExternBlock ->\n `unsafe`?[^unsafe-2024] `extern` Abi? `{`\n InnerAttribute*\n ExternalItem*\n `}`\n\nExternalItem ->\n OuterAttribute* (\n MacroInvocationSemi\n | Visibility? StaticItem\n | Visibility? Function\n )\n```\n[^unsafe-2024]: Starting with the 2024 Edition, the `unsafe` keyword is required semantically.\nExternal 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.\nTwo kinds of item _declarations_ are allowed in external blocks: [functions] and [statics].\nCalling unsafe functions or accessing unsafe statics that are declared in external blocks is only allowed in an [`unsafe` context].\nThe external block defines its functions and statics in the [value namespace] of the module or block where it is located.\nThe `unsafe` keyword is semantically required to appear before the `extern` keyword on external blocks.\n[!EDITION-2024]\nPrior to the 2024 edition, the `unsafe` keyword is optional. The `safe` and `unsafe` item qualifiers are only allowed if the external block itself is marked as `unsafe`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "External blocks", "heading_path": ["External blocks"], "path": "items/external-blocks.md", "url": "https://doc.rust-lang.org/reference/items/external-blocks.html#external-blocks", "has_code": true, "code_tags": ["grammar,items"]}} {"id": "reference/items/external-blocks.md#functions-1", "text": "The Rust Reference › External blocks › Functions\n\nFunctions 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.\nPatterns are not allowed in parameters, only [IDENTIFIER] or `_` may be used.\nThe `safe` and `unsafe` function qualifiers are allowed, but other function qualifiers (e.g. `const`, `async`, `extern`) are not.\nFunctions 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.\nA function declared in an extern block is implicitly `unsafe` unless the `safe` function qualifier is present.\nWhen coerced to a function pointer, a function declared in an extern block has type `for<'l1, ..., 'lm> extern \"abi\" 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "External blocks", "heading_path": ["External blocks", "Functions"], "path": "items/external-blocks.md", "url": "https://doc.rust-lang.org/reference/items/external-blocks.html#functions", "has_code": false, "code_tags": []}} {"id": "reference/items/external-blocks.md#statics-2", "text": "The Rust Reference › External blocks › Statics\n\nStatics within external blocks are declared in the same way as [statics] outside of external blocks, except that they do not have an expression initializing their value.\nUnless a static item declared in an extern block is qualified as `safe`, it is `unsafe` to access that item, 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.\nExtern statics can be either immutable or mutable just like [statics] outside of external blocks.\nAn 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. Once Rust code runs, mutating an immutable static (from inside or outside Rust) is UB, except if the mutation happens to bytes inside of an `UnsafeCell`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "External blocks", "heading_path": ["External blocks", "Statics"], "path": "items/external-blocks.md", "url": "https://doc.rust-lang.org/reference/items/external-blocks.html#statics", "has_code": false, "code_tags": []}} {"id": "reference/items/external-blocks.md#abi-3", "text": "The Rust Reference › External blocks › ABI\n\nThe `extern` keyword can be followed by an optional [ABI] string. The ABI specifies the calling convention of the functions in the block. The calling convention defines a low-level interface for functions, such as how arguments are placed in registers or on the stack, how return values are passed, and who is responsible for cleaning up the stack.\n```rust\n// Interface to the Windows API.\nunsafe extern \"system\" { /* ... */ }\n```\nIf the ABI string is not specified, it defaults to `\"C\"`.\nThe `extern` syntax without an explicit ABI is being phased out, so it's better to always write the ABI explicitly.\nFor more details, see Rust issue #134986.\nThe following ABI strings are supported on all platforms:\n* `unsafe extern \"Rust\"` --- The native calling convention for Rust functions and closures. This is the default when a function is declared without using [`extern fn`]. The Rust ABI offers no stability guarantees.\n* `unsafe extern \"C\"` --- The \"C\" ABI matches the default ABI chosen by the dominant C compiler for the target.\n* `unsafe extern \"system\"` --- This is equivalent to `extern \"C\"` except on Windows x86_32 where it is equivalent to `\"stdcall\"` for non-variadic functions, and equivalent to `\"C\"` for variadic functions.\nAs the correct underlying ABI on Windows is target-specific, it's best to use `extern \"system\"` when attempting to link Windows API functions that don't use an explicitly defined ABI.\n* `extern \"C-unwind\"` and `extern \"system-unwind\"` --- Identical to `\"C\"` and `\"system\"`, respectively, but with different behavior when the callee unwinds (by panicking or throwing a C++ style exception).", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "External blocks", "heading_path": ["External blocks", "ABI"], "path": "items/external-blocks.md", "url": "https://doc.rust-lang.org/reference/items/external-blocks.html#abi", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/external-blocks.md#abi-4", "text": "The Rust Reference › External blocks › ABI\n\nThere are also some platform-specific ABI strings:\n* `unsafe extern \"cdecl\"` --- The calling convention typically used with x86_32 C code.\n * Only available on x86_32 targets.\n * Corresponds to MSVC's `__cdecl` and GCC and clang's `__attribute__((cdecl))`.\nFor details, see:\n- \n- \n* `unsafe extern \"stdcall\"` --- The calling convention typically used by the [Win32 API] on x86_32.\n * Only available on x86_32 targets.\n * Corresponds to MSVC's `__stdcall` and GCC and clang's `__attribute__((stdcall))`.\nFor details, see:\n- \n- \n* `unsafe extern \"win64\"` --- The Windows x64 ABI.\n * Only available on x86_64 targets.\n * \"win64\" is the same as the \"C\" ABI on Windows x86_64 targets.\n * Corresponds to GCC and clang's `__attribute__((ms_abi))`.\nFor details, see:\n- \n- ", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "External blocks", "heading_path": ["External blocks", "ABI"], "path": "items/external-blocks.md", "url": "https://doc.rust-lang.org/reference/items/external-blocks.html#abi", "has_code": false, "code_tags": []}} {"id": "reference/items/external-blocks.md#abi-5", "text": "The Rust Reference › External blocks › ABI\n\n* `unsafe extern \"sysv64\"` --- The System V ABI.\n * Only available on x86_64 targets.\n * \"sysv64\" is the same as the \"C\" ABI on non-Windows x86_64 targets.\n * Corresponds to GCC and clang's `__attribute__((sysv_abi))`.\nFor details, see:\n- \n- \n* `unsafe extern \"aapcs\"` --- The soft-float ABI for ARM.\n * Only available on ARM32 targets.\n * \"aapcs\" is the same as the \"C\" ABI on soft-float ARM32.\n * Corresponds to clang's `__attribute__((pcs(\"aapcs\")))`.\nFor details, see:\n- Arm Procedure Call Standard\n* `unsafe extern \"fastcall\"` --- A \"fast\" variant of stdcall that passes some arguments in registers.\n * Only available on x86_32 targets.\n * Corresponds to MSVC's `__fastcall` and GCC and clang's `__attribute__((fastcall))`.\nFor details, see:\n- \n- ", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "External blocks", "heading_path": ["External blocks", "ABI"], "path": "items/external-blocks.md", "url": "https://doc.rust-lang.org/reference/items/external-blocks.html#abi", "has_code": false, "code_tags": []}} {"id": "reference/items/external-blocks.md#abi-6", "text": "The Rust Reference › External blocks › ABI\n\n* `unsafe extern \"thiscall\"` --- The calling convention typically used on C++ class member functions on x86_32 MSVC.\n * Only available on x86_32 targets.\n * Corresponds to MSVC's `__thiscall` and GCC and clang's `__attribute__((thiscall))`.\nFor details, see:\n- \n- \n* `unsafe extern \"efiapi\"` --- The ABI used for [UEFI] functions.\n * Only available on x86 and ARM targets (32bit and 64bit).\nLike `\"C\"` and `\"system\"`, most platform-specific ABI strings also have a corresponding `-unwind` variant; specifically, these are:\n* `\"aapcs-unwind\"`\n* `\"cdecl-unwind\"`\n* `\"fastcall-unwind\"`\n* `\"stdcall-unwind\"`\n* `\"sysv64-unwind\"`\n* `\"thiscall-unwind\"`\n* `\"win64-unwind\"`", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "External blocks", "heading_path": ["External blocks", "ABI"], "path": "items/external-blocks.md", "url": "https://doc.rust-lang.org/reference/items/external-blocks.html#abi", "has_code": false, "code_tags": []}} {"id": "reference/items/external-blocks.md#variadic-functions-7", "text": "The Rust Reference › External blocks › Variadic functions\n\nFunctions within external blocks may be variadic by specifying `...` as the last argument. The variadic parameter may optionally be specified with an identifier.\n```rust\nunsafe extern \"C\" {\n unsafe fn foo(...);\n unsafe fn bar(x: i32, ...);\n unsafe fn with_name(format: *const u8, args: ...);\n // SAFETY: This function guarantees it will not access\n // variadic arguments.\n safe fn ignores_variadic_arguments(x: i32, ...);\n}\n```\nThe `safe` qualifier should not be used on a function in an `extern` block unless that function guarantees that it will not access the variadic arguments at all. Passing an unexpected number of arguments or arguments of unexpected type to a variadic function may lead to undefined behavior.\nVariadic parameters can only be specified within `extern` blocks with the following ABI strings or their corresponding `-unwind` variants:\n- `\"aapcs\"`\n- `\"C\"`\n- `\"cdecl\"`\n- `\"efiapi\"`\n- `\"system\"`\n- `\"sysv64\"`\n- `\"win64\"`", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "External blocks", "heading_path": ["External blocks", "Variadic functions"], "path": "items/external-blocks.md", "url": "https://doc.rust-lang.org/reference/items/external-blocks.html#variadic-functions", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/external-blocks.md#attributes-on-extern-blocks-8", "text": "The Rust Reference › External blocks › Attributes on extern blocks\n\nThe following [attributes] control the behavior of external blocks.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "External blocks", "heading_path": ["External blocks", "Attributes on extern blocks"], "path": "items/external-blocks.md", "url": "https://doc.rust-lang.org/reference/items/external-blocks.html#attributes-on-extern-blocks", "has_code": false, "code_tags": []}} {"id": "reference/items/external-blocks.md#the-link-attribute-9", "text": "The Rust Reference › External blocks › Attributes on extern blocks › The `link` attribute\n\nThe *`link` attribute* specifies the name of a native library that the compiler should link with for the items within an `extern` block.\nIt uses the [MetaListNameValueStr] 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:\n- `dylib` --- Indicates a dynamic library. This is the default if `kind` is not specified.\n- `static` --- Indicates a static library.\n- `framework` --- Indicates a macOS framework. This is only valid for macOS targets.\n- `raw-dylib` --- Indicates a dynamic library where the compiler will generate an import library to link against (see [`dylib` versus `raw-dylib`] below for details). This is only valid for Windows targets.\nThe `name` key must be included if `kind` is specified.\nThe optional `modifiers` argument is a way to specify linking modifiers for the library to link.\nModifiers 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.\nSpecifying 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\")]`.\nThe `wasm_import_module` key may be used to specify the [WebAssembly module] 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "External blocks", "heading_path": ["External blocks", "Attributes on extern blocks", "The `link` attribute"], "path": "items/external-blocks.md", "url": "https://doc.rust-lang.org/reference/items/external-blocks.html#the-link-attribute", "has_code": false, "code_tags": []}} {"id": "reference/items/external-blocks.md#linking-modifiers-whole-archive-10", "text": "The Rust Reference › External blocks › Attributes on extern blocks › The `link` attribute › Linking modifiers: `whole-archive`\n\n```rust,ignore\n#[link(name = \"crypto\")]\nunsafe extern {\n // …\n}\n\n#[link(name = \"CoreFoundation\", kind = \"framework\")]\nunsafe extern {\n // …\n}\n\n#[link(wasm_import_module = \"foo\")]\nunsafe extern {\n // …\n}\n```\nIt 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.\nThis modifier is only compatible with the `static` linking kind. Using any other kind will result in a compiler error.\nWhen 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.\nWhen 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.\nThis modifier has no effect when building other targets like executables or dynamic libraries.\nThe default for this modifier is `+bundle`.\nMore implementation details about this modifier can be found in [`bundle` documentation for rustc].\nThis modifier is only compatible with the `static` linking kind. Using any other kind will result in a compiler error.\n`+whole-archive` means that the static library is linked as a whole archive without throwing any object files away.\nThe default for this modifier is `-whole-archive`.\nMore implementation details about this modifier can be found in [`whole-archive` documentation for rustc].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "External blocks", "heading_path": ["External blocks", "Attributes on extern blocks", "The `link` attribute", "Linking modifiers: `whole-archive`"], "path": "items/external-blocks.md", "url": "https://doc.rust-lang.org/reference/items/external-blocks.html#linking-modifiers-whole-archive", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "reference/items/external-blocks.md#the-import_name_type-key-11", "text": "The Rust Reference › External blocks › Attributes on extern blocks › Linking modifiers: `verbatim` › The `import_name_type` key\n\nThis modifier is compatible with all linking kinds.\n`+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.\n`-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.\nThe default for this modifier is `-verbatim`.\nMore implementation details about this modifier can be found in [`verbatim` documentation for rustc].\nOn 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.\nSpecifying `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.\n`raw-dylib` is only supported on Windows. Using it when targeting other platforms will result in a compiler error.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "External blocks", "heading_path": ["External blocks", "Attributes on extern blocks", "Linking modifiers: `verbatim`", "The `import_name_type` key"], "path": "items/external-blocks.md", "url": "https://doc.rust-lang.org/reference/items/external-blocks.html#the-import_name_type-key", "has_code": false, "code_tags": []}} {"id": "reference/items/external-blocks.md#the-import_name_type-key-12", "text": "The Rust Reference › External blocks › Attributes on extern blocks › Linking modifiers: `verbatim` › The `import_name_type` key\n\nOn 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] 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.\nTo 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:\n* `decorated`: The function name will be fully-decorated using the MSVC toolchain format.\n* `noprefix`: The function name will be decorated using the MSVC toolchain format, but skipping the leading `?`, `@`, or optionally `_`.\n* `undecorated`: The function name will not be decorated.\nIf the `import_name_type` key is not specified, then the function name will be fully-decorated using the target toolchain's format.\nVariables are never decorated and so the `import_name_type` key has no effect on how they are named in the generated import library.\nThe `import_name_type` key is only supported on x86 Windows. Using it when targeting other platforms will result in a compiler error.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "External blocks", "heading_path": ["External blocks", "Attributes on extern blocks", "Linking modifiers: `verbatim`", "The `import_name_type` key"], "path": "items/external-blocks.md", "url": "https://doc.rust-lang.org/reference/items/external-blocks.html#the-import_name_type-key", "has_code": false, "code_tags": []}} {"id": "reference/items/external-blocks.md#the-link_name-attribute-13", "text": "The Rust Reference › External blocks › Attributes on extern blocks › The `link_name` attribute\n\nThe *`link_name` attribute* may be applied to declarations inside an `extern` block to specify the symbol to import for the given function or static.\n```rust\nunsafe extern \"C\" {\n #[link_name = \"actual_symbol_name\"]\n safe fn name_in_rust();\n}\n```\nThe `link_name` attribute uses the [MetaNameValueStr] syntax.\nThe symbol name must not be the empty string or contain any `U+0000` (NUL) bytes.\nThe `link_name` attribute may only be applied to a function or static item in an `extern` block.\n`rustc` ignores use in other positions but lints against it. This may become an error in the future.\nOnly the first use of `link_name` on an item has effect.\n`rustc` lints against any use following the first with a future-compatibility warning. This may become an error in the future.\nThe `link_name` attribute may not be used with the [`link_ordinal`] attribute.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "External blocks", "heading_path": ["External blocks", "Attributes on extern blocks", "The `link_name` attribute"], "path": "items/external-blocks.md", "url": "https://doc.rust-lang.org/reference/items/external-blocks.html#the-link_name-attribute", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/external-blocks.md#the-link_ordinal-attribute-14", "text": "The Rust Reference › External blocks › Attributes on extern blocks › The `link_ordinal` attribute\n\nThe *`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.\n`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.\n```rust\n#[link(name = \"exporter\", kind = \"raw-dylib\")]\nunsafe extern \"stdcall\" {\n #[link_ordinal(15)]\n safe fn imported_function_stdcall(i: i32);\n}\n```\nThis attribute is only used with the `raw-dylib` linking kind. Using any other kind will result in a compiler error.\nUsing this attribute with the `link_name` attribute will result in a compiler error.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "External blocks", "heading_path": ["External blocks", "Attributes on extern blocks", "The `link_ordinal` attribute"], "path": "items/external-blocks.md", "url": "https://doc.rust-lang.org/reference/items/external-blocks.html#the-link_ordinal-attribute", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/external-blocks.md#attributes-on-function-parameters-15", "text": "The Rust Reference › External blocks › Attributes on extern blocks › Attributes on function parameters\n\nAttributes on extern function parameters follow the same rules and restrictions as [regular function parameters].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "External blocks", "heading_path": ["External blocks", "Attributes on extern blocks", "Attributes on function parameters"], "path": "items/external-blocks.md", "url": "https://doc.rust-lang.org/reference/items/external-blocks.html#attributes-on-function-parameters", "has_code": false, "code_tags": []}} {"id": "reference/items/generics.md#generic-parameters-0", "text": "The Rust Reference › Generic parameters\n\n```grammar,items\nGenericParams -> `<` ( GenericParam (`,` GenericParam)* `,`? )? `>`\n\nGenericParam -> OuterAttribute* ( LifetimeParam | TypeParam | ConstParam )\n\nLifetimeParam -> Lifetime ( `:` LifetimeBounds? )?\n\nTypeParam -> IDENTIFIER ( `:` Bounds? )? ( `=` Type )?\n\nConstParam ->\n `const` IDENTIFIER `:` Type\n ( `=` ( BlockExpression | IDENTIFIER | `-`?LiteralExpression ) )?\n```\n[Functions], [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`.\nThe order of generic parameters is restricted to lifetime parameters and then type and const parameters intermixed.\nThe same parameter name may not be declared more than once in a [GenericParams] list.\nSome examples of items with type, const, and lifetime parameters:\n```rust\nfn foo<'a, T>() {}\ntrait A {}\nstruct Ref<'a, T> where T: 'a { r: &'a T }\nstruct InnerArray([T; N]);\nstruct EitherOrderWorks(U);\n```\nGeneric 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]. See [generic parameter scopes] for more details.\n[References], [raw pointers], [arrays], [slices], [tuples], and [function pointers] have lifetime or type parameters as well, but are not referred to with path syntax.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Generic parameters", "heading_path": ["Generic parameters"], "path": "items/generics.md", "url": "https://doc.rust-lang.org/reference/items/generics.html#generic-parameters", "has_code": true, "code_tags": ["grammar,items", "rust"]}} {"id": "reference/items/generics.md#generic-parameters-1", "text": "The Rust Reference › Generic parameters\n\n`'_` and `'static` are not valid lifetime parameter names.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Generic parameters", "heading_path": ["Generic parameters"], "path": "items/generics.md", "url": "https://doc.rust-lang.org/reference/items/generics.html#generic-parameters", "has_code": false, "code_tags": []}} {"id": "reference/items/generics.md#const-generics-2", "text": "The Rust Reference › Generic parameters › Const generics\n\n*Const generic parameters* allow items to be generic over constant values.\nThe const identifier introduces a name in the [value namespace] for the constant parameter, and all instances of the item must be instantiated with a value of the given type.\nThe only allowed types of const parameters are `u8`, `u16`, `u32`, `u64`, `u128`, `usize`, `i8`, `i16`, `i32`, `i64`, `i128`, `isize`, `char` and `bool`.\nConst parameters can be used anywhere a [const item] can be used, with the exception that when used in a [type] or [array repeat expression], it must be standalone (as described below). That is, they are allowed in the following places:\n1. As an applied const to any type which forms a part of the signature of the item in question.\n2. As part of a const expression used to define an [associated const], or as a parameter to an [associated type].\n3. As a value in any runtime expression in the body of any functions in the item.\n4. As a parameter to any type used in the body of any functions in the item.\n5. As a part of the type of any fields in the item.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Generic parameters", "heading_path": ["Generic parameters", "Const generics"], "path": "items/generics.md", "url": "https://doc.rust-lang.org/reference/items/generics.html#const-generics", "has_code": false, "code_tags": []}} {"id": "reference/items/generics.md#const-generics-3", "text": "The Rust Reference › Generic parameters › Const generics\n\n```rust\n// Examples where const generic parameters can be used.\n\n// Used in the signature of the item itself.\nfn foo(arr: [i32; N]) {\n // Used as a type within a function body.\n let x: [i32; N];\n // Used as an expression.\n println!(\"{}\", N * 2);\n}\n\n// Used as a field of a struct.\nstruct Foo([i32; N]);\n\nimpl Foo {\n // Used as an associated constant.\n const CONST: usize = N * 4;\n}\n\ntrait Trait {\n type Output;\n}\n\nimpl Trait for Foo {\n // Used as an associated type.\n type Output = [i32; N];\n}\n```\n```rust,compile_fail\n// Examples where const generic parameters cannot be used.\nfn foo() {\n // Cannot use in item definitions within a function body.\n const BAD_CONST: [usize; N] = [1; N];\n static BAD_STATIC: [usize; N] = [1; N];\n fn inner(bad_arg: [usize; N]) {\n let bad_value = N * 2;\n }\n type BadAlias = [usize; N];\n struct BadStruct([usize; N]);\n}\n```\nAs a further restriction, const parameters may only appear as a standalone argument inside of a [type] or [array repeat expression]. In those contexts, they may only be used as a single segment [path expression], possibly inside a [block] (such as `N` or `{N}`). That is, they cannot be combined with other expressions.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Generic parameters", "heading_path": ["Generic parameters", "Const generics"], "path": "items/generics.md", "url": "https://doc.rust-lang.org/reference/items/generics.html#const-generics", "has_code": true, "code_tags": ["rust", "rust,compile_fail"]}} {"id": "reference/items/generics.md#const-generics-4", "text": "The Rust Reference › Generic parameters › Const generics\n\n```rust,compile_fail\n// Examples where const parameters may not be used.\n\n// Not allowed to combine in other expressions in types, such as the\n// arithmetic expression in the return type here.\nfn bad_function() -> [u8; {N + 1}] {\n // Similarly not allowed for array repeat expressions.\n [1; {N + 1}]\n}\n```\nA const argument in a [path] specifies the const value to use for that item.\nThe argument must either be an [inferred const] or be a [const expression] of the type ascribed to the const parameter. The const expression must be a block expression (surrounded with braces) unless it is a single path segment (an [IDENTIFIER]) or a [literal] (with a possibly leading `-` token).\nThis syntactic restriction is necessary to avoid requiring infinite lookahead when parsing an expression inside of a type.\n```rust\nstruct S;\nconst C: i64 = 1;\nfn f() -> S { S }\n\nlet _ = f::<1>(); // Literal.\nlet _ = f::<-1>(); // Negative literal.\nlet _ = f::<{ 1 + 2 }>(); // Constant expression.\nlet _ = f::(); // Single segment path.\nlet _ = f::<{ C + 1 }>(); // Constant expression.\nlet _: S<1> = f::<_>(); // Inferred const.\nlet _: S<1> = f::<(((_)))>(); // Inferred const.\n```\nIn a generic argument list, an [inferred const] is parsed as an inferred type but then semantically treated as a separate kind of [const generic argument].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Generic parameters", "heading_path": ["Generic parameters", "Const generics"], "path": "items/generics.md", "url": "https://doc.rust-lang.org/reference/items/generics.html#const-generics", "has_code": true, "code_tags": ["rust", "rust,compile_fail"]}} {"id": "reference/items/generics.md#const-generics-5", "text": "The Rust Reference › Generic parameters › Const generics\n\nWhere a const argument is expected, an `_` (optionally surrounded by any number of matching parentheses), called the *inferred const* (path rules, array expression rules), can be used instead. This asks the compiler to infer the const argument if possible based on surrounding information.\n```rust\nfn make_buf() -> [u8; N] {\n [0; _]\n // ^ Infers `N`.\n}\nlet _: [u8; 1024] = make_buf::<_>();\n// ^ Infers `1024`.\n```\nAn [inferred const] is not semantically an expression and so is not accepted within braces.\n```rust,compile_fail\nfn f() -> [u8; N] { [0; _] }\nlet _: [_; 1] = f::<{ _ }>();\n// ^ ERROR `_` not allowed here\n```\nThe inferred const cannot be used in item signatures.\n```rust,compile_fail\nfn f(x: [u8; N]) -> [u8; _] { x }\n// ^ ERROR not allowed\n```\nWhen 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Generic parameters", "heading_path": ["Generic parameters", "Const generics"], "path": "items/generics.md", "url": "https://doc.rust-lang.org/reference/items/generics.html#const-generics", "has_code": true, "code_tags": ["rust", "rust,compile_fail"]}} {"id": "reference/items/generics.md#const-generics-6", "text": "The Rust Reference › Generic parameters › Const generics\n\n```rust,compile_fail\ntype N = u32;\nstruct Foo;\n// The following is an error, because `N` is interpreted as the type alias `N`.\nfn foo() -> Foo { todo!() } // ERROR\n// Can be fixed by wrapping in braces to force it to be interpreted as the `N`\n// const parameter:\nfn bar() -> Foo<{ N }> { todo!() } // ok\n```\nUnlike 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]:\n```rust,compile_fail\n// ok\nstruct Foo;\nenum Bar { A, B }\n\n// ERROR: unused parameter\nstruct Baz;\nstruct Biz<'a>;\nstruct Unconstrained;\nimpl Unconstrained {}\n```\nWhen 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:\n```rust,compile_fail\nstruct Foo;\ntrait Bar {}\nimpl Bar for Foo {}\nimpl Bar for Foo {}\n\nfn needs_bar(_: impl Bar) {}\nfn generic() {\n let v = Foo::;\n needs_bar(v); // ERROR: trait bound `Foo: Bar` is not satisfied\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Generic parameters", "heading_path": ["Generic parameters", "Const generics"], "path": "items/generics.md", "url": "https://doc.rust-lang.org/reference/items/generics.html#const-generics", "has_code": true, "code_tags": ["rust,compile_fail"]}} {"id": "reference/items/generics.md#where-clauses-7", "text": "The Rust Reference › Generic parameters › Where clauses\n\n```grammar,items\nWhereClause -> `where` ( WhereClauseItem `,` )* WhereClauseItem?\n\nWhereClauseItem ->\n LifetimeWhereClauseItem\n | TypeBoundWhereClauseItem\n\nLifetimeWhereClauseItem -> Lifetime `:` LifetimeBounds?\n\nTypeBoundWhereClauseItem -> ForLifetimes? Type `:` Bounds?\n```\n*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.\nThe `for` keyword can be used to introduce [higher-ranked lifetimes]. It only allows [LifetimeParam] parameters.\n```rust\nstruct A\nwhere\n T: Iterator, // Could use A instead\n T::Item: Copy, // Bound on an associated type\n String: PartialEq, // Bound on `String`, using the type parameter\n i32: Default, // Allowed, but not useful\n{\n f: T,\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Generic parameters", "heading_path": ["Generic parameters", "Where clauses"], "path": "items/generics.md", "url": "https://doc.rust-lang.org/reference/items/generics.html#where-clauses", "has_code": true, "code_tags": ["grammar,items", "rust"]}} {"id": "reference/items/generics.md#attributes-8", "text": "The Rust Reference › Generic parameters › Attributes\n\nGeneric lifetime and type parameters allow [attributes] on them. There are no built-in attributes that do anything in this position, although custom derive attributes may give meaning to it.\nThis example shows using a custom derive attribute to modify the meaning of a generic parameter.\n```rust,ignore\n// Assume that the derive for MyFlexibleClone declared `my_flexible_clone` as\n// an attribute it understands.\n#[derive(MyFlexibleClone)]\nstruct Foo<#[my_flexible_clone(unbounded)] H> {\n a: *const H\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Generic parameters", "heading_path": ["Generic parameters", "Attributes"], "path": "items/generics.md", "url": "https://doc.rust-lang.org/reference/items/generics.html#attributes", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "reference/items/associated-items.md#associated-items-0", "text": "The Rust Reference › Associated items\n\n```grammar,items\nAssociatedItem ->\n OuterAttribute* (\n MacroInvocationSemi\n | ( Visibility? ( TypeAlias | ConstantItem | Function ) )\n )\n```\n*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.\nThey are a subset of the kinds of items you can declare in a module. Specifically, there are [associated functions] (including methods), [associated types], and [associated constants].\nAssociated items are useful when the associated item is logically related to the associating item. For example, the `is_some` method on `Option` is intrinsically related to Options, so should be associated.\nEvery associated item kind comes in two varieties: definitions that contain the actual implementation and declarations that declare signatures for definitions.\nIt is the declarations that make up the contract of traits and what is available on generic types.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Associated items", "heading_path": ["Associated items"], "path": "items/associated-items.md", "url": "https://doc.rust-lang.org/reference/items/associated-items.html#associated-items", "has_code": true, "code_tags": ["grammar,items"]}} {"id": "reference/items/associated-items.md#associated-functions-and-methods-1", "text": "The Rust Reference › Associated items › Associated functions and methods\n\n*Associated functions* are [functions] associated with a type.\nAn *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 `;`.\nThe identifier is the name of the function.\nThe generics, parameter list, return type, and where clause of the associated function must be the same as the associated function declarations's.\nAn *associated function definition* defines a function associated with another type. It is written the same as a [function item].\nA common example is an associated function named `new` that returns a value of the type with which it is associated.\n```rust\nstruct Struct {\n field: i32\n}\n\nimpl Struct {\n fn new() -> Struct {\n Struct {\n field: 0i32\n }\n }\n}\n\nfn main () {\n let _struct = Struct::new();\n}\n```\nWhen the associated function is declared on a trait, the function can also be called with a [path] 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`.\n```rust\ntrait Num {\n fn from_i32(n: i32) -> Self;\n}\n\nimpl Num for f64 {\n fn from_i32(n: i32) -> f64 { n as f64 }\n}\n\n// These 4 are all equivalent in this case.\nlet _: f64 = Num::from_i32(42);\nlet _: f64 = <_ as Num>::from_i32(42);\nlet _: f64 = ::from_i32(42);\nlet _: f64 = f64::from_i32(42);\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Associated items", "heading_path": ["Associated items", "Associated functions and methods"], "path": "items/associated-items.md", "url": "https://doc.rust-lang.org/reference/items/associated-items.html#associated-functions-and-methods", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/associated-items.md#methods-2", "text": "The Rust Reference › Associated items › Associated functions and methods › Methods\n\nAssociated functions whose first parameter is named `self` are called *methods* and may be invoked using the [method call operator], for example, `x.foo()`, as well as the usual function call notation.\nIf 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):\n```text\nP = &'lt S | &'lt mut S | Box | Rc | Arc | Pin

\nS = Self | P\n```\nThe `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.\n```rust\n// Examples of methods implemented on struct `Example`.\nstruct Example;\ntype Alias = Example;\ntrait Trait { type Output; }\nimpl Trait for Example { type Output = Example; }\nimpl Example {\n fn by_value(self: Self) {}\n fn by_ref(self: &Self) {}\n fn by_ref_mut(self: &mut Self) {}\n fn by_box(self: Box) {}\n fn by_rc(self: Rc) {}\n fn by_arc(self: Arc) {}\n fn by_pin(self: Pin<&Self>) {}\n fn explicit_type(self: Arc) {}\n fn with_lifetime<'a>(self: &'a Self) {}\n fn nested<'a>(self: &mut &'a Arc>>) {}\n fn via_projection(self: ::Output) {}\n}\n```\nShorthand syntax can be used without specifying a type, which have the following equivalents:\nShorthand | Equivalent\n----------------------|-----------\n`self` | `self: Self`\n`&'lifetime self` | `self: &'lifetime Self`\n`&'lifetime mut self` | `self: &'lifetime mut Self`", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Associated items", "heading_path": ["Associated items", "Associated functions and methods", "Methods"], "path": "items/associated-items.md", "url": "https://doc.rust-lang.org/reference/items/associated-items.html#methods", "has_code": true, "code_tags": ["rust", "text"]}} {"id": "reference/items/associated-items.md#attributes-on-method-parameters-3", "text": "The Rust Reference › Associated items › Associated functions and methods › Methods › Attributes on method parameters\n\nLifetimes can be, and usually are, elided with this shorthand.\nIf the `self` parameter is prefixed with `mut`, it becomes a mutable variable, similar to regular parameters using a `mut` [identifier pattern]. For example:\n```rust\ntrait Changer: Sized {\n fn change(mut self) {}\n fn modify(mut self: Box) {}\n}\n```\nAs an example of methods on a trait, consider the following:\n```rust\ntrait Shape {\n fn draw(&self, surface: Surface);\n fn bounding_box(&self) -> BoundingBox;\n}\n```\nThis 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.\n```rust\nstruct Circle {\n // ...\n}\n\nimpl Shape for Circle {\n // ...\n}\n\nlet circle_shape = Circle::new();\nlet bounding_box = circle_shape.bounding_box();\n```\n[!EDITION-2018]\nIn 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.\nAttributes on method parameters follow the same rules and restrictions as [regular function parameters].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Associated items", "heading_path": ["Associated items", "Associated functions and methods", "Methods", "Attributes on method parameters"], "path": "items/associated-items.md", "url": "https://doc.rust-lang.org/reference/items/associated-items.html#attributes-on-method-parameters", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/associated-items.md#associated-types-4", "text": "The Rust Reference › Associated items › Associated types\n\n*Associated types* are [type aliases] associated with another type.\nAssociated types cannot be defined in [inherent implementations] nor can they be given a default implementation in traits.\nAn *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:\n```rust,ignore\ntype Assoc;\ntype Assoc: Bounds;\ntype Assoc;\ntype Assoc: Bounds;\ntype Assoc where WhereBounds;\ntype Assoc: Bounds where WhereBounds;\n```\nThe identifier is the name of the declared type alias.\nThe optional trait bounds must be fulfilled by the implementations of the type alias.\nThere is an implicit [`Sized`] bound on associated types that can be relaxed using the special `?Sized` bound.\nAn *associated type definition* defines a type alias for the implementation of a trait on a type.\nThey are written similarly to an *associated type declaration*, but cannot contain `Bounds`, but instead must contain a `Type`:\n```rust,ignore\ntype Assoc = Type;\ntype Assoc = Type; // the type `Type` here may reference `Params`\ntype Assoc = Type where WhereBounds;\ntype Assoc where WhereBounds = Type; // deprecated, prefer the form above\n```\nIf a type `Item` has an associated type `Assoc` from a trait `Trait`, then `::Assoc` is a type that is an alias of the type specified in the associated type definition.\nFurthermore, if `Item` is a type parameter, then `Item::Assoc` can be used in type parameters.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Associated items", "heading_path": ["Associated items", "Associated types"], "path": "items/associated-items.md", "url": "https://doc.rust-lang.org/reference/items/associated-items.html#associated-types", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "reference/items/associated-items.md#associated-types-5", "text": "The Rust Reference › Associated items › Associated types\n\nAssociated types may include [generic parameters] and [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 `::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.\n```rust\ntrait AssociatedType {\n // Associated type declaration\n type Assoc;\n}\n\nstruct Struct;\n\nstruct OtherStruct;\n\nimpl AssociatedType for Struct {\n // Associated type definition\n type Assoc = OtherStruct;\n}\n\nimpl OtherStruct {\n fn new() -> OtherStruct {\n OtherStruct\n }\n}\n\nfn main() {\n // Usage of the associated type to refer to OtherStruct as ::Assoc\n let _other_struct: OtherStruct = ::Assoc::new();\n}\n```\nAn example of associated types with generics and where clauses:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Associated items", "heading_path": ["Associated items", "Associated types"], "path": "items/associated-items.md", "url": "https://doc.rust-lang.org/reference/items/associated-items.html#associated-types", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/associated-items.md#associated-types-6", "text": "The Rust Reference › Associated items › Associated types\n\n```rust\nstruct ArrayLender<'a, T>(&'a mut [T; 16]);\n\ntrait Lend {\n // Generic associated type declaration\n type Lender<'a> where Self: 'a;\n fn lend<'a>(&'a mut self) -> Self::Lender<'a>;\n}\n\nimpl Lend for [T; 16] {\n // Generic associated type definition\n type Lender<'a> = ArrayLender<'a, T> where Self: 'a;\n\n fn lend<'a>(&'a mut self) -> Self::Lender<'a> {\n ArrayLender(self)\n }\n}\n\nfn borrow<'a, T: Lend>(array: &'a mut T) -> ::Lender<'a> {\n array.lend()\n}\n\nfn main() {\n let mut array = [0usize; 16];\n let lender = borrow(&mut array);\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Associated items", "heading_path": ["Associated items", "Associated types"], "path": "items/associated-items.md", "url": "https://doc.rust-lang.org/reference/items/associated-items.html#associated-types", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/associated-items.md#associated-types-container-example-7", "text": "The Rust Reference › Associated items › Associated types › Associated types container example\n\nConsider the following example of a `Container` trait. Notice that the type is available for use in the method signatures:\n```rust\ntrait Container {\n type E;\n fn empty() -> Self;\n fn insert(&mut self, elem: Self::E);\n}\n```\nIn 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`:\n```rust\nimpl Container for Vec {\n type E = T;\n fn empty() -> Vec { Vec::new() }\n fn insert(&mut self, x: T) { self.push(x); }\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Associated items", "heading_path": ["Associated items", "Associated types", "Associated types container example"], "path": "items/associated-items.md", "url": "https://doc.rust-lang.org/reference/items/associated-items.html#associated-types-container-example", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/associated-items.md#relationship-between-bounds-and-wherebounds-8", "text": "The Rust Reference › Associated items › Associated types › Relationship between `Bounds` and `WhereBounds`\n\nIn this example:\n```rust\ntrait Example {\n type Output: Ord where T: Debug;\n}\n```\nGiven a reference to the associated type like `::Output`, the associated type itself must be `Ord`, and the type `Y` must be `Debug`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Associated items", "heading_path": ["Associated items", "Associated types", "Relationship between `Bounds` and `WhereBounds`"], "path": "items/associated-items.md", "url": "https://doc.rust-lang.org/reference/items/associated-items.html#relationship-between-bounds-and-wherebounds", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/associated-items.md#required-where-clauses-on-generic-associated-types-9", "text": "The Rust Reference › Associated items › Associated types › Required where clauses on generic associated types\n\nGeneric 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.\nIn 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.\n```rust\ntrait LendingIterator {\n type Item<'x> where Self: 'x;\n fn next<'a>(&'a mut self) -> Self::Item<'a>;\n}\n```\nIn 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`.\nWhen 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.\n```rust\ntrait Check {\n type Checker<'x>;\n fn create_checker<'a>(item: &'a T) -> Self::Checker<'a>;\n fn do_check(checker: Self::Checker<'_>);\n}\n```\nIn 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`.\nThe bounds on associated types also propagate required where clauses.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Associated items", "heading_path": ["Associated items", "Associated types", "Required where clauses on generic associated types"], "path": "items/associated-items.md", "url": "https://doc.rust-lang.org/reference/items/associated-items.html#required-where-clauses-on-generic-associated-types", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/associated-items.md#required-where-clauses-on-generic-associated-types-10", "text": "The Rust Reference › Associated items › Associated types › Required where clauses on generic associated types\n\n```rust\ntrait Iterable {\n type Item<'a> where Self: 'a;\n type Iterator<'a>: Iterator> where Self: 'a;\n fn iter<'a>(&'a self) -> Self::Iterator<'a>;\n}\n```\nHere, `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.\nFinally, any explicit uses of `'static` on GATs in the trait do not count towards the required bounds.\n```rust\ntrait StaticReturn {\n type Y<'a>;\n fn foo(&self) -> Self::Y<'static>;\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Associated items", "heading_path": ["Associated items", "Associated types", "Required where clauses on generic associated types"], "path": "items/associated-items.md", "url": "https://doc.rust-lang.org/reference/items/associated-items.html#required-where-clauses-on-generic-associated-types", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/items/associated-items.md#associated-constants-11", "text": "The Rust Reference › Associated items › Associated constants\n\n*Associated constants* are [constants] associated with a type.\nAn *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 `;`.\nThe identifier is the name of the constant used in the path. The type is the type that the definition has to implement.\nAn *associated constant definition* defines a constant associated with a type. It is written the same as a [constant item].\nAssociated constant definitions undergo [constant evaluation] only when referenced. Further, definitions that include [generic parameters] are evaluated after monomorphization.\n```rust,compile_fail\nstruct Struct;\nstruct GenericStruct;\n\nimpl Struct {\n // Definition not immediately evaluated\n const PANIC: () = panic!(\"compile-time panic\");\n}\n\nimpl GenericStruct {\n // Definition not immediately evaluated\n const NON_ZERO: () = if ID == 0 {\n panic!(\"contradiction\")\n };\n}\n\nfn main() {\n // Referencing Struct::PANIC causes compilation error\n let _ = Struct::PANIC;\n\n // Fine, ID is not 0\n let _ = GenericStruct::<1>::NON_ZERO;\n\n // Compilation error from evaluating NON_ZERO with ID=0\n let _ = GenericStruct::<0>::NON_ZERO;\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Associated items", "heading_path": ["Associated items", "Associated constants"], "path": "items/associated-items.md", "url": "https://doc.rust-lang.org/reference/items/associated-items.html#associated-constants", "has_code": true, "code_tags": ["rust,compile_fail"]}} {"id": "reference/items/associated-items.md#associated-constants-examples-12", "text": "The Rust Reference › Associated items › Associated constants › Associated constants examples\n\nA basic example:\n```rust\ntrait ConstantId {\n const ID: i32;\n}\n\nstruct Struct;\n\nimpl ConstantId for Struct {\n const ID: i32 = 1;\n}\n\nfn main() {\n assert_eq!(1, Struct::ID);\n}\n```\nUsing default values:\n```rust\ntrait ConstantIdDefault {\n const ID: i32 = 1;\n}\n\nstruct Struct;\nstruct OtherStruct;\n\nimpl ConstantIdDefault for Struct {}\n\nimpl ConstantIdDefault for OtherStruct {\n const ID: i32 = 5;\n}\n\nfn main() {\n assert_eq!(1, Struct::ID);\n assert_eq!(5, OtherStruct::ID);\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Associated items", "heading_path": ["Associated items", "Associated constants", "Associated constants examples"], "path": "items/associated-items.md", "url": "https://doc.rust-lang.org/reference/items/associated-items.html#associated-constants-examples", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/attributes.md#attributes-0", "text": "The Rust Reference › Attributes\n\n```grammar,attributes\nInnerAttribute -> `#` `!` `[` Attr `]`\n\nOuterAttribute -> `#` `[` Attr `]`\n\nAttr ->\n SimplePath AttrInput?\n | `unsafe` `(` SimplePath AttrInput? `)`\n\nAttrInput ->\n DelimTokenTree\n | `=` Expression\n```\nAn _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], with the syntax coming from [ECMA-334] \\(C#).\n_Inner attributes_, written with a bang (`!`) after the hash (`#`), apply to the form that the attribute is declared within.\n```rust\n// General metadata applied to the enclosing module or crate.\n#![crate_type = \"lib\"]\n\n// Inner attribute applies to the entire function.\nfn some_unused_variables() {\n #![allow(unused_variables)]\n\n let x = ();\n let y = ();\n let z = ();\n}\n```\n_Outer attributes_, written without the bang after the hash, apply to the form that follows the attribute.\n```rust\n// A function marked as a unit test\n#[test]\nfn test_foo() {\n /* ... */\n}\n\n// A conditionally-compiled module\n#[cfg(target_os = \"linux\")]\nmod bar {\n /* ... */\n}\n\n// A lint attribute used to suppress a warning/error\n#[allow(non_camel_case_types)]\ntype int8_t = i8;\n```\nThe 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 below for more details.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Attributes", "heading_path": ["Attributes"], "path": "attributes.md", "url": "https://doc.rust-lang.org/reference/attributes.html#attributes", "has_code": true, "code_tags": ["grammar,attributes", "rust"]}} {"id": "reference/attributes.md#attributes-1", "text": "The Rust Reference › Attributes\n\nAn attribute may be unsafe to apply. To avoid undefined behavior when using these attributes, certain obligations that cannot be checked by the compiler must be met. To assert these have been, the attribute is wrapped in `unsafe(..)`, e.g. `#[unsafe(no_mangle)]`.\nThe following attributes are unsafe:\n* [`export_name`]\n* [`link_section`]\n* [`naked`]\n* [`no_mangle`]\nAttributes can be classified into the following kinds:\n* [Built-in attributes]\n* Proc macro attributes\n* [Derive macro helper attributes]\n* Tool attributes\nAttributes may be applied to many forms in the language:\n* All [item declarations] accept outer attributes while [external blocks], [functions], [implementations], and [modules] accept inner attributes.\n* Most [statements] accept outer attributes (see [Expression Attributes] for limitations on expression statements).\n* [Block expressions] accept outer and inner attributes, but only when they are the outer expression of an [expression statement] or the final expression of another block expression.\n* [Enum] variants and [struct] and [union] fields accept outer attributes.\n* Match expression arms accept outer attributes.\n* Generic lifetime or type parameter accept outer attributes.\n* Expressions accept outer attributes in limited situations, see [Expression Attributes] for details.\n* Function, [closure] and [function pointer] parameters accept outer attributes. This includes attributes on variadic parameters denoted with `...` in function pointers and external blocks.\n* [Inline assembly] template strings and operands accept outer attributes. Only certain attributes are accepted semantically; for details, see [asm.attributes.supported-attributes].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Attributes", "heading_path": ["Attributes"], "path": "attributes.md", "url": "https://doc.rust-lang.org/reference/attributes.html#attributes", "has_code": false, "code_tags": []}} {"id": "reference/attributes.md#meta-item-attribute-syntax-2", "text": "The Rust Reference › Attributes › Meta item attribute syntax\n\nA \"meta item\" is the syntax used for the [Attr] rule by most [built-in attributes]. It has the following grammar:\n```grammar,attributes\n@root MetaItem ->\n SimplePath\n | SimplePath `=` Expression\n | SimplePath `(` MetaSeq? `)`\n\nMetaSeq ->\n MetaItemInner ( `,` MetaItemInner )* `,`?\n\nMetaItemInner ->\n MetaItem\n | Expression\n```\nExpressions 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.\nNote 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:\n```rust ignore\n#[derive(Serialize)]\nstruct Foo {\n #[doc = include_str!(\"x.md\")]\n x: u32\n}\n```\nAdditionally, macros in attributes will be expanded only after all other attributes applied to the item:\n```rust ignore\n#[macro_attr1] // expanded first\n#[doc = mac!()] // `mac!` is expanded fourth.\n#[macro_attr2] // expanded second\n#[derive(MacroDerive1, MacroDerive2)] // expanded third\nfn foo() {}\n```\nVarious built-in attributes use different subsets of the meta item syntax to specify their inputs. The following grammar rules show some commonly used forms:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Attributes", "heading_path": ["Attributes", "Meta item attribute syntax"], "path": "attributes.md", "url": "https://doc.rust-lang.org/reference/attributes.html#meta-item-attribute-syntax", "has_code": true, "code_tags": ["grammar,attributes", "rust ignore"]}} {"id": "reference/attributes.md#meta-item-attribute-syntax-3", "text": "The Rust Reference › Attributes › Meta item attribute syntax\n\n```grammar,attributes\n@root MetaWord ->\n IDENTIFIER\n\nMetaNameValueStr ->\n IDENTIFIER `=` (STRING_LITERAL | RAW_STRING_LITERAL)\n\n@root MetaListPaths ->\n IDENTIFIER `(` ( SimplePath (`,` SimplePath)* `,`? )? `)`\n\n@root MetaListIdents ->\n IDENTIFIER `(` ( IDENTIFIER (`,` IDENTIFIER)* `,`? )? `)`\n\n@root MetaListNameValueStr ->\n IDENTIFIER `(` ( MetaNameValueStr (`,` MetaNameValueStr)* `,`? )? `)`\n```\nSome examples of meta items are:\nStyle | Example\n------|--------\n[MetaWord] | `no_std`\n[MetaNameValueStr] | `doc = \"example\"`\n[MetaListPaths] | `allow(unused, clippy::inline_always)`\n[MetaListIdents] | `macro_use(foo, bar)`\n[MetaListNameValueStr] | `link(name = \"CoreFoundation\", kind = \"framework\")`", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Attributes", "heading_path": ["Attributes", "Meta item attribute syntax"], "path": "attributes.md", "url": "https://doc.rust-lang.org/reference/attributes.html#meta-item-attribute-syntax", "has_code": true, "code_tags": ["grammar,attributes"]}} {"id": "reference/attributes.md#active-and-inert-attributes-4", "text": "The Rust Reference › Attributes › Active and inert attributes\n\nAn attribute is either active or inert. During attribute processing, *active attributes* remove themselves from the form they are on while *inert attributes* stay on.\nThe [`cfg`] and [`cfg_attr`] attributes are active. [Attribute macros] are active. All other attributes are inert.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Attributes", "heading_path": ["Attributes", "Active and inert attributes"], "path": "attributes.md", "url": "https://doc.rust-lang.org/reference/attributes.html#active-and-inert-attributes", "has_code": false, "code_tags": []}} {"id": "reference/attributes.md#tool-attributes-5", "text": "The Rust Reference › Attributes › Tool attributes\n\nThe compiler may allow attributes for external tools where each tool resides in its own module in the [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.\nWhen 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.\nTool attributes are not available if the [`no_implicit_prelude`] attribute is used.\n```rust\n// Tells the rustfmt tool to not format the following element.\n#[rustfmt::skip]\nstruct S {\n}\n\n// Controls the \"cyclomatic complexity\" threshold for the clippy tool.\n#[clippy::cyclomatic_complexity = \"100\"]\npub fn f() {}\n```\n`rustc` currently recognizes the tools \"clippy\", \"rustfmt\", \"diagnostic\", \"miri\", and \"rust_analyzer\".", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Attributes", "heading_path": ["Attributes", "Tool attributes"], "path": "attributes.md", "url": "https://doc.rust-lang.org/reference/attributes.html#tool-attributes", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/attributes.md#built-in-attributes-index-6", "text": "The Rust Reference › Attributes › Built-in attributes index\n\nThe following is an index of all built-in attributes.\n- Conditional compilation\n - [`cfg`] --- Controls conditional compilation.\n - [`cfg_attr`] --- Conditionally includes attributes.\n- Testing\n - [`test`] --- Marks a function as a test.\n - [`ignore`] --- Disables a test function.\n - [`should_panic`] --- Indicates a test should generate a panic.\n- Derive\n - [`derive`] --- Automatic trait implementations.\n - [`automatically_derived`] --- Marker for implementations created by `derive`.\n- Macros\n - [`macro_export`] --- Exports a `macro_rules` macro for cross-crate use.\n - [`macro_use`] --- Expands macro visibility, or imports macros from other crates.\n - [`proc_macro`] --- Defines a function-like macro.\n - [`proc_macro_derive`] --- Defines a derive macro.\n - [`proc_macro_attribute`] --- Defines an attribute macro.\n- Diagnostics\n - [`allow`], [`expect`], [`warn`], [`deny`], [`forbid`] --- Alters the default lint level.\n - [`deprecated`] --- Generates deprecation notices.\n - [`must_use`] --- Generates a lint for unused values.\n - [`diagnostic::on_unimplemented`] --- Hints the compiler to emit a certain error message if a trait is not implemented.\n - [`diagnostic::do_not_recommend`] --- Hints the compiler to not show a certain trait impl in error messages.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Attributes", "heading_path": ["Attributes", "Built-in attributes index"], "path": "attributes.md", "url": "https://doc.rust-lang.org/reference/attributes.html#built-in-attributes-index", "has_code": false, "code_tags": []}} {"id": "reference/attributes.md#built-in-attributes-index-7", "text": "The Rust Reference › Attributes › Built-in attributes index\n\n- ABI, linking, symbols, and FFI\n - [`link`] --- Specifies a native library to link with an `extern` block.\n - [`link_name`] --- Specifies the name of the symbol for functions or statics in an `extern` block.\n - [`link_ordinal`] --- Specifies the ordinal of the symbol for functions or statics in an `extern` block.\n - [`no_link`] --- Prevents linking an extern crate.\n - [`repr`] --- Controls type layout.\n - [`crate_type`] --- Specifies the type of crate (library, executable, etc.).\n - [`no_main`] --- Disables emitting the `main` symbol.\n - [`export_name`] --- Specifies the exported symbol name for a function or static.\n - [`link_section`] --- Specifies the section of an object file to use for a function or static.\n - [`no_mangle`] --- Disables symbol name encoding.\n - [`used`] --- Forces the compiler to keep a static item in the output object file.\n - [`crate_name`] --- Specifies the crate name.\n- Code generation\n - [`inline`] --- Hint to inline code.\n - [`cold`] --- Hint that a function is unlikely to be called.\n - [`naked`] --- Prevent the compiler from emitting a function prologue and epilogue.\n - [`no_builtins`] --- Disables use of certain built-in functions.\n - [`target_feature`] --- Configure platform-specific code generation.\n - [`track_caller`] --- Pass the parent call location to `std::panic::Location::caller()`.\n - [`instruction_set`] --- Specify the instruction set used to generate a function's code.\n- Documentation\n - `doc` --- Specifies documentation. See [The Rustdoc Book] for more information. [Doc comments] are transformed into `doc` attributes.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Attributes", "heading_path": ["Attributes", "Built-in attributes index"], "path": "attributes.md", "url": "https://doc.rust-lang.org/reference/attributes.html#built-in-attributes-index", "has_code": false, "code_tags": []}} {"id": "reference/attributes.md#built-in-attributes-index-8", "text": "The Rust Reference › Attributes › Built-in attributes index\n\n- Preludes\n - [`no_std`] --- Removes std from the prelude.\n - [`no_implicit_prelude`] --- Disables prelude lookups within a module.\n- Modules\n - [`path`] --- Specifies the filename for a module.\n- Limits\n - [`recursion_limit`] --- Sets the maximum recursion limit for certain compile-time operations.\n - [`type_length_limit`] --- Sets the maximum size of a polymorphic type.\n- Runtime\n - [`panic_handler`] --- Sets the function to handle panics.\n - [`global_allocator`] --- Sets the global memory allocator.\n - [`windows_subsystem`] --- Specifies the windows subsystem to link with.\n- Features\n - `feature` --- Used to enable unstable or experimental compiler features. See [The Unstable Book] for features implemented in `rustc`.\n- Type System\n - [`non_exhaustive`] --- Indicate that a type will have more fields/variants added in future.\n- Debugger\n - [`debugger_visualizer`] --- Embeds a file that specifies debugger output for a type.\n - [`collapse_debuginfo`] --- Controls how macro invocations are encoded in debuginfo.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Attributes", "heading_path": ["Attributes", "Built-in attributes index"], "path": "attributes.md", "url": "https://doc.rust-lang.org/reference/attributes.html#built-in-attributes-index", "has_code": false, "code_tags": []}} {"id": "reference/attributes/testing.md#testing-attributes-0", "text": "The Rust Reference › Testing attributes\n\nThe following [attributes] are used for specifying functions for performing\ntests. Compiling a crate in \"test\" mode enables building the test functions\nalong with a test harness for executing the tests. Enabling the test mode also\nenables the [`test` conditional compilation option].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Testing", "heading_path": ["Testing attributes"], "path": "attributes/testing.md", "url": "https://doc.rust-lang.org/reference/attributes/testing.html#testing-attributes", "has_code": false, "code_tags": []}} {"id": "reference/attributes/testing.md#the-test-attribute-1", "text": "The Rust Reference › Testing attributes › The `test` attribute\n\nThe *`test` attribute* marks a function to be executed as a test.\n```rust,no_run\n#[test]\nfn it_works() {\n let result = add(2, 2);\n assert_eq!(result, 4);\n}\n```\nThe `test` attribute uses the [MetaWord] syntax.\nThe `test` attribute may only be applied to [free functions] that are monomorphic, that take no arguments, and where the return type implements the [`Termination`] trait.\nSome of types that implement the [`Termination`] trait include:\n* `()`\n* `Result where T: Termination, E: Debug`\nOnly the first use of `test` on a function has effect.\n`rustc` lints against any use following the first. This may become an error in the future.\nThe `test` attribute is exported from the standard library prelude as [`std::prelude::v1::test`].\nThese functions are only compiled when in test mode.\nThe test mode is enabled by passing the `--test` argument to `rustc` or using `cargo test`.\nThe test harness calls the returned value's [`report`] method, and classifies the test as passed or failed depending on whether the resulting [`ExitCode`] represents successful termination.\nIn particular:\n* Tests that return `()` pass as long as they terminate and do not panic.\n* Tests that return a `Result<(), E>` pass as long as they return `Ok(())`.\n* Tests that return `ExitCode::SUCCESS` pass, and tests that return `ExitCode::FAILURE` fail.\n* Tests that do not terminate neither pass nor fail.\n```rust,no_run\n#[test]\nfn test_the_thing() -> io::Result<()> {\n let state = setup_the_thing()?; // expected to succeed\n do_the_thing(&state)?; // expected to succeed\n Ok(())\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Testing", "heading_path": ["Testing attributes", "The `test` attribute"], "path": "attributes/testing.md", "url": "https://doc.rust-lang.org/reference/attributes/testing.html#the-test-attribute", "has_code": true, "code_tags": ["rust,no_run"]}} {"id": "reference/attributes/testing.md#the-ignore-attribute-2", "text": "The Rust Reference › Testing attributes › The `ignore` attribute\n\nThe *`ignore` attribute* can be used with the `test` attribute to tell the test harness to not execute that function as a test.\n```rust,no_run\n#[test]\n#[ignore]\nfn check_thing() {\n // …\n}\n```\nThe `rustc` test harness supports the `--include-ignored` flag to force ignored tests to be run.\nThe `ignore` attribute uses the [MetaWord] and [MetaNameValueStr] syntaxes.\nThe [MetaNameValueStr] form of the `ignore` attribute provides a way to specify a reason why the test is ignored.\n```rust,no_run\n#[test]\n#[ignore = \"not yet implemented\"]\nfn mytest() {\n // …\n}\n```\nThe `ignore` attribute may only be applied to functions annotated with the `test` attribute.\n`rustc` ignores use in other positions but lints against it. This may become an error in the future.\nOnly the first use of `ignore` on a function has effect.\n`rustc` lints against any use following the first. This may become an error in the future.\nIgnored tests are still compiled when in test mode, but they are not executed.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Testing", "heading_path": ["Testing attributes", "The `ignore` attribute"], "path": "attributes/testing.md", "url": "https://doc.rust-lang.org/reference/attributes/testing.html#the-ignore-attribute", "has_code": true, "code_tags": ["rust,no_run"]}} {"id": "reference/attributes/testing.md#the-should_panic-attribute-3", "text": "The Rust Reference › Testing attributes › The `should_panic` attribute\n\nThe *`should_panic` attribute* causes a test to pass only if the test function to which the attribute is applied panics.\n```rust,no_run\n#[test]\n#[should_panic(expected = \"values don't match\")]\nfn mytest() {\n assert_eq!(1, 2, \"values don't match\");\n}\n```\nThe `should_panic` attribute has these forms:\n- [MetaWord]\n```rust,no_run\n#[test]\n#[should_panic]\nfn mytest() { panic!(\"error: some message, and more\"); }\n```\n- [MetaNameValueStr] --- The given string must appear within the panic message for the test to pass.\n```rust,no_run\n#[test]\n#[should_panic = \"some message\"]\nfn mytest() { panic!(\"error: some message, and more\"); }\n```\n- [MetaListNameValueStr] --- As with the [MetaNameValueStr] syntax, the given string must appear within the panic message.\n```rust,no_run\n#[test]\n#[should_panic(expected = \"some message\")]\nfn mytest() { panic!(\"error: some message, and more\"); }\n```\nThe `should_panic` attribute may only be applied to functions annotated with the `test` attribute.\n`rustc` ignores use in other positions but lints against it. This may become an error in the future.\nOnly the first use of `should_panic` on a function has effect.\n`rustc` lints against any use following the first with a future-compatibility warning. This may become an error in the future.\nWhen the [MetaNameValueStr] form or the [MetaListNameValueStr] form with the `expected` key is used, the given string must appear somewhere within the panic message for the test to pass.\nThe return type of the test function must be `()`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Testing", "heading_path": ["Testing attributes", "The `should_panic` attribute"], "path": "attributes/testing.md", "url": "https://doc.rust-lang.org/reference/attributes/testing.html#the-should_panic-attribute", "has_code": true, "code_tags": ["rust,no_run"]}} {"id": "reference/attributes/derive.md#derive-0", "text": "The Rust Reference › Derive\n\nThe *`derive` attribute* invokes one or more [derive macros], allowing new [items] to be automatically generated for data structures. You can create `derive` macros with [procedural macros].\nThe `PartialEq` derive macro emits an [implementation] of [`PartialEq`] for `Foo where T: PartialEq`. The `Clone` derive macro does likewise for [`Clone`].\n```rust\n#[derive(PartialEq, Clone)]\nstruct Foo {\n a: i32,\n b: T,\n}\n```\nThe generated `impl` items are equivalent to:\n```rust\nimpl PartialEq for Foo {\n fn eq(&self, other: &Foo) -> bool {\n self.a == other.a && self.b == other.b\n }\n}\n\nimpl Clone for Foo {\n fn clone(&self) -> Self {\n Foo { a: self.a.clone(), b: self.b.clone() }\n }\n}\n```\nThe `derive` attribute uses the [MetaListPaths] syntax to specify a list of paths to [derive macros] to invoke.\nThe `derive` attribute may only be applied to structs, enums, and unions.\nThe `derive` attribute may be used any number of times on an item. All derive macros listed in all attributes are invoked.\nThe `derive` attribute is exported in the standard library as:\n- [`core::derive`]\n- [`std::derive`]\n- [`core::prelude::v1::derive`]\n- [`std::prelude::v1::derive`]\nBuilt-in derives are defined in the language prelude. The list of built-in derives are:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Derive", "heading_path": ["Derive"], "path": "attributes/derive.md", "url": "https://doc.rust-lang.org/reference/attributes/derive.html#derive", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/attributes/derive.md#derive-1", "text": "The Rust Reference › Derive\n\n- [`Clone`]\n- [`Copy`]\n- [`Debug`]\n- [`Default`]\n- [`Eq`]\n- [`Hash`]\n- [`Ord`]\n- [`PartialEq`]\n- [`PartialOrd`]\nThe built-in derives include the `automatically_derived` attribute on the implementations they generate.\nDuring macro expansion, for each element in the list of derives, the corresponding derive macro expands to zero or more [items].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Derive", "heading_path": ["Derive"], "path": "attributes/derive.md", "url": "https://doc.rust-lang.org/reference/attributes/derive.html#derive", "has_code": false, "code_tags": []}} {"id": "reference/attributes/derive.md#the-automatically_derived-attribute-2", "text": "The Rust Reference › Derive › The `automatically_derived` attribute\n\nThe *`automatically_derived` attribute* is used to annotate an [implementation] to indicate that it was automatically created by a [derive macro]. It has no direct effect, but it may be used by tools and diagnostic lints to detect these automatically generated implementations.\nGiven [`#[derive(Clone)]`][macro@Clone] on `struct Example`, the [derive macro] may produce:\n```rust\n#[automatically_derived]\nimpl ::core::clone::Clone for Example {\n #[inline]\n fn clone(&self) -> Self {\n Example\n }\n}\n```\nThe `automatically_derived` attribute uses the [MetaWord] syntax.\nThe `automatically_derived` attribute may only be applied to an [implementation].\n`rustc` ignores use in other positions but lints against it. This may become an error in the future.\nUsing `automatically_derived` more than once on an implementation has the same effect as using it once.\n`rustc` lints against any use following the first.\nThe `automatically_derived` attribute has no behavior.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Derive", "heading_path": ["Derive", "The `automatically_derived` attribute"], "path": "attributes/derive.md", "url": "https://doc.rust-lang.org/reference/attributes/derive.html#the-automatically_derived-attribute", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/attributes/diagnostics.md#diagnostic-attributes-0", "text": "The Rust Reference › Diagnostic attributes\n\nThe following [attributes] are used for controlling or generating diagnostic\nmessages during compilation.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Diagnostics", "heading_path": ["Diagnostic attributes"], "path": "attributes/diagnostics.md", "url": "https://doc.rust-lang.org/reference/attributes/diagnostics.html#diagnostic-attributes", "has_code": false, "code_tags": []}} {"id": "reference/attributes/diagnostics.md#lint-check-attributes-1", "text": "The Rust Reference › Diagnostic attributes › Lint check attributes\n\nA lint check names a potentially undesirable coding pattern, such as\nunreachable code or omitted documentation.\nThe lint attributes `allow`,\n`expect`, `warn`, `deny`, and `forbid` use the [MetaListPaths] syntax\nto specify a list of lint names to change the lint level for the entity\nto which the attribute applies.\nFor any lint check `C`:\n* `#[allow(C)]` overrides the check for `C` so that violations will go\n unreported.\n* `#[expect(C)]` indicates that lint `C` is expected to be emitted. The\n attribute will suppress the emission of `C` or issue a warning, if the\n expectation is unfulfilled.\n* `#[warn(C)]` warns about violations of `C` but continues compilation.\n* `#[deny(C)]` signals an error after encountering a violation of `C`,\n* `#[forbid(C)]` is the same as `deny(C)`, but also forbids changing the lint\n level afterwards,\nThe lint checks supported by `rustc` can be found via `rustc -W help`, along with their default settings and are documented in the [rustc book].\n```rust\npub mod m1 {\n // Missing documentation is ignored here\n #[allow(missing_docs)]\n pub fn undocumented_one() -> i32 { 1 }\n\n // Missing documentation signals a warning here\n #[warn(missing_docs)]\n pub fn undocumented_too() -> i32 { 2 }\n\n // Missing documentation signals an error here\n #[deny(missing_docs)]\n pub fn undocumented_end() -> i32 { 3 }\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Diagnostics", "heading_path": ["Diagnostic attributes", "Lint check attributes"], "path": "attributes/diagnostics.md", "url": "https://doc.rust-lang.org/reference/attributes/diagnostics.html#lint-check-attributes", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/attributes/diagnostics.md#lint-check-attributes-2", "text": "The Rust Reference › Diagnostic attributes › Lint check attributes\n\nLint attributes can override the level specified from a previous attribute, as\nlong as the level does not attempt to change a forbidden lint\n(except for `deny`, which is allowed inside a `forbid` context, but ignored).\nPrevious attributes are those from a higher level in the syntax tree, or from a\nprevious attribute on the same entity as listed in left-to-right source order.\nThis example shows how one can use `allow` and `warn` to toggle a particular\ncheck on and off:\n```rust\n#[warn(missing_docs)]\npub mod m2 {\n #[allow(missing_docs)]\n pub mod nested {\n // Missing documentation is ignored here\n pub fn undocumented_one() -> i32 { 1 }\n\n // Missing documentation signals a warning here,\n // despite the allow above.\n #[warn(missing_docs)]\n pub fn undocumented_two() -> i32 { 2 }\n }\n\n // Missing documentation signals a warning here\n pub fn undocumented_too() -> i32 { 3 }\n}\n```\nThis example shows how one can use `forbid` to disallow uses of `allow` or\n`expect` for that lint check:\n```rust,compile_fail\n#[forbid(missing_docs)]\npub mod m3 {\n // Attempting to toggle warning signals an error here\n #[allow(missing_docs)]\n /// Returns 2.\n pub fn undocumented_too() -> i32 { 2 }\n}\n```\n`rustc` allows setting lint levels on the command-line, and also supports setting caps on the lints that are reported.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Diagnostics", "heading_path": ["Diagnostic attributes", "Lint check attributes"], "path": "attributes/diagnostics.md", "url": "https://doc.rust-lang.org/reference/attributes/diagnostics.html#lint-check-attributes", "has_code": true, "code_tags": ["rust", "rust,compile_fail"]}} {"id": "reference/attributes/diagnostics.md#lint-reasons-3", "text": "The Rust Reference › Diagnostic attributes › Lint check attributes › Lint reasons\n\nAll lint attributes support an additional `reason` parameter, to give context why\na certain attribute was added. This reason will be displayed as part of the lint\nmessage if the lint is emitted at the defined level.\n```rust,edition2015,compile_fail\n// `keyword_idents` is allowed by default. Here we deny it to\n// avoid migration of identifiers when we update the edition.\n#![deny(\n keyword_idents,\n reason = \"we want to avoid these idents to be future compatible\"\n)]\n\n// This name was allowed in Rust's 2015 edition. We still aim to avoid\n// this to be future compatible and not confuse end users.\nfn dyn() {}\n```\nHere is another example, where the lint is allowed with a reason:\n```rust\nuse std::path::PathBuf;\n\npub fn get_path() -> PathBuf {\n // The `reason` parameter on `allow` attributes acts as documentation for the reader.\n #[allow(unused_mut, reason = \"this is only modified on some platforms\")]\n let mut file_name = PathBuf::from(\"git\");\n\n #[cfg(target_os = \"windows\")]\n file_name.set_extension(\"exe\");\n\n file_name\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Diagnostics", "heading_path": ["Diagnostic attributes", "Lint check attributes", "Lint reasons"], "path": "attributes/diagnostics.md", "url": "https://doc.rust-lang.org/reference/attributes/diagnostics.html#lint-reasons", "has_code": true, "code_tags": ["rust", "rust,edition2015,compile_fail"]}} {"id": "reference/attributes/diagnostics.md#the-expect-attribute-4", "text": "The Rust Reference › Diagnostic attributes › Lint check attributes › The `#[expect]` attribute\n\nThe `#[expect(C)]` attribute creates a lint expectation for lint `C`. The\nexpectation will be fulfilled, if a `#[warn(C)]` attribute at the same location\nwould result in a lint emission. If the expectation is unfulfilled, because\nlint `C` would not be emitted, the `unfulfilled_lint_expectations` lint will\nbe emitted at the attribute.\n```rust\nfn main() {\n // This `#[expect]` attribute creates a lint expectation, that the `unused_variables`\n // lint would be emitted by the following statement. This expectation is\n // unfulfilled, since the `question` variable is used by the `println!` macro.\n // Therefore, the `unfulfilled_lint_expectations` lint will be emitted at the\n // attribute.\n #[expect(unused_variables)]\n let question = \"who lives in a pineapple under the sea?\";\n println!(\"{question}\");\n\n // This `#[expect]` attribute creates a lint expectation that will be fulfilled, since\n // the `answer` variable is never used. The `unused_variables` lint, that would usually\n // be emitted, is suppressed. No warning will be issued for the statement or attribute.\n #[expect(unused_variables)]\n let answer = \"SpongeBob SquarePants!\";\n}\n```\nThe lint expectation is only fulfilled by lint emissions which have been suppressed by\nthe `expect` attribute. If the lint level is modified in the scope with other level\nattributes like `allow` or `warn`, the lint emission will be handled accordingly and the\nexpectation will remain unfulfilled.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Diagnostics", "heading_path": ["Diagnostic attributes", "Lint check attributes", "The `#[expect]` attribute"], "path": "attributes/diagnostics.md", "url": "https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-expect-attribute", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/attributes/diagnostics.md#the-expect-attribute-5", "text": "The Rust Reference › Diagnostic attributes › Lint check attributes › The `#[expect]` attribute\n\n```rust\n#[expect(unused_variables)]\nfn select_song() {\n // This will emit the `unused_variables` lint at the warn level\n // as defined by the `warn` attribute. This will not fulfill the\n // expectation above the function.\n #[warn(unused_variables)]\n let song_name = \"Crab Rave\";\n\n // The `allow` attribute suppresses the lint emission. This will not\n // fulfill the expectation as it has been suppressed by the `allow`\n // attribute and not the `expect` attribute above the function.\n #[allow(unused_variables)]\n let song_creator = \"Noisestorm\";\n\n // This `expect` attribute will suppress the `unused_variables` lint emission\n // at the variable. The `expect` attribute above the function will still not\n // be fulfilled, since this lint emission has been suppressed by the local\n // expect attribute.\n #[expect(unused_variables)]\n let song_version = \"Monstercat Release\";\n}\n```\nIf the `expect` attribute contains several lints, each one is expected separately. For a\nlint group it's enough if one lint inside the group has been emitted:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Diagnostics", "heading_path": ["Diagnostic attributes", "Lint check attributes", "The `#[expect]` attribute"], "path": "attributes/diagnostics.md", "url": "https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-expect-attribute", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/attributes/diagnostics.md#the-expect-attribute-6", "text": "The Rust Reference › Diagnostic attributes › Lint check attributes › The `#[expect]` attribute\n\n```rust\n// This expectation will be fulfilled by the unused value inside the function\n// since the emitted `unused_variables` lint is inside the `unused` lint group.\n#[expect(unused)]\npub fn thoughts() {\n let unused = \"I'm running out of examples\";\n}\n\npub fn another_example() {\n // This attribute creates two lint expectations. The `unused_mut` lint will be\n // suppressed and with that fulfill the first expectation. The `unused_variables`\n // wouldn't be emitted, since the variable is used. That expectation will therefore\n // be unsatisfied, and a warning will be emitted.\n #[expect(unused_mut, unused_variables)]\n let mut link = \"https://www.rust-lang.org/\";\n\n println!(\"Welcome to our community: {link}\");\n}\n```\nThe behavior of `#[expect(unfulfilled_lint_expectations)]` is currently defined to always generate the `unfulfilled_lint_expectations` lint.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Diagnostics", "heading_path": ["Diagnostic attributes", "Lint check attributes", "The `#[expect]` attribute"], "path": "attributes/diagnostics.md", "url": "https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-expect-attribute", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/attributes/diagnostics.md#lint-groups-7", "text": "The Rust Reference › Diagnostic attributes › Lint check attributes › Lint groups\n\nLints may be organized into named groups so that the level of related lints\ncan be adjusted together. Using a named group is equivalent to listing out the\nlints within that group.\n```rust,compile_fail\n// This allows all lints in the \"unused\" group.\n#[allow(unused)]\n// This overrides the \"unused_must_use\" lint from the \"unused\"\n// group to deny.\n#[deny(unused_must_use)]\nfn example() {\n // This does not generate a warning because the \"unused_variables\"\n // lint is in the \"unused\" group.\n let x = 1;\n // This generates an error because the result is unused and\n // \"unused_must_use\" is marked as \"deny\".\n std::fs::remove_file(\"some_file\"); // ERROR: unused `Result` that must be used\n}\n```\nThere is a special group named \"warnings\" which includes all lints at the\n\"warn\" level. The \"warnings\" group ignores attribute order and applies to all\nlints that would otherwise warn within the entity.\n```rust,compile_fail\n// The order of these two attributes does not matter.\n#[deny(warnings)]\n// The unsafe_code lint is normally \"allow\" by default.\n#[warn(unsafe_code)]\nfn example_err() {\n // This is an error because the `unsafe_code` warning has\n // been lifted to \"deny\".\n unsafe { an_unsafe_fn() } // ERROR: use of `unsafe` block\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Diagnostics", "heading_path": ["Diagnostic attributes", "Lint check attributes", "Lint groups"], "path": "attributes/diagnostics.md", "url": "https://doc.rust-lang.org/reference/attributes/diagnostics.html#lint-groups", "has_code": true, "code_tags": ["rust,compile_fail"]}} {"id": "reference/attributes/diagnostics.md#tool-lint-attributes-8", "text": "The Rust Reference › Diagnostic attributes › Lint check attributes › Tool lint attributes\n\nTool lints allows using scoped lints, to `allow`, `warn`, `deny` or `forbid`\nlints of certain tools.\nTool lints only get checked when the associated tool is active. If a lint\nattribute, such as `allow`, references a nonexistent tool lint, the compiler\nwill not warn about the nonexistent lint until you use the tool.\nOtherwise, they work just like regular lint attributes:\n```rust\n// set the entire `pedantic` clippy lint group to warn\n#![warn(clippy::pedantic)]\n// silence warnings from the `filter_map` clippy lint\n#![allow(clippy::filter_map)]\n\nfn main() {\n // ...\n}\n\n// silence the `cmp_nan` clippy lint just for this function\n#[allow(clippy::cmp_nan)]\nfn foo() {\n // ...\n}\n```\n`rustc` currently recognizes the tool lints for \"[clippy]\" and \"[rustdoc]\".", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Diagnostics", "heading_path": ["Diagnostic attributes", "Lint check attributes", "Tool lint attributes"], "path": "attributes/diagnostics.md", "url": "https://doc.rust-lang.org/reference/attributes/diagnostics.html#tool-lint-attributes", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/attributes/diagnostics.md#the-deprecated-attribute-9", "text": "The Rust Reference › Diagnostic attributes › The `deprecated` attribute\n\nThe *`deprecated` attribute* marks an item as deprecated. `rustc` will issue\nwarnings on use of `#[deprecated]` items. `rustdoc` will show item\ndeprecation, including the `since` version and `note`, if available.\nThe `deprecated` attribute has several forms:\n- `deprecated` --- Issues a generic message.\n- `deprecated = \"message\"` --- Includes the given string in the deprecation\n message.\n- [MetaListNameValueStr] syntax with two optional fields:\n - `since` --- Specifies a version number when the item was deprecated. `rustc`\n does not currently interpret the string, but external tools like [Clippy]\n may check the validity of the value.\n - `note` --- Specifies a string that should be included in the deprecation\n message. This is typically used to provide an explanation about the\n deprecation and preferred alternatives.\nThe `deprecated` attribute may be applied to any [item], [trait item], [enum\nvariant], [struct field], [external block item], or [macro definition]. It\ncannot be applied to trait implementation items. When applied to an item\ncontaining other items, such as a [module] or [implementation], all child\nitems inherit the deprecation attribute.\nHere is an example:\n```rust\n#[deprecated(since = \"5.2.0\", note = \"foo was rarely used. Users should instead use bar\")]\npub fn foo() {}\n\npub fn bar() {}\n```\nThe RFC contains motivations and more details.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Diagnostics", "heading_path": ["Diagnostic attributes", "The `deprecated` attribute"], "path": "attributes/diagnostics.md", "url": "https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-deprecated-attribute", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/attributes/diagnostics.md#the-must_use-attribute-10", "text": "The Rust Reference › Diagnostic attributes › The `must_use` attribute\n\nThe *`must_use` [attribute]* marks a value that should be used.\nThe `must_use` attribute uses the [MetaWord] and [MetaNameValueStr] syntaxes.\n```rust\n#[must_use]\nfn use_me1() -> u8 { 0 }\n\n#[must_use = \"explanation of why it should be used\"]\nfn use_me2() -> u8 { 0 }\n```\nThe `must_use` attribute may be applied to a:\n- [Struct]\n- [Enumeration]\n- [Union]\n- [Function]\n- [Trait]\n`rustc` ignores use in other positions but lints against it. This may become an error in the future.\nThe `must_use` attribute may be used only once on an item.\n`rustc` lints against any use following the first. This may become an error in the future.\nThe `must_use` attribute may include a message by using the [MetaNameValueStr] syntax, e.g., `#[must_use = \"example message\"]`. The message may be emitted as part of the lint.\nWhen the attribute is applied to a [struct], [enumeration], or [union], if the [expression] of an [expression statement] has that type, the use triggers the `unused_must_use` lint.\n```rust,compile_fail\n#![deny(unused_must_use)]\n#[must_use]\nstruct MustUse();\nMustUse(); // ERROR: Unused value that must be used.\n```\nAs an exception to [attributes.diagnostics.must_use.type], the lint does not fire for `Result<(), E>` when `E` is [uninhabited] or for `ControlFlow` when `B` is [uninhabited]. A `#[non_exhaustive]` type from an external crate is not considered uninhabited for this purpose, because it may gain constructors in the future.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Diagnostics", "heading_path": ["Diagnostic attributes", "The `must_use` attribute"], "path": "attributes/diagnostics.md", "url": "https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute", "has_code": true, "code_tags": ["rust", "rust,compile_fail"]}} {"id": "reference/attributes/diagnostics.md#the-must_use-attribute-11", "text": "The Rust Reference › Diagnostic attributes › The `must_use` attribute\n\n```rust\n#![deny(unused_must_use)]\nenum Empty {}\nfn f1() -> Result<(), Empty> { Ok(()) }\nf1(); // OK: `Empty` is uninhabited.\nfn f2() -> ControlFlow { ControlFlow::Continue(()) }\nf2(); // OK: `Empty` is uninhabited.\n```\nIf the [expression] of an [expression statement] is a [call expression] or [method call expression] whose function operand is a function to which the attribute is applied, the use triggers the `unused_must_use` lint.\n```rust,compile_fail\n#![deny(unused_must_use)]\n#[must_use]\nfn f() {}\nf(); // ERROR: Unused return value that must be used.\n```\nIf the [expression] of an [expression statement] is a [call expression] or [method call expression] whose function operand is a function that returns an [impl trait] or a [dyn trait] type where one or more traits in the bound are marked with the attribute, the use triggers the `unused_must_use` lint.\n```rust,compile_fail\n#![deny(unused_must_use)]\n#[must_use]\ntrait Tr {}\nimpl Tr for () {}\nfn f() -> impl Tr {}\nf(); // ERROR: Unused implementor that must be used.\n```\nWhen the attribute is applied to a function in a trait declaration, the rules described in [attributes.diagnostics.must_use.fn] also apply when the function operand of the [call expression] or [method call expression] is an implementation of that function.\n```rust,compile_fail\n#![deny(unused_must_use)]\ntrait Tr {\n #[must_use]\n fn use_me(&self);\n}\n\nimpl Tr for () {\n fn use_me(&self) {}\n}\n\n().use_me(); // ERROR: Unused return value that must be used.\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Diagnostics", "heading_path": ["Diagnostic attributes", "The `must_use` attribute"], "path": "attributes/diagnostics.md", "url": "https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute", "has_code": true, "code_tags": ["rust", "rust,compile_fail"]}} {"id": "reference/attributes/diagnostics.md#the-must_use-attribute-12", "text": "The Rust Reference › Diagnostic attributes › The `must_use` attribute\n\n```rust,compile_fail\n<() as Tr>::use_me(&());\n// ^^^^^^^^^^^ ERROR: Unused return value that must be used.\n```\nWhen checking the [expression] of an [expression statement] for [attributes.diagnostics.must_use.type], [attributes.diagnostics.must_use.fn], [attributes.diagnostics.must_use.trait], and [attributes.diagnostics.must_use.trait-function], the lint looks through block expressions (including [`unsafe` blocks] and [labeled block expressions]) to the trailing expression of each. This applies recursively for nested block expressions.\n```rust,compile_fail\n#![deny(unused_must_use)]\n#[must_use]\nfn f() {}\n\n{ f() }; // ERROR: The lint looks through block expressions.\nunsafe { f() }; // ERROR: The lint looks through `unsafe` blocks.\n{ { f() } }; // ERROR: The lint looks through nested blocks.\n```\nWhen used on a function in a trait implementation, the attribute does nothing.\n```rust\n#![deny(unused_must_use)]\ntrait Tr {\n fn f(&self);\n}\n\nimpl Tr for () {\n #[must_use] // This has no effect.\n fn f(&self) {}\n}\n\n().f(); // OK.\n```\n`rustc` lints against use on functions in trait implementations. This may become an error in the future.\nWrapping the result of a `#[must_use]` function in certain expressions can suppress the fn-based check, because the [expression] of the [expression statement] is not a [call expression] or [method call expression] to a `#[must_use]` function. The type-based check still applies if the type of the overall expression is `#[must_use]`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Diagnostics", "heading_path": ["Diagnostic attributes", "The `must_use` attribute"], "path": "attributes/diagnostics.md", "url": "https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute", "has_code": true, "code_tags": ["rust", "rust,compile_fail"]}} {"id": "reference/attributes/diagnostics.md#the-must_use-attribute-13", "text": "The Rust Reference › Diagnostic attributes › The `must_use` attribute\n\n```rust\n#![deny(unused_must_use)]\n#[must_use]\nfn f() {}\n\n// The fn-based check does not fire for any of these, because the\n// expression of the expression statement is not a call to a\n// `#[must_use]` function.\n(f(),); // Expression is a tuple, not a call.\nSome(f()); // Callee `Some` is not `#[must_use]`.\nif true { f() } else {}; // Expression is an `if`, not a call.\nmatch true { // Expression is a `match`, not a call.\n _ => f()\n};\n```\n```rust,compile_fail\n#![deny(unused_must_use)]\n#[must_use]\nstruct MustUse;\nfn g() -> MustUse { MustUse }\n\n// Despite the `if` expression not being a call, the type-based check\n// fires because the type of the expression is `MustUse`, which has\n// the `#[must_use]` attribute.\nif true { g() } else { MustUse }; // ERROR: Must be used.\n```\nUsing a [let statement] or [destructuring assignment] with a pattern of `_` when a must-used value is purposely discarded is idiomatic.\n```rust\n#![deny(unused_must_use)]\n#[must_use]\nfn f() {}\nlet _ = f(); // OK.\n_ = f(); // OK.\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Diagnostics", "heading_path": ["Diagnostic attributes", "The `must_use` attribute"], "path": "attributes/diagnostics.md", "url": "https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute", "has_code": true, "code_tags": ["rust", "rust,compile_fail"]}} {"id": "reference/attributes/diagnostics.md#the-diagnostic-tool-attribute-namespace-14", "text": "The Rust Reference › Diagnostic attributes › The `diagnostic` tool attribute namespace\n\nThe `#[diagnostic]` attribute namespace is a home for attributes to influence compile-time error messages.\nThe hints provided by these attributes are not guaranteed to be used.\nUnknown attributes in this namespace are accepted, though they may emit warnings for unused attributes.\nAdditionally, invalid inputs to known attributes will typically be a warning (see the attribute definitions for details).\nThis is meant to allow adding or discarding attributes and changing inputs in the future to allow changes without the need to keep the non-meaningful attributes or options working.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Diagnostics", "heading_path": ["Diagnostic attributes", "The `diagnostic` tool attribute namespace"], "path": "attributes/diagnostics.md", "url": "https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-diagnostic-tool-attribute-namespace", "has_code": false, "code_tags": []}} {"id": "reference/attributes/diagnostics.md#the-diagnosticon_unimplemented-attribute-15", "text": "The Rust Reference › Diagnostic attributes › The `diagnostic` tool attribute namespace › The `diagnostic::on_unimplemented` attribute\n\nThe `#[diagnostic::on_unimplemented]` attribute is a hint to the compiler to supplement the error message that would normally be generated in scenarios where a trait is required but not implemented on a type.\nThe attribute should be placed on a [trait declaration], though it is not an error to be located in other positions.\nThe attribute uses the [MetaListNameValueStr] syntax to specify its inputs, though any malformed input to the attribute is not considered as an error to provide both forwards and backwards compatibility.\nThe following keys have the given meaning:\n* `message` --- The text for the top level error message.\n* `label` --- The text for the label shown inline in the broken code in the error message.\n* `note` --- Provides additional notes.\nThe `note` option can appear several times, which results in several note messages being emitted.\nIf any of the other options appears several times the first occurrence of the relevant option specifies the actually used value. Subsequent occurrences generates a warning.\nA warning is generated for any unknown keys.\nAll three options accept a string as an argument, interpreted using the same formatting as a [`std::fmt`] string.\nFormat parameters with the given named parameter will be replaced with the following text:\n* `{Self}` --- The name of the type implementing the trait.\n* `{` *GenericParameterName* `}` --- The name of the generic argument's type for the given generic parameter.\nAny other format parameter will generate a warning, but will otherwise be included in the string as-is.\nInvalid format strings may generate a warning, but are otherwise allowed, but may not display as intended.\nFormat specifiers may generate a warning, but are otherwise ignored.\nIn this example:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Diagnostics", "heading_path": ["Diagnostic attributes", "The `diagnostic` tool attribute namespace", "The `diagnostic::on_unimplemented` attribute"], "path": "attributes/diagnostics.md", "url": "https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-diagnosticon_unimplemented-attribute", "has_code": false, "code_tags": []}} {"id": "reference/attributes/diagnostics.md#the-diagnosticon_unimplemented-attribute-16", "text": "The Rust Reference › Diagnostic attributes › The `diagnostic` tool attribute namespace › The `diagnostic::on_unimplemented` attribute\n\n```rust,compile_fail,E0277\n#[diagnostic::on_unimplemented(\n message = \"My Message for `ImportantTrait<{A}>` implemented for `{Self}`\",\n label = \"My Label\",\n note = \"Note 1\",\n note = \"Note 2\"\n)]\ntrait ImportantTrait {}\n\nfn use_my_trait(_: impl ImportantTrait) {}\n\nfn main() {\n use_my_trait(String::new());\n}\n```\nthe compiler may generate an error message which looks like this:\n```text\nerror[E0277]: My Message for `ImportantTrait` implemented for `String`\n --> src/main.rs:14:18\n |\n14 | use_my_trait(String::new());\n | ------------ ^^^^^^^^^^^^^ My Label\n | |\n | required by a bound introduced by this call\n |\n = help: the trait `ImportantTrait` is not implemented for `String`\n = note: Note 1\n = note: Note 2\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Diagnostics", "heading_path": ["Diagnostic attributes", "The `diagnostic` tool attribute namespace", "The `diagnostic::on_unimplemented` attribute"], "path": "attributes/diagnostics.md", "url": "https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-diagnosticon_unimplemented-attribute", "has_code": true, "code_tags": ["rust,compile_fail,E0277", "text"]}} {"id": "reference/attributes/diagnostics.md#the-diagnosticdo_not_recommend-attribute-17", "text": "The Rust Reference › Diagnostic attributes › The `diagnostic` tool attribute namespace › The `diagnostic::do_not_recommend` attribute\n\nThe `#[diagnostic::do_not_recommend]` attribute is a hint to the compiler to not show the annotated trait implementation as part of a diagnostic message.\nSuppressing the recommendation can be useful if you know that the recommendation would normally not be useful to the programmer. This often occurs with broad, blanket impls. The recommendation may send the programmer down the wrong path, or the trait implementation may be an internal detail that you don't want to expose, or the bounds may not be able to be satisfied by the programmer.\nFor example, in an error message about a type not implementing a required trait, the compiler may find a trait implementation that would satisfy the requirements if it weren't for specific bounds in the trait implementation. The compiler may tell the user that there is an impl, but the problem is the bounds in the trait implementation. The `#[diagnostic::do_not_recommend]` attribute can be used to tell the compiler to *not* tell the user about the trait implementation, and instead simply tell the user the type doesn't implement the required trait.\nThe attribute should be placed on a trait implementation item, though it is not an error to be located in other positions.\nThe attribute does not accept any arguments, though unexpected arguments are not considered as an error.\nIn the following example, there is a trait called `AsExpression` which is used for casting arbitrary types to the `Expression` type used in an SQL library. There is a method called `check` which takes an `AsExpression`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Diagnostics", "heading_path": ["Diagnostic attributes", "The `diagnostic` tool attribute namespace", "The `diagnostic::do_not_recommend` attribute"], "path": "attributes/diagnostics.md", "url": "https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-diagnosticdo_not_recommend-attribute", "has_code": false, "code_tags": []}} {"id": "reference/attributes/diagnostics.md#the-diagnosticdo_not_recommend-attribute-18", "text": "The Rust Reference › Diagnostic attributes › The `diagnostic` tool attribute namespace › The `diagnostic::do_not_recommend` attribute\n\n```rust,compile_fail,E0277\n\n// Uncomment this line to change the recommendation.\n// #[diagnostic::do_not_recommend]\nimpl AsExpression for T\nwhere\n T: Expression,\n{\n type Expression = T;\n}\n\ntrait Foo: Expression + Sized {\n fn check(&self, _: T) -> ::SqlType>>::Expression\n where\n T: AsExpression,\n {\n todo!()\n }\n}\n\nfn main() {\n SelectInt.check(\"bar\");\n}\n```\nThe `SelectInt` type's `check` method is expecting an `Integer` type. Calling it with an i32 type works, as it gets converted to an `Integer` by the `AsExpression` trait. However, calling it with a string does not, and generates a an error that may look like this:\n```text\nerror[E0277]: the trait bound `&str: Expression` is not satisfied\n --> src/main.rs:53:15\n |\n53 | SelectInt.check(\"bar\");\n | ^^^^^ the trait `Expression` is not implemented for `&str`\n |\n = help: the following other types implement trait `Expression`:\n Bound\n SelectInt\nnote: required for `&str` to implement `AsExpression`\n --> src/main.rs:45:13\n |\n45 | impl AsExpression for T\n | ^^^^^^^^^^^^^^^^ ^\n46 | where\n47 | T: Expression,\n | ------------------------ unsatisfied trait bound introduced here\n```\nBy adding the `#[diagnostic::do_not_recommend]` attribute to the blanket `impl` for `AsExpression`, the message changes to:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Diagnostics", "heading_path": ["Diagnostic attributes", "The `diagnostic` tool attribute namespace", "The `diagnostic::do_not_recommend` attribute"], "path": "attributes/diagnostics.md", "url": "https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-diagnosticdo_not_recommend-attribute", "has_code": true, "code_tags": ["rust,compile_fail,E0277", "text"]}} {"id": "reference/attributes/diagnostics.md#the-diagnosticdo_not_recommend-attribute-19", "text": "The Rust Reference › Diagnostic attributes › The `diagnostic` tool attribute namespace › The `diagnostic::do_not_recommend` attribute\n\n```text\nerror[E0277]: the trait bound `&str: AsExpression` is not satisfied\n --> src/main.rs:53:15\n |\n53 | SelectInt.check(\"bar\");\n | ^^^^^ the trait `AsExpression` is not implemented for `&str`\n |\n = help: the trait `AsExpression` is not implemented for `&str`\n but trait `AsExpression` is implemented for it\n = help: for that trait implementation, expected `Text`, found `Integer`\n```\nThe first error message includes a somewhat confusing error message about the relationship of `&str` and `Expression`, as well as the unsatisfied trait bound in the blanket impl. After adding `#[diagnostic::do_not_recommend]`, it no longer considers the blanket impl for the recommendation. The message should be a little clearer, with an indication that a string cannot be converted to an `Integer`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Diagnostics", "heading_path": ["Diagnostic attributes", "The `diagnostic` tool attribute namespace", "The `diagnostic::do_not_recommend` attribute"], "path": "attributes/diagnostics.md", "url": "https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-diagnosticdo_not_recommend-attribute", "has_code": true, "code_tags": ["text"]}} {"id": "reference/attributes/codegen.md#code-generation-attributes-0", "text": "The Rust Reference › Code generation attributes\n\nThe following [attributes] are used for controlling code generation.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Code generation", "heading_path": ["Code generation attributes"], "path": "attributes/codegen.md", "url": "https://doc.rust-lang.org/reference/attributes/codegen.html#code-generation-attributes", "has_code": false, "code_tags": []}} {"id": "reference/attributes/codegen.md#the-inline-attribute-1", "text": "The Rust Reference › Code generation attributes › The `inline` attribute\n\nThe *`inline` [attribute]* suggests whether a copy of the attributed function's code should be placed in the caller rather than generating a call to the function.\n```rust\n#[inline]\npub fn example1() {}\n\n#[inline(always)]\npub fn example2() {}\n\n#[inline(never)]\npub fn example3() {}\n```\n`rustc` automatically inlines functions when doing so seems worthwhile. Use this attribute carefully as poor decisions about what to inline can slow down programs.\nThe syntax for the `inline` attribute is:\n```grammar,attributes\n@root InlineAttribute ->\n `inline` `(` `always` `)`\n | `inline` `(` `never` `)`\n | `inline`\n```\nThe `inline` attribute may only be applied to functions with [bodies] --- [closures], [async blocks], [free functions], [associated functions] in an [inherent impl] or [trait impl], and associated functions in a [trait definition] when those functions have a [default definition] .\n`rustc` ignores use in other positions but lints against it. This may become an error in the future.\nThough the attribute can be applied to [closures] and [async blocks], the usefulness of this is limited as we do not yet support attributes on expressions.\n```rust\n// We allow attributes on statements.\n#[inline] || (); // OK\n#[inline] async {}; // OK\n```\n```rust,compile_fail,E0658\n// We don't yet allow attributes on expressions.\nlet f = #[inline] || (); // ERROR\n```\nOnly the first use of `inline` on a function has effect.\n`rustc` lints against any use following the first. This may become an error in the future.\nThe `inline` attribute supports these modes:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Code generation", "heading_path": ["Code generation attributes", "The `inline` attribute"], "path": "attributes/codegen.md", "url": "https://doc.rust-lang.org/reference/attributes/codegen.html#the-inline-attribute", "has_code": true, "code_tags": ["grammar,attributes", "rust", "rust,compile_fail,E0658"]}} {"id": "reference/attributes/codegen.md#the-inline-attribute-2", "text": "The Rust Reference › Code generation attributes › The `inline` attribute\n\n- `#[inline]` *suggests* performing inline expansion.\n- `#[inline(always)]` *suggests* that inline expansion should always be performed.\n- `#[inline(never)]` *suggests* that inline expansion should never be performed.\nIn every form the attribute is a hint. The compiler may ignore it.\nWhen `inline` is applied to a function in a [trait], it applies only to the code of the [default definition].\nWhen `inline` is applied to an [async function] or [async closure], it applies only to the code of the generated `poll` function.\nFor more details, see Rust issue #129347.\nThe `inline` attribute is ignored if the function is externally exported with [`no_mangle`] or [`export_name`].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Code generation", "heading_path": ["Code generation attributes", "The `inline` attribute"], "path": "attributes/codegen.md", "url": "https://doc.rust-lang.org/reference/attributes/codegen.html#the-inline-attribute", "has_code": false, "code_tags": []}} {"id": "reference/attributes/codegen.md#the-cold-attribute-3", "text": "The Rust Reference › Code generation attributes › The `cold` attribute\n\nThe *`cold` [attribute]* suggests that the attributed function is unlikely to be called which may help the compiler produce better code.\n```rust\n#[cold]\npub fn example() {}\n```\nThe `cold` attribute uses the [MetaWord] syntax.\nThe `cold` attribute may only be applied to functions with [bodies] --- [closures], [async blocks], [free functions], [associated functions] in an [inherent impl] or [trait impl], and associated functions in a [trait definition] when those functions have a [default definition] .\n`rustc` ignores use in other positions but lints against it. This may become an error in the future.\nThough the attribute can be applied to [closures] and [async blocks], the usefulness of this is limited as we do not yet support attributes on expressions.\nOnly the first use of `cold` on a function has effect.\n`rustc` lints against any use following the first. This may become an error in the future.\nWhen `cold` is applied to a function in a [trait], it applies only to the code of the [default definition].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Code generation", "heading_path": ["Code generation attributes", "The `cold` attribute"], "path": "attributes/codegen.md", "url": "https://doc.rust-lang.org/reference/attributes/codegen.html#the-cold-attribute", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/attributes/codegen.md#the-naked-attribute-4", "text": "The Rust Reference › Code generation attributes › The `naked` attribute\n\nThe *`naked` [attribute]* prevents the compiler from emitting a function prologue and epilogue for the attributed function --- a *naked function*.\n```rust\n/// Adds 3 to the given number.\n// SAFETY: The body respects the \"sysv64\" calling convention,\n// upholds the signature, and does not fall through.\n#[unsafe(naked)]\npub extern \"sysv64\" fn add_n(number: u64) -> u64 {\n core::arch::naked_asm!(\n \"add rdi, {}\",\n \"mov rax, rdi\",\n \"ret\",\n const 3,\n )\n}\n```\nThe `naked` attribute uses the [MetaWord] syntax.\nThe `naked` attribute may only be applied to [free functions], [associated functions] in an [inherent impl] or [trait impl], and associated functions in a [trait definition] when those functions have a [default definition].\nOnly the first use of `naked` on a function has effect.\n`rustc` lints against any use following the first.\nThe `naked` attribute must be marked with `unsafe` because the body must respect the function's calling convention, uphold its signature, and either return or diverge (i.e., not fall through past the end of the assembly code).\nThe [function body] must consist of exactly one [`naked_asm!`] macro invocation.\nThe compiler emits no prologue or epilogue for a naked function: the assembly code in the [`naked_asm!`] invocation constitutes its entire body.\nOn entry the assembly code may assume that the call stack and register state are valid per the function's signature and calling convention.\nThe compiler may not duplicate the assembly code except when monomorphizing a polymorphic function.\nThis guarantee matters for naked functions that define symbols.\nThe [`unused_variables` lint] is suppressed in naked functions.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Code generation", "heading_path": ["Code generation attributes", "The `naked` attribute"], "path": "attributes/codegen.md", "url": "https://doc.rust-lang.org/reference/attributes/codegen.html#the-naked-attribute", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/attributes/codegen.md#the-naked-attribute-5", "text": "The Rust Reference › Code generation attributes › The `naked` attribute\n\nThe [`inline` attribute] cannot be applied to a naked function.\nThe [`track_caller` attribute] cannot be applied to a naked function.\nThe [testing attributes] cannot be applied to a naked function.\nThe [`target_feature` attribute] cannot be applied to a naked function.\nA naked function cannot use the [\"Rust\" ABI].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Code generation", "heading_path": ["Code generation attributes", "The `naked` attribute"], "path": "attributes/codegen.md", "url": "https://doc.rust-lang.org/reference/attributes/codegen.html#the-naked-attribute", "has_code": false, "code_tags": []}} {"id": "reference/attributes/codegen.md#the-no_builtins-attribute-6", "text": "The Rust Reference › Code generation attributes › The `no_builtins` attribute\n\nThe *`no_builtins` [attribute]* disables optimization of certain code patterns related to calls to library functions that are assumed to exist.\n```rust\n#![no_builtins]\n```\nThe `no_builtins` attribute uses the [MetaWord] syntax.\nThe `no_builtins` attribute can only be applied to the crate root.\nOnly the first use of the `no_builtins` attribute has effect.\n`rustc` lints against any use following the first.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Code generation", "heading_path": ["Code generation attributes", "The `no_builtins` attribute"], "path": "attributes/codegen.md", "url": "https://doc.rust-lang.org/reference/attributes/codegen.html#the-no_builtins-attribute", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/attributes/codegen.md#the-target_feature-attribute-7", "text": "The Rust Reference › Code generation attributes › The `target_feature` attribute\n\nThe *`target_feature` [attribute]* may be applied to a function to\nenable code generation of that function for specific platform architecture\nfeatures. It uses the [MetaListNameValueStr] syntax with a single key of\n`enable` whose value is a string of comma-separated feature names to enable.\n```rust\n#[target_feature(enable = \"avx2\")]\nfn foo_avx2() {}\n```\nEach [target architecture] has a set of features that may be enabled. It is an\nerror to specify a feature for a target architecture that the crate is not\nbeing compiled for.\nClosures defined within a `target_feature`-annotated function inherit the\nattribute from the enclosing function.\nIt is [undefined behavior] to call a function that is compiled with a feature\nthat is not supported on the current platform the code is running on, *except*\nif the platform explicitly documents this to be safe.\nThe following restrictions apply unless otherwise specified by the platform rules below:\n- Safe `#[target_feature]` functions (and closures that inherit the attribute) can only be safely called within a caller that enables all the `target_feature`s that the callee enables.\n This restriction does not apply in an `unsafe` context.\n- Safe `#[target_feature]` functions (and closures that inherit the attribute) can only be coerced to *safe* function pointers in contexts that enable all the `target_feature`s that the coercee enables.\n This restriction does not apply to `unsafe` function pointers.\nImplicitly enabled features are included in this rule. For example an `sse2` function can call ones marked with `sse`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Code generation", "heading_path": ["Code generation attributes", "The `target_feature` attribute"], "path": "attributes/codegen.md", "url": "https://doc.rust-lang.org/reference/attributes/codegen.html#the-target_feature-attribute", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/attributes/codegen.md#the-target_feature-attribute-8", "text": "The Rust Reference › Code generation attributes › The `target_feature` attribute\n\n```rust\n#[target_feature(enable = \"sse\")]\nfn foo_sse() {}\n\nfn bar() {\n // Calling `foo_sse` here is unsafe, as we must ensure that SSE is\n // available first, even if `sse` is enabled by default on the target\n // platform or manually enabled as compiler flags.\n unsafe {\n foo_sse();\n }\n}\n\n#[target_feature(enable = \"sse\")]\nfn bar_sse() {\n // Calling `foo_sse` here is safe.\n foo_sse();\n || foo_sse();\n}\n\n#[target_feature(enable = \"sse2\")]\nfn bar_sse2() {\n // Calling `foo_sse` here is safe because `sse2` implies `sse`.\n foo_sse();\n}\n```\nA function with a `#[target_feature]` attribute *never* implements the `Fn` family of traits, although closures inheriting features from the enclosing function do.\nThe `#[target_feature]` attribute is not allowed on the following places:\n- the `main` function\n- a `panic_handler` function\n- safe trait methods\n- safe default functions in traits\nFunctions marked with `target_feature` are not inlined into a context that\ndoes not support the given features. The `#[inline(always)]` attribute may not\nbe used with a `target_feature` attribute.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Code generation", "heading_path": ["Code generation attributes", "The `target_feature` attribute"], "path": "attributes/codegen.md", "url": "https://doc.rust-lang.org/reference/attributes/codegen.html#the-target_feature-attribute", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/attributes/codegen.md#x86-or-x86_64-9", "text": "The Rust Reference › Code generation attributes › The `target_feature` attribute › Available features › `x86` or `x86_64`\n\nThe following is a list of the available feature names.\nTarget feature names marked as \"(cfg only)\" in this list may only be used with the `target_feature` conditional compilation option, not with the `target_feature` attribute.\nExecuting code with unsupported features is undefined behavior on this platform.\nHence on this platform use of `#[target_feature]` functions follows the\nabove restrictions.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Code generation", "heading_path": ["Code generation attributes", "The `target_feature` attribute", "Available features", "`x86` or `x86_64`"], "path": "attributes/codegen.md", "url": "https://doc.rust-lang.org/reference/attributes/codegen.html#x86-or-x86_64", "has_code": false, "code_tags": []}} {"id": "reference/attributes/codegen.md#aarch64-10", "text": "The Rust Reference › Code generation attributes › The `target_feature` attribute › Available features › `aarch64`\n\nFeature | Implicitly Enables | Description\n------------|--------------------|-------------------\n`adx` | | [ADX] --- Multi-Precision Add-Carry Instruction Extensions\n`aes` | `sse2` | [AES] --- Advanced Encryption Standard\n`avx` | `sse4.2` | [AVX] --- Advanced Vector Extensions\n`avx2` | `avx` | [AVX2] --- Advanced Vector Extensions 2\n`avx512bf16` | `avx512bw` | [AVX512-BF16] --- Advanced Vector Extensions 512-bit - Bfloat16 Extensions\n`avx512bitalg` | `avx512bw` | [AVX512-BITALG] --- Advanced Vector Extensions 512-bit - Bit Algorithms\n`avx512bw` | `avx512f` | [AVX512-BW] --- Advanced Vector Extensions 512-bit - Byte and Word Instructions\n`avx512cd` | `avx512f` | [AVX512-CD] --- Advanced Vector Extensions 512-bit - Conflict Detection Instructions\n`avx512dq` | `avx512f` | [AVX512-DQ] --- Advanced Vector Extensions 512-bit - Doubleword and Quadword Instructions\n`avx512f` | `avx2`, `fma`, `f16c`| [AVX512-F] --- Advanced Vector Extensions 512-bit - Foundation\n`avx512fp16` | `avx512bw` | [AVX512-FP16] --- Advanced Vector Extensions 512-bit - Float16 Extensions\n`avx512ifma` | `avx512f` | [AVX512-IFMA] --- Advanced Vector Extensions 512-bit - Integer Fused Multiply Add\n`avx512vbmi` | `avx512bw` | [AVX512-VBMI] --- Advanced Vector Extensions 512-bit - Vector Byte Manipulation Instructions\n`avx512vbmi2` | `avx512bw` | [AVX512-VBMI2] --- Advanced Vector Extensions 512-bit - Vector Byte Manipulation Instructions 2\n`avx512vl` | `avx512f` | [AVX512-VL] --- Advanced Vector Extensions 512-bit - Vector Length Extensions\n`avx512vnni` | `avx512f` | [AVX512-VNNI] --- Advanced Vector Extensions 512-bit - Vector Neural Network Instructions\n`avx512vp2intersect`| `avx512f` | [AVX512-VP2INTERSECT] --- Advanced Vector Extensions 512-bit - Vector Pair Intersection to a Pair of Mask Registers\n`avx512vpopcntdq` | `avx512f` | [AVX512-VPOPCNTDQ] --- Advanced Vector Extensions 512-bit - Vector Population Count Instruction\n`avxifma` | `avx2` | [AVX-IFMA] --- Advanced Vector Extensions - Integer Fused Multiply Add\n`avxneconvert` | `avx2` | [AVX-NE-CONVERT] --- Advanced Vector Extensions - No-Exception Floating-Point conversion Instructions\n`avxvnni` | `avx2` | [AVX-VNNI] --- Advanced Vector Extensions - Vector Neural Network Instructions\n`avxvnniint16` | `avx2` | [AVX-VNNI-INT16] --- Advanced Vector Extensions - Vector Neural Network Instructions with 16-bit Integers\n`avxvnniint8` | `avx2` | [AVX-VNNI-INT8] --- Advanced Vector Extensions - Vector Neural Network Instructions with 8-bit Integers\n`bmi1` | | [BMI1] --- Bit Manipulation Instruction Sets\n`bmi2` | | [BMI2] --- Bit Manipulation Instruction Sets 2\n`cmpxchg16b`| | [`cmpxchg16b`] --- Compares and exchange 16 bytes (128 bits) of data atomically\n`f16c` | `avx` | [F16C] --- 16-bit floating point conversion instructions\n`fma` | `avx` | [FMA3] --- Three-operand fused multiply-add\n`fxsr` | | [`fxsave`] and [`fxrstor`] --- Save and restore x87 FPU, MMX Technology, and SSE State\n`gfni` | `sse2` | [GFNI] --- Galois Field New Instructions\n`kl` | `sse2` | [KEYLOCKER] --- Intel Key Locker Instructions\n`lzcnt` | | [`lzcnt`] --- Leading zeros count\n`movbe` | | [`movbe`] --- Move data after swapping bytes\n`pclmulqdq` | `sse2` | [`pclmulqdq`] --- Packed carry-less multiplication quadword\n`popcnt` | | [`popcnt`] --- Count of bits set to 1\n`rdrand` | | [`rdrand`] --- Read random number\n`rdseed` | | [`rdseed`] --- Read random seed\n`sha` | `sse2` | [SHA] --- Secure Hash Algorithm\n`sha512` | `avx2` | [SHA512] --- Secure Hash Algorithm with 512-bit digest\n`sm3` | `avx` | [SM3] --- ShangMi 3 Hash Algorithm\n`sm4` | `avx2` | [SM4] --- ShangMi 4 Cipher Algorithm\n`sse` | | [SSE] --- Streaming SIMD Extensions\n`sse2` | `sse` | [SSE2] --- Streaming SIMD Extensions 2\n`sse3` | `sse2` | [SSE3] --- Streaming SIMD Extensions 3\n`sse4.1` | `ssse3` | [SSE4.1] --- Streaming SIMD Extensions 4.1\n`sse4.2` | `sse4.1` | [SSE4.2] --- Streaming SIMD Extensions 4.2\n`sse4a` | `sse3` | [SSE4a] --- Streaming SIMD Extensions 4a\n`ssse3` | `sse3` | [SSSE3] --- Supplemental Streaming SIMD Extensions 3\n`tbm` | | [TBM] --- Trailing Bit Manipulation\n`vaes` | `avx2`, `aes` | [VAES] --- Vector AES Instructions\n`vpclmulqdq`| `avx`, `pclmulqdq`| [VPCLMULQDQ] --- Vector Carry-less multiplication of Quadwords\n`widekl` | `kl` | [KEYLOCKER_WIDE] --- Intel Wide Keylocker Instructions\n`xsave` | | [`xsave`] --- Save processor extended states\n`xsavec` | | [`xsavec`] --- Save processor extended states with compaction\n`xsaveopt` | | [`xsaveopt`] --- Save processor extended states optimized\n`xsaves` | | [`xsaves`] --- Save processor extended states supervisor", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Code generation", "heading_path": ["Code generation attributes", "The `target_feature` attribute", "Available features", "`aarch64`"], "path": "attributes/codegen.md", "url": "https://doc.rust-lang.org/reference/attributes/codegen.html#aarch64", "has_code": false, "code_tags": []}} {"id": "reference/attributes/codegen.md#aarch64-11", "text": "The Rust Reference › Code generation attributes › The `target_feature` attribute › Available features › `aarch64`\n\nOn this platform the use of `#[target_feature]` functions follows the\nabove restrictions.\nFurther documentation on these features can be found in the [ARM Architecture\nReference Manual], or elsewhere on [developer.arm.com].\nThe following pairs of features should both be marked as enabled or disabled together if used:\n- `paca` and `pacg`, which LLVM currently implements as one feature.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Code generation", "heading_path": ["Code generation attributes", "The `target_feature` attribute", "Available features", "`aarch64`"], "path": "attributes/codegen.md", "url": "https://doc.rust-lang.org/reference/attributes/codegen.html#aarch64", "has_code": false, "code_tags": []}} {"id": "reference/attributes/codegen.md#loongarch-12", "text": "The Rust Reference › Code generation attributes › The `target_feature` attribute › Available features › `loongarch`\n\nFeature | Implicitly Enables | Feature Name\n------- | ------------------ | ------------\n`aes` | `neon` | FEAT_AES & FEAT_PMULL --- Advanced SIMD AES & PMULL instructions\n`bf16` | | FEAT_BF16 --- BFloat16 instructions\n`bti` | | FEAT_BTI --- Branch Target Identification\n`crc` | | FEAT_CRC --- CRC32 checksum instructions\n`dit` | | FEAT_DIT --- Data Independent Timing instructions\n`dotprod` | `neon` | FEAT_DotProd --- Advanced SIMD Int8 dot product instructions\n`dpb` | | FEAT_DPB --- Data cache clean to point of persistence\n`dpb2` | `dpb` | FEAT_DPB2 --- Data cache clean to point of deep persistence\n`f32mm` | `sve` | FEAT_F32MM --- SVE single-precision FP matrix multiply instruction\n`f64mm` | `sve` | FEAT_F64MM --- SVE double-precision FP matrix multiply instruction\n`fcma` | `neon` | FEAT_FCMA --- Floating point complex number support\n`fhm` | `fp16` | FEAT_FHM --- Half-precision FP FMLAL instructions\n`flagm` | | FEAT_FLAGM --- Conditional flag manipulation\n`fp16` | `neon` | FEAT_FP16 --- Half-precision FP data processing\n`frintts` | | FEAT_FRINTTS --- Floating-point to int helper instructions\n`i8mm` | | FEAT_I8MM --- Int8 Matrix Multiplication\n`jsconv` | `neon` | FEAT_JSCVT --- JavaScript conversion instruction\n`lor` | | FEAT_LOR --- Limited Ordering Regions extension\n`lse` | | FEAT_LSE --- Large System Extensions\n`mte` | | FEAT_MTE & FEAT_MTE2 --- Memory Tagging Extension\n`neon` | | FEAT_AdvSimd & FEAT_FP --- Floating Point and Advanced SIMD extension\n`paca` | | FEAT_PAUTH --- Pointer Authentication (address authentication)\n`pacg` | | FEAT_PAUTH --- Pointer Authentication (generic authentication)\n`pan` | | FEAT_PAN --- Privileged Access-Never extension\n`pmuv3` | | FEAT_PMUv3 --- Performance Monitors extension (v3)\n`rand` | | FEAT_RNG --- Random Number Generator\n`ras` | | FEAT_RAS & FEAT_RASv1p1 --- Reliability, Availability and Serviceability extension\n`rcpc` | | FEAT_LRCPC --- Release consistent Processor Consistent\n`rcpc2` | `rcpc` | FEAT_LRCPC2 --- RcPc with immediate offsets\n`rdm` | `neon` | FEAT_RDM --- Rounding Double Multiply accumulate\n`sb` | | FEAT_SB --- Speculation Barrier\n`sha2` | `neon` | FEAT_SHA1 & FEAT_SHA256 --- Advanced SIMD SHA instructions\n`sha3` | `sha2` | FEAT_SHA512 & FEAT_SHA3 --- Advanced SIMD SHA instructions\n`sm4` | `neon` | FEAT_SM3 & FEAT_SM4 --- Advanced SIMD SM3/4 instructions\n`spe` | | FEAT_SPE --- Statistical Profiling Extension\n`ssbs` | | FEAT_SSBS & FEAT_SSBS2 --- Speculative Store Bypass Safe\n`sve` | `neon` | FEAT_SVE --- Scalable Vector Extension\n`sve2` | `sve` | FEAT_SVE2 --- Scalable Vector Extension 2\n`sve2-aes` | `sve2`, `aes` | FEAT_SVE_AES & FEAT_SVE_PMULL128 --- SVE AES instructions\n`sve2-bitperm` | `sve2` | FEAT_SVE2_BitPerm --- SVE Bit Permute\n`sve2-sha3` | `sve2`, `sha3` | FEAT_SVE2_SHA3 --- SVE SHA3 instructions\n`sve2-sm4` | `sve2`, `sm4` | FEAT_SVE2_SM4 --- SVE SM4 instructions\n`tme` | | FEAT_TME --- Transactional Memory Extension\n`vh` | | FEAT_VHE --- Virtualization Host Extensions", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Code generation", "heading_path": ["Code generation attributes", "The `target_feature` attribute", "Available features", "`loongarch`"], "path": "attributes/codegen.md", "url": "https://doc.rust-lang.org/reference/attributes/codegen.html#loongarch", "has_code": false, "code_tags": []}} {"id": "reference/attributes/codegen.md#riscv32-or-riscv64-13", "text": "The Rust Reference › Code generation attributes › The `target_feature` attribute › Available features › `riscv32` or `riscv64`\n\nOn this platform the use of `#[target_feature]` functions follows the\nabove restrictions.\nFeature | Implicitly Enables | Description\n------------|---------------------|-------------------\n`f` | | F --- Single-precision float-point instructions\n`d` | `f` | D --- Double-precision float-point instructions\n`frecipe` | | FRECIPE --- Reciprocal approximation instructions\n`lasx` | `lsx` | LASX --- 256-bit vector instructions\n`lbt` | | LBT --- Binary translation instructions\n`lsx` | `d` | LSX --- 128-bit vector instructions\n`lvz` | | LVZ --- Virtualization instructions\n`div32` | | DIV32 --- Division instructions accepting non-sign-extended 32-bit operands\n`lam-bh` | | LAM-BH --- Atomic swap and add instructions for byte and halfword\n`lamcas` | | LAMCAS --- Atomic compare-and-swap instructions for byte, halfword, word, and doubleword\n`ld-seq-sa` | | LD-SEQ-SA --- Sequential ordering of load operations to the same address\n`scq` | | SCQ --- Store-conditional quadword instructions\nOn this platform the use of `#[target_feature]` functions follows the\nabove restrictions.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Code generation", "heading_path": ["Code generation attributes", "The `target_feature` attribute", "Available features", "`riscv32` or `riscv64`"], "path": "attributes/codegen.md", "url": "https://doc.rust-lang.org/reference/attributes/codegen.html#riscv32-or-riscv64", "has_code": false, "code_tags": []}} {"id": "reference/attributes/codegen.md#riscv32-or-riscv64-14", "text": "The Rust Reference › Code generation attributes › The `target_feature` attribute › Available features › `riscv32` or `riscv64`\n\nFurther documentation on these features can be found in their respective\nspecification. Many specifications are described in the [RISC-V ISA Manual],\n[version 20250508], or in another manual hosted on the [RISC-V GitHub Account].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Code generation", "heading_path": ["Code generation attributes", "The `target_feature` attribute", "Available features", "`riscv32` or `riscv64`"], "path": "attributes/codegen.md", "url": "https://doc.rust-lang.org/reference/attributes/codegen.html#riscv32-or-riscv64", "has_code": false, "code_tags": []}} {"id": "reference/attributes/codegen.md#wasm32-or-wasm64-15", "text": "The Rust Reference › Code generation attributes › The `target_feature` attribute › Available features › `wasm32` or `wasm64`\n\nFeature | Implicitly Enables | Description\n------------|---------------------|-------------------\n`a` | `zaamo`, `zalrsc` | A --- Atomic instructions\n`b` | `zba`, `zbc`, `zbs` | B --- Bit Manipulation instructions\n`c` | `zca` | C --- Compressed instructions\n`d` | `f` | D --- [(cfg only)] Double-Precision Floating-Point\n`e` | | E --- [(cfg only)] Embedded Instruction Set with 16 GPRs\n`f` | `zicsr` | F --- [(cfg only)] Single-Precision Floating-Point\n`m` | | M --- Integer Multiplication and Division instructions\n`za64rs` | `za128rs` | Za64rs --- Platform Behavior: Naturally aligned Reservation sets with ≦ 64 Bytes\n`za128rs` | | Za128rs --- Platform Behavior: Naturally aligned Reservation sets with ≦ 128 Bytes\n`zaamo` | | Zaamo --- Atomic Memory Operation instructions\n`zabha` | `zaamo` | Zabha --- Byte and Halfword Atomic Memory Operation instructions\n`zacas` | `zaamo` | Zacas --- Atomic Compare-and-Swap (CAS) instructions\n`zalrsc` | | Zalrsc --- Load-Reserved/Store-Conditional instructions\n`zama16b` | | Zama16b --- Platform Behavior: Misaligned loads, stores, and AMOs to main memory regions that do not cross a naturally aligned 16-byte boundary are atomic\n`zawrs` | | Zawrs --- Wait-on-Reservation-Set instructions\n`zba` | | Zba --- Address Generation instructions\n`zbb` | | Zbb --- Basic bit-manipulation\n`zbc` | `zbkc` | Zbc --- Carry-less multiplication\n`zbkb` | | Zbkb --- Bit Manipulation Instructions for Cryptography\n`zbkc` | | Zbkc --- Carry-less multiplication for Cryptography\n`zbkx` | | Zbkx --- Crossbar permutations\n`zbs` | | Zbs --- Single-bit instructions\n`zca` | | Zca --- Compressed instructions: integer part subset\n`zcb` | `zca` | Zcb --- Simple Code-size Saving Compressed instructions\n`zcmop` | `zca` | Zcmop --- Compressed May-Be-Operations\n`zic64b` | | Zic64b --- Platform Behavior: Naturally aligned 64 byte Cache blocks\n`zicbom` | | Zicbom --- Cache-Block Management instructions\n`zicbop` | | Zicbop --- Cache-Block Prefetch Hint instructions\n`zicboz` | | Zicboz --- Cache-Block Zero instruction\n`ziccamoa` | | Ziccamoa --- Platform Behavior: Cacheable and Coherent Main memory supports all basic atomic operations\n`ziccif` | | Ziccif --- Platform Behavior: Cacheable and Coherent Main memory supports instruction fetch and fetches of naturally aligned power-of-2 sizes up to `min(ILEN,XLEN)` are atomic\n`zicclsm` | | Zicclsm --- Platform Behavior: Cacheable and Coherent Main memory supports misaligned load/store accesses\n`ziccrse` | | Ziccrse --- Platform Behavior: Cacheable and Coherent Main memory guarantees eventual success on LR/SC sequences\n`zicntr` | `zicsr` | Zicntr --- Base Counters and Timers\n`zicond` | | Zicond --- Integer Conditional Operation instructions\n`zicsr` | | Zicsr --- Control and Status Register (CSR) instructions\n`zifencei` | | Zifencei --- Instruction-Fetch Fence instruction\n`zihintntl` | | Zihintntl --- Non-Temporal Locality Hint instructions\n`zihintpause` | | Zihintpause --- Pause Hint instruction\n`zihpm` | `zicsr` | Zihpm --- Hardware Performance Counters\n`zimop` | | Zimop --- May-Be-Operations\n`zk` | `zkn`, `zkr`, `zks`, `zkt`, `zbkb`, `zbkc`, `zkbx` | Zk --- Scalar Cryptography\n`zkn` | `zknd`, `zkne`, `zknh`, `zbkb`, `zbkc`, `zkbx` | Zkn --- NIST Algorithm suite extension\n`zknd` | | Zknd --- NIST Suite: AES Decryption\n`zkne` | | Zkne --- NIST Suite: AES Encryption\n`zknh` | | Zknh --- NIST Suite: Hash Function Instructions\n`zkr` | | Zkr --- Entropy Source Extension\n`zks` | `zksed`, `zksh`, `zbkb`, `zbkc`, `zkbx` | Zks --- ShangMi Algorithm Suite\n`zksed` | | Zksed --- ShangMi Suite: SM4 Block Cipher Instructions\n`zksh` | | Zksh --- ShangMi Suite: SM3 Hash Function Instructions\n`zkt` | | Zkt --- Data Independent Execution Latency Subset\n`ztso` | | Ztso --- Total Store Ordering", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Code generation", "heading_path": ["Code generation attributes", "The `target_feature` attribute", "Available features", "`wasm32` or `wasm64`"], "path": "attributes/codegen.md", "url": "https://doc.rust-lang.org/reference/attributes/codegen.html#wasm32-or-wasm64", "has_code": false, "code_tags": []}} {"id": "reference/attributes/codegen.md#s390x-16", "text": "The Rust Reference › Code generation attributes › The `target_feature` attribute › Available features › `s390x`\n\nSafe `#[target_feature]` functions may always be used in safe contexts on Wasm\nplatforms. It is impossible to cause undefined behavior via the\n`#[target_feature]` attribute because attempting to use instructions\nunsupported by the Wasm engine will fail at load time without the risk of being\ninterpreted in a way different from what the compiler expected.\nFeature | Implicitly Enables | Description\n----------------------|---------------------|-------------------\n`bulk-memory` | | WebAssembly bulk memory operations proposal\n`extended-const` | | WebAssembly extended const expressions proposal\n`mutable-globals` | | WebAssembly mutable global proposal\n`nontrapping-fptoint` | | WebAssembly non-trapping float-to-int conversion proposal\n`relaxed-simd` | `simd128` | WebAssembly relaxed simd proposal\n`sign-ext` | | WebAssembly sign extension operators Proposal\n`simd128` | | WebAssembly simd proposal\n`multivalue` | | WebAssembly multivalue proposal\n`reference-types` | | WebAssembly reference-types proposal\n`tail-call` | | WebAssembly tail-call proposal\nOn `s390x` targets, use of functions with the `#[target_feature]` attribute follows the above restrictions.\nFurther documentation on these features can be found in the \"Additions to z/Architecture\" section of Chapter 1 of the *[z/Architecture Principles of Operation]*.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Code generation", "heading_path": ["Code generation attributes", "The `target_feature` attribute", "Available features", "`s390x`"], "path": "attributes/codegen.md", "url": "https://doc.rust-lang.org/reference/attributes/codegen.html#s390x", "has_code": false, "code_tags": []}} {"id": "reference/attributes/codegen.md#s390x-17", "text": "The Rust Reference › Code generation attributes › The `target_feature` attribute › Available features › `s390x`\n\nFeature | Implicitly Enables | Description\n---------------------------------------|---------------------------------------|---------------------\n`vector` | | 128-bit vector instructions\n`vector-enhancements-1` | `vector` | vector enhancements 1\n`vector-enhancements-2` | `vector-enhancements-1` | vector enhancements 2\n`vector-enhancements-3` | `vector-enhancements-2` | vector enhancements 3\n`vector-packed-decimal` | `vector` | vector packed-decimal\n`vector-packed-decimal-enhancement` | `vector-packed-decimal` | vector packed-decimal enhancement\n`vector-packed-decimal-enhancement-2` | `vector-packed-decimal-enhancement-2` | vector packed-decimal enhancement 2\n`vector-packed-decimal-enhancement-3` | `vector-packed-decimal-enhancement-3` | vector packed-decimal enhancement 3\n`nnp-assist` | `vector` | nnp assist\n`miscellaneous-extensions-2` | | miscellaneous extensions 2\n`miscellaneous-extensions-3` | | miscellaneous extensions 3\n`miscellaneous-extensions-4` | | miscellaneous extensions 4", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Code generation", "heading_path": ["Code generation attributes", "The `target_feature` attribute", "Available features", "`s390x`"], "path": "attributes/codegen.md", "url": "https://doc.rust-lang.org/reference/attributes/codegen.html#s390x", "has_code": false, "code_tags": []}} {"id": "reference/attributes/codegen.md#additional-information-18", "text": "The Rust Reference › Code generation attributes › The `target_feature` attribute › Additional information\n\nSee the [`target_feature` conditional compilation option] for selectively\nenabling or disabling compilation of code based on compile-time settings. Note\nthat this option is not affected by the `target_feature` attribute, and is\nonly driven by the features enabled for the entire crate.\nWhether a feature is enabled can be checked at runtime using a platform-specific macro from the standard library, for instance [`is_x86_feature_detected`] or [`is_aarch64_feature_detected`].\n`rustc` has a default set of features enabled for each target and CPU. The CPU may be chosen with the [`-C target-cpu`] flag. Individual features may be enabled or disabled for an entire crate with the [`-C target-feature`] flag.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Code generation", "heading_path": ["Code generation attributes", "The `target_feature` attribute", "Additional information"], "path": "attributes/codegen.md", "url": "https://doc.rust-lang.org/reference/attributes/codegen.html#additional-information", "has_code": false, "code_tags": []}} {"id": "reference/attributes/codegen.md#the-track_caller-attribute-19", "text": "The Rust Reference › Code generation attributes › The `track_caller` attribute\n\nThe `track_caller` attribute may be applied to any function with `\"Rust\"` ABI\nwith the exception of the entry point `fn main`.\nWhen applied to functions and methods in trait declarations, the attribute applies to all implementations. If the trait provides a\ndefault implementation with the attribute, then the attribute also applies to override implementations.\nWhen applied to a function in an `extern` block the attribute must also be applied to any linked\nimplementations, otherwise undefined behavior results. When applied to a function which is made\navailable to an `extern` block, the declaration in the `extern` block must also have the attribute,\notherwise undefined behavior results.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Code generation", "heading_path": ["Code generation attributes", "The `track_caller` attribute"], "path": "attributes/codegen.md", "url": "https://doc.rust-lang.org/reference/attributes/codegen.html#the-track_caller-attribute", "has_code": false, "code_tags": []}} {"id": "reference/attributes/codegen.md#examples-20", "text": "The Rust Reference › Code generation attributes › The `track_caller` attribute › Behavior › Examples\n\nApplying the attribute to a function `f` allows code within `f` to get a hint of the [`Location`] of\nthe \"topmost\" tracked call that led to `f`'s invocation. At the point of observation, an\nimplementation behaves as if it walks up the stack from `f`'s frame to find the nearest frame of an\n*unattributed* function `outer`, and it returns the [`Location`] of the tracked call in `outer`.\n```rust\n#[track_caller]\nfn f() {\n println!(\"{}\", std::panic::Location::caller());\n}\n```\n`core` provides [`core::panic::Location::caller`] for observing caller locations. It wraps the [`core::intrinsics::caller_location`] intrinsic implemented by `rustc`.\nBecause the resulting `Location` is a hint, an implementation may halt its walk up the stack early. See Limitations for important caveats.\nWhen `f` is called directly by `calls_f`, code in `f` observes its callsite within `calls_f`:\n```rust\nfn calls_f() {\n f(); // <-- f() prints this location\n}\n```\nWhen `f` is called by another attributed function `g` which is in turn called by `calls_g`, code in\nboth `f` and `g` observes `g`'s callsite within `calls_g`:\n```rust\n#[track_caller]\nfn g() {\n println!(\"{}\", std::panic::Location::caller());\n f();\n}\n\nfn calls_g() {\n g(); // <-- g() prints this location twice, once itself and once from f()\n}\n```\nWhen `g` is called by another attributed function `h` which is in turn called by `calls_h`, all code\nin `f`, `g`, and `h` observes `h`'s callsite within `calls_h`:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Code generation", "heading_path": ["Code generation attributes", "The `track_caller` attribute", "Behavior", "Examples"], "path": "attributes/codegen.md", "url": "https://doc.rust-lang.org/reference/attributes/codegen.html#examples", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/attributes/codegen.md#examples-21", "text": "The Rust Reference › Code generation attributes › The `track_caller` attribute › Behavior › Examples\n\n```rust\n#[track_caller]\nfn h() {\n println!(\"{}\", std::panic::Location::caller());\n g();\n}\n\nfn calls_h() {\n h(); // <-- prints this location three times, once itself, once from g(), once from f()\n}\n```\nAnd so on.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Code generation", "heading_path": ["Code generation attributes", "The `track_caller` attribute", "Behavior", "Examples"], "path": "attributes/codegen.md", "url": "https://doc.rust-lang.org/reference/attributes/codegen.html#examples", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/attributes/codegen.md#limitations-22", "text": "The Rust Reference › Code generation attributes › The `track_caller` attribute › Limitations\n\nThis information is a hint and implementations are not required to preserve it.\nIn particular, coercing a function with `#[track_caller]` to a function pointer creates a shim which\nappears to observers to have been called at the attributed function's definition site, losing actual\ncaller information across virtual calls. A common example of this coercion is the creation of a\ntrait object whose methods are attributed.\nThe 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Code generation", "heading_path": ["Code generation attributes", "The `track_caller` attribute", "Limitations"], "path": "attributes/codegen.md", "url": "https://doc.rust-lang.org/reference/attributes/codegen.html#limitations", "has_code": false, "code_tags": []}} {"id": "reference/attributes/codegen.md#the-instruction_set-attribute-23", "text": "The Rust Reference › Code generation attributes › The `instruction_set` attribute\n\nThe *`instruction_set` [attribute]* specifies the instruction set that a function will use during code generation. This allows mixing more than one instruction set in a single program.\n```rust,ignore\n#[instruction_set(arm::a32)]\nfn arm_code() {}\n\n#[instruction_set(arm::t32)]\nfn thumb_code() {}\n```\nThe `instruction_set` attribute uses the [MetaListPaths] syntax to specify a single path consisting of the architecture family name and instruction set name.\nThe `instruction_set` attribute may only be applied to functions with [bodies] --- [closures], [async blocks], [free functions], [associated functions] in an [inherent impl] or [trait impl], and associated functions in a [trait definition] when those functions have a [default definition] .\n`rustc` ignores use in other positions but lints against it. This may become an error in the future.\nThough the attribute can be applied to [closures] and [async blocks], the usefulness of this is limited as we do not yet support attributes on expressions.\nThe `instruction_set` attribute may be used only once on a function.\nThe `instruction_set` attribute may only be used with a target that supports the given value.\nWhen the `instruction_set` attribute is used, any inline assembly in the function must use the specified instruction set instead of the target default.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Code generation", "heading_path": ["Code generation attributes", "The `instruction_set` attribute"], "path": "attributes/codegen.md", "url": "https://doc.rust-lang.org/reference/attributes/codegen.html#the-instruction_set-attribute", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "reference/attributes/codegen.md#instruction_set-on-arm-24", "text": "The Rust Reference › Code generation attributes › The `instruction_set` attribute › `instruction_set` on ARM\n\nWhen targeting the `ARMv4T` and `ARMv5te` architectures, the supported values for `instruction_set` are:\n- `arm::a32` --- Generate the function as A32 \"ARM\" code.\n- `arm::t32` --- Generate the function as T32 \"Thumb\" code.\nIf the address of the function is taken as a function pointer, the low bit of the address will depend on the selected instruction set:\n- For `arm::a32` (\"ARM\"), it will be 0.\n- For `arm::t32` (\"Thumb\"), it will be 1.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Code generation", "heading_path": ["Code generation attributes", "The `instruction_set` attribute", "`instruction_set` on ARM"], "path": "attributes/codegen.md", "url": "https://doc.rust-lang.org/reference/attributes/codegen.html#instruction_set-on-arm", "has_code": false, "code_tags": []}} {"id": "reference/attributes/limits.md#limits-0", "text": "The Rust Reference › Limits\n\nThe following [attributes] affect compile-time limits.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Limits", "heading_path": ["Limits"], "path": "attributes/limits.md", "url": "https://doc.rust-lang.org/reference/attributes/limits.html#limits", "has_code": false, "code_tags": []}} {"id": "reference/attributes/limits.md#the-recursion_limit-attribute-1", "text": "The Rust Reference › Limits › The `recursion_limit` attribute\n\nThe *`recursion_limit` attribute* may be applied at the [crate] level to set the\nmaximum depth for potentially infinitely-recursive compile-time operations\nlike macro expansion or auto-dereference.\nIt uses the [MetaNameValueStr]\nsyntax to specify the recursion depth.\nThe default in `rustc` is 128.\n```rust,compile_fail\n#![recursion_limit = \"4\"]\n\nmacro_rules! a {\n () => { a!(1); };\n (1) => { a!(2); };\n (2) => { a!(3); };\n (3) => { a!(4); };\n (4) => { };\n}\n\n// This fails to expand because it requires a recursion depth greater than 4.\na!{}\n```\n```rust,compile_fail\n#![recursion_limit = \"1\"]\n\n// This fails because it requires two recursive steps to auto-dereference.\n(|_: &u8| {})(&&&1);\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Limits", "heading_path": ["Limits", "The `recursion_limit` attribute"], "path": "attributes/limits.md", "url": "https://doc.rust-lang.org/reference/attributes/limits.html#the-recursion_limit-attribute", "has_code": true, "code_tags": ["rust,compile_fail"]}} {"id": "reference/attributes/limits.md#the-type_length_limit-attribute-2", "text": "The Rust Reference › Limits › The `type_length_limit` attribute\n\nThe *`type_length_limit` attribute* sets the maximum number of type substitutions allowed when constructing a concrete type during monomorphization.\n`rustc` only enforces the limit when the nightly `-Zenforce-type-length-limit` flag is active.\nFor more information, see Rust PR #127670.\n```rust,ignore\n#![type_length_limit = \"4\"]\n\nfn f(x: T) {}\n\n// This fails to compile because monomorphizing to\n// `f::<((((i32,), i32), i32), i32)>` requires more\n// than 4 type elements.\nf(((((1,), 2), 3), 4));\n```\nThe default value in `rustc` is `1048576`.\nThe `type_length_limit` attribute uses the [MetaNameValueStr] syntax. The value in the string must be a non-negative number.\nThe `type_length_limit` attribute may only be applied to the crate root.\n`rustc` ignores use in other positions but lints against it. This may become an error in the future.\nOnly the first use of `type_length_limit` on an item has effect.\n`rustc` lints against any use following the first. This may become an error in the future.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Limits", "heading_path": ["Limits", "The `type_length_limit` attribute"], "path": "attributes/limits.md", "url": "https://doc.rust-lang.org/reference/attributes/limits.html#the-type_length_limit-attribute", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "reference/attributes/type_system.md#type-system-attributes-0", "text": "The Rust Reference › Type system attributes\n\nThe following [attributes] are used for changing how a type can be used.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type system", "heading_path": ["Type system attributes"], "path": "attributes/type_system.md", "url": "https://doc.rust-lang.org/reference/attributes/type_system.html#type-system-attributes", "has_code": false, "code_tags": []}} {"id": "reference/attributes/type_system.md#the-non_exhaustive-attribute-1", "text": "The Rust Reference › Type system attributes › The `non_exhaustive` attribute\n\nThe *`non_exhaustive` attribute* indicates that a type or variant may have\nmore fields or variants added in the future.\nIt can be applied to `struct`s, `enum`s, and `enum` variants.\nThe `non_exhaustive` attribute uses the [MetaWord] syntax and thus does not\ntake any inputs.\nWithin the defining crate, `non_exhaustive` has no effect.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type system", "heading_path": ["Type system attributes", "The `non_exhaustive` attribute"], "path": "attributes/type_system.md", "url": "https://doc.rust-lang.org/reference/attributes/type_system.html#the-non_exhaustive-attribute", "has_code": false, "code_tags": []}} {"id": "reference/attributes/type_system.md#the-non_exhaustive-attribute-2", "text": "The Rust Reference › Type system attributes › The `non_exhaustive` attribute\n\n```rust\n#[non_exhaustive]\npub struct Config {\n pub window_width: u16,\n pub window_height: u16,\n}\n\n#[non_exhaustive]\npub struct Token;\n\n#[non_exhaustive]\npub struct Id(pub u64);\n\n#[non_exhaustive]\npub enum Error {\n Message(String),\n Other,\n}\n\npub enum Message {\n #[non_exhaustive] Send { from: u32, to: u32, contents: String },\n #[non_exhaustive] Reaction(u32),\n #[non_exhaustive] Quit,\n}\n\n// Non-exhaustive structs can be constructed as normal within the defining crate.\nlet config = Config { window_width: 640, window_height: 480 };\nlet token = Token;\nlet id = Id(4);\n\n// Non-exhaustive structs can be matched on exhaustively within the defining crate.\nlet Config { window_width, window_height } = config;\nlet Token = token;\nlet Id(id_number) = id;\n\nlet error = Error::Other;\nlet message = Message::Reaction(3);\n\n// Non-exhaustive enums can be matched on exhaustively within the defining crate.\nmatch error {\n Error::Message(ref s) => { },\n Error::Other => { },\n}\n\nmatch message {\n // Non-exhaustive variants can be matched on exhaustively within the defining crate.\n Message::Send { from, to, contents } => { },\n Message::Reaction(id) => { },\n Message::Quit => { },\n}\n```\nOutside of the defining crate, types annotated with `non_exhaustive` have limitations that\npreserve backwards compatibility when new fields or variants are added.\nNon-exhaustive types cannot be constructed outside of the defining crate:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type system", "heading_path": ["Type system attributes", "The `non_exhaustive` attribute"], "path": "attributes/type_system.md", "url": "https://doc.rust-lang.org/reference/attributes/type_system.html#the-non_exhaustive-attribute", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/attributes/type_system.md#the-non_exhaustive-attribute-3", "text": "The Rust Reference › Type system attributes › The `non_exhaustive` attribute\n\n- Non-exhaustive variants (`struct` or `enum` variant) cannot be constructed\n with a [StructExpression] \\(including with [functional update syntax]).\n- The implicitly defined same-named constant of a unit-like struct,\n or the same-named constructor function of a tuple struct,\n has a [visibility] no greater than `pub(crate)`.\n That is, if the struct’s visibility is `pub`, then the constant or constructor’s visibility\n is `pub(crate)`, and otherwise the visibility of the two items is the same\n (as is the case without `#[non_exhaustive]`).\n- `enum` instances can be constructed.\nThe following examples of construction do not compile when outside the defining crate:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type system", "heading_path": ["Type system attributes", "The `non_exhaustive` attribute"], "path": "attributes/type_system.md", "url": "https://doc.rust-lang.org/reference/attributes/type_system.html#the-non_exhaustive-attribute", "has_code": false, "code_tags": []}} {"id": "reference/attributes/type_system.md#the-non_exhaustive-attribute-4", "text": "The Rust Reference › Type system attributes › The `non_exhaustive` attribute\n\n```rust,ignore\n// These are types defined in an upstream crate that have been annotated as\n// `#[non_exhaustive]`.\nuse upstream::{Config, Token, Id, Error, Message};\n\n// Cannot construct an instance of `Config`; if new fields were added in\n// a new version of `upstream` then this would fail to compile, so it is\n// disallowed.\nlet config = Config { window_width: 640, window_height: 480 };\n\n// Cannot construct an instance of `Token`; if new fields were added, then\n// it would not be a unit-like struct any more, so the same-named constant\n// created by it being a unit-like struct is not public outside the crate;\n// this code fails to compile.\nlet token = Token;\n\n// Cannot construct an instance of `Id`; if new fields were added, then\n// its constructor function signature would change, so its constructor\n// function is not public outside the crate; this code fails to compile.\nlet id = Id(5);\n\n// Can construct an instance of `Error`; new variants being introduced would\n// not result in this failing to compile.\nlet error = Error::Message(\"foo\".to_string());\n\n// Cannot construct an instance of `Message::Send` or `Message::Reaction`;\n// if new fields were added in a new version of `upstream` then this would\n// fail to compile, so it is disallowed.\nlet message = Message::Send { from: 0, to: 1, contents: \"foo\".to_string(), };\nlet message = Message::Reaction(0);\n\n// Cannot construct an instance of `Message::Quit`; if this were converted to\n// a tuple enum variant `upstream`, this would fail to compile.\nlet message = Message::Quit;\n```\nThere are limitations when matching on non-exhaustive types outside of the defining crate:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type system", "heading_path": ["Type system attributes", "The `non_exhaustive` attribute"], "path": "attributes/type_system.md", "url": "https://doc.rust-lang.org/reference/attributes/type_system.html#the-non_exhaustive-attribute", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "reference/attributes/type_system.md#the-non_exhaustive-attribute-5", "text": "The Rust Reference › Type system attributes › The `non_exhaustive` attribute\n\n- When pattern matching on a non-exhaustive variant (`struct` or `enum` variant), a [StructPattern] must be used which must include a `..`. A tuple enum variant's constructor's [visibility] is reduced to be no greater than `pub(crate)`.\n- When pattern matching on a non-exhaustive `enum`, matching on a variant does not contribute towards the exhaustiveness of the arms. The following examples of matching do not compile when outside the defining crate:\n```rust, ignore\n// These are types defined in an upstream crate that have been annotated as\n// `#[non_exhaustive]`.\nuse upstream::{Config, Token, Id, Error, Message};\n\n// Cannot match on a non-exhaustive enum without including a wildcard arm.\nmatch error {\n Error::Message(ref s) => { },\n Error::Other => { },\n // would compile with: `_ => {},`\n}\n\n// Cannot match on a non-exhaustive struct without a wildcard.\nif let Ok(Config { window_width, window_height }) = config {\n // would compile with: `..`\n}\n\n// Cannot match a non-exhaustive unit-like or tuple struct except by using\n// braced struct syntax with a wildcard.\n// This would compile as `let Token { .. } = token;`\nlet Token = token;\n// This would compile as `let Id { 0: id_number, .. } = id;`\nlet Id(id_number) = id;\n\nmatch message {\n // Cannot match on a non-exhaustive struct enum variant without including a wildcard.\n Message::Send { from, to, contents } => { },\n // Cannot match on a non-exhaustive tuple or unit enum variant.\n Message::Reaction(type) => { },\n Message::Quit => { },\n}\n```\nIt's also not allowed to use numeric casts (`as`) on enums that contain any non-exhaustive variants.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type system", "heading_path": ["Type system attributes", "The `non_exhaustive` attribute"], "path": "attributes/type_system.md", "url": "https://doc.rust-lang.org/reference/attributes/type_system.html#the-non_exhaustive-attribute", "has_code": true, "code_tags": ["rust, ignore"]}} {"id": "reference/attributes/type_system.md#the-non_exhaustive-attribute-6", "text": "The Rust Reference › Type system attributes › The `non_exhaustive` attribute\n\nFor example, the following enum can be cast because it doesn't contain any non-exhaustive variants:\n```rust\n#[non_exhaustive]\npub enum Example {\n First,\n Second,\n}\n```\nHowever, if the enum contains even a single non-exhaustive variant, casting will result in an error. Consider this modified version of the same enum:\n```rust\n#[non_exhaustive]\npub enum EnumWithNonExhaustiveVariants {\n First,\n #[non_exhaustive]\n Second,\n}\n```\n```rust,ignore\nuse othercrate::EnumWithNonExhaustiveVariants;\n\n// Error: cannot cast an enum with a non-exhaustive variant when it's defined in another crate\nlet _ = EnumWithNonExhaustiveVariants::First as u8;\n```\nNon-exhaustive types are always considered inhabited in downstream crates.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type system", "heading_path": ["Type system attributes", "The `non_exhaustive` attribute"], "path": "attributes/type_system.md", "url": "https://doc.rust-lang.org/reference/attributes/type_system.html#the-non_exhaustive-attribute", "has_code": true, "code_tags": ["rust", "rust,ignore"]}} {"id": "reference/attributes/debugger.md#debugger-attributes-0", "text": "The Rust Reference › Debugger attributes\n\nThe following [attributes] are used for enhancing the debugging experience when using third-party debuggers like GDB or WinDbg.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Debugger", "heading_path": ["Debugger attributes"], "path": "attributes/debugger.md", "url": "https://doc.rust-lang.org/reference/attributes/debugger.html#debugger-attributes", "has_code": false, "code_tags": []}} {"id": "reference/attributes/debugger.md#the-debugger_visualizer-attribute-1", "text": "The Rust Reference › Debugger attributes › The `debugger_visualizer` attribute\n\nThe *`debugger_visualizer` attribute* can be used to embed a debugger visualizer file into the debug information. This improves the debugger experience when displaying values.\n```rust,ignore\n#![debugger_visualizer(natvis_file = \"Example.natvis\")]\n#![debugger_visualizer(gdb_script_file = \"example.py\")]\n```\nThe `debugger_visualizer` attribute uses the [MetaListNameValueStr] syntax to specify its inputs. One of the following keys must be specified:\n- `natvis_file`\n- `gdb_script_file`\nThe `debugger_visualizer` attribute may only be applied to a [module] or to the crate root.\nThe `debugger_visualizer` attribute may be used any number of times on a form. All specified visualizer files will be loaded.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Debugger", "heading_path": ["Debugger attributes", "The `debugger_visualizer` attribute"], "path": "attributes/debugger.md", "url": "https://doc.rust-lang.org/reference/attributes/debugger.html#the-debugger_visualizer-attribute", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "reference/attributes/debugger.md#using-debugger_visualizer-with-natvis-2", "text": "The Rust Reference › Debugger attributes › The `debugger_visualizer` attribute › Using `debugger_visualizer` with Natvis\n\nNatvis 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].\nThis attribute only supports embedding Natvis files on `-windows-msvc` targets.\nThe path to the Natvis file is specified with the `natvis_file` key, which is a path relative to the source file.\n```rust ignore\n#![debugger_visualizer(natvis_file = \"Rectangle.natvis\")]\n\nstruct FancyRect {\n x: f32,\n y: f32,\n dx: f32,\n dy: f32,\n}\n\nfn main() {\n let fancy_rect = FancyRect { x: 10.0, y: 10.0, dx: 5.0, dy: 5.0 };\n println!(\"set breakpoint here\");\n}\n```\n`Rectangle.natvis` contains:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Debugger", "heading_path": ["Debugger attributes", "The `debugger_visualizer` attribute", "Using `debugger_visualizer` with Natvis"], "path": "attributes/debugger.md", "url": "https://doc.rust-lang.org/reference/attributes/debugger.html#using-debugger_visualizer-with-natvis", "has_code": true, "code_tags": ["rust ignore"]}} {"id": "reference/attributes/debugger.md#using-debugger_visualizer-with-natvis-3", "text": "The Rust Reference › Debugger attributes › The `debugger_visualizer` attribute › Using `debugger_visualizer` with Natvis\n\n```xml\n\n\n \n ({x},{y}) + ({dx}, {dy})\n \n \n ({x}, {y})\n \n \n ({x}, {y + dy})\n \n \n ({x + dx}, {y + dy})\n \n \n ({x + dx}, {y})\n \n \n \n\n```\nWhen viewed under WinDbg, the `fancy_rect` variable would be shown as follows:\n```text\nVariables:\nfancy_rect: (10.0, 10.0) + (5.0, 5.0)\nLowerLeft: (10.0, 10.0)\nUpperLeft: (10.0, 15.0)\nUpperRight: (15.0, 15.0)\nLowerRight: (15.0, 10.0)\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Debugger", "heading_path": ["Debugger attributes", "The `debugger_visualizer` attribute", "Using `debugger_visualizer` with Natvis"], "path": "attributes/debugger.md", "url": "https://doc.rust-lang.org/reference/attributes/debugger.html#using-debugger_visualizer-with-natvis", "has_code": true, "code_tags": ["text", "xml"]}} {"id": "reference/attributes/debugger.md#using-debugger_visualizer-with-gdb-4", "text": "The Rust Reference › Debugger attributes › The `debugger_visualizer` attribute › Using `debugger_visualizer` with GDB\n\nGDB 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].\nEmbedded pretty printers are not automatically loaded when debugging a binary under GDB.\nThere are two ways to enable auto-loading embedded pretty printers:\n1. 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].\n1. 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`.\nThese scripts are embedded using the `gdb_script_file` key, which is a path relative to the source file.\n```rust ignore\n#![debugger_visualizer(gdb_script_file = \"printer.py\")]\n\nstruct Person {\n name: String,\n age: i32,\n}\n\nfn main() {\n let bob = Person { name: String::from(\"Bob\"), age: 10 };\n println!(\"set breakpoint here\");\n}\n```\n`printer.py` contains:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Debugger", "heading_path": ["Debugger attributes", "The `debugger_visualizer` attribute", "Using `debugger_visualizer` with GDB"], "path": "attributes/debugger.md", "url": "https://doc.rust-lang.org/reference/attributes/debugger.html#using-debugger_visualizer-with-gdb", "has_code": true, "code_tags": ["rust ignore"]}} {"id": "reference/attributes/debugger.md#using-debugger_visualizer-with-gdb-5", "text": "The Rust Reference › Debugger attributes › The `debugger_visualizer` attribute › Using `debugger_visualizer` with GDB\n\n```python\nimport gdb\n\nclass PersonPrinter:\n \"Print a Person\"\n\n def __init__(self, val):\n self.val = val\n self.name = val[\"name\"]\n self.age = int(val[\"age\"])\n\n def to_string(self):\n return \"{} is {} years old.\".format(self.name, self.age)\n\ndef lookup(val):\n lookup_tag = val.type.tag\n if lookup_tag is None:\n return None\n if \"foo::Person\" == lookup_tag:\n return PersonPrinter(val)\n\n return None\n\ngdb.current_objfile().pretty_printers.append(lookup)\n```\nWhen the crate's debug executable is passed into GDB[^rust-gdb], `print bob` will display:\n```text\n\"Bob\" is 10 years old.\n```\n[^rust-gdb]: Note: This assumes you are using the `rust-gdb` script which configures pretty-printers for standard library types like `String`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Debugger", "heading_path": ["Debugger attributes", "The `debugger_visualizer` attribute", "Using `debugger_visualizer` with GDB"], "path": "attributes/debugger.md", "url": "https://doc.rust-lang.org/reference/attributes/debugger.html#using-debugger_visualizer-with-gdb", "has_code": true, "code_tags": ["python", "text"]}} {"id": "reference/attributes/debugger.md#the-collapse_debuginfo-attribute-6", "text": "The Rust Reference › Debugger attributes › The `collapse_debuginfo` attribute\n\nThe *`collapse_debuginfo` [attribute]* controls whether code locations from a macro definition are collapsed into a single location associated with the macro's call site when generating debuginfo for code calling this macro.\n```rust\n#[collapse_debuginfo(yes)]\nmacro_rules! example {\n () => {\n println!(\"hello!\");\n };\n}\n```\nWhen using a debugger, invoking the `example` macro may appear as though it is calling a function. That is, when you step to the invocation site, it may show the macro invocation rather than the expanded code.\nThe syntax for the `collapse_debuginfo` attribute is:\n```grammar,attributes\n@root CollapseDebuginfoAttribute -> `collapse_debuginfo` `(` CollapseDebuginfoOption `)`\n\nCollapseDebuginfoOption ->\n `yes`\n | `no`\n | `external`\n```\nThe `collapse_debuginfo` attribute may only be applied to a [`macro_rules` definition].\nThe `collapse_debuginfo` attribute may used only once on a macro.\nThe `collapse_debuginfo` attribute accepts these options:\n- `#[collapse_debuginfo(yes)]` --- Code locations in debuginfo are collapsed.\n- `#[collapse_debuginfo(no)]` --- Code locations in debuginfo are not collapsed.\n- `#[collapse_debuginfo(external)]` --- Code locations in debuginfo are collapsed only if the macro comes from a different crate.\nThe `external` behavior is the default for macros that don't have this attribute unless they are built-in macros. For built-in macros the default is `yes`.\n`rustc` has a [`-C collapse-macro-debuginfo`] CLI option to override both the default behavior and the values of any `#[collapse_debuginfo]` attributes.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Debugger", "heading_path": ["Debugger attributes", "The `collapse_debuginfo` attribute"], "path": "attributes/debugger.md", "url": "https://doc.rust-lang.org/reference/attributes/debugger.html#the-collapse_debuginfo-attribute", "has_code": true, "code_tags": ["grammar,attributes", "rust"]}} {"id": "reference/statements-and-expressions.md#statements-and-expressions-0", "text": "The Rust Reference › Statements and expressions\n\nRust 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.\nIn contrast, statements serve _mostly_ to contain and explicitly sequence expression evaluation.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Statements and expressions", "heading_path": ["Statements and expressions"], "path": "statements-and-expressions.md", "url": "https://doc.rust-lang.org/reference/statements-and-expressions.html#statements-and-expressions", "has_code": false, "code_tags": []}} {"id": "reference/statements.md#statements-0", "text": "The Rust Reference › Statements\n\n```grammar,statements\nStatement ->\n `;`\n | Item\n | LetStatement\n | ExpressionStatement\n | OuterAttribute* MacroInvocationSemi\n```\nA *statement* is a component of a [block], which is in turn a component of an outer [expression] or [function].\nRust has two kinds of statement: declaration statements and expression statements.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Statements", "heading_path": ["Statements"], "path": "statements.md", "url": "https://doc.rust-lang.org/reference/statements.html#statements", "has_code": true, "code_tags": ["grammar,statements"]}} {"id": "reference/statements.md#declaration-statements-1", "text": "The Rust Reference › Statements › Declaration statements\n\nA *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.\nThe two kinds of declaration statements are item declarations and `let` statements.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Statements", "heading_path": ["Statements", "Declaration statements"], "path": "statements.md", "url": "https://doc.rust-lang.org/reference/statements.html#declaration-statements", "has_code": false, "code_tags": []}} {"id": "reference/statements.md#item-declarations-2", "text": "The Rust Reference › Statements › Declaration statements › Item declarations\n\nAn *item declaration statement* has a syntactic form identical to an item declaration within a [module].\nDeclaring an item within a statement block restricts its [scope] to the block containing the statement. The item is not given a [canonical path] nor are any sub-items it may declare.\nThe exception to this is that associated items defined by [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.\nThere is no implicit capture of the containing function's generic parameters, parameters, and local variables. For example, `inner` may not access `outer_var`.\n```rust\nfn outer() {\n let outer_var = true;\n\n fn inner() { /* outer_var is not in scope here */ }\n\n inner();\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Statements", "heading_path": ["Statements", "Declaration statements", "Item declarations"], "path": "statements.md", "url": "https://doc.rust-lang.org/reference/statements.html#item-declarations", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/statements.md#let-statements-3", "text": "The Rust Reference › Statements › Declaration statements › `let` statements\n\n```grammar,statements\nLetStatement ->\n OuterAttribute* `let` PatternNoTopAlt ( `:` Type )?\n (\n `=` Expression\n | `=` Expression _except [LazyBooleanExpression] or end with a `}`_\n `else` BlockExpressionNoInnerAttributes\n )? `;`\n```\nA *`let` statement* introduces a new set of [variables], given by a [pattern]. 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.\nWhen no type annotation is given, the compiler will infer the type, or signal an error if insufficient type information is available for definite inference.\nAny 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.\nIf an `else` block is not present, the pattern must be irrefutable. If an `else` block is present, the pattern may be refutable.\nIf 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]).\n```rust\nlet (mut v, w) = (vec![1, 2, 3], 42); // The bindings may be mut or const\nlet Some(t) = v.pop() else { // Refutable patterns require an else block\n panic!(); // The else block must diverge\n};\nlet [u, v] = [v[0], v[1]] else { // This pattern is irrefutable, so the compiler\n // will lint as the else block is redundant.\n panic!();\n};\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Statements", "heading_path": ["Statements", "Declaration statements", "`let` statements"], "path": "statements.md", "url": "https://doc.rust-lang.org/reference/statements.html#let-statements", "has_code": true, "code_tags": ["grammar,statements", "rust"]}} {"id": "reference/statements.md#expression-statements-4", "text": "The Rust Reference › Statements › Expression statements\n\n```grammar,statements\nExpressionStatement ->\n ExpressionWithoutBlock `;`\n | ExpressionWithBlock `;`?\n```\nAn *expression statement* is one that evaluates an [expression] and ignores its result. As a rule, an expression statement's purpose is to trigger the effects of evaluating its expression.\nAn expression that consists of only a block expression 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.\nThe type of [ExpressionWithBlock] expressions when used as statements must be the unit type.\n```rust\nv.pop(); // Ignore the element returned from pop\nif v.is_empty() {\n v.push(5);\n} else {\n v.remove(0);\n} // Semicolon can be omitted.\n[1]; // Separate expression statement, not an indexing expression.\n```\nWhen the trailing semicolon is omitted, the result must be type `()`.\n```rust\n// bad: the block's type is i32, not ()\n// Error: expected `()` because of default return type\n// if true {\n// 1\n// }\n\n// good: the block's type is i32\nif true {\n 1\n} else {\n 2\n};\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Statements", "heading_path": ["Statements", "Expression statements"], "path": "statements.md", "url": "https://doc.rust-lang.org/reference/statements.html#expression-statements", "has_code": true, "code_tags": ["grammar,statements", "rust"]}} {"id": "reference/statements.md#attributes-on-statements-5", "text": "The Rust Reference › Statements › Attributes on statements\n\nStatements accept [outer attributes]. The attributes that have meaning on a statement are [`cfg`], and [the lint check attributes].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Statements", "heading_path": ["Statements", "Attributes on statements"], "path": "statements.md", "url": "https://doc.rust-lang.org/reference/statements.html#attributes-on-statements", "has_code": false, "code_tags": []}} {"id": "reference/expressions.md#expressions-0", "text": "The Rust Reference › Expressions\n\n```grammar,expressions\nExpression ->\n ExpressionWithoutBlock\n | ExpressionWithBlock\n\nExpressionWithoutBlock ->\n OuterAttribute* ExpressionWithoutBlockNoAttrs\n\nExpressionWithoutBlockNoAttrs ->\n LiteralExpression\n | PathExpression\n | OperatorExpression\n | GroupedExpression\n | ArrayExpression\n | AwaitExpression\n | IndexExpression\n | TupleExpression\n | TupleIndexingExpression\n | StructExpression\n | CallExpression\n | MethodCallExpression\n | FieldExpression\n | ClosureExpression\n | AsyncBlockExpression\n | ContinueExpression\n | BreakExpression\n | RangeExpression\n | ReturnExpression\n | UnderscoreExpression\n | MacroInvocation\n\nExpressionWithBlock ->\n OuterAttribute* ExpressionWithBlockNoAttrs\n\nExpressionWithBlockNoAttrs ->\n BlockExpression\n | ConstBlockExpression\n | UnsafeBlockExpression\n | LoopExpression\n | IfExpression\n | MatchExpression\n```\nAn expression may have two roles: it always produces a *value*, and it may have *effects* (otherwise known as \"side effects\").\nAn expression *evaluates to* a value, and has effects during *evaluation*.\nMany expressions contain sub-expressions, called the *operands* of the expression.\nThe meaning of each kind of expression dictates several things:\n* Whether or not to evaluate the operands when evaluating the expression\n* The order in which to evaluate the operands\n* How to combine the operands' values to obtain the value of the expression\nIn 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.\nWe give names to the operands of expressions so that we may discuss them, but these names are not stable and may be changed.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Expressions", "heading_path": ["Expressions"], "path": "expressions.md", "url": "https://doc.rust-lang.org/reference/expressions.html#expressions", "has_code": true, "code_tags": ["grammar,expressions"]}} {"id": "reference/expressions.md#expression-precedence-1", "text": "The Rust Reference › Expressions › Expression precedence\n\nThe 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Expressions", "heading_path": ["Expressions", "Expression precedence"], "path": "expressions.md", "url": "https://doc.rust-lang.org/reference/expressions.html#expression-precedence", "has_code": false, "code_tags": []}} {"id": "reference/expressions.md#expression-precedence-2", "text": "The Rust Reference › Expressions › Expression precedence\n\n| Operator/Expression | Associativity |\n|-----------------------------|---------------------|\n| Paths | |\n| Method calls | |\n| Field expressions | left to right |\n| Function calls, array indexing | |\n| `?` | |\n| Unary `-` `!` `*` borrow | |\n| `as` | left to right |\n| `*` `/` `%` | left to right |\n| `+` `-` | left to right |\n| `<<` `>>` | left to right |\n| `&` | left to right |\n| `^` | left to right |\n| | | left to right |\n| `==` `!=` `<` `>` `<=` `>=` | Require parentheses |\n| `&&` | left to right |\n| || | left to right |\n| `..` `..=` | Require parentheses |\n| `=` `+=` `-=` `*=` `/=` `%=`
`&=` |= `^=` `<<=` `>>=` | right to left |\n| `return` `break` closures | |", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Expressions", "heading_path": ["Expressions", "Expression precedence"], "path": "expressions.md", "url": "https://doc.rust-lang.org/reference/expressions.html#expression-precedence", "has_code": false, "code_tags": []}} {"id": "reference/expressions.md#evaluation-order-of-operands-3", "text": "The Rust Reference › Expressions › Evaluation order of operands\n\nThe 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.\n* Dereference expression\n* Error propagation expression\n* Negation expression\n* Arithmetic and logical binary operators\n* Comparison operators\n* Type cast expression\n* Grouped expression\n* Array expression\n* Await expression\n* Index expression\n* Tuple expression\n* Tuple index expression\n* Struct expression\n* Call expression\n* Method call expression\n* Field expression\n* Break expression\n* Range expression\n* Return expression\nThe 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.\nWhich subexpressions are the operands of an expression is determined by expression precedence as per the previous section.\nFor example, the two `next` method calls will always be called in the same order:\n```rust\nlet mut one_two = vec![1, 2].into_iter();\nassert_eq!(\n (1, 2),\n (one_two.next().unwrap(), one_two.next().unwrap())\n);\n```\nSince this is applied recursively, these expressions are also evaluated from innermost to outermost, ignoring siblings until there are no inner subexpressions.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Expressions", "heading_path": ["Expressions", "Evaluation order of operands"], "path": "expressions.md", "url": "https://doc.rust-lang.org/reference/expressions.html#evaluation-order-of-operands", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions.md#place-expressions-and-value-expressions-4", "text": "The Rust Reference › Expressions › Place expressions and value expressions\n\nExpressions 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.\nA *place expression* is an expression that represents a memory location.\nThese expressions are [paths] which refer to local variables, [static variables], dereferences (`*expr`), [array indexing] expressions (`expr[expr]`), [field] references (`expr.f`) and parenthesized place expressions.\nAll other expressions are value expressions.\nA *value expression* is an expression that represents an actual value.\nThe following contexts are *place expression* contexts:\n* The left operand of a [compound assignment] expression.\n* The operand of a unary [borrow], [raw borrow] or dereference operator.\n* The operand of a [field expression].\n* The indexed operand of an [array indexing expression].\n* The tuple operand of a [tuple indexing expression].\n* The operand of any [implicit borrow].\n* The initializer of a [let statement].\n* The [scrutinee] of an [`if let`], `match`, or [`while let`] expression.\n* The base of a [functional update] struct expression.\nHistorically, place expressions were called *lvalues* and value expressions were called *rvalues*.\nAn *assignee expression* is an expression that appears in the left operand of an assignment expression. Explicitly, the assignee expressions are:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Expressions", "heading_path": ["Expressions", "Place expressions and value expressions"], "path": "expressions.md", "url": "https://doc.rust-lang.org/reference/expressions.html#place-expressions-and-value-expressions", "has_code": false, "code_tags": []}} {"id": "reference/expressions.md#place-expressions-and-value-expressions-5", "text": "The Rust Reference › Expressions › Place expressions and value expressions\n\n- Place expressions.\n- [Underscores].\n- [Tuples] of assignee expressions.\n- Slices of assignee expressions.\n- [Tuple structs] of assignee expressions.\n- [Structs] of assignee expressions (with optionally named fields).\n- [Unit structs]\nArbitrary parenthesisation is permitted inside assignee expressions.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Expressions", "heading_path": ["Expressions", "Place expressions and value expressions"], "path": "expressions.md", "url": "https://doc.rust-lang.org/reference/expressions.html#place-expressions-and-value-expressions", "has_code": false, "code_tags": []}} {"id": "reference/expressions.md#moved-and-copied-types-6", "text": "The Rust Reference › Expressions › Place expressions and value expressions › Moved and copied types\n\nWhen 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.\nIf the type of that value implements [`Copy`], then the value will be copied.\nIn the remaining situations, if that type is [`Sized`], then it may be possible to move the value.\nOnly the following place expressions may be moved out of:\n* [Variables] which are not currently borrowed.\n* Temporary values.\n* Fields of a place expression which can be moved out of and don't implement [`Drop`].\n* The result of dereferencing an expression with type [`Box`] and that can also be moved out of.\nAfter 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.\nIn all other cases, trying to use a place expression in a value expression context is an error.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Expressions", "heading_path": ["Expressions", "Place expressions and value expressions", "Moved and copied types"], "path": "expressions.md", "url": "https://doc.rust-lang.org/reference/expressions.html#moved-and-copied-types", "has_code": false, "code_tags": []}} {"id": "reference/expressions.md#mutability-7", "text": "The Rust Reference › Expressions › Place expressions and value expressions › Mutability\n\nFor a place expression to be assigned to, mutably borrowed, [implicitly mutably borrowed], 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*.\nThe following expressions can be mutable place expression contexts:\n* Mutable [variables] which are not currently borrowed.\n* [Mutable `static` items].\n* [Temporary values].\n* Fields: this evaluates the subexpression in a mutable place expression context.\n* Dereferences of a `*mut T` pointer.\n* 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.\n* Dereferences of a type that implements `DerefMut`: this then requires that the value being dereferenced is evaluated in a mutable place expression context.\n* [Array indexing] of a type that implements `IndexMut`: this then evaluates the value being indexed, but not the index, in mutable place expression context.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Expressions", "heading_path": ["Expressions", "Place expressions and value expressions", "Mutability"], "path": "expressions.md", "url": "https://doc.rust-lang.org/reference/expressions.html#mutability", "has_code": false, "code_tags": []}} {"id": "reference/expressions.md#temporaries-8", "text": "The Rust Reference › Expressions › Place expressions and value expressions › Temporaries\n\nWhen 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] to a `static`. The [drop scope] of the temporary is usually the end of the enclosing statement.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Expressions", "heading_path": ["Expressions", "Place expressions and value expressions", "Temporaries"], "path": "expressions.md", "url": "https://doc.rust-lang.org/reference/expressions.html#temporaries", "has_code": false, "code_tags": []}} {"id": "reference/expressions.md#format_args-9", "text": "The Rust Reference › Expressions › Place expressions and value expressions › Super macros › `format_args!`\n\nCertain built-in macros may create [temporaries] whose scopes may be [extended]. These temporaries are *super temporaries* and these macros are *super macros*. Invocations of these macros are *super macro call expressions*. Arguments to these macros may be *super operands*.\nWhen a super macro call expression is an [extending expression], its super operands are [extending expressions] and the scopes of the super temporaries are [extended]. See [destructors.scope.lifetime-extension.exprs].\nExcept for the format string argument, all arguments passed to [`format_args!`] are *super operands*.\n```rust,edition2024\n// Due to the call being an extending expression and the argument\n// being a super operand, the inner block is an extending expression,\n// so the scope of the temporary created in its trailing expression\n// is extended.\nlet _ = format_args!(\"{}\", { &temp() }); // OK\n```\nThe super operands of [`format_args!`] are [implicitly borrowed] and are therefore [place expression contexts]. When a [value expression] is passed as an argument, it creates a *super temporary*.\n```rust\nlet x = format_args!(\"{}\", temp());\nx; // <-- The temporary is extended, allowing use here.\n```\nThe expansion of a call to [`format_args!`] sometimes creates other internal *super temporaries*.\n```rust,compile_fail,E0716\nlet x = {\n // This call creates an internal temporary.\n let x = format_args!(\"{:?}\", 0);\n x // <-- The temporary is extended, allowing its use here.\n}; // <-- The temporary is dropped here.\nx; // ERROR\n```\n```rust\n// This call doesn't create an internal temporary.\nlet x = { let x = format_args!(\"{}\", 0); x };\nx; // OK\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Expressions", "heading_path": ["Expressions", "Place expressions and value expressions", "Super macros", "`format_args!`"], "path": "expressions.md", "url": "https://doc.rust-lang.org/reference/expressions.html#format_args", "has_code": true, "code_tags": ["rust", "rust,compile_fail,E0716", "rust,edition2024"]}} {"id": "reference/expressions.md#pin-10", "text": "The Rust Reference › Expressions › Place expressions and value expressions › Super macros › `pin!`\n\nThe details of when [`format_args!`] does or does not create internal temporaries are currently unspecified.\nThe argument to [`pin!`] is a *super operand*.\n```rust,edition2024\n// As above for `format_args!`.\nlet _ = pin!({ &temp() }); // OK\n```\nThe argument to [`pin!`] is a [value expression context] and creates a *super temporary*.\n```rust\n// The argument is evaluated into a super temporary.\nlet x = pin!(temp());\n// The temporary is extended, allowing its use here.\nx; // OK\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Expressions", "heading_path": ["Expressions", "Place expressions and value expressions", "Super macros", "`pin!`"], "path": "expressions.md", "url": "https://doc.rust-lang.org/reference/expressions.html#pin", "has_code": true, "code_tags": ["rust", "rust,edition2024"]}} {"id": "reference/expressions.md#implicit-borrows-11", "text": "The Rust Reference › Expressions › Place expressions and value expressions › Implicit borrows\n\nCertain expressions will treat an expression as a place expression by implicitly borrowing it. For example, it is possible to compare two unsized slices for equality directly, because the `==` operator implicitly borrows its operands:\n```rust\nlet a: &[i32];\nlet b: &[i32];\n// ...\n*a == *b;\n// Equivalent form:\n::std::cmp::PartialEq::eq(&*a, &*b);\n```\nImplicit borrows may be taken in the following expressions:\n* Left operand in [method-call] expressions.\n* Left operand in [field] expressions.\n* Left operand in [call expressions].\n* Left operand in [array indexing] expressions.\n* Operand of the dereference operator (`*`).\n* Operands of [comparison].\n* Left operands of the [compound assignment].\n* Arguments to [`format_args!`] except the format string.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Expressions", "heading_path": ["Expressions", "Place expressions and value expressions", "Implicit borrows"], "path": "expressions.md", "url": "https://doc.rust-lang.org/reference/expressions.html#implicit-borrows", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions.md#overloading-traits-12", "text": "The Rust Reference › Expressions › Overloading traits\n\nMany 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Expressions", "heading_path": ["Expressions", "Overloading traits"], "path": "expressions.md", "url": "https://doc.rust-lang.org/reference/expressions.html#overloading-traits", "has_code": false, "code_tags": []}} {"id": "reference/expressions.md#expression-attributes-13", "text": "The Rust Reference › Expressions › Expression attributes\n\n[Outer attributes] before an expression are allowed only in a few specific cases:\n* Before an expression used as a [statement].\n* Elements of [array expressions], [tuple expressions], [call expressions], and tuple-style [struct] expressions.\n* The tail expression of [block expressions].\nThey are never allowed before:\n* [Range] expressions.\n* Binary operator expressions ([ArithmeticOrLogicalExpression], [ComparisonExpression], [LazyBooleanExpression], [TypeCastExpression], [AssignmentExpression], [CompoundAssignmentExpression]).", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Expressions", "heading_path": ["Expressions", "Expression attributes"], "path": "expressions.md", "url": "https://doc.rust-lang.org/reference/expressions.html#expression-attributes", "has_code": false, "code_tags": []}} {"id": "reference/expressions/literal-expr.md#literal-expressions-0", "text": "The Rust Reference › Literal expressions\n\n```grammar,expressions\nLiteralExpression ->\n CHAR_LITERAL\n | STRING_LITERAL\n | RAW_STRING_LITERAL\n | BYTE_LITERAL\n | BYTE_STRING_LITERAL\n | RAW_BYTE_STRING_LITERAL\n | C_STRING_LITERAL\n | RAW_C_STRING_LITERAL\n | INTEGER_LITERAL\n | FLOAT_LITERAL\n | `true`\n | `false`\n```\nA _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.\nA literal is a form of [constant expression], so is evaluated (primarily) at compile time.\nEach of the lexical literal forms described earlier can make up a literal expression, as can the keywords `true` and `false`.\n```rust\n\"hello\"; // string type\n'5'; // character type\n5; // integer type\n```\nIn the descriptions below, the _string representation_ of a token is the sequence of characters from the input which matched the token's production in a *Lexer* grammar snippet.\nThis string representation never includes a character `U+000D` (CR) immediately followed by `U+000A` (LF): this pair would have been previously transformed into a single `U+000A` (LF).", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Literal expressions", "heading_path": ["Literal expressions"], "path": "expressions/literal-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/literal-expr.html#literal-expressions", "has_code": true, "code_tags": ["grammar,expressions", "rust"]}} {"id": "reference/expressions/literal-expr.md#escapes-1", "text": "The Rust Reference › Literal expressions › Escapes\n\nThe descriptions of textual literal expressions below make use of several forms of _escape_.\nEach form of escape is characterised by:\n * an _escape sequence_: a sequence of characters, which always begins with `U+005C` (`\\`)\n * an _escaped value_: either a single character or an empty sequence of characters\nIn the definitions of escapes below:\n * An _octal digit_ is any of the characters in the range \\[`0`-`7`].\n * A _hexadecimal digit_ is any of the characters in the ranges \\[`0`-`9`], \\[`a`-`f`], or \\[`A`-`F`].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Literal expressions", "heading_path": ["Literal expressions", "Escapes"], "path": "expressions/literal-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/literal-expr.html#escapes", "has_code": false, "code_tags": []}} {"id": "reference/expressions/literal-expr.md#simple-escapes-2", "text": "The Rust Reference › Literal expressions › Escapes › Simple escapes\n\nEach sequence of characters occurring in the first column of the following table is an escape sequence.\nIn each case, the escaped value is the character given in the corresponding entry in the second column.\n| Escape sequence | Escaped value |\n|-----------------|--------------------------|\n| `\\0` | U+0000 (NUL) |\n| `\\t` | U+0009 (HT) |\n| `\\n` | U+000A (LF) |\n| `\\r` | U+000D (CR) |\n| `\\\"` | U+0022 (QUOTATION MARK) |\n| `\\'` | U+0027 (APOSTROPHE) |\n| `\\\\` | U+005C (REVERSE SOLIDUS) |", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Literal expressions", "heading_path": ["Literal expressions", "Escapes", "Simple escapes"], "path": "expressions/literal-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/literal-expr.html#simple-escapes", "has_code": false, "code_tags": []}} {"id": "reference/expressions/literal-expr.md#8-bit-escapes-3", "text": "The Rust Reference › Literal expressions › Escapes › 8-bit escapes\n\nThe escape sequence consists of `\\x` followed by two hexadecimal digits.\nThe escaped value is the character whose [Unicode scalar value] is the result of interpreting the final two characters in the escape sequence as a hexadecimal integer, as if by [`u8::from_str_radix`] with radix 16.\nThe escaped value therefore has a [Unicode scalar value] in the range of `u8`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Literal expressions", "heading_path": ["Literal expressions", "Escapes", "8-bit escapes"], "path": "expressions/literal-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/literal-expr.html#8-bit-escapes", "has_code": false, "code_tags": []}} {"id": "reference/expressions/literal-expr.md#7-bit-escapes-4", "text": "The Rust Reference › Literal expressions › Escapes › 7-bit escapes\n\nThe escape sequence consists of `\\x` followed by an octal digit then a hexadecimal digit.\nThe escaped value is the character whose [Unicode scalar value] is the result of interpreting the final two characters in the escape sequence as a hexadecimal integer, as if by [`u8::from_str_radix`] with radix 16.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Literal expressions", "heading_path": ["Literal expressions", "Escapes", "7-bit escapes"], "path": "expressions/literal-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/literal-expr.html#7-bit-escapes", "has_code": false, "code_tags": []}} {"id": "reference/expressions/literal-expr.md#unicode-escapes-5", "text": "The Rust Reference › Literal expressions › Escapes › Unicode escapes\n\nThe escape sequence consists of `\\u{`, followed by a sequence of characters each of which is a hexadecimal digit or `_`, followed by `}`.\nThe escaped value is the character whose [Unicode scalar value] is the result of interpreting the hexadecimal digits contained in the escape sequence as a hexadecimal integer, as if by [`u32::from_str_radix`] with radix 16.\nThe permitted forms of a [CHAR_LITERAL] or [STRING_LITERAL] token ensure that there is such a character.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Literal expressions", "heading_path": ["Literal expressions", "Escapes", "Unicode escapes"], "path": "expressions/literal-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/literal-expr.html#unicode-escapes", "has_code": false, "code_tags": []}} {"id": "reference/expressions/literal-expr.md#string-continuation-escapes-6", "text": "The Rust Reference › Literal expressions › Escapes › String continuation escapes\n\nThe escape sequence consists of `\\` followed immediately by `U+000A` (LF), and all following whitespace characters before the next non-whitespace character. For this purpose, the whitespace characters are `U+0009` (HT), `U+000A` (LF), `U+000D` (CR), and `U+0020` (SPACE).\nThe escaped value is an empty sequence of characters.\nThe effect of this form of escape is that a string continuation skips following whitespace, including additional newlines. Thus `a`, `b` and `c` are equal:\n```rust\nlet a = \"foobar\";\nlet b = \"foo\\\n bar\";\nlet c = \"foo\\\n\n bar\";\n\nassert_eq!(a, b);\nassert_eq!(b, c);\n```\nSkipping additional newlines (as 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 skipping multiple newlines with line continuations. See this issue for more information.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Literal expressions", "heading_path": ["Literal expressions", "Escapes", "String continuation escapes"], "path": "expressions/literal-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/literal-expr.html#string-continuation-escapes", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/literal-expr.md#character-literal-expressions-7", "text": "The Rust Reference › Literal expressions › Character literal expressions\n\nA character literal expression consists of a single [CHAR_LITERAL] token.\nThe expression's type is the primitive [`char`] type.\nThe token must not have a suffix.\nThe token's _literal content_ is the sequence of characters following the first `U+0027` (`'`) and preceding the last `U+0027` (`'`) in the string representation of the token.\nThe literal expression's _represented character_ is derived from the literal content as follows:\n* If the literal content is one of the following forms of escape sequence, the represented character is the escape sequence's escaped value:\n * [Simple escapes]\n * [7-bit escapes]\n * [Unicode escapes]\n* Otherwise the represented character is the single character that makes up the literal content.\nThe expression's value is the [`char`] corresponding to the represented character's [Unicode scalar value].\nThe permitted forms of a [CHAR_LITERAL] token ensure that these rules always produce a single character.\nExamples of character literal expressions:\n```rust\n'R'; // R\n'\\''; // '\n'\\x52'; // R\n'\\u{00E6}'; // LATIN SMALL LETTER AE (U+00E6)\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Literal expressions", "heading_path": ["Literal expressions", "Character literal expressions"], "path": "expressions/literal-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/literal-expr.html#character-literal-expressions", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/literal-expr.md#string-literal-expressions-8", "text": "The Rust Reference › Literal expressions › String literal expressions\n\nA string literal expression consists of a single [STRING_LITERAL] or [RAW_STRING_LITERAL] token.\nThe expression's type is a shared reference (with `static` lifetime) to the primitive [`str`] type. That is, the type is `&'static str`.\nThe token must not have a suffix.\nThe token's _literal content_ is the sequence of characters following the first `U+0022` (`\"`) and preceding the last `U+0022` (`\"`) in the string representation of the token.\nThe literal expression's _represented string_ is a sequence of characters derived from the literal content as follows:\n* If the token is a [STRING_LITERAL], each escape sequence of any of the following forms occurring in the literal content is replaced by the escape sequence's escaped value.\n * [Simple escapes]\n * [7-bit escapes]\n * [Unicode escapes]\n * [String continuation escapes]\n These replacements take place in left-to-right order. For example, the token `\"\\\\x41\"` is converted to the characters `\\` `x` `4` `1`.\n* If the token is a [RAW_STRING_LITERAL], the represented string is identical to the literal content.\nThe expression's value is a reference to a statically allocated [`str`] containing the UTF-8 encoding of the represented string.\nExamples of string literal expressions:\n```rust\n\"foo\"; r\"foo\"; // foo\n\"\\\"foo\\\"\"; r#\"\"foo\"\"#; // \"foo\"\n\n\"foo #\\\"# bar\";\nr##\"foo #\"# bar\"##; // foo #\"# bar\n\n\"\\x52\"; \"R\"; r\"R\"; // R\n\"\\\\x52\"; r\"\\x52\"; // \\x52\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Literal expressions", "heading_path": ["Literal expressions", "String literal expressions"], "path": "expressions/literal-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/literal-expr.html#string-literal-expressions", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/literal-expr.md#byte-literal-expressions-9", "text": "The Rust Reference › Literal expressions › Byte literal expressions\n\nA byte literal expression consists of a single [BYTE_LITERAL] token.\nThe expression's type is the primitive `u8` type.\nThe token must not have a suffix.\nThe token's _literal content_ is the sequence of characters following the first `U+0027` (`'`) and preceding the last `U+0027` (`'`) in the string representation of the token.\nThe literal expression's _represented character_ is derived from the literal content as follows:\n* If the literal content is one of the following forms of escape sequence, the represented character is the escape sequence's escaped value:\n * [Simple escapes]\n * [8-bit escapes]\n* Otherwise the represented character is the single character that makes up the literal content.\nThe expression's value is the represented character's [Unicode scalar value].\nThe permitted forms of a [BYTE_LITERAL] token ensure that these rules always produce a single character, whose Unicode scalar value is in the range of `u8`.\nExamples of byte literal expressions:\n```rust\nb'R'; // 82\nb'\\''; // 39\nb'\\x52'; // 82\nb'\\xA0'; // 160\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Literal expressions", "heading_path": ["Literal expressions", "Byte literal expressions"], "path": "expressions/literal-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/literal-expr.html#byte-literal-expressions", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/literal-expr.md#byte-string-literal-expressions-10", "text": "The Rust Reference › Literal expressions › Byte string literal expressions\n\nA byte string literal expression consists of a single [BYTE_STRING_LITERAL] or [RAW_BYTE_STRING_LITERAL] token.\nThe expression's type is a shared reference (with `static` lifetime) to an array whose element type is `u8`. That is, the type is `&'static [u8; N]`, where `N` is the number of bytes in the represented string described below.\nThe token must not have a suffix.\nThe token's _literal content_ is the sequence of characters following the first `U+0022` (`\"`) and preceding the last `U+0022` (`\"`) in the string representation of the token.\nThe literal expression's _represented string_ is a sequence of characters derived from the literal content as follows:\n* If the token is a [BYTE_STRING_LITERAL], each escape sequence of any of the following forms occurring in the literal content is replaced by the escape sequence's escaped value.\n * [Simple escapes]\n * [8-bit escapes]\n * [String continuation escapes]\n These replacements take place in left-to-right order. For example, the token `b\"\\\\x41\"` is converted to the characters `\\` `x` `4` `1`.\n* If the token is a [RAW_BYTE_STRING_LITERAL], the represented string is identical to the literal content.\nThe expression's value is a reference to a statically allocated array containing the [Unicode scalar values] of the characters in the represented string, in the same order.\nThe permitted forms of [BYTE_STRING_LITERAL] and [RAW_BYTE_STRING_LITERAL] tokens ensure that these rules always produce array element values in the range of `u8`.\nExamples of byte string literal expressions:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Literal expressions", "heading_path": ["Literal expressions", "Byte string literal expressions"], "path": "expressions/literal-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/literal-expr.html#byte-string-literal-expressions", "has_code": false, "code_tags": []}} {"id": "reference/expressions/literal-expr.md#byte-string-literal-expressions-11", "text": "The Rust Reference › Literal expressions › Byte string literal expressions\n\n```rust\nb\"foo\"; br\"foo\"; // foo\nb\"\\\"foo\\\"\"; br#\"\"foo\"\"#; // \"foo\"\n\nb\"foo #\\\"# bar\";\nbr##\"foo #\"# bar\"##; // foo #\"# bar\n\nb\"\\x52\"; b\"R\"; br\"R\"; // R\nb\"\\\\x52\"; br\"\\x52\"; // \\x52\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Literal expressions", "heading_path": ["Literal expressions", "Byte string literal expressions"], "path": "expressions/literal-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/literal-expr.html#byte-string-literal-expressions", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/literal-expr.md#c-string-literal-expressions-12", "text": "The Rust Reference › Literal expressions › C string literal expressions\n\nA C string literal expression consists of a single [C_STRING_LITERAL] or [RAW_C_STRING_LITERAL] token.\nThe expression's type is a shared reference (with `static` lifetime) to the standard library [CStr] type. That is, the type is `&'static core::ffi::CStr`.\nThe token must not have a suffix.\nThe token's _literal content_ is the sequence of characters following the first `\"` and preceding the last `\"` in the string representation of the token.\nThe literal expression's _represented bytes_ are a sequence of bytes derived from the literal content as follows:\n* If the token is a [C_STRING_LITERAL], the literal content is treated as a sequence of items, each of which is either a single Unicode character other than `\\` or an [escape]. The sequence of items is converted to a sequence of bytes as follows:\n * Each single Unicode character contributes its UTF-8 representation.\n * Each [simple escape] contributes the [Unicode scalar value] of its escaped value.\n * Each [8-bit escape] contributes a single byte containing the [Unicode scalar value] of its escaped value.\n * Each [unicode escape] contributes the UTF-8 representation of its escaped value.\n * Each [string continuation escape] contributes no bytes.\n* If the token is a [RAW_C_STRING_LITERAL], the represented bytes are the UTF-8 encoding of the literal content.\nThe permitted forms of [C_STRING_LITERAL] and [RAW_C_STRING_LITERAL] tokens ensure that the represented bytes never include a null byte.\nThe expression's value is a reference to a statically allocated [CStr] whose array of bytes contains the represented bytes followed by a null byte.\nExamples of C string literal expressions:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Literal expressions", "heading_path": ["Literal expressions", "C string literal expressions"], "path": "expressions/literal-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/literal-expr.html#c-string-literal-expressions", "has_code": false, "code_tags": []}} {"id": "reference/expressions/literal-expr.md#c-string-literal-expressions-13", "text": "The Rust Reference › Literal expressions › C string literal expressions\n\n```rust\nc\"foo\"; cr\"foo\"; // foo\nc\"\\\"foo\\\"\"; cr#\"\"foo\"\"#; // \"foo\"\n\nc\"foo #\\\"# bar\";\ncr##\"foo #\"# bar\"##; // foo #\"# bar\n\nc\"\\x52\"; c\"R\"; cr\"R\"; // R\nc\"\\\\x52\"; cr\"\\x52\"; // \\x52\n\nc\"æ\"; // LATIN SMALL LETTER AE (U+00E6)\nc\"\\u{00E6}\"; // LATIN SMALL LETTER AE (U+00E6)\nc\"\\xC3\\xA6\"; // LATIN SMALL LETTER AE (U+00E6)\n\nc\"\\xE6\".to_bytes(); // [230]\nc\"\\u{00E6}\".to_bytes(); // [195, 166]\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Literal expressions", "heading_path": ["Literal expressions", "C string literal expressions"], "path": "expressions/literal-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/literal-expr.html#c-string-literal-expressions", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/literal-expr.md#integer-literal-expressions-14", "text": "The Rust Reference › Literal expressions › Integer literal expressions\n\nAn integer literal expression consists of a single [INTEGER_LITERAL] token.\nIf the token has a [suffix], the suffix must be the name of one of the primitive integer types: `u8`, `i8`, `u16`, `i16`, `u32`, `i32`, `u64`, `i64`, `u128`, `i128`, `usize`, or `isize`, and the expression has that type.\nIf the token has no suffix, the expression's type is determined by type inference:\n* If an integer type can be _uniquely_ determined from the surrounding program context, the expression has that type.\n* If the program context under-constrains the type, it defaults to the signed 32-bit integer `i32`.\n* If the program context over-constrains the type, it is considered a static type error.\nExamples of integer literal expressions:\n```rust\n123; // type i32\n123i32; // type i32\n123u32; // type u32\n123_u32; // type u32\nlet a: u64 = 123; // type u64\n\n0xff; // type i32\n0xff_u8; // type u8\n\n0o70; // type i32\n0o70_i16; // type i16\n\n0b1111_1111_1001_0000; // type i32\n0b1111_1111_1001_0000i64; // type i64\n\n0usize; // type usize\n```\nThe value of the expression is determined from the string representation of the token as follows:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Literal expressions", "heading_path": ["Literal expressions", "Integer literal expressions"], "path": "expressions/literal-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/literal-expr.html#integer-literal-expressions", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/literal-expr.md#integer-literal-expressions-15", "text": "The Rust Reference › Literal expressions › Integer literal expressions\n\n* An integer radix is chosen by inspecting the first two characters of the string, as follows:\n * `0b` indicates radix 2\n * `0o` indicates radix 8\n * `0x` indicates radix 16\n * otherwise the radix is 10.\n* If the radix is not 10, the first two characters are removed from the string.\n* Any suffix is removed from the string.\n* Any underscores are removed from the string.\n* The string is converted to a `u128` value as if by [`u128::from_str_radix`] with the chosen radix. If the value does not fit in `u128`, it is a compiler error.\n* The `u128` value is converted to the expression's type via a [numeric cast].\nThe final cast will truncate the value of the literal if it does not fit in the expression's type. `rustc` includes a [lint check] named `overflowing_literals`, defaulting to `deny`, which rejects expressions where this occurs.\n`-1i8`, for example, is an application of the [negation operator] to the literal expression `1i8`, not a single integer literal expression. See [Overflow] for notes on representing the most negative value for a signed type.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Literal expressions", "heading_path": ["Literal expressions", "Integer literal expressions"], "path": "expressions/literal-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/literal-expr.html#integer-literal-expressions", "has_code": false, "code_tags": []}} {"id": "reference/expressions/literal-expr.md#floating-point-literal-expressions-16", "text": "The Rust Reference › Literal expressions › Floating-point literal expressions\n\nA floating-point literal expression has one of two forms:\n * a single [FLOAT_LITERAL] token\n * a single [INTEGER_LITERAL] token which has a suffix and no radix indicator\nIf the token has a [suffix], the suffix must be the name of one of the primitive floating-point types: `f32` or `f64`, and the expression has that type.\nIf the token has no suffix, the expression's type is determined by type inference:\n* If a floating-point type can be _uniquely_ determined from the surrounding program context, the expression has that type.\n* If the program context under-constrains the type, it defaults to `f64`.\n* If the program context over-constrains the type, it is considered a static type error.\nExamples of floating-point literal expressions:\n```rust\n123.0f64; // type f64\n0.1f64; // type f64\n0.1f32; // type f32\n12E+99_f64; // type f64\n5f32; // type f32\nlet x: f64 = 2.; // type f64\n```\nThe value of the expression is determined from the string representation of the token as follows:\n* Any suffix is removed from the string.\n* Any underscores are removed from the string.\n* The string is converted to the expression's type as if by [`f32::from_str`] or [`f64::from_str`].\n`-1.0`, for example, is an application of the [negation operator] to the literal expression `1.0`, not a single floating-point literal expression.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Literal expressions", "heading_path": ["Literal expressions", "Floating-point literal expressions"], "path": "expressions/literal-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/literal-expr.html#floating-point-literal-expressions", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/literal-expr.md#floating-point-literal-expressions-17", "text": "The Rust Reference › Literal expressions › Floating-point literal expressions\n\n`inf` and `NaN` are not literal tokens. The [`f32::INFINITY`], [`f64::INFINITY`], [`f32::NAN`], and [`f64::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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Literal expressions", "heading_path": ["Literal expressions", "Floating-point literal expressions"], "path": "expressions/literal-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/literal-expr.html#floating-point-literal-expressions", "has_code": false, "code_tags": []}} {"id": "reference/expressions/literal-expr.md#boolean-literal-expressions-18", "text": "The Rust Reference › Literal expressions › Boolean literal expressions\n\nA boolean literal expression consists of one of the keywords `true` or `false`.\nThe expression's type is the primitive [boolean type], and its value is:\n * true if the keyword is `true`\n * false if the keyword is `false`", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Literal expressions", "heading_path": ["Literal expressions", "Boolean literal expressions"], "path": "expressions/literal-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/literal-expr.html#boolean-literal-expressions", "has_code": false, "code_tags": []}} {"id": "reference/expressions/path-expr.md#path-expressions-0", "text": "The Rust Reference › Path expressions\n\n```grammar,expressions\nPathExpression ->\n PathInExpression\n | QualifiedPathInExpression\n```\nA [path] used as an expression context denotes either a local variable or an item.\nPath expressions that resolve to local or static variables are [place expressions]; other paths are [value expressions].\nUsing a [`static mut`] variable requires an [`unsafe` block].\n```rust\nlocal_var;\nglobals::STATIC_VAR;\nunsafe { globals::STATIC_MUT_VAR };\nlet some_constructor = Some::;\nlet push_integer = Vec::::push;\nlet slice_reverse = <[i32]>::reverse;\n```\nEvaluation of associated constants is handled the same way as [`const` blocks].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Path expressions", "heading_path": ["Path expressions"], "path": "expressions/path-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/path-expr.html#path-expressions", "has_code": true, "code_tags": ["grammar,expressions", "rust"]}} {"id": "reference/expressions/block-expr.md#block-expressions-0", "text": "The Rust Reference › Block expressions\n\n```grammar,expressions\nBlockExpression ->\n `{`\n InnerAttribute*\n Statements?\n `}`\n\nBlockExpressionNoInnerAttributes ->\n `{`\n Statements?\n `}`\n\nStatements ->\n Statement+\n | Statement+ ExpressionWithoutBlock\n | ExpressionWithoutBlock\n```\nA *block expression*, or *block*, is a control flow expression and anonymous namespace scope for items and variable declarations.\nAs a control flow expression, a block sequentially executes its component non-item declaration statements and then its final optional expression.\nAs 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. See the [scopes] chapter for more details.\nThe syntax for a block is `{`, then any [inner attributes], then any number of [statements], then an optional expression, called the final operand, and finally a `}`.\nStatements are usually required to be followed by a semicolon, with two exceptions:\n1. Item declaration statements do not need to be followed by a semicolon.\n2. Expression statements usually require a following semicolon except if its outer expression is a flow control expression.\nFurthermore, extra semicolons between statements are allowed, but these semicolons do not affect semantics.\nWhen evaluating a block expression, each statement, except for item declaration statements, is executed sequentially.\nThen the final operand is executed, if given.\nWhen a block contains a [final operand], the block has the type and value of that final operand.\n```rust\nlet x: u8 = { 0u8 }; // `0u8` is the final operand.\nassert_eq!(x, 0);\nlet x: u8 = { (); 0u8 }; // As above.\nassert_eq!(x, 0);\n```\nWhen a block does not contain a [final operand] and the block does not diverge, the block has [unit type] and [unit value].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Block expressions", "heading_path": ["Block expressions"], "path": "expressions/block-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/block-expr.html#block-expressions", "has_code": true, "code_tags": ["grammar,expressions", "rust"]}} {"id": "reference/expressions/block-expr.md#block-expressions-1", "text": "The Rust Reference › Block expressions\n\n```rust\nlet x: () = {}; // Has no final operand.\nassert_eq!(x, ());\nlet x: () = { 0u8; }; // As above.\nassert_eq!(x, ());\n```\nWhen a block does not contain a [final operand] and the block [diverges], the block has the [never type] and has no final value (because its type is [uninhabited]).\n```rust,no_run\nfn f() -> ! { loop {}; } // Diverges and has no final operand.\n// ^^^^^^^^^^^^\n// The body of a function is a block expression.\n```\nObserve that a block having no final operand is distinct from having an explicit final operand with unit type. E.g., even though this block diverges, the type of the block is [unit] rather than [never].\n```rust,compile_fail,E0308\nfn f() -> ! { loop {}; () } // ERROR: Mismatched types.\n// ^^^^^^^^^^^^^^^ This block has unit type.\n```\nAs 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.\nA block is considered to be diverging if all reachable control flow paths contain a diverging expression, unless that expression is a [place expression] that is not read from.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Block expressions", "heading_path": ["Block expressions"], "path": "expressions/block-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/block-expr.html#block-expressions", "has_code": true, "code_tags": ["rust", "rust,compile_fail,E0308", "rust,no_run"]}} {"id": "reference/expressions/block-expr.md#block-expressions-2", "text": "The Rust Reference › Block expressions\n\n```rust,no_run\nfn no_control_flow() -> ! {\n // There are no conditional statements, so this entire function body is diverging.\n loop {}\n}\n\nfn control_flow_diverging() -> ! {\n // All paths are diverging, so this entire function body is diverging.\n if true {\n loop {}\n } else {\n loop {}\n }\n}\n\nfn control_flow_not_diverging() -> () {\n // Some paths are not diverging, so this entire block is not diverging.\n if true {\n ()\n } else {\n loop {}\n }\n}\n\n// Note: This makes use of the unstable never type which is only available on\n// Rust's nightly channel. This is done for illustration purposes. It is\n// possible to encounter this scenario in stable Rust, but requires a more\n// convoluted example.\nstruct Foo {\n x: !,\n}\n\nfn make() -> T { loop {} }\n\nfn diverging_place_read() -> ! {\n let foo = Foo { x: make() };\n // A read of a place expression produces a diverging block.\n let _x = foo.x;\n}\n```\n```rust,compile_fail,E0308\nfn diverging_place_not_read() -> ! {\n let foo = Foo { x: make() };\n // Assignment to `_` means the place is not read.\n let _ = foo.x;\n} // ERROR: Mismatched types.\n```\nBlocks are always [value expressions] and evaluate the last operand in value expression context.\nThis 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Block expressions", "heading_path": ["Block expressions"], "path": "expressions/block-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/block-expr.html#block-expressions", "has_code": true, "code_tags": ["rust,compile_fail,E0308", "rust,no_run"]}} {"id": "reference/expressions/block-expr.md#block-expressions-3", "text": "The Rust Reference › Block expressions\n\n```rust,compile_fail\nstruct Struct;\n\nimpl Struct {\n fn consume_self(self) {}\n fn borrow_self(&self) {}\n}\n\nfn move_by_block_expression() {\n let s = Struct;\n\n // Move the value out of `s` in the block expression.\n (&{ s }).borrow_self();\n\n // Fails to execute because `s` is moved out of.\n s.consume_self();\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Block expressions", "heading_path": ["Block expressions"], "path": "expressions/block-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/block-expr.html#block-expressions", "has_code": true, "code_tags": ["rust,compile_fail"]}} {"id": "reference/expressions/block-expr.md#async-blocks-4", "text": "The Rust Reference › Block expressions › `async` blocks\n\n```grammar,expressions\nAsyncBlockExpression -> `async` `move`? BlockExpression\n```\nAn *async block* is a variant of a block expression which evaluates to a future.\nThe final expression of the block, if present, determines the result value of the future.\nExecuting an async block is similar to executing a closure expression: its immediate effect is to produce and return an anonymous type.\nWhereas closures return a type that implements one or more of the [`std::ops::Fn`] traits, however, the type returned for an async block implements the [`std::future::Future`] trait.\nThe actual data format for this type is unspecified.\nThe 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.\n[!EDITION-2018]\nAsync blocks are only available beginning with Rust 2018.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Block expressions", "heading_path": ["Block expressions", "`async` blocks"], "path": "expressions/block-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/block-expr.html#async-blocks", "has_code": true, "code_tags": ["grammar,expressions"]}} {"id": "reference/expressions/block-expr.md#capture-modes-5", "text": "The Rust Reference › Block expressions › `async` blocks › Capture modes\n\nAsync blocks capture variables from their environment using the same [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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Block expressions", "heading_path": ["Block expressions", "`async` blocks", "Capture modes"], "path": "expressions/block-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/block-expr.html#capture-modes", "has_code": false, "code_tags": []}} {"id": "reference/expressions/block-expr.md#async-context-6", "text": "The Rust Reference › Block expressions › `async` blocks › Async context\n\nBecause async blocks construct a future, they define an **async context** which can in turn contain [`await` expressions]. Async contexts are established by async blocks as well as the bodies of async functions, whose semantics are defined in terms of async blocks.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Block expressions", "heading_path": ["Block expressions", "`async` blocks", "Async context"], "path": "expressions/block-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/block-expr.html#async-context", "has_code": false, "code_tags": []}} {"id": "reference/expressions/block-expr.md#control-flow-operators-7", "text": "The Rust Reference › Block expressions › `async` blocks › Control-flow operators\n\nAsync blocks act like a function boundary, much like closures.\nTherefore, the `?` operator and `return` expressions both affect the output of the future, not the enclosing function or other context. That is, `return ` from within an async block will return the result of `` as the output of the future. Similarly, if `?` propagates an error, that error is propagated as the result of the future.\nFinally, the `break` and `continue` keywords cannot be used to branch out from an async block. Therefore the following is illegal:\n```rust,compile_fail\nloop {\n async move {\n break; // error[E0267]: `break` inside of an `async` block\n }\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Block expressions", "heading_path": ["Block expressions", "`async` blocks", "Control-flow operators"], "path": "expressions/block-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/block-expr.html#control-flow-operators", "has_code": true, "code_tags": ["rust,compile_fail"]}} {"id": "reference/expressions/block-expr.md#const-blocks-8", "text": "The Rust Reference › Block expressions › `const` blocks\n\n```grammar,expressions\nConstBlockExpression -> `const` BlockExpression\n```\nA *const block* is a variant of a block expression whose body evaluates at compile-time instead of at runtime.\nConst blocks allows you to define a constant value without having to define new [constant items], and thus they are also sometimes referred as *inline consts*. It also supports type inference so there is no need to specify the type, unlike [constant items].\nConst blocks have the ability to reference generic parameters in scope, unlike free constant items. They are desugared to constant items with generic parameters in scope (similar to associated constants, but without a trait or type they are associated with). For example, this code:\n```rust\nfn foo() -> usize {\n const { std::mem::size_of::() + 1 }\n}\n```\nis equivalent to:\n```rust\nfn foo() -> usize {\n {\n struct Const(T);\n impl Const {\n const CONST: usize = std::mem::size_of::() + 1;\n }\n Const::::CONST\n }\n}\n```\nIf the const block expression is executed at runtime, then the constant is guaranteed to be evaluated, even if its return value is ignored:\n```rust\nfn foo() -> usize {\n // If this code ever gets executed, then the assertion has definitely\n // been evaluated at compile-time.\n const { assert!(std::mem::size_of::() > 0); }\n // Here we can have unsafe code relying on the type being non-zero-sized.\n /* ... */\n 42\n}\n```\nIf the const block expression is not executed at runtime, it may or may not be evaluated:\n```rust,compile_fail\nif false {\n // The panic may or may not occur when the program is built.\n const { panic!(); }\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Block expressions", "heading_path": ["Block expressions", "`const` blocks"], "path": "expressions/block-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/block-expr.html#const-blocks", "has_code": true, "code_tags": ["grammar,expressions", "rust", "rust,compile_fail"]}} {"id": "reference/expressions/block-expr.md#unsafe-blocks-9", "text": "The Rust Reference › Block expressions › `unsafe` blocks\n\n```grammar,expressions\nUnsafeBlockExpression -> `unsafe` BlockExpression\n```\n_See [`unsafe` blocks] for more information on when to use `unsafe`_.\nA block of code can be prefixed with the `unsafe` keyword to permit [unsafe operations]. Examples:\n```rust\nunsafe {\n let b = [13u8, 17u8];\n let a = &b[0] as *const u8;\n assert_eq!(*a, 13);\n assert_eq!(*a.offset(1), 17);\n}\n\nlet a = unsafe { an_unsafe_fn() };\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Block expressions", "heading_path": ["Block expressions", "`unsafe` blocks"], "path": "expressions/block-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/block-expr.html#unsafe-blocks", "has_code": true, "code_tags": ["grammar,expressions", "rust"]}} {"id": "reference/expressions/block-expr.md#labeled-block-expressions-10", "text": "The Rust Reference › Block expressions › Labeled block expressions\n\nLabeled block expressions are documented in the [Loops and other breakable expressions] section.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Block expressions", "heading_path": ["Block expressions", "Labeled block expressions"], "path": "expressions/block-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/block-expr.html#labeled-block-expressions", "has_code": false, "code_tags": []}} {"id": "reference/expressions/block-expr.md#attributes-on-block-expressions-11", "text": "The Rust Reference › Block expressions › Attributes on block expressions\n\n[Inner attributes] are allowed directly after the opening brace of a block expression in the following situations:\n* [Function] and [method] bodies.\n* Loop bodies ([`loop`], [`while`], and [`for`]).\n* Block expressions used as a [statement].\n* Block expressions as elements of [array expressions], [tuple expressions], [call expressions], and tuple-style [struct] expressions.\n* A block expression as the tail expression of another block expression.\nThe attributes that have meaning on a block expression are [`cfg`] and [the lint check attributes].\nFor example, this function returns `true` on unix platforms and `false` on other platforms.\n```rust\nfn is_unix_platform() -> bool {\n #[cfg(unix)] { true }\n #[cfg(not(unix))] { false }\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Block expressions", "heading_path": ["Block expressions", "Attributes on block expressions"], "path": "expressions/block-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/block-expr.html#attributes-on-block-expressions", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/operator-expr.md#operator-expressions-0", "text": "The Rust Reference › Operator expressions\n\n```grammar,expressions\nOperatorExpression ->\n BorrowExpression\n | DereferenceExpression\n | TryPropagationExpression\n | NegationExpression\n | ArithmeticOrLogicalExpression\n | ComparisonExpression\n | LazyBooleanExpression\n | TypeCastExpression\n | AssignmentExpression\n | CompoundAssignmentExpression\n```\nOperators are defined for built in types by the Rust language.\nMany of the following operators can also be overloaded using traits in `std::ops` or `std::cmp`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#operator-expressions", "has_code": true, "code_tags": ["grammar,expressions"]}} {"id": "reference/expressions/operator-expr.md#overflow-1", "text": "The Rust Reference › Operator expressions › Overflow\n\nInteger 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:\n* When `+`, `*` or binary `-` create a value greater than the maximum value, or less than the minimum value that can be stored.\n* Applying unary `-` to the most negative value of any signed integer type, unless the operand is a [literal expression] (or a literal expression standing alone inside one or more grouped expressions).\n* 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.\n* 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.\nThe 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.\nIn 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.\nNegation of these most negative values leaves the value unchanged due to two's complement overflow conventions.\nIn `rustc`, these most negative expressions are also ignored by the `overflowing_literals` lint check.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Overflow"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#overflow", "has_code": false, "code_tags": []}} {"id": "reference/expressions/operator-expr.md#borrow-operators-2", "text": "The Rust Reference › Operator expressions › Borrow operators\n\n```grammar,expressions\nBorrowExpression ->\n (`&`|`&&`) Expression\n | (`&`|`&&`) `mut` Expression\n | (`&`|`&&`) `raw` `const` Expression\n | (`&`|`&&`) `raw` `mut` Expression\n```\nThe `&` (shared borrow) and `&mut` (mutable borrow) operators are unary prefix operators.\nWhen applied to a [place expression], this expressions produces a reference (pointer) to the location that the value refers to.\nThe 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.\n`&mut` evaluates its operand in a mutable place expression context.\nIf the `&` or `&mut` operators are applied to a [value expression], then a [temporary value] is created.\nThese operators cannot be overloaded.\n```rust\n{\n // a temporary with value 7 is created that lasts for this scope.\n let shared_reference = &7;\n}\nlet mut array = [-2, 3, 9];\n{\n // Mutably borrows `array` for this scope.\n // `array` may only be used through `mutable_reference`.\n let mutable_reference = &mut array;\n}\n```\nEven though `&&` is a single token (the lazy 'and' operator), when used in the context of borrow expressions it works as two borrows:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Borrow operators"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#borrow-operators", "has_code": true, "code_tags": ["grammar,expressions", "rust"]}} {"id": "reference/expressions/operator-expr.md#borrow-operators-3", "text": "The Rust Reference › Operator expressions › Borrow operators\n\n```rust\n// same meanings:\nlet a = && 10;\nlet a = & & 10;\n\n// same meanings:\nlet a = &&&& mut 10;\nlet a = && && mut 10;\nlet a = & & & & mut 10;\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Borrow operators"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#borrow-operators", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/operator-expr.md#raw-borrow-operators-4", "text": "The Rust Reference › Operator expressions › Borrow operators › Raw borrow operators\n\n`&raw const` and `&raw mut` are the *raw borrow operators*.\nThe operand expression of these operators is evaluated in place expression context.\n`&raw const expr` then creates a const raw pointer of type `*const T` to the given place, and `&raw mut expr` creates a mutable raw pointer of type `*mut T`.\nThe raw borrow 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] by creating an invalid reference, but a raw pointer may still be constructed.\nThe following is an example of creating a raw pointer to an unaligned place through a `packed` struct:\n```rust\n#[repr(packed)]\nstruct Packed {\n f1: u8,\n f2: u16,\n}\n\nlet packed = Packed { f1: 1, f2: 2 };\n// `&packed.f2` would create an unaligned reference, and thus be undefined behavior!\nlet raw_f2 = &raw const packed.f2;\nassert_eq!(unsafe { raw_f2.read_unaligned() }, 2);\n```\nThe following is an example of creating a raw pointer to a place that does not contain a valid value:\n```rust\nuse std::mem::MaybeUninit;\n\nstruct Demo {\n field: bool,\n}\n\nlet mut uninit = MaybeUninit::::uninit();\n// `&uninit.as_mut().field` would create a reference to an uninitialized `bool`,\n// and thus be undefined behavior!\nlet f1_ptr = unsafe { &raw mut (*uninit.as_mut_ptr()).field };\nunsafe { f1_ptr.write(true); }\nlet init = unsafe { uninit.assume_init() };\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Borrow operators", "Raw borrow operators"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#raw-borrow-operators", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/operator-expr.md#the-dereference-operator-5", "text": "The Rust Reference › Operator expressions › The dereference operator\n\n```grammar,expressions\nDereferenceExpression -> `*` Expression\n```\nThe `*` (dereference) operator is also a unary prefix operator.\nWhen applied to a pointer or [`Box`], it denotes the pointed-to location.\nIf the expression is of type `&mut T`, `*mut T`, or `Box`, and is either a local variable, a (nested) field of a local variable or is a mutable [place expression], then the resulting memory location can be assigned to.\nWhen applied to a [`Box`], the resultant place may be [moved from].\nDereferencing a raw pointer requires `unsafe`.\nOn non-pointer types `*x` is equivalent to `*std::ops::Deref::deref(&x)` in an immutable place expression context and `*std::ops::DerefMut::deref_mut(&mut x)` in a mutable place expression context, except that when `*x` undergoes [temporary lifetime extension], the dereferenced expression `x` also has its [temporary scope] extended.\n```rust\nlet a = &7;\nassert_eq!(*a, 7);\nlet b = &mut 9;\n*b = 11;\nassert_eq!(*b, 11);\nlet c = Box::new(NoCopy);\nlet d: NoCopy = *c;\n```\n```rust\n// The temporary holding the result of `String::new()` is extended\n// to live to the end of the block, so `x` may be used in subsequent\n// statements.\nlet x = &*String::new();\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "The dereference operator"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-dereference-operator", "has_code": true, "code_tags": ["grammar,expressions", "rust"]}} {"id": "reference/expressions/operator-expr.md#the-dereference-operator-6", "text": "The Rust Reference › Operator expressions › The dereference operator\n\n```rust,compile_fail,E0716\n// The temporary holding the result of `String::new()` is dropped at\n// the end of the statement, so it's an error to use `y` after.\nlet y = &*std::ops::Deref::deref(&String::new()); // ERROR\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "The dereference operator"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-dereference-operator", "has_code": true, "code_tags": ["rust,compile_fail,E0716"]}} {"id": "reference/expressions/operator-expr.md#the-try-propagation-expression-7", "text": "The Rust Reference › Operator expressions › The try propagation expression\n\n```grammar,expressions\nTryPropagationExpression -> Expression `?`\n```\nThe try propagation expression uses the value of the inner expression and the [`Try`] trait to decide whether to produce a value, and if so, what value to produce, or whether to return a value to the caller, and if so, what value to return.\n```rust\nfn try_to_parse() -> Result {\n let x: i32 = \"123\".parse()?; // `x` is `123`.\n let y: i32 = \"24a\".parse()?; // Returns an `Err()` immediately.\n Ok(x + y) // Doesn't run.\n}\n\nlet res = try_to_parse();\nprintln!(\"{res:?}\");\n```\n```rust\nfn try_option_some() -> Option {\n let val = Some(1)?;\n Some(val)\n}\nassert_eq!(try_option_some(), Some(1));\n\nfn try_option_none() -> Option {\n let val = None?;\n Some(val)\n}\nassert_eq!(try_option_none(), None);\n```\n```rust\nuse std::ops::ControlFlow;\n\npub struct TreeNode {\n value: T,\n left: Option>>,\n right: Option>>,\n}\n\nimpl TreeNode {\n pub fn traverse_inorder(&self, f: &mut impl FnMut(&T) -> ControlFlow) -> ControlFlow {\n if let Some(left) = &self.left {\n left.traverse_inorder(f)?;\n }\n f(&self.value)?;\n if let Some(right) = &self.right {\n right.traverse_inorder(f)?;\n }\n ControlFlow::Continue(())\n }\n}\n```\nThe [`Try`] trait is currently unstable, and thus cannot be implemented for user types.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "The try propagation expression"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-try-propagation-expression", "has_code": true, "code_tags": ["grammar,expressions", "rust"]}} {"id": "reference/expressions/operator-expr.md#the-try-propagation-expression-8", "text": "The Rust Reference › Operator expressions › The try propagation expression\n\nThe try propagation expression is currently roughly equivalent to:\n```rust\nmatch core::ops::Try::branch(expr) {\n core::ops::ControlFlow::Continue(val) => val,\n core::ops::ControlFlow::Break(residual) =>\n return core::ops::FromResidual::from_residual(residual),\n}\n```\nThe try propagation operator is sometimes called *the question mark operator*, *the `?` operator*, or *the try operator*.\nThe try propagation operator can be applied to expressions with the type of:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "The try propagation expression"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-try-propagation-expression", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/operator-expr.md#the-try-propagation-expression-9", "text": "The Rust Reference › Operator expressions › The try propagation expression\n\n- [`Result`]\n - `Result::Ok(val)` evaluates to `val`.\n - `Result::Err(e)` returns `Result::Err(From::from(e))`.\n- [`Option`]\n - `Option::Some(val)` evaluates to `val`.\n - `Option::None` returns `Option::None`.\n- `ControlFlow`\n - `ControlFlow::Continue(c)` evaluates to `c`.\n - `ControlFlow::Break(b)` returns `ControlFlow::Break(b)`.\n- `Poll>`\n - `Poll::Ready(Ok(val))` evaluates to `Poll::Ready(val)`.\n - `Poll::Ready(Err(e))` returns `Poll::Ready(Err(From::from(e)))`.\n - `Poll::Pending` evaluates to `Poll::Pending`.\n- `Poll>>`\n - `Poll::Ready(Some(Ok(val)))` evaluates to `Poll::Ready(Some(val))`.\n - `Poll::Ready(Some(Err(e)))` returns `Poll::Ready(Some(Err(From::from(e))))`.\n - `Poll::Ready(None)` evaluates to `Poll::Ready(None)`.\n - `Poll::Pending` evaluates to `Poll::Pending`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "The try propagation expression"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-try-propagation-expression", "has_code": false, "code_tags": []}} {"id": "reference/expressions/operator-expr.md#negation-operators-10", "text": "The Rust Reference › Operator expressions › Negation operators\n\n```grammar,expressions\nNegationExpression ->\n `-` Expression\n | `!` Expression\n```\nThese are the last two unary operators.\nThis 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 so are moved or copied.\n| Symbol | Integer | `bool` | Floating Point | Overloading Trait |\n|--------|-------------|-------------- |----------------|--------------------|\n| `-` | Negation* | | Negation | `std::ops::Neg` |\n| `!` | Bitwise NOT | [Logical NOT] | | `std::ops::Not` |\n\\* Only for signed integer types.\nHere are some example of these operators\n```rust\nlet x = 6;\nassert_eq!(-x, -6);\nassert_eq!(!x, -7);\nassert_eq!(true, !false);\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Negation operators"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#negation-operators", "has_code": true, "code_tags": ["grammar,expressions", "rust"]}} {"id": "reference/expressions/operator-expr.md#arithmetic-and-logical-binary-operators-11", "text": "The Rust Reference › Operator expressions › Arithmetic and logical binary operators\n\n```grammar,expressions\nArithmeticOrLogicalExpression ->\n Expression `+` Expression\n | Expression `-` Expression\n | Expression `*` Expression\n | Expression `/` Expression\n | Expression `%` Expression\n | Expression `&` Expression\n | Expression `|` Expression\n | Expression `^` Expression\n | Expression `<<` Expression\n | Expression `>>` Expression\n```\nBinary operators expressions are all written with infix notation.\nThis 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 so are moved or copied.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Arithmetic and logical binary operators"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#arithmetic-and-logical-binary-operators", "has_code": true, "code_tags": ["grammar,expressions"]}} {"id": "reference/expressions/operator-expr.md#arithmetic-and-logical-binary-operators-12", "text": "The Rust Reference › Operator expressions › Arithmetic and logical binary operators\n\n| Symbol | Integer | `bool` | Floating Point | Overloading Trait | Overloading Compound Assignment Trait |\n|--------|-------------------------|---------------|----------------|--------------------| ------------------------------------- |\n| `+` | Addition | | Addition | `std::ops::Add` | `std::ops::AddAssign` |\n| `-` | Subtraction | | Subtraction | `std::ops::Sub` | `std::ops::SubAssign` |\n| `*` | Multiplication | | Multiplication | `std::ops::Mul` | `std::ops::MulAssign` |\n| `/` | Division*† | | Division | `std::ops::Div` | `std::ops::DivAssign` |\n| `%` | Remainder**† | | Remainder | `std::ops::Rem` | `std::ops::RemAssign` |\n| `&` | Bitwise AND | [Logical AND] | | `std::ops::BitAnd` | `std::ops::BitAndAssign` |\n| `\\|` | Bitwise OR | [Logical OR] | | `std::ops::BitOr` | `std::ops::BitOrAssign` |\n| `^` | Bitwise XOR | [Logical XOR] | | `std::ops::BitXor` | `std::ops::BitXorAssign` |\n| `<<` | Left Shift | | | `std::ops::Shl` | `std::ops::ShlAssign` |\n| `>>` | Right Shift*** | | | `std::ops::Shr` | `std::ops::ShrAssign` |", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Arithmetic and logical binary operators"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#arithmetic-and-logical-binary-operators", "has_code": false, "code_tags": []}} {"id": "reference/expressions/operator-expr.md#arithmetic-and-logical-binary-operators-13", "text": "The Rust Reference › Operator expressions › Arithmetic and logical binary operators\n\n\\* Integer division rounds towards zero.\n\\*\\* Rust uses a remainder defined with truncating division. Given `remainder = dividend % divisor`, the remainder will have the same sign as the dividend.\n\\*\\*\\* Arithmetic right shift on signed integer types, logical right shift on unsigned integer types.\n† For integer types, division by zero panics.\nHere are examples of these operators being used.\n```rust\nassert_eq!(3 + 6, 9);\nassert_eq!(5.5 - 1.25, 4.25);\nassert_eq!(-5 * 14, -70);\nassert_eq!(14 / 3, 4);\nassert_eq!(100 % 7, 2);\nassert_eq!(0b1010 & 0b1100, 0b1000);\nassert_eq!(0b1010 | 0b1100, 0b1110);\nassert_eq!(0b1010 ^ 0b1100, 0b110);\nassert_eq!(13 << 3, 104);\nassert_eq!(-10 >> 2, -3);\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Arithmetic and logical binary operators"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#arithmetic-and-logical-binary-operators", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/operator-expr.md#comparison-operators-14", "text": "The Rust Reference › Operator expressions › Comparison operators\n\n```grammar,expressions\nComparisonExpression ->\n Expression `==` Expression\n | Expression `!=` Expression\n | Expression `>` Expression\n | Expression `<` Expression\n | Expression `>=` Expression\n | Expression `<=` Expression\n```\nComparison operators are also defined both for primitive types and many types in the standard library.\nParentheses are required when chaining comparison operators. For example, the expression `a == b == c` is invalid and may be written as `(a == b) == c`.\nUnlike 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).\nUnlike the arithmetic and logical operators above, these operators implicitly take shared borrows of their operands, evaluating them in place expression context:\n```rust\na == b;\n// is equivalent to\n::std::cmp::PartialEq::eq(&a, &b);\n```\nThis means that the operands don't have to be moved out of.\n| Symbol | Meaning | Overloading method |\n|--------|--------------------------|----------------------------|\n| `==` | Equal | `std::cmp::PartialEq::eq` |\n| `!=` | Not equal | `std::cmp::PartialEq::ne` |\n| `>` | Greater than | `std::cmp::PartialOrd::gt` |\n| `<` | Less than | `std::cmp::PartialOrd::lt` |\n| `>=` | Greater than or equal to | `std::cmp::PartialOrd::ge` |\n| `<=` | Less than or equal to | `std::cmp::PartialOrd::le` |\nHere are examples of the comparison operators being used.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Comparison operators"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#comparison-operators", "has_code": true, "code_tags": ["grammar,expressions", "rust"]}} {"id": "reference/expressions/operator-expr.md#comparison-operators-15", "text": "The Rust Reference › Operator expressions › Comparison operators\n\n```rust\nassert!(123 == 123);\nassert!(23 != -12);\nassert!(12.5 > 12.2);\nassert!([1, 2, 3] < [1, 3, 4]);\nassert!('A' <= 'B');\nassert!(\"World\" >= \"Hello\");\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Comparison operators"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#comparison-operators", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/operator-expr.md#lazy-boolean-operators-16", "text": "The Rust Reference › Operator expressions › Lazy boolean operators\n\n```grammar,expressions\nLazyBooleanExpression ->\n Expression `||` Expression\n | Expression `&&` Expression\n```\nThe operators `||` and `&&` may be applied to operands of boolean type. The `||` operator denotes logical 'or', and the `&&` operator denotes logical 'and'.\nThey 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`.\n```rust\nlet x = false || true; // true\nlet y = false && panic!(); // false, doesn't evaluate `panic!()`\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Lazy boolean operators"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#lazy-boolean-operators", "has_code": true, "code_tags": ["grammar,expressions", "rust"]}} {"id": "reference/expressions/operator-expr.md#type-cast-expressions-17", "text": "The Rust Reference › Operator expressions › Type cast expressions\n\n```grammar,expressions\nTypeCastExpression -> Expression `as` TypeNoBounds\n```\nA type cast expression is denoted with the binary operator `as`.\nExecuting an `as` expression casts the value on the left-hand side to the type on the right-hand side.\nAn example of an `as` expression:\n```rust\nfn average(values: &[f64]) -> f64 {\n let sum: f64 = sum(values);\n let size: f64 = len(values) as f64;\n sum / size\n}\n```\n`as` can be used to explicitly perform 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Type cast expressions"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions", "has_code": true, "code_tags": ["grammar,expressions", "rust"]}} {"id": "reference/expressions/operator-expr.md#type-cast-expressions-18", "text": "The Rust Reference › Operator expressions › Type cast expressions\n\n| Type of `e` | `U` | Cast performed by `e as U` |\n|-----------------------|-----------------------|-------------------------------------------------------|\n| Integer or Float type | Integer or Float type | Numeric cast |\n| Enumeration | Integer type | Enum cast |\n| `bool` or `char` | Integer type | Primitive to integer cast |\n| `u8` | `char` | `u8` to `char` cast |\n| `*T` | `*V` (when compatible) | Pointer to pointer cast |\n| `*T` where `T: Sized` | Integer type | Pointer to address cast |\n| Integer type | `*V` where `V: Sized` | Address to pointer cast |\n| `&m₁ [T; n]` | `*m₂ T` [^lessmut] | Array to pointer cast |\n| `*m₁ [T; n]` | `*m₂ T` [^lessmut] | Array to pointer cast |\n| [Function item] | [Function pointer] | Function item to function pointer cast |\n| [Function item] | `*V` where `V: Sized` | Function item to pointer cast |\n| [Function item] | Integer | Function item to address cast |\n| [Function pointer] | `*V` where `V: Sized` | Function pointer to pointer cast |\n| [Function pointer] | Integer | Function pointer to address cast |\n| Closure [^no-capture] | Function pointer | Closure to function pointer cast |", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Type cast expressions"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions", "has_code": false, "code_tags": []}} {"id": "reference/expressions/operator-expr.md#type-cast-expressions-19", "text": "The Rust Reference › Operator expressions › Type cast expressions\n\n[^lessmut]: Only when `m₁` is `mut` or `m₂` is `const`. Casting `mut` reference/pointer to `const` pointer is allowed.\n[^no-capture]: Only closures that do not capture (close over) any local variables can be cast to function pointers.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Type cast expressions"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions", "has_code": false, "code_tags": []}} {"id": "reference/expressions/operator-expr.md#numeric-cast-20", "text": "The Rust Reference › Operator expressions › Type cast expressions › Semantics › Numeric cast\n\n* 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)\n```rust\n assert_eq!(42i8 as u8, 42u8);\n assert_eq!(-1i8 as u8, 255u8);\n assert_eq!(255u8 as i8, -1i8);\n assert_eq!(-1i16 as u16, 65535u16);\n```\n* Casting from a larger integer to a smaller integer (e.g. u32 -> u8) will truncate\n```rust\n assert_eq!(42u16 as u8, 42u8);\n assert_eq!(1234u16 as u8, 210u8);\n assert_eq!(0xabcdu16 as u8, 0xcdu8);\n\n assert_eq!(-42i16 as i8, -42i8);\n assert_eq!(1234u16 as i8, -46i8);\n assert_eq!(0xabcdi32 as i8, -51i8);\n```\n* Casting from a smaller integer to a larger integer (e.g. u8 -> u32) will\n * zero-extend if the source is unsigned\n * sign-extend if the source is signed", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Type cast expressions", "Semantics", "Numeric cast"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#numeric-cast", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/operator-expr.md#numeric-cast-21", "text": "The Rust Reference › Operator expressions › Type cast expressions › Semantics › Numeric cast\n\n```rust\n assert_eq!(42i8 as i16, 42i16);\n assert_eq!(-17i8 as i16, -17i16);\n assert_eq!(0b1000_1010u8 as u16, 0b0000_0000_1000_1010u16, \"Zero-extend\");\n assert_eq!(0b0000_1010i8 as i16, 0b0000_0000_0000_1010i16, \"Sign-extend 0\");\n assert_eq!(0b1000_1010u8 as i8 as i16, 0b1111_1111_1000_1010u16 as i16, \"Sign-extend 1\");\n```\n* Casting from a float to an integer will round the float towards zero\n * `NaN` will return `0`\n * Values larger than the maximum integer value, including `INFINITY`, will saturate to the maximum value of the integer type.\n * Values smaller than the minimum integer value, including `NEG_INFINITY`, will saturate to the minimum value of the integer type.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Type cast expressions", "Semantics", "Numeric cast"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#numeric-cast", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/operator-expr.md#numeric-cast-22", "text": "The Rust Reference › Operator expressions › Type cast expressions › Semantics › Numeric cast\n\n```rust\n assert_eq!(42.9f32 as i32, 42);\n assert_eq!(-42.9f32 as i32, -42);\n assert_eq!(42_000_000f32 as i32, 42_000_000);\n assert_eq!(std::f32::NAN as i32, 0);\n assert_eq!(1_000_000_000_000_000f32 as i32, 0x7fffffffi32);\n assert_eq!(std::f32::NEG_INFINITY as i32, -0x80000000i32);\n```\n* Casting from an integer to float will produce the closest possible float \\*\n * if necessary, rounding is according to `roundTiesToEven` mode \\*\\*\\*\n * on overflow, infinity (of the same sign as the input) is produced\n * 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)`\n```rust\n assert_eq!(1337i32 as f32, 1337f32);\n assert_eq!(123_456_789i32 as f32, 123_456_790f32, \"Rounded\");\n assert_eq!(0xffffffff_ffffffff_ffffffff_ffffffff_u128 as f32, std::f32::INFINITY);\n```\n* Casting from an f32 to an f64 is perfect and lossless", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Type cast expressions", "Semantics", "Numeric cast"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#numeric-cast", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/operator-expr.md#enum-cast-23", "text": "The Rust Reference › Operator expressions › Type cast expressions › Semantics › Enum cast\n\n```rust\n assert_eq!(1_234.5f32 as f64, 1_234.5f64);\n assert_eq!(std::f32::INFINITY as f64, std::f64::INFINITY);\n assert!((std::f32::NAN as f64).is_nan());\n```\n* Casting from an f64 to an f32 will produce the closest possible f32 \\*\\*\n * if necessary, rounding is according to `roundTiesToEven` mode \\*\\*\\*\n * on overflow, infinity (of the same sign as the input) is produced\n```rust\n assert_eq!(1_234.5f64 as f32, 1_234.5f32);\n assert_eq!(1_234_567_891.123f64 as f32, 1_234_567_890f32, \"Rounded\");\n assert_eq!(std::f64::INFINITY as f32, std::f32::INFINITY);\n assert!((std::f64::NAN as f32).is_nan());\n```\n\\* 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.\n\\*\\* 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.\n\\*\\*\\* 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Type cast expressions", "Semantics", "Enum cast"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#enum-cast", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/operator-expr.md#address-to-pointer-cast-24", "text": "The Rust Reference › Operator expressions › Type cast expressions › Semantics › Address to pointer cast\n\nCasts an enum to its discriminant, then uses a numeric cast if needed. Casting is limited to the following kinds of enumerations:\n* [Unit-only enums]\n* [Field-less enums] without [explicit discriminants], or where only unit-variants have explicit discriminants\n```rust\nenum Enum { A, B, C }\nassert_eq!(Enum::A as i32, 0);\nassert_eq!(Enum::B as i32, 1);\nassert_eq!(Enum::C as i32, 2);\n```\nCasting is not allowed if the enum implements [`Drop`].\n* `false` casts to `0`, `true` casts to `1`\n* `char` casts to the value of the code point, then uses a numeric cast if needed.\n```rust\nassert_eq!(false as i32, 0);\nassert_eq!(true as i32, 1);\nassert_eq!('A' as i32, 65);\nassert_eq!('Ö' as i32, 214);\n```\nCasts to the `char` with the corresponding code point.\n```rust\nassert_eq!(65u8 as char, 'A');\nassert_eq!(214u8 as char, 'Ö');\n```\nCasting 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.\nCasting from an integer to a raw pointer interprets the integer as a memory address and produces a pointer referencing that memory.\nThis interacts with the Rust memory model, which is still under development.\nA pointer obtained from this cast may suffer additional restrictions even if it is bitwise equal to a valid pointer.\nDereferencing such a pointer may be [undefined behavior] if aliasing rules are not followed.\nA trivial example of sound address arithmetic:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Type cast expressions", "Semantics", "Address to pointer cast"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#address-to-pointer-cast", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/operator-expr.md#pointer-to-pointer-cast-25", "text": "The Rust Reference › Operator expressions › Type cast expressions › Semantics › Pointer-to-pointer cast\n\n```rust\nlet mut values: [i32; 2] = [1, 2];\nlet p1: *mut i32 = values.as_mut_ptr();\nlet first_address = p1 as usize;\nlet second_address = first_address + 4; // 4 == size_of::()\nlet p2 = second_address as *mut i32;\nunsafe {\n *p2 += 1;\n}\nassert_eq!(values[1], 3);\n```\n`*const T` / `*mut T` can be cast to `*const U` / `*mut U` with the following behavior:\n- If `T` and `U` are both sized, the pointer is returned unchanged.\n```rust\nlet x: i32 = 42;\nlet p1: *const i32 = &x;\nlet p2: *const u8 = p1 as *const u8;\n// The pointer address remains the same.\nassert_eq!(p1 as usize, p2 as usize);\n```\n- If `T` is unsized and `U` is sized, the cast discards all [metadata] that completes the wide pointer `T` and produces a thin pointer `U` consisting of the data part of the unsized pointer.\n```rust\nlet slice: &[i32] = &[1, 2, 3];\nlet ptr: *const [i32] = slice as *const [i32];\n// Cast from wide pointer (*const [i32]) to thin pointer (*const i32)\n// discarding the length metadata.\nlet data_ptr: *const i32 = ptr as *const i32;\nassert_eq!(unsafe { *data_ptr }, 1);\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Type cast expressions", "Semantics", "Pointer-to-pointer cast"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#pointer-to-pointer-cast", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/operator-expr.md#pointer-to-pointer-cast-26", "text": "The Rust Reference › Operator expressions › Type cast expressions › Semantics › Pointer-to-pointer cast\n\n- If `T` and `U` are both unsized, the pointer is also returned unchanged. In particular, the metadata is preserved exactly. The cast can only be performed if the metadata is compatible according to the below rules:\n- When `T` and `U` are unsized with slice metadata, they are always compatible. The metadata of a slice is the number of elements, so casting `*[u16] -> *[u8]` is legal but will result in reducing the number of bytes by half.\n```rust\nlet slice: &[u16] = &[1, 2, 3];\nlet ptr: *const [u16] = slice as *const [u16];\nlet byte_ptr: *const [u8] = ptr as *const [u8];\nassert_eq!(byte_ptr.len(), 3);\n```\n- When `T` and `U` are unsized with trait object metadata, the metadata is compatible only when all of the following holds:\n 1. The principal trait must be the same.\n```rust,compile_fail,E0606\ntrait Foo {}\ntrait Bar {}\nimpl Foo for i32 {}\nimpl Bar for i32 {}\n\nlet x: i32 = 42;\nlet ptr_foo: *const dyn Foo = &x as *const dyn Foo;\n// You can't cast to a different principal trait.\nlet ptr_bar: *const dyn Bar = ptr_foo as *const dyn Bar; // ERROR\n```\n 2. Auto traits may be removed.\n```rust\ntrait Foo {}\nstruct S;\nimpl Foo for S {}\nunsafe impl Send for S {}\n\nlet s = S;\nlet ptr_send: *const (dyn Foo + Send) = &s;\n// Removing an auto trait.\nlet ptr_no_send: *const dyn Foo = ptr_send as *const dyn Foo;\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Type cast expressions", "Semantics", "Pointer-to-pointer cast"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#pointer-to-pointer-cast", "has_code": true, "code_tags": ["rust", "rust,compile_fail,E0606"]}} {"id": "reference/expressions/operator-expr.md#pointer-to-pointer-cast-27", "text": "The Rust Reference › Operator expressions › Type cast expressions › Semantics › Pointer-to-pointer cast\n\n3. Auto traits may be added only if they are a super trait of the principal trait.\n```rust\ntrait Foo: Send {}\nstruct S;\nimpl Foo for S {}\nunsafe impl Send for S {}\n\nlet s = S;\nlet ptr_no_send: *const dyn Foo = &s;\n// Adding an auto trait.\nlet ptr_send: *const (dyn Foo + Send) = ptr_no_send as *const (dyn Foo + Send);\n```\n```rust,compile_fail,E0804\ntrait Foo {}\n// Same as above, except trait Foo does not have Send as a super trait.\nlet ptr_send: *const (dyn Foo + Send) = ptr_no_send as *const (dyn Foo + Send); // ERROR\n```\n 4. Trailing lifetimes may only be shortened.\n```rust\ntrait Foo {}\n\nfn shorten_lifetime<'long: 'short, 'short>(\n ptr: *const (dyn Foo + 'long),\n) -> *const (dyn Foo + 'short) {\n // Shortening the lifetime is allowed.\n ptr as *const (dyn Foo + 'short)\n}\n```\n```rust,compile_fail\ntrait Foo {}\n\nfn lengthen_lifetime<'long: 'short, 'short>(\n ptr: *const (dyn Foo + 'short),\n) -> *const (dyn Foo + 'long) {\n // It is not allowed to cast to a longer lifetime.\n ptr as *const (dyn Foo + 'long) // ERROR\n}\n```\n 5. Generics (including lifetimes) and associated types must match exactly.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Type cast expressions", "Semantics", "Pointer-to-pointer cast"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#pointer-to-pointer-cast", "has_code": true, "code_tags": ["rust", "rust,compile_fail", "rust,compile_fail,E0804"]}} {"id": "reference/expressions/operator-expr.md#pointer-to-pointer-cast-28", "text": "The Rust Reference › Operator expressions › Type cast expressions › Semantics › Pointer-to-pointer cast\n\n```rust,compile_fail,E0606\ntrait Generic {}\nimpl Generic for () {}\nimpl Generic for () {}\n\nlet x = ();\nlet ptr_i32: *const dyn Generic = &x;\n// You can't cast to a different generic parameter.\nlet ptr_u32: *const dyn Generic = ptr_i32 as *const dyn Generic; // ERROR\n```\n```rust\ntrait HasType {\n type Output;\n}\n\ntrait Generic<'x, T> {}\n\nfn cast_via_associated<'a, 'b, A, B>(\n ptr: *const dyn Generic<'a, A::Output>,\n) -> *const dyn Generic<'b, B::Output>\nwhere\n 'a: 'b,\n 'b: 'a,\n A: HasType,\n B: HasType, // Forces equality\n{\n ptr as *const dyn Generic<'b, B::Output>\n}\n```\n- When `T` or `U` is a struct or tuple type whose last field is unsized, it has the same metadata and compatibility rules as its last field.\n```rust\nstruct Wrapper(u32, [u8]);\n\nlet slice: &[u8] = &[1, 2, 3];\nlet ptr: *const [u8] = slice;\n\n// The metadata (length 3) is preserved when casting to a struct\n// where the last field is the unsized type `[u8]`.\nlet wrapper_ptr: *const Wrapper = ptr as *const Wrapper;\n\n// And preserved when casting back.\nlet ptr_back: *const [u8] = wrapper_ptr as *const [u8];\nassert_eq!(ptr_back.len(), 3);\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Type cast expressions", "Semantics", "Pointer-to-pointer cast"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#pointer-to-pointer-cast", "has_code": true, "code_tags": ["rust", "rust,compile_fail,E0606"]}} {"id": "reference/expressions/operator-expr.md#assignment-expressions-29", "text": "The Rust Reference › Operator expressions › Assignment expressions\n\n```grammar,expressions\nAssignmentExpression -> Expression `=` Expression\n```\nAn *assignment expression* moves a value into a specified place.\nAn assignment expression consists of a [mutable] [assignee expression], the *assignee operand*, followed by an equals sign (`=`) and a [value expression], the *assigned value operand*.\nIn its most basic form, an assignee expression is a [place expression], and we discuss this case first.\nThe 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Assignment expressions"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#assignment-expressions", "has_code": true, "code_tags": ["grammar,expressions"]}} {"id": "reference/expressions/operator-expr.md#basic-assignments-30", "text": "The Rust Reference › Operator expressions › Assignment expressions › Basic assignments\n\nEvaluating assignment expressions begins by evaluating its operands. The assigned value operand is evaluated first, followed by the assignee expression.\nFor destructuring assignment, subexpressions of the assignee expression are evaluated left-to-right.\nThis is different than other expressions in that the right operand is evaluated before the left one.\nIt then has the effect of first [dropping] the value at the assigned place, unless the place is an uninitialized local variable or an uninitialized field of a local variable.\nNext it either [copies or moves] the assigned value to the assigned place.\nAn assignment expression always produces the unit value.\nExample:\n```rust\nlet mut x = 0;\nlet y = 0;\nx = y;\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Assignment expressions", "Basic assignments"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#basic-assignments", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/operator-expr.md#destructuring-assignments-31", "text": "The Rust Reference › Operator expressions › Assignment expressions › Destructuring assignments\n\nDestructuring 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:\n```rust\nlet (mut a, mut b) = (0, 1);\n// Swap `a` and `b` using destructuring assignment.\n(b, a) = (a, b);\n```\nIn 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, and permitted on the left-hand side of an assignment. Assignee expressions are then desugared to pattern matches followed by sequential assignment.\nThe 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.\nThe desugaring method is straightforward, and is illustrated best by example.\n```rust\n(a, b) = (3, 4);\n\n[a, b] = [3, 4];\n\nStruct { x: a, y: b } = Struct { x: 3, y: 4};\n\n// desugars to:\n\n{\n let (_a, _b) = (3, 4);\n a = _a;\n b = _b;\n}\n\n{\n let [_a, _b] = [3, 4];\n a = _a;\n b = _b;\n}\n\n{\n let Struct { x: _a, y: _b } = Struct { x: 3, y: 4};\n a = _a;\n b = _b;\n}\n```\nIdentifiers are not forbidden from being used multiple times in a single assignee expression.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Assignment expressions", "Destructuring assignments"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#destructuring-assignments", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/operator-expr.md#destructuring-assignments-32", "text": "The Rust Reference › Operator expressions › Assignment expressions › Destructuring assignments\n\n[Underscore expressions] and empty [range expressions] may be used to ignore certain values, without binding them.\nNote that default binding modes do not apply for the desugared expression.\nThe desugaring restricts the [temporary scope] of the assigned value operand (the RHS) of a destructuring assignment.\nIn a basic assignment, the [temporary] is dropped at the end of the enclosing temporary scope. Below, that's the statement. Therefore, the assignment and use is allowed.\n```rust\nfn f(x: T) -> T { x }\nlet x;\n(x = f(&temp()), x); // OK\n```\nConversely, in a destructuring assignment, the temporary is dropped at the end of the `let` statement in the desugaring. As that happens before we try to assign to `x`, below, it fails.\n```rust,compile_fail,E0716\n[x] = [f(&temp())]; // ERROR\n```\nThis desugars to:\n```rust,compile_fail,E0716\n{\n let [_x] = [f(&temp())];\n // ^\n // The temporary is dropped here.\n x = _x; // ERROR\n}\n```\nDue to the desugaring, the assigned value operand (the RHS) of a destructuring assignment is an [extending expression] within a newly-introduced block.\nBelow, because the [temporary scope] is extended to the end of this introduced block, the assignment is allowed.\n```rust\n[x] = [&temp()]; // OK\n```\nThis desugars to:\n```rust\n{ let [_x] = [&temp()]; x = _x; } // OK\n```\nHowever, if we try to use `x`, even within the same statement, we'll get an error because the [temporary] is dropped at the end of this introduced block.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Assignment expressions", "Destructuring assignments"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#destructuring-assignments", "has_code": true, "code_tags": ["rust", "rust,compile_fail,E0716"]}} {"id": "reference/expressions/operator-expr.md#destructuring-assignments-33", "text": "The Rust Reference › Operator expressions › Assignment expressions › Destructuring assignments\n\n```rust,compile_fail,E0716\n([x] = [&temp()], x); // ERROR\n```\nThis desugars to:\n```rust,compile_fail,E0716\n(\n {\n let [_x] = [&temp()];\n x = _x;\n }, // <-- The temporary is dropped here.\n x, // ERROR\n);\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Assignment expressions", "Destructuring assignments"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#destructuring-assignments", "has_code": true, "code_tags": ["rust,compile_fail,E0716"]}} {"id": "reference/expressions/operator-expr.md#compound-assignment-expressions-34", "text": "The Rust Reference › Operator expressions › Compound assignment expressions\n\n```grammar,expressions\nCompoundAssignmentExpression ->\n Expression `+=` Expression\n | Expression `-=` Expression\n | Expression `*=` Expression\n | Expression `/=` Expression\n | Expression `%=` Expression\n | Expression `&=` Expression\n | Expression `|=` Expression\n | Expression `^=` Expression\n | Expression `<<=` Expression\n | Expression `>>=` Expression\n```\n*Compound assignment expressions* combine arithmetic and logical binary operators with assignment expressions.\nFor example:\n```rust\nlet mut x = 5;\nx += 1;\nassert!(x == 6);\n```\nThe syntax of compound assignment is a [mutable] [place expression], the *assigned operand*, then one of the operators followed by an `=` as a single token (no whitespace), and then a [value expression], the *modifying operand*.\nUnlike other place operands, the assigned place operand must be a place expression.\nAttempting to use a value expression is a compiler error rather than promoting it to a temporary.\nEvaluation of compound assignment expressions depends on the types of the operands.\nIf the types of both operands are known, prior to monomorphization, to be primitive, the right hand side is evaluated first, the left hand side is evaluated next, and the place given by the evaluation of the left hand side is mutated by applying the operator to the values of both sides.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Compound assignment expressions"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#compound-assignment-expressions", "has_code": true, "code_tags": ["grammar,expressions", "rust"]}} {"id": "reference/expressions/operator-expr.md#compound-assignment-expressions-35", "text": "The Rust Reference › Operator expressions › Compound assignment expressions\n\n```rust\ntrait Equate {}\nimpl Equate for (T, T) {}\n\nfn f1(x: (u8,)) {\n let mut order = vec![];\n // The RHS is evaluated first as both operands are of primitive\n // type.\n { order.push(2); x }.0 += { order.push(1); x }.0;\n assert!(order.is_sorted());\n}\n\nfn f2(x: (Wrapping,)) {\n let mut order = vec![];\n // The LHS is evaluated first as `Wrapping<_>` is not a primitive\n // type.\n { order.push(1); x }.0 += { order.push(2); (0u8,) }.0;\n assert!(order.is_sorted());\n}\n\nfn f3 + Copy>(x: (T,)) where (T, u8): Equate {\n let mut order = vec![];\n // The LHS is evaluated first as one of the operands is a generic\n // parameter, even though that generic parameter can be unified\n // with a primitive type due to the where clause bound.\n { order.push(1); x }.0 += { order.push(2); (0u8,) }.0;\n assert!(order.is_sorted());\n}\n\nfn main() {\n f1((0u8,));\n f2((Wrapping(0u8),));\n // We supply a primitive type as the generic argument, but this\n // does not affect the evaluation order in `f3` when\n // monomorphized.\n f3::((0u8,));\n}\n```\nThis is unusual. Elsewhere left to right evaluation is the norm.\nSee the [eval order test] for more examples.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Compound assignment expressions"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#compound-assignment-expressions", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/operator-expr.md#compound-assignment-expressions-36", "text": "The Rust Reference › Operator expressions › Compound assignment expressions\n\nOtherwise, this expression is syntactic sugar for using the corresponding trait for the operator (see [expr.arith-logic.behavior]) and calling its method with the left hand side as the [receiver] and the right hand side as the next argument.\nFor example, the following two statements are equivalent:\n```rust\nfn f(mut x: T, y: T) {\n x += y; // Statement 1.\n x.add_assign(y); // Statement 2.\n}\n```\nSurprisingly, desugaring this further to a fully qualified method call is not equivalent, as there is special borrow checker behavior when the mutable reference to the first operand is taken via [autoref].\n```rust\nfn f(mut x: T) {\n // Here we used `x` as both the LHS and the RHS. Because the\n // mutable borrow of the LHS needed to call the trait method\n // is taken implicitly by autoref, this is OK.\n x += x; //~ OK\n x.add_assign(x); //~ OK\n}\n```\n```rust,compile_fail,E0503\nfn f(mut x: T) {\n // We can't desugar the above to the below, as once we take the\n // mutable borrow of `x` to pass the first argument, we can't\n // pass `x` by value in the second argument because the mutable\n // reference is still live.\n ::add_assign(&mut x, x);\n //~^ ERROR cannot use `x` because it was mutably borrowed\n}\n```\n```rust,compile_fail,E0503\nfn f(mut x: T) {\n // As above.\n (&mut x).add_assign(x);\n //~^ ERROR cannot use `x` because it was mutably borrowed\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Compound assignment expressions"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#compound-assignment-expressions", "has_code": true, "code_tags": ["rust", "rust,compile_fail,E0503"]}} {"id": "reference/expressions/operator-expr.md#compound-assignment-expressions-37", "text": "The Rust Reference › Operator expressions › Compound assignment expressions\n\nAs with normal assignment expressions, compound assignment expressions always produce the unit value.\nAvoid writing code that depends on the evaluation order of operands in compound assignments as it can be unusual and surprising.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Operator expressions", "heading_path": ["Operator expressions", "Compound assignment expressions"], "path": "expressions/operator-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/operator-expr.html#compound-assignment-expressions", "has_code": false, "code_tags": []}} {"id": "reference/expressions/grouped-expr.md#grouped-expressions-0", "text": "The Rust Reference › Grouped expressions\n\n```grammar,expressions\nGroupedExpression -> `(` Expression `)`\n```\nA *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 `)`.\nParenthesized expressions evaluate to the value of the enclosed operand.\nA parenthesized expression is a place expression if the enclosed operand is a place expression, and is a value expression if the enclosed operand is a value expression.\nParentheses can be used to explicitly modify the precedence order of subexpressions within an expression.\nAn example of a parenthesized expression:\n```rust\nlet x: i32 = 2 + 3 * 4; // not parenthesized\nlet y: i32 = (2 + 3) * 4; // parenthesized\nassert_eq!(x, 14);\nassert_eq!(y, 20);\n```\nAn example of a necessary use of parentheses is when calling a function pointer that is a member of a struct:\n```rust\nassert_eq!( a.f (), \"The method f\");\nassert_eq!((a.f)(), \"The field f\");\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Grouped expressions", "heading_path": ["Grouped expressions"], "path": "expressions/grouped-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/grouped-expr.html#grouped-expressions", "has_code": true, "code_tags": ["grammar,expressions", "rust"]}} {"id": "reference/expressions/array-expr.md#array-expressions-0", "text": "The Rust Reference › Array and array index expressions › Array expressions\n\n```grammar,expressions\nArrayExpression -> `[` ArrayElements? `]`\n\nArrayElements ->\n Expression ( `,` Expression )* `,`?\n | Expression `;` Expression\n```\n*Array expressions* construct arrays. Array expressions come in two forms.\nThe first form lists out every value in the array.\nThe syntax for this form is a comma-separated list of expressions of uniform type enclosed in square brackets.\nThis produces an array containing each of these values in the order they are written.\nThe syntax for the second form is two expressions separated by a semicolon (`;`) enclosed in square brackets.\nThe expression before the `;` is called the *repeat operand*.\nThe expression after the `;` is called the *length operand*.\nThe length operand must either be an [inferred const] or be a [constant expression] of type `usize` (e.g. a [literal] or a [constant item]).\n```rust\nconst C: usize = 1;\nlet _: [u8; C] = [0; 1]; // Literal.\nlet _: [u8; C] = [0; C]; // Constant item.\nlet _: [u8; C] = [0; _]; // Inferred const.\nlet _: [u8; C] = [0; (((_)))]; // Inferred const.\n```\nIn an array expression, an [inferred const] is parsed as an expression but then semantically treated as a separate kind of [const generic argument].\nAn 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`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Array and index expressions", "heading_path": ["Array and array index expressions", "Array expressions"], "path": "expressions/array-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/array-expr.html#array-expressions", "has_code": true, "code_tags": ["grammar,expressions", "rust"]}} {"id": "reference/expressions/array-expr.md#array-expressions-1", "text": "The Rust Reference › Array and array index expressions › Array expressions\n\nIf the length operand has a value greater than 1 then this requires the repeat operand to have a type that implements [`Copy`], to be a [const block expression], or to be a [path] to a constant item.\nWhen the repeat operand is a const block or a path to a constant item, it is evaluated the number of times specified in the length operand.\nIf that value is `0`, then the const block or constant item is not evaluated at all.\nFor expressions that are neither a const block nor a path to a constant item, it is evaluated exactly once, and then the result is copied the length operand's value times.\n```rust\n[1, 2, 3, 4];\n[\"a\", \"b\", \"c\", \"d\"];\n[0; 128]; // array with 128 zeros\n[0u8, 0u8, 0u8, 0u8,];\n[[1, 0, 0], [0, 1, 0], [0, 0, 1]]; // 2D array\nconst EMPTY: Vec = Vec::new();\n[EMPTY; 2];\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Array and index expressions", "heading_path": ["Array and array index expressions", "Array expressions"], "path": "expressions/array-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/array-expr.html#array-expressions", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/array-expr.md#array-and-slice-indexing-expressions-2", "text": "The Rust Reference › Array and array index expressions › Array and slice indexing expressions\n\n```grammar,expressions\nIndexExpression -> Expression `[` Expression `]`\n```\n[Array] and [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] can be assigned to.\nFor 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, except that when the index expression undergoes [temporary lifetime extension], the indexed expression `a` also has its [temporary scope] extended. Just as with methods, Rust will also insert dereference operations on `a` repeatedly to find an implementation.\n```rust\n// The temporary holding the result of `vec![()]` is extended to\n// live to the end of the block, so `x` may be used in subsequent\n// statements.\nlet x = &vec();\n```\n```rust,compile_fail,E0716\n// The temporary holding the result of `vec![()]` is dropped at the\n// end of the statement, so it's an error to use `y` after.\nlet y = &*std::ops::Index::index(&vec![()], 0); // ERROR\n```\nIndices are zero-based for arrays and slices.\nArray access is a [constant expression], 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Array and index expressions", "heading_path": ["Array and array index expressions", "Array and slice indexing expressions"], "path": "expressions/array-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/array-expr.html#array-and-slice-indexing-expressions", "has_code": true, "code_tags": ["grammar,expressions", "rust", "rust,compile_fail,E0716"]}} {"id": "reference/expressions/array-expr.md#array-and-slice-indexing-expressions-3", "text": "The Rust Reference › Array and array index expressions › Array and slice indexing expressions\n\n```rust,should_panic\n// lint is deny by default.\n#![warn(unconditional_panic)]\n\n([1, 2, 3, 4])[2]; // Evaluates to 3\n\nlet b = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];\nb1; // multidimensional array indexing\n\nlet x = ([\"a\", \"b\"])[10]; // warning: index out of bounds\n\nlet n = 10;\nlet y = ([\"a\", \"b\"])[n]; // panics\n\nlet arr = [\"a\", \"b\"];\narr[10]; // warning: index out of bounds\n```\nThe array index expression can be implemented for types other than arrays and slices by implementing the [Index] and [IndexMut] traits.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Array and index expressions", "heading_path": ["Array and array index expressions", "Array and slice indexing expressions"], "path": "expressions/array-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/array-expr.html#array-and-slice-indexing-expressions", "has_code": true, "code_tags": ["rust,should_panic"]}} {"id": "reference/expressions/tuple-expr.md#tuple-expressions-0", "text": "The Rust Reference › Tuple and tuple indexing expressions › Tuple expressions\n\n```grammar,expressions\nTupleExpression -> `(` TupleElements? `)`\n\nTupleElements -> ( Expression `,` )+ Expression?\n```\nA *tuple expression* constructs tuple values.\nThe syntax for tuple expressions is a parenthesized, comma separated list of expressions, called the *tuple initializer operands*.\n1-ary tuple expressions require a comma after their tuple initializer operand to be disambiguated with a [parenthetical expression].\nTuple expressions are a [value expression] that evaluate into a newly constructed value of a tuple type.\nThe number of tuple initializer operands is the arity of the constructed tuple.\nTuple expressions without any tuple initializer operands produce the unit tuple.\nFor 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`.\nExamples of tuple expressions and their types:\n| Expression | Type |\n| -------------------- | ------------ |\n| `()` | `()` (unit) |\n| `(0.0, 4.5)` | `(f64, f64)` |\n| `(\"x\".to_string(), )` | `(String, )` |\n| `(\"a\", 4usize, true)`| `(&'static str, usize, bool)` |", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tuple and index expressions", "heading_path": ["Tuple and tuple indexing expressions", "Tuple expressions"], "path": "expressions/tuple-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/tuple-expr.html#tuple-expressions", "has_code": true, "code_tags": ["grammar,expressions"]}} {"id": "reference/expressions/tuple-expr.md#tuple-indexing-expressions-1", "text": "The Rust Reference › Tuple and tuple indexing expressions › Tuple indexing expressions\n\n```grammar,expressions\nTupleIndexingExpression -> Expression `.` TUPLE_INDEX\n```\nA *tuple indexing expression* accesses fields of tuples and tuple structs.\nThe syntax for a tuple index expression is an expression, called the *tuple operand*, then a `.`, then finally a tuple index.\nThe syntax for the *tuple index* is a [decimal literal] with no leading zeros, underscores, or suffix. For example `0` and `2` are valid tuple indices but not `01`, `0_`, nor `0i32`.\nThe type of the tuple operand must be a [tuple type] or a [tuple struct].\nThe tuple index must be a name of a field of the type of the tuple operand.\nEvaluation of tuple index expressions has no side effects beyond evaluation of its tuple operand. As a [place expression], it evaluates to the location of the field of the tuple operand with the same name as the tuple index.\nExamples of tuple indexing expressions:\n```rust\n// Indexing a tuple\nlet pair = (\"a string\", 2);\nassert_eq!(pair.1, 2);\n\n// Indexing a tuple struct\nlet point = Point(1.0, 0.0);\nassert_eq!(point.0, 1.0);\nassert_eq!(point.1, 0.0);\n```\nUnlike field access expressions, tuple index expressions can be the function operand of a [call expression] as it cannot be confused with a method call since method names cannot be numbers.\nAlthough arrays and slices also have elements, you must use an [array or slice indexing expression] or a [slice pattern] to access their elements.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tuple and index expressions", "heading_path": ["Tuple and tuple indexing expressions", "Tuple indexing expressions"], "path": "expressions/tuple-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/tuple-expr.html#tuple-indexing-expressions", "has_code": true, "code_tags": ["grammar,expressions", "rust"]}} {"id": "reference/expressions/struct-expr.md#struct-expressions-0", "text": "The Rust Reference › Struct expressions\n\n```grammar,expressions\nStructExpression ->\n PathInExpression `{` (StructExprFields | StructBase)? `}`\n\nStructExprFields ->\n StructExprField (`,` StructExprField)* (`,` StructBase | `,`?)\n\nStructExprField ->\n OuterAttribute*\n (\n IDENTIFIER\n | (IDENTIFIER | TUPLE_INDEX) `:` Expression\n )\n\nStructBase -> `..` Expression\n```\nA *struct expression* creates a struct, enum, or union value. It consists of a path to a [struct], [enum variant], or [union] item followed by the values for the fields of the item.\nThe following are examples of struct expressions:\n```rust\nPoint {x: 10.0, y: 20.0};\nNothingInMe {};\nlet u = game::User {name: \"Joe\", age: 35, score: 100_000};\nEnum::Variant {};\n```\nTuple structs and tuple enum variants are typically instantiated using a call expression referring to the constructor in the value namespace. These are distinct from a struct expression using curly braces referring to the constructor in the type namespace.\n```rust\nstruct Position(i32, i32, i32);\nPosition(0, 0, 0); // Typical way of creating a tuple struct.\nlet c = Position; // `c` is a function that takes 3 arguments.\nlet pos = c(8, 6, 7); // Creates a `Position` value.\n\nenum Version { Triple(i32, i32, i32) };\nVersion::Triple(0, 0, 0);\nlet f = Version::Triple;\nlet ver = f(8, 6, 7);\n```\nThe last segment of the call path cannot refer to a type alias:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Struct expressions", "heading_path": ["Struct expressions"], "path": "expressions/struct-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/struct-expr.html#struct-expressions", "has_code": true, "code_tags": ["grammar,expressions", "rust"]}} {"id": "reference/expressions/struct-expr.md#struct-expressions-1", "text": "The Rust Reference › Struct expressions\n\n```rust\ntrait Tr { type T; }\nimpl Tr for T { type T = T; }\n\nstruct Tuple();\nenum Enum { Tuple() }\n\n// ::T(); // causes an error -- `::T` is a type, not a value\n::T::Tuple(); // OK\n```\n----\nUnit structs and unit enum variants are typically instantiated using a path expression referring to the constant in the value namespace.\n```rust\nstruct Gamma;\n// Gamma unit value, referring to the const in the value namespace.\nlet a = Gamma;\n// Exact same value as `a`, but constructed using a struct expression\n// referring to the type namespace.\nlet b = Gamma {};\n\nenum ColorSpace { Oklch }\nlet c = ColorSpace::Oklch;\nlet d = ColorSpace::Oklch {};\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Struct expressions", "heading_path": ["Struct expressions"], "path": "expressions/struct-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/struct-expr.html#struct-expressions", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/struct-expr.md#field-struct-expression-2", "text": "The Rust Reference › Struct expressions › Field struct expression\n\nA 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.\nA value of a [union] type can only be created using this syntax, and it must specify exactly one field.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Struct expressions", "heading_path": ["Struct expressions", "Field struct expression"], "path": "expressions/struct-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/struct-expr.html#field-struct-expression", "has_code": false, "code_tags": []}} {"id": "reference/expressions/struct-expr.md#functional-update-syntax-3", "text": "The Rust Reference › Struct expressions › Functional update syntax\n\nA struct expression that constructs a value of a struct type can terminate with the syntax `..` followed by an expression to denote a functional update.\nThe expression following `..` (the base) must have the same struct type as the new struct type being formed.\nThe entire expression uses the given values for the fields that were specified and moves or copies the remaining fields from the base expression.\nAs with all struct expressions, all of the fields of the struct must be [visible], even those not explicitly named.\n```rust\nlet mut base = Point3d {x: 1, y: 2, z: 3};\nlet y_ref = &mut base.y;\nPoint3d {y: 0, z: 10, .. base}; // OK, only base.x is accessed\ndrop(y_ref);\n```\nStruct expressions can't be used directly in a [loop] or [if] expression's head, or in the [scrutinee] of an [if let] or [match] expression. However, struct expressions can be used in these situations if they are within another expression, for example inside [parentheses].\nThe 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:\n```rust\nstruct Color(u8, u8, u8);\nlet c1 = Color(0, 0, 0); // Typical way of creating a tuple struct.\nlet c2 = Color{0: 255, 1: 127, 2: 0}; // Specifying fields by index.\nlet c3 = Color{1: 0, ..c2}; // Fill out all other fields using a base struct.\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Struct expressions", "heading_path": ["Struct expressions", "Functional update syntax"], "path": "expressions/struct-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/struct-expr.html#functional-update-syntax", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/struct-expr.md#struct-field-init-shorthand-4", "text": "The Rust Reference › Struct expressions › Functional update syntax › Struct field init shorthand\n\nWhen 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:\n```rust\nPoint3d { x: x, y: y_value, z: z };\nPoint3d { x, y: y_value, z };\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Struct expressions", "heading_path": ["Struct expressions", "Functional update syntax", "Struct field init shorthand"], "path": "expressions/struct-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/struct-expr.html#struct-field-init-shorthand", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/call-expr.md#call-expressions-0", "text": "The Rust Reference › Call expressions\n\n```grammar,expressions\nCallExpression -> Expression `(` CallParams? `)`\n\nCallParams -> Expression ( `,` Expression )* `,`?\n```\nA *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*.\nIf the function eventually returns, then the expression completes.\nFor [non-function types], the expression `f(...)` uses the method on one of the following traits based on the function operand:\n- [`Fn`] or [`AsyncFn`] --- shared reference.\n- [`FnMut`] or [`AsyncFnMut`] --- mutable reference.\n- [`FnOnce`] or [`AsyncFnOnce`] --- value.\nAn automatic borrow will be taken if needed. The function operand will also be [automatically dereferenced] as required.\nSome examples of call expressions:\n```rust\nlet three: i32 = add(1i32, 2i32);\nlet name: &'static str = (|| \"Rust\")();\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Call expressions", "heading_path": ["Call expressions"], "path": "expressions/call-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/call-expr.html#call-expressions", "has_code": true, "code_tags": ["grammar,expressions", "rust"]}} {"id": "reference/expressions/call-expr.md#disambiguating-function-calls-1", "text": "The Rust Reference › Call expressions › Disambiguating function calls\n\nAll function calls are sugar for a more explicit [fully-qualified syntax].\nFunction calls may need to be fully qualified, depending on the ambiguity of a call in light of in-scope items.\nIn 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.\nSeveral situations often occur which result in ambiguities about the receiver or referent of method or associated function calls. These situations may include:\n* Multiple in-scope traits define methods with the same name for the same types\n* Auto-`deref` is undesirable; for example, distinguishing between methods on a smart pointer itself and the pointer's referent\n* Methods which take no arguments, like [`default()`], and return properties of a type, like [`size_of()`]\nTo resolve the ambiguity, the programmer may refer to their desired method or function using more specific paths, types, or traits.\nFor example,", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Call expressions", "heading_path": ["Call expressions", "Disambiguating function calls"], "path": "expressions/call-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/call-expr.html#disambiguating-function-calls", "has_code": false, "code_tags": []}} {"id": "reference/expressions/call-expr.md#disambiguating-function-calls-2", "text": "The Rust Reference › Call expressions › Disambiguating function calls\n\n```rust\ntrait Pretty {\n fn print(&self);\n}\n\ntrait Ugly {\n fn print(&self);\n}\n\nstruct Foo;\nimpl Pretty for Foo {\n fn print(&self) {}\n}\n\nstruct Bar;\nimpl Pretty for Bar {\n fn print(&self) {}\n}\nimpl Ugly for Bar {\n fn print(&self) {}\n}\n\nfn main() {\n let f = Foo;\n let b = Bar;\n\n // we can do this because we only have one item called `print` for `Foo`s\n f.print();\n // more explicit, and, in the case of `Foo`, not necessary\n Foo::print(&f);\n // if you're not into the whole brevity thing\n ::print(&f);\n\n // b.print(); // Error: multiple 'print' found\n // Bar::print(&b); // Still an error: multiple `print` found\n\n // necessary because of in-scope items defining `print`\n ::print(&b);\n}\n```\nRefer to [RFC 132] for further details and motivations.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Call expressions", "heading_path": ["Call expressions", "Disambiguating function calls"], "path": "expressions/call-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/call-expr.html#disambiguating-function-calls", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/method-call-expr.md#method-call-expressions-0", "text": "The Rust Reference › Method-call expressions\n\n```grammar,expressions\nMethodCallExpression -> Expression `.` PathExprSegment `(`CallParams? `)`\n```\nA _method call_ consists of an expression (the *receiver*) followed by a single dot, an expression path segment, and a parenthesized expression-list.\nMethod calls are resolved to associated [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.\n```rust\nlet pi: Result = \"3.14\".parse();\nlet log_pi = pi.unwrap_or(1.0).log(2.72);\n```\nWhen 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:\nThe first step is to build a list of candidate receiver types. Obtain these by repeatedly dereferencing the receiver expression's type, adding each type encountered to the list, then finally attempting an array [unsized coercion] at the end, and adding the result type if that is successful.\nThen, for each candidate `T`, add `&T` and `&mut T` to the list immediately after `T`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Method call expressions", "heading_path": ["Method-call expressions"], "path": "expressions/method-call-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/method-call-expr.html#method-call-expressions", "has_code": true, "code_tags": ["grammar,expressions", "rust"]}} {"id": "reference/expressions/method-call-expr.md#method-call-expressions-1", "text": "The Rust Reference › Method-call expressions\n\nFor 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]`.\nThen, for each candidate type `T`, search for a [visible] method with a receiver of that type in the following places:\n1. `T`'s inherent methods (methods implemented directly on `T`).\n1. Any of the methods provided by a [visible] 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.\nThe 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.\n```rust\nstruct Foo {}\n\ntrait Bar {\n fn bar(&self);\n}\n\nimpl Foo {\n fn bar(&mut self) {\n println!(\"In struct impl!\")\n }\n}\n\nimpl Bar for Foo {\n fn bar(&self) {\n println!(\"In trait impl!\")\n }\n}\n\nfn main() {\n let mut f = Foo{};\n f.bar();\n}\n```\nIf this results in multiple possible candidates, then it is an error, and the receiver must be converted to an appropriate receiver type to make the method call.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Method call expressions", "heading_path": ["Method-call expressions"], "path": "expressions/method-call-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/method-call-expr.html#method-call-expressions", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/method-call-expr.md#method-call-expressions-2", "text": "The Rust Reference › Method-call expressions\n\nThis 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.\nIf 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] for method and function invocation.\n[!EDITION-2021]\nBefore the 2021 edition, during the search for visible methods, if the candidate receiver type is an [array type], methods provided by the standard library [`IntoIterator`] trait are ignored.\nThe edition used for this purpose is determined by the token representing the method name.\nThis special case may be removed in the future.\nFor [trait objects], 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], 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Method call expressions", "heading_path": ["Method-call expressions"], "path": "expressions/method-call-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/method-call-expr.html#method-call-expressions", "has_code": false, "code_tags": []}} {"id": "reference/expressions/field-expr.md#field-access-expressions-0", "text": "The Rust Reference › Field access expressions\n\n```grammar,expressions\nFieldExpression -> Expression `.` IDENTIFIER\n```\nA *field expression* is a [place expression] that evaluates to the location of a field of a [struct] or [union].\nWhen the operand is [mutable], the field expression is also mutable.\nThe syntax for a field expression is an expression, called the *container operand*, then a `.`, and finally an [identifier].\nField expressions cannot be followed by a parenthetical comma-separated list of expressions, as that is instead parsed as a [method call expression]. That is, they cannot be the function operand of a [call expression].\nWrap the field expression in a [parenthesized expression] to use it in a call expression.\n```rust\nlet holds_callable = HoldsCallable { callable: || () };\n\n// Invalid: Parsed as calling the method \"callable\"\n// holds_callable.callable();\n\n// Valid\n(holds_callable.callable)();\n```\nExamples:\n```rust,ignore\nmystruct.myfield;\nfoo().x;\n(Struct {a: 10, b: 20}).a;\n(mystruct.function_field)() // Call expression containing a field expression\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Field access expressions", "heading_path": ["Field access expressions"], "path": "expressions/field-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/field-expr.html#field-access-expressions", "has_code": true, "code_tags": ["grammar,expressions", "rust", "rust,ignore"]}} {"id": "reference/expressions/field-expr.md#automatic-dereferencing-1", "text": "The Rust Reference › Field access expressions › Automatic dereferencing\n\nIf the type of the container operand implements [`Deref`] or `DerefMut` depending on whether the operand is [mutable], it is *automatically dereferenced* as many times as necessary to make the field access possible. This process is also called *autoderef* for short.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Field access expressions", "heading_path": ["Field access expressions", "Automatic dereferencing"], "path": "expressions/field-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/field-expr.html#automatic-dereferencing", "has_code": false, "code_tags": []}} {"id": "reference/expressions/field-expr.md#borrowing-2", "text": "The Rust Reference › Field access expressions › Borrowing\n\nThe fields of a struct or a reference to a struct are treated as separate entities when borrowing. If the struct does not implement [`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 through user-defined types other than [`Box`].\n```rust\nstruct A { f1: String, f2: String, f3: String }\nlet mut x: A;\nlet a: &mut String = &mut x.f1; // x.f1 borrowed mutably\nlet b: &String = &x.f2; // x.f2 borrowed immutably\nlet c: &String = &x.f2; // Can borrow again\nlet d: String = x.f3; // Move out of x.f3\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Field access expressions", "heading_path": ["Field access expressions", "Borrowing"], "path": "expressions/field-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/field-expr.html#borrowing", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/closure-expr.md#closure-expressions-0", "text": "The Rust Reference › Closure expressions\n\n```grammar,expressions\nClosureExpression ->\n `async`?[^cl-async-edition]\n `move`?\n ( `||` | `|` ClosureParameters? `|` )\n (Expression | `->` TypeNoBounds BlockExpression)\n\nClosureParameters -> ClosureParam (`,` ClosureParam)* `,`?\n\nClosureParam -> OuterAttribute* PatternNoTopAlt ( `:` Type )?\n```\n[^cl-async-edition]: The `async` qualifier is not allowed in the 2015 edition.\nA *closure expression*, also known as a lambda expression or a lambda, defines a [closure type] and evaluates to a value of that type. The syntax for a closure expression is an optional `async` keyword, an optional `move` keyword, then a pipe-symbol-delimited (`|`) comma-separated list of [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*.\nThe optional type after each pattern is a type annotation for the pattern.\nIf there is a return type, the closure body must be a [block].\nA closure expression denotes a function that maps a list of parameters onto the expression that follows the parameters. Just like a [`let` binding], the closure parameters are irrefutable [patterns], whose type annotation is optional and will be inferred from context if not given.\nEach closure expression has a unique, anonymous type.\nSignificantly, closure expressions _capture their environment_, which regular [function definitions] do not.\nWithout the `move` keyword, the closure expression infers how it captures each variable from its environment, preferring to capture by shared reference, effectively borrowing all outer variables mentioned inside the closure's body.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure expressions", "heading_path": ["Closure expressions"], "path": "expressions/closure-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/closure-expr.html#closure-expressions", "has_code": true, "code_tags": ["grammar,expressions"]}} {"id": "reference/expressions/closure-expr.md#closure-expressions-1", "text": "The Rust Reference › Closure expressions\n\nIf 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.\nA 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`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure expressions", "heading_path": ["Closure expressions"], "path": "expressions/closure-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/closure-expr.html#closure-expressions", "has_code": false, "code_tags": []}} {"id": "reference/expressions/closure-expr.md#closure-trait-implementations-2", "text": "The Rust Reference › Closure expressions › Closure trait implementations\n\nWhich traits the closure type implements depends on how variables are captured, the types of the captured variables, and the presence of `async`. See the [call traits and coercions] chapter for how and when a closure implements `Fn`, `FnMut`, and `FnOnce`. The closure type implements [`Send`] and [`Sync`] if the type of every captured variable also implements the trait.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure expressions", "heading_path": ["Closure expressions", "Closure trait implementations"], "path": "expressions/closure-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/closure-expr.html#closure-trait-implementations", "has_code": false, "code_tags": []}} {"id": "reference/expressions/closure-expr.md#async-closures-3", "text": "The Rust Reference › Closure expressions › Async closures\n\nClosures marked with the `async` keyword indicate that they are asynchronous in an analogous way to an async function.\nCalling the async closure does not perform any work, but instead evaluates to a value that implements [`Future`] that corresponds to the computation of the body of the closure.\n```rust\nasync fn takes_async_callback(f: impl AsyncFn(u64)) {\n f(0).await;\n f(1).await;\n}\n\nasync fn example() {\n takes_async_callback(async |i| {\n core::future::ready(i).await;\n println!(\"done with {i}.\");\n }).await;\n}\n```\n[!EDITION-2018]\nAsync closures are only available beginning with Rust 2018.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure expressions", "heading_path": ["Closure expressions", "Async closures"], "path": "expressions/closure-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/closure-expr.html#async-closures", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/closure-expr.md#example-4", "text": "The Rust Reference › Closure expressions › Example\n\nIn 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.\n```rust\nfn ten_times(f: F) where F: Fn(i32) {\n for index in 0..10 {\n f(index);\n }\n}\n\nten_times(|j| println!(\"hello, {}\", j));\n// With type annotations\nten_times(|j: i32| -> () { println!(\"hello, {}\", j) });\n\nlet word = \"konnichiwa\".to_owned();\nten_times(move |j| println!(\"{}, {}\", word, j));\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure expressions", "heading_path": ["Closure expressions", "Example"], "path": "expressions/closure-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/closure-expr.html#example", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/closure-expr.md#attributes-on-closure-parameters-5", "text": "The Rust Reference › Closure expressions › Attributes on closure parameters\n\nAttributes on closure parameters follow the same rules and restrictions as [regular function parameters].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure expressions", "heading_path": ["Closure expressions", "Attributes on closure parameters"], "path": "expressions/closure-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/closure-expr.html#attributes-on-closure-parameters", "has_code": false, "code_tags": []}} {"id": "reference/expressions/loop-expr.md#loops-and-other-breakable-expressions-0", "text": "The Rust Reference › Loops and other breakable expressions\n\n```grammar,expressions\nLoopExpression ->\n LoopLabel? (\n InfiniteLoopExpression\n | PredicateLoopExpression\n | IteratorLoopExpression\n | LabelBlockExpression\n )\n```\nRust supports four loop expressions:\n* A `loop` expression denotes an infinite loop.\n* A `while` expression loops until a predicate is false.\n* A `for` expression extracts values from an iterator, looping until the iterator is empty.\n* A labeled block expression runs a loop exactly once, but allows exiting the loop early with `break`.\nAll four types of loop support `break` expressions, and labels.\nAll except labeled block expressions support `continue` expressions.\nOnly `loop` and labeled block expressions support evaluation to non-trivial values.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Loop expressions", "heading_path": ["Loops and other breakable expressions"], "path": "expressions/loop-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/loop-expr.html#loops-and-other-breakable-expressions", "has_code": true, "code_tags": ["grammar,expressions"]}} {"id": "reference/expressions/loop-expr.md#infinite-loops-1", "text": "The Rust Reference › Loops and other breakable expressions › Infinite loops\n\n```grammar,expressions\nInfiniteLoopExpression -> `loop` BlockExpression\n```\nA `loop` expression repeats execution of its body continuously: `loop { println!(\"I live.\"); }`.\nA `loop` expression without an associated `break` expression is [diverging] and has type [`!`].\nA `loop` expression containing associated `break` expression(s) may terminate, and must have type compatible with the value of the `break` expression(s).", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Loop expressions", "heading_path": ["Loops and other breakable expressions", "Infinite loops"], "path": "expressions/loop-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/loop-expr.html#infinite-loops", "has_code": true, "code_tags": ["grammar,expressions"]}} {"id": "reference/expressions/loop-expr.md#predicate-loops-2", "text": "The Rust Reference › Loops and other breakable expressions › Predicate loops\n\n```grammar,expressions\nPredicateLoopExpression -> `while` Conditions BlockExpression\n```\nA `while` loop expression allows repeating the evaluation of a block while a set of conditions remain true.\nCondition operands must be either an [Expression] with a [boolean type] or a conditional `let` match. If all of the condition operands evaluate to `true` and all of the `let` patterns successfully match their [scrutinee]s, then the loop body block executes.\nAfter the loop body successfully executes, the condition operands are re-evaluated to determine if the body should be executed again.\nIf any condition operand evaluates to `false` or any `let` pattern does not match its scrutinee, the body is not executed and execution continues after the `while` expression.\nA `while` expression evaluates to `()`.\nAn example:\n```rust\nlet mut i = 0;\n\nwhile i < 10 {\n println!(\"hello\");\n i = i + 1;\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Loop expressions", "heading_path": ["Loops and other breakable expressions", "Predicate loops"], "path": "expressions/loop-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/loop-expr.html#predicate-loops", "has_code": true, "code_tags": ["grammar,expressions", "rust"]}} {"id": "reference/expressions/loop-expr.md#while-let-patterns-3", "text": "The Rust Reference › Loops and other breakable expressions › Predicate loops › `while let` patterns\n\n`let` patterns in a `while` condition allow binding new variables into scope when the pattern matches successfully. The following examples illustrate bindings using `let` patterns:\n```rust\nlet mut x = vec![1, 2, 3];\n\nwhile let Some(y) = x.pop() {\n println!(\"y = {}\", y);\n}\n\nwhile let _ = 5 {\n println!(\"Irrefutable patterns are always true\");\n break;\n}\n```\nA `while let` loop is equivalent to a `loop` expression containing a [`match` expression] as follows.\n```rust,ignore\n'label: while let PATS = EXPR {\n /* loop body */\n}\n```\nis equivalent to\n```rust,ignore\n'label: loop {\n match EXPR {\n PATS => { /* loop body */ },\n _ => break,\n }\n}\n```\nMultiple patterns may be specified with the `|` operator. This has the same semantics as with `|` in `match` expressions:\n```rust\nlet mut vals = vec![2, 3, 1, 2, 2];\nwhile let Some(v @ 1) | Some(v @ 2) = vals.pop() {\n // Prints 2, 2, then 1\n println!(\"{}\", v);\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Loop expressions", "heading_path": ["Loops and other breakable expressions", "Predicate loops", "`while let` patterns"], "path": "expressions/loop-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/loop-expr.html#while-let-patterns", "has_code": true, "code_tags": ["rust", "rust,ignore"]}} {"id": "reference/expressions/loop-expr.md#while-condition-chains-4", "text": "The Rust Reference › Loops and other breakable expressions › Predicate loops › `while` condition chains\n\nMultiple condition operands can be separated with `&&`. These have the same semantics and restrictions as [`if` condition chains].\nThe following is an example of chaining multiple expressions, mixing `let` bindings and boolean expressions, and with expressions able to reference pattern bindings from previous expressions:\n```rust\nfn main() {\n let outer_opt = Some(Some(1i32));\n\n while let Some(inner_opt) = outer_opt\n && let Some(number) = inner_opt\n && number == 1\n {\n println!(\"Peek a boo\");\n break;\n }\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Loop expressions", "heading_path": ["Loops and other breakable expressions", "Predicate loops", "`while` condition chains"], "path": "expressions/loop-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/loop-expr.html#while-condition-chains", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/loop-expr.md#iterator-loops-5", "text": "The Rust Reference › Loops and other breakable expressions › Iterator loops\n\n```grammar,expressions\nIteratorLoopExpression ->\n `for` Pattern `in` Expression _except [StructExpression]_ BlockExpression\n```\nA `for` expression is a syntactic construct for looping over elements provided by an implementation of `std::iter::IntoIterator`.\nIf 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.\nAn example of a `for` loop over the contents of an array:\n```rust\nlet v = &[\"apples\", \"cake\", \"coffee\"];\n\nfor text in v {\n println!(\"I like {}.\", text);\n}\n```\nAn example of a for loop over a series of integers:\n```rust\nlet mut sum = 0;\nfor n in 1..11 {\n sum += n;\n}\nassert_eq!(sum, 55);\n```\nA `for` loop is equivalent to a `loop` expression containing a [`match` expression] as follows:\n```rust,ignore\n'label: for PATTERN in iter_expr {\n /* loop body */\n}\n```\nis equivalent to\n```rust,ignore\n{\n let result = match IntoIterator::into_iter(iter_expr) {\n mut iter => 'label: loop {\n let mut next;\n match Iterator::next(&mut iter) {\n Option::Some(val) => next = val,\n Option::None => break,\n };\n let PATTERN = next;\n let () = { /* loop body */ };\n },\n };\n result\n}\n```\n`IntoIterator`, `Iterator`, and `Option` are always the standard library items here, not whatever those names resolve to in the current scope.\nThe variable names `next`, `iter`, and `val` are for exposition only, they do not actually have names the user can type.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Loop expressions", "heading_path": ["Loops and other breakable expressions", "Iterator loops"], "path": "expressions/loop-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/loop-expr.html#iterator-loops", "has_code": true, "code_tags": ["grammar,expressions", "rust", "rust,ignore"]}} {"id": "reference/expressions/loop-expr.md#iterator-loops-6", "text": "The Rust Reference › Loops and other breakable expressions › Iterator loops\n\nThe outer `match` is used to ensure that any [temporary values] 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Loop expressions", "heading_path": ["Loops and other breakable expressions", "Iterator loops"], "path": "expressions/loop-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/loop-expr.html#iterator-loops", "has_code": false, "code_tags": []}} {"id": "reference/expressions/loop-expr.md#loop-labels-7", "text": "The Rust Reference › Loops and other breakable expressions › Loop labels\n\n```grammar,expressions\nLoopLabel -> LIFETIME_OR_LABEL `:`\n```\nA 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 {}`.\nIf 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 and continue expressions.\nLabels follow the hygiene and shadowing rules of local variables. For example, this code will print \"outer loop\":\n```rust\n'a: loop {\n 'a: loop {\n break 'a;\n }\n print!(\"outer loop\");\n break 'a;\n}\n```\n`'_` is not a valid loop label.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Loop expressions", "heading_path": ["Loops and other breakable expressions", "Loop labels"], "path": "expressions/loop-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/loop-expr.html#loop-labels", "has_code": true, "code_tags": ["grammar,expressions", "rust"]}} {"id": "reference/expressions/loop-expr.md#break-expressions-8", "text": "The Rust Reference › Loops and other breakable expressions › `break` expressions\n\n```grammar,expressions\nBreakExpression -> `break` LIFETIME_OR_LABEL? Expression?\n```\nWhen `break` is encountered, execution of the associated loop body is immediately terminated, for example:\n```rust\nlet mut last = 0;\nfor x in 1..100 {\n if x > 12 {\n break;\n }\n last = x;\n}\nassert_eq!(last, 12);\n```\nA `break` expression is [diverging] and has a type of [`!`].\nA `break` expression is normally associated with the innermost `loop`, `for` or `while` loop enclosing the `break` expression, but a label can be used to specify which enclosing loop is affected. Example:\n```rust\n'outer: loop {\n while true {\n break 'outer;\n }\n}\n```\nA `break` expression is only permitted in the body of a loop, and has one of the forms `break`, `break 'label` or (see below) `break EXPR` or `break 'label EXPR`.\nIn a `loop` with break expressions or a [labeled block expression], a `break` without an expression is equivalent to `break ()`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Loop expressions", "heading_path": ["Loops and other breakable expressions", "`break` expressions"], "path": "expressions/loop-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/loop-expr.html#break-expressions", "has_code": true, "code_tags": ["grammar,expressions", "rust"]}} {"id": "reference/expressions/loop-expr.md#labeled-block-expressions-9", "text": "The Rust Reference › Loops and other breakable expressions › Labeled block expressions\n\n```grammar,expressions\nLabelBlockExpression -> BlockExpression\n```\nLabeled block expressions are exactly like block expressions, except that they allow using `break` expressions within the block.\nUnlike loops, `break` expressions within a labeled block expression *must* have a label (i.e. the label is not optional).\nSimilarly, labeled block expressions *must* begin with a label.\n```rust\nlet result = 'block: {\n do_thing();\n if condition_not_met() {\n break 'block 1;\n }\n do_next_thing();\n if condition_not_met() {\n break 'block 2;\n }\n do_last_thing();\n 3\n};\n```\nThe type of a labeled block expression is the [least upper bound] of all of the break operands and the final operand. If the final operand is omitted, the type of the final operand defaults to the [unit type], unless the block diverges, in which case it is the [never type].\n```rust\nfn example(condition: bool) {\n let s = String::from(\"owned\");\n\n let _: &str = 'block: {\n if condition {\n break 'block &s; // &String coerced to &str via Deref\n }\n break 'block \"literal\"; // &'static str coerced to &str\n };\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Loop expressions", "heading_path": ["Loops and other breakable expressions", "Labeled block expressions"], "path": "expressions/loop-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/loop-expr.html#labeled-block-expressions", "has_code": true, "code_tags": ["grammar,expressions", "rust"]}} {"id": "reference/expressions/loop-expr.md#continue-expressions-10", "text": "The Rust Reference › Loops and other breakable expressions › `continue` expressions\n\n```grammar,expressions\nContinueExpression -> `continue` LIFETIME_OR_LABEL?\n```\nWhen `continue` is encountered, the current iteration of the associated loop body is immediately terminated, returning control to the loop *head*.\nA `continue` expression is [diverging] and has a type of [`!`].\nIn the case of a `while` loop, the head is the conditional operands controlling the loop.\nIn the case of a `for` loop, the head is the call-expression controlling the loop.\nLike `break`, `continue` is normally associated with the innermost enclosing loop, but `continue 'label` may be used to specify the loop affected.\nA `continue` expression is only permitted in the body of a loop.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Loop expressions", "heading_path": ["Loops and other breakable expressions", "`continue` expressions"], "path": "expressions/loop-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/loop-expr.html#continue-expressions", "has_code": true, "code_tags": ["grammar,expressions"]}} {"id": "reference/expressions/loop-expr.md#break-and-loop-values-11", "text": "The Rust Reference › Loops and other breakable expressions › `break` and loop values\n\nWhen 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:\n```rust\nlet (mut a, mut b) = (1, 1);\nlet result = loop {\n if b > 10 {\n break b;\n }\n let c = a + b;\n a = b;\n b = c;\n};\n// first number in Fibonacci sequence over 10:\nassert_eq!(result, 13);\n```\nThe type of a `loop` with associated `break` expressions is the [least upper bound] of all of the break operands.\n```rust\nfn example(condition: bool) {\n let s = String::from(\"owned\");\n\n let _: &str = loop {\n if condition {\n break &s; // &String coerced to &str via Deref\n }\n break \"literal\"; // &'static str coerced to &str\n };\n}\n```\nA `loop` with associated `break` expressions does not [diverge] if any of the break operands do not diverge. If all of the `break` operands diverge, then the `loop` expression also diverges.\n```rust\nfn diverging_loop_with_break(condition: bool) -> ! {\n // This loop is diverging because all `break` operands are diverging.\n loop {\n if condition {\n break loop {};\n } else {\n break panic!();\n }\n }\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Loop expressions", "heading_path": ["Loops and other breakable expressions", "`break` and loop values"], "path": "expressions/loop-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/loop-expr.html#break-and-loop-values", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/loop-expr.md#break-and-loop-values-12", "text": "The Rust Reference › Loops and other breakable expressions › `break` and loop values\n\n```rust,compile_fail,E0308\nfn loop_with_non_diverging_break(condition: bool) -> ! {\n // The type of this loop is i32 even though one of the breaks is\n // diverging.\n loop {\n if condition {\n break loop {};\n } else {\n break 123i32;\n }\n } // ERROR: expected `!`, found `i32`\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Loop expressions", "heading_path": ["Loops and other breakable expressions", "`break` and loop values"], "path": "expressions/loop-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/loop-expr.html#break-and-loop-values", "has_code": true, "code_tags": ["rust,compile_fail,E0308"]}} {"id": "reference/expressions/range-expr.md#range-expressions-0", "text": "The Rust Reference › Range expressions\n\n```grammar,expressions\nRangeExpression ->\n RangeExpr\n | RangeFromExpr\n | RangeToExpr\n | RangeFullExpr\n | RangeInclusiveExpr\n | RangeToInclusiveExpr\n\nRangeExpr -> Expression `..` Expression\n\nRangeFromExpr -> Expression `..`\n\nRangeToExpr -> `..` Expression\n\nRangeFullExpr -> `..`\n\nRangeInclusiveExpr -> Expression `..=` Expression\n\nRangeToInclusiveExpr -> `..=` Expression\n```\nThe `..` and `..=` operators will construct an object of one of the `std::ops::Range` (or `core::ops::Range`) variants, according to the following table:\n| Production | Syntax | Type | Range |\n|------------------------|---------------|------------------------------|-----------------------|\n| [RangeExpr] | start`..`end | [std::ops::Range] | start ≤ x < end |\n| [RangeFromExpr] | start`..` | [std::ops::RangeFrom] | start ≤ x |\n| [RangeToExpr] | `..`end | [std::ops::RangeTo] | x < end |\n| [RangeFullExpr] | `..` | [std::ops::RangeFull] | - |\n| [RangeInclusiveExpr] | start`..=`end | [std::ops::RangeInclusive] | start ≤ x ≤ end |\n| [RangeToInclusiveExpr] | `..=`end | [std::ops::RangeToInclusive] | x ≤ end |\nExamples:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Range expressions", "heading_path": ["Range expressions"], "path": "expressions/range-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/range-expr.html#range-expressions", "has_code": true, "code_tags": ["grammar,expressions"]}} {"id": "reference/expressions/range-expr.md#range-expressions-1", "text": "The Rust Reference › Range expressions\n\n```rust\n1..2; // std::ops::Range\n3..; // std::ops::RangeFrom\n..4; // std::ops::RangeTo\n..; // std::ops::RangeFull\n5..=6; // std::ops::RangeInclusive\n..=7; // std::ops::RangeToInclusive\n```\nThe following expressions are equivalent.\n```rust\nlet x = std::ops::Range {start: 0, end: 10};\nlet y = 0..10;\n\nassert_eq!(x, y);\n```\nRanges can be used in `for` loops:\n```rust\nfor i in 1..11 {\n println!(\"{}\", i);\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Range expressions", "heading_path": ["Range expressions"], "path": "expressions/range-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/range-expr.html#range-expressions", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/if-expr.md#if-expressions-0", "text": "The Rust Reference › `if` expressions\n\n```grammar,expressions\nIfExpression ->\n `if` Conditions BlockExpressionNoInnerAttributes\n (`else` ( BlockExpressionNoInnerAttributes | IfExpression ) )?\n\nConditions ->\n Expression _except [StructExpression]_\n | LetChain\n\nLetChain -> LetChainCondition ( `&&` LetChainCondition )*\n\nLetChainCondition ->\n Expression _except [ExcludedConditions]_\n | OuterAttribute* `let` Pattern `=` Scrutinee _except [ExcludedConditions]_\n\n@root ExcludedConditions ->\n StructExpression\n | LazyBooleanExpression\n | RangeExpr\n | RangeFromExpr\n | RangeInclusiveExpr\n | AssignmentExpression\n | CompoundAssignmentExpression\n```\nThe syntax of an `if` expression is a sequence of one or more condition operands separated by `&&`, followed by a consequent block, any number of `else if` conditions and blocks, and an optional trailing `else` block.\nCondition operands must be either an [Expression] with a [boolean type] or a conditional `let` match.\nIf all of the condition operands evaluate to `true` and all of the `let` patterns successfully match their [scrutinee]s, the consequent block is executed and any subsequent `else if` or `else` block is skipped.\nIf any condition operand evaluates to `false` or any `let` pattern does not match its scrutinee, the consequent block is skipped and any subsequent `else if` condition is evaluated.\nIf all `if` and `else if` conditions evaluate to `false` then any `else` block is executed.\nAn `if` expression evaluates to the same value as the executed block, or `()` if no block is evaluated.\nAn `if` expression must have the same type in all situations.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "If expressions", "heading_path": ["`if` expressions"], "path": "expressions/if-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/if-expr.html#if-expressions", "has_code": true, "code_tags": ["grammar,expressions"]}} {"id": "reference/expressions/if-expr.md#if-expressions-1", "text": "The Rust Reference › `if` expressions\n\n```rust\nif x == 4 {\n println!(\"x is four\");\n} else if x == 3 {\n println!(\"x is three\");\n} else {\n println!(\"x is something else\");\n}\n\n// `if` can be used as an expression.\nlet y = if 12 * 15 > 150 {\n \"Bigger\"\n} else {\n \"Smaller\"\n};\nassert_eq!(y, \"Bigger\");\n```\nAn `if` expression [diverges] if either the condition expression diverges or if all arms diverge.\n```rust,no_run\nfn diverging_condition() -> ! {\n // Diverges because the condition expression diverges\n if loop {} {\n ()\n } else {\n ()\n };\n // The semicolon above is important: The type of the `if` expression is\n // `()`, despite being diverging. When the final body expression is\n // elided, the type of the body is inferred to ! because the function body\n // diverges. Without the semicolon, the `if` would be the tail expression\n // with type `()`, which would fail to match the return type `!`.\n}\n\nfn diverging_arms() -> ! {\n // Diverges because all arms diverge\n if true {\n loop {}\n } else {\n loop {}\n }\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "If expressions", "heading_path": ["`if` expressions"], "path": "expressions/if-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/if-expr.html#if-expressions", "has_code": true, "code_tags": ["rust", "rust,no_run"]}} {"id": "reference/expressions/if-expr.md#if-let-patterns-2", "text": "The Rust Reference › `if` expressions › `if let` patterns\n\n`let` patterns in an `if` condition allow binding new variables into scope when the pattern matches successfully.\nThe following examples illustrate bindings using `let` patterns:\n```rust\nlet dish = (\"Ham\", \"Eggs\");\n\n// This body will be skipped because the pattern is refuted.\nif let (\"Bacon\", b) = dish {\n println!(\"Bacon is served with {}\", b);\n} else {\n // This block is evaluated instead.\n println!(\"No bacon will be served\");\n}\n\n// This body will execute.\nif let (\"Ham\", b) = dish {\n println!(\"Ham is served with {}\", b);\n}\n\nif let _ = 5 {\n println!(\"Irrefutable patterns are always true\");\n}\n```\nMultiple patterns may be specified with the `|` operator. This has the same semantics as with `|` in [`match` expressions]:\n```rust\nenum E {\n X(u8),\n Y(u8),\n Z(u8),\n}\nlet v = E::Y(12);\nif let E::X(n) | E::Y(n) = v {\n assert_eq!(n, 12);\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "If expressions", "heading_path": ["`if` expressions", "`if let` patterns"], "path": "expressions/if-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/if-expr.html#if-let-patterns", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/if-expr.md#chains-of-conditions-3", "text": "The Rust Reference › `if` expressions › Chains of conditions\n\nMultiple condition operands can be separated with `&&`.\nSimilar to a `&&` [LazyBooleanExpression], each operand is evaluated from left-to-right until an operand evaluates as `false` or a `let` match fails, in which case the subsequent operands are not evaluated.\nThe bindings of each pattern are put into scope to be available for the next condition operand and the consequent block.\nThe following is an example of chaining multiple expressions, mixing `let` bindings and boolean expressions, and with expressions able to reference pattern bindings from previous expressions:\n```rust\nfn single() {\n let outer_opt = Some(Some(1i32));\n\n if let Some(inner_opt) = outer_opt\n && let Some(number) = inner_opt\n && number == 1\n {\n println!(\"Peek a boo\");\n }\n}\n```\nThe above is equivalent to the following without using chains of conditions:\n```rust\nfn nested() {\n let outer_opt = Some(Some(1i32));\n\n if let Some(inner_opt) = outer_opt {\n if let Some(number) = inner_opt {\n if number == 1 {\n println!(\"Peek a boo\");\n }\n }\n }\n}\n```\nIf any condition operand is a `let` pattern, then none of the condition operands can be a `||` lazy boolean operator expression due to ambiguity and precedence with the `let` scrutinee.\nIf a `||` expression is needed, then parentheses can be used. For example:\n```rust\nif let Some(x) = foo\n // Parentheses are required here.\n && (condition1 || condition2)\n{}\n```\n[!EDITION-2024]\nBefore the 2024 edition, let chains are not supported. That is, the [LetChain] grammar is not allowed in an `if` expression.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "If expressions", "heading_path": ["`if` expressions", "Chains of conditions"], "path": "expressions/if-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/if-expr.html#chains-of-conditions", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/match-expr.md#match-expressions-0", "text": "The Rust Reference › `match` expressions\n\n```grammar,expressions\nMatchExpression ->\n `match` Scrutinee `{`\n InnerAttribute*\n MatchArms?\n `}`\n\nScrutinee -> Expression _except [StructExpression]_\n\nMatchArms ->\n ( MatchArm `=>` ( ExpressionWithoutBlock `,` | ExpressionWithBlock `,`? ) )*\n MatchArm `=>` Expression `,`?\n\nMatchArm -> OuterAttribute* Pattern MatchArmGuard?\n\nMatchArmGuard -> `if` MatchConditions\n\nMatchConditions ->\n MatchGuardChain\n | Expression\n\nMatchGuardChain -> MatchGuardCondition ( `&&` MatchGuardCondition )*\n\nMatchGuardCondition ->\n Expression _except [ExcludedMatchConditions]_\n | OuterAttribute* `let` Pattern `=` MatchGuardScrutinee\n\nMatchGuardScrutinee -> Expression _except [ExcludedMatchConditions]_\n\n@root ExcludedMatchConditions ->\n LazyBooleanExpression\n | RangeExpr\n | RangeFromExpr\n | RangeInclusiveExpr\n | AssignmentExpression\n | CompoundAssignmentExpression\n```\nA *`match` expression* branches on a pattern. The exact form of matching that occurs depends on the [pattern].\nA `match` expression has a *[scrutinee] expression*, which is the value to compare to the patterns.\nThe scrutinee expression and the patterns must have the same type.\nA `match` behaves differently depending on whether or not the scrutinee expression is a place expression or value expression.\nIf the scrutinee expression is a [value expression], 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Match expressions", "heading_path": ["`match` expressions"], "path": "expressions/match-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/match-expr.html#match-expressions", "has_code": true, "code_tags": ["grammar,expressions"]}} {"id": "reference/expressions/match-expr.md#match-expressions-1", "text": "The Rust Reference › `match` expressions\n\nWhen the scrutinee expression is a [place expression], 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.\nAn example of a `match` expression:\n```rust\nlet x = 1;\n\nmatch x {\n 1 => println!(\"one\"),\n 2 => println!(\"two\"),\n 3 => println!(\"three\"),\n 4 => println!(\"four\"),\n 5 => println!(\"five\"),\n _ => println!(\"something else\"),\n}\n```\nVariables bound within the pattern are scoped to the match guard and the arm's expression.\nThe [binding mode] (move, copy, or reference) depends on the pattern.\nMultiple match patterns may be joined with the `|` operator. Each pattern will be tested in left-to-right sequence until a successful match is found.\n```rust\nlet x = 9;\nlet message = match x {\n 0 | 1 => \"not many\",\n 2 ..= 9 => \"a few\",\n _ => \"lots\"\n};\n\nassert_eq!(message, \"a few\");\n\n// Demonstration of pattern match order.\nstruct S(i32, i32);\n\nmatch S(1, 2) {\n S(z @ 1, _) | S(_, z @ 2) => assert_eq!(z, 1),\n _ => panic!(),\n}\n```\nThe `2..=9` is a [Range Pattern], not a [Range Expression]. Thus, only those types of ranges supported by range patterns can be used in match arms.\nEvery binding in each `|` separated pattern must appear in all of the patterns in the arm.\nEvery binding of the same name must have the same type, and have the same binding mode.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Match expressions", "heading_path": ["`match` expressions"], "path": "expressions/match-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/match-expr.html#match-expressions", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/match-expr.md#match-expressions-2", "text": "The Rust Reference › `match` expressions\n\nThe type of the overall `match` expression is the [least upper bound] of the individual match arms.\nIf there are no match arms, then the `match` expression is [diverging] and the type is [`!`].\n```rust\nenum Empty {}\n\nfn diverging_match_no_arms() -> ! {\n let e: Empty = make();\n match e {}\n}\n```\nIf either the scrutinee expression or all of the match arms diverge, then the entire `match` expression also diverges.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Match expressions", "heading_path": ["`match` expressions"], "path": "expressions/match-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/match-expr.html#match-expressions", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/match-expr.md#match-guards-3", "text": "The Rust Reference › `match` expressions › Match guards\n\nMatch arms can accept _match guards_ to further refine the criteria for matching a case.\nPattern guards appear after the pattern following the `if` keyword and consist of an [Expression] with a boolean type or a conditional `let` match.\nWhen the pattern matches successfully, the pattern guard is executed. If all of the guard condition operands evaluate to `true` and all of the `let` patterns successfully match their [scrutinee]s, the match arm is successfully matched against and the arm body is executed.\nOtherwise, the next pattern, including other matches with the `|` operator in the same arm, is tested.\n```rust\nlet message = match maybe_digit {\n Some(x) if x < 10 => process_digit(x),\n Some(x) => process_other(x),\n None => panic!(),\n};\n```\nMultiple matches using the `|` operator can cause the pattern guard and the side effects it has to execute multiple times. For example:\n```rust\nlet i : Cell = Cell::new(0);\nmatch 1 {\n 1 | _ if { i.set(i.get() + 1); false } => {}\n _ => {}\n}\nassert_eq!(i.get(), 2);\n```\nA pattern guard may refer to the variables bound within the pattern they follow.\nBefore 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.\nOnly when the guard evaluates successfully 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.\nMoreover, by holding a shared reference while evaluating the guard, mutation inside guards is also prevented.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Match expressions", "heading_path": ["`match` expressions", "Match guards"], "path": "expressions/match-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/match-expr.html#match-guards", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/match-expr.md#match-guards-4", "text": "The Rust Reference › `match` expressions › Match guards\n\nGuards can use `let` patterns to conditionally match a scrutinee and to bind new variables into scope when the pattern matches successfully.\nIn this example, the guard condition `let Some(first_char) = name.chars().next()` is evaluated. If the `let` pattern successfully matches (i.e. the string has at least one character), the arm's body is executed. Otherwise, pattern matching continues to the next arm.\nThe `let` pattern creates a new binding (`first_char`), which can be used alongside the original pattern bindings (`name`) in the arm's body.\n```rust\nlet cmd = Command::Run(\"example\".to_string());\n\nmatch cmd {\n Command::Run(name) if let Some(first_char) = name.chars().next() => {\n // Both `name` and `first_char` are available here\n println!(\"Running: {name} (starts with '{first_char}')\");\n }\n Command::Run(name) => {\n println!(\"{name} is empty\");\n }\n _ => {}\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Match expressions", "heading_path": ["`match` expressions", "Match guards"], "path": "expressions/match-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/match-expr.html#match-guards", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/match-expr.md#match-guard-chains-5", "text": "The Rust Reference › `match` expressions › Match guard chains\n\nMultiple guard condition operands can be separated with `&&`.\n```rust\nmatch foo {\n Some(xs) if let [single] = xs && !already_checked => { dbg!(single); }\n _ => {}\n}\n```\nSimilar to a `&&` [LazyBooleanExpression], each operand is evaluated from left-to-right until an operand evaluates as `false` or a `let` match fails, in which case the subsequent operands are not evaluated.\nThe bindings of each `let` pattern are put into scope to be available for the next condition operand and the match arm body.\nIf any guard condition operand is a `let` pattern, then none of the condition operands can be a `||` lazy boolean operator expression due to ambiguity and precedence with the `let` scrutinee.\nIf a `||` expression is needed, then parentheses can be used. For example:\n```rust\nmatch foo {\n Some(xs) if let [x] = xs\n // Parentheses are required here.\n && (x < -100 || x > 20) => {}\n _ => {}\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Match expressions", "heading_path": ["`match` expressions", "Match guard chains"], "path": "expressions/match-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/match-expr.html#match-guard-chains", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/expressions/match-expr.md#attributes-on-match-arms-6", "text": "The Rust Reference › `match` expressions › Attributes on match arms\n\nOuter attributes are allowed on match arms. The only attributes that have meaning on match arms are [`cfg`] and the [lint check attributes].\n[Inner attributes] are allowed directly after the opening brace of the match expression in the same expression contexts as [attributes on block expressions].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Match expressions", "heading_path": ["`match` expressions", "Attributes on match arms"], "path": "expressions/match-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/match-expr.html#attributes-on-match-arms", "has_code": false, "code_tags": []}} {"id": "reference/expressions/return-expr.md#return-expressions-0", "text": "The Rust Reference › `return` expressions\n\n```grammar,expressions\nReturnExpression -> `return` Expression?\n```\nReturn expressions are denoted with the keyword `return`.\nEvaluating 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.\nA `return` expression is [diverging] and has a type of [`!`].\nAn example of a `return` expression:\n```rust\nfn max(a: i32, b: i32) -> i32 {\n if a > b {\n return a;\n }\n return b;\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Return expressions", "heading_path": ["`return` expressions"], "path": "expressions/return-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/return-expr.html#return-expressions", "has_code": true, "code_tags": ["grammar,expressions", "rust"]}} {"id": "reference/expressions/await-expr.md#await-expressions-0", "text": "The Rust Reference › Await expressions\n\n```grammar,expressions\nAwaitExpression -> Expression `.` `await`\n```\nAn `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.\nThe syntax for an await expression is an expression with a type that implements the [`IntoFuture`] trait, called the *future operand*, then the token `.`, and then the `await` keyword.\nAwait expressions are legal only within an [async context], like an [`async fn`], [`async` closure], or [`async` block].\nMore specifically, an await expression has the following effect.\n1. Create a future by calling [`IntoFuture::into_future`] on the future operand.\n2. Evaluate the future to a [future] `tmp`;\n3. Pin `tmp` using [`Pin::new_unchecked`];\n4. This pinned future is then polled by calling the [`Future::poll`] method and passing it the current task context;\n5. If the call to `poll` returns [`Poll::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;\n6. Otherwise the call to `poll` must have returned [`Poll::Ready`], in which case the value contained in the [`Poll::Ready`] variant is used as the result of the `await` expression itself.\n[!EDITION-2018]\nAwait expressions are only available beginning with Rust 2018.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Await expressions", "heading_path": ["Await expressions"], "path": "expressions/await-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/await-expr.html#await-expressions", "has_code": true, "code_tags": ["grammar,expressions"]}} {"id": "reference/expressions/await-expr.md#task-context-1", "text": "The Rust Reference › Await expressions › Task context\n\nThe task context refers to the [`Context`] which was supplied to the current [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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Await expressions", "heading_path": ["Await expressions", "Task context"], "path": "expressions/await-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/await-expr.html#task-context", "has_code": false, "code_tags": []}} {"id": "reference/expressions/await-expr.md#approximate-desugaring-2", "text": "The Rust Reference › Await expressions › Approximate desugaring\n\nEffectively, an await expression is roughly equivalent to the following non-normative desugaring:\n```rust,ignore\nmatch operand.into_future() {\n mut pinned => loop {\n let mut pin = unsafe { Pin::new_unchecked(&mut pinned) };\n match Pin::future::poll(Pin::borrow(&mut pin), &mut current_context) {\n Poll::Ready(r) => break r,\n Poll::Pending => yield Poll::Pending,\n }\n }\n}\n```\nwhere 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Await expressions", "heading_path": ["Await expressions", "Approximate desugaring"], "path": "expressions/await-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/await-expr.html#approximate-desugaring", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "reference/expressions/underscore-expr.md#_-expressions-0", "text": "The Rust Reference › `_` expressions\n\n```grammar,expressions\nUnderscoreExpression -> `_`\n```\nUnderscore expressions, denoted with the symbol `_`, are used to signify a placeholder in a destructuring assignment.\nThey may only appear in the left-hand side of an assignment.\nNote that this is distinct from the wildcard pattern.\nExamples of `_` expressions:\n```rust\nlet p = (1, 2);\nlet mut a = 0;\n(_, a) = p;\n\nstruct Position {\n x: u32,\n y: u32,\n}\n\nPosition { x: a, y: _ } = Position{ x: 2, y: 3 };\n\n// unused result, assignment to `_` used to declare intent and remove a warning\n_ = 2 + 2;\n// triggers unused_must_use warning\n// 2 + 2;\n\n// equivalent technique using a wildcard pattern in a let-binding\nlet _ = 2 + 2;\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Underscore expressions", "heading_path": ["`_` expressions"], "path": "expressions/underscore-expr.md", "url": "https://doc.rust-lang.org/reference/expressions/underscore-expr.html#_-expressions", "has_code": true, "code_tags": ["grammar,expressions", "rust"]}} {"id": "reference/patterns.md#patterns-0", "text": "The Rust Reference › Patterns\n\n```grammar,patterns\nPattern -> `|`? PatternNoTopAlt ( `|` PatternNoTopAlt )*\n\nPatternNoTopAlt ->\n PatternWithoutModernRange\n | ModernRangePattern\n\nPatternWithoutModernRange ->\n LiteralPattern\n | IdentifierPattern\n | WildcardPattern\n | RestPattern\n | ReferencePattern\n | StructPattern\n | TupleStructPattern\n | TuplePattern\n | GroupedPattern\n | SlicePattern\n | PathPattern\n | MacroInvocation\n | ObsoleteRangePattern[^obsolete-range-edition]\n```\n[^obsolete-range-edition]: The [ObsoleteRangePattern] syntax is semantically invalid in the 2021 edition and beyond.\nPatterns 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.\nThe pattern in the following example does four things:\n* Tests if `person` has the `car` field filled with something.\n* Tests if the person's `age` field is between 13 and 19, and binds its value to the `person_age` variable.\n* Binds a reference to the `name` field to the variable `person_name`.\n* Ignores the rest of the fields of `person`. The remaining fields can have any value and are not bound to any variables.\n```rust\nif let\n Person {\n car: Some(_),\n age: person_age @ 13..=19,\n name: ref person_name,\n ..\n } = person\n{\n println!(\"{} has a car and is {} years old.\", person_name, person_age);\n}\n```\nPatterns are used in:\n* `let` declarations\n* Function and closure parameters\n* `match` expressions", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#patterns", "has_code": true, "code_tags": ["grammar,patterns", "rust"]}} {"id": "reference/patterns.md#patterns-1", "text": "The Rust Reference › Patterns\n\n* `if let` expressions\n* `while let` expressions\n* `for` expressions", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#patterns", "has_code": false, "code_tags": []}} {"id": "reference/patterns.md#destructuring-2", "text": "The Rust Reference › Patterns › Destructuring\n\nPatterns can be used to *destructure* [structs], [enums], and [tuples]. Destructuring breaks up a value into its component pieces. The syntax used is almost the same as when creating such values.\nIn a pattern whose [scrutinee] expression has a `struct`, `enum` or `tuple` type, a wildcard pattern (`_`) stands in for a *single* data field, whereas an et cetera or rest pattern (`..`) stands in for *all* the remaining fields of a particular variant.\nWhen destructuring a data structure with named (but not numbered) fields, it is allowed to write `fieldname` as a shorthand for `fieldname: fieldname`.\n```rust\nmatch message {\n Message::Quit => println!(\"Quit\"),\n Message::WriteString(write) => println!(\"{}\", &write),\n Message::Move{ x, y: 0 } => println!(\"move {} horizontally\", x),\n Message::Move{ .. } => println!(\"other move\"),\n Message::ChangeColor { 0: red, 1: green, 2: _ } => {\n println!(\"color change, red: {}, green: {}\", red, green);\n }\n};\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns", "Destructuring"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#destructuring", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/patterns.md#refutability-3", "text": "The Rust Reference › Patterns › Refutability\n\nA 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:\n```rust\nlet (x, y) = (1, 2); // \"(x, y)\" is an irrefutable pattern\n\nif let (a, 3) = (1, 2) { // \"(a, 3)\" is refutable, and will not match\n panic!(\"Shouldn't reach here\");\n} else if let (a, 4) = (3, 4) { // \"(a, 4)\" is refutable, and will match\n println!(\"Matched ({}, 4)\", a);\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns", "Refutability"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#refutability", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/patterns.md#literal-patterns-4", "text": "The Rust Reference › Patterns › Literal patterns\n\n```grammar,patterns\nLiteralPattern -> `-`? LiteralExpression\n```\n_Literal patterns_ match exactly the same value as what is created by the literal. Since negative numbers are not [literals], literals in patterns may be prefixed by an optional minus sign, which acts like the negation operator.\nC string and raw C string literals are accepted in literal patterns, but `&CStr` doesn't implement structural equality (`#[derive(Eq, PartialEq)]`) and therefore any such `match` on a `&CStr` will be rejected with a type error.\nLiteral patterns are always refutable.\nExamples:\n```rust\nfor i in -2..5 {\n match i {\n -1 => println!(\"It's minus one\"),\n 1 => println!(\"It's a one\"),\n 2|4 => println!(\"It's either a two or a four\"),\n _ => println!(\"Matched none of the arms\"),\n }\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns", "Literal patterns"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#literal-patterns", "has_code": true, "code_tags": ["grammar,patterns", "rust"]}} {"id": "reference/patterns.md#identifier-patterns-5", "text": "The Rust Reference › Patterns › Identifier patterns\n\n```grammar,patterns\nIdentifierPattern -> `ref`? `mut`? IDENTIFIER ( `@` PatternNoTopAlt )?\n```\nIdentifier patterns bind the value they match to a variable in the [value namespace].\nThe identifier must be unique within the pattern.\nThe 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).\nPatterns 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.\n```rust\nlet mut variable = 10;\nfn sum(x: i32, y: i32) -> i32 {\n```\nTo 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).\n```rust\nlet x = 2;\n\nmatch x {\n e @ 1 ..= 5 => println!(\"got a range element {}\", e),\n _ => println!(\"anything\"),\n}\n```\nBy default, identifier patterns bind a variable to a copy of or move from the matched value depending on whether the matched value implements [`Copy`].\nThis can be changed to bind to a reference by using the `ref` keyword, or to a mutable reference using `ref mut`. For example:\n```rust\nmatch a {\n None => (),\n Some(value) => (),\n}\n\nmatch a {\n None => (),\n Some(ref value) => (),\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns", "Identifier patterns"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#identifier-patterns", "has_code": true, "code_tags": ["grammar,patterns", "rust"]}} {"id": "reference/patterns.md#identifier-patterns-6", "text": "The Rust Reference › Patterns › Identifier patterns\n\nIn 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:\n```rust,compile_fail\nif let Person { name: &person_name, age: 18..=150 } = value { }\n```\nTo make it valid, write the following:\n```rust\nif let Person { name: ref person_name, age: 18..=150 } = value { }\n```\nThus, `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.\nPath patterns take precedence over identifier patterns.\nWhen a pattern is a single-segment identifier, the grammar is ambiguous whether it means an [IdentifierPattern] or a [PathPattern]. This ambiguity can only be resolved after [name resolution].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns", "Identifier patterns"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#identifier-patterns", "has_code": true, "code_tags": ["rust", "rust,compile_fail"]}} {"id": "reference/patterns.md#identifier-patterns-7", "text": "The Rust Reference › Patterns › Identifier patterns\n\n```rust\nconst EXPECTED_VALUE: u8 = 42;\n// ^^^^^^^^^^^^^^ That this constant is in scope affects how the\n// patterns below are treated.\n\nfn check_value(x: u8) -> Result {\n match x {\n EXPECTED_VALUE => Ok(x),\n // ^^^^^^^^^^^^^^ Parsed as a `PathPattern` that resolves to\n // the constant `42`.\n other_value => Err(x),\n // ^^^^^^^^^^^ Parsed as an `IdentifierPattern`.\n }\n}\n\n// If `EXPECTED_VALUE` were treated as an `IdentifierPattern` above,\n// that pattern would always match, making the function always return\n// `Ok(_) regardless of the input.\nassert_eq!(check_value(42), Ok(42));\nassert_eq!(check_value(43), Err(43));\n```\nIt is an error if `ref` or `ref mut` is specified and the identifier shadows a constant.\nIdentifier patterns are irrefutable if the `@` subpattern is irrefutable or the subpattern is not specified.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns", "Identifier patterns"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#identifier-patterns", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/patterns.md#binding-modes-8", "text": "The Rust Reference › Patterns › Identifier patterns › Binding modes\n\nTo 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:\n```rust\nlet x: &Option = &Some(3);\nif let Some(y) = x {\n // y was converted to `ref y` and its type is &i32\n}\n```\n*Non-reference patterns* include all patterns except bindings, wildcard patterns (`_`), `const` patterns of reference types, and reference patterns.\nIf 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.\nThe default binding mode starts in \"move\" mode which uses move semantics.\nWhen matching a pattern, the compiler starts from the outside of the pattern and works inwards.\nEach time a reference is matched using a non-reference pattern, it will automatically dereference the value and update the default binding mode.\nReferences will set the default binding mode to `ref`.\nMutable references will set the mode to `ref mut` unless the mode is already `ref` in which case it remains `ref`.\nIf the automatically dereferenced value is still a reference, it is dereferenced and this process repeats.\nThe binding pattern may only explicitly specify a `ref` or `ref mut` binding mode, or specify mutability with `mut`, when the default binding mode is \"move\". For example, these are not accepted:\n```rust,edition2024,compile_fail\nlet [mut x] = &[()]; //~ ERROR\nlet [ref x] = &[()]; //~ ERROR\nlet [ref mut x] = &mut [()]; //~ ERROR\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns", "Identifier patterns", "Binding modes"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#binding-modes", "has_code": true, "code_tags": ["rust", "rust,edition2024,compile_fail"]}} {"id": "reference/patterns.md#binding-modes-9", "text": "The Rust Reference › Patterns › Identifier patterns › Binding modes\n\n[!EDITION-2024]\nBefore the 2024 edition, bindings could explicitly specify a `ref` or `ref mut` binding mode even when the default binding mode was not \"move\", and they could specify mutability on such bindings with `mut`. In these editions, specifying `mut` on a binding set the binding mode to \"move\" regardless of the current default binding mode.\nSimilarly, a reference pattern may only appear when the default binding mode is \"move\". For example, this is not accepted:\n```rust,edition2024,compile_fail\nlet [&x] = &[&()]; //~ ERROR\n```\n[!EDITION-2024]\nBefore the 2024 edition, reference patterns could appear even when the default binding mode was not \"move\", and had both the effect of matching against the scrutinee and of causing the default binding mode to be reset to \"move\".\nMove 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.\nIn 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*.\nExample:\n```rust\n// `name` is moved from person and `age` referenced\nlet Person { name, ref age } = person;\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns", "Identifier patterns", "Binding modes"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#binding-modes", "has_code": true, "code_tags": ["rust", "rust,edition2024,compile_fail"]}} {"id": "reference/patterns.md#wildcard-pattern-10", "text": "The Rust Reference › Patterns › Wildcard pattern\n\n```grammar,patterns\nWildcardPattern -> `_`\n```\nThe _wildcard pattern_ (an underscore symbol) matches any value. It is used to ignore values when they don't matter.\nInside other patterns, it matches a single data field (as opposed to the `..`, which matches the remaining fields).\nUnlike identifier patterns, it does not copy, move, or borrow the value it matches.\nExamples:\n```rust\nlet (a, _) = (10, x); // the x is always matched by _\n\n// ignore a function/closure param\nlet real_part = |a: f64, _: f64| { a };\n\n// ignore a field from a struct\nlet RGBA{r: red, g: green, b: blue, a: _} = color;\n\n// accept any Some, with any value\nif let Some(_) = x {}\n```\nThe wildcard pattern is always irrefutable.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns", "Wildcard pattern"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#wildcard-pattern", "has_code": true, "code_tags": ["grammar,patterns", "rust"]}} {"id": "reference/patterns.md#rest-pattern-11", "text": "The Rust Reference › Patterns › Rest pattern\n\n```grammar,patterns\nRestPattern -> `..`\n```\nThe _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.\nIt may only be used in tuple, tuple struct, and slice patterns, and may only appear once as one of the elements in those patterns. It is also allowed in an identifier pattern for slice patterns only.\nThe rest pattern is always irrefutable.\nExamples:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns", "Rest pattern"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#rest-pattern", "has_code": true, "code_tags": ["grammar,patterns"]}} {"id": "reference/patterns.md#rest-pattern-12", "text": "The Rust Reference › Patterns › Rest pattern\n\n```rust\nmatch slice {\n [] => println!(\"slice is empty\"),\n [one] => println!(\"single element {}\", one),\n [head, tail @ ..] => println!(\"head={} tail={:?}\", head, tail),\n}\n\nmatch slice {\n // Ignore everything but the last element, which must be \"!\".\n [.., \"!\"] => println!(\"!!!\"),\n\n // `start` is a slice of everything except the last element, which must be \"z\".\n [start @ .., \"z\"] => println!(\"starts with: {:?}\", start),\n\n // `end` is a slice of everything but the first element, which must be \"a\".\n [\"a\", end @ ..] => println!(\"ends with: {:?}\", end),\n\n // 'whole' is the entire slice and `last` is the final element\n whole @ [.., last] => println!(\"the last element of {:?} is {}\", whole, last),\n\n rest => println!(\"{:?}\", rest),\n}\n\nif let [.., penultimate, _] = slice {\n println!(\"next to last is {}\", penultimate);\n}\n\n// The rest pattern may also be used in tuple and tuple\n// struct patterns.\nmatch tuple {\n (1, .., y, z) => println!(\"y={} z={}\", y, z),\n (.., 5) => println!(\"tail must be 5\"),\n (..) => println!(\"matches everything else\"),\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns", "Rest pattern"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#rest-pattern", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/patterns.md#range-patterns-13", "text": "The Rust Reference › Patterns › Range patterns\n\n```grammar,patterns\nModernRangePattern ->\n RangeExclusivePattern\n | RangeInclusivePattern\n | RangeFromPattern\n | RangeToExclusivePattern\n | RangeToInclusivePattern\n\nRangeExclusivePattern ->\n RangePatternBound `..` RangePatternBound\n\nRangeInclusivePattern ->\n RangePatternBound `..=` RangePatternBound\n\nRangeFromPattern ->\n RangePatternBound `..`\n\nRangeToExclusivePattern ->\n `..` RangePatternBound\n\nRangeToInclusivePattern ->\n `..=` RangePatternBound\n\nObsoleteRangePattern ->\n RangePatternBound `...` RangePatternBound\n\nRangePatternBound ->\n LiteralPattern\n | PathExpression\n```\n*Range patterns* match scalar values within the range defined by their bounds. They comprise a *sigil* (`..` or `..=`) and a bound on one or both sides.\nA bound on the left of the sigil is called a *lower bound*. A bound on the right is called an *upper bound*.\nThe *exclusive range pattern* matches all values from the lower bound up to, but not including the upper bound. It is written as its lower bound, followed by `..`, followed by the upper bound.\nFor example, a pattern `'m'..'p'` will match only `'m'`, `'n'` and `'o'`, specifically **not** including `'p'`.\nThe *inclusive range pattern* matches all values from the lower bound up to and including the upper bound. It is written as its lower bound, followed by `..=`, followed by the upper bound.\nFor example, a pattern `'m'..='p'` will match only the values `'m'`, `'n'`, `'o'`, and `'p'`.\nThe *from range pattern* matches all values greater than or equal to the lower bound. It is written as its lower bound followed by `..`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns", "Range patterns"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#range-patterns", "has_code": true, "code_tags": ["grammar,patterns"]}} {"id": "reference/patterns.md#range-patterns-14", "text": "The Rust Reference › Patterns › Range patterns\n\nFor example, `1..` will match any integer greater than or equal to 1, such as 1, 9, or 9001, or 9007199254740991 (if it is of an appropriate size), but not 0, and not negative numbers for signed integers.\nThe *to exclusive range pattern* matches all values less than the upper bound. It is written as `..` followed by the upper bound.\nFor example, `..10` will match any integer less than 10, such as 9, 1, 0, and for signed integer types, all negative values.\nThe *to inclusive range pattern* matches all values less than or equal to the upper bound. It is written as `..=` followed by the upper bound.\nFor example, `..=10` will match any integer less than or equal to 10, such as 10, 1, 0, and for signed integer types, all negative values.\nA range pattern must be nonempty; it must span at least one value in the set of possible values for its type. In other words:\n* In `a..=b`, a ≤ b must be the case. For example, it is an error to have a range pattern `10..=0`, but `10..=10` is allowed.\n* In `a..b`, a < b must be the case. For example, it is an error to have a range pattern `10..0` or `10..10`.\n* In `..b`, b must not be the smallest value of its type. For example, it is an error to have a range pattern `..-128i8` or `..f64::NEG_INFINITY`.\nA bound is written as one of:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns", "Range patterns"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#range-patterns", "has_code": false, "code_tags": []}} {"id": "reference/patterns.md#range-patterns-15", "text": "The Rust Reference › Patterns › Range patterns\n\n* A character, byte, integer, or float literal.\n* A `-` followed by an integer or float literal.\n* A [path].\nWe syntactically accept more than this for a *[RangePatternBound]*. We later reject the other things semantically.\nIf a bound 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.\nThe range pattern matches the type of its upper and lower bounds, which must be the same type.\nIf a bound is a [path], the bound matches the type and has the value of the [constant] the path resolves to.\nIf a bound is a literal, the bound matches the type and has the value of the corresponding [literal expression].\nIf a bound is a literal preceded by a `-`, the bound matches the same type as the corresponding [literal expression] and has the value of [negating] the value of the corresponding literal expression.\nFor float range patterns, the constant may not be a `NaN`.\nExamples:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns", "Range patterns"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#range-patterns", "has_code": false, "code_tags": []}} {"id": "reference/patterns.md#range-patterns-16", "text": "The Rust Reference › Patterns › Range patterns\n\n```rust\nlet valid_variable = match c {\n 'a'..='z' => true,\n 'A'..='Z' => true,\n 'α'..='ω' => true,\n _ => false,\n};\n\nprintln!(\"{}\", match ph {\n 0..7 => \"acid\",\n 7 => \"neutral\",\n 8..=14 => \"base\",\n _ => unreachable!(),\n});\n\nmatch uint {\n 0 => \"zero!\",\n 1.. => \"positive number!\",\n};\n\n// using paths to constants:\nprintln!(\"{}\", match altitude {\n TROPOSPHERE_MIN..=TROPOSPHERE_MAX => \"troposphere\",\n STRATOSPHERE_MIN..=STRATOSPHERE_MAX => \"stratosphere\",\n MESOSPHERE_MIN..=MESOSPHERE_MAX => \"mesosphere\",\n _ => \"outer space, maybe\",\n});\n\nif let size @ binary::MEGA..=binary::GIGA = n_items * bytes_per_item {\n println!(\"It fits and occupies {} bytes\", size);\n}\n\n// using qualified paths:\nprintln!(\"{}\", match 0xfacade {\n 0 ..= ::MAX => \"fits in a u8\",\n 0 ..= ::MAX => \"fits in a u16\",\n 0 ..= ::MAX => \"fits in a u32\",\n _ => \"too big\",\n});\n```\nRange 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.\nThe range of values for an integer type is the closed range from its minimum to maximum value.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns", "Range patterns"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#range-patterns", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/patterns.md#range-patterns-17", "text": "The Rust Reference › Patterns › Range patterns\n\nThe 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}'`.\n[RangeFromPattern] cannot be used as a top-level pattern for subpatterns in slice patterns. For example, the pattern `[1.., _]` is not a valid pattern.\n[!EDITION-2021]\nBefore the 2021 edition, range patterns with both a lower and upper bound may also be written using `...` in place of `..=`, with the same meaning.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns", "Range patterns"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#range-patterns", "has_code": false, "code_tags": []}} {"id": "reference/patterns.md#reference-patterns-18", "text": "The Rust Reference › Patterns › Reference patterns\n\n```grammar,patterns\nReferencePattern -> (`&`|`&&`) `mut`? PatternWithoutModernRange\n```\nReference patterns dereference the pointers that are being matched and, thus, borrow them.\nFor example, these two matches on `x: &i32` are equivalent:\n```rust\nlet int_reference = &3;\n\nlet a = match *int_reference { 0 => \"zero\", _ => \"some\" };\nlet b = match int_reference { &0 => \"zero\", _ => \"some\" };\n\nassert_eq!(a, b);\n```\nThe 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.\nAdding the `mut` keyword dereferences a mutable reference. The mutability must match the mutability of the reference.\nReference patterns are always irrefutable.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns", "Reference patterns"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#reference-patterns", "has_code": true, "code_tags": ["grammar,patterns", "rust"]}} {"id": "reference/patterns.md#struct-patterns-19", "text": "The Rust Reference › Patterns › Struct patterns\n\n```grammar,patterns\nStructPattern ->\n PathInExpression `{`\n StructPatternElements?\n `}`\n\nStructPatternElements ->\n StructPatternFields (`,` | `,` StructPatternEtCetera)?\n | StructPatternEtCetera\n\nStructPatternFields ->\n StructPatternField (`,` StructPatternField)*\n\nStructPatternField ->\n OuterAttribute*\n (\n TUPLE_INDEX `:` Pattern\n | IDENTIFIER `:` Pattern\n | `ref`? `mut`? IDENTIFIER\n )\n\nStructPatternEtCetera -> `..`\n```\nStruct patterns match struct, enum, and union values that match all criteria defined by its subpatterns. They are also used to destructure a struct, enum, or union value.\nOn a struct pattern, the fields are referenced by name, index (in the case of tuple structs) or ignored by use of `..`:\n```rust\nmatch s {\n Point {x: 10, y: 20} => (),\n Point {y: 10, x: 20} => (), // order doesn't matter\n Point {x: 10, ..} => (),\n Point {..} => (),\n}\n\nmatch t {\n PointTuple {0: 10, 1: 20} => (),\n PointTuple {1: 10, 0: 20} => (), // order doesn't matter\n PointTuple {0: 10, ..} => (),\n PointTuple {..} => (),\n}\n\nmatch m {\n Message::Quit => (),\n Message::Move {x: 10, y: 20} => (),\n Message::Move {..} => (),\n}\n```\nIf `..` is not used, a struct pattern used to match a struct is required to specify all fields:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns", "Struct patterns"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#struct-patterns", "has_code": true, "code_tags": ["grammar,patterns", "rust"]}} {"id": "reference/patterns.md#struct-patterns-20", "text": "The Rust Reference › Patterns › Struct patterns\n\n```rust\nmatch struct_value {\n Struct{a: 10, b: 'X', c: false} => (),\n Struct{a: 10, b: 'X', ref c} => (),\n Struct{a: 10, b: 'X', ref mut c} => (),\n Struct{a: 10, b: 'X', c: _} => (),\n Struct{a: _, b: _, c: _} => (),\n}\n```\nA struct pattern used to match a union must specify exactly one field (see [Pattern matching on unions]).\nThe [IDENTIFIER] syntax matches any value and binds it to a variable with the same name as the given field. It is a shorthand for `fieldname: fieldname`. The `ref` and `mut` qualifiers can be included with the behavior as described in [patterns.ident.ref].\n```rust\nlet Struct { a, b, c } = struct_value;\n```\nA struct pattern is refutable if the [PathInExpression] resolves to a constructor of an enum with more than one variant, or one of its subpatterns is refutable.\nA struct pattern matches against the struct, union, or enum variant whose constructor is resolved from [PathInExpression] in the [type namespace]. See [patterns.tuple-struct.namespace] for more details.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns", "Struct patterns"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#struct-patterns", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/patterns.md#tuple-struct-patterns-21", "text": "The Rust Reference › Patterns › Tuple struct patterns\n\n```grammar,patterns\nTupleStructPattern -> PathInExpression `(` TupleStructItems? `)`\n\nTupleStructItems -> Pattern ( `,` Pattern )* `,`?\n```\nTuple struct patterns match tuple struct and enum values that match all criteria defined by its subpatterns. They are also used to destructure a tuple struct or enum value.\nA tuple struct pattern is refutable if the [PathInExpression] resolves to a constructor of an enum with more than one variant, or one of its subpatterns is refutable.\nA tuple struct pattern matches against the tuple struct or [tuple-like enum variant] whose constructor is resolved from [PathInExpression] in the [value namespace].\nConversely, a struct pattern for a tuple struct or [tuple-like enum variant], e.g. `S { 0: _ }`, matches against the tuple struct or variant whose constructor is resolved in the [type namespace].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns", "Tuple struct patterns"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#tuple-struct-patterns", "has_code": true, "code_tags": ["grammar,patterns"]}} {"id": "reference/patterns.md#tuple-struct-patterns-22", "text": "The Rust Reference › Patterns › Tuple struct patterns\n\n```rust,no_run\nenum E1 { V(u16) }\nenum E2 { V(u32) }\n\n// Import `E1::V` from the type namespace only.\nmod _0 {\n const V: () = (); // For namespace masking.\n pub(super) use super::E1::*;\n}\nuse _0::*;\n\n// Import `E2::V` from the value namespace only.\nmod _1 {\n struct V {} // For namespace masking.\n pub(super) use super::E2::*;\n}\nuse _1::*;\n\nfn f() {\n // This struct pattern matches against the tuple-like\n // enum variant whose constructor was found in the type\n // namespace.\n let V { 0: ..=u16::MAX } = (loop {}) else { loop {} };\n // This tuple struct pattern matches against the tuple-like\n // enum variant whose constructor was found in the value\n // namespace.\n let V(..=u32::MAX) = (loop {}) else { loop {} };\n}\n```\nThe Lang team has made certain decisions, such as in [PR #138458], that raise questions about the desirability of using the value namespace in this way for patterns, as described in [PR #140593]. It might be prudent to not intentionally rely on this nuance in your code.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns", "Tuple struct patterns"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#tuple-struct-patterns", "has_code": true, "code_tags": ["rust,no_run"]}} {"id": "reference/patterns.md#tuple-patterns-23", "text": "The Rust Reference › Patterns › Tuple patterns\n\n```grammar,patterns\nTuplePattern -> `(` TuplePatternItems? `)`\n\nTuplePatternItems ->\n Pattern `,`\n | RestPattern\n | Pattern (`,` Pattern)+ `,`?\n```\nTuple patterns match tuple values that match all criteria defined by its subpatterns. They are also used to destructure a tuple.\nThe form `(..)` with a single [RestPattern] is a special form that does not require a comma, and matches a tuple of any size.\nThe tuple pattern is refutable when one of its subpatterns is refutable.\nAn example of using tuple patterns:\n```rust\nlet pair = (10, \"ten\");\nlet (a, b) = pair;\n\nassert_eq!(a, 10);\nassert_eq!(b, \"ten\");\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns", "Tuple patterns"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#tuple-patterns", "has_code": true, "code_tags": ["grammar,patterns", "rust"]}} {"id": "reference/patterns.md#grouped-patterns-24", "text": "The Rust Reference › Patterns › Grouped patterns\n\n```grammar,patterns\nGroupedPattern -> `(` Pattern `)`\n```\nEnclosing 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.\n```rust\nlet int_reference = &3;\nmatch int_reference {\n &(0..=5) => (),\n _ => (),\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns", "Grouped patterns"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#grouped-patterns", "has_code": true, "code_tags": ["grammar,patterns", "rust"]}} {"id": "reference/patterns.md#slice-patterns-25", "text": "The Rust Reference › Patterns › Slice patterns\n\n```grammar,patterns\nSlicePattern -> `[` SlicePatternItems? `]`\n\nSlicePatternItems -> Pattern (`,` Pattern)* `,`?\n```\nSlice patterns can match both arrays of fixed size and slices of dynamic size.\n```rust\n// Fixed size\nlet arr = [1, 2, 3];\nmatch arr {\n [1, _, _] => \"starts with one\",\n [a, b, c] => \"starts with something else\",\n};\n```\n```rust\n// Dynamic size\nlet v = vec![1, 2, 3];\nmatch v[..] {\n [a, b] => { /* this arm will not apply because the length doesn't match */ }\n [a, b, c] => { /* this arm will apply */ }\n _ => { /* this wildcard is required, since the length is not known statically */ }\n};\n```\nSlice patterns are irrefutable when matching an array as long as each element is irrefutable.\nWhen matching a slice, it is irrefutable only in the form with a single `..` rest pattern or identifier pattern with the `..` rest pattern as a subpattern.\nWithin 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns", "Slice patterns"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#slice-patterns", "has_code": true, "code_tags": ["grammar,patterns", "rust"]}} {"id": "reference/patterns.md#path-patterns-26", "text": "The Rust Reference › Patterns › Path patterns\n\n```grammar,patterns\nPathPattern -> PathExpression\n```\n_Path patterns_ are patterns that refer either to constant values or to structs or enum variants that have no fields.\nUnqualified path patterns can refer to:\n* enum variants\n* structs\n* constants\n* associated constants\nQualified path patterns can only refer to associated constants.\nPath 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns", "Path patterns"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#path-patterns", "has_code": true, "code_tags": ["grammar,patterns"]}} {"id": "reference/patterns.md#constant-patterns-27", "text": "The Rust Reference › Patterns › Path patterns › Constant patterns\n\nWhen a constant `C` of type `T` is used as a pattern, we first check that `T: PartialEq`.\nFurthermore we require that the value of `C` *has (recursive) structural equality*, which is defined recursively as follows:\n- Integers as well as `str`, `bool` and `char` values always have structural equality.\n- Tuples, arrays, and slices have structural equality if all their fields/elements have structural equality. (In particular, `()` and `[]` always have structural equality.)\n- References have structural equality if the value they point to has structural equality.\n- A value of `struct` or `enum` type has structural equality if its `PartialEq` instance is derived via `#[derive(PartialEq)]`, and all fields (for enums: of the active variant) have structural equality.\n- A raw pointer has structural equality if it was defined as a constant integer (and then cast/transmuted).\n- A float value has structural equality if it is not a `NaN`.\n- Nothing else has structural equality.\nIn particular, the value of `C` must be known at pattern-building time (which is pre-monomorphization). This means that associated consts that involve generic parameters cannot be used as patterns.\nThe value of `C` must not contain any references to mutable statics (`static mut` items or interior mutable `static` items) or `extern` statics.\nAfter ensuring all conditions are met, the constant value is translated into a pattern, and now behaves exactly as-if that pattern had been written directly. In particular, it fully participates in exhaustiveness checking. (For raw pointers, constants are the only way to write such patterns. Only `_` is ever considered exhaustive for these types.)", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns", "Path patterns", "Constant patterns"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#constant-patterns", "has_code": false, "code_tags": []}} {"id": "reference/patterns.md#or-patterns-28", "text": "The Rust Reference › Patterns › Or-patterns\n\n_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 parameters (represented by the [PatternNoTopAlt] production).", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns", "Or-patterns"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#or-patterns", "has_code": false, "code_tags": []}} {"id": "reference/patterns.md#static-semantics-29", "text": "The Rust Reference › Patterns › Or-patterns › Static semantics\n\n1. Given a pattern `p | q` at some depth for some arbitrary patterns `p` and `q`, the pattern is considered ill-formed if:\n + the type inferred for `p` does not unify with the type inferred for `q`, or\n + the same set of bindings are not introduced in `p` and `q`, or\n + the type of any two bindings with the same name in `p` and `q` do not unify with respect to types or binding modes.\n Unification of types is in all instances aforementioned exact and implicit [type coercions] do not apply.\n2. 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`.\n3. 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.\n 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns", "Or-patterns", "Static semantics"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#static-semantics", "has_code": false, "code_tags": []}} {"id": "reference/patterns.md#dynamic-semantics-30", "text": "The Rust Reference › Patterns › Or-patterns › Dynamic semantics\n\n1. 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)`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns", "Or-patterns", "Dynamic semantics"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#dynamic-semantics", "has_code": false, "code_tags": []}} {"id": "reference/patterns.md#precedence-with-other-undelimited-patterns-31", "text": "The Rust Reference › Patterns › Or-patterns › Precedence with other undelimited patterns\n\nAs 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Patterns", "heading_path": ["Patterns", "Or-patterns", "Precedence with other undelimited patterns"], "path": "patterns.md", "url": "https://doc.rust-lang.org/reference/patterns.html#precedence-with-other-undelimited-patterns", "has_code": false, "code_tags": []}} {"id": "reference/types.md#types-0", "text": "The Rust Reference › Types\n\nEvery 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.\nBuilt-in types are tightly integrated into the language, in nontrivial ways that are not possible to emulate in user-defined types.\nUser-defined types have limited capabilities.\nThe list of types is:\n* Primitive types:\n * [Boolean] --- `bool`\n * [Numeric] --- integer and float\n * [`char`]\n * [`str`]\n * [Never] --- `!` --- a type with no values\n* Sequence types:\n * [Tuple]\n * [Array]\n * [Slice]\n* User-defined types:\n * [Struct]\n * [Enum]\n * [Union]\n* Function types:\n * [Functions]\n * [Closures]\n* Pointer types:\n * [References]\n * [Raw pointers]\n * [Function pointers]\n* Trait types:\n * [Trait objects]\n * [Impl trait]", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Types", "heading_path": ["Types"], "path": "types.md", "url": "https://doc.rust-lang.org/reference/types.html#types", "has_code": false, "code_tags": []}} {"id": "reference/types.md#type-expressions-1", "text": "The Rust Reference › Types › Type expressions\n\n```grammar,types\nType ->\n TypeNoBounds\n | ImplTraitType\n | TraitObjectType\n\nTypeNoBounds ->\n ParenthesizedType\n | ImplTraitTypeOneBound\n | TraitObjectTypeOneBound\n | TypePath\n | TupleType\n | NeverType\n | RawPointerType\n | ReferenceType\n | ArrayType\n | SliceType\n | InferredType\n | QualifiedPathInType\n | BareFunctionType\n | MacroInvocation\n```\nA _type expression_ as defined in the [Type] grammar rule above is the syntax for referring to a type. It may refer to:\n* Sequence types ([tuple], [array], [slice]).\n* [Type paths] which can reference:\n * Primitive types ([boolean], [numeric], [`char`], [`str`]).\n * Paths to an [item] ([struct], [enum], [union], [type alias], [trait]).\n * [`Self` path] where `Self` is the implementing type.\n * Generic [type parameters].\n* Pointer types ([reference], [raw pointer], [function pointer]).\n* The [inferred type] which asks the compiler to determine the type.\n* [Parentheses] which are used for disambiguation.\n* Trait types: [Trait objects] and [impl trait].\n* The [never] type.\n* [Macros] which expand to a type expression.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Types", "heading_path": ["Types", "Type expressions"], "path": "types.md", "url": "https://doc.rust-lang.org/reference/types.html#type-expressions", "has_code": true, "code_tags": ["grammar,types"]}} {"id": "reference/types.md#parenthesized-types-2", "text": "The Rust Reference › Types › Type expressions › Parenthesized types\n\n```grammar,types\nParenthesizedType -> `(` Type `)`\n```\nIn some situations the combination of types may be ambiguous. Use parentheses around a type to avoid ambiguity. For example, the `+` operator for [type boundaries] within a [reference type] is unclear where the boundary applies, so the use of parentheses is required. Grammar rules that require this disambiguation use the [TypeNoBounds] rule instead of Type.\n```rust\ntype T<'a> = &'a (dyn Any + Send);\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Types", "heading_path": ["Types", "Type expressions", "Parenthesized types"], "path": "types.md", "url": "https://doc.rust-lang.org/reference/types.html#parenthesized-types", "has_code": true, "code_tags": ["grammar,types", "rust"]}} {"id": "reference/types.md#recursive-types-3", "text": "The Rust Reference › Types › Recursive types\n\nNominal types — [structs], [enumerations], and [unions] — 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.\nSuch recursion has restrictions:\n* Recursive types must include a nominal type in the recursion (not mere [type aliases], or other structural types such as [arrays] or [tuples]). So `type Rec = &'static [Rec]` is not allowed.\n* The size of a recursive type must be finite; in other words the recursive fields of the type must be [pointer types].\nAn example of a *recursive* type and its use:\n```rust\nenum List {\n Nil,\n Cons(T, Box>)\n}\n\nlet a: List = List::Cons(7, Box::new(List::Cons(13, Box::new(List::Nil))));\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Types", "heading_path": ["Types", "Recursive types"], "path": "types.md", "url": "https://doc.rust-lang.org/reference/types.html#recursive-types", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/types/boolean.md#boolean-type-0", "text": "The Rust Reference › Boolean type\n\n```rust\nlet b: bool = true;\n```\nThe *boolean type* or *bool* is a primitive data type that can take on one of two values, called *true* and *false*.\nValues of this type may be created using a [literal expression] using the keywords `true` and `false` corresponding to the value of the same name.\nThis type is a part of the [language prelude] with the [name] `bool`.\nAn object with the boolean type has a [size and alignment] of 1 each.\nThe value false has the bit pattern `0x00` and the value true has the bit pattern `0x01`. It is [undefined behavior] for an object with the boolean type to have any other bit pattern.\nThe boolean type is the type of many operands in various [expressions]:\n* The condition operand in [if expressions] and [while expressions]\n* The operands in lazy boolean operator expressions\nThe boolean type acts similarly to but is not an [enumerated type]. In practice, this mostly means that constructors are not associated to the type (e.g. `bool::true`).\nLike all primitives, the boolean type implements the traits `Clone`, `Copy`, `Sized`, `Send`, and `Sync`.\nSee the standard library docs for library operations.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Boolean type", "heading_path": ["Boolean type"], "path": "types/boolean.md", "url": "https://doc.rust-lang.org/reference/types/boolean.html#boolean-type", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/types/boolean.md#operations-on-boolean-values-1", "text": "The Rust Reference › Boolean type › Operations on boolean values\n\nWhen using certain operator expressions with a boolean type for its operands, they evaluate using the rules of [boolean logic].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Boolean type", "heading_path": ["Boolean type", "Operations on boolean values"], "path": "types/boolean.md", "url": "https://doc.rust-lang.org/reference/types/boolean.html#operations-on-boolean-values", "has_code": false, "code_tags": []}} {"id": "reference/types/boolean.md#logical-not-2", "text": "The Rust Reference › Boolean type › Operations on boolean values › Logical not\n\n| `b` | `!b` |\n|- | - |\n| `true` | `false` |\n| `false` | `true` |", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Boolean type", "heading_path": ["Boolean type", "Operations on boolean values", "Logical not"], "path": "types/boolean.md", "url": "https://doc.rust-lang.org/reference/types/boolean.html#logical-not", "has_code": false, "code_tags": []}} {"id": "reference/types/boolean.md#logical-or-3", "text": "The Rust Reference › Boolean type › Operations on boolean values › Logical or\n\n| `a` | `b` | `a \\| b` |\n|- | - | - |\n| `true` | `true` | `true` |\n| `true` | `false` | `true` |\n| `false` | `true` | `true` |\n| `false` | `false` | `false` |", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Boolean type", "heading_path": ["Boolean type", "Operations on boolean values", "Logical or"], "path": "types/boolean.md", "url": "https://doc.rust-lang.org/reference/types/boolean.html#logical-or", "has_code": false, "code_tags": []}} {"id": "reference/types/boolean.md#logical-and-4", "text": "The Rust Reference › Boolean type › Operations on boolean values › Logical and\n\n| `a` | `b` | `a & b` |\n|- | - | - |\n| `true` | `true` | `true` |\n| `true` | `false` | `false` |\n| `false` | `true` | `false` |\n| `false` | `false` | `false` |", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Boolean type", "heading_path": ["Boolean type", "Operations on boolean values", "Logical and"], "path": "types/boolean.md", "url": "https://doc.rust-lang.org/reference/types/boolean.html#logical-and", "has_code": false, "code_tags": []}} {"id": "reference/types/boolean.md#logical-xor-5", "text": "The Rust Reference › Boolean type › Operations on boolean values › Logical xor\n\n| `a` | `b` | `a ^ b` |\n|- | - | - |\n| `true` | `true` | `false` |\n| `true` | `false` | `true` |\n| `false` | `true` | `true` |\n| `false` | `false` | `false` |", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Boolean type", "heading_path": ["Boolean type", "Operations on boolean values", "Logical xor"], "path": "types/boolean.md", "url": "https://doc.rust-lang.org/reference/types/boolean.html#logical-xor", "has_code": false, "code_tags": []}} {"id": "reference/types/boolean.md#comparisons-6", "text": "The Rust Reference › Boolean type › Operations on boolean values › Comparisons\n\n| `a` | `b` | `a == b` |\n|- | - | - |\n| `true` | `true` | `true` |\n| `true` | `false` | `false` |\n| `false` | `true` | `false` |\n| `false` | `false` | `true` |\n| `a` | `b` | `a > b` |\n|- | - | - |\n| `true` | `true` | `false` |\n| `true` | `false` | `true` |\n| `false` | `true` | `false` |\n| `false` | `false` | `false` |\n* `a != b` is the same as `!(a == b)`\n* `a >= b` is the same as `a == b | a > b`\n* `a < b` is the same as `!(a >= b)`\n* `a <= b` is the same as `a == b | a < b`", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Boolean type", "heading_path": ["Boolean type", "Operations on boolean values", "Comparisons"], "path": "types/boolean.md", "url": "https://doc.rust-lang.org/reference/types/boolean.html#comparisons", "has_code": false, "code_tags": []}} {"id": "reference/types/boolean.md#bit-validity-7", "text": "The Rust Reference › Boolean type › Bit validity\n\nThe single byte of a `bool` is guaranteed to be initialized (in other words, `transmute::(...)` is always sound -- but since some bit patterns are invalid `bool`s, the inverse is not always sound).", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Boolean type", "heading_path": ["Boolean type", "Bit validity"], "path": "types/boolean.md", "url": "https://doc.rust-lang.org/reference/types/boolean.html#bit-validity", "has_code": false, "code_tags": []}} {"id": "reference/types/numeric.md#integer-types-0", "text": "The Rust Reference › Numeric types › Integer types\n\nThe unsigned integer types consist of:\nType | Minimum | Maximum\n-------|---------|-------------------\n`u8` | 0 | 28-1\n`u16` | 0 | 216-1\n`u32` | 0 | 232-1\n`u64` | 0 | 264-1\n`u128` | 0 | 2128-1\nThe signed two's complement integer types consist of:\nType | Minimum | Maximum\n-------|--------------------|-------------------\n`i8` | -(27) | 27-1\n`i16` | -(215) | 215-1\n`i32` | -(231) | 231-1\n`i64` | -(263) | 263-1\n`i128` | -(2127) | 2127-1", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Numeric types", "heading_path": ["Numeric types", "Integer types"], "path": "types/numeric.md", "url": "https://doc.rust-lang.org/reference/types/numeric.html#integer-types", "has_code": false, "code_tags": []}} {"id": "reference/types/numeric.md#floating-point-types-1", "text": "The Rust Reference › Numeric types › Floating-point types\n\nThe IEEE 754-2008 \"binary32\" and \"binary64\" floating-point types are `f32` and `f64`, respectively.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Numeric types", "heading_path": ["Numeric types", "Floating-point types"], "path": "types/numeric.md", "url": "https://doc.rust-lang.org/reference/types/numeric.html#floating-point-types", "has_code": false, "code_tags": []}} {"id": "reference/types/numeric.md#machine-dependent-integer-types-2", "text": "The Rust Reference › Numeric types › Machine-dependent integer types\n\nThe `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.\nWhile a `usize` can represent every *address*, converting a *pointer* to a `usize` is not necessarily a reversible operation. For more information, see the documentation for [type cast expressions], [`std::ptr`], and provenance in particular.\nThe `isize` type is a signed two's complement 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.\n`usize` and `isize` are at least 16-bits wide.\nMany 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Numeric types", "heading_path": ["Numeric types", "Machine-dependent integer types"], "path": "types/numeric.md", "url": "https://doc.rust-lang.org/reference/types/numeric.html#machine-dependent-integer-types", "has_code": false, "code_tags": []}} {"id": "reference/types/numeric.md#bit-validity-3", "text": "The Rust Reference › Numeric types › Bit validity\n\nFor every numeric type, `T`, the bit validity of `T` is equivalent to the bit validity of `[u8; size_of::()]`. An uninitialized byte is not a valid `u8`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Numeric types", "heading_path": ["Numeric types", "Bit validity"], "path": "types/numeric.md", "url": "https://doc.rust-lang.org/reference/types/numeric.html#bit-validity", "has_code": false, "code_tags": []}} {"id": "reference/types/char.md#character-type-0", "text": "The Rust Reference › Character type\n\nThe `char` type represents a single [Unicode scalar value] (i.e., a code point that is not a surrogate).\n```rust\nlet c: char = 'a';\nlet emoji: char = '😀';\nlet unicode: char = '\\u{1F600}';\n```\nSee the standard library docs for information on the impls of the `char` type.\nA value of type `char` is represented as a 32-bit unsigned word in the 0x0000 to 0xD7FF or 0xE000 to 0x10FFFF range. It is immediate [undefined behavior] to create a `char` that falls outside this range.\n`char` is guaranteed to have the same size and alignment as `u32` on all platforms.\nEvery byte of a `char` is guaranteed to be initialized. In other words, `transmute::()]>(...)` is always sound -- but since some bit patterns are invalid `char`s, the inverse is not always sound.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Character type", "heading_path": ["Character type"], "path": "types/char.md", "url": "https://doc.rust-lang.org/reference/types/char.html#character-type", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/types/str.md#string-slice-type-0", "text": "The Rust Reference › String slice type\n\nThe string slice (`str`) type represents a sequence of characters.\n```rust\nlet greeting1: &str = \"Hello, world!\";\nlet greeting2: &str = \"你好,世界\";\n```\nSee the standard library docs for information on the impls of the `str` type.\nA value of type `str` is represented in the same way as `[u8]`, a slice of 8-bit unsigned bytes.\nThe standard library makes extra assumptions about `str`: methods working on `str` assume and ensure that the data it contains is valid UTF-8. Calling a `str` method with a non-UTF-8 buffer can cause [undefined behavior] now or in the future.\nA `str` is a [dynamically sized type]. It can only be instantiated through a pointer type, such as `&str`. The layout of `&str` is the same as the layout of `&[u8]`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "String slice type", "heading_path": ["String slice type"], "path": "types/str.md", "url": "https://doc.rust-lang.org/reference/types/str.html#string-slice-type", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/types/never.md#never-type-0", "text": "The Rust Reference › Never type\n\n```grammar,types\nNeverType -> `!`\n```\nThe never type `!` is a type with no values, representing the result of computations that never complete.\nExpressions of type `!` can be coerced into any other type.\nThe `!` type can **only** appear in function return types presently, indicating it is a diverging function that never returns.\n```rust\nfn foo() -> ! {\n panic!(\"This call never returns.\");\n}\n```\n```rust\nunsafe extern \"C\" {\n pub safe fn no_return_extern_func() -> !;\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Never type", "heading_path": ["Never type"], "path": "types/never.md", "url": "https://doc.rust-lang.org/reference/types/never.html#never-type", "has_code": true, "code_tags": ["grammar,types", "rust"]}} {"id": "reference/types/tuple.md#tuple-types-0", "text": "The Rust Reference › Tuple types\n\n```grammar,types\nTupleType ->\n `(` `)`\n | `(` ( Type `,` )+ Type? `)`\n```\n*Tuple types* are a family of structural types[^1] for heterogeneous lists of other types.\nThe syntax for a tuple type is a parenthesized, comma-separated list of types.\n1-ary tuples require a comma after their element type to be disambiguated with a [parenthesized type].\nA 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.\nFields 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.\nFor 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*.\nSome examples of tuple types:\n* `()` (unit)\n* `(i32,)` (1-ary tuple)\n* `(f64, f64)`\n* `(String, i32)`\n* `(i32, String)` (different type from the previous example)\n* `(i32, f64, Vec, Option)`\nValues of this type are constructed using a [tuple expression]. Furthermore, various expressions will produce the unit value if there is no other meaningful value for it to evaluate to.\nTuple fields can be accessed by either a [tuple index expression] or [pattern matching].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tuple types", "heading_path": ["Tuple types"], "path": "types/tuple.md", "url": "https://doc.rust-lang.org/reference/types/tuple.html#tuple-types", "has_code": true, "code_tags": ["grammar,types"]}} {"id": "reference/types/tuple.md#tuple-types-1", "text": "The Rust Reference › Tuple types\n\n[^1]: Structural types are always equivalent if their internal types are equivalent. For a nominal version of tuples, see [tuple structs].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Tuple types", "heading_path": ["Tuple types"], "path": "types/tuple.md", "url": "https://doc.rust-lang.org/reference/types/tuple.html#tuple-types", "has_code": false, "code_tags": []}} {"id": "reference/types/array.md#array-types-0", "text": "The Rust Reference › Array types\n\n```grammar,types\nArrayType -> `[` Type `;` Expression `]`\n```\nAn array is a fixed-size sequence of `N` elements of type `T`. The array type is written as `[T; N]`.\nThe size is a [constant expression] that evaluates to a [`usize`].\nExamples:\n```rust\n// A stack-allocated array\nlet array: [i32; 3] = [1, 2, 3];\n\n// A heap-allocated array, coerced to a slice\nlet boxed_array: Box<[i32]> = Box::new([1, 2, 3]);\n```\nAll elements of arrays are always initialized, and access to an array is always bounds-checked in safe methods and operators.\nThe [`Vec`] standard library type provides a heap-allocated resizable array type.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Array types", "heading_path": ["Array types"], "path": "types/array.md", "url": "https://doc.rust-lang.org/reference/types/array.html#array-types", "has_code": true, "code_tags": ["grammar,types", "rust"]}} {"id": "reference/types/slice.md#slice-types-0", "text": "The Rust Reference › Slice types\n\n```grammar,types\nSliceType -> `[` Type `]`\n```\nA slice is a [dynamically sized type] representing a 'view' into a sequence of elements of type `T`. The slice type is written as `[T]`.\nSlice types are generally used through pointer types. For example:\n* `&[T]`: a 'shared slice', often just called a 'slice'. It doesn't own the data it points to; it borrows it.\n* `&mut [T]`: a 'mutable slice'. It mutably borrows the data it points to.\n* `Box<[T]>`: a 'boxed slice'\nExamples:\n```rust\n// A heap-allocated array, coerced to a slice\nlet boxed_array: Box<[i32]> = Box::new([1, 2, 3]);\n\n// A (shared) slice into an array\nlet slice: &[i32] = &boxed_array[..];\n```\nAll elements of slices are always initialized, and access to a slice is always bounds-checked in safe methods and operators.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Slice types", "heading_path": ["Slice types"], "path": "types/slice.md", "url": "https://doc.rust-lang.org/reference/types/slice.html#slice-types", "has_code": true, "code_tags": ["grammar,types", "rust"]}} {"id": "reference/types/struct.md#struct-types-0", "text": "The Rust Reference › Struct types\n\nA `struct` *type* is a heterogeneous product of other types, called the *fields* of the type.[^structtype]\nNew instances of a `struct` can be constructed with a [struct expression].\nThe 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]. 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.\nThe fields of a `struct` may be qualified by [visibility modifiers], to allow access to data in a struct outside a module.\nA _tuple struct_ type is just like a struct type, except that the fields are anonymous.\nA _unit-like struct_ type is like a struct type, except that it has no fields. The one value constructed by the associated [struct expression] is the only value that inhabits such a type.\n[^structtype]: `struct` types are analogous to `struct` types in C, the *record* types of the ML family, or the *struct* types of the Lisp family.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Struct types", "heading_path": ["Struct types"], "path": "types/struct.md", "url": "https://doc.rust-lang.org/reference/types/struct.html#struct-types", "has_code": false, "code_tags": []}} {"id": "reference/types/enum.md#enumerated-types-0", "text": "The Rust Reference › Enumerated types\n\nAn *enumerated type* is a nominal, heterogeneous disjoint union type, denoted by the name of an [`enum` item]. [^enumtype]\nAn [`enum` item] 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.\nNew instances of an `enum` can be constructed with a [struct expression].\nAny `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.\nEnum types cannot be denoted *structurally* as types, but must be denoted by named reference to an [`enum` item].\n[^enumtype]: The `enum` type is analogous to a `data` constructor declaration in Haskell, or a *pick ADT* in Limbo.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Enumerated types", "heading_path": ["Enumerated types"], "path": "types/enum.md", "url": "https://doc.rust-lang.org/reference/types/enum.html#enumerated-types", "has_code": false, "code_tags": []}} {"id": "reference/types/union.md#union-types-0", "text": "The Rust Reference › Union types\n\nA *union type* is a nominal, heterogeneous C-like union, denoted by the name of a `union` item.\nUnions 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.\nSince transmutes can cause unexpected or undefined behaviour, `unsafe` is required to read from a union field.\nUnion field types are also restricted to a subset of types which ensures that they never need dropping. See the [item] documentation for further details.\nThe 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Union types", "heading_path": ["Union types"], "path": "types/union.md", "url": "https://doc.rust-lang.org/reference/types/union.html#union-types", "has_code": false, "code_tags": []}} {"id": "reference/types/function-item.md#function-item-types-0", "text": "The Rust Reference › Function item types\n\nWhen 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_.\nThat 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.\nThere 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.\nBecause 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:\n```rust,compile_fail,E0308\nfn foo() { }\nlet x = &mut foo::;\n*x = foo::; //~ ERROR mismatched types\n```\nHowever, there is a [coercion] from function items to [function pointers] 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`:\n```rust\n\n// `foo_ptr_1` has function pointer type `fn()` here\nlet foo_ptr_1: fn() = foo::;\n\n// ... and so does `foo_ptr_2` - this type-checks.\nlet foo_ptr_2 = if want_i32 {\n foo::\n} else {\n foo::\n};\n```\nAll function items implement [`Copy`], [`Clone`], [`Send`], and [`Sync`].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Function item types", "heading_path": ["Function item types"], "path": "types/function-item.md", "url": "https://doc.rust-lang.org/reference/types/function-item.html#function-item-types", "has_code": true, "code_tags": ["rust", "rust,compile_fail,E0308"]}} {"id": "reference/types/function-item.md#function-item-types-1", "text": "The Rust Reference › Function item types\n\n[`Fn`], [`FnMut`], and [`FnOnce`] are implemented unless the function has any of the following:\n- an `unsafe` qualifier\n- a `target_feature` attribute\n- an ABI other than `\"Rust\"`", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Function item types", "heading_path": ["Function item types"], "path": "types/function-item.md", "url": "https://doc.rust-lang.org/reference/types/function-item.html#function-item-types", "has_code": false, "code_tags": []}} {"id": "reference/types/closure.md#closure-types-0", "text": "The Rust Reference › Closure types\n\nA [closure expression] 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 values. For instance, the following closure:\n```rust\n#[derive(Debug)]\nstruct Point { x: i32, y: i32 }\nstruct Rectangle { left_top: Point, right_bottom: Point }\n\nfn f String> (g: F) {\n println!(\"{}\", g());\n}\n\nlet mut rect = Rectangle {\n left_top: Point { x: 1, y: 1 },\n right_bottom: Point { x: 0, y: 0 }\n};\n\nlet c = || {\n rect.left_top.x += 1;\n rect.right_bottom.x += 1;\n format!(\"{:?}\", rect.left_top)\n};\nf(c); // Prints \"Point { x: 2, y: 1 }\".\n```\ngenerates a closure type roughly like the following:\n```rust,ignore\n// Note: This is not exactly how it is translated, this is only for\n// illustration.\n\nstruct Closure<'a> {\n left_top : &'a mut Point,\n right_bottom_x : &'a mut i32,\n}\n\nimpl<'a> FnOnce<()> for Closure<'a> {\n type Output = String;\n extern \"rust-call\" fn call_once(self, args: ()) -> String {\n self.left_top.x += 1;\n *self.right_bottom_x += 1;\n format!(\"{:?}\", self.left_top)\n }\n}\n```\nso that the call to `f` works as if it were:\n```rust,ignore\nf(Closure{ left_top: &mut rect.left_top, right_bottom_x: &mut rect.right_bottom.x });\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure types", "heading_path": ["Closure types"], "path": "types/closure.md", "url": "https://doc.rust-lang.org/reference/types/closure.html#closure-types", "has_code": true, "code_tags": ["rust", "rust,ignore"]}} {"id": "reference/types/closure.md#capture-modes-1", "text": "The Rust Reference › Closure types › Capture modes\n\nA *capture mode* determines how a [place expression] from the environment is borrowed or moved into the closure. The capture modes are:\n1. Immutable borrow (`ImmBorrow`) --- The place expression is captured as a [shared reference].\n2. Unique immutable borrow (`UniqueImmBorrow`) --- This is similar to an immutable borrow, but must be unique as described below.\n3. Mutable borrow (`MutBorrow`) --- The place expression is captured as a [mutable reference].\n4. Move (`ByValue`) --- The place expression is captured by [moving the value] into the closure.\nPlace expressions from the environment are captured from the first mode that is compatible with how the captured value is used inside the closure body. The mode is not affected by the code surrounding the closure, such as the lifetimes of involved variables or fields, or of the closure itself.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure types", "heading_path": ["Closure types", "Capture modes"], "path": "types/closure.md", "url": "https://doc.rust-lang.org/reference/types/closure.html#capture-modes", "has_code": false, "code_tags": []}} {"id": "reference/types/closure.md#copy-values-2", "text": "The Rust Reference › Closure types › Capture modes › `Copy` values\n\nValues that implement [`Copy`] that are moved into the closure are captured with the `ImmBorrow` mode.\n```rust\nlet x = [0; 1024];\nlet c = || {\n let y = x; // x captured by ImmBorrow\n};\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure types", "heading_path": ["Closure types", "Capture modes", "`Copy` values"], "path": "types/closure.md", "url": "https://doc.rust-lang.org/reference/types/closure.html#copy-values", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/types/closure.md#async-input-capture-3", "text": "The Rust Reference › Closure types › Capture modes › Async input capture\n\nAsync closures always capture all input arguments, regardless of whether or not they are used within the body.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure types", "heading_path": ["Closure types", "Capture modes", "Async input capture"], "path": "types/closure.md", "url": "https://doc.rust-lang.org/reference/types/closure.html#async-input-capture", "has_code": false, "code_tags": []}} {"id": "reference/types/closure.md#capture-precision-4", "text": "The Rust Reference › Closure types › Capture precision\n\nA *capture path* is a sequence starting with a variable from the environment followed by zero or more place projections from that variable.\nA *place projection* is a [field access], [tuple index], [dereference] (and automatic dereferences), [array or slice index] expression, or [pattern destructuring] applied to a variable.\nIn `rustc`, pattern destructuring desugars into a series of dereferences and field or element accesses.\nThe closure borrows or moves the capture path, which may be truncated based on the rules described below.\nFor example:\n```rust\nstruct SomeStruct {\n f1: (i32, i32),\n}\nlet s = SomeStruct { f1: (1, 2) };\n\nlet c = || {\n let x = s.f1.1; // s.f1.1 captured by ImmBorrow\n};\nc();\n```\nHere the capture path is the local variable `s`, followed by a field access `.f1`, and then a tuple index `.1`. This closure captures an immutable borrow of `s.f1.1`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure types", "heading_path": ["Closure types", "Capture precision"], "path": "types/closure.md", "url": "https://doc.rust-lang.org/reference/types/closure.html#capture-precision", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/types/closure.md#shared-prefix-5", "text": "The Rust Reference › Closure types › Capture precision › Shared prefix\n\nIn the case where a capture path and one of the ancestors of that path are both captured by a closure, the ancestor path is captured with the highest capture mode among the two captures, `CaptureMode = max(AncestorCaptureMode, DescendantCaptureMode)`, using the strict weak ordering:\n`ImmBorrow < UniqueImmBorrow < MutBorrow < ByValue`\nNote that this might need to be applied recursively.\n```rust\n// In this example, there are three different capture paths with a shared ancestor:\nlet s = String::from(\"S\");\nlet t = (s, String::from(\"T\"));\nlet mut u = (t, String::from(\"U\"));\n\nlet c = || {\n println!(\"{:?}\", u); // u captured by ImmBorrow\n u.1.truncate(0); // u.1 captured by MutBorrow\n move_value(u.0.0); // u.0.0 captured by ByValue\n};\nc();\n```\nOverall this closure will capture `u` by `ByValue`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure types", "heading_path": ["Closure types", "Capture precision", "Shared prefix"], "path": "types/closure.md", "url": "https://doc.rust-lang.org/reference/types/closure.html#shared-prefix", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/types/closure.md#rightmost-shared-reference-truncation-6", "text": "The Rust Reference › Closure types › Capture precision › Rightmost shared reference truncation\n\nThe capture path is truncated at the rightmost dereference in the capture path if the dereference is applied to a shared reference.\nThis truncation is allowed because fields that are read through a shared reference will always be read via a shared reference or a copy. This helps reduce the size of the capture when the extra precision does not yield any benefit from a borrow checking perspective.\nThe reason it is the *rightmost* dereference is to help avoid a shorter lifetime than is necessary. Consider the following example:\n```rust\nstruct Int(i32);\nstruct B<'a>(&'a i32);\n\nstruct MyStruct<'a> {\n a: &'static Int,\n b: B<'a>,\n}\n\nfn foo<'a, 'b>(m: &'a MyStruct<'b>) -> impl FnMut() + 'static {\n let c = || drop(&m.a.0);\n c\n}\n```\nIf this were to capture `m`, then the closure would no longer outlive `'static`, since `m` is constrained to `'a`. Instead, it captures `(*(*m).a)` by `ImmBorrow`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure types", "heading_path": ["Closure types", "Capture precision", "Rightmost shared reference truncation"], "path": "types/closure.md", "url": "https://doc.rust-lang.org/reference/types/closure.html#rightmost-shared-reference-truncation", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/types/closure.md#wildcard-pattern-bindings-7", "text": "The Rust Reference › Closure types › Capture precision › Wildcard pattern bindings\n\nClosures only capture data that needs to be read. Binding a value with a [wildcard pattern] does not read the value, so the place is not captured.\n```rust,no_run\nstruct S; // A non-`Copy` type.\nlet x = S;\nlet c = || {\n let _ = x; // Does not capture `x`.\n};\nlet c = || match x {\n _ => (), // Does not capture `x`.\n};\nx; // OK: `x` can be moved here.\nc();\n```\nDestructuring tuples, structs, and single-variant enums does not, by itself, cause a read or the place to be captured.\nEnums marked with [`#[non_exhaustive]`][attributes.type-system.non_exhaustive] are always treated as having multiple variants. See *[type.closure.capture.precision.discriminants.non_exhaustive]*.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure types", "heading_path": ["Closure types", "Capture precision", "Wildcard pattern bindings"], "path": "types/closure.md", "url": "https://doc.rust-lang.org/reference/types/closure.html#wildcard-pattern-bindings", "has_code": true, "code_tags": ["rust,no_run"]}} {"id": "reference/types/closure.md#wildcard-pattern-bindings-8", "text": "The Rust Reference › Closure types › Capture precision › Wildcard pattern bindings\n\n```rust,no_run\nstruct S; // A non-`Copy` type.\n\n// Destructuring tuples does not cause a read or capture.\nlet x = (S,);\nlet c = || {\n let (..) = x; // Does not capture `x`.\n};\nx; // OK: `x` can be moved here.\nc();\n\n// Destructuring unit structs does not cause a read or capture.\nlet x = S;\nlet c = || {\n let S = x; // Does not capture `x`.\n};\nx; // OK: `x` can be moved here.\nc();\n\n// Destructuring structs does not cause a read or capture.\nstruct W(T);\nlet x = W(S);\nlet c = || {\n let W(..) = x; // Does not capture `x`.\n};\nx; // OK: `x` can be moved here.\nc();\n\n// Destructuring single-variant enums does not cause a read\n// or capture.\nenum E { V(T) }\nlet x = E::V(S);\nlet c = || {\n let E::V(..) = x; // Does not capture `x`.\n};\nx; // OK: `x` can be moved here.\nc();\n```\nFields matched against [RestPattern] (`..`) or [StructPatternEtCetera] (also `..`) are not read, and those fields are not captured.\n```rust,no_run\nstruct S; // A non-`Copy` type.\nlet x = (S, S);\nlet c = || {\n let (x0, ..) = x; // Captures `x.0` by `ByValue`.\n};\n// Only the first tuple field was captured by the closure.\nx.1; // OK: `x.1` can be moved here.\nc();\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure types", "heading_path": ["Closure types", "Capture precision", "Wildcard pattern bindings"], "path": "types/closure.md", "url": "https://doc.rust-lang.org/reference/types/closure.html#wildcard-pattern-bindings", "has_code": true, "code_tags": ["rust,no_run"]}} {"id": "reference/types/closure.md#wildcard-pattern-bindings-9", "text": "The Rust Reference › Closure types › Capture precision › Wildcard pattern bindings\n\nPartial captures of arrays and slices are not supported; the entire slice or array is always captured even if used with wildcard pattern matching, indexing, or sub-slicing.\n```rust,compile_fail,E0382\nstruct S; // A non-`Copy` type.\nlet mut x = [S, S];\nlet c = || {\n let [x0, _] = x; // Captures all of `x` by `ByValue`.\n};\nlet _ = &mut x[1]; // ERROR: Borrow of moved value.\n```\nValues that are matched with wildcards must still be initialized.\n```rust,compile_fail,E0381\nlet x: u8;\nlet c = || {\n let _ = x; // ERROR: Binding `x` isn't initialized.\n};\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure types", "heading_path": ["Closure types", "Capture precision", "Wildcard pattern bindings"], "path": "types/closure.md", "url": "https://doc.rust-lang.org/reference/types/closure.html#wildcard-pattern-bindings", "has_code": true, "code_tags": ["rust,compile_fail,E0381", "rust,compile_fail,E0382"]}} {"id": "reference/types/closure.md#capturing-for-discriminant-reads-10", "text": "The Rust Reference › Closure types › Capture precision › Capturing for discriminant reads\n\nIf pattern matching reads a discriminant, the place containing that discriminant is captured by `ImmBorrow`.\nMatching against a variant of an enum that has more than one variant reads the discriminant, capturing the place by `ImmBorrow`.\n```rust,compile_fail,E0502\nstruct S; // A non-`Copy` type.\nlet mut x = (Some(S), S);\nlet c = || match x {\n (None, _) => (),\n// ^^^^\n// This pattern requires reading the discriminant, which\n// causes `x.0` to be captured by `ImmBorrow`.\n _ => (),\n};\nlet _ = &mut x.0; // ERROR: Cannot borrow `x.0` as mutable.\n// ^^^\n// The closure is still live, so `x.0` is still immutably\n// borrowed here.\nc();\n```\n```rust,no_run\nlet c = || match x { // Captures `x.0` by `ImmBorrow`.\n (None, _) => (),\n _ => (),\n};\n// Though `x.0` is captured due to the discriminant read,\n// `x.1` is not captured.\nx.1; // OK: `x.1` can be moved here.\nc();\n```\nMatching against the only variant of a single-variant enum does not read the discriminant and does not capture the place.\n```rust,no_run\nenum E { V(T) } // A single-variant enum.\nlet x = E::V(());\nlet c = || {\n let E::V(_) = x; // Does not capture `x`.\n};\nx; // OK: `x` can be moved here.\nc();\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure types", "heading_path": ["Closure types", "Capture precision", "Capturing for discriminant reads"], "path": "types/closure.md", "url": "https://doc.rust-lang.org/reference/types/closure.html#capturing-for-discriminant-reads", "has_code": true, "code_tags": ["rust,compile_fail,E0502", "rust,no_run"]}} {"id": "reference/types/closure.md#capturing-for-discriminant-reads-11", "text": "The Rust Reference › Closure types › Capture precision › Capturing for discriminant reads\n\nIf [`#[non_exhaustive]`][attributes.type-system.non_exhaustive] is applied to an enum, the enum is treated as having multiple variants for the purpose of deciding whether a read occurs, even if it actually has only one variant.\nEven if all variants but the one being matched against are uninhabited, making the pattern irrefutable, the discriminant is still read if it otherwise would be.\n```rust,compile_fail,E0502\nenum Empty {}\nlet mut x = Ok::<_, Empty>(42);\nlet c = || {\n let Ok(_) = x; // Captures `x` by `ImmBorrow`.\n};\nlet _ = &mut x; // ERROR: Cannot borrow `x` as mutable.\nc();\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure types", "heading_path": ["Closure types", "Capture precision", "Capturing for discriminant reads"], "path": "types/closure.md", "url": "https://doc.rust-lang.org/reference/types/closure.html#capturing-for-discriminant-reads", "has_code": true, "code_tags": ["rust,compile_fail,E0502"]}} {"id": "reference/types/closure.md#capturing-and-range-patterns-12", "text": "The Rust Reference › Closure types › Capture precision › Capturing and range patterns\n\nMatching against a range pattern reads the place being matched, even if the range includes all possible values of the type, and captures the place by `ImmBorrow`.\n```rust,compile_fail,E0502\nlet mut x = 0u8;\nlet c = || {\n let 0..=u8::MAX = x; // Captures `x` by `ImmBorrow`.\n};\nlet _ = &mut x; // ERROR: Cannot borrow `x` as mutable.\nc();\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure types", "heading_path": ["Closure types", "Capture precision", "Capturing and range patterns"], "path": "types/closure.md", "url": "https://doc.rust-lang.org/reference/types/closure.html#capturing-and-range-patterns", "has_code": true, "code_tags": ["rust,compile_fail,E0502"]}} {"id": "reference/types/closure.md#capturing-and-slice-patterns-13", "text": "The Rust Reference › Closure types › Capture precision › Capturing and slice patterns\n\nMatching a slice against a slice pattern other than one with only a single rest pattern (i.e. `[..]`) is treated as a read of the length from the slice and captures the slice by `ImmBorrow`.\n```rust,compile_fail,E0502\nlet x: &mut [u8] = &mut [];\nlet c = || match x { // Captures `*x` by `ImmBorrow`.\n &mut [] => (),\n// ^^\n// This matches a slice of exactly zero elements. To know whether the\n// scrutinee matches, the length must be read, causing the slice to\n// be captured.\n _ => (),\n};\nlet _ = &mut *x; // ERROR: Cannot borrow `*x` as mutable.\nc();\n```\n```rust,no_run\nlet x: &mut [u8] = &mut [];\nlet c = || match x { // Does not capture `*x`.\n [..] => (),\n// ^^ Rest pattern.\n};\nlet _ = &mut *x; // OK\nc();\n```\nPerhaps surprisingly, even though the length is contained in the (wide) *pointer* to the slice, it is the place of the *pointee* (the slice) that is treated as read and is captured.\n```rust,no_run\nfn f<'l: 's, 's>(x: &'s mut &'l [u8]) -> impl Fn() + 'l {\n // The closure outlives `'l` because it captures `**x`. If\n // instead it captured `*x`, it would not live long enough\n // to satisfy the `impl Fn() + 'l` bound.\n || match *x { // Captures `**x` by `ImmBorrow`.\n &[] => (),\n _ => (),\n }\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure types", "heading_path": ["Closure types", "Capture precision", "Capturing and slice patterns"], "path": "types/closure.md", "url": "https://doc.rust-lang.org/reference/types/closure.html#capturing-and-slice-patterns", "has_code": true, "code_tags": ["rust,compile_fail,E0502", "rust,no_run"]}} {"id": "reference/types/closure.md#capturing-and-slice-patterns-14", "text": "The Rust Reference › Closure types › Capture precision › Capturing and slice patterns\n\nIn this way, the behavior is consistent with dereferencing to the slice in the scrutinee.\n```rust,no_run\nfn f<'l: 's, 's>(x: &'s mut &'l [u8]) -> impl Fn() + 'l {\n || match **x { // Captures `**x` by `ImmBorrow`.\n [] => (),\n _ => (),\n }\n}\n```\nFor details, see Rust PR #138961.\nAs the length of an array is fixed by its type, matching an array against a slice pattern does not by itself capture the place.\n```rust,no_run\nlet x: [u8; 1] = [0];\nlet c = || match x { // Does not capture `x`.\n [_] => (), // Length is fixed.\n};\nx; // OK: `x` can be moved here.\nc();\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure types", "heading_path": ["Closure types", "Capture precision", "Capturing and slice patterns"], "path": "types/closure.md", "url": "https://doc.rust-lang.org/reference/types/closure.html#capturing-and-slice-patterns", "has_code": true, "code_tags": ["rust,no_run"]}} {"id": "reference/types/closure.md#capturing-references-in-move-contexts-15", "text": "The Rust Reference › Closure types › Capture precision › Capturing references in move contexts\n\nBecause it is not allowed to move fields out of a reference, `move` closures will only capture the prefix of a capture path that runs up to, but not including, the first dereference of a reference. The reference itself will be moved into the closure.\n```rust\nstruct T(String, String);\n\nlet mut t = T(String::from(\"foo\"), String::from(\"bar\"));\nlet t_mut_ref = &mut t;\nlet mut c = move || {\n t_mut_ref.0.push_str(\"123\"); // captures `t_mut_ref` ByValue\n};\nc();\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure types", "heading_path": ["Closure types", "Capture precision", "Capturing references in move contexts"], "path": "types/closure.md", "url": "https://doc.rust-lang.org/reference/types/closure.html#capturing-references-in-move-contexts", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/types/closure.md#raw-pointer-dereference-16", "text": "The Rust Reference › Closure types › Capture precision › Raw pointer dereference\n\nBecause it is `unsafe` to dereference a raw pointer, closures will only capture the prefix of a capture path that runs up to, but not including, the first dereference of a raw pointer.\n```rust\nstruct T(String, String);\n\nlet t = T(String::from(\"foo\"), String::from(\"bar\"));\nlet t_ptr = &t as *const T;\n\nlet c = || unsafe {\n println!(\"{}\", (*t_ptr).0); // captures `t_ptr` by ImmBorrow\n};\nc();\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure types", "heading_path": ["Closure types", "Capture precision", "Raw pointer dereference"], "path": "types/closure.md", "url": "https://doc.rust-lang.org/reference/types/closure.html#raw-pointer-dereference", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/types/closure.md#union-fields-17", "text": "The Rust Reference › Closure types › Capture precision › Union fields\n\nBecause it is `unsafe` to access a union field, closures will only capture the prefix of a capture path that runs up to the union itself.\n```rust\nunion U {\n a: (i32, i32),\n b: bool,\n}\nlet u = U { a: (123, 456) };\n\nlet c = || {\n let x = unsafe { u.a.0 }; // captures `u` ByValue\n};\nc();\n\n// This also includes writing to fields.\nlet mut u = U { a: (123, 456) };\n\nlet mut c = || {\n u.b = true; // captures `u` with MutBorrow\n};\nc();\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure types", "heading_path": ["Closure types", "Capture precision", "Union fields"], "path": "types/closure.md", "url": "https://doc.rust-lang.org/reference/types/closure.html#union-fields", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/types/closure.md#reference-into-unaligned-structs-18", "text": "The Rust Reference › Closure types › Capture precision › Reference into unaligned `struct`s\n\nBecause it is [undefined behavior] to create references to unaligned fields in a structure, closures will only capture the prefix of the capture path that runs up to, but not including, the first field access into a structure that uses [the `packed` representation]. This includes all fields, even those that are aligned, to protect against compatibility concerns should any of the fields in the structure change in the future.\n```rust\n#[repr(packed)]\nstruct T(i32, i32);\n\nlet t = T(2, 5);\nlet c = || {\n let a = t.0; // captures `t` with ImmBorrow\n};\n// Copies out of `t` are ok.\nlet (a, b) = (t.0, t.1);\nc();\n```\nSimilarly, taking the address of an unaligned field also captures the entire struct:\n```rust,compile_fail,E0505\n#[repr(packed)]\nstruct T(String, String);\n\nlet mut t = T(String::new(), String::new());\nlet c = || {\n let a = std::ptr::addr_of!(t.1); // captures `t` with ImmBorrow\n};\nlet a = t.0; // ERROR: cannot move out of `t.0` because it is borrowed\nc();\n```\nbut the above works if it is not packed since it captures the field precisely:\n```rust\nstruct T(String, String);\n\nlet mut t = T(String::new(), String::new());\nlet c = || {\n let a = std::ptr::addr_of!(t.1); // captures `t.1` with ImmBorrow\n};\n// The move here is allowed.\nlet a = t.0;\nc();\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure types", "heading_path": ["Closure types", "Capture precision", "Reference into unaligned `struct`s"], "path": "types/closure.md", "url": "https://doc.rust-lang.org/reference/types/closure.html#reference-into-unaligned-structs", "has_code": true, "code_tags": ["rust", "rust,compile_fail,E0505"]}} {"id": "reference/types/closure.md#box-with-move-closure-19", "text": "The Rust Reference › Closure types › Capture precision › `Box` vs other `Deref` implementations › `Box` with move closure\n\nThe implementation of the [`Deref`] trait for [`Box`] is treated differently from other `Deref` implementations, as it is considered a special entity.\nFor example, let us look at examples involving `Rc` and `Box`. The `*rc` is desugared to a call to the trait method `deref` defined on `Rc`, but since `*box` is treated differently, it is possible to do a precise capture of the contents of the `Box`.\nIn a non-`move` closure, if the contents of the `Box` are not moved into the closure body, the contents of the `Box` are precisely captured.\n```rust\nstruct S(String);\n\nlet b = Box::new(S(String::new()));\nlet c_box = || {\n let x = &(*b).0; // captures `(*b).0` by ImmBorrow\n};\nc_box();\n\n// Contrast `Box` with another type that implements Deref:\nlet r = std::rc::Rc::new(S(String::new()));\nlet c_rc = || {\n let x = &(*r).0; // captures `r` by ImmBorrow\n};\nc_rc();\n```\nHowever, if the contents of the `Box` are moved into the closure, then the box is entirely captured. This is done so the amount of data that needs to be moved into the closure is minimized.\n```rust\n// This is the same as the example above except the closure\n// moves the value instead of taking a reference to it.\n\nstruct S(String);\n\nlet b = Box::new(S(String::new()));\nlet c_box = || {\n let x = (*b).0; // captures `b` with ByValue\n};\nc_box();\n```\nSimilarly to moving contents of a `Box` in a non-`move` closure, reading the contents of a `Box` in a `move` closure will capture the `Box` entirely.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure types", "heading_path": ["Closure types", "Capture precision", "`Box` vs other `Deref` implementations", "`Box` with move closure"], "path": "types/closure.md", "url": "https://doc.rust-lang.org/reference/types/closure.html#box-with-move-closure", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/types/closure.md#box-with-move-closure-20", "text": "The Rust Reference › Closure types › Capture precision › `Box` vs other `Deref` implementations › `Box` with move closure\n\n```rust\nstruct S(i32);\n\nlet b = Box::new(S(10));\nlet c_box = move || {\n let x = (*b).0; // captures `b` with ByValue\n};\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure types", "heading_path": ["Closure types", "Capture precision", "`Box` vs other `Deref` implementations", "`Box` with move closure"], "path": "types/closure.md", "url": "https://doc.rust-lang.org/reference/types/closure.html#box-with-move-closure", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/types/closure.md#unique-immutable-borrows-in-captures-21", "text": "The Rust Reference › Closure types › Unique immutable borrows in captures\n\nCaptures 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:\n```rust\nlet mut b = false;\nlet x = &mut b;\nlet mut c = || {\n // An ImmBorrow and a MutBorrow of `x`.\n let a = &x;\n *x = true; // `x` captured by UniqueImmBorrow\n};\n// The following line is an error:\n// let y = &x;\nc();\n// However, the following is OK.\nlet z = &x;\n```\nIn 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.\nIn 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure types", "heading_path": ["Closure types", "Unique immutable borrows in captures"], "path": "types/closure.md", "url": "https://doc.rust-lang.org/reference/types/closure.html#unique-immutable-borrows-in-captures", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/types/closure.md#call-traits-and-coercions-22", "text": "The Rust Reference › Closure types › Call traits and coercions\n\nClosure types all implement [`FnOnce`], indicating that they can be called once by consuming ownership of the closure. Additionally, some closures implement more specific call traits:\n* A closure which does not move out of any captured variables implements [`FnMut`], indicating that it can be called by mutable reference.\n* A closure which does not mutate or move out of any captured variables implements [`Fn`], indicating that it can be called by shared reference.\n`move` closures may still implement [`Fn`] or [`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.\n*Non-capturing closures* are closures that don't capture anything from their environment. Non-async, non-capturing closures can be coerced to function pointers (e.g., `fn()`) with the matching signature.\n```rust\nlet add = |x, y| x + y;\n\nlet mut x = add(5,7);\n\ntype Binop = fn(i32, i32) -> i32;\nlet bo: Binop = add;\nx = bo(5,7);\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure types", "heading_path": ["Closure types", "Call traits and coercions"], "path": "types/closure.md", "url": "https://doc.rust-lang.org/reference/types/closure.html#call-traits-and-coercions", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/types/closure.md#async-closure-traits-23", "text": "The Rust Reference › Closure types › Call traits and coercions › Async closure traits\n\nAsync closures have a further restriction of whether or not they implement [`FnMut`] or [`Fn`].\nThe [`Future`] returned by the async closure has similar capturing characteristics as a closure. It captures place expressions from the async closure based on how they are used. The async closure is said to be *lending* to its [`Future`] if it has either of the following properties:\n- The `Future` includes a mutable capture.\n- The async closure captures by value, except when the value is accessed with a dereference projection.\nIf the async closure is lending to its `Future`, then [`FnMut`] and [`Fn`] are *not* implemented. [`FnOnce`] is always implemented.\n**Example**: The first clause for a mutable capture can be illustrated with the following:\n```rust,compile_fail\nfn takes_callback(c: impl FnMut() -> Fut) {}\n\nfn f() {\n let mut x = 1i32;\n let c = async || {\n x = 2; // x captured with MutBorrow\n };\n takes_callback(c); // ERROR: async closure does not implement `FnMut`\n}\n```\nThe second clause for a regular value capture can be illustrated with the following:\n```rust,compile_fail\nfn takes_callback(c: impl Fn() -> Fut) {}\n\nfn f() {\n let x = &1i32;\n let c = async move || {\n let a = x + 2; // x captured ByValue\n };\n takes_callback(c); // ERROR: async closure does not implement `Fn`\n}\n```\nThe exception of the the second clause can be illustrated by using a dereference, which does allow `Fn` and `FnMut` to be implemented:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure types", "heading_path": ["Closure types", "Call traits and coercions", "Async closure traits"], "path": "types/closure.md", "url": "https://doc.rust-lang.org/reference/types/closure.html#async-closure-traits", "has_code": true, "code_tags": ["rust,compile_fail"]}} {"id": "reference/types/closure.md#async-closure-traits-24", "text": "The Rust Reference › Closure types › Call traits and coercions › Async closure traits\n\n```rust\nfn takes_callback(c: impl Fn() -> Fut) {}\n\nfn f() {\n let x = &1i32;\n let c = async move || {\n let a = *x + 2;\n };\n takes_callback(c); // OK: implements `Fn`\n}\n```\nAsync closures implement [`AsyncFn`], [`AsyncFnMut`], and [`AsyncFnOnce`] in an analogous way as regular closures implement [`Fn`], [`FnMut`], and [`FnOnce`]; that is, depending on the use of the captured variables in its body.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure types", "heading_path": ["Closure types", "Call traits and coercions", "Async closure traits"], "path": "types/closure.md", "url": "https://doc.rust-lang.org/reference/types/closure.html#async-closure-traits", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/types/closure.md#other-traits-25", "text": "The Rust Reference › Closure types › Call traits and coercions › Other traits\n\nAll closure types implement [`Sized`]. Additionally, closure types implement the following traits if allowed to do so by the types of the captures it stores:\n* [`Clone`]\n* [`Copy`]\n* [`Sync`]\n* [`Send`]\nThe rules for [`Send`] and [`Sync`] match those for normal struct types, while [`Clone`] and [`Copy`] behave as if [derived]. For [`Clone`], the order of cloning of the captured values is left unspecified.\nBecause captures are often by reference, the following general rules arise:\n* A closure is [`Sync`] if all captured values are [`Sync`].\n* A closure is [`Send`] if all values captured by non-unique immutable reference are [`Sync`], and all values captured by unique immutable or mutable reference, copy, or move are [`Send`].\n* A closure is [`Clone`] or [`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`] or [`Copy`], respectively.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure types", "heading_path": ["Closure types", "Call traits and coercions", "Other traits"], "path": "types/closure.md", "url": "https://doc.rust-lang.org/reference/types/closure.html#other-traits", "has_code": false, "code_tags": []}} {"id": "reference/types/closure.md#drop-order-26", "text": "The Rust Reference › Closure types › Drop order\n\nIf a closure captures a field of a composite types such as structs, tuples, and enums by value, the field's lifetime would now be tied to the closure. As a result, it is possible for disjoint fields of a composite types to be dropped at different times.\n```rust\n{\n let tuple =\n (String::from(\"foo\"), String::from(\"bar\")); // --+\n { // |\n let c = || { // ----------------------------+ |\n // tuple.0 is captured into the closure | |\n drop(tuple.0); // | |\n }; // | |\n } // 'c' and 'tuple.0' dropped here ------------+ |\n} // tuple.1 dropped here -----------------------------+\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure types", "heading_path": ["Closure types", "Drop order"], "path": "types/closure.md", "url": "https://doc.rust-lang.org/reference/types/closure.html#drop-order", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/types/closure.md#closure-types-difference-27", "text": "The Rust Reference › Closure types › Edition 2018 and before › Closure types difference\n\nIn Edition 2018 and before, closures always capture a variable in its entirety, without its precise capture path. This means that for the example used in the Closure types section, the generated closure type would instead look something like this:\n```rust,ignore\nstruct Closure<'a> {\n rect : &'a mut Rectangle,\n}\n\nimpl<'a> FnOnce<()> for Closure<'a> {\n type Output = String;\n extern \"rust-call\" fn call_once(self, args: ()) -> String {\n self.rect.left_top.x += 1;\n self.rect.right_bottom.x += 1;\n format!(\"{:?}\", self.rect.left_top)\n }\n}\n```\nand the call to `f` would work as follows:\n```rust,ignore\nf(Closure { rect: rect });\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure types", "heading_path": ["Closure types", "Edition 2018 and before", "Closure types difference"], "path": "types/closure.md", "url": "https://doc.rust-lang.org/reference/types/closure.html#closure-types-difference", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "reference/types/closure.md#capture-precision-difference-28", "text": "The Rust Reference › Closure types › Edition 2018 and before › Capture precision difference\n\nComposite types such as structs, tuples, and enums are always captured in its entirety, not by individual fields. As a result, it may be necessary to borrow into a local variable in order to capture a single field:\n```rust\nstruct SetVec {\n set: HashSet,\n vec: Vec\n}\n\nimpl SetVec {\n fn populate(&mut self) {\n let vec = &mut self.vec;\n self.set.iter().for_each(|&n| {\n vec.push(n);\n })\n }\n}\n```\nIf, 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.\nIf 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.\nRegardless of if the data will be read by the closure, i.e. in case of wild card patterns, if a variable defined outside the closure is mentioned within the closure the variable will be captured in its entirety.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure types", "heading_path": ["Closure types", "Edition 2018 and before", "Capture precision difference"], "path": "types/closure.md", "url": "https://doc.rust-lang.org/reference/types/closure.html#capture-precision-difference", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/types/closure.md#drop-order-difference-29", "text": "The Rust Reference › Closure types › Edition 2018 and before › Drop order difference\n\nAs composite types are captured in their entirety, a closure which captures one of those composite types by value would drop the entire captured variable at the same time as the closure gets dropped.\n```rust\n{\n let tuple =\n (String::from(\"foo\"), String::from(\"bar\"));\n {\n let c = || { // --------------------------+\n // tuple is captured into the closure |\n drop(tuple.0); // |\n }; // |\n } // 'c' and 'tuple' dropped here ------------+\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Closure types", "heading_path": ["Closure types", "Edition 2018 and before", "Drop order difference"], "path": "types/closure.md", "url": "https://doc.rust-lang.org/reference/types/closure.html#drop-order-difference", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/types/pointer.md#pointer-types-0", "text": "The Rust Reference › Pointer types\n\nAll pointers are explicit first-class values. They can be moved or copied, stored into data structs, and returned from functions.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Pointer types", "heading_path": ["Pointer types"], "path": "types/pointer.md", "url": "https://doc.rust-lang.org/reference/types/pointer.html#pointer-types", "has_code": false, "code_tags": []}} {"id": "reference/types/pointer.md#references--and-mut-1", "text": "The Rust Reference › Pointer types › References (`&` and `&mut`)\n\n```grammar,types\nReferenceType -> `&` Lifetime? `mut`? TypeNoBounds\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Pointer types", "heading_path": ["Pointer types", "References (`&` and `&mut`)"], "path": "types/pointer.md", "url": "https://doc.rust-lang.org/reference/types/pointer.html#references--and-mut", "has_code": true, "code_tags": ["grammar,types"]}} {"id": "reference/types/pointer.md#shared-references--2", "text": "The Rust Reference › Pointer types › References (`&` and `&mut`) › Shared references (`&`)\n\nShared references point to memory which is owned by some other value.\nWhen a shared reference to a value is created, it prevents direct mutation of the value. [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.\nCopying 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] will keep it alive during the scope of the reference itself.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Pointer types", "heading_path": ["Pointer types", "References (`&` and `&mut`)", "Shared references (`&`)"], "path": "types/pointer.md", "url": "https://doc.rust-lang.org/reference/types/pointer.html#shared-references-", "has_code": false, "code_tags": []}} {"id": "reference/types/pointer.md#mutable-references-mut-3", "text": "The Rust Reference › Pointer types › References (`&` and `&mut`) › Mutable references (`&mut`)\n\nMutable references point to memory which is owned by some other value. A mutable reference type is written `&mut type` or `&'a mut type`.\nA mutable reference (that hasn't been borrowed) is the only way to access the value it points to, so is not `Copy`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Pointer types", "heading_path": ["Pointer types", "References (`&` and `&mut`)", "Mutable references (`&mut`)"], "path": "types/pointer.md", "url": "https://doc.rust-lang.org/reference/types/pointer.html#mutable-references-mut", "has_code": false, "code_tags": []}} {"id": "reference/types/pointer.md#raw-pointers-const-and-mut-4", "text": "The Rust Reference › Pointer types › Raw pointers (`const` and `mut`)\n\n```grammar,types\nRawPointerType -> `*` ( `mut` | `const` ) TypeNoBounds\n```\nRaw 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.\nCopying or dropping a raw pointer has no effect on the lifecycle of any other value.\nDereferencing a raw pointer is an [`unsafe` operation].\nThis 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.\nWhen comparing raw pointers they are compared by their address, rather than by what they point to. When comparing raw pointers to [dynamically sized types] they also have their additional data compared.\nRaw pointers can be created directly using `&raw const` for `*const` pointers and `&raw mut` for `*mut` pointers.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Pointer types", "heading_path": ["Pointer types", "Raw pointers (`const` and `mut`)"], "path": "types/pointer.md", "url": "https://doc.rust-lang.org/reference/types/pointer.html#raw-pointers-const-and-mut", "has_code": true, "code_tags": ["grammar,types"]}} {"id": "reference/types/pointer.md#smart-pointers-5", "text": "The Rust Reference › Pointer types › Smart pointers\n\nThe standard library contains additional 'smart pointer' types beyond references and raw pointers.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Pointer types", "heading_path": ["Pointer types", "Smart pointers"], "path": "types/pointer.md", "url": "https://doc.rust-lang.org/reference/types/pointer.html#smart-pointers", "has_code": false, "code_tags": []}} {"id": "reference/types/pointer.md#bit-validity-6", "text": "The Rust Reference › Pointer types › Bit validity\n\nDespite pointers and references being similar to `usize`s in the machine code emitted on most platforms, the semantics of transmuting a reference or pointer type to a non-pointer type is currently undecided. Thus, it may not be valid to transmute a pointer or reference type, `P`, to a `[u8; size_of::

()]`.\nFor thin raw pointers (i.e., for `P = *const T` or `P = *mut T` for `T: Sized`), the inverse direction (transmuting from an integer or array of integers to `P`) is always valid. However, the pointer produced via such a transmutation may not be dereferenced (not even if `T` has [size zero]).", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Pointer types", "heading_path": ["Pointer types", "Bit validity"], "path": "types/pointer.md", "url": "https://doc.rust-lang.org/reference/types/pointer.html#bit-validity", "has_code": false, "code_tags": []}} {"id": "reference/types/function-pointer.md#function-pointer-types-0", "text": "The Rust Reference › Function pointer types\n\n```grammar,types\nBareFunctionType ->\n ForLifetimes? FunctionTypeQualifiers `fn`\n `(` FunctionParametersMaybeNamedVariadic? `)` BareFunctionReturnType?\n\nFunctionTypeQualifiers -> `unsafe`? (`extern` Abi?)?\n\nBareFunctionReturnType -> `->` TypeNoBounds\n\nFunctionParametersMaybeNamedVariadic ->\n MaybeNamedFunctionParameters | MaybeNamedFunctionParametersVariadic\n\nMaybeNamedFunctionParameters ->\n MaybeNamedParam ( `,` MaybeNamedParam )* `,`?\n\nMaybeNamedParam ->\n OuterAttribute* ( ( IDENTIFIER | `_` ) `:` )? Type\n\nMaybeNamedFunctionParametersVariadic ->\n ( MaybeNamedParam `,` )* MaybeNamedParam `,` OuterAttribute* `...`\n```\nA function pointer type, written using the `fn` keyword, refers to a function whose identity is not necessarily known at compile-time.\nAn example where `Binop` is defined as a function pointer type:\n```rust\nfn add(x: i32, y: i32) -> i32 {\n x + y\n}\n\nlet mut x = add(5,7);\n\ntype Binop = fn(i32, i32) -> i32;\nlet bo: Binop = add;\nx = bo(5,7);\n```\nFunction pointers can be created via a coercion from both [function items] and non-capturing, non-async [closures].\nThe `unsafe` qualifier indicates that the type's value is an [unsafe function], and the `extern` qualifier indicates it is an [extern function].\nFor the function to be variadic, its `extern` ABI must be one of those listed in [items.extern.variadic.conventions].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Function pointer types", "heading_path": ["Function pointer types"], "path": "types/function-pointer.md", "url": "https://doc.rust-lang.org/reference/types/function-pointer.html#function-pointer-types", "has_code": true, "code_tags": ["grammar,types", "rust"]}} {"id": "reference/types/function-pointer.md#attributes-on-function-pointer-parameters-1", "text": "The Rust Reference › Function pointer types › Attributes on function pointer parameters\n\nAttributes on function pointer parameters follow the same rules and restrictions as [regular function parameters].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Function pointer types", "heading_path": ["Function pointer types", "Attributes on function pointer parameters"], "path": "types/function-pointer.md", "url": "https://doc.rust-lang.org/reference/types/function-pointer.html#attributes-on-function-pointer-parameters", "has_code": false, "code_tags": []}} {"id": "reference/types/trait-object.md#trait-objects-0", "text": "The Rust Reference › Trait objects\n\n```grammar,types\nTraitObjectType -> Bounds[^bare-2021] | `dyn`[^dyn-2018] Bounds?\n\nTraitObjectTypeOneBound -> TraitBound[^bare-2021] | `dyn`[^dyn-2018] TraitBound?\n```\n[^bare-2021]: See [type.trait-object.syntax-edition2021].\n[^dyn-2018]: See [type.trait-object.syntax-edition2018].\nA *trait object* is an opaque value of another type that implements a set of traits. The set of traits is made up of a [dyn compatible] *base trait* plus any number of [auto traits].\nTrait objects implement the base trait, its auto traits, and any [supertraits] of the base trait.\nThere must be at least one trait bound, there may not be more than one non-auto trait, no more than one lifetime, and opt-out bounds (e.g., `?Sized`) and `use<..>` bounds are not allowed.\nFor example, given a trait `Trait`, the following are all trait objects:\n* `dyn Trait`\n* `dyn Trait + Send`\n* `dyn Trait + Send + Sync`\n* `dyn Trait + 'static`\n* `dyn Trait + Send + 'static`\n* `dyn Trait +`\n* `dyn 'static + Trait`.\n* `dyn (Trait)`\n[!EDITION-2021]\nBefore the 2021 edition, the `dyn` keyword may be omitted. In the 2021 edition and beyond, the `dyn` keyword is required semantically.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Trait object types", "heading_path": ["Trait objects"], "path": "types/trait-object.md", "url": "https://doc.rust-lang.org/reference/types/trait-object.html#trait-objects", "has_code": true, "code_tags": ["grammar,types"]}} {"id": "reference/types/trait-object.md#trait-objects-1", "text": "The Rust Reference › Trait objects\n\n[!EDITION-2018]\nIn the 2015 edition, `dyn` must be followed by [PathIdentSegment], [LIFETIME_TOKEN], `for`, `(` or `?` to be interpreted as a keyword instead of a regular identifier.\nMost notably, `dyn`, `dyn::T` and `dyn` will all be treated as type paths. As such, if you want a trait object type with the trait `::module::Trait`, you need to put the path in parentheses and write it as `dyn (::module::Trait)`.\nBeginning in the 2018 edition, `dyn` is a true keyword and is not allowed in paths, so the parentheses are not necessary.\nTwo 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`.\nDue to the opaqueness of which concrete type the value is of, trait objects are [dynamically sized types]. Like all DSTs, trait objects are used behind some type of pointer; for example `&dyn SomeTrait` or `Box`. Each instance of a pointer to a trait object includes:\n - a pointer to an instance of a type `T` that implements `SomeTrait`\n - a _virtual method table_, often just called a _vtable_, which contains, for each method of `SomeTrait` and its [supertraits] that `T` implements, a pointer to `T`'s implementation (i.e. a function pointer).", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Trait object types", "heading_path": ["Trait objects"], "path": "types/trait-object.md", "url": "https://doc.rust-lang.org/reference/types/trait-object.html#trait-objects", "has_code": false, "code_tags": []}} {"id": "reference/types/trait-object.md#trait-objects-2", "text": "The Rust Reference › Trait objects\n\nThe 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.\nAn example of a trait object:\n```rust\ntrait Printable {\n fn stringify(&self) -> String;\n}\n\nimpl Printable for i32 {\n fn stringify(&self) -> String { self.to_string() }\n}\n\nfn print(a: Box) {\n println!(\"{}\", a.stringify());\n}\n\nfn main() {\n print(Box::new(10) as Box);\n}\n```\nIn this example, the trait `Printable` occurs as a trait object in both the type signature of `print`, and the cast expression in `main`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Trait object types", "heading_path": ["Trait objects"], "path": "types/trait-object.md", "url": "https://doc.rust-lang.org/reference/types/trait-object.html#trait-objects", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/types/trait-object.md#trait-object-lifetime-bounds-3", "text": "The Rust Reference › Trait objects › Trait object lifetime bounds\n\nSince 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] that allow this lifetime to usually be inferred with a sensible choice.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Trait object types", "heading_path": ["Trait objects", "Trait object lifetime bounds"], "path": "types/trait-object.md", "url": "https://doc.rust-lang.org/reference/types/trait-object.html#trait-object-lifetime-bounds", "has_code": false, "code_tags": []}} {"id": "reference/types/impl-trait.md#impl-trait-0", "text": "The Rust Reference › Impl trait\n\n```grammar,types\nImplTraitType -> `impl` Bounds?\n\nImplTraitTypeOneBound -> `impl` TraitBound?\n```\n`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).\n```rust\ntrait Trait {}\n\n// argument position: anonymous type parameter\nfn foo(arg: impl Trait) {\n}\n\n// return position: abstract return type\nfn bar() -> impl Trait {\n}\n```\nThere must be at least one trait bound, no more than one `use<..>` bound, and no more than one opt-out bound (e.g., `?Sized`).", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Impl trait type", "heading_path": ["Impl trait"], "path": "types/impl-trait.md", "url": "https://doc.rust-lang.org/reference/types/impl-trait.html#impl-trait", "has_code": true, "code_tags": ["grammar,types", "rust"]}} {"id": "reference/types/impl-trait.md#anonymous-type-parameters-1", "text": "The Rust Reference › Impl trait › Anonymous type parameters\n\nThis 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.)\nFunctions 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.\nFor example, these two forms are almost equivalent:\n```rust\ntrait Trait {}\n\n// generic type parameter\nfn with_generic_type(arg: T) {\n}\n\n// impl Trait in argument position\nfn with_impl_trait(arg: impl Trait) {\n}\n```\nThat is, `impl Trait` in argument position is syntactic sugar for a generic type parameter like ``, except that the type is anonymous and doesn't appear in the [GenericParams] list.\nFor function parameters, generic type parameters and `impl Trait` are not exactly equivalent. With a generic parameter such as ``, the caller has the option to explicitly specify the generic argument for `T` at the call site using [GenericArgs], for example, `foo::(1)`. Changing a parameter from either one to the other can constitute a breaking change for the callers of a function, since this changes the number of generic arguments.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Impl trait type", "heading_path": ["Impl trait", "Anonymous type parameters"], "path": "types/impl-trait.md", "url": "https://doc.rust-lang.org/reference/types/impl-trait.html#anonymous-type-parameters", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/types/impl-trait.md#abstract-return-types-2", "text": "The Rust Reference › Impl trait › Abstract return types\n\nThis is often called \"impl Trait in return position\".\nFunctions 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`.\nEach possible return value from the function must resolve to the same concrete type.\n`impl Trait` in return position allows a function to return an unboxed abstract type. This is particularly useful with [closures] 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]:\n```rust\nfn returns_closure() -> Box i32> {\n Box::new(|x| x + 1)\n}\n```\nThis 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:\n```rust\nfn returns_closure() -> impl Fn(i32) -> i32 {\n |x| x + 1\n}\n```\nwhich also avoids the drawbacks of using a boxed trait object.\nSimilarly, 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Impl trait type", "heading_path": ["Impl trait", "Abstract return types"], "path": "types/impl-trait.md", "url": "https://doc.rust-lang.org/reference/types/impl-trait.html#abstract-return-types", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/types/impl-trait.md#return-position-impl-trait-in-traits-and-trait-implementations-3", "text": "The Rust Reference › Impl trait › Return-position `impl Trait` in traits and trait implementations\n\nFunctions in traits may also use `impl Trait` as a syntax for an anonymous associated type.\nEvery `impl Trait` in the return type of an associated function in a trait is desugared to an anonymous associated type. The return type that appears in the implementation's function signature is used to determine the value of the associated type.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Impl trait type", "heading_path": ["Impl trait", "Return-position `impl Trait` in traits and trait implementations"], "path": "types/impl-trait.md", "url": "https://doc.rust-lang.org/reference/types/impl-trait.html#return-position-impl-trait-in-traits-and-trait-implementations", "has_code": false, "code_tags": []}} {"id": "reference/types/impl-trait.md#capturing-4", "text": "The Rust Reference › Impl trait › Capturing\n\nBehind each return-position `impl Trait` abstract type is some hidden concrete type. For this concrete type to use a generic parameter, that generic parameter must be *captured* by the abstract type.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Impl trait type", "heading_path": ["Impl trait", "Capturing"], "path": "types/impl-trait.md", "url": "https://doc.rust-lang.org/reference/types/impl-trait.html#capturing", "has_code": false, "code_tags": []}} {"id": "reference/types/impl-trait.md#automatic-capturing-5", "text": "The Rust Reference › Impl trait › Automatic capturing\n\nReturn-position `impl Trait` abstract types automatically capture all in-scope generic parameters, including generic type, const, and lifetime parameters (including higher-ranked ones).\n[!EDITION-2024]\nBefore the 2024 edition, on free functions and on associated functions and methods of inherent impls, generic lifetime parameters that do not appear in the bounds of the abstract return type are not automatically captured.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Impl trait type", "heading_path": ["Impl trait", "Automatic capturing"], "path": "types/impl-trait.md", "url": "https://doc.rust-lang.org/reference/types/impl-trait.html#automatic-capturing", "has_code": false, "code_tags": []}} {"id": "reference/types/impl-trait.md#precise-capturing-6", "text": "The Rust Reference › Impl trait › Precise capturing\n\nThe set of generic parameters captured by a return-position `impl Trait` abstract type may be explicitly controlled with a [`use<..>` bound]. If present, only the generic parameters listed in the `use<..>` bound will be captured. E.g.:\n```rust\nfn capture<'a, 'b, T>(x: &'a (), y: T) -> impl Sized + use<'a, T> {\n // ~~~~~~~~~~~~~~~~~~~~~~~\n // Captures `'a` and `T` only.\n (x, y)\n}\n```\nCurrently, only one `use<..>` bound may be present in a bounds list, all in-scope type and const generic parameters must be included, and all lifetime parameters that appear in other bounds of the abstract type must be included.\nWithin the `use<..>` bound, any lifetime parameters present must appear before all type and const generic parameters, and the elided lifetime (`'_`) may be present if it is otherwise allowed to appear within the `impl Trait` return type.\nBecause all in-scope type parameters must be included by name, a `use<..>` bound may not be used in the signature of items that use argument-position `impl Trait`, as those items have anonymous type parameters in scope.\nAny `use<..>` bound that is present in an associated function in a trait definition must include all generic parameters of the trait, including the implicit `Self` generic type parameter of the trait.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Impl trait type", "heading_path": ["Impl trait", "Precise capturing"], "path": "types/impl-trait.md", "url": "https://doc.rust-lang.org/reference/types/impl-trait.html#precise-capturing", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/types/impl-trait.md#differences-between-generics-and-impl-trait-in-return-position-7", "text": "The Rust Reference › Impl trait › Differences between generics and `impl Trait` in return position\n\nIn 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.\nThe function:\n```rust\nfn foo() -> T {\n // ...\n}\n```\nallows the caller to determine the return type, `T`, and the function returns that type.\nThe function:\n```rust\nfn foo() -> impl Trait {\n // ...\n}\n```\ndoesn't allow the caller to determine the return type. Instead, the function chooses the return type, but only promises that it will implement `Trait`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Impl trait type", "heading_path": ["Impl trait", "Differences between generics and `impl Trait` in return position"], "path": "types/impl-trait.md", "url": "https://doc.rust-lang.org/reference/types/impl-trait.html#differences-between-generics-and-impl-trait-in-return-position", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/types/impl-trait.md#limitations-8", "text": "The Rust Reference › Impl trait › Limitations\n\n`impl Trait` can only appear as a parameter or return type of a non-`extern` function. It cannot be the type of a `let` binding, field type, or appear inside a type alias.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Impl trait type", "heading_path": ["Impl trait", "Limitations"], "path": "types/impl-trait.md", "url": "https://doc.rust-lang.org/reference/types/impl-trait.html#limitations", "has_code": false, "code_tags": []}} {"id": "reference/types/parameters.md#type-parameters-0", "text": "The Rust Reference › Type parameters\n\nWithin the body of an item that has type parameter declarations, the names of its type parameters are types:\n```rust\nfn to_vec(xs: &[A]) -> Vec {\n if xs.is_empty() {\n return vec![];\n }\n let first: A = xs[0].clone();\n let mut rest: Vec = to_vec(&xs[1..]);\n rest.insert(0, first);\n rest\n}\n```\nHere, `first` has type `A`, referring to `to_vec`'s `A` type parameter; and `rest` has type `Vec`, a vector with element type `A`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type parameters", "heading_path": ["Type parameters"], "path": "types/parameters.md", "url": "https://doc.rust-lang.org/reference/types/parameters.html#type-parameters", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/types/inferred.md#inferred-type-0", "text": "The Rust Reference › Inferred type\n\n```grammar,types\nInferredType -> `_`\n```\nThe inferred type asks the compiler to infer the type if possible based on the surrounding information available.\nThe inferred type is often used in generic arguments:\n```rust\nlet x: Vec<_> = (0..10).collect();\n```\nThe inferred type cannot be used in item signatures.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inferred type", "heading_path": ["Inferred type"], "path": "types/inferred.md", "url": "https://doc.rust-lang.org/reference/types/inferred.html#inferred-type", "has_code": true, "code_tags": ["grammar,types", "rust"]}} {"id": "reference/dynamically-sized-types.md#dynamically-sized-types-0", "text": "The Rust Reference › Dynamically sized types\n\nMost types have a fixed size that is known at compile time and implement the trait `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], [trait objects], and [str] are examples of DSTs.\nSuch types can only be used in certain cases:\n* [Pointer types] to DSTs are sized but have twice the size of pointers to sized types, since they also store *metadata*:\n * Pointers to slices store the number of elements; pointers to `str` store the length in bytes.\n * Pointers to trait objects store a pointer to a vtable.\n * Pointers to a struct or tuple with an [unsized tail] store the same metadata as a pointer to that tail.\n* 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`.\n* Traits may be implemented for DSTs. Unlike with generic type parameters, `Self: ?Sized` is the default in trait definitions.\n* Structs may contain a DST as the last field; this makes the struct itself a DST.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Dynamically sized types", "heading_path": ["Dynamically sized types"], "path": "dynamically-sized-types.md", "url": "https://doc.rust-lang.org/reference/dynamically-sized-types.html#dynamically-sized-types", "has_code": false, "code_tags": []}} {"id": "reference/dynamically-sized-types.md#dynamically-sized-types-1", "text": "The Rust Reference › Dynamically sized types\n\n[Variables], function parameters, [const] items, and [static] items must be `Sized`.\nThe *unsized tail* of a type is the dynamically sized component that the [metadata] of a pointer to the type describes. A [slice] (`[T]`) and a [`str`] are each their own unsized tail, described by a length; a [trait object] (`dyn Trait`) is its own unsized tail, described by a pointer to a vtable. When a struct (per [dynamic-sized.struct-field]) or a tuple has an unsized last field, its unsized tail is the unsized tail of that field. A sized type has no unsized tail.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Dynamically sized types", "heading_path": ["Dynamically sized types"], "path": "dynamically-sized-types.md", "url": "https://doc.rust-lang.org/reference/dynamically-sized-types.html#dynamically-sized-types", "has_code": false, "code_tags": []}} {"id": "reference/type-layout.md#type-layout-0", "text": "The Rust Reference › Type layout\n\nThe 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.\nType layout can be changed with each compilation. Instead of trying to document exactly what is done, we only document what is guaranteed today.\nNote that even types with the same layout can still differ in how they are passed across function boundaries. For function call ABI compatibility of types, see here.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type layout", "heading_path": ["Type layout"], "path": "type-layout.md", "url": "https://doc.rust-lang.org/reference/type-layout.html#type-layout", "has_code": false, "code_tags": []}} {"id": "reference/type-layout.md#size-and-alignment-1", "text": "The Rust Reference › Type layout › Size and alignment\n\nAll values have an alignment and size.\nThe *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`] function.\nThe *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`] function.\nTypes where all values have the same size and alignment, and both are known at compile time, implement the [`Sized`] trait and can be checked with the [`size_of`] and [`align_of`] functions. Types that are not [`Sized`] are known as [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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type layout", "heading_path": ["Type layout", "Size and alignment"], "path": "type-layout.md", "url": "https://doc.rust-lang.org/reference/type-layout.html#size-and-alignment", "has_code": false, "code_tags": []}} {"id": "reference/type-layout.md#primitive-data-layout-2", "text": "The Rust Reference › Type layout › Primitive data layout\n\nThe size of most primitives is given in this table.\n| Type | `size_of::()`|\n|-- |-- |\n| `bool` | 1 |\n| `u8` / `i8` | 1 |\n| `u16` / `i16` | 2 |\n| `u32` / `i32` | 4 |\n| `u64` / `i64` | 8 |\n| `u128` / `i128` | 16 |\n| `usize` / `isize` | See below |\n| `f32` | 4 |\n| `f64` | 8 |\n| `char` | 4 |\n`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.\n`usize` and `isize` have the same size and alignment.\nThe alignment of primitives is platform-specific. In most cases, their alignment is equal to their size, but it may be less. In particular, `i128` and `u128` are often aligned to 4 or 8 bytes even though their size is 16, and on many 32-bit platforms, `i64`, `u64`, and `f64` are only aligned to 4 bytes, not 8.\nAlignment is guaranteed to be the same for fixed-width signed and unsigned integer variants of the same indicated size --- that is, for a given size `N`, `align_of::() == align_of::()`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type layout", "heading_path": ["Type layout", "Primitive data layout"], "path": "type-layout.md", "url": "https://doc.rust-lang.org/reference/type-layout.html#primitive-data-layout", "has_code": false, "code_tags": []}} {"id": "reference/type-layout.md#pointers-and-references-layout-3", "text": "The Rust Reference › Type layout › Pointers and references layout\n\nPointers and references have the same layout. Mutability of the pointer or reference does not change the layout.\nPointers to sized types have the same size and alignment as `usize`.\nPointers to unsized types are sized. The size and alignment of a pointer to an unsized type are each guaranteed to be greater than or equal to those of a pointer to a sized type.\nThough 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type layout", "heading_path": ["Type layout", "Pointers and references layout"], "path": "type-layout.md", "url": "https://doc.rust-lang.org/reference/type-layout.html#pointers-and-references-layout", "has_code": false, "code_tags": []}} {"id": "reference/type-layout.md#array-layout-4", "text": "The Rust Reference › Type layout › Array layout\n\nAn array of `[T; N]` has a size of `size_of::() * 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::()` bytes.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type layout", "heading_path": ["Type layout", "Array layout"], "path": "type-layout.md", "url": "https://doc.rust-lang.org/reference/type-layout.html#array-layout", "has_code": false, "code_tags": []}} {"id": "reference/type-layout.md#slice-layout-5", "text": "The Rust Reference › Type layout › Slice layout\n\nSlices have the same layout as the section of the array they slice.\nThis is about the raw `[T]` type, not pointers (`&[T]`, `Box<[T]>`, etc.) to slices.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type layout", "heading_path": ["Type layout", "Slice layout"], "path": "type-layout.md", "url": "https://doc.rust-lang.org/reference/type-layout.html#slice-layout", "has_code": false, "code_tags": []}} {"id": "reference/type-layout.md#str-layout-6", "text": "The Rust Reference › Type layout › `str` Layout\n\nString slices are a UTF-8 representation of characters that have the same layout as slices of type `[u8]`. A reference `&str` has the same layout as a reference `&[u8]`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type layout", "heading_path": ["Type layout", "`str` Layout"], "path": "type-layout.md", "url": "https://doc.rust-lang.org/reference/type-layout.html#str-layout", "has_code": false, "code_tags": []}} {"id": "reference/type-layout.md#tuple-layout-7", "text": "The Rust Reference › Type layout › Tuple layout\n\nTuples are laid out according to the `Rust` representation.\nThe 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type layout", "heading_path": ["Type layout", "Tuple layout"], "path": "type-layout.md", "url": "https://doc.rust-lang.org/reference/type-layout.html#tuple-layout", "has_code": false, "code_tags": []}} {"id": "reference/type-layout.md#trait-object-layout-8", "text": "The Rust Reference › Type layout › Trait object layout\n\nTrait objects have the same layout as the value the trait object is of.\nThis is about the raw trait object types, not pointers (`&dyn Trait`, `Box`, etc.) to trait objects.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type layout", "heading_path": ["Type layout", "Trait object layout"], "path": "type-layout.md", "url": "https://doc.rust-lang.org/reference/type-layout.html#trait-object-layout", "has_code": false, "code_tags": []}} {"id": "reference/type-layout.md#closure-layout-9", "text": "The Rust Reference › Type layout › Closure layout\n\nClosures have no layout guarantees.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type layout", "heading_path": ["Type layout", "Closure layout"], "path": "type-layout.md", "url": "https://doc.rust-lang.org/reference/type-layout.html#closure-layout", "has_code": false, "code_tags": []}} {"id": "reference/type-layout.md#representations-10", "text": "The Rust Reference › Type layout › Representations\n\nAll user-defined composite types (`struct`s, `enum`s, and `union`s) have a *representation* that specifies what the layout is for the type.\nThe possible representations for a type are:\n- [`Rust`] (default)\n- [`C`]\n- The [primitive representations]\n- [`transparent`]\nThe representation of a type can be changed by applying the `repr` attribute to it. The following example shows a struct with a `C` representation.\n```rust\n#[repr(C)]\nstruct ThreeInts {\n first: i16,\n second: i8,\n third: i32\n}\n```\nThe 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.\n```rust\n// Default representation, alignment lowered to 2.\n#[repr(packed(2))]\nstruct PackedStruct {\n first: i16,\n second: i8,\n third: i32\n}\n\n// C representation, alignment raised to 8\n#[repr(C, align(8))]\nstruct AlignedStruct {\n first: i16,\n second: i8,\n third: i32\n}\n```\nAs 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` and `Foo` both have the same representation.\nThe 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 `Rust` representation will not change the layout of `Inner`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type layout", "heading_path": ["Type layout", "Representations"], "path": "type-layout.md", "url": "https://doc.rust-lang.org/reference/type-layout.html#representations", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/type-layout.md#the-rust-representation-11", "text": "The Rust Reference › Type layout › Representations › The `Rust` representation\n\nThe `Rust` representation is the default representation for nominal types without a `repr` attribute. Using this representation explicitly through a `repr` attribute is guaranteed to be the same as omitting the attribute entirely.\nThe only data layout guarantees made by this representation are those required for soundness. These are:\n 1. The offset of a field is divisible by that field's alignment.\n 2. The alignment of the type is at least the maximum alignment of its fields.\nFor [structs], it is further guaranteed that the fields do not overlap. That is, 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.\nBe aware that this 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.\nFor [structs] with no fields or where all fields are [zero sized], it is further guaranteed that the structs are themselves [zero sized].\nFor [enums] (without a [primitive representation] specified) with a single [field-struct-like variant], a single [unit-struct-like variant], or a single [tuple-struct-like variant] and where the struct-like thing has no fields or where all of the fields are [zero sized], the enums themselves are [zero sized].\nThere are no other guarantees of data layout made by this representation.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type layout", "heading_path": ["Type layout", "Representations", "The `Rust` representation"], "path": "type-layout.md", "url": "https://doc.rust-lang.org/reference/type-layout.html#the-rust-representation", "has_code": false, "code_tags": []}} {"id": "reference/type-layout.md#reprc-structs-12", "text": "The Rust Reference › Type layout › Representations › The `C` representation › `#[repr(C)]` Structs\n\nThe `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.\nBecause of this dual purpose, it is possible to create types that are not useful for interfacing with the C programming language.\nThis representation can be applied to structs, unions, and enums. The exception is [zero-variant enums] for which the `C` representation is an error.\nThe alignment of the struct is the alignment of the most-aligned field in it, or one if there are no fields.\nThe size and offset of fields is determined by the following algorithm.\nStart with a current offset of 0 bytes.\nFor 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.\nFinally, the size of the struct is the current offset rounded up to the nearest multiple of the struct's alignment.\nHere is the algorithm:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type layout", "heading_path": ["Type layout", "Representations", "The `C` representation", "`#[repr(C)]` Structs"], "path": "type-layout.md", "url": "https://doc.rust-lang.org/reference/type-layout.html#reprc-structs", "has_code": false, "code_tags": []}} {"id": "reference/type-layout.md#reprc-structs-13", "text": "The Rust Reference › Type layout › Representations › The `C` representation › `#[repr(C)]` Structs\n\n```rust\nstruct Field {\n alignment: usize,\n size: usize,\n}\nstruct MockLayout {\n fields: Vec,\n field_offsets: Vec,\n alignment: usize,\n size: usize,\n}\n\nimpl MockLayout {\n /// Returns the amount of padding needed after `offset` to ensure that the\n /// following address will be aligned to `alignment`.\n fn padding_needed_for(offset: usize, alignment: usize) -> usize {\n let misalignment = offset % alignment;\n if misalignment > 0 {\n // Round up to next multiple of `alignment`.\n alignment - misalignment\n } else {\n // Already a multiple of `alignment`.\n 0\n }\n }\n\n /// Fields must be in declaration order. By this point, they have already\n /// had their alignments and sizes calculated.\n pub fn from_fields(fields: Vec) -> Self {\n // \"The alignment of the struct is the alignment of the most-aligned\n // field in it, or one if there are no fields.\"\n let alignment = fields\n .iter()\n .map(|field| field.alignment)\n .max()\n .unwrap_or(1);\n\n // \"Start with a current offset of 0 bytes.\"\n let mut current_offset = 0;\n\n let mut field_offsets = vec![];\n for field in &fields {\n // \"If the current offset is not a multiple of the field's\n // alignment, then add padding bytes to the current offset until it\n // is a multiple of the field's alignment.\"\n current_offset += Self::padding_needed_for(\n current_offset,\n field.alignment\n );\n\n // \"The offset for the field is what the current offset is now.\"\n field_offsets.push(current_offset);\n\n // \"Then increase the current offset by the size of the field.\"\n current_offset += field.size;\n }\n\n // \"Finally, the size of the struct is the current offset rounded up to\n // the nearest multiple of the struct's alignment.\"\n let size = current_offset + Self::padding_needed_for(\n current_offset,\n alignment\n );\n\n MockLayout { fields, field_offsets, alignment, size }\n }\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type layout", "heading_path": ["Type layout", "Representations", "The `C` representation", "`#[repr(C)]` Structs"], "path": "type-layout.md", "url": "https://doc.rust-lang.org/reference/type-layout.html#reprc-structs", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/type-layout.md#reprc-unions-14", "text": "The Rust Reference › Type layout › Representations › The `C` representation › `#[repr(C)]` Unions\n\nThis mock implementation uses a naive algorithm that ignores overflow issues for the sake of clarity. To perform memory layout computations in actual code, use [`Layout`].\nThis 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.\nA 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.\nThe 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. Each field lives at byte offset 0 from the beginning of the union.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type layout", "heading_path": ["Type layout", "Representations", "The `C` representation", "`#[repr(C)]` Unions"], "path": "type-layout.md", "url": "https://doc.rust-lang.org/reference/type-layout.html#reprc-unions", "has_code": false, "code_tags": []}} {"id": "reference/type-layout.md#reprc-field-less-enums-15", "text": "The Rust Reference › Type layout › Representations › The `C` representation › `#[repr(C)]` Field-less Enums\n\n```rust\n#[repr(C)]\nunion Union {\n f1: u16,\n f2: [u8; 4],\n}\n\nassert_eq!(std::mem::size_of::(), 4); // From f2\nassert_eq!(std::mem::align_of::(), 2); // From f1\n\nassert_eq!(std::mem::offset_of!(Union, f1), 0);\nassert_eq!(std::mem::offset_of!(Union, f2), 0);\n\n#[repr(C)]\nunion SizeRoundedUp {\n a: u32,\n b: [u16; 3],\n}\n\nassert_eq!(std::mem::size_of::(), 8); // Size of 6 from b,\n // rounded up to 8 from\n // alignment of a.\nassert_eq!(std::mem::align_of::(), 4); // From a\n\nassert_eq!(std::mem::offset_of!(SizeRoundedUp, a), 0);\nassert_eq!(std::mem::offset_of!(SizeRoundedUp, b), 0);\n```\nFor [field-less enums], the `C` representation has the size and alignment of the default `enum` size and alignment for the target platform's C ABI.\nThe 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type layout", "heading_path": ["Type layout", "Representations", "The `C` representation", "`#[repr(C)]` Field-less Enums"], "path": "type-layout.md", "url": "https://doc.rust-lang.org/reference/type-layout.html#reprc-field-less-enums", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/type-layout.md#reprc-enums-with-fields-16", "text": "The Rust Reference › Type layout › Representations › The `C` representation › `#[repr(C)]` Enums With Fields\n\nThere are crucial differences between an `enum` in the C language and Rust's [field-less enums] 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] can only legally hold the discriminant values, everything else is [undefined behavior]. Therefore, using a field-less enum in FFI to model a C `enum` is often wrong.\nThe representation of a `repr(C)` enum with fields is a `repr(C)` struct with two fields, also called a \"tagged union\" in C:\n- a `repr(C)` version of the enum with all fields removed (\"the tag\")\n- a `repr(C)` union of `repr(C)` structs for the fields of each variant that had them (\"the payload\")\nDue 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type layout", "heading_path": ["Type layout", "Representations", "The `C` representation", "`#[repr(C)]` Enums With Fields"], "path": "type-layout.md", "url": "https://doc.rust-lang.org/reference/type-layout.html#reprc-enums-with-fields", "has_code": false, "code_tags": []}} {"id": "reference/type-layout.md#reprc-enums-with-fields-17", "text": "The Rust Reference › Type layout › Representations › The `C` representation › `#[repr(C)]` Enums With Fields\n\n```rust\n// This Enum has the same representation as ...\n#[repr(C)]\nenum MyEnum {\n A(u32),\n B(f32, u64),\n C { x: u32, y: u8 },\n D,\n }\n\n// ... this struct.\n#[repr(C)]\nstruct MyEnumRepr {\n tag: MyEnumDiscriminant,\n payload: MyEnumFields,\n}\n\n// This is the discriminant enum.\n#[repr(C)]\nenum MyEnumDiscriminant { A, B, C, D }\n\n// This is the variant union.\n#[repr(C)]\nunion MyEnumFields {\n A: MyAFields,\n B: MyBFields,\n C: MyCFields,\n D: MyDFields,\n}\n\n#[repr(C)]\n#[derive(Copy, Clone)]\nstruct MyAFields(u32);\n\n#[repr(C)]\n#[derive(Copy, Clone)]\nstruct MyBFields(f32, u64);\n\n#[repr(C)]\n#[derive(Copy, Clone)]\nstruct MyCFields { x: u32, y: u8 }\n\n// This struct could be omitted (it is a zero-sized type), and it must be in\n// C/C++ headers.\n#[repr(C)]\n#[derive(Copy, Clone)]\nstruct MyDFields;\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type layout", "heading_path": ["Type layout", "Representations", "The `C` representation", "`#[repr(C)]` Enums With Fields"], "path": "type-layout.md", "url": "https://doc.rust-lang.org/reference/type-layout.html#reprc-enums-with-fields", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/type-layout.md#primitive-representation-of-enums-with-fields-18", "text": "The Rust Reference › Type layout › Representations › Primitive representations › Primitive representation of enums with fields\n\nThe *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`.\nPrimitive 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] to have a primitive representation. Combining two primitive representations together is an error.\nFor [field-less enums], 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.\nThe 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.\nThis 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`).", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type layout", "heading_path": ["Type layout", "Representations", "Primitive representations", "Primitive representation of enums with fields"], "path": "type-layout.md", "url": "https://doc.rust-lang.org/reference/type-layout.html#primitive-representation-of-enums-with-fields", "has_code": false, "code_tags": []}} {"id": "reference/type-layout.md#combining-primitive-representations-of-enums-with-fields-and-reprc-19", "text": "The Rust Reference › Type layout › Representations › Primitive representations › Combining primitive representations of enums with fields and `#[repr(C)]`\n\n```rust\n// This enum has the same representation as ...\n#[repr(u8)]\nenum MyEnum {\n A(u32),\n B(f32, u64),\n C { x: u32, y: u8 },\n D,\n }\n\n// ... this union.\n#[repr(C)]\nunion MyEnumRepr {\n A: MyVariantA,\n B: MyVariantB,\n C: MyVariantC,\n D: MyVariantD,\n}\n\n// This is the discriminant enum.\n#[repr(u8)]\n#[derive(Copy, Clone)]\nenum MyEnumDiscriminant { A, B, C, D }\n\n#[repr(C)]\n#[derive(Clone, Copy)]\nstruct MyVariantA(MyEnumDiscriminant, u32);\n\n#[repr(C)]\n#[derive(Clone, Copy)]\nstruct MyVariantB(MyEnumDiscriminant, f32, u64);\n\n#[repr(C)]\n#[derive(Clone, Copy)]\nstruct MyVariantC { tag: MyEnumDiscriminant, x: u32, y: u8 }\n\n#[repr(C)]\n#[derive(Clone, Copy)]\nstruct MyVariantD(MyEnumDiscriminant);\n```\nFor 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)`] 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.\nThe discriminant enum from the example earlier then becomes:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type layout", "heading_path": ["Type layout", "Representations", "Primitive representations", "Combining primitive representations of enums with fields and `#[repr(C)]`"], "path": "type-layout.md", "url": "https://doc.rust-lang.org/reference/type-layout.html#combining-primitive-representations-of-enums-with-fields-and-reprc", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/type-layout.md#combining-primitive-representations-of-enums-with-fields-and-reprc-20", "text": "The Rust Reference › Type layout › Representations › Primitive representations › Combining primitive representations of enums with fields and `#[repr(C)]`\n\n```rust\n#[repr(C, u8)] // `u8` was added\nenum MyEnum {\n A(u32),\n B(f32, u64),\n C { x: u32, y: u8 },\n D,\n }\n\n// ...\n\n#[repr(u8)] // So `u8` is used here instead of `C`\nenum MyEnumDiscriminant { A, B, C, D }\n\n// ...\n```\nFor 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.\nUsing a primitive representation in addition to `repr(C)` can change the size of an enum from the `repr(C)` form:\n```rust\n#[repr(C)]\nenum EnumC {\n Variant0(u8),\n Variant1,\n}\n\n#[repr(C, u8)]\nenum Enum8 {\n Variant0(u8),\n Variant1,\n}\n\n#[repr(C, u16)]\nenum Enum16 {\n Variant0(u8),\n Variant1,\n}\n\n// The size of the C representation is platform dependent\nassert_eq!(std::mem::size_of::(), 8);\n// One byte for the discriminant and one byte for the value in Enum8::Variant0\nassert_eq!(std::mem::size_of::(), 2);\n// Two bytes for the discriminant and one byte for the value in Enum16::Variant0\n// plus one byte of padding.\nassert_eq!(std::mem::size_of::(), 4);\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type layout", "heading_path": ["Type layout", "Representations", "Primitive representations", "Combining primitive representations of enums with fields and `#[repr(C)]`"], "path": "type-layout.md", "url": "https://doc.rust-lang.org/reference/type-layout.html#combining-primitive-representations-of-enums-with-fields-and-reprc", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/type-layout.md#the-alignment-modifiers-21", "text": "The Rust Reference › Type layout › Representations › The alignment modifiers\n\nThe `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). On their own, `align` and `packed` do not provide guarantees about the order of fields in the layout of a struct or the layout of an enum variant, although they may be combined with representations (such as `C`) which do provide such guarantees.\nThe 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.\nFor `align`, if the specified alignment is less than the alignment of the type without the `align` modifier, then the alignment is unaffected.\nFor `packed`, if the specified alignment is greater than the type's alignment without the `packed` modifier, then the alignment and layout is unaffected.\nThe 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.\nInter-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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type layout", "heading_path": ["Type layout", "Representations", "The alignment modifiers"], "path": "type-layout.md", "url": "https://doc.rust-lang.org/reference/type-layout.html#the-alignment-modifiers", "has_code": false, "code_tags": []}} {"id": "reference/type-layout.md#the-alignment-modifiers-22", "text": "The Rust Reference › Type layout › Representations › The alignment modifiers\n\nThe `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 [`Rust`] and [`C`] representations.\nThe `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.\nReferences to unaligned fields are not allowed because it is [undefined behavior]. When fields are unaligned due to an alignment modifier, consider the following options for using references and dereferences:\n```rust\n#[repr(packed)]\nstruct Packed {\n f1: u8,\n f2: u16,\n}\nlet mut e = Packed { f1: 1, f2: 2 };\n// Instead of creating a reference to a field, copy the value to a local variable.\nlet x = e.f2;\n// Or in situations like `println!` which creates a reference, use braces\n// to change it to a copy of the value.\nprintln!(\"{}\", {e.f2});\n// Or if you need a pointer, use the unaligned methods for reading and writing\n// instead of dereferencing the pointer directly.\nlet ptr: *const u16 = &raw const e.f2;\nlet value = unsafe { ptr.read_unaligned() };\nlet mut_ptr: *mut u16 = &raw mut e.f2;\nunsafe { mut_ptr.write_unaligned(3) }\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type layout", "heading_path": ["Type layout", "Representations", "The alignment modifiers"], "path": "type-layout.md", "url": "https://doc.rust-lang.org/reference/type-layout.html#the-alignment-modifiers", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/type-layout.md#the-transparent-representation-23", "text": "The Rust Reference › Type layout › Representations › The `transparent` representation\n\nThe `transparent` representation can only be used on a `struct` or an `enum` with a single variant that has:\n- any number of fields with size 0 and alignment 1 (e.g. [`PhantomData`]), and\n- at most one other field.\nStructs and enums with this representation have the same layout and ABI as the only non-size 0 non-alignment 1 field, if present, or unit otherwise.\nThis 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.\nBecause this representation delegates type layout to another type, it cannot be used with any other representation.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type layout", "heading_path": ["Type layout", "Representations", "The `transparent` representation"], "path": "type-layout.md", "url": "https://doc.rust-lang.org/reference/type-layout.html#the-transparent-representation", "has_code": false, "code_tags": []}} {"id": "reference/interior-mutability.md#interior-mutability-0", "text": "The Rust Reference › Interior mutability\n\nSometimes a type needs to be mutated while having multiple aliases. In Rust this is achieved using a pattern called _interior mutability_.\nA type has interior mutability if its internal state can be changed through a [shared reference] to it.\nThis goes against the usual requirement that the value pointed to by a shared reference is not mutated.\n[`std::cell::UnsafeCell`] type is the only allowed way to disable this requirement. When `UnsafeCell` is immutably aliased, it is still safe to mutate, or obtain a mutable reference to, the `T` it contains.\nAs with all other types, it is undefined behavior to have multiple `&mut UnsafeCell` aliases.\nOther types with interior mutability can be created by using `UnsafeCell` as a field. The standard library provides a variety of types that provide safe interior mutability APIs.\nFor example, [`std::cell::RefCell`] uses run-time borrow checks to ensure the usual rules around multiple references.\nThe [`std::sync::atomic`] module contains types that wrap a value that is only accessed with atomic operations, allowing the value to be shared and mutated across threads.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Interior mutability", "heading_path": ["Interior mutability"], "path": "interior-mutability.md", "url": "https://doc.rust-lang.org/reference/interior-mutability.html#interior-mutability", "has_code": false, "code_tags": []}} {"id": "reference/subtyping.md#subtyping-and-variance-0", "text": "The Rust Reference › Subtyping and variance\n\nSubtyping is implicit and can occur at any stage in type checking or inference.\nSubtyping 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.\nConsider the following example: string literals always have `'static` lifetime. Nevertheless, we can assign `s` to `t`:\n```rust\nfn bar<'a>() {\n let s: &'static str = \"hi\";\n let t: &'a str = s;\n}\n```\nSince `'static` outlives the lifetime parameter `'a`, `&'static str` is a subtype of `&'a str`.\n[Higher-ranked] [function pointers] and [trait objects] have another subtype relation. They are subtypes of types that are given by substitutions of the higher-ranked lifetimes. Some examples:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Subtyping and variance", "heading_path": ["Subtyping and variance"], "path": "subtyping.md", "url": "https://doc.rust-lang.org/reference/subtyping.html#subtyping-and-variance", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/subtyping.md#subtyping-and-variance-1", "text": "The Rust Reference › Subtyping and variance\n\n```rust\n// Here 'a is substituted for 'static\nlet subtype: &(for<'a> fn(&'a i32) -> &'a i32) = &((|x| x) as fn(&_) -> &_);\nlet supertype: &(fn(&'static i32) -> &'static i32) = subtype;\n\n// This works similarly for trait objects\nlet subtype: &(dyn for<'a> Fn(&'a i32) -> &'a i32) = &|x| x;\nlet supertype: &(dyn Fn(&'static i32) -> &'static i32) = subtype;\n\n// We can also substitute one higher-ranked lifetime for another\nlet subtype: &(for<'a, 'b> fn(&'a i32, &'b i32)) = &((|x, y| {}) as fn(&_, &_));\nlet supertype: &for<'c> fn(&'c i32, &'c i32) = subtype;\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Subtyping and variance", "heading_path": ["Subtyping and variance"], "path": "subtyping.md", "url": "https://doc.rust-lang.org/reference/subtyping.html#subtyping-and-variance", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/subtyping.md#variance-2", "text": "The Rust Reference › Subtyping and variance › Variance\n\nVariance 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.\n* `F` is *covariant* over `T` if `T` being a subtype of `U` implies that `F` is a subtype of `F` (subtyping \"passes through\")\n* `F` is *contravariant* over `T` if `T` being a subtype of `U` implies that `F` is a subtype of `F`\n* `F` is *invariant* over `T` otherwise (no subtyping relation can be derived)\nVariance of types is automatically determined as follows\n| Type | Variance in `'a` | Variance in `T` |\n|-------------------------------|-------------------|-------------------|\n| `&'a T` | covariant | covariant |\n| `&'a mut T` | covariant | invariant |\n| `*const T` | | covariant |\n| `*mut T` | | invariant |\n| `[T]` and `[T; n]` | | covariant |\n| `fn() -> T` | | covariant |\n| `fn(T) -> ()` | | contravariant |\n| `std::cell::UnsafeCell` | | invariant |\n| `std::marker::PhantomData` | | covariant |\n| `dyn Trait + 'a` | covariant | invariant |", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Subtyping and variance", "heading_path": ["Subtyping and variance", "Variance"], "path": "subtyping.md", "url": "https://doc.rust-lang.org/reference/subtyping.html#variance", "has_code": false, "code_tags": []}} {"id": "reference/subtyping.md#variance-3", "text": "The Rust Reference › Subtyping and variance › Variance\n\nThe 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`.\n```rust\nuse std::cell::UnsafeCell;\nstruct Variance<'a, 'b, 'c, T, U: 'a> {\n x: &'a U, // This makes `Variance` covariant in 'a, and would\n // make it covariant in U, but U is used later\n y: *const T, // Covariant in T\n z: UnsafeCell<&'b f64>, // Invariant in 'b\n w: *mut U, // Invariant in U, makes the whole struct invariant\n\n f: fn(&'c ()) -> &'c () // Both co- and contravariant, makes 'c invariant\n // in the struct.\n}\n```\nWhen used outside of an `struct`, `enum`, or `union`, the variance for parameters is checked at each location separately.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Subtyping and variance", "heading_path": ["Subtyping and variance", "Variance"], "path": "subtyping.md", "url": "https://doc.rust-lang.org/reference/subtyping.html#variance", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/subtyping.md#variance-4", "text": "The Rust Reference › Subtyping and variance › Variance\n\n```rust\nfn generic_tuple<'short, 'long: 'short>(\n // 'long is used inside of a tuple in both a co- and invariant position.\n x: (&'long u32, UnsafeCell<&'long u32>),\n) {\n // As the variance at these positions is computed separately,\n // we can freely shrink 'long in the covariant position.\n let _: (&'short u32, UnsafeCell<&'long u32>) = x;\n}\n\nfn takes_fn_ptr<'short, 'middle: 'short>(\n // 'middle is used in both a co- and contravariant position.\n f: fn(&'middle ()) -> &'middle (),\n) {\n // As the variance at these positions is computed separately,\n // we can freely shrink 'middle in the covariant position\n // and extend it in the contravariant position.\n let _: fn(&'static ()) -> &'short () = f;\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Subtyping and variance", "heading_path": ["Subtyping and variance", "Variance"], "path": "subtyping.md", "url": "https://doc.rust-lang.org/reference/subtyping.html#variance", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/trait-bounds.md#trait-and-lifetime-bounds-0", "text": "The Rust Reference › Trait and lifetime bounds\n\n```grammar,miscellaneous\nBounds -> Bound ( `+` Bound )* `+`?\n\nBound -> Lifetime | TraitBound | UseBound\n\nTraitBound ->\n ( `?` | ForLifetimes )? TypePath\n | `(` ( `?` | ForLifetimes )? TypePath `)`\n\nLifetimeBounds -> ( Lifetime `+` )* Lifetime?\n\nLifetime ->\n LIFETIME_OR_LABEL\n | `'static`\n | `'_`\n\nUseBound -> `use` UseBoundGenericArgs\n\nUseBoundGenericArgs ->\n `<` `>`\n | `<` ( UseBoundGenericArg `,`)* UseBoundGenericArg `,`? `>`\n\nUseBoundGenericArg ->\n Lifetime\n | IDENTIFIER\n | `Self`\n```\n[Trait] and lifetime bounds provide a way for generic items to restrict which types and lifetimes are used as their parameters. Bounds can be provided on any type in a [where clause]. There are also shorter forms for certain common cases:\n* Bounds written after declaring a generic parameter: `fn f() {}` is the same as `fn f() where A: Copy {}`.\n* In trait declarations as [supertraits]: `trait Circle : Shape {}` is equivalent to `trait Circle where Self : Shape {}`.\n* In trait declarations as bounds on [associated types]: `trait A { type B: Copy; }` is equivalent to `trait A where Self::B: Copy { type B; }`.\nBounds 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`", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Trait and lifetime bounds", "heading_path": ["Trait and lifetime bounds"], "path": "trait-bounds.md", "url": "https://doc.rust-lang.org/reference/trait-bounds.html#trait-and-lifetime-bounds", "has_code": true, "code_tags": ["grammar,miscellaneous"]}} {"id": "reference/trait-bounds.md#trait-and-lifetime-bounds-1", "text": "The Rust Reference › Trait and lifetime bounds\n\n* 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.\n* Associated types from `Trait` can be used.\n* Generic functions and types with a `T: Trait` bounds can be used with `Ty` being used for `T`.\n```rust\ntrait Shape {\n fn draw(&self, surface: Surface);\n fn name() -> &'static str;\n}\n\nfn draw_twice(surface: Surface, sh: T) {\n sh.draw(surface); // Can call method because T: Shape\n sh.draw(surface);\n}\n\nfn copy_and_draw_twice(surface: Surface, sh: T) where T: Shape {\n let shape_copy = sh; // doesn't move sh because T: Copy\n draw_twice(surface, sh); // Can use generic function because T: Shape\n}\n\nstruct Figure(S, S);\n\nfn name_figure(\n figure: Figure, // Type Figure is well-formed because U: Shape\n) {\n println!(\n \"Figure of two {}\",\n U::name(), // Can use associated function\n );\n}\n```\nBounds that don't use the item's parameters or [higher-ranked lifetimes] are checked when the item is defined. It is an error for such a bound to be false.\n[`Copy`], [`Clone`], and [`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], or [slice]. It is an error to have `Sized` as a bound on a trait object or slice.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Trait and lifetime bounds", "heading_path": ["Trait and lifetime bounds"], "path": "trait-bounds.md", "url": "https://doc.rust-lang.org/reference/trait-bounds.html#trait-and-lifetime-bounds", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/trait-bounds.md#trait-and-lifetime-bounds-2", "text": "The Rust Reference › Trait and lifetime bounds\n\n```rust,compile_fail\nstruct A<'a, T>\nwhere\n i32: Default, // Allowed, but not useful\n i32: Iterator, // Error: `i32` is not an iterator\n &'a mut T: Copy, // (at use) Error: the trait bound is not satisfied\n [T]: Sized, // (at use) Error: size cannot be known at compilation\n{\n f: &'a T,\n}\nstruct UsesA<'a, T>(A<'a, T>);\n```\nTrait and lifetime bounds are also used to name [trait objects].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Trait and lifetime bounds", "heading_path": ["Trait and lifetime bounds"], "path": "trait-bounds.md", "url": "https://doc.rust-lang.org/reference/trait-bounds.html#trait-and-lifetime-bounds", "has_code": true, "code_tags": ["rust,compile_fail"]}} {"id": "reference/trait-bounds.md#sized-3", "text": "The Rust Reference › Trait and lifetime bounds › `?Sized`\n\n`?` is only used to relax the implicit [`Sized`] trait bound for [type parameters] or [associated types]. `?Sized` may not be used as a bound for other types.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Trait and lifetime bounds", "heading_path": ["Trait and lifetime bounds", "`?Sized`"], "path": "trait-bounds.md", "url": "https://doc.rust-lang.org/reference/trait-bounds.html#sized", "has_code": false, "code_tags": []}} {"id": "reference/trait-bounds.md#lifetime-bounds-4", "text": "The Rust Reference › Trait and lifetime bounds › Lifetime bounds\n\nLifetime bounds can be applied to types or to other lifetimes.\nThe 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.\n```rust\nfn f<'a, 'b>(x: &'a i32, mut y: &'b i32) where 'a: 'b {\n y = x; // &'a i32 is a subtype of &'b i32 because 'a: 'b\n let r: &'b &'a i32 = &&0; // &'b &'a i32 is well formed because 'a: 'b\n}\n```\n`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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Trait and lifetime bounds", "heading_path": ["Trait and lifetime bounds", "Lifetime bounds"], "path": "trait-bounds.md", "url": "https://doc.rust-lang.org/reference/trait-bounds.html#lifetime-bounds", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/trait-bounds.md#higher-ranked-trait-bounds-5", "text": "The Rust Reference › Trait and lifetime bounds › Higher-ranked trait bounds\n\n```grammar,miscellaneous\nForLifetimes -> `for` GenericParams\n```\nTrait 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` would require an implementation like\n```rust\nimpl<'a> PartialEq for &'a T {\n // ...\n}\n```\nand could then be used to compare a `&'a T` with any lifetime to an `i32`.\nOnly a higher-ranked bound can be used here, because the lifetime of the reference is shorter than any possible lifetime parameter on the function:\n```rust\nfn call_on_ref_zero(f: F) where for<'a> F: Fn(&'a i32) {\n let zero = 0;\n f(&zero);\n}\n```\nHigher-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.\n```rust\nfn call_on_ref_zero(f: F) where F: for<'a> Fn(&'a i32) {\n let zero = 0;\n f(&zero);\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Trait and lifetime bounds", "heading_path": ["Trait and lifetime bounds", "Higher-ranked trait bounds"], "path": "trait-bounds.md", "url": "https://doc.rust-lang.org/reference/trait-bounds.html#higher-ranked-trait-bounds", "has_code": true, "code_tags": ["grammar,miscellaneous", "rust"]}} {"id": "reference/trait-bounds.md#implied-bounds-6", "text": "The Rust Reference › Trait and lifetime bounds › Implied bounds\n\nLifetime bounds required for types to be well-formed are sometimes inferred.\n```rust\nfn requires_t_outlives_a<'a, T>(x: &'a T) {}\n```\nThe type parameter `T` is required to outlive `'a` for the type `&'a T` to be well-formed. This is inferred because the function signature contains the type `&'a T` which is only valid if `T: 'a` holds.\nImplied bounds are added for all parameters and outputs of functions. Inside of `requires_t_outlives_a` you can assume `T: 'a` to hold even if you don't explicitly specify this:\n```rust\nfn requires_t_outlives_a_not_implied<'a, T: 'a>() {}\n\nfn requires_t_outlives_a<'a, T>(x: &'a T) {\n // This compiles, because `T: 'a` is implied by\n // the reference type `&'a T`.\n requires_t_outlives_a_not_implied::<'a, T>();\n}\n```\n```rust,compile_fail,E0309\nfn not_implied<'a, T>() {\n // This errors, because `T: 'a` is not implied by\n // the function signature.\n requires_t_outlives_a_not_implied::<'a, T>();\n}\n```\nOnly lifetime bounds are implied, trait bounds still have to be explicitly added. The following example therefore causes an error:\n```rust,compile_fail,E0277\nuse std::fmt::Debug;\nstruct IsDebug(T);\n// error[E0277]: `T` doesn't implement `Debug`\nfn doesnt_specify_t_debug(x: IsDebug) {}\n```\nLifetime bounds are also inferred for type definitions and impl blocks for any type:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Trait and lifetime bounds", "heading_path": ["Trait and lifetime bounds", "Implied bounds"], "path": "trait-bounds.md", "url": "https://doc.rust-lang.org/reference/trait-bounds.html#implied-bounds", "has_code": true, "code_tags": ["rust", "rust,compile_fail,E0277", "rust,compile_fail,E0309"]}} {"id": "reference/trait-bounds.md#implied-bounds-7", "text": "The Rust Reference › Trait and lifetime bounds › Implied bounds\n\n```rust\nstruct Struct<'a, T> {\n // This requires `T: 'a` to be well-formed\n // which is inferred by the compiler.\n field: &'a T,\n}\n\nenum Enum<'a, T> {\n // This requires `T: 'a` to be well-formed,\n // which is inferred by the compiler.\n //\n // Note that `T: 'a` is required even when only\n // using `Enum::OtherVariant`.\n SomeVariant(&'a T),\n OtherVariant,\n}\n\ntrait Trait<'a, T: 'a> {}\n\n// This would error because `T: 'a` is not implied by any type\n// in the impl header.\n// impl<'a, T> Trait<'a, T> for () {}\n\n// This compiles as `T: 'a` is implied by the self type `&'a T`.\nimpl<'a, T> Trait<'a, T> for &'a T {}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Trait and lifetime bounds", "heading_path": ["Trait and lifetime bounds", "Implied bounds"], "path": "trait-bounds.md", "url": "https://doc.rust-lang.org/reference/trait-bounds.html#implied-bounds", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/trait-bounds.md#use-bounds-8", "text": "The Rust Reference › Trait and lifetime bounds › Use bounds\n\nCertain bounds lists may include a `use<..>` bound to control which generic parameters are captured by the `impl Trait` [abstract return type]. See [precise capturing] for more details.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Trait and lifetime bounds", "heading_path": ["Trait and lifetime bounds", "Use bounds"], "path": "trait-bounds.md", "url": "https://doc.rust-lang.org/reference/trait-bounds.html#use-bounds", "has_code": false, "code_tags": []}} {"id": "reference/type-coercions.md#type-coercions-0", "text": "The Rust Reference › Type coercions\n\n**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.\nAny conversions allowed by coercion can also be explicitly performed by the [type cast operator], `as`.\nCoercions are originally defined in [RFC 401] and expanded upon in [RFC 1558].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type coercions", "heading_path": ["Type coercions"], "path": "type-coercions.md", "url": "https://doc.rust-lang.org/reference/type-coercions.html#type-coercions", "has_code": false, "code_tags": []}} {"id": "reference/type-coercions.md#coercion-sites-1", "text": "The Rust Reference › Type coercions › Coercion sites\n\nA 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:\n* `let` statements where an explicit type is given.\n For example, `&mut 42` is coerced to have type `&i8` in the following:\n```rust\n let _: &i8 = &mut 42;\n```\n* `static` and `const` item declarations (similar to `let` statements).\n* Arguments for function calls\n The value being coerced is the actual parameter, and it is coerced to the type of the formal parameter.\n For example, `&mut 42` is coerced to have type `&i8` in the following:\n```rust\n fn bar(_: &i8) { }\n\n fn main() {\n bar(&mut 42);\n }\n```\n For method calls, the receiver (`self` parameter) type is coerced differently, see the documentation on [method-call expressions] for details.\n* Instantiations of struct, union, or enum variant fields\n For example, `&mut 42` is coerced to have type `&i8` in the following:\n```rust\n struct Foo<'a> { x: &'a i8 }\n\n fn main() {\n Foo { x: &mut 42 };\n }\n```\n* Function results—either the final line of a block if it is not semicolon-terminated or any expression in a `return` statement\n For example, `x` is coerced to have type `&dyn Display` in the following:\n```rust\n use std::fmt::Display;\n fn foo(x: &u32) -> &dyn Display {\n x\n }\n```\n* Assigned value operands in assignment expressions", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type coercions", "heading_path": ["Type coercions", "Coercion sites"], "path": "type-coercions.md", "url": "https://doc.rust-lang.org/reference/type-coercions.html#coercion-sites", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/type-coercions.md#coercion-sites-2", "text": "The Rust Reference › Type coercions › Coercion sites\n\nFor example, `y` is coerced to have type `&i8` in the following:\n```rust\n let mut x = &0i8;\n let y = &mut 42i8;\n x = y;\n```\nIf 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:\n* 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`.\n* 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`.\n* 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`.\n* Parenthesized sub-expressions (`(e)`): if the expression has type `U`, then the sub-expression is a coercion site to `U`.\n* 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type coercions", "heading_path": ["Type coercions", "Coercion sites"], "path": "type-coercions.md", "url": "https://doc.rust-lang.org/reference/type-coercions.html#coercion-sites", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/type-coercions.md#coercion-types-3", "text": "The Rust Reference › Type coercions › Coercion types\n\nCoercion is allowed between the following types:\n* `T` to `U` if `T` is a [subtype] of `U` (*reflexive case*)\n* `T_1` to `T_3` where `T_1` coerces to `T_2` and `T_2` coerces to `T_3` (*transitive case*)\n Note that this is not fully supported yet.\n* `&mut T` to `&T`\n* `*mut T` to `*const T`\n* `&T` to `*const T`\n* `&mut T` to `*mut T`\n* `&T` or `&mut T` to `&U` if `T` implements `Deref`. For example:\n```rust\n use std::ops::Deref;\n\n struct CharContainer {\n value: char,\n }\n\n impl Deref for CharContainer {\n type Target = char;\n\n fn deref<'a>(&'a self) -> &'a char {\n &self.value\n }\n }\n\n fn foo(arg: &char) {}\n\n fn main() {\n let x = &mut CharContainer { value: 'y' };\n foo(x); //&mut CharContainer is coerced to &char.\n }\n```\n* `&mut T` to `&mut U` if `T` implements `DerefMut`.\n* TyCtor(`T`) to TyCtor(`U`), where TyCtor(`T`) is one of\n - `&T`\n - `&mut T`\n - `*const T`\n - `*mut T`\n - `Box`\n and where `U` can be obtained from `T` by unsized coercion.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type coercions", "heading_path": ["Type coercions", "Coercion types"], "path": "type-coercions.md", "url": "https://doc.rust-lang.org/reference/type-coercions.html#coercion-types", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/type-coercions.md#coercion-types-4", "text": "The Rust Reference › Type coercions › Coercion types\n\n* Function item types to `fn` pointers\n* Non capturing closures to `fn` pointers\n* `!` to any `T`", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type coercions", "heading_path": ["Type coercions", "Coercion types"], "path": "type-coercions.md", "url": "https://doc.rust-lang.org/reference/type-coercions.html#coercion-types", "has_code": false, "code_tags": []}} {"id": "reference/type-coercions.md#unsized-coercions-5", "text": "The Rust Reference › Type coercions › Coercion types › Unsized coercions\n\nThe following coercions are called `unsized coercions`, since they relate to converting 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.\nTwo traits, [`Unsize`] and [`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` for `T` will be provided:\n* `[T; n]` to `[T]`.\n* `T` to `dyn U`, when `T` implements `U + Sized`, and `U` is [dyn compatible].\n* `dyn T` to `dyn U`, when `U` is one of `T`'s [supertraits].\n * This allows dropping auto traits, i.e. `dyn T + Auto` to `dyn U` is allowed.\n * This allows adding auto traits if the principal trait has the auto trait as a super trait, i.e. given `trait T: U + Send {}`, `dyn T` to `dyn T + Send` or to `dyn U + Send` coercions are allowed.\n* `Foo<..., T, ...>` to `Foo<..., U, ...>`, when:\n * `Foo` is a struct.\n * `T` implements `Unsize`.\n * The last field of `Foo` has a type involving `T`.\n * If that field has type `Bar`, then `Bar` implements `Unsize>`.\n * T is not part of the type of any other fields.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type coercions", "heading_path": ["Type coercions", "Coercion types", "Unsized coercions"], "path": "type-coercions.md", "url": "https://doc.rust-lang.org/reference/type-coercions.html#unsized-coercions", "has_code": false, "code_tags": []}} {"id": "reference/type-coercions.md#unsized-coercions-6", "text": "The Rust Reference › Type coercions › Coercion types › Unsized coercions\n\nAdditionally, a type `Foo` can implement `CoerceUnsized>` when `T` implements `Unsize` or `CoerceUnsized>`. This allows it to provide an unsized coercion to `Foo`.\nWhile 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type coercions", "heading_path": ["Type coercions", "Coercion types", "Unsized coercions"], "path": "type-coercions.md", "url": "https://doc.rust-lang.org/reference/type-coercions.html#unsized-coercions", "has_code": false, "code_tags": []}} {"id": "reference/type-coercions.md#least-upper-bound-coercions-7", "text": "The Rust Reference › Type coercions › Least upper bound coercions\n\nIn 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:\n+ To find the common type for a series of if branches.\n+ To find the common type for a series of match arms.\n+ To find the common type for array elements.\n+ To find the common type for a [labeled block expression] among the break operands and the final block operand.\n+ To find the common type for an [`loop` expression with break expressions] among the break operands.\n+ To find the type for the return type of a closure with multiple return statements.\n+ To check the type for the return type of a function with multiple return statements.\nIn 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.\nComputing the LUB coercion is done iteratively. The target type `T_t` begins as the type `T0`. For each new type `Ti`, we consider whether\n+ If `Ti` can be coerced to the current target type `T_t`, then no change is made.\n+ 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.)\n+ If not, try to compute a mutual supertype of `T_t` and `Ti`, which will become the new target type.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type coercions", "heading_path": ["Type coercions", "Least upper bound coercions"], "path": "type-coercions.md", "url": "https://doc.rust-lang.org/reference/type-coercions.html#least-upper-bound-coercions", "has_code": false, "code_tags": []}} {"id": "reference/type-coercions.md#examples-8", "text": "The Rust Reference › Type coercions › Least upper bound coercions › Examples:\n\n```rust\n// For if branches\nlet bar = if true {\n a\n} else if false {\n b\n} else {\n c\n};\n\n// For match arms\nlet baw = match 42 {\n 0 => a,\n 1 => b,\n _ => c,\n};\n\n// For array elements\nlet bax = [a, b, c];\n\n// For closure with multiple return statements\nlet clo = || {\n if true {\n a\n } else if false {\n b\n } else {\n c\n }\n};\nlet baz = clo();\n\n// For type checking of function with multiple return statements\nfn foo() -> i32 {\n let (a, b, c) = (0, 1, 2);\n match 42 {\n 0 => a,\n 1 => b,\n _ => c,\n }\n}\n```\nIn 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`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type coercions", "heading_path": ["Type coercions", "Least upper bound coercions", "Examples:"], "path": "type-coercions.md", "url": "https://doc.rust-lang.org/reference/type-coercions.html#examples", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/type-coercions.md#caveat-9", "text": "The Rust Reference › Type coercions › Least upper bound coercions › Caveat\n\nThis 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Type coercions", "heading_path": ["Type coercions", "Least upper bound coercions", "Caveat"], "path": "type-coercions.md", "url": "https://doc.rust-lang.org/reference/type-coercions.html#caveat", "has_code": false, "code_tags": []}} {"id": "reference/divergence.md#divergence-0", "text": "The Rust Reference › Divergence\n\nA *diverging expression* is an expression that never completes normal execution.\n```rust\nfn diverges() -> ! {\n panic!(\"This function never returns!\");\n}\n\nfn example() {\n let x: i32 = diverges(); // This line never completes.\n println!(\"This is never printed: {x}\");\n}\n```\nSee the following rules for specific expression divergence behavior:\n- [expr.block.diverging] --- Block expressions.\n- [expr.if.diverging] --- `if` expressions.\n- [expr.loop.block-labels.type] --- Labeled block expressions with `break`.\n- [expr.loop.break-value.diverging] --- `loop` expressions with `break`.\n- [expr.loop.break.diverging] --- `break` expressions.\n- [expr.loop.continue.diverging] --- `continue` expressions.\n- [expr.loop.infinite.diverging] --- Infinite `loop` expressions.\n- [expr.match.diverging] --- `match` expressions.\n- [expr.match.empty] --- Empty `match` expressions.\n- [expr.return.diverging] --- `return` expressions.\n- [type.never.constraint] --- Function calls returning `!`.\nThe [`panic!`] macro and related panic-generating macros like [`unreachable!`] also have the type [`!`] and are diverging.\nAny expression of type [`!`] is a diverging expression. However, diverging expressions are not limited to type [`!`]; expressions of other types may also diverge (e.g., `Some(loop {})` has type `Option`).\nThough `!` is considered an uninhabited type, a type being uninhabited is not sufficient for it to diverge.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Divergence", "heading_path": ["Divergence"], "path": "divergence.md", "url": "https://doc.rust-lang.org/reference/divergence.html#divergence", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/divergence.md#divergence-1", "text": "The Rust Reference › Divergence\n\n```rust,compile_fail,E0308\nenum Empty {}\nfn make_never() -> ! {loop{}}\nfn make_empty() -> Empty {loop{}}\n\nfn diverging() -> ! {\n // This has a type of `!`.\n // So, the entire function is considered diverging.\n make_never();\n // OK: The type of the body is `!` which matches the return type.\n}\nfn not_diverging() -> ! {\n // This type is uninhabited.\n // However, the entire function is not considered diverging.\n make_empty();\n // ERROR: The type of the body is `()` but expected type `!`.\n}\n```\nDivergence can propagate to the surrounding block. See [expr.block.diverging].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Divergence", "heading_path": ["Divergence"], "path": "divergence.md", "url": "https://doc.rust-lang.org/reference/divergence.html#divergence", "has_code": true, "code_tags": ["rust,compile_fail,E0308"]}} {"id": "reference/divergence.md#fallback-2", "text": "The Rust Reference › Divergence › Fallback\n\nIf a type to be inferred is only unified with diverging expressions, then that type will be inferred to be [`!`].\n```rust,compile_fail,E0277\nfn foo() -> i32 { 22 }\nmatch foo() {\n // ERROR: The trait bound `!: Default` is not satisfied.\n 4 => Default::default(),\n _ => return,\n};\n```\n[!EDITION-2024]\nBefore the 2024 edition, the type was inferred to instead be `()`.\nImportantly, type unification may happen *structurally*, so the fallback `!` may be part of a larger type. The following compiles:\n```rust\nfn foo() -> i32 { 22 }\n// This has the type `Option`, not `!`\nmatch foo() {\n 4 => Default::default(),\n _ => Some(return),\n};\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Divergence", "heading_path": ["Divergence", "Fallback"], "path": "divergence.md", "url": "https://doc.rust-lang.org/reference/divergence.html#fallback", "has_code": true, "code_tags": ["rust", "rust,compile_fail,E0277"]}} {"id": "reference/destructors.md#destructors-0", "text": "The Rust Reference › Destructors\n\nWhen an [initialized] [variable] or [temporary] goes out of scope, its *destructor* is run or it is *dropped*. [Assignment] 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.\nThe destructor of a type `T` consists of:\n1. If `T: Drop`, calling `::drop`\n2. Recursively running the destructor of all of its fields.\n * The fields of a [struct] are dropped in declaration order.\n * The fields of the active [enum variant] are dropped in declaration order.\n * The fields of a [tuple] are dropped in order.\n * The elements of an [array] or owned [slice] are dropped from the first element to the last.\n * The variables that a [closure] captures by move are dropped in an unspecified order.\n * [Trait objects] run the destructor of the underlying type.\n * Other types don't result in any further drops.\nIf a destructor must be run manually, such as when implementing your own smart pointer, [`core::ptr::drop_in_place`] can be used.\nSome examples:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Destructors", "heading_path": ["Destructors"], "path": "destructors.md", "url": "https://doc.rust-lang.org/reference/destructors.html#destructors", "has_code": false, "code_tags": []}} {"id": "reference/destructors.md#destructors-1", "text": "The Rust Reference › Destructors\n\n```rust\nstruct PrintOnDrop(&'static str);\n\nimpl Drop for PrintOnDrop {\n fn drop(&mut self) {\n println!(\"{}\", self.0);\n }\n}\n\nlet mut overwritten = PrintOnDrop(\"drops when overwritten\");\noverwritten = PrintOnDrop(\"drops when scope ends\");\n\nlet tuple = (PrintOnDrop(\"Tuple first\"), PrintOnDrop(\"Tuple second\"));\n\nlet moved;\n// No destructor run on assignment.\nmoved = PrintOnDrop(\"Drops when moved\");\n// Drops now, but is then uninitialized.\nmoved;\n\n// Uninitialized does not drop.\nlet uninitialized: PrintOnDrop;\n\n// After a partial move, only the remaining fields are dropped.\nlet mut partial_move = (PrintOnDrop(\"first\"), PrintOnDrop(\"forgotten\"));\n// Perform a partial move, leaving only `partial_move.0` initialized.\ncore::mem::forget(partial_move.1);\n// When partial_move's scope ends, only the first field is dropped.\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Destructors", "heading_path": ["Destructors"], "path": "destructors.md", "url": "https://doc.rust-lang.org/reference/destructors.html#destructors", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/destructors.md#drop-scopes-2", "text": "The Rust Reference › Destructors › Drop scopes\n\nEach 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).\nDrop scopes can be determined by replacing [`for`], [`if`], and [`while`] expressions with equivalent expressions using [`match`], [`loop`] and `break`.\nOverloaded operators are not distinguished from built-in operators and [binding modes] are not considered.\nGiven a function, or closure, there are drop scopes for:\n* The entire function\n* Each [statement]\n* Each [expression]\n* Each block, including the function body\n * In the case of a [block expression], the scope for the block and the expression are the same scope.\n* Each arm of a `match` expression\nDrop 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.\n* The entire function scope is the outer most scope.\n* The function body block is contained within the scope of the entire function.\n* The parent of the expression in an expression statement is the scope of the statement.\n* The parent of the initializer of a [`let` statement] is the `let` statement's scope.\n* The parent of a statement scope is the scope of the block that contains the statement.\n* The parent of the expression for a `match` guard is the scope of the arm that the guard is for.\n* The parent of the expression after the `=>` in a `match` expression is the scope of the arm that it's in.\n* The parent of the arm scope is the scope of the `match` expression that it belongs to.\n* The parent of all other scopes is the scope of the immediately enclosing expression.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Destructors", "heading_path": ["Destructors", "Drop scopes"], "path": "destructors.md", "url": "https://doc.rust-lang.org/reference/destructors.html#drop-scopes", "has_code": false, "code_tags": []}} {"id": "reference/destructors.md#scopes-of-function-parameters-3", "text": "The Rust Reference › Destructors › Drop scopes › Scopes of function parameters\n\nAll 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.\n```rust\n// Drops `y`, then the second parameter, then `x`, then the first parameter\nfn patterns_in_parameters(\n (x, _): (PrintOnDrop, PrintOnDrop),\n (_, y): (PrintOnDrop, PrintOnDrop),\n) {}\n\n// drop order is 3 2 0 1\npatterns_in_parameters(\n (PrintOnDrop(\"0\"), PrintOnDrop(\"1\")),\n (PrintOnDrop(\"2\"), PrintOnDrop(\"3\")),\n);\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Destructors", "heading_path": ["Destructors", "Drop scopes", "Scopes of function parameters"], "path": "destructors.md", "url": "https://doc.rust-lang.org/reference/destructors.html#scopes-of-function-parameters", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/destructors.md#scopes-of-local-variables-4", "text": "The Rust Reference › Destructors › Drop scopes › Scopes of local variables\n\nLocal variables declared in a `let` statement are associated to the scope of the block that contains the `let` statement.\n```rust\nlet declared_first = PrintOnDrop(\"Dropped last in outer scope\");\n{\n let declared_in_block = PrintOnDrop(\"Dropped in inner scope\");\n}\nlet declared_last = PrintOnDrop(\"Dropped first in outer scope\");\n```\nLocal variables declared in a `match` expression or pattern-matching `match` guard are associated to the arm scope of the `match` arm that they are declared in.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Destructors", "heading_path": ["Destructors", "Drop scopes", "Scopes of local variables"], "path": "destructors.md", "url": "https://doc.rust-lang.org/reference/destructors.html#scopes-of-local-variables", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/destructors.md#scopes-of-local-variables-5", "text": "The Rust Reference › Destructors › Drop scopes › Scopes of local variables\n\n```rust\nmatch PrintOnDrop(\"Dropped last in the first arm's scope\") {\n // When guard evaluation succeeds, control-flow stays in the arm and\n // values may be moved from the scrutinee into the arm's bindings,\n // causing them to be dropped in the arm's scope.\n x if let y = PrintOnDrop(\"Dropped second in the first arm's scope\")\n && let z = PrintOnDrop(\"Dropped first in the first arm's scope\") =>\n {\n let declared_in_block = PrintOnDrop(\"Dropped in inner scope\");\n // Pattern-matching guards' bindings and temporaries are dropped in\n // reverse order, dropping each guard condition operand's bindings\n // before its temporaries. Lastly, variables bound by the arm's\n // pattern are dropped.\n }\n _ => unreachable!(),\n}\n\nmatch PrintOnDrop(\"Dropped in the enclosing temporary scope\") {\n // When guard evaluation fails, control-flow leaves the arm scope,\n // causing bindings and temporaries from earlier pattern-matching\n // guard condition operands to be dropped. This occurs before evaluating\n // the next arm's guard or body.\n _ if let y = PrintOnDrop(\"Dropped in the first arm's scope\")\n && false => unreachable!(),\n // When a guard is executed multiple times due to self-overlapping\n // or-patterns, control-flow leaves the arm scope when the guard fails\n // and re-enters the arm scope before executing the guard again.\n _ | _ if let y = PrintOnDrop(\"Dropped in the second arm's scope twice\")\n && false => unreachable!(),\n _ => {},\n}\n```\nVariables in patterns are dropped in reverse order of declaration within the pattern.\n```rust\nlet (declared_first, declared_last) = (\n PrintOnDrop(\"Dropped last\"),\n PrintOnDrop(\"Dropped first\"),\n);\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Destructors", "heading_path": ["Destructors", "Drop scopes", "Scopes of local variables"], "path": "destructors.md", "url": "https://doc.rust-lang.org/reference/destructors.html#scopes-of-local-variables", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/destructors.md#scopes-of-local-variables-6", "text": "The Rust Reference › Destructors › Drop scopes › Scopes of local variables\n\nFor the purpose of drop order, [or-patterns] declare bindings in the order given by the first subpattern.\n```rust\n// Drops `x` before `y`.\nfn or_pattern_drop_order(\n (Ok([x, y]) | Err([y, x])): Result<[T; 2], [T; 2]>\n// ^^^^^^^^^^ ^^^^^^^^^^^ This is the second subpattern.\n// |\n// This is the first subpattern.\n//\n// In the first subpattern, `x` is declared before `y`. Since it is\n// the first subpattern, that is the order used even if the second\n// subpattern, where the bindings are declared in the opposite\n// order, is matched.\n) {}\n\n// Here we match the first subpattern, and the drops happen according\n// to the declaration order in the first subpattern.\nor_pattern_drop_order(Ok([\n PrintOnDrop(\"Declared first, dropped last\"),\n PrintOnDrop(\"Declared last, dropped first\"),\n]));\n\n// Here we match the second subpattern, and the drops still happen\n// according to the declaration order in the first subpattern.\nor_pattern_drop_order(Err([\n PrintOnDrop(\"Declared last, dropped first\"),\n PrintOnDrop(\"Declared first, dropped last\"),\n]));\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Destructors", "heading_path": ["Destructors", "Drop scopes", "Scopes of local variables"], "path": "destructors.md", "url": "https://doc.rust-lang.org/reference/destructors.html#scopes-of-local-variables", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/destructors.md#temporary-scopes-7", "text": "The Rust Reference › Destructors › Drop scopes › Temporary scopes\n\nThe *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], unless it is [promoted].\nApart from lifetime extension, the temporary scope of an expression is the smallest scope that contains the expression and is one of the following:\n* The entire function.\n* A statement.\n* The body of an [`if`], [`while`] or [`loop`] expression.\n* The `else` block of an `if` expression.\n* The non-pattern matching condition expression of an `if` or `while` expression or a non-pattern-matching `match` [guard condition operand].\n* The pattern-matching guard, if present, and body expression for a `match` arm.\n* Each operand of a [lazy boolean expression].\n* The pattern-matching condition(s) and consequent body of [`if`] ([destructors.scope.temporary.edition2024]).\n* The pattern-matching condition and loop body of [`while`].\n* The entirety of the tail expression of a block ([destructors.scope.temporary.edition2024]).\nThe [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.\nThe desugaring of a [destructuring assignment] restricts the temporary scope of its assigned value operand (the RHS). For details, see [expr.assign.destructure.tmp-scopes].\n[!EDITION-2024]\nThe 2024 edition added two new temporary scope narrowing rules: `if let` temporaries are dropped before the `else` block, and temporaries of tail expressions of blocks are dropped immediately after the tail expression is evaluated.\nSome examples:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Destructors", "heading_path": ["Destructors", "Drop scopes", "Temporary scopes"], "path": "destructors.md", "url": "https://doc.rust-lang.org/reference/destructors.html#temporary-scopes", "has_code": false, "code_tags": []}} {"id": "reference/destructors.md#temporary-scopes-8", "text": "The Rust Reference › Destructors › Drop scopes › Temporary scopes\n\n```rust\nlet local_var = PrintOnDrop(\"local var\");\n\n// Dropped once the condition has been evaluated\nif PrintOnDrop(\"If condition\").0 == \"If condition\" {\n // Dropped at the end of the block\n PrintOnDrop(\"If body\").0\n} else {\n unreachable!()\n};\n\nif let \"if let scrutinee\" = PrintOnDrop(\"if let scrutinee\").0 {\n PrintOnDrop(\"if let consequent\").0\n // `if let consequent` dropped here\n}\n// `if let scrutinee` is dropped here\nelse {\n PrintOnDrop(\"if let else\").0\n // `if let else` dropped here\n};\n\nwhile let x = PrintOnDrop(\"while let scrutinee\").0 {\n PrintOnDrop(\"while let loop body\").0;\n break;\n // `while let loop body` dropped here.\n // `while let scrutinee` dropped here.\n}\n\n// Dropped before the first ||\n(PrintOnDrop(\"first operand\").0 == \"\"\n// Dropped before the )\n|| PrintOnDrop(\"second operand\").0 == \"\")\n// Dropped before the ;\n|| PrintOnDrop(\"third operand\").0 == \"\";\n\n// Scrutinee is dropped at the end of the function, before local variables\n// (because this is the tail expression of the function body block).\nmatch PrintOnDrop(\"Matched value in final expression\") {\n // Non-pattern-matching guards' temporaries are dropped once the\n // condition has been evaluated\n _ if PrintOnDrop(\"guard condition\").0 == \"\" => (),\n // Pattern-matching guards' temporaries are dropped when leaving the\n // arm's scope\n _ if let \"guard scrutinee\" = PrintOnDrop(\"guard scrutinee\").0 => {\n let _ = &PrintOnDrop(\"lifetime-extended temporary in inner scope\");\n // `lifetime-extended temporary in inner scope` is dropped here\n }\n // `guard scrutinee` is dropped here\n _ => (),\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Destructors", "heading_path": ["Destructors", "Drop scopes", "Temporary scopes"], "path": "destructors.md", "url": "https://doc.rust-lang.org/reference/destructors.html#temporary-scopes", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/destructors.md#operands-9", "text": "The Rust Reference › Destructors › Drop scopes › Operands\n\nTemporaries 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.\n```rust\nloop {\n // Tuple expression doesn't finish evaluating so operands drop in reverse order\n (\n PrintOnDrop(\"Outer tuple first\"),\n PrintOnDrop(\"Outer tuple second\"),\n (\n PrintOnDrop(\"Inner tuple first\"),\n PrintOnDrop(\"Inner tuple second\"),\n break,\n ),\n PrintOnDrop(\"Never created\"),\n );\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Destructors", "heading_path": ["Destructors", "Drop scopes", "Operands"], "path": "destructors.md", "url": "https://doc.rust-lang.org/reference/destructors.html#operands", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/destructors.md#constant-promotion-10", "text": "The Rust Reference › Destructors › Drop scopes › Constant promotion\n\nPromotion 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] 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).", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Destructors", "heading_path": ["Destructors", "Drop scopes", "Constant promotion"], "path": "destructors.md", "url": "https://doc.rust-lang.org/reference/destructors.html#constant-promotion", "has_code": false, "code_tags": []}} {"id": "reference/destructors.md#extending-based-on-patterns-11", "text": "The Rust Reference › Destructors › Drop scopes › Temporary lifetime extension › Extending based on patterns\n\nThe exact rules for temporary lifetime extension are subject to change. This is describing the current behavior only.\nThe 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:\n```rust\nlet x = &mut 0;\n// Usually a temporary would be dropped by now, but the temporary for `0` lives\n// to the end of the block.\nprintln!(\"{}\", x);\n```\nLifetime extension also applies to `static` and `const` items, where it makes temporaries live until the end of the program. For example:\n```rust\nconst C: &Vec = &Vec::new();\n// Usually this would be a dangling reference as the `Vec` would only\n// exist inside the initializer expression of `C`, but instead the\n// borrow gets lifetime-extended so it effectively has `'static` lifetime.\nprintln!(\"{:?}\", C);\n```\nIf a [borrow], dereference, field, or [tuple indexing expression] has an extended temporary scope, then so does its operand. If an [indexing expression] has an extended temporary scope, then the indexed expression also has an extended temporary scope.\nAn *extending pattern* is either:\n* An [identifier pattern] that binds by reference or mutable reference.\n```rust\n # fn temp() {}\n let ref x = temp(); // Binds by reference.\n # x;\n let ref mut x = temp(); // Binds by mutable reference.\n # x;\n```\n* A struct, tuple, tuple struct, slice, or or-pattern where at least one of the direct subpatterns is an extending pattern.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Destructors", "heading_path": ["Destructors", "Drop scopes", "Temporary lifetime extension", "Extending based on patterns"], "path": "destructors.md", "url": "https://doc.rust-lang.org/reference/destructors.html#extending-based-on-patterns", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/destructors.md#extending-based-on-expressions-12", "text": "The Rust Reference › Destructors › Drop scopes › Temporary lifetime extension › Extending based on expressions\n\n```rust\n # use core::sync::atomic::{AtomicU64, Ordering::Relaxed};\n # static X: AtomicU64 = AtomicU64::new(0);\n struct W(T);\n # impl Drop for W { fn drop(&mut self) { X.fetch_add(1, Relaxed); } }\n let W { 0: ref x } = W(()); // Struct pattern.\n # x;\n let W(ref x) = W(()); // Tuple struct pattern.\n # x;\n let (W(ref x),) = (W(()),); // Tuple pattern.\n # x;\n let [W(ref x), ..] = [W(())]; // Slice pattern.\n # x;\n let (Ok(W(ref x)) | Err(&ref x)) = Ok(W(())); // Or pattern.\n # x;\n //\n // All of the temporaries above are still live here.\n # assert_eq!(0, X.load(Relaxed));\n```\nSo `ref x`, `V(ref x)` and `[ref x, y]` are all extending patterns, but `x`, `&ref x` and `&(ref x,)` are not.\nIf the pattern in a `let` statement is an extending pattern then the temporary scope of the initializer expression is extended.\n```rust\n// This is an extending pattern, so the temporary scope is extended.\nlet ref x = *&temp(); // OK\n```\n```rust,compile_fail,E0716\n// This is neither an extending pattern nor an extending expression,\n// so the temporary is dropped at the semicolon.\nlet &ref x = *&&temp(); // ERROR\n```\n```rust\n// This is not an extending pattern but it is an extending expression,\n// so the temporary lives beyond the `let` statement.\nlet &ref x = &*&temp(); // OK\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Destructors", "heading_path": ["Destructors", "Drop scopes", "Temporary lifetime extension", "Extending based on expressions"], "path": "destructors.md", "url": "https://doc.rust-lang.org/reference/destructors.html#extending-based-on-expressions", "has_code": true, "code_tags": ["rust", "rust,compile_fail,E0716"]}} {"id": "reference/destructors.md#examples-13", "text": "The Rust Reference › Destructors › Drop scopes › Temporary lifetime extension › Examples\n\nFor a let statement with an initializer, an *extending expression* is an expression which is one of the following:\n* The initializer expression.\n* The operand of an extending [borrow] expression.\n* The [super operands] of an extending [super macro call] expression.\n* The operand(s) of an extending array, cast, braced struct, or tuple expression.\n* The arguments to an extending [tuple struct] or [tuple enum variant] constructor expression.\n* The final expression of an extending [block expression] except for an [async block expression].\n* The final expression of an extending [`if`] expression's consequent, `else if`, or `else` block.\n* An arm expression of an extending [`match`] expression.\nThe desugaring of a [destructuring assignment] makes its assigned value operand (the RHS) an extending expression within a newly-introduced block. For details, see [expr.assign.destructure.tmp-ext].\nSo the borrow expressions in `&mut 0`, `(&1, &mut 2)`, and `Some(&mut 3)` are all extending expressions. The borrows in `&0 + &1` and `f(&mut 0)` are not.\nThe operand of an extending [borrow] expression has its [temporary scope] [extended].\nThe [super temporaries] of an extending [super macro call] expression have their scopes [extended].\n`rustc` does not treat [array repeat operands] of extending [array] expressions as extending expressions. Whether it should is an open question.\nFor details, see Rust issue #146092.\nHere are some examples where expressions have extended temporary scopes:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Destructors", "heading_path": ["Destructors", "Drop scopes", "Temporary lifetime extension", "Examples"], "path": "destructors.md", "url": "https://doc.rust-lang.org/reference/destructors.html#examples", "has_code": false, "code_tags": []}} {"id": "reference/destructors.md#examples-14", "text": "The Rust Reference › Destructors › Drop scopes › Temporary lifetime extension › Examples\n\n```rust,edition2024\nlet x = &temp(); // Operand of borrow.\nlet x = &raw const *&temp(); // Operand of raw borrow.\nlet x = &temp() as &dyn Send; // Operand of cast.\nlet x = (&*&temp(),); // Operand of tuple constructor.\nstruct W(T);\nlet x = W(&temp()); // Argument to tuple struct constructor.\nlet x = Some(&temp()); // Argument to tuple enum variant constructor.\nlet x = { [Some(&temp())] }; // Final expr of block.\nlet x = const { &temp() }; // Final expr of `const` block.\nlet x = unsafe { &temp() }; // Final expr of `unsafe` block.\nlet x = if true { &temp() } else { &temp() };\n// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n// Final exprs of `if`/`else` blocks.\nlet x = match () { _ => &temp() }; // `match` arm expression.\nlet x = pin!(temp()); // Super operand of super macro call expression.\nlet x = pin!({ &mut temp() }); // As above.\nlet x = format_args!(\"{:?}\", temp()); // As above.\n//\n// All of the temporaries above are still live here.\n```\nHere are some examples where expressions don't have extended temporary scopes:\n```rust,compile_fail,E0716\n// Arguments to function calls are not extending expressions. The\n// temporary is dropped at the semicolon.\nlet x = core::convert::identity(&temp()); // ERROR\n```\n```rust,compile_fail,E0716\n// Receivers of method calls are not extending expressions.\nlet x = (&temp()).use_temp(); // ERROR\n```\n```rust,compile_fail,E0716\n// Scrutinees of match expressions are not extending expressions.\nlet x = match &temp() { x => x }; // ERROR\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Destructors", "heading_path": ["Destructors", "Drop scopes", "Temporary lifetime extension", "Examples"], "path": "destructors.md", "url": "https://doc.rust-lang.org/reference/destructors.html#examples", "has_code": true, "code_tags": ["rust,compile_fail,E0716", "rust,edition2024"]}} {"id": "reference/destructors.md#examples-15", "text": "The Rust Reference › Destructors › Drop scopes › Temporary lifetime extension › Examples\n\n```rust,compile_fail,E0515\n// Final expressions of `async` blocks are not extending expressions.\nlet x = async { &temp() }; // ERROR\n```\n```rust,compile_fail,E0515\n// Final expressions of closures are not extending expressions.\nlet x = || &temp(); // ERROR\n```\n```rust,compile_fail,E0716\n// Operands of loop breaks are not extending expressions.\nlet x = loop { break &temp() }; // ERROR\n```\n```rust,compile_fail,E0716\n// Operands of breaks to labels are not extending expressions.\nlet x = 'a: { break 'a &temp() }; // ERROR\n```\n```rust,edition2024,compile_fail,E0716\n// The argument to `pin!` is only an extending expression if the call\n// is an extending expression. Since it's not, the inner block is not\n// an extending expression, so the temporaries in its trailing\n// expression are dropped immediately.\npin!({ &temp() }); // ERROR\n```\n```rust,edition2024,compile_fail,E0716\n// As above.\nformat_args!(\"{:?}\", { &temp() }); // ERROR\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Destructors", "heading_path": ["Destructors", "Drop scopes", "Temporary lifetime extension", "Examples"], "path": "destructors.md", "url": "https://doc.rust-lang.org/reference/destructors.html#examples", "has_code": true, "code_tags": ["rust,compile_fail,E0515", "rust,compile_fail,E0716", "rust,edition2024,compile_fail,E0716"]}} {"id": "reference/destructors.md#manually-suppressing-destructors-16", "text": "The Rust Reference › Destructors › Not running destructors › Manually suppressing destructors\n\n[`core::mem::forget`] can be used to prevent the destructor of a variable from being run, and [`core::mem::ManuallyDrop`] provides a wrapper to prevent a variable or field from being dropped automatically.\nPreventing a destructor from being run via [`core::mem::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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Destructors", "heading_path": ["Destructors", "Not running destructors", "Manually suppressing destructors"], "path": "destructors.md", "url": "https://doc.rust-lang.org/reference/destructors.html#manually-suppressing-destructors", "has_code": false, "code_tags": []}} {"id": "reference/destructors.md#process-termination-without-unwinding-17", "text": "The Rust Reference › Destructors › Not running destructors › Process termination without unwinding\n\nThere are some ways to terminate the process without [unwinding], in which case destructors will not be run.\nThe standard library provides [`std::process::exit`] and [`std::process::abort`] to do this explicitly. Additionally, if the panic handler is set to `abort`, panicking will always terminate the process without destructors being run.\nThere is one additional case to be aware of: when a panic reaches a [non-unwinding ABI boundary], either no destructors will run, or all destructors up until the ABI boundary will run.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Destructors", "heading_path": ["Destructors", "Not running destructors", "Process termination without unwinding"], "path": "destructors.md", "url": "https://doc.rust-lang.org/reference/destructors.html#process-termination-without-unwinding", "has_code": false, "code_tags": []}} {"id": "reference/lifetime-elision.md#lifetime-elision-0", "text": "The Rust Reference › Lifetime elision\n\nRust has rules that allow lifetimes to be elided in various places where the compiler can infer a sensible default choice.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Lifetime elision", "heading_path": ["Lifetime elision"], "path": "lifetime-elision.md", "url": "https://doc.rust-lang.org/reference/lifetime-elision.html#lifetime-elision", "has_code": false, "code_tags": []}} {"id": "reference/lifetime-elision.md#lifetime-elision-in-functions-1", "text": "The Rust Reference › Lifetime elision › Lifetime elision in functions\n\nIn order to make common patterns more ergonomic, lifetime arguments can be *elided* in [function item], [function pointer], and [closure trait] signatures. The following rules are used to infer lifetime parameters for elided lifetimes.\nIt is an error to elide lifetime parameters that cannot be inferred.\nThe placeholder lifetime, `'_`, can also be used to have a lifetime inferred in the same way. For lifetimes in paths, using `'_` is preferred.\nTrait object lifetimes follow different rules discussed below.\n* Each elided lifetime in the parameters becomes a distinct lifetime parameter.\n* If there is exactly one lifetime used in the parameters (elided or not), that lifetime is assigned to *all* elided output lifetimes.\nIn method signatures there is another rule\n* 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.\nExamples:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Lifetime elision", "heading_path": ["Lifetime elision", "Lifetime elision in functions"], "path": "lifetime-elision.md", "url": "https://doc.rust-lang.org/reference/lifetime-elision.html#lifetime-elision-in-functions", "has_code": false, "code_tags": []}} {"id": "reference/lifetime-elision.md#lifetime-elision-in-functions-2", "text": "The Rust Reference › Lifetime elision › Lifetime elision in functions\n\n```rust\nfn print1(s: &str); // elided\nfn print2(s: &'_ str); // also elided\nfn print3<'a>(s: &'a str); // expanded\n\nfn debug1(lvl: usize, s: &str); // elided\nfn debug2<'a>(lvl: usize, s: &'a str); // expanded\n\nfn substr1(s: &str, until: usize) -> &str; // elided\nfn substr2<'a>(s: &'a str, until: usize) -> &'a str; // expanded\n\nfn get_mut1(&mut self) -> &mut dyn T; // elided\nfn get_mut2<'a>(&'a mut self) -> &'a mut dyn T; // expanded\n\nfn args1(&mut self, args: &[T]) -> &mut Command; // elided\nfn args2<'a, 'b, T: ToCStr>(&'a mut self, args: &'b [T]) -> &'a mut Command; // expanded\n\nfn other_args1<'a>(arg: &str) -> &'a str; // elided\nfn other_args2<'a, 'b>(arg: &'b str) -> &'a str; // expanded\n\nfn new1(buf: &mut [u8]) -> Thing<'_>; // elided - preferred\nfn new2(buf: &mut [u8]) -> Thing; // elided\nfn new3<'a>(buf: &'a mut [u8]) -> Thing<'a>; // expanded\n\ntype FunPtr1 = fn(&str) -> &str; // elided\ntype FunPtr2 = for<'a> fn(&'a str) -> &'a str; // expanded\n\ntype FunTrait1 = dyn Fn(&str) -> &str; // elided\ntype FunTrait2 = dyn for<'a> Fn(&'a str) -> &'a str; // expanded\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Lifetime elision", "heading_path": ["Lifetime elision", "Lifetime elision in functions"], "path": "lifetime-elision.md", "url": "https://doc.rust-lang.org/reference/lifetime-elision.html#lifetime-elision-in-functions", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/lifetime-elision.md#lifetime-elision-in-functions-3", "text": "The Rust Reference › Lifetime elision › Lifetime elision in functions\n\n```rust,compile_fail\n// The following examples show situations where it is not allowed to elide the\n// lifetime parameter.\n\n// Cannot infer, because there are no parameters to infer from.\nfn get_str() -> &str; // ILLEGAL\n\n// Cannot infer, ambiguous if it is borrowed from the first or second parameter.\nfn frob(s: &str, t: &str) -> &str; // ILLEGAL\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Lifetime elision", "heading_path": ["Lifetime elision", "Lifetime elision in functions"], "path": "lifetime-elision.md", "url": "https://doc.rust-lang.org/reference/lifetime-elision.html#lifetime-elision-in-functions", "has_code": true, "code_tags": ["rust,compile_fail"]}} {"id": "reference/lifetime-elision.md#default-trait-object-lifetimes-4", "text": "The Rust Reference › Lifetime elision › Default trait object lifetimes\n\nThe assumed lifetime of references held by a [trait object] is called its _default object lifetime bound_. These were defined in [RFC 599] and amended in [RFC 1156].\nThese default object lifetime bounds are used instead of the lifetime parameter elision rules defined above when the lifetime bound is omitted entirely.\nIf `'_` is used as the lifetime bound then the bound follows the usual elision rules.\nIf 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.\n* If there is a unique bound from the containing type then that is the default.\n* If there is more than one bound from the containing type then an explicit bound must be specified.\nIf neither of those rules apply, then the bounds on the trait are used:\n* If the trait is defined with a single lifetime _bound_ then that bound is used.\n* If `'static` is used for any lifetime bound then `'static` is used.\n* If the trait has no lifetime bounds, then the lifetime is inferred in expressions and is `'static` outside of expressions.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Lifetime elision", "heading_path": ["Lifetime elision", "Default trait object lifetimes"], "path": "lifetime-elision.md", "url": "https://doc.rust-lang.org/reference/lifetime-elision.html#default-trait-object-lifetimes", "has_code": false, "code_tags": []}} {"id": "reference/lifetime-elision.md#default-trait-object-lifetimes-5", "text": "The Rust Reference › Lifetime elision › Default trait object lifetimes\n\n```rust\n// For the following trait...\ntrait Foo { }\n\n// These two are the same because Box has no lifetime bound on T\ntype T1 = Box;\ntype T2 = Box;\n\n// ...and so are these:\nimpl dyn Foo {}\nimpl dyn Foo + 'static {}\n\n// ...so are these, because &'a T requires T: 'a\ntype T3<'a> = &'a dyn Foo;\ntype T4<'a> = &'a (dyn Foo + 'a);\n\n// std::cell::Ref<'a, T> also requires T: 'a, so these are the same\ntype T5<'a> = std::cell::Ref<'a, dyn Foo>;\ntype T6<'a> = std::cell::Ref<'a, dyn Foo + 'a>;\n```\n```rust,compile_fail\n// This is an example of an error.\nstruct TwoBounds<'a, 'b, T: ?Sized + 'a + 'b> {\n f1: &'a i32,\n f2: &'b i32,\n f3: T,\n}\ntype T7<'a, 'b> = TwoBounds<'a, 'b, dyn Foo>;\n// ^^^^^^^\n// Error: the lifetime bound for this object type cannot be deduced from context\n```\nNote that the innermost object sets the bound, so `&'a Box` is still `&'a Box`.\n```rust\n// For the following trait...\ntrait Bar<'a>: 'a { }\n\n// ...these two are the same:\ntype T1<'a> = Box>;\ntype T2<'a> = Box + 'a>;\n\n// ...and so are these:\nimpl<'a> dyn Bar<'a> {}\nimpl<'a> dyn Bar<'a> + 'a {}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Lifetime elision", "heading_path": ["Lifetime elision", "Default trait object lifetimes"], "path": "lifetime-elision.md", "url": "https://doc.rust-lang.org/reference/lifetime-elision.html#default-trait-object-lifetimes", "has_code": true, "code_tags": ["rust", "rust,compile_fail"]}} {"id": "reference/lifetime-elision.md#const-and-static-elision-6", "text": "The Rust Reference › Lifetime elision › `const` and `static` elision\n\nBoth [constant] and [static] 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.\n```rust\n// STRING: &'static str\nconst STRING: &str = \"bitstring\";\n\nstruct BitsNStrings<'a> {\n mybits: [u32; 2],\n mystring: &'a str,\n}\n\n// BITS_N_STRINGS: BitsNStrings<'static>\nconst BITS_N_STRINGS: BitsNStrings<'_> = BitsNStrings {\n mybits: [1, 2],\n mystring: STRING,\n};\n```\nNote 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:\n```rust\n// Resolved as `for<'a> fn(&'a str) -> &'a str`.\nconst RESOLVED_SINGLE: fn(&str) -> &str = |x| x;\n\n// Resolved as `for<'a, 'b, 'c> Fn(&'a Foo, &'b Bar, &'c Baz) -> usize`.\nconst RESOLVED_MULTIPLE: &dyn Fn(&Foo, &Bar, &Baz) -> usize = &somefunc;\n```\n```rust,compile_fail\n// There is insufficient information to bound the return reference lifetime\n// relative to the argument lifetimes, so this is an error.\nconst RESOLVED_STATIC: &dyn Fn(&Foo, &Bar) -> &Baz = &somefunc;\n// ^\n// this function's return type contains a borrowed value, but the signature\n// does not say whether it is borrowed from argument 1 or argument 2\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Lifetime elision", "heading_path": ["Lifetime elision", "`const` and `static` elision"], "path": "lifetime-elision.md", "url": "https://doc.rust-lang.org/reference/lifetime-elision.html#const-and-static-elision", "has_code": true, "code_tags": ["rust", "rust,compile_fail"]}} {"id": "reference/special-types-and-traits.md#special-types-and-traits-0", "text": "The Rust Reference › Special types and traits\n\nCertain types and traits that exist in [the standard library] are known to the Rust compiler. This chapter documents the special features of these types and traits.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Special types and traits", "heading_path": ["Special types and traits"], "path": "special-types-and-traits.md", "url": "https://doc.rust-lang.org/reference/special-types-and-traits.html#special-types-and-traits", "has_code": false, "code_tags": []}} {"id": "reference/special-types-and-traits.md#boxt-1", "text": "The Rust Reference › Special types and traits › `Box`\n\n[`Box`] has a few special features that Rust doesn't currently allow for user defined types.\n* The [dereference operator] for `Box` produces a place which can be [moved from]. This means that the `*` operator and the destructor of `Box` are built-in to the language.\n* [Methods] can take `Box` as a receiver.\n* A trait may be implemented for `Box` in the same crate as `T`, which the [orphan rules] prevent for other generic types.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Special types and traits", "heading_path": ["Special types and traits", "`Box`"], "path": "special-types-and-traits.md", "url": "https://doc.rust-lang.org/reference/special-types-and-traits.html#boxt", "has_code": false, "code_tags": []}} {"id": "reference/special-types-and-traits.md#rct-2", "text": "The Rust Reference › Special types and traits › `Rc`\n\n[Methods] can take [`Rc`] as a receiver.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Special types and traits", "heading_path": ["Special types and traits", "`Rc`"], "path": "special-types-and-traits.md", "url": "https://doc.rust-lang.org/reference/special-types-and-traits.html#rct", "has_code": false, "code_tags": []}} {"id": "reference/special-types-and-traits.md#arct-3", "text": "The Rust Reference › Special types and traits › `Arc`\n\n[Methods] can take [`Arc`] as a receiver.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Special types and traits", "heading_path": ["Special types and traits", "`Arc`"], "path": "special-types-and-traits.md", "url": "https://doc.rust-lang.org/reference/special-types-and-traits.html#arct", "has_code": false, "code_tags": []}} {"id": "reference/special-types-and-traits.md#pinp-4", "text": "The Rust Reference › Special types and traits › `Pin

`\n\n[Methods] can take [`Pin

`] as a receiver.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Special types and traits", "heading_path": ["Special types and traits", "`Pin

`"], "path": "special-types-and-traits.md", "url": "https://doc.rust-lang.org/reference/special-types-and-traits.html#pinp", "has_code": false, "code_tags": []}} {"id": "reference/special-types-and-traits.md#unsafecellt-5", "text": "The Rust Reference › Special types and traits › `UnsafeCell`\n\n[`std::cell::UnsafeCell`] is used for [interior mutability]. It ensures that the compiler doesn't perform optimisations that are incorrect for such types.\nIt also ensures that [`static` items] which have a type with interior mutability aren't placed in memory marked as read only.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Special types and traits", "heading_path": ["Special types and traits", "`UnsafeCell`"], "path": "special-types-and-traits.md", "url": "https://doc.rust-lang.org/reference/special-types-and-traits.html#unsafecellt", "has_code": false, "code_tags": []}} {"id": "reference/special-types-and-traits.md#phantomdatat-6", "text": "The Rust Reference › Special types and traits › `PhantomData`\n\n[`std::marker::PhantomData`] is a [zero-sized], minimum alignment, type that is considered to own a `T` for the purposes of [variance], [drop check], and auto traits.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Special types and traits", "heading_path": ["Special types and traits", "`PhantomData`"], "path": "special-types-and-traits.md", "url": "https://doc.rust-lang.org/reference/special-types-and-traits.html#phantomdatat", "has_code": false, "code_tags": []}} {"id": "reference/special-types-and-traits.md#operator-traits-7", "text": "The Rust Reference › Special types and traits › Operator traits\n\nThe traits in [`std::ops`] and [`std::cmp`] are used to overload [operators], [indexing expressions], and [call expressions].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Special types and traits", "heading_path": ["Special types and traits", "Operator traits"], "path": "special-types-and-traits.md", "url": "https://doc.rust-lang.org/reference/special-types-and-traits.html#operator-traits", "has_code": false, "code_tags": []}} {"id": "reference/special-types-and-traits.md#deref-and-derefmut-8", "text": "The Rust Reference › Special types and traits › `Deref` and `DerefMut`\n\nAs well as overloading the unary `*` operator, [`Deref`] and [`DerefMut`] are also used in [method resolution] and [deref coercions].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Special types and traits", "heading_path": ["Special types and traits", "`Deref` and `DerefMut`"], "path": "special-types-and-traits.md", "url": "https://doc.rust-lang.org/reference/special-types-and-traits.html#deref-and-derefmut", "has_code": false, "code_tags": []}} {"id": "reference/special-types-and-traits.md#drop-9", "text": "The Rust Reference › Special types and traits › `Drop`\n\nThe [`Drop`] trait provides a [destructor], to be run whenever a value of this type is to be destroyed.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Special types and traits", "heading_path": ["Special types and traits", "`Drop`"], "path": "special-types-and-traits.md", "url": "https://doc.rust-lang.org/reference/special-types-and-traits.html#drop", "has_code": false, "code_tags": []}} {"id": "reference/special-types-and-traits.md#copy-10", "text": "The Rust Reference › Special types and traits › `Copy`\n\nThe [`Copy`] trait changes the semantics of a type implementing it.\nValues whose type implements `Copy` are copied rather than moved upon assignment.\n`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`.\n`Copy` is implemented by the compiler for\n* [Tuples] of `Copy` types\n* [Function pointers]\n* [Function items]\n* [Closures] that capture no values or that only capture values of `Copy` types", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Special types and traits", "heading_path": ["Special types and traits", "`Copy`"], "path": "special-types-and-traits.md", "url": "https://doc.rust-lang.org/reference/special-types-and-traits.html#copy", "has_code": false, "code_tags": []}} {"id": "reference/special-types-and-traits.md#clone-11", "text": "The Rust Reference › Special types and traits › `Clone`\n\nThe [`Clone`] trait is a supertrait of `Copy`, so it also needs compiler generated implementations.\nIt is implemented by the compiler for the following types:\n* Types with a built-in `Copy` implementation (see above)\n* [Tuples] of `Clone` types\n* [Closures] that only capture values of `Clone` types or capture no values from the environment", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Special types and traits", "heading_path": ["Special types and traits", "`Clone`"], "path": "special-types-and-traits.md", "url": "https://doc.rust-lang.org/reference/special-types-and-traits.html#clone", "has_code": false, "code_tags": []}} {"id": "reference/special-types-and-traits.md#send-12", "text": "The Rust Reference › Special types and traits › `Send`\n\nThe [`Send`] trait indicates that a value of this type is safe to send from one thread to another.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Special types and traits", "heading_path": ["Special types and traits", "`Send`"], "path": "special-types-and-traits.md", "url": "https://doc.rust-lang.org/reference/special-types-and-traits.html#send", "has_code": false, "code_tags": []}} {"id": "reference/special-types-and-traits.md#sync-13", "text": "The Rust Reference › Special types and traits › `Sync`\n\nThe [`Sync`] trait indicates that a value of this type is safe to share between multiple threads.\nThis trait must be implemented for all types used in immutable [`static` items].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Special types and traits", "heading_path": ["Special types and traits", "`Sync`"], "path": "special-types-and-traits.md", "url": "https://doc.rust-lang.org/reference/special-types-and-traits.html#sync", "has_code": false, "code_tags": []}} {"id": "reference/special-types-and-traits.md#termination-14", "text": "The Rust Reference › Special types and traits › `Termination`\n\nThe [`Termination`] trait indicates the acceptable return types for the [main function] and [test functions].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Special types and traits", "heading_path": ["Special types and traits", "`Termination`"], "path": "special-types-and-traits.md", "url": "https://doc.rust-lang.org/reference/special-types-and-traits.html#termination", "has_code": false, "code_tags": []}} {"id": "reference/special-types-and-traits.md#auto-traits-15", "text": "The Rust Reference › Special types and traits › Auto traits\n\nThe [`Send`], [`Sync`], [`Unpin`], [`UnwindSafe`], and [`RefUnwindSafe`] traits are _auto traits_. Auto traits have special properties.\nIf 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:\n* `&T`, `&mut T`, `*const T`, `*mut T`, `[T; n]`, and `[T]` implement the trait if `T` does.\n* Function item types and function pointers automatically implement the trait.\n* Structs, enums, unions, and tuples implement the trait if all of their fields do.\n* 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.\nFor 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`.\nAuto 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Special types and traits", "heading_path": ["Special types and traits", "Auto traits"], "path": "special-types-and-traits.md", "url": "https://doc.rust-lang.org/reference/special-types-and-traits.html#auto-traits", "has_code": false, "code_tags": []}} {"id": "reference/special-types-and-traits.md#auto-traits-16", "text": "The Rust Reference › Special types and traits › Auto traits\n\nAuto traits may be added as an additional bound to any [trait object], even though normally only one trait is allowed. For instance, `Box` is a valid type.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Special types and traits", "heading_path": ["Special types and traits", "Auto traits"], "path": "special-types-and-traits.md", "url": "https://doc.rust-lang.org/reference/special-types-and-traits.html#auto-traits", "has_code": false, "code_tags": []}} {"id": "reference/special-types-and-traits.md#sized-17", "text": "The Rust Reference › Special types and traits › `Sized`\n\nThe [`Sized`] trait indicates that the size of this type is known at compile-time; that is, it's not a [dynamically sized type].\n[Type parameters] (except `Self` in traits) are `Sized` by default, as are [associated types].\n`Sized` is always implemented automatically by the compiler, not by [implementation items].\nThese implicit `Sized` bounds may be relaxed by using the special `?Sized` bound.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Special types and traits", "heading_path": ["Special types and traits", "`Sized`"], "path": "special-types-and-traits.md", "url": "https://doc.rust-lang.org/reference/special-types-and-traits.html#sized", "has_code": false, "code_tags": []}} {"id": "reference/names.md#names-0", "text": "The Rust Reference › Names\n\nAn *entity* is a language construct that can be referred to in some way within the source program, usually via a [path]. Entities include [types], [items], [generic parameters], [variable bindings], [loop labels], [lifetimes], [fields], [attributes], and [lints].\nA *declaration* is a syntactical construct that can introduce a *name* to refer to an entity. Entity names are valid within a [*scope*] --- a region of source text where that name may be referenced.\nSome entities are explicitly declared in the source code, and some are implicitly declared as part of the language or compiler extensions.\n[*Paths*] are used to refer to an entity, possibly in another module or type.\nLifetimes and loop labels use a dedicated syntax using a leading quote.\nNames are segregated into different [*namespaces*], allowing entities in different namespaces to share the same name without conflict.\n[*Name resolution*] is the compile-time process of tying paths, identifiers, and labels to entity declarations.\nAccess to certain names may be restricted based on their [*visibility*].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Names", "heading_path": ["Names"], "path": "names.md", "url": "https://doc.rust-lang.org/reference/names.html#names", "has_code": false, "code_tags": []}} {"id": "reference/names.md#explicitly-declared-entities-1", "text": "The Rust Reference › Names › Explicitly declared entities\n\nEntities that explicitly introduce a name in the source code are:\n* [Items]:\n * [Module declarations]\n * [External crate declarations]\n * [Use declarations]\n * [Function declarations] and [function parameters]\n * [Type aliases]\n * [struct], [union], [enum], enum variant declarations, and their named fields\n * [Constant item declarations]\n * [Static item declarations]\n * [Trait item declarations] and their [associated items]\n * [External block items]\n * [`macro_rules` declarations] and [matcher metavariables]\n * [Implementation] associated items\n* [Expressions]:\n * [Closure] parameters\n * [`while let`] pattern bindings\n * [`for`] pattern bindings\n * [`if let`] pattern bindings\n * [`match`] pattern bindings\n * [Loop labels]\n* [Generic parameters]\n* [Higher ranked trait bounds]\n* [`let` statement] pattern bindings\n* The [`macro_use` attribute] can introduce macro names from another crate\n* The [`macro_export` attribute] can introduce an alias for the macro into the crate root\nAdditionally, [macro invocations] and [attributes] can introduce names by expanding to one of the above items.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Names", "heading_path": ["Names", "Explicitly declared entities"], "path": "names.md", "url": "https://doc.rust-lang.org/reference/names.html#explicitly-declared-entities", "has_code": false, "code_tags": []}} {"id": "reference/names.md#implicitly-declared-entities-2", "text": "The Rust Reference › Names › Implicitly declared entities\n\nThe following entities are implicitly defined by the language, or are introduced by compiler options and extensions:\n* [Language prelude]:\n * [Boolean type] --- `bool`\n * Textual types --- [`char`] and [`str`]\n * [Integer types] --- `i8`, `i16`, `i32`, `i64`, `i128`, `u8`, `u16`, `u32`, `u64`, `u128`\n * [Machine-dependent integer types] --- `usize` and `isize`\n * [floating-point types] --- `f32` and `f64`\n* [Built-in attributes]\n* [Standard library prelude] items, attributes, and macros\n* Standard library crates in the root module\n* External crates linked by the compiler\n* [Tool attributes]\n* [Lints] and [tool lint attributes]\n* [Derive helper attributes] are valid within an item without being explicitly imported\n* The [`'static`] lifetime\nAdditionally, the crate root module does not have a name, but can be referred to with certain [path qualifiers] or aliases.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Names", "heading_path": ["Names", "Implicitly declared entities"], "path": "names.md", "url": "https://doc.rust-lang.org/reference/names.html#implicitly-declared-entities", "has_code": false, "code_tags": []}} {"id": "reference/names/namespaces.md#namespaces-0", "text": "The Rust Reference › Namespaces\n\nA *namespace* is a logical grouping of declared [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.\nThere are several different namespaces that each contain different kinds of entities. The use of a name will look for the declaration of that name in different namespaces, based on the context, as described in the [name resolution] chapter.\nThe following is a list of namespaces, with their corresponding entities:\n* Type Namespace\n * [Module declarations]\n * [External crate declarations]\n * [External crate prelude] items\n * [Struct], [union], [enum], enum variant declarations\n * [Trait item declarations]\n * [Type aliases]\n * [Associated type declarations]\n * Built-in types: [boolean], [numeric], [`char`], and [`str`]\n * [Generic type parameters]\n * [`Self` type]\n * [Tool attribute modules]\n* Value Namespace\n * [Function declarations]\n * [Constant item declarations]\n * [Static item declarations]\n * [Struct constructors]\n * [Enum variant constructors]\n * [`Self` constructors]\n * [Generic const parameters]\n * [Associated const declarations]\n * [Associated function declarations]\n * Local bindings --- [`let`], [`if let`], [`while let`], [`for`], [`match`] arms, [function parameters], [closure parameters]\n * Captured [closure] variables\n* Macro Namespace\n * [`macro_rules` declarations]\n * [Built-in attributes]\n * [Tool attributes]\n * [Function-like procedural macros]\n * [Derive macros]\n * [Derive macro helpers]\n * [Attribute macros]\n* Lifetime Namespace\n * [Generic lifetime parameters]\n* Label Namespace\n * [Loop labels]\n * [Block labels]", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Namespaces", "heading_path": ["Namespaces"], "path": "names/namespaces.md", "url": "https://doc.rust-lang.org/reference/names/namespaces.html#namespaces", "has_code": false, "code_tags": []}} {"id": "reference/names/namespaces.md#namespaces-1", "text": "The Rust Reference › Namespaces\n\nAn example of how overlapping names in different namespaces can be used unambiguously:\n```rust\n// Foo introduces a type in the type namespace and a constructor in the value\n// namespace.\nstruct Foo(u32);\n\n// The `Foo` macro is declared in the macro namespace.\nmacro_rules! Foo {\n () => {};\n}\n\n// `Foo` in the `f` parameter type refers to `Foo` in the type namespace.\n// `'Foo` introduces a new lifetime in the lifetime namespace.\nfn example<'Foo>(f: Foo) {\n // `Foo` refers to the `Foo` constructor in the value namespace.\n let ctor = Foo;\n // `Foo` refers to the `Foo` macro in the macro namespace.\n Foo!{}\n // `'Foo` introduces a label in the label namespace.\n 'Foo: loop {\n // `'Foo` refers to the `'Foo` lifetime parameter, and `Foo`\n // refers to the type namespace.\n let x: &'Foo Foo;\n // `'Foo` refers to the label.\n break 'Foo;\n }\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Namespaces", "heading_path": ["Namespaces"], "path": "names/namespaces.md", "url": "https://doc.rust-lang.org/reference/names/namespaces.html#namespaces", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/names/namespaces.md#named-entities-without-a-namespace-2", "text": "The Rust Reference › Namespaces › Named entities without a namespace\n\nThe following entities have explicit names, but the names are not a part of any specific namespace.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Namespaces", "heading_path": ["Namespaces", "Named entities without a namespace"], "path": "names/namespaces.md", "url": "https://doc.rust-lang.org/reference/names/namespaces.html#named-entities-without-a-namespace", "has_code": false, "code_tags": []}} {"id": "reference/names/namespaces.md#fields-3", "text": "The Rust Reference › Namespaces › Named entities without a namespace › Fields\n\nEven 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], which only inspects the field names of the specific type being accessed.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Namespaces", "heading_path": ["Namespaces", "Named entities without a namespace", "Fields"], "path": "names/namespaces.md", "url": "https://doc.rust-lang.org/reference/names/namespaces.html#fields", "has_code": false, "code_tags": []}} {"id": "reference/names/namespaces.md#use-declarations-4", "text": "The Rust Reference › Namespaces › Named entities without a namespace › Use declarations\n\nA [use declaration] 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Namespaces", "heading_path": ["Namespaces", "Named entities without a namespace", "Use declarations"], "path": "names/namespaces.md", "url": "https://doc.rust-lang.org/reference/names/namespaces.html#use-declarations", "has_code": false, "code_tags": []}} {"id": "reference/names/namespaces.md#sub-namespaces-5", "text": "The Rust Reference › Namespaces › Sub-namespaces\n\nThe macro namespace is split into two sub-namespaces: one for [bang-style macros] and one for [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.\nFor example, the [`cfg` attribute] and 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.\n`use` imports still cannot create duplicate bindings of the same name in a module or block, regardless of sub-namespace.\n```rust,ignore\n#[macro_export]\nmacro_rules! mymac {\n () => {};\n}\n\nuse myattr::mymac; // error[E0252]: the name `mymac` is defined multiple times.\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Namespaces", "heading_path": ["Namespaces", "Sub-namespaces"], "path": "names/namespaces.md", "url": "https://doc.rust-lang.org/reference/names/namespaces.html#sub-namespaces", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "reference/names/scopes.md#scopes-0", "text": "The Rust Reference › Scopes\n\nA *scope* is the region of source text where a named [entity] may be referenced with that name. The following sections provide details on the scoping rules and behavior, which depend on the kind of entity and where it is declared. The process of how names are resolved to entities is described in the [name resolution] chapter. More information on \"drop scopes\" used for the purpose of running destructors may be found in the [destructors] chapter.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Scopes", "heading_path": ["Scopes"], "path": "names/scopes.md", "url": "https://doc.rust-lang.org/reference/names/scopes.html#scopes", "has_code": false, "code_tags": []}} {"id": "reference/names/scopes.md#item-scopes-1", "text": "The Rust Reference › Scopes › Item scopes\n\nThe name of an item declared directly in a [module] has a scope that extends from the start of the module to the end of the module. These items are also members of the module and can be referred to with a [path] leading from their module.\nThe name of an item declared as a [statement] has a scope that extends from the start of the block the item statement is in until the end of the block.\nIt is an error to introduce an item with a duplicate name of another item in the same [namespace] within the same module or block. [Asterisk glob imports] have special behavior for dealing with duplicate names and shadowing, see the linked chapter for more details.\nItems in a module may shadow items in a prelude.\nItem names from outer modules are not in scope within a nested module. A [path] may be used to refer to an item in another module.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Scopes", "heading_path": ["Scopes", "Item scopes"], "path": "names/scopes.md", "url": "https://doc.rust-lang.org/reference/names/scopes.html#item-scopes", "has_code": false, "code_tags": []}} {"id": "reference/names/scopes.md#associated-item-scopes-2", "text": "The Rust Reference › Scopes › Item scopes › Associated item scopes\n\n[Associated items] are not scoped and can only be referred to by using a [path] leading from the type or trait they are associated with. [Methods] can also be referred to via [call expressions].\nSimilar to items within a module or block, it is an error to introduce an item within a trait or implementation that is a duplicate of another item in the trait or impl in the same namespace.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Scopes", "heading_path": ["Scopes", "Item scopes", "Associated item scopes"], "path": "names/scopes.md", "url": "https://doc.rust-lang.org/reference/names/scopes.html#associated-item-scopes", "has_code": false, "code_tags": []}} {"id": "reference/names/scopes.md#pattern-binding-scopes-3", "text": "The Rust Reference › Scopes › Pattern binding scopes\n\nThe scope of a local variable [pattern] binding depends on where it is used:\n* [`let` statement] bindings range from just after the `let` statement until the end of the block where it is declared.\n* [Function parameter] bindings are within the body of the function.\n* [Closure parameter] bindings are within the closure body.\n* [`for`] bindings are within the loop body.\n* [`if let`] and [`while let`] bindings are valid in the following conditions as well as the consequent block.\n* [`match` arms] bindings are within the [match guard] and the match arm expression.\n* [`match` guard `let`] bindings are valid in the following guard conditions and the match arm expression.\nLocal variable scopes do not extend into item declarations.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Scopes", "heading_path": ["Scopes", "Pattern binding scopes"], "path": "names/scopes.md", "url": "https://doc.rust-lang.org/reference/names/scopes.html#pattern-binding-scopes", "has_code": false, "code_tags": []}} {"id": "reference/names/scopes.md#pattern-binding-shadowing-4", "text": "The Rust Reference › Scopes › Pattern binding scopes › Pattern binding shadowing\n\nPattern bindings are allowed to shadow any name in scope with the following exceptions which are an error:\n* [Const generic parameters]\n* [Static items]\n* [Const items]\n* Constructors for [structs] and [enums]\nThe following example illustrates how local bindings can shadow item declarations:\n```rust\nfn shadow_example() {\n // Since there are no local variables in scope yet, this resolves to the function.\n foo(); // prints `function`\n let foo = || println!(\"closure\");\n fn foo() { println!(\"function\"); }\n // This resolves to the local closure since it shadows the item.\n foo(); // prints `closure`\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Scopes", "heading_path": ["Scopes", "Pattern binding scopes", "Pattern binding shadowing"], "path": "names/scopes.md", "url": "https://doc.rust-lang.org/reference/names/scopes.html#pattern-binding-shadowing", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/names/scopes.md#generic-parameter-scopes-5", "text": "The Rust Reference › Scopes › Generic parameter scopes\n\nGeneric parameters are declared in a [GenericParams] list. The scope of a generic parameter is within the item it is declared on.\nAll parameters are in scope within the generic parameter list regardless of the order they are declared. The following shows some examples where a parameter may be referenced before it is declared:\n```rust\n// The 'b bound is referenced before it is declared.\nfn params_scope<'a: 'b, 'b>() {}\n\n// The const N is referenced in the trait bound before it is declared.\nfn f, const N: usize>() {}\n```\nGeneric parameters are also in scope for type bounds and where clauses, for example:\n```rust\n// The <'a, U> for `SomeTrait` refer to the 'a and U parameters of `bounds_scope`.\nfn bounds_scope<'a, T: SomeTrait<'a, U>, U>() {}\n\nfn where_scope<'a, T, U>()\n where T: SomeTrait<'a, U>\n{}\n```\nIt is an error for [items] declared inside a function to refer to a generic parameter from their outer scope.\n```rust,compile_fail\nfn example() {\n fn inner(x: T) {} // ERROR: can't use generic parameters from outer function\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Scopes", "heading_path": ["Scopes", "Generic parameter scopes"], "path": "names/scopes.md", "url": "https://doc.rust-lang.org/reference/names/scopes.html#generic-parameter-scopes", "has_code": true, "code_tags": ["rust", "rust,compile_fail"]}} {"id": "reference/names/scopes.md#generic-parameter-shadowing-6", "text": "The Rust Reference › Scopes › Generic parameter scopes › Generic parameter shadowing\n\nIt is an error to shadow a generic parameter with the exception that items declared within functions are allowed to shadow generic parameter names from the function.\n```rust\nfn example<'a, T, const N: usize>() {\n // Items within functions are allowed to shadow generic parameter in scope.\n fn inner_lifetime<'a>() {} // OK\n fn inner_type() {} // OK\n fn inner_const() {} // OK\n}\n```\n```rust,compile_fail\ntrait SomeTrait<'a, T, const N: usize> {\n fn example_lifetime<'a>() {} // ERROR: 'a is already in use\n fn example_type() {} // ERROR: T is already in use\n fn example_const() {} // ERROR: N is already in use\n fn example_mixed() {} // ERROR: T is already in use\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Scopes", "heading_path": ["Scopes", "Generic parameter scopes", "Generic parameter shadowing"], "path": "names/scopes.md", "url": "https://doc.rust-lang.org/reference/names/scopes.html#generic-parameter-shadowing", "has_code": true, "code_tags": ["rust", "rust,compile_fail"]}} {"id": "reference/names/scopes.md#impl-trait-restrictions-7", "text": "The Rust Reference › Scopes › Generic parameter scopes › Lifetime scopes › Impl trait restrictions\n\nLifetime parameters are declared in a [GenericParams] list and higher-ranked trait bounds.\nThe `'static` lifetime and [placeholder lifetime] `'_` have a special meaning and cannot be declared as a parameter.\n[Constant] and [static] items and [const contexts] only ever allow `'static` lifetime references, so no other lifetime may be in scope within them. [Associated consts] do allow referring to lifetimes declared in their trait or implementation.\nThe scope of a lifetime parameter declared as a higher-ranked trait bound depends on the scenario where it is used.\n* As a [TypeBoundWhereClauseItem] the declared lifetimes are in scope in the type and the type bounds.\n* As a [TraitBound] the declared lifetimes are in scope within the bound type path.\n* As a [BareFunctionType] the declared lifetimes are in scope within the function parameters and return type.\n```rust\n\nfn where_clause()\n // 'a is in scope in both the type and the type bounds.\n where for <'a> &'a T: Trait<'a>\n{}\n\nfn bound()\n // 'a is in scope within the bound.\n where T: for <'a> Trait<'a>\n{}\n\n\n// 'a is in scope in both the parameters and return type.\ntype FnExample = for<'a> fn(x: Example<'a>) -> Example<'a>;\n```\n[Impl trait] types can only reference lifetimes declared on a function or implementation.\n```rust\n// The `impl Trait2` here is not allowed to refer to 'b but it is allowed to\n// refer to 'a.\nfn foo<'a>() -> impl for<'b> Trait1 + use<'a>> {\n // ...\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Scopes", "heading_path": ["Scopes", "Generic parameter scopes", "Lifetime scopes", "Impl trait restrictions"], "path": "names/scopes.md", "url": "https://doc.rust-lang.org/reference/names/scopes.html#impl-trait-restrictions", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/names/scopes.md#loop-label-scopes-8", "text": "The Rust Reference › Scopes › Loop label scopes\n\n[Loop labels] may be declared by a [loop expression]. The scope of a loop label is from the point it is declared till the end of the loop expression. The scope does not extend into [items], [closures], [async blocks], [const arguments], [const contexts], and the iterator expression of the defining [`for` loop].\n```rust\n'a: for n in 0..3 {\n if n % 2 == 0 {\n break 'a;\n }\n fn inner() {\n // Using 'a here would be an error.\n // break 'a;\n }\n}\n\n// The label is in scope for the expression of `while` loops.\n'a: while break 'a {} // Loop does not run.\n'a: while let _ = break 'a {} // Loop does not run.\n\n// The label is not in scope in the defining `for` loop:\n'a: for outer in 0..5 {\n // This will break the outer loop, skipping the inner loop and stopping\n // the outer loop.\n 'a: for inner in { break 'a; 0..1 } {\n println!(\"{}\", inner); // This does not run.\n }\n println!(\"{}\", outer); // This does not run, either.\n}\n\n```\nLoop labels may shadow labels of the same name in outer scopes. References to a label refer to the closest definition.\n```rust\n// Loop label shadowing example.\n'a: for outer in 0..5 {\n 'a: for inner in 0..5 {\n // This terminates the inner loop, but the outer loop continues to run.\n break 'a;\n }\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Scopes", "heading_path": ["Scopes", "Loop label scopes"], "path": "names/scopes.md", "url": "https://doc.rust-lang.org/reference/names/scopes.html#loop-label-scopes", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/names/scopes.md#prelude-scopes-9", "text": "The Rust Reference › Scopes › Prelude scopes\n\n[Preludes] bring entities into scope of every module. The entities are not members of the module, but are implicitly queried during [name resolution].\nThe prelude names may be shadowed by declarations in a module.\nThe preludes are layered such that one shadows another if they contain entities of the same name. The order that preludes may shadow other preludes is the following where earlier entries may shadow later ones:\n1. [Extern prelude]\n2. [Tool prelude]\n3. [`macro_use` prelude]\n4. [Standard library prelude]\n5. [Language prelude]", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Scopes", "heading_path": ["Scopes", "Prelude scopes"], "path": "names/scopes.md", "url": "https://doc.rust-lang.org/reference/names/scopes.html#prelude-scopes", "has_code": false, "code_tags": []}} {"id": "reference/names/scopes.md#macro_rules-scopes-10", "text": "The Rust Reference › Scopes › `macro_rules` scopes\n\nThe scope of `macro_rules` macros is described in the [Macros By Example] chapter. The behavior depends on the use of the [`macro_use`] and [`macro_export`] attributes.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Scopes", "heading_path": ["Scopes", "`macro_rules` scopes"], "path": "names/scopes.md", "url": "https://doc.rust-lang.org/reference/names/scopes.html#macro_rules-scopes", "has_code": false, "code_tags": []}} {"id": "reference/names/scopes.md#derive-macro-helper-attributes-11", "text": "The Rust Reference › Scopes › Derive macro helper attributes\n\n[Derive macro helper attributes] are in scope in the item where their corresponding [`derive` attribute] is specified. The scope extends from just after the `derive` attribute to the end of the item. \nHelper attributes shadow other attributes of the same name in scope.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Scopes", "heading_path": ["Scopes", "Derive macro helper attributes"], "path": "names/scopes.md", "url": "https://doc.rust-lang.org/reference/names/scopes.html#derive-macro-helper-attributes", "has_code": false, "code_tags": []}} {"id": "reference/names/scopes.md#self-scope-12", "text": "The Rust Reference › Scopes › `Self` scope\n\nAlthough [`Self`] is a keyword with special meaning, it interacts with name resolution in a way similar to normal names.\nThe implicit `Self` type in the definition of a [struct], [enum], [union], [trait], or [implementation] is treated similarly to a generic parameter, and is in scope in the same way as a generic type parameter.\nThe implicit `Self` constructor in the value [namespace] of an [implementation] is in scope within the body of the implementation (the implementation's [associated items]).\n```rust\n// Self type within struct definition.\nstruct Recursive {\n f1: Option>\n}\n\n// Self type within generic parameters.\nstruct SelfGeneric>(T);\n\n// Self value constructor within an implementation.\nstruct ImplExample();\nimpl ImplExample {\n fn example() -> Self { // Self type\n Self() // Self value constructor\n }\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Scopes", "heading_path": ["Scopes", "`Self` scope"], "path": "names/scopes.md", "url": "https://doc.rust-lang.org/reference/names/scopes.html#self-scope", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/names/preludes.md#preludes-0", "text": "The Rust Reference › Preludes\n\nA *prelude* is a collection of names that are automatically brought into scope of every module in a crate.\nThese prelude names are not part of the module itself: they are implicitly queried during [name resolution]. For example, even though something like [`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.\nThere are several different preludes:\n- [Standard library prelude]\n- [Extern prelude]\n- [Language prelude]\n- [`macro_use` prelude]\n- [Tool prelude]", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Preludes", "heading_path": ["Preludes"], "path": "names/preludes.md", "url": "https://doc.rust-lang.org/reference/names/preludes.html#preludes", "has_code": false, "code_tags": []}} {"id": "reference/names/preludes.md#standard-library-prelude-1", "text": "The Rust Reference › Preludes › Standard library prelude\n\nEach crate has a standard library prelude, which consists of the names from a single standard library module.\nThe module used depends on the crate's edition, and on whether the [`no_std` attribute] is applied to the crate:\nEdition | `no_std` not applied | `no_std` applied\n--------| --------------------------- | ----------------------------\n2015 | [`std::prelude::rust_2015`] | [`core::prelude::rust_2015`]\n2018 | [`std::prelude::rust_2018`] | [`core::prelude::rust_2018`]\n2021 | [`std::prelude::rust_2021`] | [`core::prelude::rust_2021`]\n2024 | [`std::prelude::rust_2024`] | [`core::prelude::rust_2024`]\n[`std::prelude::rust_2015`] and [`std::prelude::rust_2018`] have the same contents as [`std::prelude::v1`].\n[`core::prelude::rust_2015`] and [`core::prelude::rust_2018`] have the same contents as [`core::prelude::v1`].\nWhen one of [`core::panic!`] or [`std::panic!`] is brought into scope due to the [standard library prelude], and a user-written [glob import] brings the other into scope, `rustc` currently allows use of `panic!`, even though it is ambiguous. The user-written glob import takes precedence to resolve this ambiguity.\nFor details, see [names.resolution.expansion.imports.ambiguity.panic-hack].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Preludes", "heading_path": ["Preludes", "Standard library prelude"], "path": "names/preludes.md", "url": "https://doc.rust-lang.org/reference/names/preludes.html#standard-library-prelude", "has_code": false, "code_tags": []}} {"id": "reference/names/preludes.md#extern-prelude-2", "text": "The Rust Reference › Preludes › Extern prelude\n\nExternal crates imported with [`extern crate`] 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.\nThe [`core`] crate is always added to the extern prelude.\nThe [`std`] crate is added as long as the [`no_std` attribute] is not specified in the crate root.\n[!EDITION-2018]\nIn the 2015 edition, crates in the extern prelude cannot be referenced via [use declarations], so it is generally standard practice to include `extern crate` declarations to bring them into scope.\nBeginning in the 2018 edition, [use declarations] can reference crates in the extern prelude, so it is considered unidiomatic to use `extern crate`.\nAdditional crates that ship with `rustc`, such as [`alloc`], and `test`, 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.\n```rust\nextern crate alloc;\nuse alloc::rc::Rc;\n```\nCargo does bring in `proc_macro` to the extern prelude for proc-macro crates only.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Preludes", "heading_path": ["Preludes", "Extern prelude"], "path": "names/preludes.md", "url": "https://doc.rust-lang.org/reference/names/preludes.html#extern-prelude", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/names/preludes.md#the-no_std-attribute-3", "text": "The Rust Reference › Preludes › Extern prelude › The `no_std` attribute\n\nThe *`no_std` attribute* causes the [`std`] crate to not be linked automatically and the [standard library prelude] to instead use the `core` prelude.\n```rust,ignore\n#![no_std]\n```\nUsing `no_std` 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`).\nUsing `no_std` does not prevent the standard library from being linked. It is still valid to write `extern crate std` in the crate or in one of its dependencies; this will cause the compiler to link the `std` crate into the program.\nThe `no_std` attribute uses the [MetaWord] syntax.\nThe `no_std` attribute may only be applied to the crate root.\nThe `no_std` attribute may be used any number of times on a form.\n`rustc` lints against any use following the first.\nThe `no_std` attribute changes the [standard library prelude] to use the `core` prelude instead of the `std` prelude.\n[!EDITION-2018]\nBefore the 2018 edition, `std` is injected into the crate root by default. If `no_std` is specified, `core` is injected instead. Starting with the 2018 edition, regardless of `no_std` being specified, neither is injected into the crate root.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Preludes", "heading_path": ["Preludes", "Extern prelude", "The `no_std` attribute"], "path": "names/preludes.md", "url": "https://doc.rust-lang.org/reference/names/preludes.html#the-no_std-attribute", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "reference/names/preludes.md#language-prelude-4", "text": "The Rust Reference › Preludes › Language prelude\n\nThe language prelude includes names of types and attributes that are built-in to the language. The language prelude is always in scope.\nIt includes the following:\n* [Type namespace]\n * [Boolean type] --- `bool`\n * [`char`]\n * [`str`]\n * [Integer types] --- `i8`, `i16`, `i32`, `i64`, `i128`, `u8`, `u16`, `u32`, `u64`, `u128`\n * [Machine-dependent integer types] --- `usize` and `isize`\n * [floating-point types] --- `f32` and `f64`\n* [Macro namespace]\n * [Built-in attributes]\n * Built-in derive macros", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Preludes", "heading_path": ["Preludes", "Language prelude"], "path": "names/preludes.md", "url": "https://doc.rust-lang.org/reference/names/preludes.html#language-prelude", "has_code": false, "code_tags": []}} {"id": "reference/names/preludes.md#macro_use-prelude-5", "text": "The Rust Reference › Preludes › `macro_use` prelude\n\nThe `macro_use` prelude includes macros from external crates that were imported by the [`macro_use` attribute] applied to an [`extern crate`].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Preludes", "heading_path": ["Preludes", "`macro_use` prelude"], "path": "names/preludes.md", "url": "https://doc.rust-lang.org/reference/names/preludes.html#macro_use-prelude", "has_code": false, "code_tags": []}} {"id": "reference/names/preludes.md#tool-prelude-6", "text": "The Rust Reference › Preludes › Tool prelude\n\nThe tool prelude includes tool names for external tools in the [type namespace]. See the [tool attributes] section for more details.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Preludes", "heading_path": ["Preludes", "Tool prelude"], "path": "names/preludes.md", "url": "https://doc.rust-lang.org/reference/names/preludes.html#tool-prelude", "has_code": false, "code_tags": []}} {"id": "reference/names/preludes.md#the-no_implicit_prelude-attribute-7", "text": "The Rust Reference › Preludes › The `no_implicit_prelude` attribute\n\nThe *`no_implicit_prelude` [attribute]* is used to prevent implicit preludes from being brought into scope.\n```rust\n// The attribute can be applied to the crate root to affect\n// all modules.\n#![no_implicit_prelude]\n\n// Or it can be applied to a module to only affect that module\n// and its descendants.\n#[no_implicit_prelude]\nmod example {\n // ...\n}\n```\nThe `no_implicit_prelude` attribute uses the [MetaWord] syntax.\nThe `no_implicit_prelude` attribute may only be applied to the crate or to a module.\n`rustc` ignores use in other positions but lints against it. This may become an error in the future.\nThe `no_implicit_prelude` attribute may be used any number of times on a form.\n`rustc` lints against any use following the first.\nThe `no_implicit_prelude` attribute prevents the [standard library prelude], [extern prelude], [`macro_use` prelude], and the [tool prelude] from being brought into scope for the module and its descendants.\nDespite `#![no_implicit_prelude]`, `rustc` currently brings certain macros implicitly into scope. Those macros are:\n- [`assert!`]\n- [`cfg!`]\n- [`cfg_select!`]\n- [`column!`]\n- [`compile_error!`]\n- [`concat!`]\n- [`concat_bytes!`]\n- [`env!`]\n- [`file!`]\n- [`format_args!`]\n- [`include!`]\n- [`include_bytes!`]\n- [`include_str!`]\n- [`line!`]\n- [`module_path!`]\n- [`option_env!`]\n- [`panic!`]\n- [`stringify!`]\n- [`unreachable!`]\nE.g., this works:\n```rust\n#![no_implicit_prelude]\nfn main() { assert!(true); }\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Preludes", "heading_path": ["Preludes", "The `no_implicit_prelude` attribute"], "path": "names/preludes.md", "url": "https://doc.rust-lang.org/reference/names/preludes.html#the-no_implicit_prelude-attribute", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/names/preludes.md#the-no_implicit_prelude-attribute-8", "text": "The Rust Reference › Preludes › The `no_implicit_prelude` attribute\n\nDon't rely on this behavior; it may be removed in the future. Always bring the items you need into scope explicitly when using `#![no_implicit_prelude]`.\nFor details, see Rust PR #62086 and Rust PR #139493.\nThe `no_implicit_prelude` attribute does not affect the [language prelude].\n[!EDITION-2018]\nIn the 2015 edition, the `no_implicit_prelude` attribute does not affect the [`macro_use` prelude], and all macros exported from the standard library are still included in the `macro_use` prelude. Starting in the 2018 edition, the attribute does remove the `macro_use` prelude.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Preludes", "heading_path": ["Preludes", "The `no_implicit_prelude` attribute"], "path": "names/preludes.md", "url": "https://doc.rust-lang.org/reference/names/preludes.html#the-no_implicit_prelude-attribute", "has_code": false, "code_tags": []}} {"id": "reference/paths.md#paths-0", "text": "The Rust Reference › Paths\n\nA *path* is a sequence of one or more path segments separated by `::` tokens. Paths are used to refer to [items], values, [types], [macros], and [attributes].\nTwo examples of simple paths consisting of only identifier segments:\n```rust,ignore\nx;\nx::y::z;\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Paths", "heading_path": ["Paths"], "path": "paths.md", "url": "https://doc.rust-lang.org/reference/paths.html#paths", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "reference/paths.md#simple-paths-1", "text": "The Rust Reference › Paths › Types of paths › Simple paths\n\n```grammar,paths\nSimplePath ->\n `::`? SimplePathSegment (`::` SimplePathSegment)*\n\nSimplePathSegment ->\n IDENTIFIER | `super` | `self` | `crate` | `$crate`\n```\nSimple paths are used in [visibility] markers, [attributes], macros, and [`use`] items. For example:\n```rust\nuse std::io::{self, Write};\nmod m {\n #[clippy::cyclomatic_complexity = \"0\"]\n pub (in super) fn f1() {}\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Paths", "heading_path": ["Paths", "Types of paths", "Simple paths"], "path": "paths.md", "url": "https://doc.rust-lang.org/reference/paths.html#simple-paths", "has_code": true, "code_tags": ["grammar,paths", "rust"]}} {"id": "reference/paths.md#paths-in-expressions-2", "text": "The Rust Reference › Paths › Types of paths › Paths in expressions\n\n```grammar,paths\nPathInExpression ->\n `::`? PathExprSegment (`::` PathExprSegment)*\n\nPathExprSegment ->\n PathIdentSegment (`::` GenericArgs)?\n\nPathIdentSegment ->\n IDENTIFIER | `super` | `self` | `Self` | `crate` | `$crate`\n\nGenericArgs ->\n `<` GenericArgList? `>`\n | `(` TypeList? `)` (`->` TypeNoBounds)?\n\nGenericArgList ->\n ( GenericArg `,` )* GenericArg `,`?\n\nTypeList ->\n ( Type `,` )* Type `,`?\n\nGenericArg ->\n Lifetime | Type | GenericArgsConst | GenericArgsBinding | GenericArgsBounds\n\nGenericArgsConst ->\n BlockExpression\n | LiteralExpression\n | `-` LiteralExpression\n | SimplePathSegment\n\nGenericArgsBinding ->\n TypePathSegment `=` Type\n\nGenericArgsBounds ->\n TypePathSegment `:` Bounds?\n```\nPaths in expressions allow for paths with generic arguments to be specified. They are used in various places in [expressions] and [patterns].\nThe `::` token is required before the opening `<` for generic arguments to avoid ambiguity with the less-than operator. This is colloquially known as \"turbofish\" syntax.\n```rust\n(0..10).collect::>();\nVec::::with_capacity(1024);\n```\nThe order of generic arguments is restricted to lifetime arguments, then type arguments, then const arguments, then equality constraints.\nConst arguments must be surrounded by braces unless they are a [literal], an [inferred const], or a single segment path. An [inferred const] may not be surrounded by braces.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Paths", "heading_path": ["Paths", "Types of paths", "Paths in expressions"], "path": "paths.md", "url": "https://doc.rust-lang.org/reference/paths.html#paths-in-expressions", "has_code": true, "code_tags": ["grammar,paths", "rust"]}} {"id": "reference/paths.md#paths-in-expressions-3", "text": "The Rust Reference › Paths › Types of paths › Paths in expressions\n\n```rust\nmod m {\n pub const C: usize = 1;\n}\nconst C: usize = m::C;\nfn f() -> [u8; N] { [0; N] }\n\nlet _ = f::<1>(); // Literal.\nlet _: [_; 1] = f::<_>(); // Inferred const.\nlet _: [_; 1] = f::<(((_)))>(); // Inferred const.\nlet _ = f::(); // Single segment path.\nlet _ = f::<{ m::C }>(); // Multi-segment path must be braced.\n```\n```rust,compile_fail\nfn f() -> [u8; N] { [0; _] }\nlet _: [_; 1] = f::<{ _ }>();\n// ^ ERROR `_` not allowed here\n```\nIn a generic argument list, an [inferred const] is parsed as an inferred type but then semantically treated as a separate kind of [const generic argument].\nThe synthetic type parameters corresponding to `impl Trait` types are implicit, and these cannot be explicitly specified.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Paths", "heading_path": ["Paths", "Types of paths", "Paths in expressions"], "path": "paths.md", "url": "https://doc.rust-lang.org/reference/paths.html#paths-in-expressions", "has_code": true, "code_tags": ["rust", "rust,compile_fail"]}} {"id": "reference/paths.md#qualified-paths-4", "text": "The Rust Reference › Paths › Qualified paths\n\n```grammar,paths\nQualifiedPathInExpression -> QualifiedPathType (`::` PathExprSegment)+\n\nQualifiedPathType -> `<` Type (`as` TypePath)? `>`\n\nQualifiedPathInType -> QualifiedPathType (`::` TypePathSegment)+\n```\nFully qualified paths allow for disambiguating the path for [trait implementations] and for specifying canonical paths. When used in a type specification, it supports using the type syntax specified below.\n```rust\nstruct S;\nimpl S {\n fn f() { println!(\"S\"); }\n}\ntrait T1 {\n fn f() { println!(\"T1 f\"); }\n}\nimpl T1 for S {}\ntrait T2 {\n fn f() { println!(\"T2 f\"); }\n}\nimpl T2 for S {}\nS::f(); // Calls the inherent impl.\n::f(); // Calls the T1 trait function.\n::f(); // Calls the T2 trait function.\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Paths", "heading_path": ["Paths", "Qualified paths"], "path": "paths.md", "url": "https://doc.rust-lang.org/reference/paths.html#qualified-paths", "has_code": true, "code_tags": ["grammar,paths", "rust"]}} {"id": "reference/paths.md#paths-in-types-5", "text": "The Rust Reference › Paths › Qualified paths › Paths in types\n\n```grammar,paths\nTypePath -> `::`? TypePathSegment (`::` TypePathSegment)*\n\nTypePathSegment -> PathIdentSegment (`::`? GenericArgs)?\n```\nType paths are used within type definitions, trait bounds, and qualified paths.\nAlthough the `::` token is allowed before the generics arguments, it is not required because there is no ambiguity like there is in [PathInExpression].\n```rust\nimpl ops::Index> for S { /*...*/ }\nfn i<'a>() -> impl Iterator> {\n // ...\n}\ntype G = std::boxed::Box isize>;\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Paths", "heading_path": ["Paths", "Qualified paths", "Paths in types"], "path": "paths.md", "url": "https://doc.rust-lang.org/reference/paths.html#paths-in-types", "has_code": true, "code_tags": ["grammar,paths", "rust"]}} {"id": "reference/paths.md#path-qualifiers-6", "text": "The Rust Reference › Paths › Path qualifiers\n\nPaths can be denoted with various leading qualifiers to change the meaning of how it is resolved.\n[`use` declarations] have additional behaviors and restrictions for `self`, `super`, `crate`, and `$crate`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Paths", "heading_path": ["Paths", "Path qualifiers"], "path": "paths.md", "url": "https://doc.rust-lang.org/reference/paths.html#path-qualifiers", "has_code": false, "code_tags": []}} {"id": "reference/paths.md#path-qualifiers-7", "text": "The Rust Reference › Paths › Path qualifiers › `::`\n\nPaths 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.\n[!EDITION-2018]\nIn 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).\nBeginning with the 2018 Edition, paths starting with `::` resolve from crates in the [extern prelude]. That is, they must be followed by the name of a crate.\n```rust\npub fn foo() {\n // In the 2018 edition, this accesses `std` via the extern prelude.\n // In the 2015 edition, this accesses `std` via the crate root.\n let now = ::std::time::Instant::now();\n println!(\"{:?}\", now);\n}\n```\n```rust,edition2015\n// 2015 Edition\nmod a {\n pub fn foo() {}\n}\nmod b {\n pub fn foo() {\n ::a::foo(); // call `a`'s foo function\n // In Rust 2018, `::a` would be interpreted as the crate `a`.\n }\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Paths", "heading_path": ["Paths", "Path qualifiers", "`::`"], "path": "paths.md", "url": "https://doc.rust-lang.org/reference/paths.html#path-qualifiers", "has_code": true, "code_tags": ["rust", "rust,edition2015"]}} {"id": "reference/paths.md#self-8", "text": "The Rust Reference › Paths › Path qualifiers › `self`\n\n`self` resolves the path relative to the current module.\n`self` may only be used as the first segment of a path (without a preceding `::`) or as the last segment (preceded by `::`).\nWhen `self` appears as the last segment of a path, it refers to the entity named by the preceding segment. The preceding path must resolve to a [module], [enumeration], or [trait].\n```rust\nmod m {\n pub enum E { V1 }\n pub trait Tr {}\n pub(in crate::m::self) fn g() {} // OK: Modules can be parents of `self`.\n}\ntype Ty = m::E::self; // OK: Enumerations can be parents of `self`.\nfn f() {} // OK: Traits can be parents of `self`.\n```\n```rust,compile_fail,E0223\nstruct S;\ntype Ty = S::self; // ERROR: Structs cannot be parents of `self`.\n```\nSee [items.use.self] for additional rules about `self` in `use` declarations.\nIn a method body, a path which consists of a single `self` segment resolves to the method's self parameter.\n```rust\nfn foo() {}\nfn bar() {\n self::foo();\n}\nstruct S(bool);\nimpl S {\n fn baz(self) {\n self.0;\n }\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Paths", "heading_path": ["Paths", "Path qualifiers", "`self`"], "path": "paths.md", "url": "https://doc.rust-lang.org/reference/paths.html#self", "has_code": true, "code_tags": ["rust", "rust,compile_fail,E0223"]}} {"id": "reference/paths.md#self-1-9", "text": "The Rust Reference › Paths › Path qualifiers › `Self`\n\n`Self`, with a capital \"S\", is used to refer to the current type being implemented or defined. It may be used in the following situations:\n* In a [trait] definition, it refers to the type implementing the trait.\n* In an [implementation], it refers to the type being implemented. When implementing a tuple or unit [struct], it also refers to the constructor in the [value namespace].\n* In the definition of a [struct], [enumeration], or [union], it refers to the type being defined. The definition is not allowed to be infinitely recursive (there must be an indirection).\nThe scope of `Self` behaves similarly to a generic parameter; see the [`Self` scope] section for more details.\n`Self` can only be used as the first segment, without a preceding `::`.\nThe `Self` path cannot include generic arguments (as in `Self::`).", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Paths", "heading_path": ["Paths", "Path qualifiers", "`Self`"], "path": "paths.md", "url": "https://doc.rust-lang.org/reference/paths.html#self-1", "has_code": false, "code_tags": []}} {"id": "reference/paths.md#self-1-10", "text": "The Rust Reference › Paths › Path qualifiers › `Self`\n\n```rust\ntrait T {\n type Item;\n const C: i32;\n // `Self` will be whatever type that implements `T`.\n fn new() -> Self;\n // `Self::Item` will be the type alias in the implementation.\n fn f(&self) -> Self::Item;\n}\nstruct S;\nimpl T for S {\n type Item = i32;\n const C: i32 = 9;\n fn new() -> Self { // `Self` is the type `S`.\n S\n }\n fn f(&self) -> Self::Item { // `Self::Item` is the type `i32`.\n Self::C // `Self::C` is the constant value `9`.\n }\n}\n\n// `Self` is in scope within the generics of a trait definition,\n// to refer to the type being defined.\ntrait Add {\n type Output;\n // `Self` can also reference associated items of the\n // type being implemented.\n fn add(self, rhs: Rhs) -> Self::Output;\n}\n\nstruct NonEmptyList {\n head: T,\n // A struct can reference itself (as long as it is not\n // infinitely recursive).\n tail: Option>,\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Paths", "heading_path": ["Paths", "Path qualifiers", "`Self`"], "path": "paths.md", "url": "https://doc.rust-lang.org/reference/paths.html#self-1", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/paths.md#super-11", "text": "The Rust Reference › Paths › Path qualifiers › `super`\n\n`super` in a path resolves to the parent module.\nIt may only be used in leading segments of the path, possibly after an initial `self` segment.\n```rust\nmod a {\n pub fn foo() {}\n}\nmod b {\n pub fn foo() {\n super::a::foo(); // call a's foo function\n }\n}\n```\n`super` may be repeated several times after the first `super` or `self` to refer to ancestor modules.\n```rust\nmod a {\n fn foo() {}\n\n mod b {\n mod c {\n fn foo() {\n super::super::foo(); // call a's foo function\n self::super::super::foo(); // call a's foo function\n }\n }\n }\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Paths", "heading_path": ["Paths", "Path qualifiers", "`super`"], "path": "paths.md", "url": "https://doc.rust-lang.org/reference/paths.html#super", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/paths.md#crate-12", "text": "The Rust Reference › Paths › Path qualifiers › `crate`\n\n`crate` resolves the path relative to the current crate.\n`crate` can only be used as the first segment, without a preceding `::`.\n```rust\nfn foo() {}\nmod a {\n fn bar() {\n crate::foo();\n }\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Paths", "heading_path": ["Paths", "Path qualifiers", "`crate`"], "path": "paths.md", "url": "https://doc.rust-lang.org/reference/paths.html#crate", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/paths.md#crate-1-13", "text": "The Rust Reference › Paths › Path qualifiers › `$crate`\n\n[`$crate`] is only used within [macro transcribers], and can only be used as the first segment, without a preceding `::`.\n[`$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.\n```rust\npub fn increment(x: u32) -> u32 {\n x + 1\n}\n\n#[macro_export]\nmacro_rules! inc {\n ($x:expr) => ( $crate::increment($x) )\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Paths", "heading_path": ["Paths", "Path qualifiers", "`$crate`"], "path": "paths.md", "url": "https://doc.rust-lang.org/reference/paths.html#crate-1", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/paths.md#canonical-paths-14", "text": "The Rust Reference › Paths › Canonical paths\n\nEach item defined in a module or implementation has a *canonical path* that corresponds to where within its crate it is defined.\nAll other paths to these items are aliases.\nThe canonical path is defined as a *path prefix* appended by the path segment the item itself defines.\n[Implementations] and [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.\nThe path prefix for modules is the canonical path to that module.\nFor bare implementations, it is the canonical path of the item being implemented surrounded by angle (`<>`) brackets.\nFor [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.\nThe 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Paths", "heading_path": ["Paths", "Canonical paths"], "path": "paths.md", "url": "https://doc.rust-lang.org/reference/paths.html#canonical-paths", "has_code": false, "code_tags": []}} {"id": "reference/paths.md#canonical-paths-15", "text": "The Rust Reference › Paths › Canonical paths\n\n```rust\n// Comments show the canonical path of the item.\n\nmod a { // crate::a\n pub struct Struct; // crate::a::Struct\n\n pub trait Trait { // crate::a::Trait\n fn f(&self); // crate::a::Trait::f\n }\n\n impl Trait for Struct {\n fn f(&self) {} // ::f\n }\n\n impl Struct {\n fn g(&self) {} // ::g\n }\n}\n\nmod without { // crate::without\n fn canonicals() { // crate::without::canonicals\n struct OtherStruct; // None\n\n trait OtherTrait { // None\n fn g(&self); // None\n }\n\n impl OtherTrait for OtherStruct {\n fn g(&self) {} // None\n }\n\n impl OtherTrait for crate::a::Struct {\n fn g(&self) {} // None\n }\n\n impl crate::a::Trait for OtherStruct {\n fn f(&self) {} // None\n }\n }\n}\n\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Paths", "heading_path": ["Paths", "Canonical paths"], "path": "paths.md", "url": "https://doc.rust-lang.org/reference/paths.html#canonical-paths", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/names/name-resolution.md#name-resolution-0", "text": "The Rust Reference › Name resolution\n\n_Name resolution_ is the process of tying paths and other identifiers to the declarations of those entities. Names are segregated into different [namespaces], allowing entities in different namespaces to share the same name without conflict. Each name is valid within a [scope], or a region of source text where that name may be referenced. Access to a name may be restricted based on its [visibility].\nName resolution is split into three stages throughout the compilation process. The first stage, *expansion-time resolution*, resolves all [`use` declarations] and [macro invocations]. The second stage, *primary resolution*, resolves all names that have not yet been resolved and that do not depend on type information to resolve. The last stage, *type-relative resolution*, resolves the remaining names once type information is available.\nExpansion-time resolution is also known as *early resolution*. Primary resolution is also known as *late resolution*.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Name resolution", "heading_path": ["Name resolution"], "path": "names/name-resolution.md", "url": "https://doc.rust-lang.org/reference/names/name-resolution.html#name-resolution", "has_code": false, "code_tags": []}} {"id": "reference/names/name-resolution.md#general-1", "text": "The Rust Reference › Name resolution › General\n\nThe rules within this section apply to all stages of name resolution.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Name resolution", "heading_path": ["Name resolution", "General"], "path": "names/name-resolution.md", "url": "https://doc.rust-lang.org/reference/names/name-resolution.html#general", "has_code": false, "code_tags": []}} {"id": "reference/names/name-resolution.md#scopes-2", "text": "The Rust Reference › Name resolution › General › Scopes\n\nThis is a placeholder for future expansion about resolution of names within various scopes.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Name resolution", "heading_path": ["Name resolution", "General", "Scopes"], "path": "names/name-resolution.md", "url": "https://doc.rust-lang.org/reference/names/name-resolution.html#scopes", "has_code": false, "code_tags": []}} {"id": "reference/names/name-resolution.md#expansion-time-name-resolution-3", "text": "The Rust Reference › Name resolution › Expansion-time name resolution\n\nExpansion-time name resolution is the stage of name resolution necessary to complete macro expansion and fully generate a crate's [AST]. This stage requires the resolution of macro invocations and `use` declarations. Resolving `use` declarations is required for macro invocations that resolve via [path-based scope]. Resolving macro invocations is required in order to expand them.\nAfter expansion-time name resolution, the AST must not contain any unexpanded macro invocations. Every macro invocation resolves to a valid definition that exists in the final AST or in an external crate.\n```rust,compile_fail\nm!(); // ERROR: Cannot find macro `m` in this scope.\n```\nThe resolution of names must be stable. After expansion, names in the fully expanded AST must resolve to the same definition regardless of the order in which macros are expanded and imports are resolved.\nAll name resolution candidates selected during macro expansion are considered speculative. Once the crate has been fully expanded, all speculative import resolutions are validated to ensure that macro expansion did not introduce any new ambiguities.\nDue to the iterative nature of macro expansion, this causes so-called time traveling ambiguities, such as when a macro or glob import introduces an item that is ambiguous with its own base path.\n```rust,compile_fail,E0659\nmacro_rules! f {\n () => {\n mod m {\n pub(crate) use f;\n }\n }\n}\nf!();\n\nconst _: () = {\n // Initially, we speculatively resolve `m` to the module in\n // the crate root.\n //\n // Expansion of `f` introduces a second `m` module inside this\n // body.\n //\n // Expansion-time resolution finalizes resolutions by re-\n // resolving all imports and macro invocations, sees the\n // introduced ambiguity and reports it as an error.\n m::f!(); // ERROR: `m` is ambiguous.\n};\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Name resolution", "heading_path": ["Name resolution", "Expansion-time name resolution"], "path": "names/name-resolution.md", "url": "https://doc.rust-lang.org/reference/names/name-resolution.html#expansion-time-name-resolution", "has_code": true, "code_tags": ["rust,compile_fail", "rust,compile_fail,E0659"]}} {"id": "reference/names/name-resolution.md#imports-4", "text": "The Rust Reference › Name resolution › Expansion-time name resolution › Imports\n\nAll `use` declarations are fully resolved during this stage of resolution. [Type-relative paths] cannot be resolved at this stage and will produce an error.\n```rust,no_run\nmod m {\n pub const C: () = ();\n pub enum E { V }\n pub type A = E;\n impl E {\n pub const C: () = ();\n }\n}\n\n// Valid imports resolved at expansion-time:\nuse m::C; // OK.\nuse m::E; // OK.\nuse m::A; // OK.\nuse m::E::V; // OK.\n\n// Valid expressions resolved during type-relative resolution:\nlet _ = m::A::V; // OK.\nlet _ = m::E::C; // OK.\n```\n```rust,compile_fail,E0432\n// Invalid type-relative imports that can't resolve at expansion-time:\nuse m::A::V; // ERROR: Unresolved import `m::A::V`.\nuse m::E::C; // ERROR: Unresolved import `m::E::C`.\n```\nNames introduced via `use` declarations in an [outer scope] are shadowed by candidates in the same namespace with the same name from an inner scope except where otherwise restricted by [name resolution ambiguities].\n```rust,no_run\npub mod m1 {\n pub mod ambig {\n pub const C: u8 = 1;\n }\n}\n\npub mod m2 {\n pub mod ambig {\n pub const C: u8 = 2;\n }\n}\n\n// This introduces the name `ambig` in the outer scope.\nuse m1::ambig;\nconst _: () = {\n // This shadows `ambig` in the inner scope.\n use m2::ambig;\n // The inner candidate is selected here\n // as the resolution of `ambig`.\n use ambig::C;\n assert!(C == 2);\n};\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Name resolution", "heading_path": ["Name resolution", "Expansion-time name resolution", "Imports"], "path": "names/name-resolution.md", "url": "https://doc.rust-lang.org/reference/names/name-resolution.html#imports", "has_code": true, "code_tags": ["rust,compile_fail,E0432", "rust,no_run"]}} {"id": "reference/names/name-resolution.md#ambiguities-5", "text": "The Rust Reference › Name resolution › Expansion-time name resolution › Imports › Ambiguities\n\nShadowing of names introduced via `use` declarations within a single scope is permitted in the following situations:\n- [`use` glob shadowing]\n- [Macro textual scope shadowing]\nThere are certain situations during expansion-time resolution where there are multiple macro definitions, `use` declarations, or modules an import or macro invocation's name could refer to where the compiler cannot consistently determine which candidate should shadow the other. Shadowing cannot be permitted in these situations and the compiler instead emits ambiguity errors.\nNames may not be resolved through ambiguous glob imports. Glob imports are allowed to import conflicting names in the same namespace as long as the name is not used. Names with conflicting candidates from ambiguous glob imports may still be shadowed by non-glob imports and used without producing an error. The errors occur at time of use, not time of import.\n```rust,compile_fail,E0659\nmod m1 {\n pub struct Ambig;\n}\n\nmod m2 {\n pub struct Ambig;\n}\n\n// OK: This brings conficting names in the same namespace into scope\n// but they have not been used yet.\nuse m1::*;\nuse m2::*;\n\nconst _: () = {\n // The error happens when the name with the conflicting candidates\n // is used.\n let x = Ambig; // ERROR: `Ambig` is ambiguous.\n};\n```\n```rust,no_run\nconst _: () = {\n // This is permitted, since resolution is not through the\n // ambiguous globs.\n struct Ambig;\n let x = Ambig; // OK.\n};\n```\nMultiple glob imports are allowed to import the same name, and that name is allowed to be used if the imports are of the same item (following reexports). The visibility of the name is the maximum visibility of the imports.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Name resolution", "heading_path": ["Name resolution", "Expansion-time name resolution", "Imports", "Ambiguities"], "path": "names/name-resolution.md", "url": "https://doc.rust-lang.org/reference/names/name-resolution.html#ambiguities", "has_code": true, "code_tags": ["rust,compile_fail,E0659", "rust,no_run"]}} {"id": "reference/names/name-resolution.md#ambiguities-6", "text": "The Rust Reference › Name resolution › Expansion-time name resolution › Imports › Ambiguities\n\n```rust,no_run\nmod m1 {\n pub struct Ambig;\n}\n\nmod m2 {\n // This reexports the same `Ambig` item from a second module.\n pub use super::m1::Ambig;\n}\n\nmod m3 {\n // These both import the same `Ambig`.\n //\n // The visibility of `Ambig` is `pub` because that is the\n // maximum visibility between these two `use` declarations.\n pub use super::m1::*;\n use super::m2::*;\n}\n\nmod m4 {\n // `Ambig` can be used through the `m3` globs and still has\n // `pub` visibility.\n pub use crate::m3::Ambig;\n}\n\nconst _: () = {\n // Therefore, we can use it here.\n let _ = m4::Ambig; // OK.\n};\n```\nNames in imports and macro invocations may not be resolved through glob imports when there is another candidate available in an [outer scope].\nWhen one of [`core::panic!`] or [`std::panic!`] is brought into scope due to the [standard library prelude], and a user-written [glob import] brings the other into scope, `rustc` currently allows use of `panic!`, even though it is ambiguous. The user-written glob import takes precedence to resolve this ambiguity.\nIn Rust 2021 and later, [`core::panic!`] and [`std::panic!`] operate identically. But in earlier editions, they differ; only [`std::panic!`] accepts a [`String`] as the format argument.\nE.g., this is an error:\n```rust,edition2018,compile_fail,E0308\nextern crate core;\nuse ::core::prelude::v1::*;\nfn main() {\n panic!(std::string::String::new()); // ERROR.\n}\n```\nAnd this is accepted:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Name resolution", "heading_path": ["Name resolution", "Expansion-time name resolution", "Imports", "Ambiguities"], "path": "names/name-resolution.md", "url": "https://doc.rust-lang.org/reference/names/name-resolution.html#ambiguities", "has_code": true, "code_tags": ["rust,edition2018,compile_fail,E0308", "rust,no_run"]}} {"id": "reference/names/name-resolution.md#ambiguities-7", "text": "The Rust Reference › Name resolution › Expansion-time name resolution › Imports › Ambiguities\n\n```rust,edition2018,ignore\n#![no_std]\nextern crate std;\nuse ::std::prelude::v1::*;\nfn main() {\n panic!(std::string::String::new()); // OK.\n}\n```\nDon't rely on this behavior; the plan is to remove it.\nFor details, see Rust issue #147319.\n```rust,compile_fail,E0659\nmod glob {\n pub mod ambig {\n pub struct Name;\n }\n}\n\n// Outer `ambig` candidate.\npub mod ambig {\n pub struct Name;\n}\n\nconst _: () = {\n // Cannot resolve `ambig` through this glob\n // because of the outer `ambig` candidate above.\n use glob::*;\n use ambig::Name; // ERROR: `ambig` is ambiguous.\n};\n```\n```rust,compile_fail,E0659\n// As above, but with macros.\npub mod m {\n macro_rules! f {\n () => {};\n }\n pub(crate) use f;\n}\npub mod glob {\n macro_rules! f {\n () => {};\n }\n pub(crate) use f as ambig;\n}\n\nuse m::f as ambig;\n\nconst _: () = {\n use glob::*;\n ambig!(); // ERROR: `ambig` is ambiguous.\n};\n```\nThese ambiguity errors are specific to expansion-time resolution. Having multiple candidates available for a given name during later stages of resolution is not considered an error. So long as none of the imports themselves are ambiguous, there will always be a single unambiguous closest resolution.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Name resolution", "heading_path": ["Name resolution", "Expansion-time name resolution", "Imports", "Ambiguities"], "path": "names/name-resolution.md", "url": "https://doc.rust-lang.org/reference/names/name-resolution.html#ambiguities", "has_code": true, "code_tags": ["rust,compile_fail,E0659", "rust,edition2018,ignore"]}} {"id": "reference/names/name-resolution.md#ambiguities-8", "text": "The Rust Reference › Name resolution › Expansion-time name resolution › Imports › Ambiguities\n\n```rust,no_run\nmod glob {\n pub const AMBIG: u8 = 1;\n}\n\nmod outer {\n pub const AMBIG: u8 = 2;\n}\n\nuse outer::AMBIG;\n\nconst C: () = {\n use glob::*;\n assert!(AMBIG == 1);\n // ^---- This `AMBIG` is resolved during primary resolution.\n};\n```\nNames may not be resolved through ambiguous macro reexports. Macro reexports are ambiguous when they would shadow a textual macro candidate for the same name in an [outer scope].\n```rust,compile_fail,E0659\n// Textual macro candidate.\nmacro_rules! ambig {\n () => {}\n}\n\n// Path-based macro candidate.\nmacro_rules! path_based {\n () => {}\n}\n\npub fn f() {\n // This reexport of the `path_based` macro definition\n // as `ambig` may not shadow the `ambig` macro definition\n // which is resolved via textual macro scope.\n use path_based as ambig;\n ambig!(); // ERROR: `ambig` is ambiguous.\n}\n```\nThis restriction is needed due to implementation details in the compiler, specifically the current scope visitation logic and the complexity of supporting this behavior. This ambiguity error may be removed in the future.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Name resolution", "heading_path": ["Name resolution", "Expansion-time name resolution", "Imports", "Ambiguities"], "path": "names/name-resolution.md", "url": "https://doc.rust-lang.org/reference/names/name-resolution.html#ambiguities", "has_code": true, "code_tags": ["rust,compile_fail,E0659", "rust,no_run"]}} {"id": "reference/names/name-resolution.md#ambiguities-1-9", "text": "The Rust Reference › Name resolution › Expansion-time name resolution › Macros › Ambiguities\n\nMacros are resolved by iterating through the available scopes to find the available candidates. Macros are split into two sub-namespaces, one for function-like macros, and the other for attributes and derives. Resolution candidates from the incorrect sub-namespace are ignored.\nThe available scope kinds are visited in the following order. Each of these scope kinds represent one or more scopes.\n* [Derive helpers]\n* [Textual scope macros]\n* [Path-based scope macros]\n* [`macro_use` prelude]\n* [Standard library prelude]\n* [Builtin attributes]\nThe compiler will attempt to resolve derive helpers that are used before their associated macro introduces them into scope. This scope is visited after the scope for resolving derive helper candidates that are correctly in scope. This behavior is slated for removal.\nFor more info see [derive helper scope].\nThis visitation order may change in the future, such as interleaving the visitation of textual and path-based scope candidates based on their lexical scopes.\n[!EDITION-2018]\nStarting in edition 2018 the `#[macro_use]` prelude is not visited when [`#[no_implicit_prelude]`][names.preludes.no_implicit_prelude] is present.\nThe names `cfg` and `cfg_attr` are reserved in the macro attribute [sub-namespace].\nNames may not be resolved through ambiguous candidates inside of macro expansions. Candidates inside of macro expansions are ambiguous when they would shadow a candidate for the same name from outside of the first candidate's macro expansion and the invocation of the name being resolved is also from outside of the first candidate's macro expansion.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Name resolution", "heading_path": ["Name resolution", "Expansion-time name resolution", "Macros", "Ambiguities"], "path": "names/name-resolution.md", "url": "https://doc.rust-lang.org/reference/names/name-resolution.html#ambiguities-1", "has_code": false, "code_tags": []}} {"id": "reference/names/name-resolution.md#ambiguities-1-10", "text": "The Rust Reference › Name resolution › Expansion-time name resolution › Macros › Ambiguities\n\n```rust,compile_fail,E0659\nmacro_rules! define_ambig {\n () => {\n macro_rules! ambig {\n () => {}\n }\n }\n}\n\n// Introduce outer candidate definition for `ambig` macro invocation.\nmacro_rules! ambig {\n () => {}\n}\n\n// Introduce a second candidate definition for `ambig` inside of a\n// macro expansion.\ndefine_ambig!();\n\n// The definition of `ambig` from the second invocation\n// of `define_ambig` is the innermost canadidate.\n//\n// The definition of `ambig` from the first invocation of\n// `define_ambig` is the second candidate.\n//\n// The compiler checks that the first candidate is inside of a macro\n// expansion, that the second candidate is not from within the same\n// macro expansion, and that the name being resolved is not from\n// within the same macro expansion.\nambig!(); // ERROR: `ambig` is ambiguous.\n```\nThe reverse is not considered ambiguous.\n```rust,no_run\n// Swap order of definitions.\ndefine_ambig!();\nmacro_rules! ambig {\n () => {}\n}\n// The innermost candidate is now less expanded so it may shadow more\n// the macro expanded definition above it.\nambig!();\n```\nNor is it ambiguous if the invocation being resolved is within the innermost candidate's expansion.\n```rust,no_run\nmacro_rules! ambig {\n () => {}\n}\n\nmacro_rules! define_and_invoke_ambig {\n () => {\n // Define innermost candidate.\n macro_rules! ambig {\n () => {}\n }\n\n // Invocation of `ambig` is in the same expansion as the\n // innermost candidate.\n ambig!(); // OK\n }\n}\n\ndefine_and_invoke_ambig!();\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Name resolution", "heading_path": ["Name resolution", "Expansion-time name resolution", "Macros", "Ambiguities"], "path": "names/name-resolution.md", "url": "https://doc.rust-lang.org/reference/names/name-resolution.html#ambiguities-1", "has_code": true, "code_tags": ["rust,compile_fail,E0659", "rust,no_run"]}} {"id": "reference/names/name-resolution.md#ambiguities-1-11", "text": "The Rust Reference › Name resolution › Expansion-time name resolution › Macros › Ambiguities\n\nIt doesn't matter if both definitions come from invocations of the same macro; the outermost candidate is still considered \"less expanded\" because it is not within the expansion containing the innermost candidate's definition.\n```rust,compile_fail,E0659\ndefine_ambig!();\ndefine_ambig!();\nambig!(); // ERROR: `ambig` is ambiguous.\n```\nThis also applies to imports so long as the innermost candidate for the name is from within a macro expansion.\n```rust,compile_fail,E0659\nmacro_rules! define_ambig {\n () => {\n mod ambig {\n pub struct Name;\n }\n }\n}\n\nmod ambig {\n pub struct Name;\n}\n\nconst _: () = {\n // Introduce innermost candidate for\n // `ambig` mod in this macro expansion.\n define_ambig!();\n use ambig::Name; // ERROR: `ambig` is ambiguous.\n};\n```\nUser-defined attributes or derive macros may not shadow built-in non-macro attributes (e.g. inline).\n```rust,ignore\n// with-helper/src/lib.rs\n#[proc_macro_derive(WithHelperAttr, attributes(non_exhaustive))]\n// ^^^^^^^^^^^^^^\n// User-defined attribute candidate.\n// ...\n```\n```rust,ignore\n// src/lib.rs\n#[derive(with_helper::WithHelperAttr)]\n#[non_exhaustive] // ERROR: `non_exhaustive` is ambiguous.\nstruct S;\n```\nThis applies regardless of the name the built-in attribute is a candidate for:\n```rust,ignore\n// with-helper/src/lib.rs\n#[proc_macro_derive(WithHelperAttr, attributes(helper))]\n// ^^^^^^\n// User-defined attribute candidate.\n// ...\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Name resolution", "heading_path": ["Name resolution", "Expansion-time name resolution", "Macros", "Ambiguities"], "path": "names/name-resolution.md", "url": "https://doc.rust-lang.org/reference/names/name-resolution.html#ambiguities-1", "has_code": true, "code_tags": ["rust,compile_fail,E0659", "rust,ignore"]}} {"id": "reference/names/name-resolution.md#ambiguities-1-12", "text": "The Rust Reference › Name resolution › Expansion-time name resolution › Macros › Ambiguities\n\n```rust,ignore\n// src/lib.rs\nuse inline as helper;\n// ^----- Built-in attribute candidate via reexport.\n\n#[derive(with_helper::WithHelperAttr)]\n#[helper] // ERROR: `helper` is ambiguous.\nstruct S;\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Name resolution", "heading_path": ["Name resolution", "Expansion-time name resolution", "Macros", "Ambiguities"], "path": "names/name-resolution.md", "url": "https://doc.rust-lang.org/reference/names/name-resolution.html#ambiguities-1", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "reference/names/name-resolution.md#primary-name-resolution-13", "text": "The Rust Reference › Name resolution › Primary name resolution\n\nThis is a placeholder for future expansion about primary name resolution.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Name resolution", "heading_path": ["Name resolution", "Primary name resolution"], "path": "names/name-resolution.md", "url": "https://doc.rust-lang.org/reference/names/name-resolution.html#primary-name-resolution", "has_code": false, "code_tags": []}} {"id": "reference/names/name-resolution.md#type-relative-resolution-14", "text": "The Rust Reference › Name resolution › Type-relative resolution\n\nThis is a placeholder for future expansion about type-dependent resolution.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Name resolution", "heading_path": ["Name resolution", "Type-relative resolution"], "path": "names/name-resolution.md", "url": "https://doc.rust-lang.org/reference/names/name-resolution.html#type-relative-resolution", "has_code": false, "code_tags": []}} {"id": "reference/visibility-and-privacy.md#visibility-and-privacy-0", "text": "The Rust Reference › Visibility and privacy\n\n```grammar,items\nVisibility ->\n `pub`\n | `pub` `(` `crate` `)`\n | `pub` `(` `self` `)`\n | `pub` `(` `super` `)`\n | `pub` `(` `in` SimplePath `)`\n```\nThese 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?\"\nRust'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.\nTo 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.\"\nBy 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:\n```rust\n// Declare a private struct\nstruct Foo;\n\n// Declare a public struct with a private field\npub struct Bar {\n field: i32,\n}\n\n// Declare a public enum with two public variants\npub enum State {\n PubliclyAccessibleState,\n PubliclyAccessibleState2,\n}\n```\nWith the notion of an item being either public or private, Rust allows item accesses in two cases:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Visibility and privacy", "heading_path": ["Visibility and privacy"], "path": "visibility-and-privacy.md", "url": "https://doc.rust-lang.org/reference/visibility-and-privacy.html#visibility-and-privacy", "has_code": true, "code_tags": ["grammar,items", "rust"]}} {"id": "reference/visibility-and-privacy.md#visibility-and-privacy-1", "text": "The Rust Reference › Visibility and privacy\n\n1. 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.\n2. If an item is private, it may be accessed by the current module and its descendants.\nThese 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:\n* 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.\n* 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.\n* 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.\nIn 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Visibility and privacy", "heading_path": ["Visibility and privacy"], "path": "visibility-and-privacy.md", "url": "https://doc.rust-lang.org/reference/visibility-and-privacy.html#visibility-and-privacy", "has_code": false, "code_tags": []}} {"id": "reference/visibility-and-privacy.md#visibility-and-privacy-2", "text": "The Rust Reference › Visibility and privacy\n\nAccessing 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.\nHere's an example of a program which exemplifies the three cases outlined above:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Visibility and privacy", "heading_path": ["Visibility and privacy"], "path": "visibility-and-privacy.md", "url": "https://doc.rust-lang.org/reference/visibility-and-privacy.html#visibility-and-privacy", "has_code": false, "code_tags": []}} {"id": "reference/visibility-and-privacy.md#visibility-and-privacy-3", "text": "The Rust Reference › Visibility and privacy\n\n```rust\n// This module is private, meaning that no external crate can access this\n// module. Because it is private at the root of this current crate, however, any\n// module in the crate may access any publicly visible item in this module.\nmod crate_helper_module {\n\n // This function can be used by anything in the current crate\n pub fn crate_helper() {}\n\n // This function *cannot* be used by anything else in the crate. It is not\n // publicly visible outside of the `crate_helper_module`, so only this\n // current module and its descendants may access it.\n fn implementation_detail() {}\n}\n\n// This function is \"public to the root\" meaning that it's available to external\n// crates linking against this one.\npub fn public_api() {}\n\n// Similarly to 'public_api', this module is public so external crates may look\n// inside of it.\npub mod submodule {\n use crate::crate_helper_module;\n\n pub fn my_method() {\n // Any item in the local crate may invoke the helper module's public\n // interface through a combination of the two rules above.\n crate_helper_module::crate_helper();\n }\n\n // This function is hidden to any module which is not a descendant of\n // `submodule`\n fn my_implementation() {}\n\n #[cfg(test)]\n mod test {\n\n #[test]\n fn test_my_implementation() {\n // Because this module is a descendant of `submodule`, it's allowed\n // to access private items inside of `submodule` without a privacy\n // violation.\n super::my_implementation();\n }\n }\n}\n\n```\nFor 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Visibility and privacy", "heading_path": ["Visibility and privacy"], "path": "visibility-and-privacy.md", "url": "https://doc.rust-lang.org/reference/visibility-and-privacy.html#visibility-and-privacy", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/visibility-and-privacy.md#pubin-path-pubcrate-pubsuper-and-pubself-4", "text": "The Rust Reference › Visibility and privacy › `pub(in path)`, `pub(crate)`, `pub(super)`, and `pub(self)`\n\nIn 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:\n- `pub(in path)` makes an item visible within the provided `path`. `path` must be a simple path which resolves to an ancestor module of the item whose visibility is being declared. Each identifier in `path` must refer directly to a module (not to a name introduced by a `use` statement).\n- `pub(crate)` makes an item visible within the current crate.\n- `pub(super)` makes an item visible to the parent module. This is equivalent to `pub(in super)`.\n- `pub(self)` makes an item visible to the current module. This is equivalent to `pub(in self)` or not using `pub` at all.\n[!EDITION-2018]\nStarting 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.\nHere's an example:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Visibility and privacy", "heading_path": ["Visibility and privacy", "`pub(in path)`, `pub(crate)`, `pub(super)`, and `pub(self)`"], "path": "visibility-and-privacy.md", "url": "https://doc.rust-lang.org/reference/visibility-and-privacy.html#pubin-path-pubcrate-pubsuper-and-pubself", "has_code": false, "code_tags": []}} {"id": "reference/visibility-and-privacy.md#pubin-path-pubcrate-pubsuper-and-pubself-5", "text": "The Rust Reference › Visibility and privacy › `pub(in path)`, `pub(crate)`, `pub(super)`, and `pub(self)`\n\n```rust,edition2015\npub mod outer_mod {\n pub mod inner_mod {\n // This function is visible within `outer_mod`\n pub(in crate::outer_mod) fn outer_mod_visible_fn() {}\n // Same as above, this is only valid in the 2015 edition.\n pub(in outer_mod) fn outer_mod_visible_fn_2015() {}\n\n // This function is visible to the entire crate\n pub(crate) fn crate_visible_fn() {}\n\n // This function is visible within `outer_mod`\n pub(super) fn super_mod_visible_fn() {\n // This function is visible since we're in the same `mod`\n inner_mod_visible_fn();\n }\n\n // This function is visible only within `inner_mod`,\n // which is the same as leaving it private.\n pub(self) fn inner_mod_visible_fn() {}\n }\n pub fn foo() {\n inner_mod::outer_mod_visible_fn();\n inner_mod::crate_visible_fn();\n inner_mod::super_mod_visible_fn();\n\n // This function is no longer visible since we're outside of `inner_mod`\n // Error! `inner_mod_visible_fn` is private\n //inner_mod::inner_mod_visible_fn();\n }\n}\n\nfn bar() {\n // This function is still visible since we're in the same crate\n outer_mod::inner_mod::crate_visible_fn();\n\n // This function is no longer visible since we're outside of `outer_mod`\n // Error! `super_mod_visible_fn` is private\n //outer_mod::inner_mod::super_mod_visible_fn();\n\n // This function is no longer visible since we're outside of `outer_mod`\n // Error! `outer_mod_visible_fn` is private\n //outer_mod::inner_mod::outer_mod_visible_fn();\n\n outer_mod::foo();\n}\n\nfn main() { bar() }\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Visibility and privacy", "heading_path": ["Visibility and privacy", "`pub(in path)`, `pub(crate)`, `pub(super)`, and `pub(self)`"], "path": "visibility-and-privacy.md", "url": "https://doc.rust-lang.org/reference/visibility-and-privacy.html#pubin-path-pubcrate-pubsuper-and-pubself", "has_code": true, "code_tags": ["rust,edition2015"]}} {"id": "reference/visibility-and-privacy.md#pubin-path-pubcrate-pubsuper-and-pubself-6", "text": "The Rust Reference › Visibility and privacy › `pub(in path)`, `pub(crate)`, `pub(super)`, and `pub(self)`\n\nThis 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Visibility and privacy", "heading_path": ["Visibility and privacy", "`pub(in path)`, `pub(crate)`, `pub(super)`, and `pub(self)`"], "path": "visibility-and-privacy.md", "url": "https://doc.rust-lang.org/reference/visibility-and-privacy.html#pubin-path-pubcrate-pubsuper-and-pubself", "has_code": false, "code_tags": []}} {"id": "reference/visibility-and-privacy.md#re-exporting-and-visibility-7", "text": "The Rust Reference › Visibility and privacy › Re-exporting and visibility\n\nRust 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:\n```rust\npub use self::implementation::api;\n\nmod implementation {\n pub mod api {\n pub fn f() {}\n }\n}\n\n```\nThis means that any external crate referencing `implementation::api::f` would receive a privacy violation, while the path `api::f` would be allowed.\nWhen 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Visibility and privacy", "heading_path": ["Visibility and privacy", "Re-exporting and visibility"], "path": "visibility-and-privacy.md", "url": "https://doc.rust-lang.org/reference/visibility-and-privacy.html#re-exporting-and-visibility", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/memory-model.md#memory-model-0", "text": "The Rust Reference › Memory model\n\nThe memory model of Rust is incomplete and not fully decided.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Memory model", "heading_path": ["Memory model"], "path": "memory-model.md", "url": "https://doc.rust-lang.org/reference/memory-model.html#memory-model", "has_code": false, "code_tags": []}} {"id": "reference/memory-model.md#bytes-1", "text": "The Rust Reference › Memory model › Bytes\n\nThe most basic unit of memory in Rust is a byte.\nWhile bytes are typically lowered to hardware bytes, Rust uses an \"abstract\" notion of bytes that can make distinctions which are absent in hardware, such as being uninitialized, or storing part of a pointer. Those distinctions can affect whether your program has undefined behavior, so they still have tangible impact on how compiled Rust programs behave.\nEach byte may have one of the following values:\n* An initialized byte containing a `u8` value and optional provenance,\n* An uninitialized byte.\nThe above list is not yet guaranteed to be exhaustive.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Memory model", "heading_path": ["Memory model", "Bytes"], "path": "memory-model.md", "url": "https://doc.rust-lang.org/reference/memory-model.html#bytes", "has_code": false, "code_tags": []}} {"id": "reference/memory-allocation-and-lifetime.md#memory-allocation-and-lifetime-0", "text": "The Rust Reference › Memory allocation and lifetime\n\nThe _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.\nThe _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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Memory allocation and lifetime", "heading_path": ["Memory allocation and lifetime"], "path": "memory-allocation-and-lifetime.md", "url": "https://doc.rust-lang.org/reference/memory-allocation-and-lifetime.html#memory-allocation-and-lifetime", "has_code": false, "code_tags": []}} {"id": "reference/variables.md#variables-0", "text": "The Rust Reference › Variables\n\nA _variable_ is a component of a stack frame, either a named function parameter, an anonymous temporary, or a named local variable.\nA _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.\nLocal variables are immutable unless declared otherwise. For example: `let mut x = ...`.\nFunction 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, y: Box)` declare one mutable variable `x` and one immutable variable `y`.\nLocal 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.\nIn this next example, `init_after_if` is initialized after the [`if` expression] while `uninit_after_if` is not because it is not initialized in the `else` case.\n```rust\nfn initialization_example() {\n let init_after_if: ();\n let uninit_after_if: ();\n\n if random_bool() {\n init_after_if = ();\n uninit_after_if = ();\n } else {\n init_after_if = ();\n }\n\n init_after_if; // ok\n // uninit_after_if; // err: use of possibly uninitialized `uninit_after_if`\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Variables", "heading_path": ["Variables"], "path": "variables.md", "url": "https://doc.rust-lang.org/reference/variables.html#variables", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/panic.md#panic-0", "text": "The Rust Reference › Panic\n\nRust provides a mechanism to prevent a function from returning normally, and instead \"panic,\" which is a response to an error condition that is typically not expected to be recoverable within the context in which the error is encountered.\nSome language constructs, such as out-of-bounds [array indexing], panic automatically.\nThere are also language features that provide a level of control over panic behavior:\n* A _panic handler_ defines the behavior of a panic.\n* FFI ABIs may alter how panics behave.\nThe standard library provides the capability to explicitly panic via the `panic!` macro.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Panic", "heading_path": ["Panic"], "path": "panic.md", "url": "https://doc.rust-lang.org/reference/panic.html#panic", "has_code": false, "code_tags": []}} {"id": "reference/panic.md#the-panic_handler-attribute-1", "text": "The Rust Reference › Panic › The `panic_handler` attribute\n\nThe *`panic_handler` attribute* can be applied to a function to define the behavior of panics.\nThe `panic_handler` attribute can only be applied to a function with signature `fn(&PanicInfo) -> !`.\nThe [`PanicInfo`] struct contains information about the location of the panic.\nThere must be a single `panic_handler` function in the dependency graph.\nBelow is shown a `panic_handler` function that logs the panic message and then halts the thread.\n```rust,ignore\n#![no_std]\n\nuse core::fmt::{self, Write};\nuse core::panic::PanicInfo;\n\nstruct Sink {\n // ..\n}\n\n#[panic_handler]\nfn panic(info: &PanicInfo) -> ! {\n let mut sink = Sink::new();\n\n // logs \"panicked at '$reason', src/main.rs:27:4\" to some `sink`\n let _ = writeln!(sink, \"{}\", info);\n\n loop {}\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Panic", "heading_path": ["Panic", "The `panic_handler` attribute"], "path": "panic.md", "url": "https://doc.rust-lang.org/reference/panic.html#the-panic_handler-attribute", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "reference/panic.md#standard-behavior-2", "text": "The Rust Reference › Panic › The `panic_handler` attribute › Standard behavior\n\n`std` provides two different panic handlers:\n* `unwind` --- unwinds the stack and is potentially recoverable.\n* `abort` ---- aborts the process and is non-recoverable.\nNot all targets may provide the `unwind` handler.\nThe panic handler used when linking with `std` can be set with the [`-C panic`] CLI flag. The default for most targets is `unwind`.\nThe standard library's panic behavior can be modified at runtime with the [`std::panic::set_hook`] function.\nLinking a [`no_std`] binary, dylib, cdylib, or staticlib will require specifying your own panic handler.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Panic", "heading_path": ["Panic", "The `panic_handler` attribute", "Standard behavior"], "path": "panic.md", "url": "https://doc.rust-lang.org/reference/panic.html#standard-behavior", "has_code": false, "code_tags": []}} {"id": "reference/panic.md#panic-strategy-3", "text": "The Rust Reference › Panic › Panic strategy\n\nThe _panic strategy_ defines the kind of panic behavior that a crate is built to support.\nThe panic strategy can be chosen in `rustc` with the [`-C panic`] CLI flag.\nWhen generating a binary, dylib, cdylib, or staticlib and linking with `std`, the `-C panic` CLI flag also influences which [panic handler] is used.\nWhen compiling code with the `abort` panic strategy, the optimizer may assume that unwinding across Rust frames is impossible, which can result in both code-size and runtime speed improvements.\nSee [link.unwinding] for restrictions on linking crates with different panic strategies. An implication is that crates built with the `unwind` strategy can use the `abort` panic handler, but the `abort` strategy cannot use the `unwind` panic handler.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Panic", "heading_path": ["Panic", "Panic strategy"], "path": "panic.md", "url": "https://doc.rust-lang.org/reference/panic.html#panic-strategy", "has_code": false, "code_tags": []}} {"id": "reference/panic.md#unwinding-4", "text": "The Rust Reference › Panic › Unwinding\n\nPanicking may either be recoverable or non-recoverable, though it can be configured (by choosing a non-unwinding panic handler) to always be non-recoverable. (The converse is not true: the `unwind` handler does not guarantee that all panics are recoverable, only that panicking via the `panic!` macro and similar standard library mechanisms is recoverable.)\nWhen a panic occurs, the `unwind` handler \"unwinds\" Rust frames, just as C++'s `throw` unwinds C++ frames, until the panic reaches the point of recovery (for instance at a thread boundary). This means that as the panic traverses Rust frames, live objects in those frames that implement `Drop` will have their `drop` methods called. Thus, when normal execution resumes, no-longer-accessible objects will have been \"cleaned up\" just as if they had gone out of scope normally.\nAs long as this guarantee of resource-cleanup is preserved, \"unwinding\" may be implemented without actually using the mechanism used by C++ for the target platform.\nThe standard library provides two mechanisms for recovering from a panic, [`std::panic::catch_unwind`] (which enables recovery within the panicking thread) and [`std::thread::spawn`] (which automatically sets up panic recovery for the spawned thread so that other threads may continue running).", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Panic", "heading_path": ["Panic", "Unwinding"], "path": "panic.md", "url": "https://doc.rust-lang.org/reference/panic.html#unwinding", "has_code": false, "code_tags": []}} {"id": "reference/panic.md#unwinding-across-ffi-boundaries-5", "text": "The Rust Reference › Panic › Unwinding › Unwinding across FFI boundaries\n\nIt is possible to unwind across FFI boundaries using an appropriate ABI declaration. While useful in certain cases, this creates unique opportunities for undefined behavior, especially when multiple language runtimes are involved.\nUnwinding with the wrong ABI is undefined behavior:\n* Causing an unwind into Rust code from a foreign function that was called via a function declaration or pointer declared with a non-unwinding ABI, such as `\"C\"`, `\"system\"`, etc. (For example, this case occurs when such a function written in C++ throws an exception that is uncaught and propagates to Rust.)\n* Calling a Rust `extern` function that unwinds (with `extern \"C-unwind\"` or another ABI that permits unwinding) from code that does not support unwinding, such as code compiled with GCC or Clang using `-fno-exceptions`\nCatching a foreign unwinding operation (such as a C++ exception) using [`std::panic::catch_unwind`], [`std::thread::JoinHandle::join`], or by letting it propagate beyond the Rust `main()` function or thread root will have one of two behaviors, and it is unspecified which will occur:\n* The process aborts.\n* The function returns a [`Result::Err`] containing an opaque type.\nRust code compiled or linked with a different instance of the Rust standard library counts as a \"foreign exception\" for the purpose of this guarantee. Thus, a library that uses `panic!` and is linked against one version of the Rust standard library, invoked from an application that uses a different version of the standard library, may cause the entire application to abort even if the library is only used within a child thread.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Panic", "heading_path": ["Panic", "Unwinding", "Unwinding across FFI boundaries"], "path": "panic.md", "url": "https://doc.rust-lang.org/reference/panic.html#unwinding-across-ffi-boundaries", "has_code": false, "code_tags": []}} {"id": "reference/panic.md#unwinding-across-ffi-boundaries-6", "text": "The Rust Reference › Panic › Unwinding › Unwinding across FFI boundaries\n\nThere are currently no guarantees about the behavior that occurs when a foreign runtime attempts to dispose of, or rethrow, a Rust `panic` payload. In other words, an unwind originated from a Rust runtime must either lead to termination of the process or be caught by the same runtime.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Panic", "heading_path": ["Panic", "Unwinding", "Unwinding across FFI boundaries"], "path": "panic.md", "url": "https://doc.rust-lang.org/reference/panic.html#unwinding-across-ffi-boundaries", "has_code": false, "code_tags": []}} {"id": "reference/linkage.md#linkage-0", "text": "The Rust Reference › Linkage\n\nThis section is described more in terms of the compiler than of the language.\nThe 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.\nIn one session of compilation, the compiler can generate multiple artifacts through the use 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.\n* `--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.\n* `--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).", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Linkage", "heading_path": ["Linkage"], "path": "linkage.md", "url": "https://doc.rust-lang.org/reference/linkage.html#linkage", "has_code": false, "code_tags": []}} {"id": "reference/linkage.md#linkage-1", "text": "The Rust Reference › Linkage\n\n* `--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.\n* `--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.\n Note that any dynamic dependencies that the static library may have (such as dependencies on system libraries, or dependencies on Rust libraries that are compiled as dynamic libraries) will have to be specified manually when linking that static library from somewhere. The `--print=native-static-libs` flag may help with this.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Linkage", "heading_path": ["Linkage"], "path": "linkage.md", "url": "https://doc.rust-lang.org/reference/linkage.html#linkage", "has_code": false, "code_tags": []}} {"id": "reference/linkage.md#linkage-2", "text": "The Rust Reference › Linkage\n\nNote that, because the resulting static library contains the code of all the dependencies, including the standard library, and also exports all public symbols of them, linking the static library into an executable or shared library may need special care. In case of a shared library the list of exported symbols will have to be limited via e.g. a linker or symbol version script, exported symbols list (macOS), or module definition file (Windows). Additionally, unused sections can be removed to remove all code of dependencies that is not actually used (e.g. `--gc-sections` or `-dead_strip` for macOS).\n* `--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.\n* `--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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Linkage", "heading_path": ["Linkage"], "path": "linkage.md", "url": "https://doc.rust-lang.org/reference/linkage.html#linkage", "has_code": false, "code_tags": []}} {"id": "reference/linkage.md#linkage-3", "text": "The Rust Reference › Linkage\n\n* `--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]. The compiler will automatically set the `proc_macro` [configuration option]. 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.\nNote 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.\nWith 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:\n1. 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Linkage", "heading_path": ["Linkage"], "path": "linkage.md", "url": "https://doc.rust-lang.org/reference/linkage.html#linkage", "has_code": false, "code_tags": []}} {"id": "reference/linkage.md#linkage-4", "text": "The Rust Reference › Linkage\n\nNote 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.\n2. 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.\n 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`!\n3. 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).\n4. 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.\n 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.\n 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.\n 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Linkage", "heading_path": ["Linkage"], "path": "linkage.md", "url": "https://doc.rust-lang.org/reference/linkage.html#linkage", "has_code": false, "code_tags": []}} {"id": "reference/linkage.md#linkage-5", "text": "The Rust Reference › Linkage\n\nIn 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Linkage", "heading_path": ["Linkage"], "path": "linkage.md", "url": "https://doc.rust-lang.org/reference/linkage.html#linkage", "has_code": false, "code_tags": []}} {"id": "reference/linkage.md#static-and-dynamic-c-runtimes-6", "text": "The Rust Reference › Linkage › Static and dynamic C runtimes\n\nThe 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:\n* `arm-unknown-linux-musleabi`\n* `arm-unknown-linux-musleabihf`\n* `armv7-unknown-linux-musleabihf`\n* `i686-unknown-linux-musl`\n* `x86_64-unknown-linux-musl`\nThe 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:\n```sh\nrustc -C target-feature=+crt-static foo.rs\n```\nwhereas to link dynamically to the C runtime you would execute:\n```sh\nrustc -C target-feature=-crt-static foo.rs\n```\nTargets 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.\nCrates 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]:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Linkage", "heading_path": ["Linkage", "Static and dynamic C runtimes"], "path": "linkage.md", "url": "https://doc.rust-lang.org/reference/linkage.html#static-and-dynamic-c-runtimes", "has_code": true, "code_tags": ["sh"]}} {"id": "reference/linkage.md#static-and-dynamic-c-runtimes-7", "text": "The Rust Reference › Linkage › Static and dynamic C runtimes\n\n```rust\n#[cfg(target_feature = \"crt-static\")]\nfn foo() {\n println!(\"the C runtime should be statically linked\");\n}\n\n#[cfg(not(target_feature = \"crt-static\"))]\nfn foo() {\n println!(\"the C runtime should be dynamically linked\");\n}\n```\nAlso note that Cargo build scripts can learn about this feature through environment variables. In a build script you can detect the linkage via:\n```rust\nuse std::env;\n\nfn main() {\n let linkage = env::var(\"CARGO_CFG_TARGET_FEATURE\").unwrap_or(String::new());\n\n if linkage.contains(\"crt-static\") {\n println!(\"the C runtime will be statically linked\");\n } else {\n println!(\"the C runtime will be dynamically linked\");\n }\n}\n```\nTo 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:\n```sh\nRUSTFLAGS='-C target-feature=+crt-static' cargo build --target x86_64-pc-windows-msvc\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Linkage", "heading_path": ["Linkage", "Static and dynamic C runtimes"], "path": "linkage.md", "url": "https://doc.rust-lang.org/reference/linkage.html#static-and-dynamic-c-runtimes", "has_code": true, "code_tags": ["rust", "sh"]}} {"id": "reference/linkage.md#mixed-rust-and-foreign-codebases-8", "text": "The Rust Reference › Linkage › Mixed Rust and foreign codebases\n\nIf you are mixing Rust with foreign code (e.g. C, C++) and wish to make a single binary containing both types of code, you have two approaches for the final binary link:\n* Use `rustc`. Pass any non-Rust libraries using `-L ` and `-l` rustc arguments, and/or `#[link]` directives in your Rust code. If you need to link against `.o` files you can use `-Clink-arg=file.o`.\n* Use your foreign linker. In this case, you first need to generate a Rust `staticlib` target and pass that into your foreign linker invocation. If you need to link multiple Rust subsystems, you will need to generate a _single_ `staticlib` perhaps using lots of `extern crate` statements to include multiple Rust `rlib`s. Multiple Rust `staticlib` files are likely to conflict.\nPassing `rlib`s directly into your foreign linker is currently unsupported.\nRust code compiled or linked with a different instance of the Rust runtime counts as \"foreign code\" for the purpose of this section.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Linkage", "heading_path": ["Linkage", "Mixed Rust and foreign codebases"], "path": "linkage.md", "url": "https://doc.rust-lang.org/reference/linkage.html#mixed-rust-and-foreign-codebases", "has_code": false, "code_tags": []}} {"id": "reference/linkage.md#prohibited-linkage-and-unwinding-9", "text": "The Rust Reference › Linkage › Mixed Rust and foreign codebases › Prohibited linkage and unwinding\n\nPanic unwinding can only be used if the binary is built consistently according to the following rules.\nA Rust artifact is called *potentially unwinding* if any of the following conditions is met:\n- The artifact uses the `unwind` panic handler.\n- The artifact contains a crate built with the `unwind` [panic strategy] that makes a call to a function using a `-unwind` ABI.\n- The artifact makes a `\"Rust\"` ABI call to code running in another Rust artifact that has a separate copy of the Rust runtime, and that other artifact is potentially unwinding.\nThis definition captures whether a `\"Rust\"` ABI call inside a Rust artifact can ever unwind.\nIf a Rust artifact is potentially unwinding, then all its crates must be built with the `unwind` [panic strategy]. Otherwise, unwinding can cause undefined behavior.\nIf you are using `rustc` to link, these rules are enforced automatically. If you are *not* using `rustc` to link, you must take care to ensure that unwinding is handled consistently across the entire binary. Linking without `rustc` includes using `dlopen` or similar facilities where linking is done by the system runtime without `rustc` being involved. This can only happen when mixing code with different [`-C panic`] flags, so most users do not have to be concerned about this.\nTo guarantee that a library will be sound (and linkable with `rustc`) regardless of the panic runtime used at link-time, the [`ffi_unwind_calls` lint] may be used. The lint flags any calls to `-unwind` foreign functions or function pointers.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Linkage", "heading_path": ["Linkage", "Mixed Rust and foreign codebases", "Prohibited linkage and unwinding"], "path": "linkage.md", "url": "https://doc.rust-lang.org/reference/linkage.html#prohibited-linkage-and-unwinding", "has_code": false, "code_tags": []}} {"id": "reference/inline-assembly.md#inline-assembly-0", "text": "The Rust Reference › Inline assembly\n\nSupport for inline assembly is provided via the [`asm!`], [`naked_asm!`], and [`global_asm!`] macros. It can be used to embed handwritten assembly in the assembly output generated by the compiler.\nSupport for inline assembly is stable on the following architectures:\n- x86 and x86-64\n- ARM\n- AArch64 and Arm64EC\n- RISC-V\n- LoongArch\n- s390x\n- PowerPC and PowerPC64\nThe compiler will emit an error if an assembly macro is used on an unsupported target.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#inline-assembly", "has_code": false, "code_tags": []}} {"id": "reference/inline-assembly.md#example-1", "text": "The Rust Reference › Inline assembly › Example\n\n```rust\nuse std::arch::asm;\n\n// Multiply x by 6 using shifts and adds\nlet mut x: u64 = 4;\nunsafe {\n asm!(\n \"mov {tmp}, {x}\",\n \"shl {tmp}, 1\",\n \"shl {x}, 2\",\n \"add {x}, {tmp}\",\n x = inout(reg) x,\n tmp = out(reg) _,\n );\n}\nassert_eq!(x, 4 * 6);\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Example"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#example", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/inline-assembly.md#syntax-2", "text": "The Rust Reference › Inline assembly › Syntax\n\nThe following grammar specifies the arguments that can be passed to the `asm!`, `global_asm!` and `naked_asm!` macros.\n```grammar,assembly\n@root AsmArgs -> AsmAttrFormatString (`,` AsmAttrFormatString)* (`,` AsmAttrOperand)* `,`?\n\nFormatString -> STRING_LITERAL | RAW_STRING_LITERAL | MacroInvocation\n\nAsmAttrFormatString -> (OuterAttribute)* FormatString\n\nAsmOperand ->\n ClobberAbi\n | AsmOptions\n | RegOperand\n\nAsmAttrOperand -> (OuterAttribute)* AsmOperand\n\nClobberAbi -> `clobber_abi` `(` Abi (`,` Abi)* `,`? `)`\n\nAsmOptions ->\n `options` `(` ( AsmOption (`,` AsmOption)* `,`? )? `)`\n\nAsmOption ->\n `pure`\n | `nomem`\n | `readonly`\n | `preserves_flags`\n | `noreturn`\n | `nostack`\n | `att_syntax`\n | `raw`\n\nRegOperand -> (ParamName `=`)?\n (\n DirSpec `(` RegSpec `)` Expression\n | DualDirSpec `(` RegSpec `)` DualDirSpecExpression\n | `sym` PathExpression\n | `const` Expression\n | `label` `{` Statements? `}`\n )\n\nParamName -> IDENTIFIER_OR_KEYWORD | RAW_IDENTIFIER\n\nDualDirSpecExpression ->\n Expression\n | Expression `=>` Expression\n\nRegSpec -> RegisterClass | ExplicitRegister\n\nRegisterClass -> IDENTIFIER_OR_KEYWORD\n\nExplicitRegister -> STRING_LITERAL\n\nDirSpec ->\n `in`\n | `out`\n | `lateout`\n\nDualDirSpec ->\n `inout`\n | `inlateout`\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Syntax"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#syntax", "has_code": true, "code_tags": ["grammar,assembly"]}} {"id": "reference/inline-assembly.md#scope-3", "text": "The Rust Reference › Inline assembly › Scope\n\nInline assembly can be used in one of three ways.\nWith 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 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.\n```rust\nunsafe { core::arch::asm!(\"/* {} */\", in(reg) 0); }\n```\nWith the `naked_asm!` macro, the assembly code is emitted in a function scope and constitutes the full assembly code of a function. The `naked_asm!` macro is only allowed in naked functions.\n```rust\ncore::arch::naked_asm!(\"/* {} */\", const 0);\n```\nWith 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.\n```rust\ncore::arch::global_asm!(\"/* {} */\", const 0);\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Scope"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#scope", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/inline-assembly.md#template-string-arguments-4", "text": "The Rust Reference › Inline assembly › Template string arguments\n\nThe assembler template uses the same syntax as format strings (i.e. placeholders are specified by curly braces).\nThe corresponding arguments are accessed in order, by index, or by name.\n```rust\nlet x: i64;\nlet y: i64;\nlet z: i64;\n// This\nunsafe { core::arch::asm!(\"mov {}, {}\", out(reg) x, in(reg) 5); }\n// ... this\nunsafe { core::arch::asm!(\"mov {0}, {1}\", out(reg) y, in(reg) 5); }\n// ... and this\nunsafe { core::arch::asm!(\"mov {out}, {in}\", out = out(reg) z, in = in(reg) 5); }\n// all have the same behavior\nassert_eq!(x, y);\nassert_eq!(y, z);\n```\nHowever, implicit named arguments (introduced by RFC #2795) are not supported.\n```rust,compile_fail\nlet x = 5;\n// We can't refer to `x` from the scope directly, we need an operand like `in(reg) x`\nunsafe { core::arch::asm!(\"/* {x} */\"); } // ERROR: no argument named x\n```\nAn `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 use is for each template string argument to correspond to a line of assembly code.\n```rust\nlet x: i64;\nlet y: i64;\n// We can separate multiple strings as if they were written together\nunsafe { core::arch::asm!(\"mov eax, 5\", \"mov ecx, eax\", out(\"rax\") x, out(\"rcx\") y); }\nassert_eq!(x, y);\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Template string arguments"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#template-string-arguments", "has_code": true, "code_tags": ["rust", "rust,compile_fail"]}} {"id": "reference/inline-assembly.md#template-string-arguments-5", "text": "The Rust Reference › Inline assembly › Template string arguments\n\nAll template string arguments must appear before any other arguments.\n```rust,compile_fail\nlet x = 5;\n// The template strings need to appear first in the asm invocation\nunsafe { core::arch::asm!(\"/* {x} */\", x = const 5, \"ud2\"); } // ERROR: unexpected token\n```\nAs with format strings, positional arguments must appear before named arguments and explicit register operands.\n```rust,compile_fail\n// Named operands need to come after positional ones\nunsafe { core::arch::asm!(\"/* {x} {} */\", x = const 5, in(reg) 5); }\n// ERROR: positional arguments cannot follow named arguments or explicit register arguments\n```\n```rust,compile_fail\n// We also can't put explicit registers before positional operands\nunsafe { core::arch::asm!(\"/* {} */\", in(\"eax\") 0, in(reg) 5); }\n// ERROR: positional arguments cannot follow named arguments or explicit register arguments\n```\nExplicit register operands cannot be used by placeholders in the template string.\n```rust,compile_fail\n// Explicit register operands don't get substituted, use `eax` explicitly in the string\nunsafe { core::arch::asm!(\"/* {} */\", in(\"eax\") 5); }\n// ERROR: invalid reference to argument at index 0\n```\nAll other named and positional operands must appear at least once in the template string, otherwise a compiler error is generated.\n```rust,compile_fail\n// We have to name all of the operands in the format string\nunsafe { core::arch::asm!(\"\", in(reg) 5, x = const 5); }\n// ERROR: multiple unused asm arguments\n```\nThe 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Template string arguments"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#template-string-arguments", "has_code": true, "code_tags": ["rust,compile_fail"]}} {"id": "reference/inline-assembly.md#template-string-arguments-6", "text": "The Rust Reference › Inline assembly › Template string arguments\n\nCurrently, 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Template string arguments"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#template-string-arguments", "has_code": false, "code_tags": []}} {"id": "reference/inline-assembly.md#attributes-7", "text": "The Rust Reference › Inline assembly › Attributes\n\nOnly the [`cfg`] and [`cfg_attr`] attributes are accepted semantically on inline assembly template strings and operands. Other attributes are parsed but rejected when the assembly macro is expanded.\n```rust\ncore::arch::global_asm!(\n #[cfg(not(panic = \"abort\"))]\n \".cfi_startproc\",\n // ...\n \"ret\",\n #[cfg(not(panic = \"abort\"))]\n \".cfi_endproc\",\n);\n```\nIn `rustc`, the assembly macros implement handling of these attributes separately from the normal system that handles similar attributes in the language. This accounts for the limited kinds of attributes supported and may give rise to subtle differences in behavior.\nSyntactically there must be at least one template string before the first operand.\n```rust,compile_fail\n// This is rejected because `a = out(reg) x` does not parse as a\n// template string.\ncore::arch::asm!(\n #[cfg(false)]\n a = out(reg) x, // ERROR.\n \"\",\n);\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Attributes"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#attributes", "has_code": true, "code_tags": ["rust", "rust,compile_fail"]}} {"id": "reference/inline-assembly.md#operand-type-8", "text": "The Rust Reference › Inline assembly › Operand type\n\nSeveral types of operands are supported:\n* `in() `\n - `` can refer to a register class or an explicit register. The allocated register name is substituted into the asm template string.\n - The allocated register will contain the value of `` at the start of the assembly code.\n - The allocated register must contain the same value at the end of the assembly code (except if a `lateout` is allocated to the same register).\n```rust\n// ``in` can be used to pass values into inline assembly...\nunsafe { core::arch::asm!(\"/* {} */\", in(reg) 5); }\n```\nIf the value's type is smaller than the register, the value of the upper bits is platform-specific. Some targets zero out the upper bits, while others leave them untouched.\n* `out() `\n - `` can refer to a register class or an explicit register. The allocated register name is substituted into the asm template string.\n - The allocated register will contain an undefined value at the start of the assembly code.\n - `` must be a (possibly uninitialized) place expression, to which the contents of the allocated register are written at the end of the assembly code.\n - 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 assembly code (effectively acting as a clobber).\n```rust\nlet x: i64;\n// and `out` can be used to pass values back to rust.\nunsafe { core::arch::asm!(\"/* {} */\", out(reg) x); }\n```\n* `lateout() `\n - Identical to `out` except that the register allocator can reuse a register allocated to an `in`.\n - You should only write to the register after all inputs are read, otherwise you may clobber an input.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Operand type"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#operand-type", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/inline-assembly.md#operand-type-9", "text": "The Rust Reference › Inline assembly › Operand type\n\n```rust\nlet x: i64;\n// `lateout` is the same as `out`\n// but the compiler knows we don't care about the value of any inputs by the\n// time we overwrite it.\nunsafe { core::arch::asm!(\"mov {}, 5\", lateout(reg) x); }\nassert_eq!(x, 5)\n```\n* `inout() `\n - `` can refer to a register class or an explicit register. The allocated register name is substituted into the asm template string.\n - The allocated register will contain the value of `` at the start of the assembly code.\n - `` must be a mutable initialized place expression, to which the contents of the allocated register are written at the end of the assembly code.\n```rust\nlet mut x: i64 = 4;\n// `inout` can be used to modify values in-register\nunsafe { core::arch::asm!(\"inc {}\", inout(reg) x); }\nassert_eq!(x, 5);\n```\n* `inout() => `\n - Same as `inout` except that the initial value of the register is taken from the value of ``.\n - `` must be a (possibly uninitialized) place expression, to which the contents of the allocated register are written at the end of the assembly code.\n - An underscore (`_`) may be specified instead of an expression for ``, which will cause the contents of the register to be discarded at the end of the assembly code (effectively acting as a clobber).\n - `` and `` may have different types.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Operand type"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#operand-type", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/inline-assembly.md#operand-type-10", "text": "The Rust Reference › Inline assembly › Operand type\n\n```rust\nlet x: i64;\n// `inout` can also move values to different places\nunsafe { core::arch::asm!(\"inc {}\", inout(reg) 4u64=>x); }\nassert_eq!(x, 5);\n```\n* `inlateout() ` / `inlateout() => `\n - 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`).\n - You should only write to the register after all inputs are read, otherwise you may clobber an input.\n```rust\nlet mut x: i64 = 4;\n// `inlateout` is `inout` using `lateout`\nunsafe { core::arch::asm!(\"inc {}\", inlateout(reg) x); }\nassert_eq!(x, 5);\n```\n* `sym `\n - `` must refer to a `fn` or `static`.\n - A mangled symbol name referring to the item is substituted into the asm template string.\n - The substituted string does not include any modifiers (e.g. GOT, PLT, relocations, etc).\n - `` is allowed to point to a `#[thread_local]` static, in which case the assembly code can combine the symbol with relocations (e.g. `@plt`, `@TPOFF`) to read from thread-local data.\n```rust\nextern \"C\" fn foo() {\n println!(\"Hello from inline assembly\")\n}\n// `sym` can be used to refer to a function (even if it doesn't have an\n// external name we can directly write)\nunsafe { core::arch::asm!(\"call {}\", sym foo, clobber_abi(\"C\")); }\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Operand type"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#operand-type", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/inline-assembly.md#operand-type-11", "text": "The Rust Reference › Inline assembly › Operand type\n\n* `const `\n - `` must be an integer constant expression. This expression follows the same rules as inline `const` blocks.\n - The type of the expression may be any integer type, but defaults to `i32` just like integer literals.\n - The value of the expression is formatted as a string and substituted directly into the asm template string.\n```rust\n// swizzle [0, 1, 2, 3] => [3, 2, 0, 1]\nconst SHUFFLE: u8 = 0b01_00_10_11;\nlet x: core::arch::x86_64::__m128 = unsafe { core::mem::transmute([0u32, 1u32, 2u32, 3u32]) };\nlet y: core::arch::x86_64::__m128;\n// Pass a constant value into an instruction that expects an immediate like `pshufd`\nunsafe {\n core::arch::asm!(\"pshufd {xmm}, {xmm}, {shuffle}\",\n xmm = inlateout(xmm_reg) x=>y,\n shuffle = const SHUFFLE\n );\n}\nlet y: [u32; 4] = unsafe { core::mem::transmute(y) };\nassert_eq!(y, [3, 2, 0, 1]);\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Operand type"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#operand-type", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/inline-assembly.md#operand-type-12", "text": "The Rust Reference › Inline assembly › Operand type\n\n* `label `\n - The address of the block is substituted into the asm template string. The assembly code may jump to the substituted address.\n - For targets that distinguish between direct jumps and indirect jumps (e.g. x86-64 with `cf-protection` enabled), the assembly code must not jump to the substituted address indirectly.\n - After execution of the block, the `asm!` expression returns.\n - The type of the block must be unit or `!` (never).\n - The block starts a new safety context; unsafe operations within the `label` block must be wrapped in an inner `unsafe` block, even though the entire `asm!` expression is already wrapped in `unsafe`.\n```rust\nunsafe {\n core::arch::asm!(\"jmp {}\", label {\n println!(\"Hello from inline assembly label\");\n });\n}\n```\nOperand 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.\n```rust\nlet mut y: i64;\n// y gets its value from the second output, rather than the first\nunsafe { core::arch::asm!(\"mov {}, 0\", \"mov {}, 1\", out(reg) y, out(reg) y); }\nassert_eq!(y, 1);\n```\nBecause `naked_asm!` defines a whole function body and the compiler cannot emit any additional code to handle operands, it can only use `sym` and `const` operands.\nBecause `global_asm!` exists outside a function, it can only use `sym` and `const` operands.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Operand type"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#operand-type", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/inline-assembly.md#operand-type-13", "text": "The Rust Reference › Inline assembly › Operand type\n\n```rust,compile_fail\n// register operands aren't allowed, since we aren't in a function\ncore::arch::global_asm!(\"\", in(reg) 5);\n// ERROR: the `in` operand cannot be used with `global_asm!`\n```\n```rust\nfn foo() {}\n\n// `const` and `sym` are both allowed, however\ncore::arch::global_asm!(\"/* {} {} */\", const 0, sym foo);\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Operand type"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#operand-type", "has_code": true, "code_tags": ["rust", "rust,compile_fail"]}} {"id": "reference/inline-assembly.md#register-operands-14", "text": "The Rust Reference › Inline assembly › Register operands\n\nInput 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`).\n```rust\nlet mut y: i64;\n// We can name both `reg`, or an explicit register like `eax` to get an\n// integer register\nunsafe { core::arch::asm!(\"mov eax, {:e}\", in(reg) 5, lateout(\"eax\") y); }\nassert_eq!(y, 5);\n```\nNote 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.\nIt is a compile-time error to use the same explicit register for two input operands or two output operands.\n```rust,compile_fail\n// We can't name eax twice\nunsafe { core::arch::asm!(\"\", in(\"eax\") 5, in(\"eax\") 4); }\n// ERROR: register `eax` conflicts with register `eax`\n```\n```rust,compile_fail\n// ... even using different aliases\nunsafe { core::arch::asm!(\"\", in(\"ax\") 5, in(\"rax\") 4); }\n// ERROR: register `rax` conflicts with register `ax`\n```\nAdditionally, it is also a compile-time error to use overlapping registers (e.g. ARM VFP) in input operands or in output operands.\n```rust,compile_fail\n// al overlaps with ax, so we can't name both of them.\nunsafe { core::arch::asm!(\"\", in(\"ax\") 5, in(\"al\") 4i8); }\n// ERROR: register `al` conflicts with register `ax`\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Register operands"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#register-operands", "has_code": true, "code_tags": ["rust", "rust,compile_fail"]}} {"id": "reference/inline-assembly.md#register-operands-15", "text": "The Rust Reference › Inline assembly › Register operands\n\nOnly the following types are allowed as operands for inline assembly:\n- Integers (signed and unsigned)\n- Floating-point numbers\n- Pointers (thin only)\n- Function pointers\n- 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).\n```rust\nextern \"C\" fn foo() {}\n\n// Integers are allowed...\nlet y: i64 = 5;\nunsafe { core::arch::asm!(\"/* {} */\", in(reg) y); }\n\n// and pointers...\nlet py = &raw const y;\nunsafe { core::arch::asm!(\"/* {} */\", in(reg) py); }\n\n// floats as well...\nlet f = 1.0f32;\nunsafe { core::arch::asm!(\"/* {} */\", in(xmm_reg) f); }\n\n// even function pointers and simd vectors.\nlet func: extern \"C\" fn() = foo;\nunsafe { core::arch::asm!(\"/* {} */\", in(reg) func); }\n\nlet z = unsafe { core::arch::x86_64::_mm_set_epi64x(1, 0) };\nunsafe { core::arch::asm!(\"/* {} */\", in(xmm_reg) z); }\n```\n```rust,compile_fail\nstruct Foo;\nlet x: Foo = Foo;\n// Complex types like structs are not allowed\nunsafe { core::arch::asm!(\"/* {} */\", in(reg) x); }\n// ERROR: cannot use value of type `Foo` for inline assembly\n```\nHere is the list of currently supported register classes:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Register operands"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#register-operands", "has_code": true, "code_tags": ["rust", "rust,compile_fail"]}} {"id": "reference/inline-assembly.md#register-operands-16", "text": "The Rust Reference › Inline assembly › Register operands\n\n| Architecture | Register class | Registers | LLVM constraint code |\n| ------------ | -------------- | --------- | -------------------- |\n| x86 | `reg` | `ax`, `bx`, `cx`, `dx`, `si`, `di`, `bp`, `r[8-15]` (x86-64 only) | `r` |\n| x86 | `reg_abcd` | `ax`, `bx`, `cx`, `dx` | `Q` |\n| x86-32 | `reg_byte` | `al`, `bl`, `cl`, `dl`, `ah`, `bh`, `ch`, `dh` | `q` |\n| x86-64 | `reg_byte`\\* | `al`, `bl`, `cl`, `dl`, `sil`, `dil`, `bpl`, `r[8-15]b` | `q` |\n| x86 | `xmm_reg` | `xmm[0-7]` (x86) `xmm[0-15]` (x86-64) | `x` |\n| x86 | `ymm_reg` | `ymm[0-7]` (x86) `ymm[0-15]` (x86-64) | `x` |\n| x86 | `zmm_reg` | `zmm[0-7]` (x86) `zmm[0-31]` (x86-64) | `v` |\n| x86 | `kreg` | `k[1-7]` | `Yk` |\n| x86 | `kreg0` | `k0` | Only clobbers |\n| x86 | `x87_reg` | `st([0-7])` | Only clobbers |\n| x86 | `mmx_reg` | `mm[0-7]` | Only clobbers |\n| x86-64 | `tmm_reg` | `tmm[0-7]` | Only clobbers |\n| AArch64 | `reg` | `x[0-30]` | `r` |\n| AArch64 | `vreg` | `v[0-31]` | `w` |\n| AArch64 | `vreg_low16` | `v[0-15]` | `x` |\n| AArch64 | `preg` | `p[0-15]`, `ffr` | Only clobbers |\n| Arm64EC | `reg` | `x[0-12]`, `x[15-22]`, `x[25-27]`, `x30` | `r` |\n| Arm64EC | `vreg` | `v[0-15]` | `w` |\n| Arm64EC | `vreg_low16` | `v[0-15]` | `x` |\n| ARM (ARM/Thumb2) | `reg` | `r[0-12]`, `r14` | `r` |\n| ARM (Thumb1) | `reg` | `r[0-7]` | `r` |\n| ARM | `sreg` | `s[0-31]` | `t` |\n| ARM | `sreg_low16` | `s[0-15]` | `x` |\n| ARM | `dreg` | `d[0-31]` | `w` |\n| ARM | `dreg_low16` | `d[0-15]` | `t` |\n| ARM | `dreg_low8` | `d[0-8]` | `x` |\n| ARM | `qreg` | `q[0-15]` | `w` |\n| ARM | `qreg_low8` | `q[0-7]` | `t` |\n| ARM | `qreg_low4` | `q[0-3]` | `x` |\n| RISC-V | `reg` | `x1`, `x[5-7]`, `x[9-15]`, `x[16-31]` (non-RV32E) | `r` |\n| RISC-V | `freg` | `f[0-31]` | `f` |\n| RISC-V | `vreg` | `v[0-31]` | Only clobbers |\n| LoongArch | `reg` | `$r1`, `$r[4-20]`, `$r[23,30]` | `r` |\n| LoongArch | `freg` | `$f[0-31]` | `f` |\n| s390x | `reg` | `r[0-10]`, `r[12-14]` | `r` |\n| s390x | `reg_addr` | `r[1-10]`, `r[12-14]` | `a` |\n| s390x | `freg` | `f[0-15]` | `f` |\n| s390x | `vreg` | `v[0-31]` | `v` |\n| s390x | `areg` | `a[2-15]` | Only clobbers |\n| PowerPC | `reg` | `r0`, `r[3-12]`, `r[14-28]` | `r` |\n| PowerPC | `reg_nonzero` | `r[3-12]`, `r[14-28]` | `b` |\n| PowerPC | `spe_acc` | `spe_acc` | Only clobbers |\n| PowerPC64 | `reg` | `r0`, `r[3-12]`, `r[14-29]` | `r` |\n| PowerPC64 | `reg_nonzero` | `r[3-12]`, `r[14-29]` | `b` |\n| PowerPC/PowerPC64 | `freg` | `f[0-31]` | `f` |\n| PowerPC/PowerPC64 | `vreg` | `v[0-31]` | `v` |\n| PowerPC/PowerPC64 | `vsreg` | `vs[0-63]` | `wa` |\n| PowerPC/PowerPC64 | `cr` | `cr[0-7]`, `cr` | Only clobbers |\n| PowerPC/PowerPC64 | `ctr` | `ctr` | Only clobbers |\n| PowerPC/PowerPC64 | `lr` | `lr` | Only clobbers |\n| PowerPC/PowerPC64 | `xer` | `xer` | Only clobbers |", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Register operands"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#register-operands", "has_code": false, "code_tags": []}} {"id": "reference/inline-assembly.md#register-operands-17", "text": "The Rust Reference › Inline assembly › Register operands\n\n- On x86 we treat `reg_byte` differently from `reg` because the compiler can allocate `al` and `ah` separately whereas `reg` reserves the whole register.\n- On x86-64 the high byte registers (e.g. `ah`) are not available in the `reg_byte` register class.\n- 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() _` or `lateout() _`.\n- The `spe_acc` register is only available on PowerPC SPE targets.\nEach 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Register operands"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#register-operands", "has_code": false, "code_tags": []}} {"id": "reference/inline-assembly.md#register-operands-18", "text": "The Rust Reference › Inline assembly › Register operands\n\n| Architecture | Register class | Target feature | Allowed types |\n| ------------ | -------------- | -------------- | ------------- |\n| x86-32 | `reg` | None | `i16`, `i32`, `f32` |\n| x86-64 | `reg` | None | `i16`, `i32`, `f32`, `i64`, `f64` |\n| x86 | `reg_byte` | None | `i8` |\n| x86 | `xmm_reg` | `sse` | `i32`, `f32`, `i64`, `f64`,
`i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2` |\n| x86 | `ymm_reg` | `avx` | `i32`, `f32`, `i64`, `f64`,
`i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2`
`i8x32`, `i16x16`, `i32x8`, `i64x4`, `f32x8`, `f64x4` |\n| 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` |\n| x86 | `kreg` | `avx512f` | `i8`, `i16` |\n| x86 | `kreg` | `avx512bw` | `i32`, `i64` |\n| x86 | `mmx_reg` | N/A | Only clobbers |\n| x86 | `x87_reg` | N/A | Only clobbers |\n| x86 | `tmm_reg` | N/A | Only clobbers |\n| AArch64 | `reg` | None | `i8`, `i16`, `i32`, `f32`, `i64`, `f64` |\n| AArch64 | `vreg` | `neon` | `i8`, `i16`, `i32`, `f32`, `i64`, `f64`,
`i8x8`, `i16x4`, `i32x2`, `i64x1`, `f32x2`, `f64x1`,
`i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2` |\n| AArch64 | `preg` | N/A | Only clobbers |\n| Arm64EC | `reg` | None | `i8`, `i16`, `i32`, `f32`, `i64`, `f64` |\n| Arm64EC | `vreg` | `neon` | `i8`, `i16`, `i32`, `f32`, `i64`, `f64`,
`i8x8`, `i16x4`, `i32x2`, `i64x1`, `f32x2`, `f64x1`,
`i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2` |\n| ARM | `reg` | None | `i8`, `i16`, `i32`, `f32` |\n| ARM | `sreg` | `vfp2` | `i32`, `f32` |\n| ARM | `dreg` | `vfp2` | `i64`, `f64`, `i8x8`, `i16x4`, `i32x2`, `i64x1`, `f32x2` |\n| ARM | `qreg` | `neon` | `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4` |\n| RISC-V32 | `reg` | None | `i8`, `i16`, `i32`, `f32` |\n| RISC-V64 | `reg` | None | `i8`, `i16`, `i32`, `f32`, `i64`, `f64` |\n| RISC-V | `freg` | `f` | `f32` |\n| RISC-V | `freg` | `d` | `f64` |\n| RISC-V | `vreg` | N/A | Only clobbers |\n| LoongArch32 | `reg` | None | `i8`, `i16`, `i32`, `f32` |\n| LoongArch64 | `reg` | None | `i8`, `i16`, `i32`, `i64`, `f32`, `f64` |\n| LoongArch | `freg` | `f` | `f32` |\n| LoongArch | `freg` | `d` | `f64` |\n| s390x | `reg`, `reg_addr` | None | `i8`, `i16`, `i32`, `i64` |\n| s390x | `freg` | None | `f32`, `f64` |\n| s390x | `vreg` | `vector` | `i32`, `f32`, `i64`, `f64`, `i128`,
`i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2` |\n| s390x | `areg` | N/A | Only clobbers |\n| PowerPC | `spe_acc` | None | Only clobbers |\n| PowerPC/PowerPC64 | `reg` | None | `i8`, `i16`, `i32`, `i64` (PowerPC64 only) |\n| PowerPC/PowerPC64 | `reg_nonzero` | None | `i8`, `i16`, `i32`, `i64` (PowerPC64 only) |\n| PowerPC/PowerPC64 | `freg` | None | `f32`, `f64` |\n| PowerPC/PowerPC64 | `vreg` | `altivec` | `i8x16`, `i16x8`, `i32x4`, `f32x4` |\n| PowerPC/PowerPC64 | `vreg` | `vsx` | `f32`, `f64`, `i64x2`, `f64x2` |\n| PowerPC/PowerPC64 | `vsreg` | `vsx` | The union of vsx and altivec vreg types |\n| PowerPC/PowerPC64 | `cr` | None | Only clobbers |\n| PowerPC/PowerPC64 | `ctr` | None | Only clobbers |\n| PowerPC/PowerPC64 | `lr` | None | Only clobbers |\n| PowerPC/PowerPC64 | `xer` | None | Only clobbers |", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Register operands"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#register-operands", "has_code": false, "code_tags": []}} {"id": "reference/inline-assembly.md#register-operands-19", "text": "The Rust Reference › Inline assembly › Register operands\n\nFor 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).\n```rust\nlet x = 5i32;\nlet y = -1i8;\nlet z = unsafe { core::arch::x86_64::_mm_set_epi64x(1, 0) };\n\n// reg is valid for `i32`, `reg_byte` is valid for `i8`, and xmm_reg is valid for `__m128i`\n// We can't use `tmm0` as an input or output, but we can clobber it.\nunsafe { core::arch::asm!(\"/* {} {} {} */\", in(reg) x, in(reg_byte) y, in(xmm_reg) z, out(\"tmm0\") _); }\n```\n```rust,compile_fail\nlet z = unsafe { core::arch::x86_64::_mm_set_epi64x(1, 0) };\n// We can't pass an `__m128i` to a `reg` input\nunsafe { core::arch::asm!(\"/* {} */\", in(reg) z); }\n// ERROR: type `__m128i` cannot be used with this register class\n```\nIf 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Register operands"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#register-operands", "has_code": true, "code_tags": ["rust", "rust,compile_fail"]}} {"id": "reference/inline-assembly.md#register-operands-20", "text": "The Rust Reference › Inline assembly › Register operands\n\n```rust,no_run\nlet mut x: i64;\n// Moving a 32-bit value into a 64-bit value, oops.\n#[allow(asm_sub_register)] // rustc warns about this behavior\nunsafe { core::arch::asm!(\"mov {}, {}\", lateout(reg) x, in(reg) 4i32); }\n// top 32-bits are indeterminate\nassert_eq!(x, 4); // This assertion is not guaranteed to succeed\nassert_eq!(x & 0xFFFFFFFF, 4); // However, this one will succeed\n```\nWhen 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.\n```rust\n// Pointers and integers can mix (as long as they are the same size)\nlet x: isize = 0;\nlet y: *mut ();\n// Transmute an `isize` to a `*mut ()`, using inline assembly magic\nunsafe { core::arch::asm!(\"/*{}*/\", inout(reg) x=>y); }\nassert!(y.is_null()); // Extremely roundabout way to make a null pointer\n```\n```rust,compile_fail\nlet x: i32 = 0;\nlet y: f32;\n// But we can't reinterpret an `i32` to an `f32` like this\nunsafe { core::arch::asm!(\"/* {} */\", inout(reg) x=>y); }\n// ERROR: incompatible types for asm inout argument\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Register operands"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#register-operands", "has_code": true, "code_tags": ["rust", "rust,compile_fail", "rust,no_run"]}} {"id": "reference/inline-assembly.md#register-names-21", "text": "The Rust Reference › Inline assembly › Register names\n\nSome 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:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Register names"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#register-names", "has_code": false, "code_tags": []}} {"id": "reference/inline-assembly.md#register-names-22", "text": "The Rust Reference › Inline assembly › Register names\n\n| Architecture | Base register | Aliases |\n| ------------ | ------------- | ------- |\n| x86 | `ax` | `eax`, `rax` |\n| x86 | `bx` | `ebx`, `rbx` |\n| x86 | `cx` | `ecx`, `rcx` |\n| x86 | `dx` | `edx`, `rdx` |\n| x86 | `si` | `esi`, `rsi` |\n| x86 | `di` | `edi`, `rdi` |\n| x86 | `bp` | `bpl`, `ebp`, `rbp` |\n| x86 | `sp` | `spl`, `esp`, `rsp` |\n| x86 | `ip` | `eip`, `rip` |\n| x86 | `st(0)` | `st` |\n| x86 | `r[8-15]` | `r[8-15]b`, `r[8-15]w`, `r[8-15]d` |\n| x86 | `xmm[0-31]` | `ymm[0-31]`, `zmm[0-31]` |\n| AArch64 | `x[0-30]` | `w[0-30]` |\n| AArch64 | `x29` | `fp` |\n| AArch64 | `x30` | `lr` |\n| AArch64 | `sp` | `wsp` |\n| AArch64 | `xzr` | `wzr` |\n| AArch64 | `v[0-31]` | `b[0-31]`, `h[0-31]`, `s[0-31]`, `d[0-31]`, `q[0-31]` |\n| Arm64EC | `x[0-30]` | `w[0-30]` |\n| Arm64EC | `x29` | `fp` |\n| Arm64EC | `x30` | `lr` |\n| Arm64EC | `sp` | `wsp` |\n| Arm64EC | `xzr` | `wzr` |\n| Arm64EC | `v[0-15]` | `b[0-15]`, `h[0-15]`, `s[0-15]`, `d[0-15]`, `q[0-15]` |\n| ARM | `r[0-3]` | `a[1-4]` |\n| ARM | `r[4-9]` | `v[1-6]` |\n| ARM | `r9` | `rfp` |\n| ARM | `r10` | `sl` |\n| ARM | `r11` | `fp` |\n| ARM | `r12` | `ip` |\n| ARM | `r13` | `sp` |\n| ARM | `r14` | `lr` |\n| ARM | `r15` | `pc` |\n| RISC-V | `x0` | `zero` |\n| RISC-V | `x1` | `ra` |\n| RISC-V | `x2` | `sp` |\n| RISC-V | `x3` | `gp` |\n| RISC-V | `x4` | `tp` |\n| RISC-V | `x[5-7]` | `t[0-2]` |\n| RISC-V | `x8` | `fp`, `s0` |\n| RISC-V | `x9` | `s1` |\n| RISC-V | `x[10-17]` | `a[0-7]` |\n| RISC-V | `x[18-27]` | `s[2-11]` |\n| RISC-V | `x[28-31]` | `t[3-6]` |\n| RISC-V | `f[0-7]` | `ft[0-7]` |\n| RISC-V | `f[8-9]` | `fs[0-1]` |\n| RISC-V | `f[10-17]` | `fa[0-7]` |\n| RISC-V | `f[18-27]` | `fs[2-11]` |\n| RISC-V | `f[28-31]` | `ft[8-11]` |\n| LoongArch | `$r0` | `$zero` |\n| LoongArch | `$r1` | `$ra` |\n| LoongArch | `$r2` | `$tp` |\n| LoongArch | `$r3` | `$sp` |\n| LoongArch | `$r[4-11]` | `$a[0-7]` |\n| LoongArch | `$r[12-20]` | `$t[0-8]` |\n| LoongArch | `$r21` | |\n| LoongArch | `$r22` | `$fp`, `$s9` |\n| LoongArch | `$r[23-31]` | `$s[0-8]` |\n| LoongArch | `$f[0-7]` | `$fa[0-7]` |\n| LoongArch | `$f[8-23]` | `$ft[0-15]` |\n| LoongArch | `$f[24-31]` | `$fs[0-7]` |\n| PowerPC/PowerPC64 | `r1` | `sp` |\n| PowerPC/PowerPC64 | `r31` | `fp` |\n| PowerPC/PowerPC64 | `r[0-31]` | `[0-31]` |\n| PowerPC/PowerPC64 | `f[0-31]` | `fr[0-31]`|", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Register names"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#register-names", "has_code": false, "code_tags": []}} {"id": "reference/inline-assembly.md#register-names-23", "text": "The Rust Reference › Inline assembly › Register names\n\n```rust\nlet z = 0i64;\n// rax is an alias for eax and ax\nunsafe { core::arch::asm!(\"\", in(\"rax\") z); }\n```\nSome registers cannot be used for input or output operands:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Register names"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#register-names", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/inline-assembly.md#register-names-24", "text": "The Rust Reference › Inline assembly › Register names\n\n| Architecture | Unsupported register | Reason |\n| ------------ | -------------------- | ------ |\n| All | `sp`, `r15` (s390x), `r1` (PowerPC and PowerPC64) | The stack pointer must be restored to its original value at the end of the assembly code or before jumping to a `label` block. |\n| All | `bp` (x86), `x29` (AArch64 and Arm64EC), `x8` (RISC-V), `$fp` (LoongArch), `r11` (s390x), `fp` (PowerPC and PowerPC64) | The frame pointer cannot be used as an input or output. |\n| 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. |\n| All | `si` (x86-32), `bx` (x86-64), `r6` (ARM), `x19` (AArch64 and Arm64EC), `x9` (RISC-V), `$s8` (LoongArch), `r29` and `r30` (PowerPC), `r30` (PowerPC64) | This is used internally by LLVM as a \"base pointer\" for functions with complex stack frames. |\n| x86 | `ip` | This is the program counter, not a real register. |\n| AArch64 | `xzr` | This is a constant zero register which can't be modified. |\n| AArch64 | `x18` | This is an OS-reserved register on some AArch64 targets. |\n| Arm64EC | `xzr` | This is a constant zero register which can't be modified. |\n| Arm64EC | `x18` | This is an OS-reserved register. |\n| Arm64EC | `x13`, `x14`, `x23`, `x24`, `x28`, `v[16-31]`, `p[0-15]`, `ffr` | These are AArch64 registers that are not supported for Arm64EC. |\n| ARM | `pc` | This is the program counter, not a real register. |\n| ARM | `r9` | This is an OS-reserved register on some ARM targets. |\n| RISC-V | `x0` | This is a constant zero register which can't be modified. |\n| RISC-V | `gp`, `tp` | These registers are reserved and cannot be used as inputs or outputs. |\n| LoongArch | `$r0` or `$zero` | This is a constant zero register which can't be modified. |\n| LoongArch | `$r2` or `$tp` | This is reserved for TLS. |\n| LoongArch | `$r21` | This is reserved by the ABI. |\n| s390x | `c[0-15]` | Reserved by the kernel. |\n| s390x | `a[0-1]` | Reserved for system use. |\n| PowerPC/PowerPC64 | `r2`, `r13` | These are system reserved registers. |\n| PowerPC/PowerPC64 | `vrsave` | The vrsave register cannot be used as an input or output. |", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Register names"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#register-names", "has_code": false, "code_tags": []}} {"id": "reference/inline-assembly.md#register-names-25", "text": "The Rust Reference › Inline assembly › Register names\n\n```rust,compile_fail\n// bp is reserved\nunsafe { core::arch::asm!(\"\", in(\"bp\") 5i32); }\n// ERROR: invalid register `bp`: the frame pointer cannot be used as an operand for inline asm\n```\nThe 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Register names"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#register-names", "has_code": true, "code_tags": ["rust,compile_fail"]}} {"id": "reference/inline-assembly.md#template-modifiers-26", "text": "The Rust Reference › Inline assembly › Template modifiers\n\nThe 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.\nOnly one modifier is allowed per template placeholder.\n```rust,compile_fail\n// We can't specify both `r` and `e` at the same time.\nunsafe { core::arch::asm!(\"/* {:er}\", in(reg) 5i32); }\n// ERROR: asm template modifier must be a single character\n```\nThe supported modifiers are a subset of LLVM's (and GCC's) asm template argument modifiers, but do not use the same letter codes.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Template modifiers"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#template-modifiers", "has_code": true, "code_tags": ["rust,compile_fail"]}} {"id": "reference/inline-assembly.md#template-modifiers-27", "text": "The Rust Reference › Inline assembly › Template modifiers\n\n| Architecture | Register class | Modifier | Example output | LLVM modifier |\n| ------------ | -------------- | -------- | -------------- | ------------- |\n| x86-32 | `reg` | None | `eax` | `k` |\n| x86-64 | `reg` | None | `rax` | `q` |\n| x86-32 | `reg_abcd` | `l` | `al` | `b` |\n| x86-64 | `reg` | `l` | `al` | `b` |\n| x86 | `reg_abcd` | `h` | `ah` | `h` |\n| x86 | `reg` | `x` | `ax` | `w` |\n| x86 | `reg` | `e` | `eax` | `k` |\n| x86-64 | `reg` | `r` | `rax` | `q` |\n| x86 | `reg_byte` | None | `al` / `ah` | None |\n| x86 | `xmm_reg` | None | `xmm0` | `x` |\n| x86 | `ymm_reg` | None | `ymm0` | `t` |\n| x86 | `zmm_reg` | None | `zmm0` | `g` |\n| x86 | `*mm_reg` | `x` | `xmm0` | `x` |\n| x86 | `*mm_reg` | `y` | `ymm0` | `t` |\n| x86 | `*mm_reg` | `z` | `zmm0` | `g` |\n| x86 | `kreg` | None | `k1` | None |\n| AArch64/Arm64EC | `reg` | None | `x0` | `x` |\n| AArch64/Arm64EC | `reg` | `w` | `w0` | `w` |\n| AArch64/Arm64EC | `reg` | `x` | `x0` | `x` |\n| AArch64/Arm64EC | `vreg` | None | `v0` | None |\n| AArch64/Arm64EC | `vreg` | `v` | `v0` | None |\n| AArch64/Arm64EC | `vreg` | `b` | `b0` | `b` |\n| AArch64/Arm64EC | `vreg` | `h` | `h0` | `h` |\n| AArch64/Arm64EC | `vreg` | `s` | `s0` | `s` |\n| AArch64/Arm64EC | `vreg` | `d` | `d0` | `d` |\n| AArch64/Arm64EC | `vreg` | `q` | `q0` | `q` |\n| ARM | `reg` | None | `r0` | None |\n| ARM | `sreg` | None | `s0` | None |\n| ARM | `dreg` | None | `d0` | `P` |\n| ARM | `qreg` | None | `q0` | `q` |\n| ARM | `qreg` | `e` / `f` | `d0` / `d1` | `e` / `f` |\n| RISC-V | `reg` | None | `x1` | None |\n| RISC-V | `freg` | None | `f0` | None |\n| LoongArch | `reg` | None | `$r1` | None |\n| LoongArch | `freg` | None | `$f0` | None |\n| s390x | `reg` | None | `%r0` | None |\n| s390x | `reg_addr` | None | `%r1` | None |\n| s390x | `freg` | None | `%f0` | None |\n| s390x | `vreg` | None | `%v0` | None |\n| PowerPC/PowerPC64 | `reg` | None | `0` | None |\n| PowerPC/PowerPC64 | `reg_nonzero` | None | `3` | None |\n| PowerPC/PowerPC64 | `freg` | None | `0` | None |\n| PowerPC/PowerPC64 | `vreg` | None | `0` | None |\n| PowerPC/PowerPC64 | `vsreg` | None | `0` | None |", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Template modifiers"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#template-modifiers", "has_code": false, "code_tags": []}} {"id": "reference/inline-assembly.md#template-modifiers-28", "text": "The Rust Reference › Inline assembly › Template modifiers\n\n- on ARM `e` / `f`: this prints the low or high doubleword register name of a NEON quad (128-bit) register.\n- 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.\n- 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.\n```rust\nlet mut x = 0x10u16;\n\n// u16::swap_bytes using `xchg`\n// low half of `{x}` is referred to by `{x:l}`, and the high half by `{x:h}`\nunsafe { core::arch::asm!(\"xchg {x:l}, {x:h}\", x = inout(reg_abcd) x); }\nassert_eq!(x, 0x1000u16);\n```\nAs 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 assembly 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Template modifiers"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#template-modifiers", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/inline-assembly.md#abi-clobbers-29", "text": "The Rust Reference › Inline assembly › ABI clobbers\n\nThe `clobber_abi` keyword can be used to apply a default set of clobbers to the assembly code. 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).\n```rust\nextern \"C\" fn foo() -> i32 { 0 }\n\nlet z: i32;\n// To call a function, we have to inform the compiler that we're clobbering\n// callee saved registers\nunsafe { core::arch::asm!(\"call {}\", sym foo, out(\"rax\") z, clobber_abi(\"C\")); }\nassert_eq!(z, 0);\n```\n`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.\n```rust\nextern \"sysv64\" fn foo() -> i32 { 0 }\nextern \"win64\" fn bar(x: i32) -> i32 { x + 1 }\n\nlet z: i32;\n// We can even call multiple functions with different conventions and\n// different saved registers\nunsafe {\n core::arch::asm!(\n \"call {}\",\n \"mov ecx, eax\",\n \"call {}\",\n sym foo,\n sym bar,\n out(\"rax\") z,\n clobber_abi(\"sysv64\"),\n clobber_abi(\"win64\"),\n );\n}\nassert_eq!(z, 1);\n```\nGeneric register class outputs are disallowed by the compiler when `clobber_abi` is used: all outputs must specify an explicit register.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "ABI clobbers"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#abi-clobbers", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/inline-assembly.md#abi-clobbers-30", "text": "The Rust Reference › Inline assembly › ABI clobbers\n\n```rust,compile_fail\nextern \"C\" fn foo(x: i32) -> i32 { 0 }\n\nlet z: i32;\n// explicit registers must be used to not accidentally overlap.\nunsafe {\n core::arch::asm!(\n \"mov eax, {:e}\",\n \"call {}\",\n out(reg) z,\n sym foo,\n clobber_abi(\"C\")\n );\n // ERROR: asm with `clobber_abi` must specify explicit registers for outputs\n}\nassert_eq!(z, 0);\n```\nExplicit 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.\nThe following ABIs can be used with `clobber_abi`:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "ABI clobbers"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#abi-clobbers", "has_code": true, "code_tags": ["rust,compile_fail"]}} {"id": "reference/inline-assembly.md#abi-clobbers-31", "text": "The Rust Reference › Inline assembly › ABI clobbers\n\n| Architecture | ABI name | Clobbered registers |\n| ------------ | -------- | ------------------- |\n| x86-32 | `\"C\"`, `\"system\"`, `\"efiapi\"`, `\"cdecl\"`, `\"stdcall\"`, `\"fastcall\"` | `ax`, `cx`, `dx`, `xmm[0-7]`, `mm[0-7]`, `k[0-7]`, `st([0-7])` |\n| 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]` |\n| 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]` |\n| AArch64 | `\"C\"`, `\"system\"`, `\"efiapi\"` | `x[0-17]`, `x18`\\*, `x30`, `v[0-31]`, `p[0-15]`, `ffr` |\n| Arm64EC | `\"C\"`, `\"system\"` | `x[0-12]`, `x[15-17]`, `x30`, `v[0-15]` |\n| ARM | `\"C\"`, `\"system\"`, `\"efiapi\"`, `\"aapcs\"` | `r[0-3]`, `r12`, `r14`, `s[0-15]`, `d[0-7]`, `d[16-31]` |\n| 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]` |\n| LoongArch | `\"C\"`, `\"system\"` | `$r1`, `$r[4-20]`, `$f[0-23]` |\n| s390x | `\"C\"`, `\"system\"` | `r[0-5]`, `r14`, `f[0-7]`, `v[0-31]`, `a[2-15]` |", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "ABI clobbers"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#abi-clobbers", "has_code": false, "code_tags": []}} {"id": "reference/inline-assembly.md#abi-clobbers-32", "text": "The Rust Reference › Inline assembly › ABI clobbers\n\n- On AArch64 `x18` only included in the clobber list if it is not considered as a reserved register on the target.\n- On RISC-V `x[16-17]` and `x[28-31]` only included in the clobber list if they are not considered as reserved registers on the target.\nThe 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "ABI clobbers"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#abi-clobbers", "has_code": false, "code_tags": []}} {"id": "reference/inline-assembly.md#options-33", "text": "The Rust Reference › Inline assembly › Options\n\nFlags are used to further influence the behavior of the inline assembly code. Currently the following options are defined:\n- `pure`: The assembly code has no side effects, must eventually return, 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 assembly code 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. The `pure` option must be combined with either the `nomem` or `readonly` options, otherwise a compile-time error is emitted.\n```rust\nlet x: i32 = 0;\nlet z: i32;\n// pure can be used to optimize by assuming the assembly has no side effects\nunsafe { core::arch::asm!(\"inc {}\", inout(reg) x => z, options(pure, nomem)); }\nassert_eq!(z, 1);\n```\n```rust,compile_fail\nlet x: i32 = 0;\nlet z: i32;\n// Either nomem or readonly must be satisfied, to indicate whether or not\n// memory is allowed to be read\nunsafe { core::arch::asm!(\"inc {}\", inout(reg) x => z, options(pure)); }\n// ERROR: the `pure` option must be combined with either `nomem` or `readonly`\nassert_eq!(z, 0);\n```\n- `nomem`: The assembly code does not read from or write to any memory accessible outside of the assembly code. This allows the compiler to cache the values of modified global variables in registers across execution of the assembly code since it knows that they are not read from or written to by it. The compiler also assumes that the assembly code does not perform any kind of synchronization with other threads, e.g. via fences.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Options"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#options", "has_code": true, "code_tags": ["rust", "rust,compile_fail"]}} {"id": "reference/inline-assembly.md#options-34", "text": "The Rust Reference › Inline assembly › Options\n\n```rust,no_run\nlet mut x = 0i32;\nlet z: i32;\n// Accessing outside memory from assembly when `nomem` is\n// specified is disallowed\nunsafe {\n core::arch::asm!(\"mov {val:e}, dword ptr [{ptr}]\",\n ptr = in(reg) &mut x,\n val = lateout(reg) z,\n options(nomem)\n )\n}\n\n// Writing to outside memory from assembly when `nomem` is\n// specified is also undefined behaviour\nunsafe {\n core::arch::asm!(\"mov dword ptr [{ptr}], {val:e}\",\n ptr = in(reg) &mut x,\n val = in(reg) z,\n options(nomem)\n )\n}\n```\n```rust\nlet x: i32 = 0;\nlet z: i32;\n// If we allocate our own memory, such as via `push`, however.\n// we can still use it\nunsafe {\n core::arch::asm!(\"push {x}\", \"add qword ptr [rsp], 1\", \"pop {x}\",\n x = inout(reg) x => z,\n options(nomem)\n );\n}\nassert_eq!(z, 1);\n```\n- `readonly`: The assembly code does not write to any memory accessible outside of the assembly code. This allows the compiler to cache the values of unmodified global variables in registers across execution of the assembly code since it knows that they are not written to by it. The compiler also assumes that this assembly code does not perform any kind of synchronization with other threads, e.g. via fences.\n```rust,no_run\nlet mut x = 0;\n// We cannot modify outside memory when `readonly` is specified\nunsafe {\n core::arch::asm!(\"mov dword ptr[{}], 1\", in(reg) &mut x, options(readonly))\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Options"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#options", "has_code": true, "code_tags": ["rust", "rust,no_run"]}} {"id": "reference/inline-assembly.md#options-35", "text": "The Rust Reference › Inline assembly › Options\n\n```rust\nlet x: i64 = 0;\nlet z: i64;\n// We can still read from it, though\nunsafe {\n core::arch::asm!(\"mov {x}, qword ptr [{x}]\",\n x = inout(reg) &x => z,\n options(readonly)\n );\n}\nassert_eq!(z, 0);\n```\n```rust\nlet x: i64 = 0;\nlet z: i64;\n// Same exception applies as with nomem.\nunsafe {\n core::arch::asm!(\"push {x}\", \"add qword ptr [rsp], 1\", \"pop {x}\",\n x = inout(reg) x => z,\n options(readonly)\n );\n}\nassert_eq!(z, 1);\n```\n- `preserves_flags`: The assembly code does not modify the flags register (defined in the rules below). This allows the compiler to avoid recomputing the condition flags after execution of the assembly code.\n- `noreturn`: The assembly code does not fall through; behavior is undefined if it does. It may still jump to `label` blocks. If any `label` blocks return unit, the `asm!` block will return unit. Otherwise it will return `!` (never). As with a call to a function that does not return, local variables in scope are not dropped before execution of the assembly code.\n```rust,no_run\nfn main() -> ! {\n // We can use an instruction to trap execution inside of a noreturn block\n unsafe { core::arch::asm!(\"ud2\", options(noreturn)); }\n}\n```\n```rust,no_run\n// You are responsible for not falling past the end of a noreturn asm block\nunsafe { core::arch::asm!(\"\", options(noreturn)); }\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Options"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#options", "has_code": true, "code_tags": ["rust", "rust,no_run"]}} {"id": "reference/inline-assembly.md#options-36", "text": "The Rust Reference › Inline assembly › Options\n\n```rust\nlet _: () = unsafe {\n // You may still jump to a `label` block\n core::arch::asm!(\"jmp {}\", label {\n println!();\n }, options(noreturn));\n};\n```\n- `nostack`: The assembly code 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 by the compiler at the start of the assembly code to be suitably aligned (according to the target ABI) for a function call.\n```rust,no_run\n// `push` and `pop` are UB when used with nostack\nunsafe { core::arch::asm!(\"push rax\", \"pop rax\", options(nostack)); }\n```\n- `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 `%`.\n```rust\nlet x: i32;\nlet y = 1i32;\n// We need to use AT&T Syntax here. src, dest order for operands\nunsafe {\n core::arch::asm!(\"mov {y:e}, {x:e}\",\n x = lateout(reg) x,\n y = in(reg) y,\n options(att_syntax)\n );\n}\nassert_eq!(x, y);\n```\n- `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!`.\nThe compiler performs some additional checks on options:\n- The `nomem` and `readonly` options are mutually exclusive: it is a compile-time error to specify both.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Options"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#options", "has_code": true, "code_tags": ["rust", "rust,no_run"]}} {"id": "reference/inline-assembly.md#options-37", "text": "The Rust Reference › Inline assembly › Options\n\n```rust,compile_fail\n// nomem is strictly stronger than readonly, they can't be specified together\nunsafe { core::arch::asm!(\"\", options(nomem, readonly)); }\n// ERROR: the `nomem` and `readonly` options are mutually exclusive\n```\n- It is a compile-time error to specify `pure` on an asm block with no outputs or only discarded outputs (`_`).\n```rust,compile_fail\n// pure blocks need at least one output\nunsafe { core::arch::asm!(\"\", options(pure)); }\n// ERROR: asm with the `pure` option must have at least one output\n```\n- It is a compile-time error to specify `noreturn` on an asm block with outputs and without labels.\n```rust,compile_fail\nlet z: i32;\n// noreturn can't have outputs\nunsafe { core::arch::asm!(\"mov {:e}, 1\", out(reg) z, options(noreturn)); }\n// ERROR: asm outputs are not allowed with the `noreturn` option\n```\n- It is a compile-time error to have any `label` blocks in an asm block with outputs.\n`naked_asm!` only supports the `att_syntax` and `raw` options. The remaining options are not meaningful because the inline assembly defines the whole function body.\n`global_asm!` only supports the `att_syntax` and `raw` options. The remaining options are not meaningful for global-scope inline assembly.\n```rust,compile_fail\n// nomem is useless on global_asm!\ncore::arch::global_asm!(\"\", options(nomem));\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Options"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#options", "has_code": true, "code_tags": ["rust,compile_fail"]}} {"id": "reference/inline-assembly.md#rules-for-inline-assembly-38", "text": "The Rust Reference › Inline assembly › Rules for inline assembly\n\nTo avoid undefined behavior, these rules must be followed when using function-scope inline assembly (`asm!`):\n- Any registers not specified as inputs will contain an undefined value on entry to the assembly code.\n - 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).\n- Any registers not specified as outputs must have the same value upon exiting the assembly code as they had on entry, otherwise behavior is undefined.\n - This only applies to registers which can be specified as an input or output. Other registers follow target-specific rules.\n - 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.\n- Behavior is undefined if execution unwinds out of the assembly code.\n - This also applies if the assembly code calls a function which then unwinds.\n- The set of memory locations that assembly code is allowed to read and write are the same as those allowed for an FFI function.\n - If the `readonly` option is set, then only memory reads are allowed.\n - If the `nomem` option is set then no reads or writes to memory are allowed.\n - These rules do not apply to memory which is private to the assembly code, such as stack space allocated within it.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Rules for inline assembly"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#rules-for-inline-assembly", "has_code": false, "code_tags": []}} {"id": "reference/inline-assembly.md#rules-for-inline-assembly-39", "text": "The Rust Reference › Inline assembly › Rules for inline assembly\n\n- The compiler cannot assume that the instructions in the assembly code are the ones that will actually end up executed.\n - This effectively means that the compiler must treat the assembly code as a black box and only take the interface specification into account, not the instructions themselves.\n - Runtime code patching is allowed, via target-specific mechanisms.\n - However there is no guarantee that each block of assembly code in the source directly corresponds to a single instance of instructions in the object file; the compiler is free to duplicate or deduplicate the assembly code in `asm!` blocks.\n- Unless the `nostack` option is set, assembly code is allowed to use stack space below the stack pointer.\n - On entry to the assembly code the stack pointer is guaranteed to be suitably aligned (according to the target ABI) for a function call.\n - You are responsible for making sure you don't overflow the stack (e.g. use stack probing to ensure you hit a guard page).\n - You should adjust the stack pointer when allocating stack memory as required by the target ABI.\n - The stack pointer must be restored to its original value before leaving the assembly code.\n- Unless the `nostack` option is set, assembly code is allowed to modify the caller's stack frame when the target ABI requires storing certain values in the caller's frame (e.g., when saving the `lr` on PowerPC64).\n- If the `noreturn` option is set then behavior is undefined if execution falls through the end of the assembly code.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Rules for inline assembly"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#rules-for-inline-assembly", "has_code": false, "code_tags": []}} {"id": "reference/inline-assembly.md#rules-for-inline-assembly-40", "text": "The Rust Reference › Inline assembly › Rules for inline assembly\n\n- 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.\n - When used with the `nomem` option, \"inputs\" are just the direct inputs of the `asm!`.\n - When used with the `readonly` option, \"inputs\" comprise the direct inputs of the assembly code and any memory that it is allowed to read.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Rules for inline assembly"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#rules-for-inline-assembly", "has_code": false, "code_tags": []}} {"id": "reference/inline-assembly.md#rules-for-inline-assembly-41", "text": "The Rust Reference › Inline assembly › Rules for inline assembly\n\n- These flags registers must be restored upon exiting the assembly code if the `preserves_flags` option is set:\n - x86\n - Status flags in `EFLAGS` (CF, PF, AF, ZF, SF, OF).\n - Floating-point status word (all).\n - Floating-point exception flags in `MXCSR` (PE, UE, OE, ZE, DE, IE).\n - ARM\n - Condition flags in `CPSR` (N, Z, C, V)\n - Saturation flag in `CPSR` (Q)\n - Greater than or equal flags in `CPSR` (GE).\n - Condition flags in `FPSCR` (N, Z, C, V)\n - Saturation flag in `FPSCR` (QC)\n - Floating-point exception flags in `FPSCR` (IDC, IXC, UFC, OFC, DZC, IOC).\n - AArch64 and Arm64EC\n - Condition flags (`NZCV` register).\n - Floating-point status (`FPSR` register).\n - RISC-V\n - Floating-point exception flags in `fcsr` (`fflags`).\n - Vector extension state (`vtype`, `vl`, `vxsat`, and `vxrm`).\n - LoongArch\n - Floating-point condition flags in `$fcc[0-7]`.\n - PowerPC/PowerPC64\n - Floating-point status and sticky bits in the `fpscr` (any field other than DRN, VE, OE, UE, ZE, XE, NI, or RN).\n - Vector status and sticky bits in the `vscr` (any field other than NJ).\n - PowerPC SPE\n - The sticky and status bits of the `spefscr` (any field other than FINXE, FINVE, FDBZE, FUNFE, FOVFE, or FRMC).\n - s390x\n - The condition code register `cc`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Rules for inline assembly"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#rules-for-inline-assembly", "has_code": false, "code_tags": []}} {"id": "reference/inline-assembly.md#rules-for-inline-assembly-42", "text": "The Rust Reference › Inline assembly › Rules for inline assembly\n\n- On x86, the direction flag (DF in `EFLAGS`) is clear on entry to the assembly code and must be clear on exit.\n - Behavior is undefined if the direction flag is set on exiting the assembly code.\n- 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)\") _, ...`.\n - If all x87 registers are clobbered then the x87 register stack is guaranteed to be empty upon entering the assembly code. Assembly code must ensure that the x87 register stack is also empty when exiting the assembly code.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Rules for inline assembly"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#rules-for-inline-assembly", "has_code": false, "code_tags": []}} {"id": "reference/inline-assembly.md#rules-for-inline-assembly-43", "text": "The Rust Reference › Inline assembly › Rules for inline assembly\n\n```rust\npub fn fadd(x: f64, y: f64) -> f64 {\n let mut out = 0f64;\n let mut top = 0u16;\n // we can do complex stuff with x87 if we clobber the entire x87 stack\n unsafe { core::arch::asm!(\n \"fld qword ptr [{x}]\",\n \"fld qword ptr [{y}])\",\n \"faddp\",\n \"fstp qword ptr [{out}]\",\n \"xor eax, eax\",\n \"fstsw ax\",\n \"shl eax, 11\",\n x = in(reg) &x,\n y = in(reg) &y,\n out = in(reg) &mut out,\n out(\"st(0)\") _, out(\"st(1)\") _, out(\"st(2)\") _, out(\"st(3)\") _,\n out(\"st(4)\") _, out(\"st(5)\") _, out(\"st(6)\") _, out(\"st(7)\") _,\n out(\"eax\") top\n );}\n\n assert_eq!(top & 0x7, 0);\n out\n}\n\npub fn main() {\n assert_eq!(fadd(1.0, 1.0), 2.0);\n}\n```\n- On arm64ec, call checkers with appropriate thunks are mandatory when calling functions.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Rules for inline assembly"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#rules-for-inline-assembly", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/inline-assembly.md#rules-for-inline-assembly-44", "text": "The Rust Reference › Inline assembly › Rules for inline assembly\n\n- The requirement of restoring the stack pointer and non-output registers to their original value only applies when exiting the assembly code.\n - This means that assembly code that does not fall through and does not jump to any `label` blocks, even if not marked `noreturn`, doesn't need to preserve these registers.\n - When returning to the assembly code of 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*.\n - You cannot exit the assembly code of an `asm!` block that has not been entered. Neither can you exit the assembly code of an `asm!` block whose assembly code has already been exited (without first entering it again).\n - You are responsible for switching any target-specific state (e.g. thread-local storage, stack bounds).\n - 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.\n - The set of memory locations that you may access is the intersection of those allowed by the `asm!` blocks you entered and exited.\n- 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.\n- 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Rules for inline assembly"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#rules-for-inline-assembly", "has_code": false, "code_tags": []}} {"id": "reference/inline-assembly.md#rules-for-inline-assembly-45", "text": "The Rust Reference › Inline assembly › Rules for inline assembly\n\n- On x86, inline assembly must not end with an instruction prefix (such as `LOCK`) that would apply to instructions generated by the compiler.\n - 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.\nAs a general rule, the flags covered by `preserves_flags` are those which are *not* preserved when performing a function call.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Rules for inline assembly"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#rules-for-inline-assembly", "has_code": false, "code_tags": []}} {"id": "reference/inline-assembly.md#rules-for-naked-inline-assembly-46", "text": "The Rust Reference › Inline assembly › Rules for naked inline assembly\n\nTo avoid undefined behavior, these rules must be followed when using function-scope inline assembly in naked functions (`naked_asm!`):\n- Any registers not used for function inputs according to the calling convention and function signature will contain an undefined value on entry to the `naked_asm!` block.\n - 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).\n- All callee-saved registers must have the same value upon return as they had on entry.\n- Caller-saved registers may be used freely.\n- Behavior is undefined if execution falls through past the end of the assembly code.\n - Every path through the assembly code is expected to terminate with a return instruction or to diverge.\n- The set of memory locations that assembly code is allowed to read and write are the same as those allowed for an FFI function.\n- The compiler cannot assume that the instructions in the `naked_asm!` block are the ones that will actually be executed.\n - This effectively means that the compiler must treat the `naked_asm!` as a black box and only take the interface specification into account, not the instructions themselves.\n - Runtime code patching is allowed, via target-specific mechanisms.\n- Unwinding out of a `naked_asm!` block is allowed.\n - For correct behavior, the appropriate assembler directives that emit unwinding metadata must be used.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Rules for naked inline assembly"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#rules-for-naked-inline-assembly", "has_code": false, "code_tags": []}} {"id": "reference/inline-assembly.md#rules-for-naked-inline-assembly-47", "text": "The Rust Reference › Inline assembly › Rules for naked inline assembly\n\n```rust\n#[unsafe(naked)]\nextern \"sysv64-unwind\" fn unwinding_naked() {\n core::arch::naked_asm!(\n // \"CFI\" here stands for \"call frame information\".\n \".cfi_startproc\",\n // The CFA (canonical frame address) is the value of `rsp`\n // before the `call`, i.e. before the return address, `rip`,\n // was pushed to `rsp`, so it's eight bytes higher in memory\n // than `rsp` upon function entry (after `rip` has been\n // pushed).\n //\n // This is the default, so we don't have to write it.\n //\".cfi_def_cfa rsp, 8\",\n //\n // The traditional thing to do is to preserve the base\n // pointer, so we'll do that.\n \"push rbp\",\n // Since we've now extended the stack downward by 8 bytes in\n // memory, we need to adjust the offset to the CFA from `rsp`\n // by another 8 bytes.\n \".cfi_adjust_cfa_offset 8\",\n // We also then annotate where we've stored the caller's value\n // of `rbp`, relative to the CFA, so that when unwinding into\n // the caller we can find it, in case we need it to calculate\n // the caller's CFA relative to it.\n //\n // Here, we've stored the caller's `rbp` starting 16 bytes\n // below the CFA. I.e., starting from the CFA, there's first\n // the `rip` (which starts 8 bytes below the CFA and continues\n // up to it), then there's the caller's `rbp` that we just\n // pushed.\n \".cfi_offset rbp, -16\",\n // As is traditional, we set the base pointer to the value of\n // the stack pointer. This way, the base pointer stays the\n // same throughout the function body.\n \"mov rbp, rsp\",\n // We can now track the offset to the CFA from the base\n // pointer. This means we don't need to make any further\n // adjustments until the end, as we don't change `rbp`.\n \".cfi_def_cfa_register rbp\",\n // We can now call a function that may panic.\n \"call {f}\",\n // Upon return, we restore `rbp` in preparation for returning\n // ourselves.\n \"pop rbp\",\n // Now that we've restored `rbp`, we must specify the offset\n // to the CFA again in terms of `rsp`.\n \".cfi_def_cfa rsp, 8\",\n // Now we can return.\n \"ret\",\n \".cfi_endproc\",\n f = sym may_panic,\n )\n}\n\nextern \"sysv64-unwind\" fn may_panic() {\n panic!(\"unwind\");\n}\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Rules for naked inline assembly"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#rules-for-naked-inline-assembly", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/inline-assembly.md#rules-for-naked-inline-assembly-48", "text": "The Rust Reference › Inline assembly › Rules for naked inline assembly\n\nFor more information on the `cfi` assembler directives above, see these resources:\n- Using `as` - CFI directives\n- DWARF Debugging Information Format Version 5\n- ImperialViolet - CFI directives in assembly files", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Rules for naked inline assembly"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#rules-for-naked-inline-assembly", "has_code": false, "code_tags": []}} {"id": "reference/inline-assembly.md#correctness-and-validity-49", "text": "The Rust Reference › Inline assembly › Rules for naked inline assembly › Correctness and validity\n\nIn 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 the assembly code. Adherence to these rules is necessary, but not sufficient, for the final expanded assembly to be both correct and valid. For instance:\n- arguments may be placed in positions which are syntactically incorrect after formatting\n- an instruction may be correctly written, but given architecturally invalid operands\n- an architecturally unspecified instruction may be assembled into unspecified code\n- a set of instructions, each correct and valid, may cause undefined behavior if placed in immediate succession\nAs 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Rules for naked inline assembly", "Correctness and validity"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#correctness-and-validity", "has_code": false, "code_tags": []}} {"id": "reference/inline-assembly.md#directives-support-50", "text": "The Rust Reference › Inline assembly › Rules for naked inline assembly › Directives support\n\nInline 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).\nIf inline assembly includes any \"stateful\" directive that modifies how subsequent assembly is processed, the assembly code must undo the effects of any such directives before the inline assembly ends.\nThe following directives are guaranteed to be supported by the assembler:\n- `.2byte`\n- `.4byte`\n- `.8byte`\n- `.align`\n- `.alt_entry`\n- `.ascii`\n- `.asciz`\n- `.balign`\n- `.balignl`\n- `.balignw`\n- `.bss`\n- `.byte`\n- `.comm`\n- `.data`\n- `.def`\n- `.double`\n- `.endef`\n- `.equ`\n- `.equiv`\n- `.eqv`\n- `.fill`\n- `.float`\n- `.global`\n- `.globl`\n- `.inst`\n- `.insn`\n- `.lcomm`\n- `.long`\n- `.octa`\n- `.option`\n- `.p2align`\n- `.popsection`\n- `.private_extern`\n- `.pushsection`\n- `.quad`\n- `.scl`\n- `.section`\n- `.set`\n- `.short`\n- `.size`\n- `.skip`\n- `.sleb128`\n- `.space`\n- `.string`\n- `.text`\n- `.type`\n- `.uleb128`\n- `.word`", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Rules for naked inline assembly", "Directives support"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#directives-support", "has_code": false, "code_tags": []}} {"id": "reference/inline-assembly.md#x86-32-bit-and-64-bit-51", "text": "The Rust Reference › Inline assembly › Rules for naked inline assembly › Directives support › Target specific directive support › x86 (32-bit and 64-bit)\n\n```rust\nlet bytes: *const u8;\nlet len: usize;\nunsafe {\n core::arch::asm!(\n \"jmp 3f\", \"2: .ascii \\\"Hello World!\\\"\",\n \"3: lea {bytes}, [2b+rip]\",\n \"mov {len}, 12\",\n bytes = out(reg) bytes,\n len = out(reg) len\n );\n}\n\nlet s = unsafe { core::str::from_utf8_unchecked(core::slice::from_raw_parts(bytes, len)) };\n\nassert_eq!(s, \"Hello World!\");\n```\nThe following directives are supported on ELF targets that support DWARF unwind info:\n- `.cfi_adjust_cfa_offset`\n- `.cfi_def_cfa`\n- `.cfi_def_cfa_offset`\n- `.cfi_def_cfa_register`\n- `.cfi_endproc`\n- `.cfi_escape`\n- `.cfi_lsda`\n- `.cfi_offset`\n- `.cfi_personality`\n- `.cfi_register`\n- `.cfi_rel_offset`\n- `.cfi_remember_state`\n- `.cfi_restore`\n- `.cfi_restore_state`\n- `.cfi_return_column`\n- `.cfi_same_value`\n- `.cfi_sections`\n- `.cfi_signal_frame`\n- `.cfi_startproc`\n- `.cfi_undefined`\n- `.cfi_window_save`\nOn targets with structured exception Handling, the following additional directives are guaranteed to be supported:\n- `.seh_endproc`\n- `.seh_endprologue`\n- `.seh_proc`\n- `.seh_pushreg`\n- `.seh_savereg`\n- `.seh_setframe`\n- `.seh_stackalloc`", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Rules for naked inline assembly", "Directives support", "Target specific directive support", "x86 (32-bit and 64-bit)"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#x86-32-bit-and-64-bit", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/inline-assembly.md#arm-32-bit-52", "text": "The Rust Reference › Inline assembly › Rules for naked inline assembly › Directives support › Target specific directive support › ARM (32-bit)\n\nOn x86 targets, both 32-bit and 64-bit, the following additional directives are guaranteed to be supported:\n- `.nops`\n- `.code16`\n- `.code32`\n- `.code64`\nUse of `.code16`, `.code32`, and `.code64` directives are only supported if the state is reset to the default before exiting the assembly code. 32-bit x86 uses `.code32` by default, and x86_64 uses `.code64` by default.\nOn ARM, the following additional directives are guaranteed to be supported:\n- `.even`\n- `.fnstart`\n- `.fnend`\n- `.save`\n- `.movsp`\n- `.code`\n- `.thumb`\n- `.thumb_func`", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Rules for naked inline assembly", "Directives support", "Target specific directive support", "ARM (32-bit)"], "path": "inline-assembly.md", "url": "https://doc.rust-lang.org/reference/inline-assembly.html#arm-32-bit", "has_code": false, "code_tags": []}} {"id": "reference/unsafety.md#unsafety-0", "text": "The Rust Reference › Unsafety\n\nUnsafe operations are those that can potentially violate the memory-safety guarantees of Rust's static semantics.\nThe following language level features cannot be used in the safe subset of Rust:\n- Dereferencing a [raw pointer].\n- Reading or writing a [mutable] or unsafe [external] static variable.\n- Accessing a field of a [`union`], other than to assign to it.\n- Calling an unsafe function.\n- Calling a safe function marked with a `target_feature` from a function that does not have a `target_feature` attribute enabling the same features (see [attributes.codegen.target_feature.safety-restrictions]).\n- Implementing an [unsafe trait].\n- Declaring an [`extern`] block[^extern-2024].\n- Applying an [unsafe attribute] to an item.\n[^extern-2024]: Prior to the 2024 edition, extern blocks were allowed to be declared without `unsafe`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Unsafety", "heading_path": ["Unsafety"], "path": "unsafety.md", "url": "https://doc.rust-lang.org/reference/unsafety.html#unsafety", "has_code": false, "code_tags": []}} {"id": "reference/unsafe-keyword.md#the-unsafe-keyword-0", "text": "The Rust Reference › The `unsafe` keyword\n\nThe `unsafe` keyword is used to create or discharge the obligation to prove something safe. Specifically:\n- It is used to mark code that *defines* extra safety conditions that must be upheld elsewhere.\n - This includes `unsafe fn`, `unsafe static`, and `unsafe trait`.\n- It is used to mark code that the programmer *asserts* satisfies safety conditions defined elsewhere.\n - This includes `unsafe {}`, `unsafe impl`, `unsafe fn` without [`unsafe_op_in_unsafe_fn`], `unsafe extern`, and `#[unsafe(attr)]`.\nThe following discusses each of these cases. See the keyword documentation for some illustrative examples.\nThe `unsafe` keyword can occur in several different contexts:\n- unsafe functions (`unsafe fn`)\n- unsafe blocks (`unsafe {}`)\n- unsafe traits (`unsafe trait`)\n- unsafe trait implementations (`unsafe impl`)\n- unsafe external blocks (`unsafe extern`)\n- unsafe external statics (`unsafe static`)\n- unsafe attributes (`#[unsafe(attr)]`)", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "The `unsafe` keyword", "heading_path": ["The `unsafe` keyword"], "path": "unsafe-keyword.md", "url": "https://doc.rust-lang.org/reference/unsafe-keyword.html#the-unsafe-keyword", "has_code": false, "code_tags": []}} {"id": "reference/unsafe-keyword.md#unsafe-functions-unsafe-fn-1", "text": "The Rust Reference › The `unsafe` keyword › Unsafe functions (`unsafe fn`)\n\nUnsafe 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`] 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.\nSuch 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`] lint.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "The `unsafe` keyword", "heading_path": ["The `unsafe` keyword", "Unsafe functions (`unsafe fn`)"], "path": "unsafe-keyword.md", "url": "https://doc.rust-lang.org/reference/unsafe-keyword.html#unsafe-functions-unsafe-fn", "has_code": false, "code_tags": []}} {"id": "reference/unsafe-keyword.md#unsafe-blocks-unsafe--2", "text": "The Rust Reference › The `unsafe` keyword › Unsafe blocks (`unsafe {}`)\n\nA block of code can be prefixed with the `unsafe` keyword to permit using the unsafe actions as defined in the [Unsafety] chapter, such as calling other unsafe functions or dereferencing raw pointers.\nBy 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`] lint.\nBy 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.\nUnsafe 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 of functions or operations called inside the block 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`, in which case the block can use the proof obligations of that function to discharge the proof obligations arising inside the block.\nUnsafe 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.\nRust'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\" for a more in-depth exploration of this particular example.)", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "The `unsafe` keyword", "heading_path": ["The `unsafe` keyword", "Unsafe blocks (`unsafe {}`)"], "path": "unsafe-keyword.md", "url": "https://doc.rust-lang.org/reference/unsafe-keyword.html#unsafe-blocks-unsafe-", "has_code": false, "code_tags": []}} {"id": "reference/unsafe-keyword.md#unsafe-traits-unsafe-trait-3", "text": "The Rust Reference › The `unsafe` keyword › Unsafe traits (`unsafe trait`)\n\nAn 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.\nSuch a trait must be prefixed with the keyword `unsafe` and can only be implemented by `unsafe impl` blocks.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "The `unsafe` keyword", "heading_path": ["The `unsafe` keyword", "Unsafe traits (`unsafe trait`)"], "path": "unsafe-keyword.md", "url": "https://doc.rust-lang.org/reference/unsafe-keyword.html#unsafe-traits-unsafe-trait", "has_code": false, "code_tags": []}} {"id": "reference/unsafe-keyword.md#unsafe-trait-implementations-unsafe-impl-4", "text": "The Rust Reference › The `unsafe` keyword › Unsafe trait implementations (`unsafe impl`)\n\nWhen 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.\nUnsafe 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "The `unsafe` keyword", "heading_path": ["The `unsafe` keyword", "Unsafe trait implementations (`unsafe impl`)"], "path": "unsafe-keyword.md", "url": "https://doc.rust-lang.org/reference/unsafe-keyword.html#unsafe-trait-implementations-unsafe-impl", "has_code": false, "code_tags": []}} {"id": "reference/unsafe-keyword.md#unsafe-external-blocks-unsafe-extern-5", "text": "The Rust Reference › The `unsafe` keyword › Unsafe external blocks (`unsafe extern`)\n\nThe programmer who declares an [external block] must assure that the signatures of the items contained within are correct. Failing to do so may lead to undefined behavior. That this obligation has been met is indicated by writing `unsafe extern`.\n[!EDITION-2024]\nPrior to edition 2024, `extern` blocks were allowed without being qualified as `unsafe`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "The `unsafe` keyword", "heading_path": ["The `unsafe` keyword", "Unsafe external blocks (`unsafe extern`)"], "path": "unsafe-keyword.md", "url": "https://doc.rust-lang.org/reference/unsafe-keyword.html#unsafe-external-blocks-unsafe-extern", "has_code": false, "code_tags": []}} {"id": "reference/unsafe-keyword.md#unsafe-attributes-unsafeattr-6", "text": "The Rust Reference › The `unsafe` keyword › Unsafe attributes (`#[unsafe(attr)]`)\n\nAn [unsafe attribute] is one that has extra safety conditions that must be upheld when using the attribute. The compiler cannot check whether these conditions have been upheld. To assert that they have been, these attributes must be wrapped in `unsafe(..)`, e.g. `#[unsafe(no_mangle)]`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "The `unsafe` keyword", "heading_path": ["The `unsafe` keyword", "Unsafe attributes (`#[unsafe(attr)]`)"], "path": "unsafe-keyword.md", "url": "https://doc.rust-lang.org/reference/unsafe-keyword.html#unsafe-attributes-unsafeattr", "has_code": false, "code_tags": []}} {"id": "reference/behavior-considered-undefined.md#behavior-considered-undefined-0", "text": "The Rust Reference › Behavior considered undefined\n\nRust 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.\nIt 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*.\nThe following list is not exhaustive; it may grow or shrink. 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. We also reserve the right to make some of the behavior in that list defined in the future. In other words, this list does not say that anything will *definitely* always be undefined in all future Rust versions (but we might make such commitments for some list items in the future).\nPlease read the [Rustonomicon] before writing unsafe code.\n* Data races.\n* Accessing (loading from or storing to) a place that is [dangling] or [based on a misaligned pointer].\n* Performing an offsetting place projection that violates the requirements of in-bounds pointer arithmetic. An offsetting place projection is a field expression, a tuple index expression, or an array/slice index expression.\n* Breaking the pointer aliasing rules. The exact aliasing rules are not determined yet, but here is an outline of the general principles:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Behavior considered undefined", "heading_path": ["Behavior considered undefined"], "path": "behavior-considered-undefined.md", "url": "https://doc.rust-lang.org/reference/behavior-considered-undefined.html#behavior-considered-undefined", "has_code": false, "code_tags": []}} {"id": "reference/behavior-considered-undefined.md#behavior-considered-undefined-1", "text": "The Rust Reference › Behavior considered undefined\n\n`&T` must point to memory that is not mutated while they are live (except for data inside an [`UnsafeCell`]), and `&mut T` must point to memory that is not read or written by any pointer not derived from the reference and that no other reference points to while they are live. `Box` is treated similar to `&'static mut T` for the purpose of these rules. The exact liveness duration is not specified, but some bounds exist:\n * 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.\n * Each time a reference or box is dereferenced or reborrowed, it is considered live.\n * Each time a reference or box is passed to or returned from a function, it is considered live.\n * 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`].\n All this also applies when values of these types are passed in a (nested) field of a compound type, but not behind pointer indirections.\n* Mutating immutable bytes. All bytes reachable through a [const-promoted] expression are immutable, as well as bytes reachable through borrows in `static` and `const` initializers that have been [lifetime-extended] to `'static`. The bytes owned by an immutable binding or immutable `static` are immutable, unless those bytes are part of an [`UnsafeCell`].\n Moreover, the bytes [pointed to] by a shared reference, including transitively through other references (both shared and mutable) and `Box`es, are immutable; transitivity includes those references stored in fields of compound types.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Behavior considered undefined", "heading_path": ["Behavior considered undefined"], "path": "behavior-considered-undefined.md", "url": "https://doc.rust-lang.org/reference/behavior-considered-undefined.html#behavior-considered-undefined", "has_code": false, "code_tags": []}} {"id": "reference/behavior-considered-undefined.md#behavior-considered-undefined-2", "text": "The Rust Reference › Behavior considered undefined\n\nA mutation is any write of more than 0 bytes which overlaps with any of the relevant bytes (even if that write does not change the memory contents).\n* Invoking undefined behavior via compiler intrinsics.\n* Executing code compiled with platform features that the current platform does not support (see [`target_feature`]), *except* if the platform explicitly documents this to be safe.\n* Calling a function with the wrong call ABI, or unwinding past a stack frame that does not allow unwinding (e.g. by calling a `\"C-unwind\"` function imported or transmuted as a `\"C\"` function or function pointer).\n* Producing an invalid value. \"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.\n* Incorrect use of inline assembly. For more details, refer to the [rules] to follow when writing code that uses inline assembly.\n* Violating assumptions of the Rust runtime. Most assumptions of the Rust runtime are currently not explicitly documented.\n * For assumptions specifically related to unwinding, see the panic documentation.\n * The runtime assumes that a Rust stack frame is not deallocated without executing destructors for local variables owned by the stack frame. This assumption can be violated by C functions like `longjmp`.\nUndefined 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Behavior considered undefined", "heading_path": ["Behavior considered undefined"], "path": "behavior-considered-undefined.md", "url": "https://doc.rust-lang.org/reference/behavior-considered-undefined.html#behavior-considered-undefined", "has_code": false, "code_tags": []}} {"id": "reference/behavior-considered-undefined.md#pointed-to-bytes-3", "text": "The Rust Reference › Behavior considered undefined › Pointed-to bytes\n\nThe span of bytes a pointer or reference \"points to\" is determined by the pointer value and the size of the pointee type (using `size_of_val`).", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Behavior considered undefined", "heading_path": ["Behavior considered undefined", "Pointed-to bytes"], "path": "behavior-considered-undefined.md", "url": "https://doc.rust-lang.org/reference/behavior-considered-undefined.html#pointed-to-bytes", "has_code": false, "code_tags": []}} {"id": "reference/behavior-considered-undefined.md#places-based-on-misaligned-pointers-4", "text": "The Rust Reference › Behavior considered undefined › Places based on misaligned pointers\n\nA place is said to be \"based on a misaligned pointer\" if the last `*` projection during place computation was performed on a pointer that was not aligned for its type. (If there is no `*` projection in the place expression, then this is accessing the field of a local or `static` and rustc will guarantee proper alignment. If there are multiple `*` projections, then each of them incurs a load of the pointer-to-be-dereferenced itself from memory, and each of these loads is subject to the alignment constraint. Note that some `*` projections can be omitted in surface Rust syntax due to automatic dereferencing; we are considering the fully expanded place expression here.)\nFor instance, if `ptr` has type `*const S` where `S` has an alignment of 8, then `ptr` must be 8-aligned or else `(*ptr).f` is \"based on an misaligned pointer\". This is true even if the type of the field `f` is `u8` (i.e., a type with alignment 1). In other words, the alignment requirement derives from the type of the pointer that was dereferenced, *not* the type of the field that is being accessed.\nNote that a place based on a misaligned pointer only leads to undefined behavior when it is loaded from or stored to.\n`&raw const`/`&raw mut` on such a place is allowed.\n`&`/`&mut` on a place requires the alignment of the field type (or else the program would be \"producing an invalid value\"), which generally is a less restrictive requirement than being based on an aligned pointer.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Behavior considered undefined", "heading_path": ["Behavior considered undefined", "Places based on misaligned pointers"], "path": "behavior-considered-undefined.md", "url": "https://doc.rust-lang.org/reference/behavior-considered-undefined.html#places-based-on-misaligned-pointers", "has_code": false, "code_tags": []}} {"id": "reference/behavior-considered-undefined.md#places-based-on-misaligned-pointers-5", "text": "The Rust Reference › Behavior considered undefined › Places based on misaligned pointers\n\nTaking a reference will lead to a compiler error in cases where the field type might be more aligned than the type that contains it, i.e., `repr(packed)`. This means that being based on an aligned pointer is always sufficient to ensure that the new reference is aligned, but it is not always necessary.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Behavior considered undefined", "heading_path": ["Behavior considered undefined", "Places based on misaligned pointers"], "path": "behavior-considered-undefined.md", "url": "https://doc.rust-lang.org/reference/behavior-considered-undefined.html#places-based-on-misaligned-pointers", "has_code": false, "code_tags": []}} {"id": "reference/behavior-considered-undefined.md#dangling-pointers-6", "text": "The Rust Reference › Behavior considered undefined › Dangling pointers\n\nA reference/pointer is \"dangling\" if 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).\nIf the size is 0, then the pointer is trivially never \"dangling\" (even if it is a null pointer).\nNote 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.\nIn particular, the dynamic size of a Rust value (as determined by `size_of_val`) must never exceed `isize::MAX`, since it is impossible for a single allocation to be larger than `isize::MAX`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Behavior considered undefined", "heading_path": ["Behavior considered undefined", "Dangling pointers"], "path": "behavior-considered-undefined.md", "url": "https://doc.rust-lang.org/reference/behavior-considered-undefined.html#dangling-pointers", "has_code": false, "code_tags": []}} {"id": "reference/behavior-considered-undefined.md#invalid-values-7", "text": "The Rust Reference › Behavior considered undefined › Invalid values\n\nThe Rust compiler assumes that all values produced during program execution are \"valid\", and producing an invalid value is hence immediate UB.\nWhether a value is valid depends on the type:\n* A [`bool`] value must be `false` (`0`) or `true` (`1`).\n* A `fn` pointer value must be non-null.\n* A `char` value must not be a surrogate (i.e., must not be in the range `0xD800..=0xDFFF`) and must be equal to or less than `char::MAX`.\n* A `!` value must never exist.\n* An integer (`i*`/`u*`), floating point value (`f*`), or raw pointer must be initialized, i.e., must not be obtained from uninitialized memory.\n* A `str` value is treated like `[u8]`, i.e. it must be initialized.\n* An `enum` must have a valid discriminant, and all fields of the variant indicated by that discriminant must be valid at their respective type.\n* A `struct`, tuple, and array requires all fields/elements to be valid at their respective type.\n* For a `union`, the exact validity requirements are not decided yet. Obviously, all values that can be created entirely in safe code are valid. If the union has a [zero-sized] field, then every possible value is valid. Further details are still being debated.\n* A reference or [`Box`] must be aligned and non-null, it cannot be [dangling], and it must point to a valid value (in case of dynamically sized types, using the actual dynamic type of the pointee as determined by the [metadata]). Note that the last point (about pointing to a valid value) remains a subject of some debate.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Behavior considered undefined", "heading_path": ["Behavior considered undefined", "Invalid values"], "path": "behavior-considered-undefined.md", "url": "https://doc.rust-lang.org/reference/behavior-considered-undefined.html#invalid-values", "has_code": false, "code_tags": []}} {"id": "reference/behavior-considered-undefined.md#invalid-values-8", "text": "The Rust Reference › Behavior considered undefined › Invalid values\n\n* The [metadata] of a wide reference, [`Box`], or raw pointer must match the type of the [unsized tail]:\n * `dyn Trait` metadata must be a pointer to a compiler-generated vtable for `Trait`. (For raw pointers, this requirement remains a subject of some debate.)\n * Slice (`[T]`) and `str` metadata must be a valid `usize`.\n In addition, for a wide reference or [`Box`], the metadata is invalid if it makes the total size of the pointed-to value (as determined by `size_of_val`) bigger than `isize::MAX`.\nThis bound is on the size of the entire pointed-to value, not just its unsized tail, and it constrains `dyn Trait` metadata just as it does a slice or `str` length. A valid vtable describes an erased type no larger than `isize::MAX`, but a sized prefix can still carry the total past the limit.\n* If a type has a custom range of valid values, then a valid value must be in that range. In the standard library, this affects [`NonNull`] and [`NonZero`].\n`rustc` achieves this with the unstable `rustc_layout_scalar_valid_range_*` attributes.\n* **In [const contexts]**: In addition to what is described above, further provenance-related requirements apply during const evaluation. Any value that holds pure integer data (the `i*`/`u*`/`f*` types as well as `bool` and `char`, enum discriminants, and slice [metadata]) must not carry any provenance. Any value that holds pointer data (references, raw pointers, function pointers, and `dyn Trait` metadata) must either carry no provenance, or all bytes must be fragments of the same original pointer value in the correct order.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Behavior considered undefined", "heading_path": ["Behavior considered undefined", "Invalid values"], "path": "behavior-considered-undefined.md", "url": "https://doc.rust-lang.org/reference/behavior-considered-undefined.html#invalid-values", "has_code": false, "code_tags": []}} {"id": "reference/behavior-considered-undefined.md#invalid-values-9", "text": "The Rust Reference › Behavior considered undefined › Invalid values\n\nThis implies that transmuting or otherwise reinterpreting a pointer (reference, raw pointer, or function pointer) into a non-pointer type (such as integers) is undefined behavior if the pointer had provenance.\nAll of the following are UB:\n```rust,compile_fail\n// We cannot reinterpret a pointer with provenance as an integer,\n// as then the bytes of the integer will have provenance.\nconst _: usize = {\n let ptr = &0;\n unsafe { (&raw const ptr as *const usize).read() }\n};\n\n// We cannot rearrange the bytes of a pointer with provenance and\n// then interpret them as a reference, as then a value holding\n// pointer data will have pointer fragments in the wrong order.\nconst _: &i32 = {\n let mut ptr = &0;\n let ptr_bytes = &raw mut ptr as *mut MaybeUninit::;\n unsafe { ptr::swap(ptr_bytes.add(1), ptr_bytes.add(2)) };\n ptr\n};\n```\n**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 of a type).", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Behavior considered undefined", "heading_path": ["Behavior considered undefined", "Invalid values"], "path": "behavior-considered-undefined.md", "url": "https://doc.rust-lang.org/reference/behavior-considered-undefined.html#invalid-values", "has_code": true, "code_tags": ["rust,compile_fail"]}} {"id": "reference/behavior-not-considered-unsafe.md#behavior-not-considered-unsafe-0", "text": "The Rust Reference › Behavior not considered `unsafe`\n\nThe Rust compiler does not consider the following behaviors _unsafe_, though a programmer may (should) find them undesirable, unexpected, or erroneous.\n- Deadlocks\n- Leaks of memory and other resources\n- Exiting without calling destructors\n- Exposing randomized base addresses through pointer leaks", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Behavior not considered unsafe", "heading_path": ["Behavior not considered `unsafe`"], "path": "behavior-not-considered-unsafe.md", "url": "https://doc.rust-lang.org/reference/behavior-not-considered-unsafe.html#behavior-not-considered-unsafe", "has_code": false, "code_tags": []}} {"id": "reference/behavior-not-considered-unsafe.md#integer-overflow-1", "text": "The Rust Reference › Behavior not considered `unsafe` › Integer overflow\n\nIf 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.\nWhen 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.\nIn the case of implicitly-wrapped overflow, implementations must provide well-defined (even if still considered erroneous) results by using two's complement overflow conventions.\nThe integral types provide inherent methods to allow programmers explicitly to perform wrapping arithmetic. For example, `i32::wrapping_add` provides two's complement, wrapping addition.\nThe standard library also provides a `Wrapping` newtype which ensures all standard arithmetic operations for `T` have wrapping semantics.\nSee [RFC 560] for error conditions, rationale, and more details about integer overflow.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Behavior not considered unsafe", "heading_path": ["Behavior not considered `unsafe`", "Integer overflow"], "path": "behavior-not-considered-unsafe.md", "url": "https://doc.rust-lang.org/reference/behavior-not-considered-unsafe.html#integer-overflow", "has_code": false, "code_tags": []}} {"id": "reference/behavior-not-considered-unsafe.md#logic-errors-2", "text": "The Rust Reference › Behavior not considered `unsafe` › Logic errors\n\nSafe 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.\nFor 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Behavior not considered unsafe", "heading_path": ["Behavior not considered `unsafe`", "Logic errors"], "path": "behavior-not-considered-unsafe.md", "url": "https://doc.rust-lang.org/reference/behavior-not-considered-unsafe.html#logic-errors", "has_code": false, "code_tags": []}} {"id": "reference/const_eval.md#constant-evaluation-0", "text": "The Rust Reference › Constant evaluation\n\nConstant evaluation is the process of computing the result of [expressions] during compilation. Only a subset of all expressions can be evaluated at compile-time.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Constant evaluation", "heading_path": ["Constant evaluation"], "path": "const_eval.md", "url": "https://doc.rust-lang.org/reference/const_eval.html#constant-evaluation", "has_code": false, "code_tags": []}} {"id": "reference/const_eval.md#constant-expressions-1", "text": "The Rust Reference › Constant evaluation › Constant expressions\n\nCertain forms of expressions, called constant expressions, can be evaluated at compile time.\nExpressions in a [const context] must be constant expressions.\nExpressions in const contexts are always evaluated at compile time.\nOutside of const contexts, constant expressions *may* be, but are not guaranteed to be, evaluated at compile time.\nBehaviors such as out of bounds [array indexing] or [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.\nThe following expressions are constant expressions, so long as any operands are also constant expressions and do not cause any `Drop::drop` calls to be run.\n* [Literals].\n* [Const parameters].\n* [Paths] to [functions] and [constants]. Recursively defining constants is not allowed.\n* Paths to [statics] with these restrictions:\n * Writes to `static` items are not allowed in any constant evaluation context.\n * Reads from `extern` statics are not allowed in any constant evaluation context.\n * If the evaluation is *not* carried out in an initializer of a `static` item, then reads from any mutable `static` are not allowed. A mutable `static` is a `static mut` item, or a `static` item with an interior-mutable type.\n These requirements are checked only when the constant is evaluated. In other words, having such accesses syntactically occur in const contexts is allowed as long as they never get executed.\n* [Tuple expressions].\n* [Array expressions].\n* [Struct expressions].\n* [Block expressions], including `unsafe` and `const` blocks.\n * [let statements] and thus irrefutable [patterns], including mutable bindings\n * [assignment expressions]\n * [compound assignment expressions]\n * [expression statements]\n* [Field expressions].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Constant evaluation", "heading_path": ["Constant evaluation", "Constant expressions"], "path": "const_eval.md", "url": "https://doc.rust-lang.org/reference/const_eval.html#constant-expressions", "has_code": false, "code_tags": []}} {"id": "reference/const_eval.md#constant-expressions-2", "text": "The Rust Reference › Constant evaluation › Constant expressions\n\n* Array and slice indexing expressions, where the index is a `usize`.\n* [Range expressions].\n* [Closure expressions] which don't capture variables from the environment.\n* Built-in [negation], [arithmetic], [logical], [comparison] or [lazy boolean] operators used on integer and floating point types, `bool`, and `char`.\n* All forms of [borrow]s, including raw borrows, except borrows of expressions whose temporary scopes would be extended (see [temporary lifetime extension]) to the end of the program and which are either:\n * Mutable borrows.\n * Shared borrows of expressions that result in values with [interior mutability].\n```rust,compile_fail,E0764\n // Due to being in tail position, this borrow extends the scope of the\n // temporary to the end of the program. Since the borrow is mutable,\n // this is not allowed in a const expression.\n const C: &u8 = &mut 0; // ERROR not allowed\n```\n```rust,compile_fail,E0764\n // Const blocks are similar to initializers of `const` items.\n let _: &u8 = const { &mut 0 }; // ERROR not allowed\n```\n```rust,compile_fail,E0492\n # use core::sync::atomic::AtomicU8;\n // This is not allowed as 1) the temporary scope is extended to the\n // end of the program and 2) the temporary has interior mutability.\n const C: &AtomicU8 = &AtomicU8::new(0); // ERROR not allowed\n```\n```rust,compile_fail,E0492\n # use core::sync::atomic::AtomicU8;\n // As above.\n let _: &_ = const { &AtomicU8::new(0) }; // ERROR not allowed\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Constant evaluation", "heading_path": ["Constant evaluation", "Constant expressions"], "path": "const_eval.md", "url": "https://doc.rust-lang.org/reference/const_eval.html#constant-expressions", "has_code": true, "code_tags": ["rust,compile_fail,E0492", "rust,compile_fail,E0764"]}} {"id": "reference/const_eval.md#constant-expressions-3", "text": "The Rust Reference › Constant evaluation › Constant expressions\n\n```rust\n # #![allow(static_mut_refs)]\n // Even though this borrow is mutable, it's not of a temporary, so\n // this is allowed.\n const C: &u8 = unsafe { static mut S: u8 = 0; &mut S }; // OK\n```\n```rust\n # use core::sync::atomic::AtomicU8;\n // Even though this borrow is of a value with interior mutability,\n // it's not of a temporary, so this is allowed.\n const C: &AtomicU8 = {\n static S: AtomicU8 = AtomicU8::new(0); &S // OK\n };\n```\n```rust\n # use core::sync::atomic::AtomicU8;\n // This shared borrow of an interior mutable temporary is allowed\n // because its scope is not extended.\n const C: () = { _ = &AtomicU8::new(0); }; // OK\n```\n```rust\n // Even though the borrow is mutable and the temporary lives to the\n // end of the program due to promotion, this is allowed because the\n // borrow is not in tail position and so the scope of the temporary\n // is not extended via temporary lifetime extension.\n const C: () = { let _: &'static mut [u8] = &mut []; }; // OK\n // ~~\n // Promoted temporary.\n```\nIn other words --- to focus on what's allowed rather than what's not allowed --- shared borrows of interior mutable data and mutable borrows are only allowed in a [const context] when the borrowed [place expression] is *transient*, *indirect*, or *static*.\nA place expression is *transient* if it is a variable local to the current const context or an expression whose temporary scope is contained inside the current const context.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Constant evaluation", "heading_path": ["Constant evaluation", "Constant expressions"], "path": "const_eval.md", "url": "https://doc.rust-lang.org/reference/const_eval.html#constant-expressions", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/const_eval.md#constant-expressions-4", "text": "The Rust Reference › Constant evaluation › Constant expressions\n\n```rust\n// The borrow is of a variable local to the initializer, therefore\n// this place expression is transient.\nconst C: () = { let mut x = 0; _ = &mut x; };\n```\n```rust\n// The borrow is of a temporary whose scope has not been extended,\n// therefore this place expression is transient.\nconst C: () = { _ = &mut 0u8; };\n```\n```rust\n// When a temporary is promoted but not lifetime extended, its\n// place expression is still treated as transient.\nconst C: () = { let _: &'static mut [u8] = &mut []; };\n```\nA place expression is *indirect* if it is a [dereference expression].\n```rust\nconst C: () = { _ = &mut *(&mut 0); };\n```\nA place expression is *static* if it is a `static` item.\n```rust\nconst C: &u8 = unsafe { static mut S: u8 = 0; &mut S };\n```\nOne surprising consequence of these rules is that we allow this,\n```rust\nconst C: &[u8] = { let x: &mut [u8] = &mut []; x }; // OK\n// ~~~~~~~\n// Empty arrays are promoted even behind mutable borrows.\n```\nbut we disallow this similar code:\n```rust,compile_fail,E0764\nconst C: &[u8] = &mut []; // ERROR\n// ~~~~~~~\n// Tail expression.\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Constant evaluation", "heading_path": ["Constant evaluation", "Constant expressions"], "path": "const_eval.md", "url": "https://doc.rust-lang.org/reference/const_eval.html#constant-expressions", "has_code": true, "code_tags": ["rust", "rust,compile_fail,E0764"]}} {"id": "reference/const_eval.md#constant-expressions-5", "text": "The Rust Reference › Constant evaluation › Constant expressions\n\nThe difference between these is that, in the first, the empty array is [promoted] but its scope does not undergo [temporary lifetime extension], so we consider the [place expression] to be transient (even though after promotion the place indeed lives to the end of the program). In the second, the scope of the empty array temporary does undergo lifetime extension, and so it is rejected due to being a mutable borrow of a lifetime-extended temporary (and therefore borrowing a non-transient place expression).\nThe effect is surprising because temporary lifetime extension, in this case, causes less code to compile than would without it.\nSee issue #143129 for more details.\n* [Dereference expressions].\n```rust,no_run\n # use core::cell::UnsafeCell;\n const _: u8 = unsafe {\n let x: *mut u8 = &raw mut *&mut 0;\n // ^^^^^^^\n // Dereference of mutable reference.\n *x = 1; // Dereference of mutable pointer.\n *(x as *const u8) // Dereference of constant pointer.\n };\n const _: u8 = unsafe {\n let x = &UnsafeCell::new(0);\n *x.get() = 1; // Mutation of interior mutable value.\n *x.get()\n };\n```\n* [Grouped] expressions.\n* [Cast] expressions, except\n * pointer to address casts and\n * function pointer to address casts.\n* Calls of [const functions] and const methods.\n* [loop] and [while] expressions.\n* [if] and [match] expressions.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Constant evaluation", "heading_path": ["Constant evaluation", "Constant expressions"], "path": "const_eval.md", "url": "https://doc.rust-lang.org/reference/const_eval.html#constant-expressions", "has_code": true, "code_tags": ["rust,no_run"]}} {"id": "reference/const_eval.md#const-context-6", "text": "The Rust Reference › Constant evaluation › Const context\n\nA _const context_ is one of the following:\n* [Array type length expressions]\n* Array repeat length expressions\n* The initializer of\n * [constants]\n * [statics]\n * [enum discriminants]\n* A [const generic argument]\n* A [const block]\nArray type length expressions, array repeat length expressions, and const generic arguments are restricted in their use of outer generic parameters: such an expression must either be a single const generic parameter, or an expression that does not reference any generic parameters.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Constant evaluation", "heading_path": ["Constant evaluation", "Const context"], "path": "const_eval.md", "url": "https://doc.rust-lang.org/reference/const_eval.html#const-context", "has_code": false, "code_tags": []}} {"id": "reference/const_eval.md#const-functions-7", "text": "The Rust Reference › Constant evaluation › Const functions\n\nA _const function_ is a function that can be called from a const context. It is defined with the `const` qualifier, and also includes [tuple struct] and [tuple enum variant] constructors.\n```rust\nconst fn square(x: i32) -> i32 { x * x }\n\nconst VALUE: i32 = square(12);\n```\nWhen called from a const context, a const 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.\nWhen a const function is called from outside a const context, it behaves the same as if it did not have the `const` qualifier.\nThe body of a const function may only use [constant expressions].\nConst functions are not allowed to be [async].\nThe types of a const function's parameters and return type are restricted to those that are compatible with a const context.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Constant evaluation", "heading_path": ["Constant evaluation", "Const functions"], "path": "const_eval.md", "url": "https://doc.rust-lang.org/reference/const_eval.html#const-functions", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/abi.md#application-binary-interface-abi-0", "text": "The Rust Reference › Application binary interface (ABI)\n\nThis section documents features that affect the ABI of the compiled output of a crate.\nSee *[extern functions]* for information on specifying the ABI for exporting functions. See *[external blocks]* for information on specifying the ABI for linking external libraries.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Application binary interface", "heading_path": ["Application binary interface (ABI)"], "path": "abi.md", "url": "https://doc.rust-lang.org/reference/abi.html#application-binary-interface-abi", "has_code": false, "code_tags": []}} {"id": "reference/abi.md#the-used-attribute-1", "text": "The Rust Reference › Application binary interface (ABI) › The `used` attribute\n\nThe *`used` [attribute]* forces a [static] to be kept in the output object file (.o, .rlib, etc., excluding final binaries) even if it's never used or referenced by any other item in the crate. The linker, however, is still free to remove it.\n```rust\n// lib.rs\n\n// This is kept because of `#[used]`.\n#[used]\nstatic S1: u8 = 0;\n\n// This is removable because it's unused.\n#[allow(dead_code)]\nstatic S2: u8 = 0;\n\n// This is kept because it's publicly reachable.\npub static S3: u8 = 0;\n\n// This is kept because it's referenced by a publicly\n// reachable function.\nstatic S4: u8 = 0;\n#[unsafe(no_mangle)] pub fn f4() -> &'static u8 { &S4 }\n\n// This is removable because it's referenced only by a\n// private, unused (dead) function.\nstatic S5: u8 = 0;\n#[allow(dead_code)]\nfn f5() -> &'static u8 { &S5 }\n```\n```console\n$ rustc -O --emit=obj --crate-type=rlib lib.rs\n$ LC_ALL=C nm -C lib.o\n0000000000000000 R lib::S1\n0000000000000000 R lib::S3\n0000000000000000 r lib::S4\n0000000000000000 T f4\n```\nThe `used` attribute uses the [MetaWord] syntax.\nThe `used` attribute may only be applied to [`static` items].\nOnly the first use of `used` on an item has effect.\n`rustc` lints against any use following the first.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Application binary interface", "heading_path": ["Application binary interface (ABI)", "The `used` attribute"], "path": "abi.md", "url": "https://doc.rust-lang.org/reference/abi.html#the-used-attribute", "has_code": true, "code_tags": ["console", "rust"]}} {"id": "reference/abi.md#the-no_mangle-attribute-2", "text": "The Rust Reference › Application binary interface (ABI) › The `no_mangle` attribute\n\nThe *`no_mangle` attribute* may be used on any [item] to disable standard symbol name mangling. The symbol for the item will be the identifier of the item's name.\nAdditionally, the item will be publicly exported from the produced library or object file, similar to the `used` attribute.\nThis attribute is unsafe as an unmangled symbol may collide with another symbol with the same name (or with a well-known symbol), leading to undefined behavior.\n```rust\n#[unsafe(no_mangle)]\nextern \"C\" fn foo() {}\n```\n[!EDITION-2024]\nBefore the 2024 edition it is allowed to use the `no_mangle` attribute without the `unsafe` qualification.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Application binary interface", "heading_path": ["Application binary interface (ABI)", "The `no_mangle` attribute"], "path": "abi.md", "url": "https://doc.rust-lang.org/reference/abi.html#the-no_mangle-attribute", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/abi.md#the-link_section-attribute-3", "text": "The Rust Reference › Application binary interface (ABI) › The `link_section` attribute\n\nThe *`link_section` attribute* specifies the section of the object file that a [function] or [static]'s content will be placed into.\nThe `link_section` attribute uses the [MetaNameValueStr] syntax to specify the section name.\n```rust,no_run\n#[unsafe(no_mangle)]\n#[unsafe(link_section = \".example_section\")]\npub static VAR1: u32 = 1;\n```\nThis attribute is unsafe as it allows users to place data and code into sections of memory not expecting them, such as mutable data into read-only areas.\nOnly the first use of `link_section` on an item has effect.\n`rustc` lints against any use following the first with a future-compatibility warning. This may become an error in the future.\n[!EDITION-2024]\nBefore the 2024 edition it is allowed to use the `link_section` attribute without the `unsafe` qualification.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Application binary interface", "heading_path": ["Application binary interface (ABI)", "The `link_section` attribute"], "path": "abi.md", "url": "https://doc.rust-lang.org/reference/abi.html#the-link_section-attribute", "has_code": true, "code_tags": ["rust,no_run"]}} {"id": "reference/abi.md#the-export_name-attribute-4", "text": "The Rust Reference › Application binary interface (ABI) › The `export_name` attribute\n\nThe *`export_name` attribute* specifies the name of the symbol that will be exported on a [function] or [static].\nThe `export_name `attribute uses the [MetaNameValueStr] syntax to specify the symbol name.\n```rust\n#[unsafe(export_name = \"exported_symbol_name\")]\npub fn name_in_rust() { }\n```\nThis attribute is unsafe as a symbol with a custom name may collide with another symbol with the same name (or with a well-known symbol), leading to undefined behavior.\nOnly the first use of `export_name` on an item has effect.\n`rustc` lints against any use following the first with a future-compatibility warning. This may become an error in the future.\n[!EDITION-2024]\nBefore the 2024 edition it is allowed to use the `export_name` attribute without the `unsafe` qualification.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Application binary interface", "heading_path": ["Application binary interface (ABI)", "The `export_name` attribute"], "path": "abi.md", "url": "https://doc.rust-lang.org/reference/abi.html#the-export_name-attribute", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/runtime.md#the-rust-runtime-0", "text": "The Rust Reference › The Rust runtime\n\nThis section documents features that define some aspects of the Rust runtime.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "The Rust runtime", "heading_path": ["The Rust runtime"], "path": "runtime.md", "url": "https://doc.rust-lang.org/reference/runtime.html#the-rust-runtime", "has_code": false, "code_tags": []}} {"id": "reference/runtime.md#the-global_allocator-attribute-1", "text": "The Rust Reference › The Rust runtime › The `global_allocator` attribute\n\nThe *`global_allocator` attribute* selects a memory allocator.\n```rust\nuse core::alloc::{GlobalAlloc, Layout};\nuse std::alloc::System;\n\nstruct MyAllocator;\n\nunsafe impl GlobalAlloc for MyAllocator {\n unsafe fn alloc(&self, layout: Layout) -> *mut u8 {\n unsafe { System.alloc(layout) }\n }\n unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {\n unsafe { System.dealloc(ptr, layout) }\n }\n}\n\n#[global_allocator]\nstatic GLOBAL: MyAllocator = MyAllocator;\n```\nThe `global_allocator` attribute uses the [MetaWord] syntax.\nThe `global_allocator` attribute may only be applied to a [static item] whose type implements the [`GlobalAlloc`] trait.\nThe `global_allocator` attribute may only be used once on an item.\nThe `global_allocator` attribute may only be used once in the crate graph.\nThe `global_allocator` attribute is exported from the standard library prelude.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "The Rust runtime", "heading_path": ["The Rust runtime", "The `global_allocator` attribute"], "path": "runtime.md", "url": "https://doc.rust-lang.org/reference/runtime.html#the-global_allocator-attribute", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/runtime.md#the-windows_subsystem-attribute-2", "text": "The Rust Reference › The Rust runtime › The `windows_subsystem` attribute\n\nThe *`windows_subsystem` attribute* sets the [subsystem] when linking on a Windows target.\n```rust\n#![windows_subsystem = \"windows\"]\n```\nThe `windows_subsystem` attribute uses the [MetaNameValueStr] syntax. Accepted values are `\"console\"` and `\"windows\"`.\nThe `windows_subsystem` attribute may only be applied to the crate root.\nOnly the first use of `windows_subsystem` has effect.\n`rustc` lints against any use following the first. This may become an error in the future.\nThe `windows_subsystem` attribute is ignored on non-Windows targets and non-`bin` [crate types].\nThe `\"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.\nThe `\"windows\"` subsystem will run detached from any existing console.\nThe `\"windows\"` subsystem is commonly used by GUI applications that do not want to display a console window on startup.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "The Rust runtime", "heading_path": ["The Rust runtime", "The `windows_subsystem` attribute"], "path": "runtime.md", "url": "https://doc.rust-lang.org/reference/runtime.html#the-windows_subsystem-attribute", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/macro-ambiguity.md#appendix-macro-follow-set-ambiguity-formal-specification-0", "text": "The Rust Reference › Appendix: Macro follow-set ambiguity formal specification\n\nThis page documents the formal specification of the follow rules for [Macros By Example]. They were originally specified in [RFC 550], from which the bulk of this text is copied, and expanded upon in subsequent RFCs.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macro follow-set ambiguity formal specification", "heading_path": ["Appendix: Macro follow-set ambiguity formal specification"], "path": "macro-ambiguity.md", "url": "https://doc.rust-lang.org/reference/macro-ambiguity.html#appendix-macro-follow-set-ambiguity-formal-specification", "has_code": false, "code_tags": []}} {"id": "reference/macro-ambiguity.md#definitions--conventions-1", "text": "The Rust Reference › Appendix: Macro follow-set ambiguity formal specification › Definitions & conventions\n\n- `macro`: anything invocable as `foo!(...)` in source code.\n - `MBE`: macro-by-example, a macro defined by `macro_rules`.\n - `matcher`: the left-hand-side of a rule in a `macro_rules` invocation, or a subportion thereof.\n - `macro parser`: the bit of code in the Rust parser that will parse the input using a grammar derived from all of the matchers.\n - `fragment`: The class of Rust syntax that a given matcher will accept (or \"match\").\n - `repetition` : a fragment that follows a regular repeating pattern\n - `NT`: non-terminal, the various \"meta-variables\" or repetition matchers that can appear in a matcher, specified in MBE syntax with a leading `$` character.\n - `simple NT`: a \"meta-variable\" non-terminal (further discussion below).\n - `complex NT`: a repetition matching non-terminal, specified via repetition operators (`*`, `+`, `?`).\n - `token`: an atomic element of a matcher; i.e. identifiers, operators, open/close delimiters, *and* simple NT's.\n - `token tree`: a tree structure formed from tokens (the leaves), complex NT's, and finite sequences of token trees.\n - `delimiter token`: a token that is meant to divide the end of one fragment and the start of the next fragment.\n - `separator token`: an optional delimiter token in an complex NT that separates each pair of elements in the matched repetition.\n - `separated complex NT`: a complex NT that has its own separator token.\n - `delimited sequence`: a sequence of token trees with appropriate open- and close-delimiters at the start and end of the sequence.\n - `empty fragment`: The class of invisible Rust syntax that separates tokens, i.e. whitespace, or (in some lexical contexts), the empty token sequence.\n - `fragment specifier`: The identifier in a simple NT that specifies which fragment the NT accepts.\n - `language`: a context-free language.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macro follow-set ambiguity formal specification", "heading_path": ["Appendix: Macro follow-set ambiguity formal specification", "Definitions & conventions"], "path": "macro-ambiguity.md", "url": "https://doc.rust-lang.org/reference/macro-ambiguity.html#definitions--conventions", "has_code": false, "code_tags": []}} {"id": "reference/macro-ambiguity.md#definitions--conventions-2", "text": "The Rust Reference › Appendix: Macro follow-set ambiguity formal specification › Definitions & conventions\n\nExample:\n```rust,compile_fail\nmacro_rules! i_am_an_mbe {\n (start $foo:expr $($i:ident),* end) => ($foo)\n}\n```\n`(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.\n`$(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.\nAnother example of a complex NT is `$(hi $e:expr ;)+`, which matches any fragment of the form `hi ; hi ; ...` where `hi ;` occurs at least once. Note that this complex NT does not have a dedicated separator token.\n(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.)\nWe 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.)\n\"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 `]`).", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macro follow-set ambiguity formal specification", "heading_path": ["Appendix: Macro follow-set ambiguity formal specification", "Definitions & conventions"], "path": "macro-ambiguity.md", "url": "https://doc.rust-lang.org/reference/macro-ambiguity.html#definitions--conventions", "has_code": true, "code_tags": ["rust,compile_fail"]}} {"id": "reference/macro-ambiguity.md#definitions--conventions-3", "text": "The Rust Reference › Appendix: Macro follow-set ambiguity formal specification › Definitions & conventions\n\nGreek 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.)\n * 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.\nNote 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.\nNote also that in the context of this formalism, the term \"token\" generally *includes* simple NTs.\nFinally, 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macro follow-set ambiguity formal specification", "heading_path": ["Appendix: Macro follow-set ambiguity formal specification", "Definitions & conventions"], "path": "macro-ambiguity.md", "url": "https://doc.rust-lang.org/reference/macro-ambiguity.html#definitions--conventions", "has_code": false, "code_tags": []}} {"id": "reference/macro-ambiguity.md#the-matcher-invariants-4", "text": "The Rust Reference › Appendix: Macro follow-set ambiguity formal specification › Definitions & conventions › The matcher invariants\n\nTo be valid, a matcher must meet the following three invariants. The definitions of FIRST and FOLLOW are described later.\n1. 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 ...`).\n1. For any separated complex NT in a matcher, `M = ... $(tt ...) SEP OP ...`, we must have `SEP` ∈ FOLLOW(`tt ...`).\n1. For an unseparated complex NT in a matcher, `M = ... $(tt ...) OP ...`, if OP = `*` or `+`, we must have FOLLOW(`tt ...`) ⊇ FIRST(`tt ...`).\nThe 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.\nThe 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.\nThe 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macro follow-set ambiguity formal specification", "heading_path": ["Appendix: Macro follow-set ambiguity formal specification", "Definitions & conventions", "The matcher invariants"], "path": "macro-ambiguity.md", "url": "https://doc.rust-lang.org/reference/macro-ambiguity.html#the-matcher-invariants", "has_code": false, "code_tags": []}} {"id": "reference/macro-ambiguity.md#the-matcher-invariants-5", "text": "The Rust Reference › Appendix: Macro follow-set ambiguity formal specification › Definitions & conventions › The matcher invariants\n\n**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].**", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macro follow-set ambiguity formal specification", "heading_path": ["Appendix: Macro follow-set ambiguity formal specification", "Definitions & conventions", "The matcher invariants"], "path": "macro-ambiguity.md", "url": "https://doc.rust-lang.org/reference/macro-ambiguity.html#the-matcher-invariants", "has_code": false, "code_tags": []}} {"id": "reference/macro-ambiguity.md#first-and-follow-informally-6", "text": "The Rust Reference › Appendix: Macro follow-set ambiguity formal specification › Definitions & conventions › FIRST and FOLLOW, informally\n\nA given matcher M maps to three sets: FIRST(M), LAST(M) and FOLLOW(M).\nEach 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.)\nInformally:\n * FIRST(M): collects the tokens potentially used first when matching a fragment to M.\n * LAST(M): collects the tokens potentially used last when matching a fragment to M.\n * FOLLOW(M): the set of tokens allowed to follow immediately after some fragment matched by M.\n In other words: t ∈ FOLLOW(M) if and only if there exists (potentially empty) token sequences α, β, γ, δ where:\n * M matches β,\n * t matches γ, and\n * The concatenation α β γ δ is a parseable Rust program.\nWe 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.\n(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 before reading their formal definitions.)", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macro follow-set ambiguity formal specification", "heading_path": ["Appendix: Macro follow-set ambiguity formal specification", "Definitions & conventions", "FIRST and FOLLOW, informally"], "path": "macro-ambiguity.md", "url": "https://doc.rust-lang.org/reference/macro-ambiguity.html#first-and-follow-informally", "has_code": false, "code_tags": []}} {"id": "reference/macro-ambiguity.md#first-7", "text": "The Rust Reference › Appendix: Macro follow-set ambiguity formal specification › Definitions & conventions › FIRST, LAST › FIRST\n\nBelow are formal inductive definitions for FIRST and LAST.\n\"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).\nFIRST(M) is defined by case analysis on the sequence M and the structure of its first token-tree (if any):\n * if M is the empty sequence, then FIRST(M) = { ε },\n * if M starts with a token t, then FIRST(M) = { t },\n (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` }.)\n (Note: this critically relies on the property that no simple NT matches the empty fragment.)\n * 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).\n * Let SEP\\_SET(M) = { SEP } if SEP is present and ε ∈ FIRST(`tt ...`); otherwise SEP\\_SET(M) = {}.\n * Let ALPHA\\_SET(M) = FIRST(`α`) if OP = `*` or `?` and ALPHA\\_SET(M) = {} if OP = `+`.\n * FIRST(M) = (FIRST(`tt ...`) \\\\ {ε}) ∪ SEP\\_SET(M) ∪ ALPHA\\_SET(M).", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macro follow-set ambiguity formal specification", "heading_path": ["Appendix: Macro follow-set ambiguity formal specification", "Definitions & conventions", "FIRST, LAST", "FIRST"], "path": "macro-ambiguity.md", "url": "https://doc.rust-lang.org/reference/macro-ambiguity.html#first", "has_code": false, "code_tags": []}} {"id": "reference/macro-ambiguity.md#last-8", "text": "The Rust Reference › Appendix: Macro follow-set ambiguity formal specification › Definitions & conventions › FIRST, LAST › LAST\n\nThe 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.\nFrom 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.\nLAST(M), defined by case analysis on M itself (a sequence of token-trees):\n * if M is the empty sequence, then LAST(M) = { ε }\n * if M is a singleton token t, then LAST(M) = { t }", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macro follow-set ambiguity formal specification", "heading_path": ["Appendix: Macro follow-set ambiguity formal specification", "Definitions & conventions", "FIRST, LAST", "LAST"], "path": "macro-ambiguity.md", "url": "https://doc.rust-lang.org/reference/macro-ambiguity.html#last", "has_code": false, "code_tags": []}} {"id": "reference/macro-ambiguity.md#last-9", "text": "The Rust Reference › Appendix: Macro follow-set ambiguity formal specification › Definitions & conventions › FIRST, LAST › LAST\n\n* if M is the singleton complex NT repeating zero or more times, `M = $( tt ... ) *`, or `M = $( tt ... ) SEP *`\n * Let sep_set = { SEP } if SEP present; otherwise sep_set = {}.\n * if ε ∈ LAST(`tt ...`) then LAST(M) = LAST(`tt ...`) ∪ sep_set\n * otherwise, the sequence `tt ...` must be non-empty; LAST(M) = LAST(`tt ...`) ∪ {ε}.\n * if M is the singleton complex NT repeating one or more times, `M = $( tt ... ) +`, or `M = $( tt ... ) SEP +`\n * Let sep_set = { SEP } if SEP present; otherwise sep_set = {}.\n * if ε ∈ LAST(`tt ...`) then LAST(M) = LAST(`tt ...`) ∪ sep_set\n * otherwise, the sequence `tt ...` must be non-empty; LAST(M) = LAST(`tt ...`)\n * if M is the singleton complex NT repeating zero or one time, `M = $( tt ...) ?`, then LAST(M) = LAST(`tt ...`) ∪ {ε}.\n * if M is a delimited token-tree sequence `OPEN tt ... CLOSE`, then LAST(M) = { `CLOSE` }.\n * if M is a non-empty sequence of token-trees `tt uu ...`,\n * If ε ∈ LAST(`uu ...`), then LAST(M) = LAST(`tt`) ∪ (LAST(`uu ...`) \\ { ε }).\n * Otherwise, the sequence `uu ...` must be non-empty; then LAST(M) = LAST(`uu ...`).", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macro follow-set ambiguity formal specification", "heading_path": ["Appendix: Macro follow-set ambiguity formal specification", "Definitions & conventions", "FIRST, LAST", "LAST"], "path": "macro-ambiguity.md", "url": "https://doc.rust-lang.org/reference/macro-ambiguity.html#last", "has_code": false, "code_tags": []}} {"id": "reference/macro-ambiguity.md#examples-of-first-and-last-10", "text": "The Rust Reference › Appendix: Macro follow-set ambiguity formal specification › Definitions & conventions › Examples of FIRST and LAST\n\nBelow 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.)\nOur 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.)\n```text\nINPUT: $( $d:ident $e:expr );* $( $( h )* );* $( f ; )+ g\n ~~~~~~~~ ~~~~~~~ ~\n | | |\nFIRST: { $d:ident } { $e:expr } { h }\n\n\nINPUT: $( $d:ident $e:expr );* $( $( h )* );* $( f ; )+\n ~~~~~~~~~~~~~~~~~~ ~~~~~~~ ~~~\n | | |\nFIRST: { $d:ident } { h, ε } { f }\n\nINPUT: $( $d:ident $e:expr );* $( $( h )* );* $( f ; )+ g\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~ ~~~~~~~~~ ~\n | | | |\nFIRST: { $d:ident, ε } { h, ε, ; } { f } { g }\n\n\nINPUT: $( $d:ident $e:expr );* $( $( h )* );* $( f ; )+ g\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n |\nFIRST: { $d:ident, h, ;, f }\n```\nThus:\n * FIRST(`$($d:ident $e:expr );* $( $(h)* );* $( f ;)+ g`) = { `$d:ident`, `h`, `;`, `f` }\nNote however that:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macro follow-set ambiguity formal specification", "heading_path": ["Appendix: Macro follow-set ambiguity formal specification", "Definitions & conventions", "Examples of FIRST and LAST"], "path": "macro-ambiguity.md", "url": "https://doc.rust-lang.org/reference/macro-ambiguity.html#examples-of-first-and-last", "has_code": true, "code_tags": ["text"]}} {"id": "reference/macro-ambiguity.md#examples-of-first-and-last-11", "text": "The Rust Reference › Appendix: Macro follow-set ambiguity formal specification › Definitions & conventions › Examples of FIRST and LAST\n\n* FIRST(`$($d:ident $e:expr );* $( $(h)* );* $($( f ;)+ g)*`) = { `$d:ident`, `h`, `;`, `f`, ε }\nHere are similar examples but now for LAST.\n * LAST(`$d:ident $e:expr`) = { `$e:expr` }\n * LAST(`$( $d:ident $e:expr );*`) = { `$e:expr`, ε }\n * LAST(`$( $d:ident $e:expr );* $(h)*`) = { `$e:expr`, ε, `h` }\n * LAST(`$( $d:ident $e:expr );* $(h)* $( f ;)+`) = { `;` }\n * LAST(`$( $d:ident $e:expr );* $(h)* $( f ;)+ g`) = { `g` }", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macro follow-set ambiguity formal specification", "heading_path": ["Appendix: Macro follow-set ambiguity formal specification", "Definitions & conventions", "Examples of FIRST and LAST"], "path": "macro-ambiguity.md", "url": "https://doc.rust-lang.org/reference/macro-ambiguity.html#examples-of-first-and-last", "has_code": false, "code_tags": []}} {"id": "reference/macro-ambiguity.md#followm-12", "text": "The Rust Reference › Appendix: Macro follow-set ambiguity formal specification › Definitions & conventions › FOLLOW(M)\n\nFinally, the definition for FOLLOW(M) is built up as follows. pat, expr, etc. represent simple nonterminals with the given fragment specifier.\n * FOLLOW(pat) = {`=>`, `,`, `=`, `|`, `if`, `in`}`.\n * FOLLOW(expr) = FOLLOW(expr_2021) = FOLLOW(stmt) = {`=>`, `,`, `;`}`.\n * FOLLOW(ty) = FOLLOW(path) = {`{`, `[`, `,`, `=>`, `:`, `=`, `>`, `>>`, `;`, `|`, `as`, `where`, block nonterminals}.\n * FOLLOW(vis) = {`,`l any keyword or identifier except a non-raw `priv`; any token that can begin a type; ident, ty, and path nonterminals}.\n * FOLLOW(t) = ANYTOKEN for any other simple token, including block, ident, tt, item, lifetime, literal and meta simple nonterminals, and all terminals.\n * FOLLOW(M), for any other M, is defined as the intersection, as t ranges over (LAST(M) \\ {ε}), of FOLLOW(t).\nThe 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.\nExamples of FOLLOW for complex M:", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macro follow-set ambiguity formal specification", "heading_path": ["Appendix: Macro follow-set ambiguity formal specification", "Definitions & conventions", "FOLLOW(M)"], "path": "macro-ambiguity.md", "url": "https://doc.rust-lang.org/reference/macro-ambiguity.html#followm", "has_code": false, "code_tags": []}} {"id": "reference/macro-ambiguity.md#followm-13", "text": "The Rust Reference › Appendix: Macro follow-set ambiguity formal specification › Definitions & conventions › FOLLOW(M)\n\n* FOLLOW(`$( $d:ident $e:expr )*`) = FOLLOW(`$e:expr`)\n * FOLLOW(`$( $d:ident $e:expr )* $(;)*`) = FOLLOW(`$e:expr`) ∩ ANYTOKEN = FOLLOW(`$e:expr`)\n * FOLLOW(`$( $d:ident $e:expr )* $(;)* $( f |)+`) = ANYTOKEN", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macro follow-set ambiguity formal specification", "heading_path": ["Appendix: Macro follow-set ambiguity formal specification", "Definitions & conventions", "FOLLOW(M)"], "path": "macro-ambiguity.md", "url": "https://doc.rust-lang.org/reference/macro-ambiguity.html#followm", "has_code": false, "code_tags": []}} {"id": "reference/macro-ambiguity.md#examples-of-valid-and-invalid-matchers-14", "text": "The Rust Reference › Appendix: Macro follow-set ambiguity formal specification › Definitions & conventions › Examples of valid and invalid matchers\n\nWith the above specification in hand, we can present arguments for why particular matchers are legal and others are not.\n * `($ty:ty < foo ,)` : illegal, because FIRST(`< foo ,`) = { `<` } ⊈ FOLLOW(`ty`)\n * `($ty:ty , foo <)` : legal, because FIRST(`, foo <`) = { `,` } is ⊆ FOLLOW(`ty`).\n * `($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`).\n * `( $($a:tt $b:tt)* ; )` : legal, because FIRST(`$b:tt`) = { `$b:tt` } is ⊆ FOLLOW(`tt`) = ANYTOKEN, as is FIRST(`;`) = { `;` }.\n * `( $($t:tt),* , $(t:tt),* )` : legal, (though any attempt to actually use this macro will signal a local ambiguity error during expansion).\n * `($ty:ty $(; not sep)* -)` : illegal, because FIRST(`$(; not sep)* -`) = { `;`, `-` } is not in FOLLOW(`ty`).\n * `($($ty:ty)-+)` : illegal, because separator `-` is not in FOLLOW(`ty`).\n * `($($e:expr)*)` : illegal, because expr NTs are not in FOLLOW(expr NT).", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Macro follow-set ambiguity formal specification", "heading_path": ["Appendix: Macro follow-set ambiguity formal specification", "Definitions & conventions", "Examples of valid and invalid matchers"], "path": "macro-ambiguity.md", "url": "https://doc.rust-lang.org/reference/macro-ambiguity.html#examples-of-valid-and-invalid-matchers", "has_code": false, "code_tags": []}} {"id": "reference/influences.md#influences-0", "text": "The Rust Reference › Influences\n\nRust 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):\n* SML, OCaml: algebraic data types, pattern matching, type inference, semicolon statement separation\n* C++: references, RAII, smart pointers, move semantics, monomorphization, memory model\n* ML Kit, Cyclone: region based memory management\n* Haskell (GHC): typeclasses, type families\n* Newsqueak, Alef, Limbo: channels, concurrency\n* Erlang: message passing, thread failure, ~~linked thread failure~~, ~~lightweight concurrency~~\n* Swift: optional bindings\n* Scheme: hygienic macros\n* C#: attributes\n* Ruby: closure syntax, ~~block syntax~~\n* NIL, Hermes: ~~typestate~~\n* Unicode Annex #31: identifier and pattern syntax", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Influences", "heading_path": ["Influences"], "path": "influences.md", "url": "https://doc.rust-lang.org/reference/influences.html#influences", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#abstract-syntax-tree-0", "text": "The Rust Reference › Glossary › Abstract syntax tree\n\nAn ‘abstract syntax tree’, or ‘AST’, is an intermediate representation of the structure of the program when the compiler is compiling it.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Abstract syntax tree"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#abstract-syntax-tree", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#alignment-1", "text": "The Rust Reference › Glossary › Alignment\n\nThe 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Alignment"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#alignment", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#application-binary-interface-abi-2", "text": "The Rust Reference › Glossary › Application binary interface (ABI)\n\nAn *application binary interface* (ABI) defines how compiled code interacts with other compiled code. With [`extern` blocks] and [`extern fn`], *ABI strings* affect:\n- **Calling convention**: How function arguments are passed, values are returned (e.g., in registers or on the stack), and who is responsible for cleaning up the stack.\n- **Unwinding**: Whether stack unwinding is allowed. For example, the `\"C-unwind\"` ABI allows unwinding across the FFI boundary, while the `\"C\"` ABI does not.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Application binary interface (ABI)"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#application-binary-interface-abi", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#arity-3", "text": "The Rust Reference › Glossary › Arity\n\nArity 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Arity"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#arity", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#array-4", "text": "The Rust Reference › Glossary › Array\n\nAn 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Array"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#array", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#associated-item-5", "text": "The Rust Reference › Glossary › Associated item\n\nAn associated item is an item that is associated with another item. Associated items are defined in [implementations] and declared in [traits]. Only functions, constants, and type aliases can be associated. Contrast to a [free item].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Associated item"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#associated-item", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#blanket-implementation-6", "text": "The Rust Reference › Glossary › Blanket implementation\n\nAny implementation where a type appears uncovered. `impl Foo for T`, `impl Bar for T`, `impl Bar> for T`, and `impl Bar for Vec` are considered blanket impls. However, `impl Bar> for Vec` is not a blanket impl, as all instances of `T` which appear in this `impl` are covered by `Vec`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Blanket implementation"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#blanket-implementation", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#bound-7", "text": "The Rust Reference › Glossary › Bound\n\nBounds 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Bound"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#bound", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#combinator-8", "text": "The Rust Reference › Glossary › Combinator\n\nCombinators 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Combinator"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#combinator", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#crate-9", "text": "The Rust Reference › Glossary › Crate\n\nA crate is the unit of compilation and linking. There are different [types of crates], 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], starting from an unnamed root module called the crate root. [Items] may be made visible to other crates by marking them as public in the crate root, including through [paths] of public modules. More.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Crate"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#crate", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#dispatch-10", "text": "The Rust Reference › Glossary › Dispatch\n\nDispatch 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. Rust supports dynamic dispatch through the use of trait objects.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Dispatch"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#dispatch", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#dynamically-sized-type-11", "text": "The Rust Reference › Glossary › Dynamically sized type\n\nA dynamically sized type (DST) is a type without a statically known size or alignment.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Dynamically sized type"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#dynamically-sized-type", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#entity-12", "text": "The Rust Reference › Glossary › Entity\n\nAn [*entity*] is a language construct that can be referred to in some way within the source program, usually via a path. Entities include [types], [items], [generic parameters], [variable bindings], [loop labels], [lifetimes], [fields], [attributes], and [lints].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Entity"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#entity", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#expression-13", "text": "The Rust Reference › Glossary › Expression\n\nAn expression is a combination of values, constants, variables, operators and functions that evaluate to a single value, with or without side-effects.\nFor example, `2 + (3 * 4)` is an expression that returns the value 14.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Expression"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#expression", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#free-item-14", "text": "The Rust Reference › Glossary › Free item\n\nAn [item] that is not a member of an [implementation], such as a *free function* or a *free const*. Contrast to an [associated item].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Free item"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#free-item", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#fundamental-traits-15", "text": "The Rust Reference › Glossary › Fundamental traits\n\nA 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Fundamental traits"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#fundamental-traits", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#fundamental-type-constructors-16", "text": "The Rust Reference › Glossary › Fundamental type constructors\n\nA fundamental type constructor is a type where implementing a blanket implementation over it is a breaking change. `&`, `&mut`, `Box`, and `Pin` are fundamental.\nAny time a type `T` is considered local, `&T`, `&mut T`, `Box`, and `Pin` are also considered local. Fundamental type constructors cannot cover other types. Any time the term \"covered type\" is used, the `T` in `&T`, `&mut T`, `Box`, and `Pin` is not considered covered.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Fundamental type constructors"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#fundamental-type-constructors", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#inhabited-17", "text": "The Rust Reference › Glossary › Inhabited\n\nA 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Inhabited"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#inhabited", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#inherent-implementation-18", "text": "The Rust Reference › Glossary › Inherent implementation\n\nAn [implementation] that applies to a nominal type, not to a trait-type pair. More.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Inherent implementation"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#inherent-implementation", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#inherent-method-19", "text": "The Rust Reference › Glossary › Inherent method\n\nA [method] defined in an [inherent implementation], not in a trait implementation.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Inherent method"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#inherent-method", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#initialized-20", "text": "The Rust Reference › Glossary › Initialized\n\nA 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Initialized"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#initialized", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#local-trait-21", "text": "The Rust Reference › Glossary › Local trait\n\nA `trait` which was defined in the current crate. A trait definition is local or not independent of applied type arguments. Given `trait Foo`, `Foo` is always local, regardless of the types substituted for `T` and `U`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Local trait"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#local-trait", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#local-type-22", "text": "The Rust Reference › Glossary › Local type\n\nA `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` is not. `LocalType` is local. Type aliases do not affect locality.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Local type"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#local-type", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#module-23", "text": "The Rust Reference › Glossary › Module\n\nA 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] may be used to refer to items from other modules, which may be restricted by [visibility rules]. More", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Module"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#module", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#name-24", "text": "The Rust Reference › Glossary › Name\n\nA [*name*] is an [identifier] or [lifetime or loop label] that refers to an entity. A *name binding* is when an entity declaration introduces an identifier or label associated with that entity. [Paths], identifiers, and labels are used to refer to an entity.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Name"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#name", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#name-resolution-25", "text": "The Rust Reference › Glossary › Name resolution\n\n[*Name resolution*] is the compile-time process of tying [paths], [identifiers], and [labels] to entity declarations.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Name resolution"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#name-resolution", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#namespace-26", "text": "The Rust Reference › Glossary › Namespace\n\nA *namespace* is a logical grouping of declared names 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.\nWithin a namespace, names are organized in a hierarchy, where each level of the hierarchy has its own collection of named entities.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Namespace"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#namespace", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#nominal-types-27", "text": "The Rust Reference › Glossary › Nominal types\n\nTypes that can be referred to by a path directly. Specifically [enums], [structs], [unions], and [trait object types].", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Nominal types"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#nominal-types", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#dyn-compatible-traits-28", "text": "The Rust Reference › Glossary › Dyn-compatible traits\n\n[Traits] that can be used in [trait object types] (`dyn Trait`). Only traits that follow specific rules are *dyn compatible*.\nThese were formerly known as *object safe* traits.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Dyn-compatible traits"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#dyn-compatible-traits", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#path-29", "text": "The Rust Reference › Glossary › Path\n\nA [*path*] is a sequence of one or more path segments used to refer to an entity in the current scope or other levels of a namespace hierarchy.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Path"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#path", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#prelude-30", "text": "The Rust Reference › Glossary › Prelude\n\nPrelude, 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Prelude"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#prelude", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#scope-31", "text": "The Rust Reference › Glossary › Scope\n\nA [*scope*] is the region of source text where a named entity may be referenced with that name.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Scope"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#scope", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#scrutinee-32", "text": "The Rust Reference › Glossary › Scrutinee\n\nA 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Scrutinee"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#scrutinee", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#size-33", "text": "The Rust Reference › Glossary › Size\n\nThe size of a value has two definitions.\nThe first is that it is how much memory must be allocated to store that value.\nThe second is that it is the offset in bytes between successive elements in an array with that item type.\nIt 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).\nMore.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Size"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#size", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#slice-34", "text": "The Rust Reference › Glossary › Slice\n\nA slice is dynamically-sized view into a contiguous sequence, written as `[T]`.\nIt 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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Slice"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#slice", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#statement-35", "text": "The Rust Reference › Glossary › Statement\n\nA statement is the smallest standalone element of a programming language that commands a computer to perform an action.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Statement"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#statement", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#string-literal-36", "text": "The Rust Reference › Glossary › String literal\n\nA string literal is a string stored directly in the final binary, and so will be valid for the `'static` duration.\nIts type is `'static` duration borrowed string slice, `&'static str`.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "String literal"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#string-literal", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#string-slice-37", "text": "The Rust Reference › Glossary › String slice\n\nA 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`.\nStrings slices are always valid UTF-8.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "String slice"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#string-slice", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#trait-38", "text": "The Rust Reference › Glossary › Trait\n\nA 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.\nGeneric functions and generic structs can use traits to constrain, or bound, the types they accept.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Trait"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#trait", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#turbofish-39", "text": "The Rust Reference › Glossary › Turbofish\n\nPaths 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.\nExamples:\n```rust\nlet ok_num = Ok::<_, ()>(5);\nlet vec = [1, 2, 3].iter().map(|n| n * 2).collect::>();\n```\nThis `::` prefix is required to disambiguate generic paths with multiple comparisons in a comma-separate list. See the bastion of the turbofish for an example where not having the prefix would be ambiguous.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Turbofish"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#turbofish", "has_code": true, "code_tags": ["rust"]}} {"id": "reference/glossary.md#uncovered-type-40", "text": "The Rust Reference › Glossary › Uncovered type\n\nA type which does not appear as an argument to another type. For example, `T` is uncovered, but the `T` in `Vec` is covered. This is only relevant for type arguments.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Uncovered type"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#uncovered-type", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#undefined-behavior-41", "text": "The Rust Reference › Glossary › Undefined behavior\n\nCompile-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.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Undefined behavior"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#undefined-behavior", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#uninhabited-42", "text": "The Rust Reference › Glossary › Uninhabited\n\nA 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] `!`, or an enum with no variants `enum Never { }`. Opposite of Inhabited.", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Uninhabited"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#uninhabited", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#zero-sized-type-zst-43", "text": "The Rust Reference › Glossary › Zero-sized type (ZST)\n\nA type is zero sized (a ZST) if its size is 0. Such types have at most one possible value. Examples include:\n- The [unit type] (see [layout.tuple.unit]).\n- [Function items] (see [type.fn-item.intro]).\n- The constructors of [tuple-like structs] (see [type.fn-item.intro]).\n- The constructors of [tuple-like enum variants] (see [type.fn-item.intro]).\n- `repr(Rust)` [structs] with no fields or where all fields are zero sized (see [layout.repr.rust.struct-zst]).\n- `repr(C)` [structs] with no fields or where all fields are zero-sized (see [layout.repr.c.struct.size-field-offset]).\n- `repr(transparent)` [structs] with no fields or where all fields are zero-sized (see [layout.repr.transparent.layout-abi]).\n- `repr(Rust)` [enums] (without a [primitive representation] specified) with a single [field-struct-like variant], a single [unit-struct-like variant], or a single [tuple-struct-like variant] and where the struct-like thing has no fields or where all of the fields are zero sized (see [layout.repr.rust.enum-struct-like-zst]).\n- [Arrays] of zero-sized types (see [layout.array]).\n- [Arrays] of length zero (see [layout.array]).\n- [Unions] of zero-sized types (see [items.union.common-storage]).", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Zero-sized type (ZST)"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#zero-sized-type-zst", "has_code": false, "code_tags": []}} {"id": "reference/glossary.md#zero-sized-type-zst-44", "text": "The Rust Reference › Glossary › Zero-sized type (ZST)\n\n```rust\nfn f() {}\nstruct S(u8);\nenum E { V(u8) }\nstruct UnitLike;\nstruct NoFields {}\nstruct OnlyZST {\n f1: (),\n f2: [(); 10],\n f3: [u8; 0],\n}\n#[repr(C)]\nstruct C1 {}\n#[repr(C)]\nstruct C2 {\n f1: (),\n f2: [(); 10],\n f3: [u8; 0],\n f4: C1,\n}\n#[repr(transparent)]\nstruct T1 {}\n#[repr(transparent)]\nstruct T2 {\n f1: (),\n f2: [(); 10],\n f3: [u8; 0],\n}\nunion U {\n f1: (),\n f2: [(); 10],\n f3: [u8; 0],\n}\nenum E2 {\n V1 { f1: (), f2: [(); 10] },\n}\nenum E3 {\n V1 {},\n}\nenum E4 {\n V1,\n}\nenum E5 {\n V1 ((), [(); 10]),\n}\nenum E6 {\n V1 (),\n}\n\nassert_eq!(0, size_of::<()>());\nassert_eq!(0, size_of_val(&f));\nassert_eq!(0, size_of_val(&S));\nassert_eq!(0, size_of_val(&E::V));\nassert_eq!(0, size_of::());\nassert_eq!(0, size_of::());\nassert_eq!(0, size_of::());\nassert_eq!(0, size_of::());\nassert_eq!(0, size_of::());\nassert_eq!(0, size_of::());\nassert_eq!(0, size_of::());\nassert_eq!(0, size_of::<[(); 10]>());\nassert_eq!(0, size_of::<[u8; 0]>());\nassert_eq!(0, size_of::());\nassert_eq!(0, size_of::());\nassert_eq!(0, size_of::());\nassert_eq!(0, size_of::());\nassert_eq!(0, size_of::());\nassert_eq!(0, size_of::());\n```", "metadata": {"book": "reference", "book_title": "The Rust Reference", "part": "The Rust Reference", "chapter": "Glossary", "heading_path": ["Glossary", "Zero-sized type (ZST)"], "path": "glossary.md", "url": "https://doc.rust-lang.org/reference/glossary.html#zero-sized-type-zst", "has_code": true, "code_tags": ["rust"]}} {"id": "rust-by-example/index.md#rust-by-example-0", "text": "Rust by Example › Rust by Example\n\nRust is a modern systems programming language focusing on safety, speed,\nand concurrency. It accomplishes these goals by being memory safe without using\ngarbage collection.\nRust by Example (RBE) is a collection of runnable examples that illustrate various Rust\nconcepts and standard libraries. To get even more out of these examples, don't forget\nto install Rust locally and check out the official docs.\nAdditionally for the curious, you can also check out the source code for this site.\nNow let's begin!\n- Hello World - Start with a traditional Hello World program.\n- Primitives - Learn about signed integers, unsigned integers and other primitives.\n- Custom Types - `struct` and `enum`.\n- Variable Bindings - mutable bindings, scope, shadowing.\n- Types - Learn about changing and defining types.\n- Conversion - Convert between different types, such as strings, integers, and floats.\n- Expressions - Learn about Expressions & how to use them.\n- Flow of Control - `if`/`else`, `for`, and others.\n- Functions - Learn about Methods, Closures and Higher Order Functions.\n- Modules - Organize code using modules\n- Crates - A crate is a compilation unit in Rust. Learn to create a library.\n- Cargo - Go through some basic features of the official Rust package management tool.\n- Attributes - An attribute is metadata applied to some module, crate or item.\n- Generics - Learn about writing a function or data type which can work for multiple types of arguments.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Introduction", "heading_path": ["Rust by Example"], "path": "index.md", "url": "https://doc.rust-lang.org/rust-by-example/index.html#rust-by-example", "has_code": false, "code_tags": []}} {"id": "rust-by-example/index.md#rust-by-example-1", "text": "Rust by Example › Rust by Example\n\n- Scoping rules - Scopes play an important part in ownership, borrowing, and lifetimes.\n- Traits - A trait is a collection of methods defined for an unknown type: `Self`\n- Macros - Macros are a way of writing code that writes other code, which is known as metaprogramming.\n- Error handling - Learn Rust way of handling failures.\n- Std library types - Learn about some custom types provided by `std` library.\n- Std misc - More custom types for file handling, threads.\n- Testing - All sorts of testing in Rust.\n- Unsafe Operations - Learn about entering a block of unsafe operations.\n- Compatibility - Handling Rust's evolution and potential compatibility issues.\n- Meta - Documentation, Benchmarking.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Introduction", "heading_path": ["Rust by Example"], "path": "index.md", "url": "https://doc.rust-lang.org/rust-by-example/index.html#rust-by-example", "has_code": false, "code_tags": []}} {"id": "rust-by-example/hello.md#hello-world-0", "text": "Rust by Example › Hello World\n\nThis is the source code of the traditional Hello World program.\n```rust,editable\n// This is a comment, and is ignored by the compiler.\n// You can test this code by clicking the \"Run\" button over there ->\n// or if you prefer to use your keyboard, you can use the \"Ctrl + Enter\"\n// shortcut.\n\n// This code is editable, feel free to hack it!\n// You can always return to the original code by clicking the \"Reset\" button ->\n\n// This is the main function.\nfn main() {\n // Statements here are executed when the compiled binary is called.\n\n // Print text to the console.\n println!(\"Hello World!\");\n}\n```\n`println!` is a *macro* that prints text to the\nconsole.\nA binary can be generated using the Rust compiler: `rustc`.\n```bash\n$ rustc hello.rs\n```\n`rustc` will produce a `hello` binary that can be executed.\n```bash\n$ ./hello\nHello World!\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Hello World", "heading_path": ["Hello World"], "path": "hello.md", "url": "https://doc.rust-lang.org/rust-by-example/hello.html#hello-world", "has_code": true, "code_tags": ["bash", "rust,editable"]}} {"id": "rust-by-example/hello.md#activity-1", "text": "Rust by Example › Hello World › Activity\n\nClick 'Run' above to see the expected output. Next, add a new\nline with a second `println!` macro so that the output shows:\n```text\nHello World!\nI'm a Rustacean!\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Hello World", "heading_path": ["Hello World", "Activity"], "path": "hello.md", "url": "https://doc.rust-lang.org/rust-by-example/hello.html#activity", "has_code": true, "code_tags": ["text"]}} {"id": "rust-by-example/hello/comment.md#comments-0", "text": "Rust by Example › Comments\n\nAny program requires comments, and Rust supports\na few different varieties:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Comments", "heading_path": ["Comments"], "path": "hello/comment.md", "url": "https://doc.rust-lang.org/rust-by-example/hello/comment.html#comments", "has_code": false, "code_tags": []}} {"id": "rust-by-example/hello/comment.md#regular-comments-1", "text": "Rust by Example › Comments › Regular Comments\n\nThese are ignored by the compiler:\n* **Line comments**: Start with `//` and continue to the end of the line\n* **Block comments**: Enclosed in `/* ... */` and can span multiple lines", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Comments", "heading_path": ["Comments", "Regular Comments"], "path": "hello/comment.md", "url": "https://doc.rust-lang.org/rust-by-example/hello/comment.html#regular-comments", "has_code": false, "code_tags": []}} {"id": "rust-by-example/hello/comment.md#documentation-comments-doc-comments-which-are-parsed-into-html-library-documentation-2", "text": "Rust by Example › Comments › Documentation Comments (Doc Comments) which are parsed into HTML library documentation:\n\n- `///` - Generates docs for the item that follows it\n- `//!` - Generates docs for the enclosing item (typically used at the top of a file or module)\n```rust,editable\n\nfn main() {\n // Line comments start with two slashes.\n // Everything after the slashes is ignored by the compiler.\n\n // Example: This line won't execute\n // println!(\"Hello, world!\");\n\n // Try removing the slashes above and running the code again.\n\n /*\n Block comments are useful for temporarily disabling code.\n They can also be nested: /* like this */ which makes it easy\n to comment out large sections quickly.\n */\n\n /*\n * Note: The asterisk column on the left is just for style - \n * it's not required by the language.\n */\n\n // Block comments make it easy to toggle code on/off by adding\n // or removing just one slash:\n\n /* <- Add a '/' here to uncomment the entire block below\n\n println!(\"Now\");\n println!(\"everything\");\n println!(\"executes!\");\n // Line comments inside remain unaffected\n\n // */\n\n // Block comments can also be used within expressions:\n let x = 5 + /* 90 + */ 5;\n println!(\"Is `x` 10 or 100? x = {}\", x);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Comments", "heading_path": ["Comments", "Documentation Comments (Doc Comments) which are parsed into HTML library documentation:"], "path": "hello/comment.md", "url": "https://doc.rust-lang.org/rust-by-example/hello/comment.html#documentation-comments-doc-comments-which-are-parsed-into-html-library-documentation", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/hello/comment.md#see-also-3", "text": "Rust by Example › Comments › Documentation Comments (Doc Comments) which are parsed into HTML library documentation: › See also:\n\nLibrary documentation", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Comments", "heading_path": ["Comments", "Documentation Comments (Doc Comments) which are parsed into HTML library documentation:", "See also:"], "path": "hello/comment.md", "url": "https://doc.rust-lang.org/rust-by-example/hello/comment.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/hello/print.md#formatted-print-0", "text": "Rust by Example › Formatted print\n\nPrinting is handled by a series of `macros` defined in\n`std::fmt` some of which are:\n* `format!`: write formatted text to `String`\n* `print!`: same as `format!` but the text is printed to the console\n (io::stdout).\n* `println!`: same as `print!` but a newline is appended.\n* `eprint!`: same as `print!` but the text is printed to the standard error\n (io::stderr).\n* `eprintln!`: same as `eprint!` but a newline is appended.\nAll parse text in the same fashion. As a plus, Rust checks formatting\ncorrectness at compile time.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Formatted print", "heading_path": ["Formatted print"], "path": "hello/print.md", "url": "https://doc.rust-lang.org/rust-by-example/hello/print.html#formatted-print", "has_code": false, "code_tags": []}} {"id": "rust-by-example/hello/print.md#formatted-print-1", "text": "Rust by Example › Formatted print\n\n```rust,editable,ignore,mdbook-runnable\nfn main() {\n // In general, the `{}` will be automatically replaced with any\n // arguments. These will be stringified.\n println!(\"{} days\", 31);\n\n // Positional arguments can be used. Specifying an integer inside `{}`\n // determines which additional argument will be replaced. Arguments start\n // at 0 immediately after the format string.\n println!(\"{0}, this is {1}. {1}, this is {0}\", \"Alice\", \"Bob\");\n\n // As can named arguments.\n println!(\"{subject} {verb} {object}\",\n object=\"the lazy dog\",\n subject=\"the quick brown fox\",\n verb=\"jumps over\");\n\n // Different formatting can be invoked by specifying the format character\n // after a `:`.\n println!(\"Base 10: {}\", 69420); // 69420\n println!(\"Base 2 (binary): {:b}\", 69420); // 10000111100101100\n println!(\"Base 8 (octal): {:o}\", 69420); // 207454\n println!(\"Base 16 (hexadecimal): {:x}\", 69420); // 10f2c\n\n // You can right-justify text with a specified width. This will\n // output \" 1\". (Four white spaces and a \"1\", for a total width of 5.)\n println!(\"{number:>5}\", number=1);\n\n // You can pad numbers with extra zeroes,\n println!(\"{number:0>5}\", number=1); // 00001\n // and left-adjust by flipping the sign. This will output \"10000\".\n println!(\"{number:0<5}\", number=1); // 10000\n\n // You can use named arguments in the format specifier by appending a `$`.\n println!(\"{number:0>width$}\", number=1, width=5);\n\n // Rust even checks to make sure the correct number of arguments are used.\n println!(\"My name is {0}, {1} {0}\", \"Bond\");\n // FIXME ^ Add the missing argument: \"James\"\n\n // Only types that implement fmt::Display can be formatted with `{}`. User-\n // defined types do not implement fmt::Display by default.\n\n #[allow(dead_code)] // disable `dead_code` which warn against unused module\n struct Structure(i32);\n\n // This will not compile because `Structure` does not implement\n // fmt::Display.\n // println!(\"This struct `{}` won't print...\", Structure(3));\n // TODO ^ Try uncommenting this line\n\n // For Rust 1.58 and above, you can directly capture the argument from a\n // surrounding variable. Just like the above, this will output\n // \" 1\", 4 white spaces and a \"1\".\n let number: f64 = 1.0;\n let width: usize = 5;\n println!(\"{number:>width$}\");\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Formatted print", "heading_path": ["Formatted print"], "path": "hello/print.md", "url": "https://doc.rust-lang.org/rust-by-example/hello/print.html#formatted-print", "has_code": true, "code_tags": ["rust,editable,ignore,mdbook-runnable"]}} {"id": "rust-by-example/hello/print.md#formatted-print-2", "text": "Rust by Example › Formatted print\n\n`std::fmt` contains many `traits` which govern the display\nof text. The base form of two important ones are listed below:\n* `fmt::Debug`: Uses the `{:?}` marker. Format text for debugging purposes.\n* `fmt::Display`: Uses the `{}` marker. Format text in a more elegant, user\n friendly fashion.\nHere, we used `fmt::Display` because the std library provides implementations\nfor these types. To print text for custom types, more steps are required.\nImplementing the `fmt::Display` trait automatically implements the\n[`ToString`] trait which allows us to [convert] the type to `String`.\nIn *line 43*, `#[allow(dead_code)]` is an [attribute] which only applies to the item after it.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Formatted print", "heading_path": ["Formatted print"], "path": "hello/print.md", "url": "https://doc.rust-lang.org/rust-by-example/hello/print.html#formatted-print", "has_code": false, "code_tags": []}} {"id": "rust-by-example/hello/print.md#activities-3", "text": "Rust by Example › Formatted print › Activities\n\n* Fix the issue in the above code (see FIXME) so that it runs without\n error.\n* Try uncommenting the line that attempts to format the `Structure` struct\n (see TODO)\n* Add a `println!` macro call that prints: `Pi is roughly 3.142` by controlling\n the number of decimal places shown. For the purposes of this exercise, use\n `let pi = 3.141592` as an estimate for pi. (Hint: you may need to check the\n `std::fmt` documentation for setting the number of decimals to display)", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Formatted print", "heading_path": ["Formatted print", "Activities"], "path": "hello/print.md", "url": "https://doc.rust-lang.org/rust-by-example/hello/print.html#activities", "has_code": false, "code_tags": []}} {"id": "rust-by-example/hello/print.md#see-also-4", "text": "Rust by Example › Formatted print › See also:\n\n`std::fmt`, `macros`, `struct`, `traits`, and `dead_code`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Formatted print", "heading_path": ["Formatted print", "See also:"], "path": "hello/print.md", "url": "https://doc.rust-lang.org/rust-by-example/hello/print.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/hello/print/print_debug.md#debug-0", "text": "Rust by Example › Debug\n\nAll types which want to use `std::fmt` formatting `traits` require an\nimplementation to be printable. Automatic implementations are only provided\nfor types such as in the `std` library. All others *must* be manually\nimplemented somehow.\nThe `fmt::Debug` `trait` makes this very straightforward. *All* types can\n`derive` (automatically create) the `fmt::Debug` implementation. This is\nnot true for `fmt::Display` which must be manually implemented.\n```rust\n// This structure cannot be printed either with `fmt::Display` or\n// with `fmt::Debug`.\nstruct UnPrintable(i32);\n\n// The `derive` attribute automatically creates the implementation\n// required to make this `struct` printable with `fmt::Debug`.\n#[derive(Debug)]\nstruct DebugPrintable(i32);\n```\nAll `std` library types are automatically printable with `{:?}` too:\n```rust,editable\n// Derive the `fmt::Debug` implementation for `Structure`. `Structure`\n// is a structure which contains a single `i32`.\n#[derive(Debug)]\nstruct Structure(i32);\n\n// Put a `Structure` inside of the structure `Deep`. Make it printable\n// also.\n#[derive(Debug)]\nstruct Deep(Structure);\n\nfn main() {\n // Printing with `{:?}` is similar to with `{}`.\n println!(\"{:?} months in a year.\", 12);\n println!(\"{1:?} {0:?} is the {actor:?} name.\",\n \"Slater\",\n \"Christian\",\n actor=\"actor's\");\n\n // `Structure` is printable!\n println!(\"Now {:?} will print!\", Structure(3));\n\n // The problem with `derive` is there is no control over how\n // the results look. What if I want this to just show a `7`?\n println!(\"Now {:?} will print!\", Deep(Structure(7)));\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Debug", "heading_path": ["Debug"], "path": "hello/print/print_debug.md", "url": "https://doc.rust-lang.org/rust-by-example/hello/print/print_debug.html#debug", "has_code": true, "code_tags": ["rust", "rust,editable"]}} {"id": "rust-by-example/hello/print/print_debug.md#debug-1", "text": "Rust by Example › Debug\n\nSo `fmt::Debug` definitely makes this printable but sacrifices some elegance.\nRust also provides \"pretty printing\" with `{:#?}`.\n```rust,editable\n#[derive(Debug)]\nstruct Person<'a> {\n name: &'a str,\n age: u8\n}\n\nfn main() {\n let name = \"Peter\";\n let age = 27;\n let peter = Person { name, age };\n\n // Pretty print\n println!(\"{:#?}\", peter);\n}\n```\nOne can manually implement `fmt::Display` to control the display.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Debug", "heading_path": ["Debug"], "path": "hello/print/print_debug.md", "url": "https://doc.rust-lang.org/rust-by-example/hello/print/print_debug.html#debug", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/hello/print/print_debug.md#see-also-2", "text": "Rust by Example › Debug › See also:\n\n`attributes`, `derive`, `std::fmt`,\nand `struct`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Debug", "heading_path": ["Debug", "See also:"], "path": "hello/print/print_debug.md", "url": "https://doc.rust-lang.org/rust-by-example/hello/print/print_debug.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/hello/print/print_display.md#display-0", "text": "Rust by Example › Display\n\n`fmt::Debug` hardly looks compact and clean, so it is often advantageous to\ncustomize the output appearance. This is done by manually implementing\n`fmt::Display`, which uses the `{}` print marker. Implementing it\nlooks like this:\n```rust\n// Import (via `use`) the `fmt` module to make it available.\nuse std::fmt;\n\n// Define a structure for which `fmt::Display` will be implemented. This is\n// a tuple struct named `Structure` that contains an `i32`.\nstruct Structure(i32);\n\n// To use the `{}` marker, the trait `fmt::Display` must be implemented\n// manually for the type.\nimpl fmt::Display for Structure {\n // This trait requires `fmt` with this exact signature.\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n // Write strictly the first element into the supplied output\n // stream: `f`. Returns `fmt::Result` which indicates whether the\n // operation succeeded or failed. Note that `write!` uses syntax which\n // is very similar to `println!`.\n write!(f, \"{}\", self.0)\n }\n}\n```\n`fmt::Display` may be cleaner than `fmt::Debug` but this presents\na problem for the `std` library. How should ambiguous types be displayed?\nFor example, if the `std` library implemented a single style for all\n`Vec`, what style should it be? Would it be either of these two?\n* `Vec`: `/:/etc:/home/username:/bin` (split on `:`)\n* `Vec`: `1,2,3` (split on `,`)", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Display", "heading_path": ["Display"], "path": "hello/print/print_display.md", "url": "https://doc.rust-lang.org/rust-by-example/hello/print/print_display.html#display", "has_code": true, "code_tags": ["rust"]}} {"id": "rust-by-example/hello/print/print_display.md#display-1", "text": "Rust by Example › Display\n\nNo, because there is no ideal style for all types and the `std` library\ndoesn't presume to dictate one. `fmt::Display` is not implemented for `Vec`\nor for any other generic containers. `fmt::Debug` must then be used for these\ngeneric cases.\nThis is not a problem though because for any new *container* type which is\n*not* generic, `fmt::Display` can be implemented.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Display", "heading_path": ["Display"], "path": "hello/print/print_display.md", "url": "https://doc.rust-lang.org/rust-by-example/hello/print/print_display.html#display", "has_code": false, "code_tags": []}} {"id": "rust-by-example/hello/print/print_display.md#display-2", "text": "Rust by Example › Display\n\n```rust,editable\nuse std::fmt; // Import `fmt`\n\n// A structure holding two numbers. `Debug` will be derived so the results can\n// be contrasted with `Display`.\n#[derive(Debug)]\nstruct MinMax(i64, i64);\n\n// Implement `Display` for `MinMax`.\nimpl fmt::Display for MinMax {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n // Use `self.number` to refer to each positional data point.\n write!(f, \"({}, {})\", self.0, self.1)\n }\n}\n\n// Define a structure where the fields are nameable for comparison.\n#[derive(Debug)]\nstruct Point2D {\n x: f64,\n y: f64,\n}\n\n// Similarly, implement `Display` for `Point2D`.\nimpl fmt::Display for Point2D {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n // Customize so only `x` and `y` are denoted.\n write!(f, \"x: {}, y: {}\", self.x, self.y)\n }\n}\n\nfn main() {\n let minmax = MinMax(0, 14);\n\n println!(\"Compare structures:\");\n println!(\"Display: {}\", minmax);\n println!(\"Debug: {:?}\", minmax);\n\n let big_range = MinMax(-300, 300);\n let small_range = MinMax(-3, 3);\n\n println!(\"The big range is {big} and the small is {small}\",\n small = small_range,\n big = big_range);\n\n let point = Point2D { x: 3.3, y: 7.2 };\n\n println!(\"Compare points:\");\n println!(\"Display: {}\", point);\n println!(\"Debug: {:?}\", point);\n\n // The following line would not compile: both `Debug` and `Display`\n // were implemented, but `{:b}` requires `fmt::Binary` to be\n // implemented, which it hasn't been for `Point2D`.\n // println!(\"What does Point2D look like in binary: {:b}?\", point);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Display", "heading_path": ["Display"], "path": "hello/print/print_display.md", "url": "https://doc.rust-lang.org/rust-by-example/hello/print/print_display.html#display", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/hello/print/print_display.md#display-3", "text": "Rust by Example › Display\n\nSo, `fmt::Display` has been implemented but `fmt::Binary` has not, and therefore\ncannot be used. `std::fmt` has many such `traits` and each requires\nits own implementation. This is detailed further in `std::fmt`.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Display", "heading_path": ["Display"], "path": "hello/print/print_display.md", "url": "https://doc.rust-lang.org/rust-by-example/hello/print/print_display.html#display", "has_code": false, "code_tags": []}} {"id": "rust-by-example/hello/print/print_display.md#activity-4", "text": "Rust by Example › Display › Activity\n\nAfter checking the output of the above example, use the `Point2D` struct as a\nguide to add a `Complex` struct to the example. When printed in the same\nway, the output should be:\n```txt\nDisplay: 3.3 +7.2i\nDebug: Complex { real: 3.3, imag: 7.2 }\n\nDisplay: 4.7 -2.3i\nDebug: Complex { real: 4.7, imag: -2.3 }\n```\nBonus: Add a space after the `+`/`-` signs.\nHints in case you get stuck:\n- Check the documentation for `Sign/#/0` in `std::fmt`.\n- Bonus: Check `if`-`else` branching and the `abs` function.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Display", "heading_path": ["Display", "Activity"], "path": "hello/print/print_display.md", "url": "https://doc.rust-lang.org/rust-by-example/hello/print/print_display.html#activity", "has_code": true, "code_tags": ["txt"]}} {"id": "rust-by-example/hello/print/print_display.md#see-also-5", "text": "Rust by Example › Display › See also:\n\n`derive`, `std::fmt`, `macros`, `struct`,\n`trait`, and `use`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Display", "heading_path": ["Display", "See also:"], "path": "hello/print/print_display.md", "url": "https://doc.rust-lang.org/rust-by-example/hello/print/print_display.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/hello/print/print_display/testcase_list.md#testcase-list-0", "text": "Rust by Example › Testcase: List\n\nImplementing `fmt::Display` for a structure where the elements must each be\nhandled sequentially is tricky. The problem is that each `write!` generates a\n`fmt::Result`. Proper handling of this requires dealing with *all* the\nresults. Rust provides the `?` operator for exactly this purpose.\nUsing `?` on `write!` looks like this:\n```rust,ignore\n// Try `write!` to see if it errors. If it errors, return\n// the error. Otherwise continue.\nwrite!(f, \"{}\", value)?;\n```\nWith `?` available, implementing `fmt::Display` for a `Vec` is\nstraightforward:\n```rust,editable\nuse std::fmt; // Import the `fmt` module.\n\n// Define a structure named `List` containing a `Vec`.\nstruct List(Vec);\n\nimpl fmt::Display for List {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n // Create a reference to the Vec stored in the List struct.\n let vec = &self.0;\n\n write!(f, \"[\")?;\n\n // Iterate over `v` in `vec` while enumerating the iteration\n // index in `index`.\n for (index, v) in vec.iter().enumerate() {\n // For every element except the first, add a comma.\n // Use the ? operator to return on errors.\n if index != 0 { write!(f, \", \")?; }\n write!(f, \"{}\", v)?;\n }\n\n // Close the opened bracket and return a fmt::Result value.\n write!(f, \"]\")\n }\n}\n\nfn main() {\n let v = List(vec![1, 2, 3]);\n println!(\"{}\", v);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Testcase: List", "heading_path": ["Testcase: List"], "path": "hello/print/print_display/testcase_list.md", "url": "https://doc.rust-lang.org/rust-by-example/hello/print/print_display/testcase_list.html#testcase-list", "has_code": true, "code_tags": ["rust,editable", "rust,ignore"]}} {"id": "rust-by-example/hello/print/print_display/testcase_list.md#activity-1", "text": "Rust by Example › Testcase: List › Activity\n\nTry changing the program so that the index of each element in the vector is also\nprinted. The new output should look like this:\n```rust,ignore\n[0: 1, 1: 2, 2: 3]\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Testcase: List", "heading_path": ["Testcase: List", "Activity"], "path": "hello/print/print_display/testcase_list.md", "url": "https://doc.rust-lang.org/rust-by-example/hello/print/print_display/testcase_list.html#activity", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "rust-by-example/hello/print/print_display/testcase_list.md#see-also-2", "text": "Rust by Example › Testcase: List › See also:\n\n`for`, `ref`, `Result`, `struct`,\n`?`, and `vec!`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Testcase: List", "heading_path": ["Testcase: List", "See also:"], "path": "hello/print/print_display/testcase_list.md", "url": "https://doc.rust-lang.org/rust-by-example/hello/print/print_display/testcase_list.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/hello/print/fmt.md#formatting-0", "text": "Rust by Example › Formatting\n\nWe've seen that formatting is specified via a *format string*:\n* `format!(\"{}\", foo)` -> `\"3735928559\"`\n* `format!(\"0x{:X}\", foo)` -> `\"0xDEADBEEF\"`\n* `format!(\"0o{:o}\", foo)` -> `\"0o33653337357\"`\nThe same variable (`foo`) can be formatted differently depending on which\n*argument type* is used: `X` vs `o` vs *unspecified*.\nThis formatting functionality is implemented via traits, and there is one trait\nfor each argument type. The most common formatting trait is `Display`, which\nhandles cases where the argument type is left unspecified: `{}` for instance.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Formatting", "heading_path": ["Formatting"], "path": "hello/print/fmt.md", "url": "https://doc.rust-lang.org/rust-by-example/hello/print/fmt.html#formatting", "has_code": false, "code_tags": []}} {"id": "rust-by-example/hello/print/fmt.md#formatting-1", "text": "Rust by Example › Formatting\n\n```rust,editable\nuse std::fmt::{self, Formatter, Display};\n\nstruct City {\n name: &'static str,\n // Latitude\n lat: f32,\n // Longitude\n lon: f32,\n}\n\nimpl Display for City {\n // `f` is a buffer, and this method must write the formatted string into it.\n fn fmt(&self, f: &mut Formatter) -> fmt::Result {\n let lat_c = if self.lat >= 0.0 { 'N' } else { 'S' };\n let lon_c = if self.lon >= 0.0 { 'E' } else { 'W' };\n\n // `write!` is like `format!`, but it will write the formatted string\n // into a buffer (the first argument).\n write!(f, \"{}: {:.3}°{} {:.3}°{}\",\n self.name, self.lat.abs(), lat_c, self.lon.abs(), lon_c)\n }\n}\n\n#[derive(Debug)]\nstruct Color {\n red: u8,\n green: u8,\n blue: u8,\n}\n\nfn main() {\n for city in [\n City { name: \"Dublin\", lat: 53.347778, lon: -6.259722 },\n City { name: \"Oslo\", lat: 59.95, lon: 10.75 },\n City { name: \"Vancouver\", lat: 49.25, lon: -123.1 },\n ] {\n println!(\"{}\", city);\n }\n for color in [\n Color { red: 128, green: 255, blue: 90 },\n Color { red: 0, green: 3, blue: 254 },\n Color { red: 0, green: 0, blue: 0 },\n ] {\n // Switch this to use {} once you've added an implementation\n // for fmt::Display.\n println!(\"{:?}\", color);\n }\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Formatting", "heading_path": ["Formatting"], "path": "hello/print/fmt.md", "url": "https://doc.rust-lang.org/rust-by-example/hello/print/fmt.html#formatting", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/hello/print/fmt.md#formatting-2", "text": "Rust by Example › Formatting\n\nYou can view a full list of formatting traits and their argument\ntypes in the `std::fmt` documentation.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Formatting", "heading_path": ["Formatting"], "path": "hello/print/fmt.md", "url": "https://doc.rust-lang.org/rust-by-example/hello/print/fmt.html#formatting", "has_code": false, "code_tags": []}} {"id": "rust-by-example/hello/print/fmt.md#activity-3", "text": "Rust by Example › Formatting › Activity\n\nAdd an implementation of the `fmt::Display` trait for the `Color` struct above\nso that the output displays as:\n```text\nRGB (128, 255, 90) 0x80FF5A\nRGB (0, 3, 254) 0x0003FE\nRGB (0, 0, 0) 0x000000\n```\nTwo hints if you get stuck:\n* You may need to list each color more than once.\n* You can pad with zeros to a width of 2 with `:0>2`.\nFor hexadecimals, you can use `:02X`.\nBonus:\n* If you would like to experiment with type casting in advance,\nthe formula for calculating a color in the RGB color space is\n`RGB = (R * 65_536) + (G * 256) + B`, where `R is RED, G is GREEN, and B is BLUE`.\nAn unsigned 8-bit integer (`u8`) can only hold numbers up to 255. To cast `u8` to `u32`, you can write `variable_name as u32`.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Formatting", "heading_path": ["Formatting", "Activity"], "path": "hello/print/fmt.md", "url": "https://doc.rust-lang.org/rust-by-example/hello/print/fmt.html#activity", "has_code": true, "code_tags": ["text"]}} {"id": "rust-by-example/hello/print/fmt.md#see-also-4", "text": "Rust by Example › Formatting › See also:\n\n`std::fmt`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Formatting", "heading_path": ["Formatting", "See also:"], "path": "hello/print/fmt.md", "url": "https://doc.rust-lang.org/rust-by-example/hello/print/fmt.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/primitives.md#primitives-0", "text": "Rust by Example › Primitives\n\nRust provides access to a wide variety of `primitives`. A sample includes:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Primitives", "heading_path": ["Primitives"], "path": "primitives.md", "url": "https://doc.rust-lang.org/rust-by-example/primitives.html#primitives", "has_code": false, "code_tags": []}} {"id": "rust-by-example/primitives.md#scalar-types-1", "text": "Rust by Example › Primitives › Scalar Types\n\n* Signed integers: `i8`, `i16`, `i32`, `i64`, `i128` and `isize` (pointer size)\n* Unsigned integers: `u8`, `u16`, `u32`, `u64`, `u128` and `usize` (pointer\n size)\n* Floating point: `f32`, `f64`\n* `char` Unicode scalar values like `'a'`, `'α'` and `'∞'` (4 bytes each)\n* `bool` either `true` or `false`\n* The unit type `()`, whose only possible value is an empty tuple: `()`\nDespite the value of a unit type being a tuple, it is not considered a compound\ntype because it does not contain multiple values.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Primitives", "heading_path": ["Primitives", "Scalar Types"], "path": "primitives.md", "url": "https://doc.rust-lang.org/rust-by-example/primitives.html#scalar-types", "has_code": false, "code_tags": []}} {"id": "rust-by-example/primitives.md#compound-types-2", "text": "Rust by Example › Primitives › Compound Types\n\n* Arrays like `[1, 2, 3]`\n* Tuples like `(1, true)`\nVariables can always be *type annotated*. Numbers may additionally be annotated\nvia a *suffix* or *by default*. Integers default to `i32` and floats to `f64`.\nNote that Rust can also infer types from context.\n```rust,editable,ignore,mdbook-runnable\nfn main() {\n // Variables can be type annotated.\n let logical: bool = true;\n\n let a_float: f64 = 1.0; // Regular annotation\n let an_integer = 5i32; // Suffix annotation\n\n // Or a default will be used.\n let default_float = 3.0; // `f64`\n let default_integer = 7; // `i32`\n\n // A type can also be inferred from context.\n let mut inferred_type = 12; // Type i64 is inferred from another line.\n inferred_type = 4294967296i64;\n\n // A mutable variable's value can be changed.\n let mut mutable = 12; // Mutable `i32`\n mutable = 21;\n\n // Error! The type of a variable can't be changed.\n mutable = true;\n\n // Variables can be overwritten with shadowing.\n let mutable = true;\n\n /* Compound types - Array and Tuple */\n\n // Array signature consists of Type T and length as [T; length].\n let my_array: [i32; 5] = [1, 2, 3, 4, 5];\n\n // Tuple is a collection of values of different types\n // and is constructed using parentheses ().\n let my_tuple = (5u32, 1u8, true, -5.04f32);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Primitives", "heading_path": ["Primitives", "Compound Types"], "path": "primitives.md", "url": "https://doc.rust-lang.org/rust-by-example/primitives.html#compound-types", "has_code": true, "code_tags": ["rust,editable,ignore,mdbook-runnable"]}} {"id": "rust-by-example/primitives.md#see-also-3", "text": "Rust by Example › Primitives › See also:\n\nthe `std` library, `mut`, `inference`, and\n`shadowing`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Primitives", "heading_path": ["Primitives", "See also:"], "path": "primitives.md", "url": "https://doc.rust-lang.org/rust-by-example/primitives.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/primitives/literals.md#literals-and-operators-0", "text": "Rust by Example › Literals and operators\n\nIntegers `1`, floats `1.2`, characters `'a'`, strings `\"abc\"`, booleans `true`\nand the unit type `()` can be expressed using literals.\nIntegers can, alternatively, be expressed using hexadecimal, octal or binary\nnotation using these prefixes respectively: `0x`, `0o` or `0b`.\nUnderscores can be inserted in numeric literals to improve readability, e.g.\n`1_000` is the same as `1000`, and `0.000_001` is the same as `0.000001`.\nRust also supports scientific E-notation, e.g. `1e6`, `7.6e-4`. The\nassociated type is `f64`.\nWe need to tell the compiler the type of the literals we use. For now,\nwe'll use the `u32` suffix to indicate that the literal is an unsigned 32-bit\ninteger, and the `i32` suffix to indicate that it's a signed 32-bit integer.\nThe operators available and their precedence in Rust are similar\nto other C-like languages.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Literals and operators", "heading_path": ["Literals and operators"], "path": "primitives/literals.md", "url": "https://doc.rust-lang.org/rust-by-example/primitives/literals.html#literals-and-operators", "has_code": false, "code_tags": []}} {"id": "rust-by-example/primitives/literals.md#literals-and-operators-1", "text": "Rust by Example › Literals and operators\n\n```rust,editable\nfn main() {\n // Integer addition\n println!(\"1 + 2 = {}\", 1u32 + 2);\n\n // Integer subtraction\n println!(\"1 - 2 = {}\", 1i32 - 2);\n // TODO ^ Try changing `1i32` to `1u32` to see why the type is important\n\n // Scientific notation\n println!(\"1e4 is {}, -2.5e-3 is {}\", 1e4, -2.5e-3);\n\n // Short-circuiting boolean logic\n println!(\"true AND false is {}\", true && false);\n println!(\"true OR false is {}\", true || false);\n println!(\"NOT true is {}\", !true);\n\n // Bitwise operations\n println!(\"0011 AND 0101 is {:04b}\", 0b0011u32 & 0b0101);\n println!(\"0011 OR 0101 is {:04b}\", 0b0011u32 | 0b0101);\n println!(\"0011 XOR 0101 is {:04b}\", 0b0011u32 ^ 0b0101);\n println!(\"1 << 5 is {}\", 1u32 << 5);\n println!(\"0x80 >> 2 is 0x{:x}\", 0x80u32 >> 2);\n\n // Use underscores to improve readability!\n println!(\"One million is written as {}\", 1_000_000u32);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Literals and operators", "heading_path": ["Literals and operators"], "path": "primitives/literals.md", "url": "https://doc.rust-lang.org/rust-by-example/primitives/literals.html#literals-and-operators", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/primitives/tuples.md#tuples-0", "text": "Rust by Example › Tuples\n\nA tuple is a collection of values of different types. Tuples are constructed\nusing parentheses `()`, and each tuple itself is a value with type signature\n`(T1, T2, ...)`, where `T1`, `T2` are the types of its members. Functions can\nuse tuples to return multiple values, as tuples can hold any number of values.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Tuples", "heading_path": ["Tuples"], "path": "primitives/tuples.md", "url": "https://doc.rust-lang.org/rust-by-example/primitives/tuples.html#tuples", "has_code": false, "code_tags": []}} {"id": "rust-by-example/primitives/tuples.md#tuples-1", "text": "Rust by Example › Tuples\n\n```rust,editable\n// Tuples can be used as function arguments and as return values.\nfn reverse(pair: (i32, bool)) -> (bool, i32) {\n // `let` can be used to bind the members of a tuple to variables.\n let (int_param, bool_param) = pair;\n\n (bool_param, int_param)\n}\n\n// The following struct is for the activity.\n#[derive(Debug)]\nstruct Matrix(f32, f32, f32, f32);\n\nfn main() {\n // A tuple with a bunch of different types.\n let long_tuple = (1u8, 2u16, 3u32, 4u64,\n -1i8, -2i16, -3i32, -4i64,\n 0.1f32, 0.2f64,\n 'a', true);\n\n // Values can be extracted from the tuple using tuple indexing.\n println!(\"Long tuple first value: {}\", long_tuple.0);\n println!(\"Long tuple second value: {}\", long_tuple.1);\n\n // Tuples can be tuple members.\n let tuple_of_tuples = ((1u8, 2u16, 2u32), (4u64, -1i8), -2i16);\n\n // Tuples are printable.\n println!(\"tuple of tuples: {:?}\", tuple_of_tuples);\n\n // But long Tuples (more than 12 elements) cannot be printed.\n //let too_long_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);\n //println!(\"Too long tuple: {:?}\", too_long_tuple);\n // TODO ^ Uncomment the above 2 lines to see the compiler error\n\n let pair = (1, true);\n println!(\"Pair is {:?}\", pair);\n\n println!(\"The reversed pair is {:?}\", reverse(pair));\n\n // To create one element tuples, the comma is required to tell them apart\n // from a literal surrounded by parentheses.\n println!(\"One element tuple: {:?}\", (5u32,));\n println!(\"Just an integer: {:?}\", (5u32));\n\n // Tuples can be destructured to create bindings.\n let tuple = (1, \"hello\", 4.5, true);\n\n let (a, b, c, d) = tuple;\n println!(\"{:?}, {:?}, {:?}, {:?}\", a, b, c, d);\n\n let matrix = Matrix(1.1, 1.2, 2.1, 2.2);\n println!(\"{:?}\", matrix);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Tuples", "heading_path": ["Tuples"], "path": "primitives/tuples.md", "url": "https://doc.rust-lang.org/rust-by-example/primitives/tuples.html#tuples", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/primitives/tuples.md#activity-2", "text": "Rust by Example › Tuples › Activity\n\n1. *Recap*: Add the `fmt::Display` trait to the `Matrix` struct in the above\n example, so that if you switch from printing the debug format `{:?}` to the\n display format `{}`, you see the following output:\n```text\n ( 1.1 1.2 )\n ( 2.1 2.2 )\n```\n You may want to refer back to the example for print display.\n2. Add a `transpose` function using the `reverse` function as a template, which\n accepts a matrix as an argument, and returns a matrix in which two elements\n have been swapped. For example:\n```rust,ignore\n println!(\"Matrix:\\n{}\", matrix);\n println!(\"Transpose:\\n{}\", transpose(matrix));\n```\n Results in the output:\n```text\n Matrix:\n ( 1.1 1.2 )\n ( 2.1 2.2 )\n Transpose:\n ( 1.1 2.1 )\n ( 1.2 2.2 )\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Tuples", "heading_path": ["Tuples", "Activity"], "path": "primitives/tuples.md", "url": "https://doc.rust-lang.org/rust-by-example/primitives/tuples.html#activity", "has_code": true, "code_tags": ["rust,ignore", "text"]}} {"id": "rust-by-example/primitives/array.md#arrays-and-slices-0", "text": "Rust by Example › Arrays and Slices\n\nAn array is a collection of objects of the same type `T`, stored in contiguous\nmemory. Arrays are created using brackets `[]`, and their length, which is known\nat compile time, is part of their type signature `[T; length]`.\nSlices are similar to arrays, but their length is not known at compile time.\nInstead, a slice is a two-word object; the first word is a pointer to the data,\nthe second word is the length of the slice. The word size is the same as usize,\ndetermined by the processor architecture, e.g. 64 bits on an x86-64. Slices can\nbe used to borrow a section of an array and have the type signature `&[T]`.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Arrays and Slices", "heading_path": ["Arrays and Slices"], "path": "primitives/array.md", "url": "https://doc.rust-lang.org/rust-by-example/primitives/array.html#arrays-and-slices", "has_code": false, "code_tags": []}} {"id": "rust-by-example/primitives/array.md#arrays-and-slices-1", "text": "Rust by Example › Arrays and Slices\n\n```rust,editable,ignore,mdbook-runnable\nuse std::mem;\n\n// This function borrows a slice.\nfn analyze_slice(slice: &[i32]) {\n println!(\"First element of the slice: {}\", slice[0]);\n println!(\"The slice has {} elements\", slice.len());\n}\n\nfn main() {\n // Fixed-size array (type signature is superfluous).\n let xs: [i32; 5] = [1, 2, 3, 4, 5];\n\n // All elements can be initialized to the same value.\n let ys: [i32; 500] = [0; 500];\n\n // Indexing starts at 0.\n println!(\"First element of the array: {}\", xs[0]);\n println!(\"Second element of the array: {}\", xs[1]);\n\n // `len` returns the count of elements in the array.\n println!(\"Number of elements in array: {}\", xs.len());\n\n // Arrays are stack allocated.\n println!(\"Array occupies {} bytes\", mem::size_of_val(&xs));\n\n // Arrays can be automatically borrowed as slices.\n println!(\"Borrow the whole array as a slice.\");\n analyze_slice(&xs);\n\n // Slices can point to a section of an array.\n // They are of the form [starting_index..ending_index].\n // `starting_index` is the first position in the slice.\n // `ending_index` is one more than the last position in the slice.\n println!(\"Borrow a section of the array as a slice.\");\n analyze_slice(&ys[1 .. 4]);\n\n // Example of empty slice `&[]`:\n let empty_array: [u32; 0] = [];\n assert_eq!(&empty_array, &[]);\n assert_eq!(&empty_array, &); // Same but more verbose\n\n // Arrays can be safely accessed using `.get`, which returns an\n // `Option`. This can be matched as shown below, or used with\n // `.expect()` if you would like the program to exit with a nice\n // message instead of happily continue.\n for i in 0..xs.len() + 1 { // Oops, one element too far!\n match xs.get(i) {\n Some(xval) => println!(\"{}: {}\", i, xval),\n None => println!(\"Slow down! {} is too far!\", i),\n }\n }\n\n // Out of bound indexing on array with constant value causes compile time error.\n //println!(\"{}\", xs[5]);\n // Out of bound indexing on slice causes runtime error.\n //println!(\"{}\", xs..);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Arrays and Slices", "heading_path": ["Arrays and Slices"], "path": "primitives/array.md", "url": "https://doc.rust-lang.org/rust-by-example/primitives/array.html#arrays-and-slices", "has_code": true, "code_tags": ["rust,editable,ignore,mdbook-runnable"]}} {"id": "rust-by-example/custom_types.md#custom-types-0", "text": "Rust by Example › Custom Types\n\nRust custom data types are formed mainly through the two keywords:\n* `struct`: define a structure\n* `enum`: define an enumeration\nConstants can also be created via the `const` and `static` keywords.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Custom Types", "heading_path": ["Custom Types"], "path": "custom_types.md", "url": "https://doc.rust-lang.org/rust-by-example/custom_types.html#custom-types", "has_code": false, "code_tags": []}} {"id": "rust-by-example/custom_types/structs.md#structures-0", "text": "Rust by Example › Structures\n\nThere are three types of structures (\"structs\") that can be created using the\n`struct` keyword:\n* Tuple structs, which are, basically, named tuples.\n* The classic C structs\n* Unit structs, which are field-less, are useful for generics.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Structures", "heading_path": ["Structures"], "path": "custom_types/structs.md", "url": "https://doc.rust-lang.org/rust-by-example/custom_types/structs.html#structures", "has_code": false, "code_tags": []}} {"id": "rust-by-example/custom_types/structs.md#structures-1", "text": "Rust by Example › Structures\n\n```rust,editable\n// An attribute to hide warnings for unused code.\n#![allow(dead_code)]\n\n#[derive(Debug)]\nstruct Person {\n name: String,\n age: u8,\n}\n\n// A unit struct\nstruct Unit;\n\n// A tuple struct\nstruct Pair(i32, f32);\n\n// A struct with two fields\nstruct Point {\n x: f32,\n y: f32,\n}\n\n// Structs can be reused as fields of another struct\nstruct Rectangle {\n // A rectangle can be specified by where the top left and bottom right\n // corners are in space.\n top_left: Point,\n bottom_right: Point,\n}\n\nfn main() {\n // Create struct with field init shorthand\n let name = String::from(\"Peter\");\n let age = 27;\n let peter = Person { name, age };\n\n // Print debug struct\n println!(\"{:?}\", peter);\n\n // Instantiate a `Point`\n let point: Point = Point { x: 5.2, y: 0.4 };\n let another_point: Point = Point { x: 10.3, y: 0.2 };\n\n // Access the fields of the point\n println!(\"point coordinates: ({}, {})\", point.x, point.y);\n\n // Make a new point by using struct update syntax to use the fields of our\n // other one\n let bottom_right = Point { x: 10.3, ..another_point };\n\n // `bottom_right.y` will be the same as `another_point.y` because we used that field\n // from `another_point`\n println!(\"second point: ({}, {})\", bottom_right.x, bottom_right.y);\n\n // Destructure the point using a `let` binding\n let Point { x: left_edge, y: top_edge } = point;\n\n let _rectangle = Rectangle {\n // struct instantiation is an expression too\n top_left: Point { x: left_edge, y: top_edge },\n bottom_right: bottom_right,\n };\n\n // Instantiate a unit struct\n let _unit = Unit;\n\n // Instantiate a tuple struct\n let pair = Pair(1, 0.1);\n\n // Access the fields of a tuple struct\n println!(\"pair contains {:?} and {:?}\", pair.0, pair.1);\n\n // Destructure a tuple struct\n let Pair(integer, decimal) = pair;\n\n println!(\"pair contains {:?} and {:?}\", integer, decimal);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Structures", "heading_path": ["Structures"], "path": "custom_types/structs.md", "url": "https://doc.rust-lang.org/rust-by-example/custom_types/structs.html#structures", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/custom_types/structs.md#activity-2", "text": "Rust by Example › Structures › Activity\n\n1. Add a function `rect_area` which calculates the area of a `Rectangle` (try\n using nested destructuring).\n2. Add a function `square` which takes a `Point` and a `f32` as arguments, and\n returns a `Rectangle` with its top left corner on the point, and a width and\n height corresponding to the `f32`.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Structures", "heading_path": ["Structures", "Activity"], "path": "custom_types/structs.md", "url": "https://doc.rust-lang.org/rust-by-example/custom_types/structs.html#activity", "has_code": false, "code_tags": []}} {"id": "rust-by-example/custom_types/structs.md#see-also-3", "text": "Rust by Example › Structures › See also\n\n`attributes`, raw identifiers and destructuring", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Structures", "heading_path": ["Structures", "See also"], "path": "custom_types/structs.md", "url": "https://doc.rust-lang.org/rust-by-example/custom_types/structs.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/custom_types/enum.md#enums-0", "text": "Rust by Example › Enums\n\nThe `enum` keyword allows the creation of a type which may be one of a few\ndifferent variants. Any variant which is valid as a `struct` is also valid in\nan `enum`.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Enums", "heading_path": ["Enums"], "path": "custom_types/enum.md", "url": "https://doc.rust-lang.org/rust-by-example/custom_types/enum.html#enums", "has_code": false, "code_tags": []}} {"id": "rust-by-example/custom_types/enum.md#enums-1", "text": "Rust by Example › Enums\n\n```rust,editable\n// Create an `enum` to classify a web event. Note how both\n// names and type information together specify the variant:\n// `PageLoad != PageUnload` and `KeyPress(char) != Paste(String)`.\n// Each is different and independent.\nenum WebEvent {\n // An `enum` variant may either be `unit-like`,\n PageLoad,\n PageUnload,\n // like tuple structs,\n KeyPress(char),\n Paste(String),\n // or c-like structures.\n Click { x: i64, y: i64 },\n}\n\n// A function which takes a `WebEvent` enum as an argument and\n// returns nothing.\nfn inspect(event: WebEvent) {\n match event {\n WebEvent::PageLoad => println!(\"page loaded\"),\n WebEvent::PageUnload => println!(\"page unloaded\"),\n // Destructure `c` from inside the `enum` variant.\n WebEvent::KeyPress(c) => println!(\"pressed '{}'.\", c),\n WebEvent::Paste(s) => println!(\"pasted \\\"{}\\\".\", s),\n // Destructure `Click` into `x` and `y`.\n WebEvent::Click { x, y } => {\n println!(\"clicked at x={}, y={}.\", x, y);\n },\n }\n}\n\nfn main() {\n let pressed = WebEvent::KeyPress('x');\n // `to_owned()` creates an owned `String` from a string slice.\n let pasted = WebEvent::Paste(\"my text\".to_owned());\n let click = WebEvent::Click { x: 20, y: 80 };\n let load = WebEvent::PageLoad;\n let unload = WebEvent::PageUnload;\n\n inspect(pressed);\n inspect(pasted);\n inspect(click);\n inspect(load);\n inspect(unload);\n}\n\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Enums", "heading_path": ["Enums"], "path": "custom_types/enum.md", "url": "https://doc.rust-lang.org/rust-by-example/custom_types/enum.html#enums", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/custom_types/enum.md#type-aliases-2", "text": "Rust by Example › Enums › Type aliases\n\nIf you use a type alias, you can refer to each enum variant via its alias.\nThis might be useful if the enum's name is too long or too generic, and you\nwant to rename it.\n```rust,editable\nenum VeryVerboseEnumOfThingsToDoWithNumbers {\n Add,\n Subtract,\n}\n\n// Creates a type alias\ntype Operations = VeryVerboseEnumOfThingsToDoWithNumbers;\n\nfn main() {\n // We can refer to each variant via its alias, not its long and inconvenient\n // name.\n let x = Operations::Add;\n}\n```\nThe most common place you'll see this is in `impl` blocks using the `Self` alias.\n```rust,editable\nenum VeryVerboseEnumOfThingsToDoWithNumbers {\n Add,\n Subtract,\n}\n\nimpl VeryVerboseEnumOfThingsToDoWithNumbers {\n fn run(&self, x: i32, y: i32) -> i32 {\n match self {\n Self::Add => x + y,\n Self::Subtract => x - y,\n }\n }\n}\n```\nTo learn more about enums and type aliases, you can read the\nstabilization report from when this feature was stabilized into\nRust.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Enums", "heading_path": ["Enums", "Type aliases"], "path": "custom_types/enum.md", "url": "https://doc.rust-lang.org/rust-by-example/custom_types/enum.html#type-aliases", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/custom_types/enum.md#see-also-3", "text": "Rust by Example › Enums › Type aliases › See also:\n\n`match`, `fn`, and `String`, \"Type alias enum variants\" RFC", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Enums", "heading_path": ["Enums", "Type aliases", "See also:"], "path": "custom_types/enum.md", "url": "https://doc.rust-lang.org/rust-by-example/custom_types/enum.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/custom_types/enum/enum_use.md#use-0", "text": "Rust by Example › use\n\nThe `use` declaration can be used to avoid typing the full module path to access a name:\n```rust,editable\n// An attribute to hide warnings for unused code.\n#![allow(dead_code)]\n\nenum Stage {\n Beginner,\n Advanced,\n}\n\nenum Role {\n Student,\n Teacher,\n}\n\nfn main() {\n // Explicitly `use` each name so they are available without\n // manual scoping.\n use Stage::{Beginner, Advanced};\n // Automatically `use` each name inside `Role`.\n use Role::*;\n\n // Equivalent to `Stage::Beginner`.\n let stage = Beginner;\n // Equivalent to `Role::Student`.\n let role = Student;\n\n match stage {\n // Note the lack of scoping because of the explicit `use` above.\n Beginner => println!(\"Beginners are starting their learning journey!\"),\n Advanced => println!(\"Advanced learners are mastering their subjects...\"),\n }\n\n match role {\n // Note again the lack of scoping.\n Student => println!(\"Students are acquiring knowledge!\"),\n Teacher => println!(\"Teachers are spreading knowledge!\"),\n }\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "use", "heading_path": ["use"], "path": "custom_types/enum/enum_use.md", "url": "https://doc.rust-lang.org/rust-by-example/custom_types/enum/enum_use.html#use", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/custom_types/enum/enum_use.md#see-also-1", "text": "Rust by Example › use › See also:\n\n`match` and `use`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "use", "heading_path": ["use", "See also:"], "path": "custom_types/enum/enum_use.md", "url": "https://doc.rust-lang.org/rust-by-example/custom_types/enum/enum_use.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/custom_types/enum/c_like.md#c-like-0", "text": "Rust by Example › C-like\n\n`enum` can also be used as C-like enums.\n```rust,editable\n// An attribute to hide warnings for unused code.\n#![allow(dead_code)]\n\n// enum with implicit discriminator (starts at 0)\nenum Number {\n Zero,\n One,\n Two,\n}\n\n// enum with explicit discriminator\nenum Color {\n Red = 0xff0000,\n Green = 0x00ff00,\n Blue = 0x0000ff,\n}\n\nfn main() {\n // `enums` can be cast as integers.\n println!(\"zero is {}\", Number::Zero as i32);\n println!(\"one is {}\", Number::One as i32);\n\n println!(\"roses are #{:06x}\", Color::Red as u32);\n println!(\"violets are #{:06x}\", Color::Blue as u32);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "C-like", "heading_path": ["C-like"], "path": "custom_types/enum/c_like.md", "url": "https://doc.rust-lang.org/rust-by-example/custom_types/enum/c_like.html#c-like", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/custom_types/enum/c_like.md#see-also-1", "text": "Rust by Example › C-like › See also:\n\ncasting", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "C-like", "heading_path": ["C-like", "See also:"], "path": "custom_types/enum/c_like.md", "url": "https://doc.rust-lang.org/rust-by-example/custom_types/enum/c_like.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/custom_types/enum/testcase_linked_list.md#testcase-linked-list-0", "text": "Rust by Example › Testcase: linked-list\n\nA common way to implement a linked-list is via `enums`:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Testcase: linked-list", "heading_path": ["Testcase: linked-list"], "path": "custom_types/enum/testcase_linked_list.md", "url": "https://doc.rust-lang.org/rust-by-example/custom_types/enum/testcase_linked_list.html#testcase-linked-list", "has_code": false, "code_tags": []}} {"id": "rust-by-example/custom_types/enum/testcase_linked_list.md#testcase-linked-list-1", "text": "Rust by Example › Testcase: linked-list\n\n```rust,editable\nuse crate::List::*;\n\nenum List {\n // Cons: Tuple struct that wraps an element and a pointer to the next node\n Cons(u32, Box),\n // Nil: A node that signifies the end of the linked list\n Nil,\n}\n\n// Methods can be attached to an enum\nimpl List {\n // Create an empty list\n fn new() -> List {\n // `Nil` has type `List`\n Nil\n }\n\n // Consume a list, and return the same list with a new element at its front\n fn prepend(self, elem: u32) -> List {\n // `Cons` also has type List\n Cons(elem, Box::new(self))\n }\n\n // Return the length of the list\n fn len(&self) -> u32 {\n // `self` has to be matched, because the behavior of this method\n // depends on the variant of `self`\n // `self` has type `&List`, and `*self` has type `List`, matching on a\n // concrete type `T` is preferred over a match on a reference `&T`\n // after Rust 2018 you can use self here and tail (with no ref) below as well,\n // rust will infer &s and ref tail.\n // See https://doc.rust-lang.org/edition-guide/rust-2018/ownership-and-lifetimes/default-match-bindings.html\n match *self {\n // Can't take ownership of the tail, because `self` is borrowed;\n // instead take a reference to the tail\n // And it's a non-tail recursive call which may cause stack overflow for long lists.\n Cons(_, ref tail) => 1 + tail.len(),\n // Base Case: An empty list has zero length\n Nil => 0\n }\n }\n\n // Return representation of the list as a (heap allocated) string\n fn stringify(&self) -> String {\n match *self {\n Cons(head, ref tail) => {\n // `format!` is similar to `print!`, but returns a heap\n // allocated string instead of printing to the console\n format!(\"{}, {}\", head, tail.stringify())\n },\n Nil => {\n format!(\"Nil\")\n },\n }\n }\n}\n\nfn main() {\n // Create an empty linked list\n let mut list = List::new();\n\n // Prepend some elements\n list = list.prepend(1);\n list = list.prepend(2);\n list = list.prepend(3);\n\n // Show the final state of the list\n println!(\"linked list has length: {}\", list.len());\n println!(\"{}\", list.stringify());\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Testcase: linked-list", "heading_path": ["Testcase: linked-list"], "path": "custom_types/enum/testcase_linked_list.md", "url": "https://doc.rust-lang.org/rust-by-example/custom_types/enum/testcase_linked_list.html#testcase-linked-list", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/custom_types/enum/testcase_linked_list.md#see-also-2", "text": "Rust by Example › Testcase: linked-list › See also:\n\n`Box` and methods", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Testcase: linked-list", "heading_path": ["Testcase: linked-list", "See also:"], "path": "custom_types/enum/testcase_linked_list.md", "url": "https://doc.rust-lang.org/rust-by-example/custom_types/enum/testcase_linked_list.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/custom_types/constants.md#constants-0", "text": "Rust by Example › constants\n\nRust has two different types of constants which can be declared in any scope\nincluding global. Both require explicit type annotation:\n* `const`: An unchangeable value (the common case).\n* `static`: A possibly mutable variable with `'static` lifetime.\n The static lifetime is inferred and does not have to be specified.\n Accessing or modifying a mutable static variable is `unsafe`.\n```rust,editable,ignore,mdbook-runnable\n// Globals are declared outside all other scopes.\nstatic LANGUAGE: &str = \"Rust\";\nconst THRESHOLD: i32 = 10;\n\nfn is_big(n: i32) -> bool {\n // Access constant in some function\n n > THRESHOLD\n}\n\nfn main() {\n let n = 16;\n\n // Access constant in the main thread\n println!(\"This is {}\", LANGUAGE);\n println!(\"The threshold is {}\", THRESHOLD);\n println!(\"{} is {}\", n, if is_big(n) { \"big\" } else { \"small\" });\n\n // Error! Cannot modify a `const`.\n THRESHOLD = 5;\n // FIXME ^ Comment out this line\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "constants", "heading_path": ["constants"], "path": "custom_types/constants.md", "url": "https://doc.rust-lang.org/rust-by-example/custom_types/constants.html#constants", "has_code": true, "code_tags": ["rust,editable,ignore,mdbook-runnable"]}} {"id": "rust-by-example/custom_types/constants.md#see-also-1", "text": "Rust by Example › constants › See also:\n\nThe `const`/`static` RFC,\n`'static` lifetime", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "constants", "heading_path": ["constants", "See also:"], "path": "custom_types/constants.md", "url": "https://doc.rust-lang.org/rust-by-example/custom_types/constants.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/variable_bindings.md#variable-bindings-0", "text": "Rust by Example › Variable Bindings\n\nRust provides type safety via static typing. Variable bindings can be type\nannotated when declared. However, in most cases, the compiler will be able\nto infer the type of the variable from the context, heavily reducing the\nannotation burden.\nValues (like literals) can be bound to variables, using the `let` binding.\n```rust,editable\nfn main() {\n let an_integer = 1u32;\n let a_boolean = true;\n let unit = ();\n\n // copy `an_integer` into `copied_integer`\n let copied_integer = an_integer;\n\n println!(\"An integer: {}\", copied_integer);\n println!(\"A boolean: {}\", a_boolean);\n println!(\"Meet the unit value: {:?}\", unit);\n\n // The compiler warns about unused variable bindings; these warnings can\n // be silenced by prefixing the variable name with an underscore\n let _unused_variable = 3u32;\n\n let noisy_unused_variable = 2u32;\n // FIXME ^ Prefix with an underscore to suppress the warning\n // Please note that warnings may not be shown in a browser\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Variable Bindings", "heading_path": ["Variable Bindings"], "path": "variable_bindings.md", "url": "https://doc.rust-lang.org/rust-by-example/variable_bindings.html#variable-bindings", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/variable_bindings/mut.md#mutability-0", "text": "Rust by Example › Mutability\n\nVariable bindings are immutable by default, but this can be overridden using\nthe `mut` modifier.\n```rust,editable,ignore,mdbook-runnable\nfn main() {\n let _immutable_binding = 1;\n let mut mutable_binding = 1;\n\n println!(\"Before mutation: {}\", mutable_binding);\n\n // Ok\n mutable_binding += 1;\n\n println!(\"After mutation: {}\", mutable_binding);\n\n // Error! Cannot assign a new value to an immutable variable\n _immutable_binding += 1;\n}\n```\nThe compiler will throw a detailed diagnostic about mutability errors.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Mutability", "heading_path": ["Mutability"], "path": "variable_bindings/mut.md", "url": "https://doc.rust-lang.org/rust-by-example/variable_bindings/mut.html#mutability", "has_code": true, "code_tags": ["rust,editable,ignore,mdbook-runnable"]}} {"id": "rust-by-example/variable_bindings/scope.md#scope-and-shadowing-0", "text": "Rust by Example › Scope and Shadowing\n\nVariable bindings have a scope, and are constrained to live in a *block*. A\nblock is a collection of statements enclosed by braces `{}`.\n```rust,editable,ignore,mdbook-runnable\nfn main() {\n // This binding lives in the main function\n let long_lived_binding = 1;\n\n // This is a block, and has a smaller scope than the main function\n {\n // This binding only exists in this block\n let short_lived_binding = 2;\n\n println!(\"inner short: {}\", short_lived_binding);\n }\n // End of the block\n\n // Error! `short_lived_binding` doesn't exist in this scope\n println!(\"outer short: {}\", short_lived_binding);\n // FIXME ^ Comment out this line\n\n println!(\"outer long: {}\", long_lived_binding);\n}\n```\nAlso, variable shadowing is allowed.\n```rust,editable,ignore,mdbook-runnable\nfn main() {\n let shadowed_binding = 1;\n\n {\n println!(\"before being shadowed: {}\", shadowed_binding);\n\n // This binding *shadows* the outer one\n let shadowed_binding = \"abc\";\n\n println!(\"shadowed in inner block: {}\", shadowed_binding);\n }\n println!(\"outside inner block: {}\", shadowed_binding);\n\n // This binding *shadows* the previous binding\n let shadowed_binding = 2;\n println!(\"shadowed in outer block: {}\", shadowed_binding);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Scope and Shadowing", "heading_path": ["Scope and Shadowing"], "path": "variable_bindings/scope.md", "url": "https://doc.rust-lang.org/rust-by-example/variable_bindings/scope.html#scope-and-shadowing", "has_code": true, "code_tags": ["rust,editable,ignore,mdbook-runnable"]}} {"id": "rust-by-example/variable_bindings/declare.md#declare-first-0", "text": "Rust by Example › Declare first\n\nIt is possible to declare variable bindings first and initialize them later, but all variable bindings must be initialized before they are used: the compiler forbids use of uninitialized variable bindings, as it would lead to undefined behavior.\nIt is not common to declare a variable binding and initialize it later in the function.\nIt is more difficult for a reader to find the initialization when initialization is separated from declaration.\nIt is common to declare and initialize a variable binding near where the variable will be used.\n```rust,editable,ignore,mdbook-runnable\nfn main() {\n // Declare a variable binding\n let a_binding;\n\n {\n let x = 2;\n\n // Initialize the binding\n a_binding = x * x;\n }\n\n println!(\"a binding: {}\", a_binding);\n\n let another_binding;\n\n // Error! Use of uninitialized binding\n println!(\"another binding: {}\", another_binding);\n // FIXME ^ Comment out this line\n\n another_binding = 1;\n\n println!(\"another binding: {}\", another_binding);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Declare first", "heading_path": ["Declare first"], "path": "variable_bindings/declare.md", "url": "https://doc.rust-lang.org/rust-by-example/variable_bindings/declare.html#declare-first", "has_code": true, "code_tags": ["rust,editable,ignore,mdbook-runnable"]}} {"id": "rust-by-example/variable_bindings/freeze.md#freezing-0", "text": "Rust by Example › Freezing\n\nWhen data is bound by the same name immutably, it also *freezes*. *Frozen* data can't be\nmodified until the immutable binding goes out of scope:\n```rust,editable,ignore,mdbook-runnable\nfn main() {\n let mut _mutable_integer = 7i32;\n\n {\n // Shadowing by immutable `_mutable_integer`\n let _mutable_integer = _mutable_integer;\n\n // Error! `_mutable_integer` is frozen in this scope\n _mutable_integer = 50;\n // FIXME ^ Comment out this line\n\n // `_mutable_integer` goes out of scope\n }\n\n // Ok! `_mutable_integer` is not frozen in this scope\n _mutable_integer = 3;\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Freezing", "heading_path": ["Freezing"], "path": "variable_bindings/freeze.md", "url": "https://doc.rust-lang.org/rust-by-example/variable_bindings/freeze.html#freezing", "has_code": true, "code_tags": ["rust,editable,ignore,mdbook-runnable"]}} {"id": "rust-by-example/types.md#types-0", "text": "Rust by Example › Types\n\nRust provides several mechanisms to change or define the type of primitive and\nuser defined types. The following sections cover:\n* [Casting] between primitive types\n* Specifying the desired type of [literals]\n* Using [type inference]\n* [Aliasing] types", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Types", "heading_path": ["Types"], "path": "types.md", "url": "https://doc.rust-lang.org/rust-by-example/types.html#types", "has_code": false, "code_tags": []}} {"id": "rust-by-example/types/cast.md#casting-0", "text": "Rust by Example › Casting\n\nRust provides no implicit type conversion (coercion) between primitive types.\nBut, explicit type conversion (casting) can be performed using the `as` keyword.\nRules for converting between integral types follow C conventions generally,\nexcept in cases where C has undefined behavior. The behavior of all casts\nbetween integral types is well defined in Rust.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Casting", "heading_path": ["Casting"], "path": "types/cast.md", "url": "https://doc.rust-lang.org/rust-by-example/types/cast.html#casting", "has_code": false, "code_tags": []}} {"id": "rust-by-example/types/cast.md#casting-1", "text": "Rust by Example › Casting\n\n```rust,editable,ignore,mdbook-runnable\n// Suppress all errors from casts which overflow.\n#![allow(overflowing_literals)]\n\nfn main() {\n let decimal = 65.4321_f32;\n\n // Error! No implicit conversion\n let integer: u8 = decimal;\n // FIXME ^ Comment out this line\n\n // Explicit conversion\n let integer = decimal as u8;\n let character = integer as char;\n\n // Error! There are limitations in conversion rules.\n // A float cannot be directly converted to a char.\n let character = decimal as char;\n // FIXME ^ Comment out this line\n\n println!(\"Casting: {} -> {} -> {}\", decimal, integer, character);\n\n // when casting any value to an unsigned type, T,\n // T::MAX + 1 is added or subtracted until the value\n // fits into the new type ONLY when the #![allow(overflowing_literals)]\n // lint is specified like above. Otherwise there will be a compiler error.\n\n // 1000 already fits in a u16\n println!(\"1000 as a u16 is: {}\", 1000 as u16);\n\n // 1000 - 256 - 256 - 256 = 232\n // Under the hood, the first 8 least significant bits (LSB) are kept,\n // while the rest towards the most significant bit (MSB) get truncated.\n println!(\"1000 as a u8 is : {}\", 1000 as u8);\n // -1 + 256 = 255\n println!(\" -1 as a u8 is : {}\", (-1i8) as u8);\n\n // For positive numbers, this is the same as the modulus\n println!(\"1000 mod 256 is : {}\", 1000 % 256);\n\n // When casting to a signed type, the (bitwise) result is the same as\n // first casting to the corresponding unsigned type. If the most significant\n // bit of that value is 1, then the value is negative.\n\n // Unless it already fits, of course.\n println!(\" 128 as a i16 is: {}\", 128 as i16);\n\n // In boundary case 128 value in 8-bit two's complement representation is -128\n println!(\" 128 as a i8 is : {}\", 128 as i8);\n\n // repeating the example above\n // 1000 as u8 -> 232\n println!(\"1000 as a u8 is : {}\", 1000 as u8);\n // and the value of 232 in 8-bit two's complement representation is -24\n println!(\" 232 as a i8 is : {}\", 232 as i8);\n\n // Since Rust 1.45, the `as` keyword performs a *saturating cast*\n // when casting from float to int. If the floating point value exceeds\n // the upper bound or is less than the lower bound, the returned value\n // will be equal to the bound crossed.\n\n // 300.0 as u8 is 255\n println!(\" 300.0 as u8 is : {}\", 300.0_f32 as u8);\n // -100.0 as u8 is 0\n println!(\"-100.0 as u8 is : {}\", -100.0_f32 as u8);\n // nan as u8 is 0\n println!(\" nan as u8 is : {}\", f32::NAN as u8);\n\n // This behavior incurs a small runtime cost and can be avoided\n // with unsafe methods, however the results might overflow and\n // return **unsound values**. Use these methods wisely:\n unsafe {\n // 300.0 as u8 is 44\n println!(\" 300.0 as u8 is : {}\", 300.0_f32.to_int_unchecked::());\n // -100.0 as u8 is 156\n println!(\"-100.0 as u8 is : {}\", (-100.0_f32).to_int_unchecked::());\n // nan as u8 is 0\n println!(\" nan as u8 is : {}\", f32::NAN.to_int_unchecked::());\n }\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Casting", "heading_path": ["Casting"], "path": "types/cast.md", "url": "https://doc.rust-lang.org/rust-by-example/types/cast.html#casting", "has_code": true, "code_tags": ["rust,editable,ignore,mdbook-runnable"]}} {"id": "rust-by-example/types/literals.md#literals-0", "text": "Rust by Example › Literals\n\nNumeric literals can be type annotated by adding the type as a suffix. As an example,\nto specify that the literal `42` should have the type `i32`, write `42i32`.\nThe type of unsuffixed numeric literals will depend on how they are used. If no\nconstraint exists, the compiler will use `i32` for integers, and `f64` for\nfloating-point numbers.\n```rust,editable\nfn main() {\n // Suffixed literals, their types are known at initialization\n let x = 1u8;\n let y = 2u32;\n let z = 3f32;\n\n // Unsuffixed literals, their types depend on how they are used\n let i = 1;\n let f = 1.0;\n\n // `size_of_val` returns the size of a variable in bytes\n println!(\"size of `x` in bytes: {}\", std::mem::size_of_val(&x));\n println!(\"size of `y` in bytes: {}\", std::mem::size_of_val(&y));\n println!(\"size of `z` in bytes: {}\", std::mem::size_of_val(&z));\n println!(\"size of `i` in bytes: {}\", std::mem::size_of_val(&i));\n println!(\"size of `f` in bytes: {}\", std::mem::size_of_val(&f));\n}\n```\nThere are some concepts used in the previous code that haven't been explained\nyet, here's a brief explanation for the impatient readers:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Literals", "heading_path": ["Literals"], "path": "types/literals.md", "url": "https://doc.rust-lang.org/rust-by-example/types/literals.html#literals", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/types/literals.md#literals-1", "text": "Rust by Example › Literals\n\n* `std::mem::size_of_val` is a function, but called with its *full path*. Code\n can be split in logical units called *modules*. In this case, the\n `size_of_val` function is defined in the `mem` module, and the `mem` module\n is defined in the `std` *crate*. For more details, see\n modules and crates.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Literals", "heading_path": ["Literals"], "path": "types/literals.md", "url": "https://doc.rust-lang.org/rust-by-example/types/literals.html#literals", "has_code": false, "code_tags": []}} {"id": "rust-by-example/types/inference.md#inference-0", "text": "Rust by Example › Inference\n\nThe type inference engine is pretty smart. It does more than looking at the\ntype of the value expression\nduring an initialization. It also looks at how the variable is used afterwards\nto infer its type. Here's an advanced example of type inference:\n```rust,editable\nfn main() {\n // Because of the annotation, the compiler knows that `elem` has type u8.\n let elem = 5u8;\n\n // Create an empty vector (a growable array).\n let mut vec = Vec::new();\n // At this point the compiler doesn't know the exact type of `vec`, it\n // just knows that it's a vector of something (`Vec<_>`).\n\n // Insert `elem` in the vector.\n vec.push(elem);\n // Aha! Now the compiler knows that `vec` is a vector of `u8`s (`Vec`)\n // TODO ^ Try commenting out the `vec.push(elem)` line\n\n println!(\"{:?}\", vec);\n}\n```\nNo type annotation of variables was needed, the compiler is happy and so is the\nprogrammer!", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Inference", "heading_path": ["Inference"], "path": "types/inference.md", "url": "https://doc.rust-lang.org/rust-by-example/types/inference.html#inference", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/types/alias.md#aliasing-0", "text": "Rust by Example › Aliasing\n\nThe `type` statement can be used to give a new name to an existing type. Types\nmust have `UpperCamelCase` names, or the compiler will raise a warning. The\nexception to this rule are the primitive types: `usize`, `f32`, etc.\n```rust,editable\n// `NanoSecond`, `Inch`, and `U64` are new names for `u64`.\ntype NanoSecond = u64;\ntype Inch = u64;\ntype U64 = u64;\n\nfn main() {\n // `NanoSecond` = `Inch` = `U64` = `u64`.\n let nanoseconds: NanoSecond = 5 as u64;\n let inches: Inch = 2 as U64;\n\n // Note that type aliases *don't* provide any extra type safety, because\n // aliases are *not* new types\n println!(\"{} nanoseconds + {} inches = {} unit?\",\n nanoseconds,\n inches,\n nanoseconds + inches);\n}\n```\nThe main use of aliases is to reduce boilerplate; for example the `io::Result` type\nis an alias for the `Result` type.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Aliasing", "heading_path": ["Aliasing"], "path": "types/alias.md", "url": "https://doc.rust-lang.org/rust-by-example/types/alias.html#aliasing", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/types/alias.md#see-also-1", "text": "Rust by Example › Aliasing › See also:\n\nAttributes", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Aliasing", "heading_path": ["Aliasing", "See also:"], "path": "types/alias.md", "url": "https://doc.rust-lang.org/rust-by-example/types/alias.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/conversion.md#conversion-0", "text": "Rust by Example › Conversion\n\nPrimitive types can be converted to each other through [casting].\nRust addresses conversion between custom types (i.e., `struct` and `enum`)\nby the use of [traits]. The generic\nconversions will use the [`From`] and [`Into`] traits. However there are more\nspecific ones for the more common cases, in particular when converting to and\nfrom `String`s.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Conversion", "heading_path": ["Conversion"], "path": "conversion.md", "url": "https://doc.rust-lang.org/rust-by-example/conversion.html#conversion", "has_code": false, "code_tags": []}} {"id": "rust-by-example/conversion/from_into.md#from-and-into-0", "text": "Rust by Example › `From` and `Into`\n\nThe [`From`] and [`Into`] traits are inherently linked, and this is actually part of\nits implementation. If you are able to convert type A from type B, then it\nshould be easy to believe that we should be able to convert type B to type A.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`From` and `Into`", "heading_path": ["`From` and `Into`"], "path": "conversion/from_into.md", "url": "https://doc.rust-lang.org/rust-by-example/conversion/from_into.html#from-and-into", "has_code": false, "code_tags": []}} {"id": "rust-by-example/conversion/from_into.md#from-1", "text": "Rust by Example › `From` and `Into` › `From`\n\nThe [`From`] trait allows for a type to define how to create itself from another\ntype, hence providing a very simple mechanism for converting between several\ntypes. There are numerous implementations of this trait within the standard\nlibrary for conversion of primitive and common types.\nFor example we can easily convert a `str` into a `String`\n```rust\nlet my_str = \"hello\";\nlet my_string = String::from(my_str);\n```\nWe can do something similar for defining a conversion for our own type.\n```rust,editable\nuse std::convert::From;\n\n#[derive(Debug)]\nstruct Number {\n value: i32,\n}\n\nimpl From for Number {\n fn from(item: i32) -> Self {\n Number { value: item }\n }\n}\n\nfn main() {\n let num = Number::from(30);\n println!(\"My number is {:?}\", num);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`From` and `Into`", "heading_path": ["`From` and `Into`", "`From`"], "path": "conversion/from_into.md", "url": "https://doc.rust-lang.org/rust-by-example/conversion/from_into.html#from", "has_code": true, "code_tags": ["rust", "rust,editable"]}} {"id": "rust-by-example/conversion/from_into.md#into-2", "text": "Rust by Example › `From` and `Into` › `Into`\n\nThe [`Into`] trait is simply the reciprocal of the `From` trait. It\ndefines how to convert a type into another type.\nCalling `into()` typically requires us to specify the result type as the compiler is unable to determine this most of the time.\n```rust,editable\nuse std::convert::Into;\n\n#[derive(Debug)]\nstruct Number {\n value: i32,\n}\n\nimpl Into for i32 {\n fn into(self) -> Number {\n Number { value: self }\n }\n}\n\nfn main() {\n let int = 5;\n // Try removing the type annotation\n let num: Number = int.into();\n println!(\"My number is {:?}\", num);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`From` and `Into`", "heading_path": ["`From` and `Into`", "`Into`"], "path": "conversion/from_into.md", "url": "https://doc.rust-lang.org/rust-by-example/conversion/from_into.html#into", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/conversion/from_into.md#from-and-into-are-interchangeable-3", "text": "Rust by Example › `From` and `Into` › `From` and `Into` are interchangeable\n\n`From` and `Into` are designed to be complementary.\nWe do not need to provide an implementation for both traits.\nIf you have implemented the `From` trait for your type, `Into` will call it\nwhen necessary. Note, however, that the converse is not true: implementing `Into` for your type will not automatically provide it with an implementation of `From`.\n```rust,editable\nuse std::convert::From;\n\n#[derive(Debug)]\nstruct Number {\n value: i32,\n}\n\n// Define `From`\nimpl From for Number {\n fn from(item: i32) -> Self {\n Number { value: item }\n }\n}\n\nfn main() {\n let int = 5;\n // use `Into`\n let num: Number = int.into();\n println!(\"My number is {:?}\", num);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`From` and `Into`", "heading_path": ["`From` and `Into`", "`From` and `Into` are interchangeable"], "path": "conversion/from_into.md", "url": "https://doc.rust-lang.org/rust-by-example/conversion/from_into.html#from-and-into-are-interchangeable", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/conversion/try_from_try_into.md#tryfrom-and-tryinto-0", "text": "Rust by Example › `TryFrom` and `TryInto`\n\nSimilar to `From` and `Into`, [`TryFrom`] and [`TryInto`] are\ngeneric traits for converting between types. Unlike `From`/`Into`, the\n`TryFrom`/`TryInto` traits are used for fallible conversions, and as such,\nreturn [`Result`]s.\n```rust,editable\nuse std::convert::TryFrom;\nuse std::convert::TryInto;\n\n#[derive(Debug, PartialEq)]\nstruct EvenNumber(i32);\n\nimpl TryFrom for EvenNumber {\n type Error = ();\n\n fn try_from(value: i32) -> Result {\n if value % 2 == 0 {\n Ok(EvenNumber(value))\n } else {\n Err(())\n }\n }\n}\n\nfn main() {\n // TryFrom\n\n assert_eq!(EvenNumber::try_from(8), Ok(EvenNumber(8)));\n assert_eq!(EvenNumber::try_from(5), Err(()));\n\n // TryInto\n\n let result: Result = 8i32.try_into();\n assert_eq!(result, Ok(EvenNumber(8)));\n let result: Result = 5i32.try_into();\n assert_eq!(result, Err(()));\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`TryFrom` and `TryInto`", "heading_path": ["`TryFrom` and `TryInto`"], "path": "conversion/try_from_try_into.md", "url": "https://doc.rust-lang.org/rust-by-example/conversion/try_from_try_into.html#tryfrom-and-tryinto", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/conversion/string.md#converting-to-string-0", "text": "Rust by Example › To and from Strings › Converting to String\n\nTo convert any type to a `String` is as simple as implementing the [`ToString`]\ntrait for the type. Rather than doing so directly, you should implement the\n`fmt::Display` trait which automatically provides [`ToString`] and\nalso allows printing the type as discussed in the section on `print!`.\n```rust,editable\nuse std::fmt;\n\nstruct Circle {\n radius: i32\n}\n\nimpl fmt::Display for Circle {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f, \"Circle of radius {}\", self.radius)\n }\n}\n\nfn main() {\n let circle = Circle { radius: 6 };\n println!(\"{}\", circle.to_string());\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "To and from `String`s", "heading_path": ["To and from Strings", "Converting to String"], "path": "conversion/string.md", "url": "https://doc.rust-lang.org/rust-by-example/conversion/string.html#converting-to-string", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/conversion/string.md#parsing-a-string-1", "text": "Rust by Example › To and from Strings › Parsing a String\n\nIt's useful to convert strings into many types, but one of the more common string\noperations is to convert them from string to number. The idiomatic approach to\nthis is to use the [`parse`] function and either to arrange for type inference or\nto specify the type to parse using the 'turbofish' syntax. Both alternatives are\nshown in the following example.\nThis will convert the string into the type specified as long as the [`FromStr`]\ntrait is implemented for that type. This is implemented for numerous types\nwithin the standard library.\n```rust,editable\nfn main() {\n let parsed: i32 = \"5\".parse().unwrap();\n let turbo_parsed = \"10\".parse::().unwrap();\n\n let sum = parsed + turbo_parsed;\n println!(\"Sum: {:?}\", sum);\n}\n```\nTo obtain this functionality on a user defined type simply implement the\n[`FromStr`] trait for that type.\n```rust,editable\nuse std::num::ParseIntError;\nuse std::str::FromStr;\n\n#[derive(Debug)]\nstruct Circle {\n radius: i32,\n}\n\nimpl FromStr for Circle {\n type Err = ParseIntError;\n fn from_str(s: &str) -> Result {\n match s.trim().parse() {\n Ok(num) => Ok(Circle{ radius: num }),\n Err(e) => Err(e),\n }\n }\n}\n\nfn main() {\n let radius = \" 3 \";\n let circle: Circle = radius.parse().unwrap();\n println!(\"{:?}\", circle);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "To and from `String`s", "heading_path": ["To and from Strings", "Parsing a String"], "path": "conversion/string.md", "url": "https://doc.rust-lang.org/rust-by-example/conversion/string.html#parsing-a-string", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/expression.md#expressions-0", "text": "Rust by Example › Expressions\n\nA Rust program is (mostly) made up of a series of statements:\n```rust,editable\nfn main() {\n // statement\n // statement\n // statement\n}\n```\nThere are a few kinds of statements in Rust. The most common two are declaring\na variable binding, and using a `;` with an expression:\n```rust,editable\nfn main() {\n // variable binding\n let x = 5;\n\n // expression;\n x;\n x + 1;\n 15;\n}\n```\nBlocks are expressions too, so they can be used as values in\nassignments. The last expression in the block will be assigned to the\nplace expression such as a local variable. However, if the last expression of the block ends with a\nsemicolon, the return value will be `()`.\n```rust,editable\nfn main() {\n let x = 5u32;\n\n let y = {\n let x_squared = x * x;\n let x_cubed = x_squared * x;\n\n // This expression will be assigned to `y`\n x_cubed + x_squared + x\n };\n\n let z = {\n // The semicolon suppresses this expression and `()` is assigned to `z`\n 2 * x;\n };\n\n println!(\"x is {:?}\", x);\n println!(\"y is {:?}\", y);\n println!(\"z is {:?}\", z);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Expressions", "heading_path": ["Expressions"], "path": "expression.md", "url": "https://doc.rust-lang.org/rust-by-example/expression.html#expressions", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/flow_control.md#flow-of-control-0", "text": "Rust by Example › Flow of Control\n\nAn integral part of any programming language are ways to modify control flow:\n`if`/`else`, `for`, and others. Let's talk about them in Rust.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Flow of Control", "heading_path": ["Flow of Control"], "path": "flow_control.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control.html#flow-of-control", "has_code": false, "code_tags": []}} {"id": "rust-by-example/flow_control/if_else.md#ifelse-0", "text": "Rust by Example › if/else\n\nBranching with `if`-`else` is similar to other languages. Unlike many of them,\nthe boolean condition doesn't need to be surrounded by parentheses, and each\ncondition is followed by a block. `if`-`else` conditionals are expressions,\nand, all branches must return the same type.\n```rust,editable\nfn main() {\n let n = 5;\n\n if n < 0 {\n print!(\"{} is negative\", n);\n } else if n > 0 {\n print!(\"{} is positive\", n);\n } else {\n print!(\"{} is zero\", n);\n }\n\n let big_n =\n if n < 10 && n > -10 {\n println!(\", and is a small number, increase ten-fold\");\n\n // This expression returns an `i32`.\n 10 * n\n } else {\n println!(\", and is a big number, halve the number\");\n\n // This expression must return an `i32` as well.\n n / 2\n // TODO ^ Try suppressing this expression with a semicolon.\n };\n // ^ Don't forget to put a semicolon here! All `let` bindings need it.\n\n println!(\"{} -> {}\", n, big_n);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "if/else", "heading_path": ["if/else"], "path": "flow_control/if_else.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/if_else.html#ifelse", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/flow_control/loop.md#loop-0", "text": "Rust by Example › loop\n\nRust provides a `loop` keyword to indicate an infinite loop.\nThe `break` statement can be used to exit a loop at anytime, whereas the\n`continue` statement can be used to skip the rest of the iteration and start a\nnew one.\n```rust,editable\nfn main() {\n let mut count = 0u32;\n\n println!(\"Let's count until infinity!\");\n\n // Infinite loop\n loop {\n count += 1;\n\n if count == 3 {\n println!(\"three\");\n\n // Skip the rest of this iteration\n continue;\n }\n\n println!(\"{}\", count);\n\n if count == 5 {\n println!(\"OK, that's enough\");\n\n // Exit this loop\n break;\n }\n }\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "loop", "heading_path": ["loop"], "path": "flow_control/loop.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/loop.html#loop", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/flow_control/loop/nested.md#nesting-and-labels-0", "text": "Rust by Example › Nesting and labels\n\nIt's possible to `break` or `continue` outer loops when dealing with nested\nloops. In these cases, the loops must be annotated with some `'label`, and the\nlabel must be passed to the `break`/`continue` statement.\n```rust,editable\n#![allow(unreachable_code, unused_labels)]\n\nfn main() {\n 'outer: loop {\n println!(\"Entered the outer loop\");\n\n 'inner: loop {\n println!(\"Entered the inner loop\");\n\n // This would break only the inner loop\n //break;\n\n // This breaks the outer loop\n break 'outer;\n }\n\n println!(\"This point will never be reached\");\n }\n\n println!(\"Exited the outer loop\");\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Nesting and labels", "heading_path": ["Nesting and labels"], "path": "flow_control/loop/nested.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/loop/nested.html#nesting-and-labels", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/flow_control/loop/return.md#returning-from-loops-0", "text": "Rust by Example › Returning from loops\n\nOne of the uses of a `loop` is to retry an operation until it succeeds. If the\noperation returns a value though, you might need to pass it to the rest of the\ncode: put it after the `break`, and it will be returned by the `loop`\nexpression.\n```rust,editable\nfn main() {\n let mut counter = 0;\n\n let result = loop {\n counter += 1;\n\n if counter == 10 {\n break counter * 2;\n }\n };\n\n assert_eq!(result, 20);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Returning from loops", "heading_path": ["Returning from loops"], "path": "flow_control/loop/return.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/loop/return.html#returning-from-loops", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/flow_control/while.md#while-0", "text": "Rust by Example › while\n\nThe `while` keyword can be used to run a loop while a condition is true.\nLet's write the infamous FizzBuzz using a `while` loop.\n```rust,editable\nfn main() {\n // A counter variable\n let mut n = 1;\n\n // Loop while `n` is less than 101\n while n < 101 {\n if n % 15 == 0 {\n println!(\"fizzbuzz\");\n } else if n % 3 == 0 {\n println!(\"fizz\");\n } else if n % 5 == 0 {\n println!(\"buzz\");\n } else {\n println!(\"{}\", n);\n }\n\n // Increment counter\n n += 1;\n }\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "while", "heading_path": ["while"], "path": "flow_control/while.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/while.html#while", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/flow_control/for.md#for-and-range-0", "text": "Rust by Example › for loops › for and range\n\nThe `for in` construct can be used to iterate through an `Iterator`.\nOne of the easiest ways to create an iterator is to use the range\nnotation `a..b`. This yields values from `a` (inclusive) to `b`\n(exclusive) in steps of one.\nLet's write FizzBuzz using `for` instead of `while`.\n```rust,editable\nfn main() {\n // `n` will take the values: 1, 2, ..., 100 in each iteration\n for n in 1..101 {\n if n % 15 == 0 {\n println!(\"fizzbuzz\");\n } else if n % 3 == 0 {\n println!(\"fizz\");\n } else if n % 5 == 0 {\n println!(\"buzz\");\n } else {\n println!(\"{}\", n);\n }\n }\n}\n```\nAlternatively, `a..=b` can be used for a range that is inclusive on both ends.\nThe above can be written as:\n```rust,editable\nfn main() {\n // `n` will take the values: 1, 2, ..., 100 in each iteration\n for n in 1..=100 {\n if n % 15 == 0 {\n println!(\"fizzbuzz\");\n } else if n % 3 == 0 {\n println!(\"fizz\");\n } else if n % 5 == 0 {\n println!(\"buzz\");\n } else {\n println!(\"{}\", n);\n }\n }\n}\n```\nJust remember that even though you can compile the code when a>b, the loop gets \nnever executed.\n```rust,editable\nfor i in 10..1{\nprintln!(\"fizzbuzz\");\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "for and range", "heading_path": ["for loops", "for and range"], "path": "flow_control/for.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/for.html#for-and-range", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/flow_control/for.md#for-and-range-1", "text": "Rust by Example › for loops › for and range\n\nIf you want to count down, you need to use .rev() instead\n```rust,editable\nfor i in (1..10).rev(){\nprintln!(\"fizzbuzz\");\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "for and range", "heading_path": ["for loops", "for and range"], "path": "flow_control/for.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/for.html#for-and-range", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/flow_control/for.md#for-and-iterators-2", "text": "Rust by Example › for loops › for and iterators\n\nThe `for in` construct is able to interact with an `Iterator` in several ways.\nAs discussed in the section on the Iterator trait, by default the `for`\nloop will apply the `into_iter` function to the collection. However, this is\nnot the only means of converting collections into iterators.\n`into_iter`, `iter` and `iter_mut` all handle the conversion of a collection\ninto an iterator in different ways, by providing different views on the data\nwithin.\n* `iter` - This borrows each element of the collection through each iteration.\n Thus leaving the collection untouched and available for reuse after the loop.\n```rust,editable\nfn main() {\n let names = vec![\"Bob\", \"Frank\", \"Ferris\"];\n\n for name in names.iter() {\n match name {\n &\"Ferris\" => println!(\"There is a rustacean among us!\"),\n // TODO ^ Try deleting the & and matching just \"Ferris\"\n _ => println!(\"Hello {}\", name),\n }\n }\n\n println!(\"names: {:?}\", names);\n}\n```\n* `into_iter` - This consumes the collection so that on each iteration the exact\n data is provided. Once the collection has been consumed it is no longer\n available for reuse as it has been 'moved' within the loop.\n```rust,editable\nfn main() {\n let names = vec![\"Bob\", \"Frank\", \"Ferris\"];\n\n for name in names.into_iter() {\n match name {\n \"Ferris\" => println!(\"There is a rustacean among us!\"),\n _ => println!(\"Hello {}\", name),\n }\n }\n\n // `names` has been 'moved' and can no longer be used.\n // Try uncommenting the line below to see the compiler error:\n // println!(\"names: {:?}\", names);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "for and range", "heading_path": ["for loops", "for and iterators"], "path": "flow_control/for.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/for.html#for-and-iterators", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/flow_control/for.md#for-and-iterators-3", "text": "Rust by Example › for loops › for and iterators\n\n* `iter_mut` - This mutably borrows each element of the collection, allowing for\n the collection to be modified in place.\n```rust,editable\nfn main() {\n let mut names = vec![\"Bob\", \"Frank\", \"Ferris\"];\n\n for name in names.iter_mut() {\n *name = match name {\n &mut \"Ferris\" => \"There is a rustacean among us!\",\n _ => \"Hello\",\n }\n }\n\n println!(\"names: {:?}\", names);\n}\n```\nIn the above snippets note the type of `match` branch, that is the key\ndifference in the types of iteration. The difference in type then of course\nimplies differing actions that are able to be performed.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "for and range", "heading_path": ["for loops", "for and iterators"], "path": "flow_control/for.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/for.html#for-and-iterators", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/flow_control/for.md#see-also-4", "text": "Rust by Example › for loops › for and iterators › See also:\n\nIterator", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "for and range", "heading_path": ["for loops", "for and iterators", "See also:"], "path": "flow_control/for.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/for.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/flow_control/match.md#match-0", "text": "Rust by Example › match\n\nRust provides pattern matching via the `match` keyword, which can be used like\na C `switch`. The first matching arm is evaluated and all possible values must be\ncovered.\n```rust,editable\nfn main() {\n let number = 13;\n // TODO ^ Try different values for `number`\n\n println!(\"Tell me about {}\", number);\n match number {\n // Match a single value\n 1 => println!(\"One!\"),\n // Match several values\n 2 | 3 | 5 | 7 | 11 => println!(\"This is a prime\"),\n // TODO ^ Try adding 13 to the list of prime values\n // Match an inclusive range\n 13..=19 => println!(\"A teen\"),\n // Handle the rest of cases\n _ => println!(\"Ain't special\"),\n // TODO ^ Try commenting out this catch-all arm\n }\n\n let boolean = true;\n // Match is an expression too\n let binary = match boolean {\n // The arms of a match must cover all the possible values\n false => 0,\n true => 1,\n // TODO ^ Try commenting out one of these arms\n };\n\n println!(\"{} -> {}\", boolean, binary);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "match", "heading_path": ["match"], "path": "flow_control/match.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/match.html#match", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/flow_control/match/destructuring.md#destructuring-0", "text": "Rust by Example › Destructuring\n\nA `match` block can destructure items in a variety of ways.\n* Destructuring Tuples\n* Destructuring Arrays and Slices\n* Destructuring Enums\n* Destructuring Pointers\n* Destructuring Structures", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Destructuring", "heading_path": ["Destructuring"], "path": "flow_control/match/destructuring.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/match/destructuring.html#destructuring", "has_code": false, "code_tags": []}} {"id": "rust-by-example/flow_control/match/destructuring.md#see-also-1", "text": "Rust by Example › Destructuring › See also:\n\nThe Rust Reference for Destructuring", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Destructuring", "heading_path": ["Destructuring", "See also:"], "path": "flow_control/match/destructuring.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/match/destructuring.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/flow_control/match/destructuring/destructure_tuple.md#tuples-0", "text": "Rust by Example › tuples\n\nTuples can be destructured in a `match` as follows:\n```rust,editable\nfn main() {\n let triple = (0, -2, 3);\n // TODO ^ Try different values for `triple`\n\n println!(\"Tell me about {:?}\", triple);\n // Match can be used to destructure a tuple\n match triple {\n // Destructure the second and third elements\n (0, y, z) => println!(\"First is `0`, `y` is {:?}, and `z` is {:?}\", y, z),\n (1, ..) => println!(\"First is `1` and the rest doesn't matter\"),\n (.., 2) => println!(\"last is `2` and the rest doesn't matter\"),\n (3, .., 4) => println!(\"First is `3`, last is `4`, and the rest doesn't matter\"),\n // `..` can be used to ignore the rest of the tuple\n _ => println!(\"It doesn't matter what they are\"),\n // `_` means don't bind the value to a variable\n }\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "tuples", "heading_path": ["tuples"], "path": "flow_control/match/destructuring/destructure_tuple.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/match/destructuring/destructure_tuple.html#tuples", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/flow_control/match/destructuring/destructure_tuple.md#see-also-1", "text": "Rust by Example › tuples › See also:\n\nTuples", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "tuples", "heading_path": ["tuples", "See also:"], "path": "flow_control/match/destructuring/destructure_tuple.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/match/destructuring/destructure_tuple.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/flow_control/match/destructuring/destructure_slice.md#arraysslices-0", "text": "Rust by Example › arrays/slices\n\nLike tuples, arrays and slices can be destructured this way:\n```rust,editable\nfn main() {\n // Try changing the values in the array, or make it a slice!\n let array = [1, -2, 6];\n\n match array {\n // Binds the second and the third elements to the respective variables\n [0, second, third] =>\n println!(\"array[0] = 0, array[1] = {}, array[2] = {}\", second, third),\n\n // Single values can be ignored with _\n [1, _, third] => println!(\n \"array[0] = 1, array[2] = {} and array[1] was ignored\",\n third\n ),\n\n // You can also bind some and ignore the rest\n [-1, second, ..] => println!(\n \"array[0] = -1, array[1] = {} and all the other ones were ignored\",\n second\n ),\n // The code below would not compile\n // [-1, second] => ...\n\n // Or store them in another array/slice (the type depends on\n // that of the value that is being matched against)\n [3, second, tail @ ..] => println!(\n \"array[0] = 3, array[1] = {} and the other elements were {:?}\",\n second, tail\n ),\n\n // Combining these patterns, we can, for example, bind the first and\n // last values, and store the rest of them in a single array\n [first, middle @ .., last] => println!(\n \"array[0] = {}, middle = {:?}, array[2] = {}\",\n first, middle, last\n ),\n }\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "arrays/slices", "heading_path": ["arrays/slices"], "path": "flow_control/match/destructuring/destructure_slice.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/match/destructuring/destructure_slice.html#arraysslices", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/flow_control/match/destructuring/destructure_slice.md#see-also-1", "text": "Rust by Example › arrays/slices › See also:\n\nArrays and Slices and Binding for `@` sigil", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "arrays/slices", "heading_path": ["arrays/slices", "See also:"], "path": "flow_control/match/destructuring/destructure_slice.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/match/destructuring/destructure_slice.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/flow_control/match/destructuring/destructure_enum.md#enums-0", "text": "Rust by Example › enums\n\nAn `enum` is destructured similarly:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "enums", "heading_path": ["enums"], "path": "flow_control/match/destructuring/destructure_enum.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/match/destructuring/destructure_enum.html#enums", "has_code": false, "code_tags": []}} {"id": "rust-by-example/flow_control/match/destructuring/destructure_enum.md#enums-1", "text": "Rust by Example › enums\n\n```rust,editable\n// `allow` required to silence warnings because only\n// one variant is used.\n#[allow(dead_code)]\nenum Color {\n // These 3 are specified solely by their name.\n Red,\n Blue,\n Green,\n // These likewise tie `u32` tuples to different names: color models.\n RGB(u32, u32, u32),\n HSV(u32, u32, u32),\n HSL(u32, u32, u32),\n CMY(u32, u32, u32),\n CMYK(u32, u32, u32, u32),\n}\n\nfn main() {\n let color = Color::RGB(122, 17, 40);\n // TODO ^ Try different variants for `color`\n\n println!(\"What color is it?\");\n // An `enum` can be destructured using a `match`.\n match color {\n Color::Red => println!(\"The color is Red!\"),\n Color::Blue => println!(\"The color is Blue!\"),\n Color::Green => println!(\"The color is Green!\"),\n Color::RGB(r, g, b) =>\n println!(\"Red: {}, green: {}, and blue: {}!\", r, g, b),\n Color::HSV(h, s, v) =>\n println!(\"Hue: {}, saturation: {}, value: {}!\", h, s, v),\n Color::HSL(h, s, l) =>\n println!(\"Hue: {}, saturation: {}, lightness: {}!\", h, s, l),\n Color::CMY(c, m, y) =>\n println!(\"Cyan: {}, magenta: {}, yellow: {}!\", c, m, y),\n Color::CMYK(c, m, y, k) =>\n println!(\"Cyan: {}, magenta: {}, yellow: {}, key (black): {}!\",\n c, m, y, k),\n // Don't need another arm because all variants have been examined\n }\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "enums", "heading_path": ["enums"], "path": "flow_control/match/destructuring/destructure_enum.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/match/destructuring/destructure_enum.html#enums", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/flow_control/match/destructuring/destructure_enum.md#see-also-2", "text": "Rust by Example › enums › See also:\n\n[`#[allow(...)]`][allow], color models and `enum`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "enums", "heading_path": ["enums", "See also:"], "path": "flow_control/match/destructuring/destructure_enum.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/match/destructuring/destructure_enum.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/flow_control/match/destructuring/destructure_pointers.md#pointersref-0", "text": "Rust by Example › pointers/ref\n\nFor pointers, a distinction needs to be made between destructuring\nand dereferencing as they are different concepts which are used\ndifferently from languages like C/C++.\n* Dereferencing uses `*`\n* Destructuring uses `&`, `ref`, and `ref mut`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "pointers/ref", "heading_path": ["pointers/ref"], "path": "flow_control/match/destructuring/destructure_pointers.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/match/destructuring/destructure_pointers.html#pointersref", "has_code": false, "code_tags": []}} {"id": "rust-by-example/flow_control/match/destructuring/destructure_pointers.md#pointersref-1", "text": "Rust by Example › pointers/ref\n\n```rust,editable\nfn main() {\n // Assign a reference of type `i32`. The `&` signifies there\n // is a reference being assigned.\n let reference = &4;\n\n match reference {\n // If `reference` is pattern matched against `&val`, it results\n // in a comparison like:\n // `&i32`\n // `&val`\n // ^ We see that if the matching `&`s are dropped, then the `i32`\n // should be assigned to `val`.\n &val => println!(\"Got a value via destructuring: {:?}\", val),\n }\n\n // To avoid the `&`, you dereference before matching.\n match *reference {\n val => println!(\"Got a value via dereferencing: {:?}\", val),\n }\n\n // What if you don't start with a reference? `reference` was a `&`\n // because the right side was already a reference. This is not\n // a reference because the right side is not one.\n let _not_a_reference = 3;\n\n // Rust provides `ref` for exactly this purpose. It modifies the\n // assignment so that a reference is created for the element; this\n // reference is assigned.\n let ref _is_a_reference = 3;\n\n // Accordingly, by defining 2 values without references, references\n // can be retrieved via `ref` and `ref mut`.\n let value = 5;\n let mut mut_value = 6;\n\n // Use `ref` keyword to create a reference.\n match value {\n ref r => println!(\"Got a reference to a value: {:?}\", r),\n }\n\n // Use `ref mut` similarly.\n match mut_value {\n ref mut m => {\n // Got a reference. Gotta dereference it before we can\n // add anything to it.\n *m += 10;\n println!(\"We added 10. `mut_value`: {:?}\", m);\n },\n }\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "pointers/ref", "heading_path": ["pointers/ref"], "path": "flow_control/match/destructuring/destructure_pointers.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/match/destructuring/destructure_pointers.html#pointersref", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/flow_control/match/destructuring/destructure_pointers.md#see-also-2", "text": "Rust by Example › pointers/ref › See also:\n\nThe ref pattern", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "pointers/ref", "heading_path": ["pointers/ref", "See also:"], "path": "flow_control/match/destructuring/destructure_pointers.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/match/destructuring/destructure_pointers.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/flow_control/match/destructuring/destructure_structures.md#structs-0", "text": "Rust by Example › structs\n\nSimilarly, a `struct` can be destructured as shown:\n```rust,editable\nfn main() {\n struct Foo {\n x: (u32, u32),\n y: u32,\n }\n\n // Try changing the values in the struct to see what happens\n let foo = Foo { x: (1, 2), y: 3 };\n\n match foo {\n Foo { x: (1, b), y } => println!(\"First of x is 1, b = {}, y = {} \", b, y),\n\n // you can destructure structs and rename the variables,\n // the order is not important\n Foo { y: 2, x: i } => println!(\"y is 2, i = {:?}\", i),\n\n // and you can also ignore some variables:\n Foo { y, .. } => println!(\"y = {}, we don't care about x\", y),\n // this will give an error: pattern does not mention field `x`\n //Foo { y } => println!(\"y = {}\", y),\n }\n\n let faa = Foo { x: (1, 2), y: 3 };\n\n // You do not need a match block to destructure structs:\n let Foo { x : x0, y: y0 } = faa;\n println!(\"Outside: x0 = {x0:?}, y0 = {y0}\");\n\n // Destructuring works with nested structs as well:\n struct Bar {\n foo: Foo,\n }\n\n let bar = Bar { foo: faa };\n let Bar { foo: Foo { x: nested_x, y: nested_y } } = bar;\n println!(\"Nested: nested_x = {nested_x:?}, nested_y = {nested_y:?}\");\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "structs", "heading_path": ["structs"], "path": "flow_control/match/destructuring/destructure_structures.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/match/destructuring/destructure_structures.html#structs", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/flow_control/match/destructuring/destructure_structures.md#see-also-1", "text": "Rust by Example › structs › See also:\n\nStructs", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "structs", "heading_path": ["structs", "See also:"], "path": "flow_control/match/destructuring/destructure_structures.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/match/destructuring/destructure_structures.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/flow_control/match/guard.md#guards-0", "text": "Rust by Example › Guards\n\nA `match` *guard* can be added to filter the arm.\n```rust,editable\n#[allow(dead_code)]\nenum Temperature {\n Celsius(i32),\n Fahrenheit(i32),\n}\n\nfn main() {\n let temperature = Temperature::Celsius(35);\n // ^ TODO try different values for `temperature`\n\n match temperature {\n Temperature::Celsius(t) if t > 30 => println!(\"{}C is above 30 Celsius\", t),\n // The `if condition` part ^ is a guard\n Temperature::Celsius(t) => println!(\"{}C is equal to or below 30 Celsius\", t),\n\n Temperature::Fahrenheit(t) if t > 86 => println!(\"{}F is above 86 Fahrenheit\", t),\n Temperature::Fahrenheit(t) => println!(\"{}F is equal to or below 86 Fahrenheit\", t),\n }\n}\n```\nNote that the compiler won't take guard conditions into account when checking\nif all patterns are covered by the match expression.\n```rust,editable,ignore,mdbook-runnable\nfn main() {\n let number: u8 = 4;\n\n match number {\n i if i == 0 => println!(\"Zero\"),\n i if i > 0 => println!(\"Greater than zero\"),\n // _ => unreachable!(\"Should never happen.\"),\n // TODO ^ uncomment to fix compilation\n }\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Guards", "heading_path": ["Guards"], "path": "flow_control/match/guard.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/match/guard.html#guards", "has_code": true, "code_tags": ["rust,editable", "rust,editable,ignore,mdbook-runnable"]}} {"id": "rust-by-example/flow_control/match/guard.md#see-also-1", "text": "Rust by Example › Guards › See also:\n\nTuples\nEnums", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Guards", "heading_path": ["Guards", "See also:"], "path": "flow_control/match/guard.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/match/guard.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/flow_control/match/binding.md#binding-0", "text": "Rust by Example › Binding\n\nIndirectly accessing a variable makes it impossible to branch and use that\nvariable without re-binding. `match` provides the `@` sigil for binding values to\nnames:\n```rust,editable\n// A function `age` which returns a `u32`.\nfn age() -> u32 {\n 15\n}\n\nfn main() {\n println!(\"Tell me what type of person you are\");\n\n match age() {\n 0 => println!(\"I haven't celebrated my first birthday yet\"),\n // Could `match` 1 ..= 12 directly but then what age\n // would the child be?\n // Could `match` n and use an `if` guard, but would\n // not contribute to exhaustiveness checks.\n // (Although in this case that would not matter since\n // a \"catch-all\" pattern is present at the bottom)\n // Instead, bind to `n` for the sequence of 1 ..= 12.\n // Now the age can be reported.\n n @ 1 ..= 12 => println!(\"I'm a child of age {:?}\", n),\n n @ 13 ..= 19 => println!(\"I'm a teen of age {:?}\", n),\n // A similar binding can be done when matching several values.\n n @ (1 | 7 | 15 | 13) => println!(\"I'm a teen of age {:?}\", n),\n // Nothing bound. Return the result.\n n => println!(\"I'm an old person of age {:?}\", n),\n }\n}\n```\nYou can also use binding to \"destructure\" `enum` variants, such as `Option`:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Binding", "heading_path": ["Binding"], "path": "flow_control/match/binding.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/match/binding.html#binding", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/flow_control/match/binding.md#binding-1", "text": "Rust by Example › Binding\n\n```rust,editable\nfn some_number() -> Option {\n Some(42)\n}\n\nfn main() {\n match some_number() {\n // Got `Some` variant, match if its value, bound to `n`,\n // is equal to 42.\n // Could also use `Some(42)` and print `\"The Answer: 42!\"`\n // but that would require changing `42` in 2 spots should\n // you ever wish to change it.\n // Could also use `Some(n) if n == 42` and print `\"The Answer: {n}!\"`\n // but that would not contribute to exhaustiveness checks.\n // (Although in this case that would not matter since\n // the next arm is a \"catch-all\" pattern)\n Some(n @ 42) => println!(\"The Answer: {}!\", n),\n // Match any other number.\n Some(n) => println!(\"Not interesting... {}\", n),\n // Match anything else (`None` variant).\n _ => (),\n }\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Binding", "heading_path": ["Binding"], "path": "flow_control/match/binding.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/match/binding.html#binding", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/flow_control/match/binding.md#see-also-2", "text": "Rust by Example › Binding › See also:\n\n`functions`, `enums` and `Option`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Binding", "heading_path": ["Binding", "See also:"], "path": "flow_control/match/binding.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/match/binding.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/flow_control/if_let.md#if-let-0", "text": "Rust by Example › if let\n\nFor some use cases, when matching enums, `match` is awkward. For example:\n```rust\n// Make `optional` of type `Option`\nlet optional = Some(7);\n\nmatch optional {\n Some(i) => println!(\"This is a really long string and `{:?}`\", i),\n _ => {},\n // ^ Required because `match` is exhaustive. Doesn't it seem\n // like wasted space?\n};\n\n```\n`if let` is cleaner for this use case and in addition allows various\nfailure options to be specified:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "if let", "heading_path": ["if let"], "path": "flow_control/if_let.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/if_let.html#if-let", "has_code": true, "code_tags": ["rust"]}} {"id": "rust-by-example/flow_control/if_let.md#if-let-1", "text": "Rust by Example › if let\n\n```rust,editable\nfn main() {\n // All have type `Option`\n let number = Some(7);\n let letter: Option = None;\n let emoticon: Option = None;\n\n // The `if let` construct reads: \"if `let` destructures `number` into\n // `Some(i)`, evaluate the block (`{}`).\n if let Some(i) = number {\n println!(\"Matched {:?}!\", i);\n }\n\n // If you need to specify a failure, use an else:\n if let Some(i) = letter {\n println!(\"Matched {:?}!\", i);\n } else {\n // Destructure failed. Change to the failure case.\n println!(\"Didn't match a number. Let's go with a letter!\");\n }\n\n // Provide an altered failing condition.\n let i_like_letters = false;\n\n if let Some(i) = emoticon {\n println!(\"Matched {:?}!\", i);\n // Destructure failed. Evaluate an `else if` condition to see if the\n // alternate failure branch should be taken:\n } else if i_like_letters {\n println!(\"Didn't match a number. Let's go with a letter!\");\n } else {\n // The condition evaluated false. This branch is the default:\n println!(\"I don't like letters. Let's go with an emoticon :)!\");\n }\n}\n```\nIn the same way, `if let` can be used to match any enum value:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "if let", "heading_path": ["if let"], "path": "flow_control/if_let.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/if_let.html#if-let", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/flow_control/if_let.md#if-let-2", "text": "Rust by Example › if let\n\n```rust,editable\n// Our example enum\nenum Foo {\n Bar,\n Baz,\n Qux(u32)\n}\n\nfn main() {\n // Create example variables\n let a = Foo::Bar;\n let b = Foo::Baz;\n let c = Foo::Qux(100);\n\n // Variable a matches Foo::Bar\n if let Foo::Bar = a {\n println!(\"a is foobar\");\n }\n\n // Variable b does not match Foo::Bar\n // So this will print nothing\n if let Foo::Bar = b {\n println!(\"b is foobar\");\n }\n\n // Variable c matches Foo::Qux which has a value\n // Similar to Some() in the previous example\n if let Foo::Qux(value) = c {\n println!(\"c is {}\", value);\n }\n\n // Binding also works with `if let`\n if let Foo::Qux(value @ 100) = c {\n println!(\"c is one hundred\");\n }\n}\n```\nAnother benefit is that `if let` allows us to match non-parameterized enum variants. This is true even in cases where the enum doesn't implement or derive `PartialEq`. In such cases `if Foo::Bar == a` would fail to compile, because instances of the enum cannot be equated, however `if let` will continue to work.\nWould you like a challenge? Fix the following example to use `if let`:\n```rust,editable,ignore,mdbook-runnable\n// This enum purposely neither implements nor derives PartialEq.\n// That is why comparing Foo::Bar == a fails below.\nenum Foo {Bar}\n\nfn main() {\n let a = Foo::Bar;\n\n // Variable a matches Foo::Bar\n if Foo::Bar == a {\n // ^-- this causes a compile-time error. Use `if let` instead.\n println!(\"a is foobar\");\n }\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "if let", "heading_path": ["if let"], "path": "flow_control/if_let.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/if_let.html#if-let", "has_code": true, "code_tags": ["rust,editable", "rust,editable,ignore,mdbook-runnable"]}} {"id": "rust-by-example/flow_control/if_let.md#see-also-3", "text": "Rust by Example › if let › See also:\n\n`enum`, `Option`, and the RFC", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "if let", "heading_path": ["if let", "See also:"], "path": "flow_control/if_let.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/if_let.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/flow_control/let_else.md#let-else-0", "text": "Rust by Example › let-else\n\n🛈 stable since: rust 1.65\n🛈 you can target specific edition by compiling like this\n`rustc --edition=2021 main.rs`\nWith `let`-`else`, a refutable pattern can match and bind variables\nin the surrounding scope like a normal `let`, or else diverge (e.g. `break`,\n`return`, `panic!`) when the pattern doesn't match.\n```rust\nuse std::str::FromStr;\n\nfn get_count_item(s: &str) -> (u64, &str) {\n let mut it = s.split(' ');\n let (Some(count_str), Some(item)) = (it.next(), it.next()) else {\n panic!(\"Can't segment count item pair: '{s}'\");\n };\n let Ok(count) = u64::from_str(count_str) else {\n panic!(\"Can't parse integer: '{count_str}'\");\n };\n (count, item)\n}\n\nfn main() {\n assert_eq!(get_count_item(\"3 chairs\"), (3, \"chairs\"));\n}\n```\nThe scope of name bindings is the main thing that makes this different from\n`match` or `if let`-`else` expressions. You could previously approximate these\npatterns with an unfortunate bit of repetition and an outer `let`:\n```rust\n let (count_str, item) = match (it.next(), it.next()) {\n (Some(count_str), Some(item)) => (count_str, item),\n _ => panic!(\"Can't segment count item pair: '{s}'\"),\n };\n let count = if let Ok(count) = u64::from_str(count_str) {\n count\n } else {\n panic!(\"Can't parse integer: '{count_str}'\");\n };\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "let-else", "heading_path": ["let-else"], "path": "flow_control/let_else.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/let_else.html#let-else", "has_code": true, "code_tags": ["rust"]}} {"id": "rust-by-example/flow_control/let_else.md#see-also-1", "text": "Rust by Example › let-else › See also:\n\noption, match, if let and the let-else RFC.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "let-else", "heading_path": ["let-else", "See also:"], "path": "flow_control/let_else.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/let_else.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/flow_control/while_let.md#while-let-0", "text": "Rust by Example › while let\n\nSimilar to `if let`, `while let` can make awkward `match` sequences\nmore tolerable. Consider the following sequence that increments `i`:\n```rust\n// Make `optional` of type `Option`\nlet mut optional = Some(0);\n\n// Repeatedly try this test.\nloop {\n match optional {\n // If `optional` destructures, evaluate the block.\n Some(i) => {\n if i > 9 {\n println!(\"Greater than 9, quit!\");\n optional = None;\n } else {\n println!(\"`i` is `{:?}`. Try again.\", i);\n optional = Some(i + 1);\n }\n // ^ Requires 3 indentations!\n },\n // Quit the loop when the destructure fails:\n _ => { break; }\n // ^ Why should this be required? There must be a better way!\n }\n}\n```\nUsing `while let` makes this sequence much nicer:\n```rust,editable\nfn main() {\n // Make `optional` of type `Option`\n let mut optional = Some(0);\n\n // This reads: \"while `let` destructures `optional` into\n // `Some(i)`, evaluate the block (`{}`). Else `break`.\n while let Some(i) = optional {\n if i > 9 {\n println!(\"Greater than 9, quit!\");\n optional = None;\n } else {\n println!(\"`i` is `{:?}`. Try again.\", i);\n optional = Some(i + 1);\n }\n // ^ Less rightward drift and doesn't require\n // explicitly handling the failing case.\n }\n // ^ `if let` had additional optional `else`/`else if`\n // clauses. `while let` does not have these.\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "while let", "heading_path": ["while let"], "path": "flow_control/while_let.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/while_let.html#while-let", "has_code": true, "code_tags": ["rust", "rust,editable"]}} {"id": "rust-by-example/flow_control/while_let.md#see-also-1", "text": "Rust by Example › while let › See also:\n\n`enum`, `Option`, and the RFC", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "while let", "heading_path": ["while let", "See also:"], "path": "flow_control/while_let.md", "url": "https://doc.rust-lang.org/rust-by-example/flow_control/while_let.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/fn.md#functions-0", "text": "Rust by Example › Functions\n\nFunctions are declared using the `fn` keyword. Its arguments are type\nannotated, just like variables, and, if the function returns a value, the\nreturn type must be specified after an arrow `->`.\nThe final expression in the function will be used as return value.\nAlternatively, the `return` statement can be used to return a value earlier\nfrom within the function, even from inside loops or `if` statements.\nLet's rewrite FizzBuzz using functions!\n```rust,editable\n// Unlike C/C++, there's no restriction on the order of function definitions\nfn main() {\n // We can use this function here, and define it somewhere later\n fizzbuzz_to(100);\n}\n\n// Function that returns a boolean value\nfn is_divisible_by(lhs: u32, rhs: u32) -> bool {\n // Corner case, early return\n if rhs == 0 {\n return false;\n }\n\n // This is an expression, the `return` keyword is not necessary here\n lhs % rhs == 0\n}\n\n// Functions that \"don't\" return a value, actually return the unit type `()`\nfn fizzbuzz(n: u32) -> () {\n if is_divisible_by(n, 15) {\n println!(\"fizzbuzz\");\n } else if is_divisible_by(n, 3) {\n println!(\"fizz\");\n } else if is_divisible_by(n, 5) {\n println!(\"buzz\");\n } else {\n println!(\"{}\", n);\n }\n}\n\n// When a function returns `()`, the return type can be omitted from the\n// signature\nfn fizzbuzz_to(n: u32) {\n for n in 1..=n {\n fizzbuzz(n);\n }\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Functions", "heading_path": ["Functions"], "path": "fn.md", "url": "https://doc.rust-lang.org/rust-by-example/fn.html#functions", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/fn/methods.md#associated-functions--methods-0", "text": "Rust by Example › Associated functions & Methods\n\nSome functions are connected to a particular type. These come in two forms:\nassociated functions, and methods. Associated functions are functions that\nare defined on a type generally, while methods are associated functions that are\ncalled on a particular instance of a type.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Methods", "heading_path": ["Associated functions & Methods"], "path": "fn/methods.md", "url": "https://doc.rust-lang.org/rust-by-example/fn/methods.html#associated-functions--methods", "has_code": false, "code_tags": []}} {"id": "rust-by-example/fn/methods.md#associated-functions--methods-1", "text": "Rust by Example › Associated functions & Methods\n\n```rust,editable\nstruct Point {\n x: f64,\n y: f64,\n}\n\n// Implementation block, all `Point` associated functions & methods go in here\nimpl Point {\n // This is an \"associated function\" because this function is associated with\n // a particular type, that is, Point.\n //\n // Associated functions don't need to be called with an instance.\n // These functions are generally used like constructors.\n fn origin() -> Point {\n Point { x: 0.0, y: 0.0 }\n }\n\n // Another associated function, taking two arguments:\n fn new(x: f64, y: f64) -> Point {\n Point { x: x, y: y }\n }\n}\n\nstruct Rectangle {\n p1: Point,\n p2: Point,\n}\n\nimpl Rectangle {\n // This is a method\n // `&self` is sugar for `self: &Self`, where `Self` is the type of the\n // caller object. In this case `Self` = `Rectangle`\n fn area(&self) -> f64 {\n // `self` gives access to the struct fields via the dot operator\n let Point { x: x1, y: y1 } = self.p1;\n let Point { x: x2, y: y2 } = self.p2;\n\n // `abs` is a `f64` method that returns the absolute value of the\n // caller\n ((x1 - x2) * (y1 - y2)).abs()\n }\n\n fn perimeter(&self) -> f64 {\n let Point { x: x1, y: y1 } = self.p1;\n let Point { x: x2, y: y2 } = self.p2;\n\n 2.0 * ((x1 - x2).abs() + (y1 - y2).abs())\n }\n\n // This method requires the caller object to be mutable\n // `&mut self` desugars to `self: &mut Self`\n fn translate(&mut self, x: f64, y: f64) {\n self.p1.x += x;\n self.p2.x += x;\n\n self.p1.y += y;\n self.p2.y += y;\n }\n}\n\n// `Pair` owns resources: two heap allocated integers\nstruct Pair(Box, Box);\n\nimpl Pair {\n // This method \"consumes\" the resources of the caller object\n // `self` desugars to `self: Self`\n fn destroy(self) {\n // Destructure `self`\n let Pair(first, second) = self;\n\n println!(\"Destroying Pair({}, {})\", first, second);\n\n // `first` and `second` go out of scope and get freed\n }\n}\n\nfn main() {\n let rectangle = Rectangle {\n // Associated functions are called using double colons\n p1: Point::origin(),\n p2: Point::new(3.0, 4.0),\n };\n\n // Methods are called using the dot operator\n // Note that the first argument `&self` is implicitly passed, i.e.\n // `rectangle.perimeter()` === `Rectangle::perimeter(&rectangle)`\n println!(\"Rectangle perimeter: {}\", rectangle.perimeter());\n println!(\"Rectangle area: {}\", rectangle.area());\n\n let mut square = Rectangle {\n p1: Point::origin(),\n p2: Point::new(1.0, 1.0),\n };\n\n // Error! `rectangle` is immutable, but this method requires a mutable\n // object\n //rectangle.translate(1.0, 0.0);\n // TODO ^ Try uncommenting this line\n\n // Okay! Mutable objects can call mutable methods\n square.translate(1.0, 1.0);\n\n let pair = Pair(Box::new(1), Box::new(2));\n\n pair.destroy();\n\n // Error! Previous `destroy` call \"consumed\" `pair`\n //pair.destroy();\n // TODO ^ Try uncommenting this line\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Methods", "heading_path": ["Associated functions & Methods"], "path": "fn/methods.md", "url": "https://doc.rust-lang.org/rust-by-example/fn/methods.html#associated-functions--methods", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/fn/closures.md#closures-0", "text": "Rust by Example › Closures\n\nClosures are functions that can capture the enclosing environment. For\nexample, a closure that captures the `x` variable:\n```Rust\n|val| val + x\n```\nThe syntax and capabilities of closures make them very convenient for\non the fly usage. Calling a closure is exactly like calling a function.\nHowever, both input and return types *can* be inferred and input\nvariable names *must* be specified.\nOther characteristics of closures include:\n* using `||` instead of `()` around input variables.\n* optional body delimitation (`{}`) for a single line expression (mandatory otherwise).\n* the ability to capture the outer environment variables.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Closures", "heading_path": ["Closures"], "path": "fn/closures.md", "url": "https://doc.rust-lang.org/rust-by-example/fn/closures.html#closures", "has_code": true, "code_tags": ["Rust"]}} {"id": "rust-by-example/fn/closures.md#closures-1", "text": "Rust by Example › Closures\n\n```rust,editable\nfn main() {\n let outer_var = 42;\n\n // A regular function can't refer to variables in the enclosing environment\n //fn function(i: i32) -> i32 { i + outer_var }\n // TODO: uncomment the line above and see the compiler error. The compiler\n // suggests that we define a closure instead.\n\n // Closures are anonymous, here we are binding them to references.\n // Annotation is identical to function annotation but is optional\n // as are the `{}` wrapping the body. These nameless functions\n // are assigned to appropriately named variables.\n let closure_annotated = |i: i32| -> i32 { i + outer_var };\n let closure_inferred = |i | i + outer_var ;\n\n // Call the closures.\n println!(\"closure_annotated: {}\", closure_annotated(1));\n println!(\"closure_inferred: {}\", closure_inferred(1));\n // Once closure's type has been inferred, it cannot be inferred again with another type.\n //println!(\"cannot reuse closure_inferred with another type: {}\", closure_inferred(42i64));\n // TODO: uncomment the line above and see the compiler error.\n\n // A closure taking no arguments which returns an `i32`.\n // The return type is inferred.\n let one = || 1;\n println!(\"closure returning one: {}\", one());\n\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Closures", "heading_path": ["Closures"], "path": "fn/closures.md", "url": "https://doc.rust-lang.org/rust-by-example/fn/closures.html#closures", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/fn/closures/capture.md#capturing-0", "text": "Rust by Example › Capturing\n\nClosures are inherently flexible and will do what the functionality requires\nto make the closure work without annotation. This allows capturing to\nflexibly adapt to the use case, sometimes moving and sometimes borrowing.\nClosures can capture variables:\n* by reference: `&T`\n* by mutable reference: `&mut T`\n* by value: `T`\nThey preferentially capture variables by reference and only go lower when\nrequired.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Capturing", "heading_path": ["Capturing"], "path": "fn/closures/capture.md", "url": "https://doc.rust-lang.org/rust-by-example/fn/closures/capture.html#capturing", "has_code": false, "code_tags": []}} {"id": "rust-by-example/fn/closures/capture.md#capturing-1", "text": "Rust by Example › Capturing\n\n```rust,editable\nfn main() {\n use std::mem;\n\n let color = String::from(\"green\");\n\n // A closure to print `color` which immediately borrows (`&`) `color` and\n // stores the borrow and closure in the `print` variable. It will remain\n // borrowed until `print` is used the last time.\n //\n // `println!` only requires arguments by immutable reference so it doesn't\n // impose anything more restrictive.\n let print = || println!(\"`color`: {}\", color);\n\n // Call the closure using the borrow.\n print();\n\n // `color` can be borrowed immutably again, because the closure only holds\n // an immutable reference to `color`.\n let _reborrow = &color;\n print();\n\n // A move or reborrow is allowed after the final use of `print`\n let _color_moved = color;\n\n\n let mut count = 0;\n // A closure to increment `count` could take either `&mut count` or `count`\n // but `&mut count` is less restrictive so it takes that. Immediately\n // borrows `count`.\n //\n // A `mut` is required on `inc` because a `&mut` is stored inside. Thus,\n // calling the closure mutates `count` which requires a `mut`.\n let mut inc = || {\n count += 1;\n println!(\"`count`: {}\", count);\n };\n\n // Call the closure using a mutable borrow.\n inc();\n\n // The closure still mutably borrows `count` because it is called later.\n // An attempt to reborrow will lead to an error.\n // let _reborrow = &count;\n // ^ TODO: try uncommenting this line.\n inc();\n\n // The closure no longer needs to borrow `&mut count`. Therefore, it is\n // possible to reborrow without an error\n let _count_reborrowed = &mut count;\n\n\n // A non-copy type.\n let movable = Box::new(3);\n\n // `mem::drop` requires `T` so this must take by value. A copy type\n // would copy into the closure leaving the original untouched.\n // A non-copy must move and so `movable` immediately moves into\n // the closure.\n let consume = || {\n println!(\"`movable`: {:?}\", movable);\n mem::drop(movable);\n };\n\n // `consume` consumes the variable so this can only be called once.\n consume();\n // consume();\n // ^ TODO: Try uncommenting this line.\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Capturing", "heading_path": ["Capturing"], "path": "fn/closures/capture.md", "url": "https://doc.rust-lang.org/rust-by-example/fn/closures/capture.html#capturing", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/fn/closures/capture.md#capturing-2", "text": "Rust by Example › Capturing\n\nUsing `move` before vertical pipes forces closure\nto take ownership of captured variables:\n```rust,editable\nfn main() {\n // `Vec` has non-copy semantics.\n let haystack = vec![1, 2, 3];\n\n let contains = move |needle| haystack.contains(needle);\n\n println!(\"{}\", contains(&1));\n println!(\"{}\", contains(&4));\n\n // println!(\"There're {} elements in vec\", haystack.len());\n // ^ Uncommenting above line will result in compile-time error\n // because borrow checker doesn't allow re-using variable after it\n // has been moved.\n\n // Removing `move` from closure's signature will cause closure\n // to borrow _haystack_ variable immutably, hence _haystack_ is still\n // available and uncommenting above line will not cause an error.\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Capturing", "heading_path": ["Capturing"], "path": "fn/closures/capture.md", "url": "https://doc.rust-lang.org/rust-by-example/fn/closures/capture.html#capturing", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/fn/closures/capture.md#see-also-3", "text": "Rust by Example › Capturing › See also:\n\n`Box` and `std::mem::drop`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Capturing", "heading_path": ["Capturing", "See also:"], "path": "fn/closures/capture.md", "url": "https://doc.rust-lang.org/rust-by-example/fn/closures/capture.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/fn/closures/input_parameters.md#as-input-parameters-0", "text": "Rust by Example › As input parameters\n\nWhile Rust chooses how to capture variables on the fly mostly without type\nannotation, this ambiguity is not allowed when writing functions. When\ntaking a closure as an input parameter, the closure's complete type must be\nannotated using one of a few `traits`, and they're determined by what the\nclosure does with captured value. In order of decreasing restriction,\nthey are:\n* `Fn`: the closure uses the captured value by reference (`&T`)\n* `FnMut`: the closure uses the captured value by mutable reference (`&mut T`)\n* `FnOnce`: the closure uses the captured value by value (`T`)\nOn a variable-by-variable basis, the compiler will capture variables in the\nleast restrictive manner possible.\nFor instance, consider a parameter annotated as `FnOnce`. This specifies\nthat the closure *may* capture by `&T`, `&mut T`, or `T`, but the compiler\nwill ultimately choose based on how the captured variables are used in the\nclosure.\nThis is because if a move is possible, then any type of borrow should also\nbe possible. Note that the reverse is not true. If the parameter is\nannotated as `Fn`, then capturing variables by `&mut T` or `T` are not\nallowed. However, `&T` is allowed.\nIn the following example, try swapping the usage of `Fn`, `FnMut`, and\n`FnOnce` to see what happens:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "As input parameters", "heading_path": ["As input parameters"], "path": "fn/closures/input_parameters.md", "url": "https://doc.rust-lang.org/rust-by-example/fn/closures/input_parameters.html#as-input-parameters", "has_code": false, "code_tags": []}} {"id": "rust-by-example/fn/closures/input_parameters.md#as-input-parameters-1", "text": "Rust by Example › As input parameters\n\n```rust,editable\n// A function which takes a closure as an argument and calls it.\n// denotes that F is a \"Generic type parameter\"\nfn apply(f: F) where\n // The closure takes no input and returns nothing.\n F: FnOnce() {\n // ^ TODO: Try changing this to `Fn` or `FnMut`.\n\n f();\n}\n\n// A function which takes a closure and returns an `i32`.\nfn apply_to_3(f: F) -> i32 where\n // The closure takes an `i32` and returns an `i32`.\n F: Fn(i32) -> i32 {\n\n f(3)\n}\n\nfn main() {\n use std::mem;\n\n let greeting = \"hello\";\n // A non-copy type.\n // `to_owned` creates owned data from borrowed one\n let mut farewell = \"goodbye\".to_owned();\n\n // Capture 2 variables: `greeting` by reference and\n // `farewell` by value.\n let diary = || {\n // `greeting` is by reference: requires `Fn`.\n println!(\"I said {}.\", greeting);\n\n // Mutation forces `farewell` to be captured by\n // mutable reference. Now requires `FnMut`.\n farewell.push_str(\"!!!\");\n println!(\"Then I screamed {}.\", farewell);\n println!(\"Now I can sleep. zzzzz\");\n\n // Manually calling drop forces `farewell` to\n // be captured by value. Now requires `FnOnce`.\n mem::drop(farewell);\n };\n\n // Call the function which applies the closure.\n apply(diary);\n\n // `double` satisfies `apply_to_3`'s trait bound\n let double = |x| 2 * x;\n\n println!(\"3 doubled: {}\", apply_to_3(double));\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "As input parameters", "heading_path": ["As input parameters"], "path": "fn/closures/input_parameters.md", "url": "https://doc.rust-lang.org/rust-by-example/fn/closures/input_parameters.html#as-input-parameters", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/fn/closures/input_parameters.md#see-also-2", "text": "Rust by Example › As input parameters › See also:\n\n`std::mem::drop`, `Fn`, `FnMut`, Generics, where and `FnOnce`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "As input parameters", "heading_path": ["As input parameters", "See also:"], "path": "fn/closures/input_parameters.md", "url": "https://doc.rust-lang.org/rust-by-example/fn/closures/input_parameters.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/fn/closures/anonymity.md#type-anonymity-0", "text": "Rust by Example › Type anonymity\n\nClosures succinctly capture variables from enclosing scopes. Does this have\nany consequences? It surely does. Observe how using a closure as a function\nparameter requires [generics], which is necessary because of how they are\ndefined:\n```rust\n// `F` must be generic.\nfn apply(f: F) where\n F: FnOnce() {\n f();\n}\n```\nWhen a closure is defined, the compiler implicitly creates a new\nanonymous structure to store the captured variables inside, meanwhile\nimplementing the functionality via one of the `traits`: `Fn`, `FnMut`, or\n`FnOnce` for this unknown type. This type is assigned to the variable which\nis stored until calling.\nSince this new type is of unknown type, any usage in a function will require\ngenerics. However, an unbounded type parameter `` would still be ambiguous\nand not be allowed. Thus, bounding by one of the `traits`: `Fn`, `FnMut`, or\n`FnOnce` (which it implements) is sufficient to specify its type.\n```rust,editable\n// `F` must implement `Fn` for a closure which takes no\n// inputs and returns nothing - exactly what is required\n// for `print`.\nfn apply(f: F) where\n F: Fn() {\n f();\n}\n\nfn main() {\n let x = 7;\n\n // Capture `x` into an anonymous type and implement\n // `Fn` for it. Store it in `print`.\n let print = || println!(\"{}\", x);\n\n apply(print);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Type anonymity", "heading_path": ["Type anonymity"], "path": "fn/closures/anonymity.md", "url": "https://doc.rust-lang.org/rust-by-example/fn/closures/anonymity.html#type-anonymity", "has_code": true, "code_tags": ["rust", "rust,editable"]}} {"id": "rust-by-example/fn/closures/anonymity.md#see-also-1", "text": "Rust by Example › Type anonymity › See also:\n\nA thorough analysis, `Fn`, `FnMut`,\nand `FnOnce`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Type anonymity", "heading_path": ["Type anonymity", "See also:"], "path": "fn/closures/anonymity.md", "url": "https://doc.rust-lang.org/rust-by-example/fn/closures/anonymity.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/fn/closures/input_functions.md#input-functions-0", "text": "Rust by Example › Input functions\n\nSince closures may be used as arguments, you might wonder if the same can be said\nabout functions. And indeed they can! If you declare a function that takes a\nclosure as parameter, then any function that satisfies the trait bound of that\nclosure can be passed as a parameter.\n```rust,editable\n// Define a function which takes a generic `F` argument\n// bounded by `Fn`, and calls it\nfn call_me(f: F) {\n f();\n}\n\n// Define a wrapper function satisfying the `Fn` bound\nfn function() {\n println!(\"I'm a function!\");\n}\n\nfn main() {\n // Define a closure satisfying the `Fn` bound\n let closure = || println!(\"I'm a closure!\");\n\n call_me(closure);\n call_me(function);\n}\n```\nAs an additional note, the `Fn`, `FnMut`, and `FnOnce` `traits` dictate how\na closure captures variables from the enclosing scope.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Input functions", "heading_path": ["Input functions"], "path": "fn/closures/input_functions.md", "url": "https://doc.rust-lang.org/rust-by-example/fn/closures/input_functions.html#input-functions", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/fn/closures/input_functions.md#see-also-1", "text": "Rust by Example › Input functions › See also:\n\n`Fn`, `FnMut`, and `FnOnce`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Input functions", "heading_path": ["Input functions", "See also:"], "path": "fn/closures/input_functions.md", "url": "https://doc.rust-lang.org/rust-by-example/fn/closures/input_functions.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/fn/closures/output_parameters.md#as-output-parameters-0", "text": "Rust by Example › As output parameters\n\nClosures as input parameters are possible, so returning closures as\noutput parameters should also be possible. However, anonymous\nclosure types are, by definition, unknown, so we have to use\n`impl Trait` to return them.\nThe valid traits for returning a closure are:\n* `Fn`\n* `FnMut`\n* `FnOnce`\nBeyond this, the `move` keyword must be used, which signals that all captures\noccur by value. This is required because any captures by reference would be\ndropped as soon as the function exited, leaving invalid references in the\nclosure.\n```rust,editable\nfn create_fn() -> impl Fn() {\n let text = \"Fn\".to_owned();\n\n move || println!(\"This is a: {}\", text)\n}\n\nfn create_fnmut() -> impl FnMut() {\n let text = \"FnMut\".to_owned();\n\n move || println!(\"This is a: {}\", text)\n}\n\nfn create_fnonce() -> impl FnOnce() {\n let text = \"FnOnce\".to_owned();\n\n move || println!(\"This is a: {}\", text)\n}\n\nfn main() {\n let fn_plain = create_fn();\n let mut fn_mut = create_fnmut();\n let fn_once = create_fnonce();\n\n fn_plain();\n fn_mut();\n fn_once();\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "As output parameters", "heading_path": ["As output parameters"], "path": "fn/closures/output_parameters.md", "url": "https://doc.rust-lang.org/rust-by-example/fn/closures/output_parameters.html#as-output-parameters", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/fn/closures/output_parameters.md#see-also-1", "text": "Rust by Example › As output parameters › See also:\n\n`Fn`, `FnMut`, Generics and impl Trait.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "As output parameters", "heading_path": ["As output parameters", "See also:"], "path": "fn/closures/output_parameters.md", "url": "https://doc.rust-lang.org/rust-by-example/fn/closures/output_parameters.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/fn/closures/closure_examples.md#examples-in-std-0", "text": "Rust by Example › Examples in `std`\n\nThis section contains a few examples of using closures from the `std` library.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Examples in `std`", "heading_path": ["Examples in `std`"], "path": "fn/closures/closure_examples.md", "url": "https://doc.rust-lang.org/rust-by-example/fn/closures/closure_examples.html#examples-in-std", "has_code": false, "code_tags": []}} {"id": "rust-by-example/fn/closures/closure_examples/iter_any.md#iteratorany-0", "text": "Rust by Example › Iterator::any\n\n`Iterator::any` is a function which when passed an iterator, will return\n`true` if any element satisfies the predicate. Otherwise `false`. Its\nsignature:\n```rust,ignore\npub trait Iterator {\n // The type being iterated over.\n type Item;\n\n // `any` takes `&mut self` meaning the caller may be borrowed\n // and modified, but not consumed.\n fn any(&mut self, f: F) -> bool where\n // `FnMut` meaning any captured variable may at most be\n // modified, not consumed. `Self::Item` is the closure parameter type,\n // which is determined by the iterator (e.g., `&T` for `.iter()`,\n // `T` for `.into_iter()`).\n F: FnMut(Self::Item) -> bool;\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Iterator::any", "heading_path": ["Iterator::any"], "path": "fn/closures/closure_examples/iter_any.md", "url": "https://doc.rust-lang.org/rust-by-example/fn/closures/closure_examples/iter_any.html#iteratorany", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "rust-by-example/fn/closures/closure_examples/iter_any.md#iteratorany-1", "text": "Rust by Example › Iterator::any\n\n```rust,editable\nfn main() {\n let vec1 = vec![1, 2, 3];\n let vec2 = vec![4, 5, 6];\n\n // `iter()` for vecs yields `&i32`. Destructure to `i32`.\n println!(\"2 in vec1: {}\", vec1.iter() .any(|&x| x == 2));\n // `into_iter()` for vecs yields `i32`. No destructuring required.\n println!(\"2 in vec2: {}\", vec2.into_iter().any(|x| x == 2));\n\n // `iter()` only borrows `vec1` and its elements, so they can be used again\n println!(\"vec1 len: {}\", vec1.len());\n println!(\"First element of vec1 is: {}\", vec1[0]);\n // `into_iter()` does move `vec2` and its elements, so they cannot be used again\n // println!(\"First element of vec2 is: {}\", vec2[0]);\n // println!(\"vec2 len: {}\", vec2.len());\n // TODO: uncomment two lines above and see compiler errors.\n\n let array1 = [1, 2, 3];\n let array2 = [4, 5, 6];\n\n // `iter()` for arrays yields `&i32`.\n println!(\"2 in array1: {}\", array1.iter() .any(|&x| x == 2));\n // `into_iter()` for arrays yields `i32`.\n println!(\"2 in array2: {}\", array2.into_iter().any(|x| x == 2));\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Iterator::any", "heading_path": ["Iterator::any"], "path": "fn/closures/closure_examples/iter_any.md", "url": "https://doc.rust-lang.org/rust-by-example/fn/closures/closure_examples/iter_any.html#iteratorany", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/fn/closures/closure_examples/iter_any.md#see-also-2", "text": "Rust by Example › Iterator::any › See also:\n\n`std::iter::Iterator::any`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Iterator::any", "heading_path": ["Iterator::any", "See also:"], "path": "fn/closures/closure_examples/iter_any.md", "url": "https://doc.rust-lang.org/rust-by-example/fn/closures/closure_examples/iter_any.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/fn/closures/closure_examples/iter_find.md#searching-through-iterators-0", "text": "Rust by Example › Searching through iterators\n\n`Iterator::find` is a function which iterates over an iterator and searches for the\nfirst value which satisfies some condition. If none of the values satisfy the\ncondition, it returns `None`. Its signature:\n```rust,ignore\npub trait Iterator {\n // The type being iterated over.\n type Item;\n\n // `find` takes `&mut self` meaning the caller may be borrowed\n // and modified, but not consumed.\n fn find

(&mut self, predicate: P) -> Option where\n // `FnMut` meaning any captured variable may at most be\n // modified, not consumed. `&Self::Item` states it takes\n // arguments to the closure by reference.\n P: FnMut(&Self::Item) -> bool;\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Searching through iterators", "heading_path": ["Searching through iterators"], "path": "fn/closures/closure_examples/iter_find.md", "url": "https://doc.rust-lang.org/rust-by-example/fn/closures/closure_examples/iter_find.html#searching-through-iterators", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "rust-by-example/fn/closures/closure_examples/iter_find.md#searching-through-iterators-1", "text": "Rust by Example › Searching through iterators\n\n```rust,editable\nfn main() {\n let vec1 = vec![1, 2, 3];\n let vec2 = vec![4, 5, 6];\n\n // `vec1.iter()` yields `&i32`.\n let mut iter = vec1.iter();\n // `vec2.into_iter()` yields `i32`.\n let mut into_iter = vec2.into_iter();\n\n // `iter()` yields `&i32`, and `find` passes `&Item` to the predicate.\n // Since `Item = &i32`, the closure argument has type `&&i32`,\n // which we pattern-match to dereference down to `i32`.\n println!(\"Find 2 in vec1: {:?}\", iter.find(|&&x| x == 2));\n \n // `into_iter()` yields `i32`, and `find` passes `&Item` to the predicate.\n // Since `Item = i32`, the closure argument has type `&i32`,\n // which we pattern-match to dereference down to `i32`.\n println!(\"Find 2 in vec2: {:?}\", into_iter.find(|&x| x == 2));\n\n let array1 = [1, 2, 3];\n let array2 = [4, 5, 6];\n\n // `array1.iter()` yields `&i32`, and `find` passes `&Item` to the\n // predicate. Since `Item = &i32`, the closure argument has type `&&i32`.\n println!(\"Find 2 in array1: {:?}\", array1.iter().find(|&&x| x == 2));\n // `array2.into_iter()` yields `i32` (since Rust 2021 edition), and\n // `find` passes `&Item` to the predicate. Since `Item = i32`, the\n // closure argument has type `&i32`.\n println!(\"Find 2 in array2: {:?}\", array2.into_iter().find(|&x| x == 2));\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Searching through iterators", "heading_path": ["Searching through iterators"], "path": "fn/closures/closure_examples/iter_find.md", "url": "https://doc.rust-lang.org/rust-by-example/fn/closures/closure_examples/iter_find.html#searching-through-iterators", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/fn/closures/closure_examples/iter_find.md#searching-through-iterators-2", "text": "Rust by Example › Searching through iterators\n\n`Iterator::find` gives you a reference to the item. But if you want the _index_ of the\nitem, use `Iterator::position`.\n```rust,editable\nfn main() {\n let vec = vec![1, 9, 3, 3, 13, 2];\n\n // `position` passes the iterator’s `Item` by value to the predicate.\n // `vec.iter()` yields `&i32`, so the predicate receives `&i32`,\n // which we pattern-match to dereference to `i32`.\n let index_of_first_even_number = vec.iter().position(|&x| x % 2 == 0);\n assert_eq!(index_of_first_even_number, Some(5));\n\n // `vec.into_iter()` yields `i32`, so the predicate receives `i32` directly.\n let index_of_first_negative_number = vec.into_iter().position(|x| x < 0);\n assert_eq!(index_of_first_negative_number, None);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Searching through iterators", "heading_path": ["Searching through iterators"], "path": "fn/closures/closure_examples/iter_find.md", "url": "https://doc.rust-lang.org/rust-by-example/fn/closures/closure_examples/iter_find.html#searching-through-iterators", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/fn/closures/closure_examples/iter_find.md#see-also-3", "text": "Rust by Example › Searching through iterators › See also:\n\n`std::iter::Iterator::find`\n`std::iter::Iterator::find_map`\n`std::iter::Iterator::position`\n`std::iter::Iterator::rposition`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Searching through iterators", "heading_path": ["Searching through iterators", "See also:"], "path": "fn/closures/closure_examples/iter_find.md", "url": "https://doc.rust-lang.org/rust-by-example/fn/closures/closure_examples/iter_find.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/fn/hof.md#higher-order-functions-0", "text": "Rust by Example › Higher Order Functions\n\nRust provides Higher Order Functions (HOF). These are functions that\ntake one or more functions and/or produce a more useful function. HOFs\nand lazy iterators give Rust its functional flavor.\n```rust,editable\nfn is_odd(n: u32) -> bool {\n n % 2 == 1\n}\n\nfn main() {\n println!(\"Find the sum of all the numbers with odd squares under 1000\");\n let upper = 1000;\n\n // Imperative approach\n // Declare accumulator variable\n let mut acc = 0;\n // Iterate: 0, 1, 2, ... to infinity\n for n in 0.. {\n // Square the number\n let n_squared = n * n;\n\n if n_squared >= upper {\n // Break loop if exceeded the upper limit\n break;\n } else if is_odd(n_squared) {\n // Accumulate value, if it's odd\n acc += n;\n }\n }\n println!(\"imperative style: {}\", acc);\n\n // Functional approach\n let sum: u32 =\n (0..).take_while(|&n| n * n < upper) // Below upper limit\n .filter(|&n| is_odd(n * n)) // That are odd\n .sum(); // Sum them\n println!(\"functional style: {}\", sum);\n}\n```\nOption\nand\nIterator\nimplement their fair share of HOFs.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Higher Order Functions", "heading_path": ["Higher Order Functions"], "path": "fn/hof.md", "url": "https://doc.rust-lang.org/rust-by-example/fn/hof.html#higher-order-functions", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/fn/diverging.md#diverging-functions-0", "text": "Rust by Example › Diverging functions\n\nDiverging functions never return. They are marked using `!`, which is an empty type.\n```rust\nfn foo() -> ! {\n panic!(\"This call never returns.\");\n}\n```\nAs opposed to all the other types, this one cannot be instantiated, because the\nset of all possible values this type can have is empty. Note that, it is\ndifferent from the `()` type, which has exactly one possible value.\nFor example, this function returns as usual, although there is no information\nin the return value.\n```rust\nfn some_fn() {\n ()\n}\n\nfn main() {\n let _a: () = some_fn();\n println!(\"This function returns and you can see this line.\");\n}\n```\nAs opposed to this function, which will never return the control back to the caller.\n```rust,ignore\n#![feature(never_type)]\n\nfn main() {\n let x: ! = panic!(\"This call never returns.\");\n println!(\"You will never see this line!\");\n}\n```\nAlthough this might seem like an abstract concept, it is actually very useful and\noften handy. The main advantage of this type is that it can be cast to any other\ntype, making it versatile in situations where an exact type is required, such as\nin match branches. This flexibility allows us to write code like this:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Diverging functions", "heading_path": ["Diverging functions"], "path": "fn/diverging.md", "url": "https://doc.rust-lang.org/rust-by-example/fn/diverging.html#diverging-functions", "has_code": true, "code_tags": ["rust", "rust,ignore"]}} {"id": "rust-by-example/fn/diverging.md#diverging-functions-1", "text": "Rust by Example › Diverging functions\n\n```rust\nfn main() {\n fn sum_odd_numbers(up_to: u32) -> u32 {\n let mut acc = 0;\n for i in 0..up_to {\n // Notice that the return type of this match expression must be u32\n // because of the type of the \"addition\" variable.\n let addition: u32 = match i%2 == 1 {\n // The \"i\" variable is of type u32, which is perfectly fine.\n true => i,\n // On the other hand, the \"continue\" expression does not return\n // u32, but it is still fine, because it never returns and therefore\n // does not violate the type requirements of the match expression.\n false => continue,\n };\n acc += addition;\n }\n acc\n }\n println!(\"Sum of odd numbers up to 9 (excluding): {}\", sum_odd_numbers(9));\n}\n```\nIt is also the return type of functions that loop forever (e.g. `loop {}`) like\nnetwork servers or functions that terminate the process (e.g. `exit()`).", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Diverging functions", "heading_path": ["Diverging functions"], "path": "fn/diverging.md", "url": "https://doc.rust-lang.org/rust-by-example/fn/diverging.html#diverging-functions", "has_code": true, "code_tags": ["rust"]}} {"id": "rust-by-example/mod.md#modules-0", "text": "Rust by Example › Modules\n\nRust provides a powerful module system that can be used to hierarchically split\ncode in logical units (modules), and manage visibility (public/private) between\nthem.\nA module is a collection of items: functions, structs, traits, `impl` blocks,\nand even other modules.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Modules", "heading_path": ["Modules"], "path": "mod.md", "url": "https://doc.rust-lang.org/rust-by-example/mod.html#modules", "has_code": false, "code_tags": []}} {"id": "rust-by-example/mod/visibility.md#visibility-0", "text": "Rust by Example › Visibility\n\nBy default, the items in a module have private visibility, but this can be\noverridden with the `pub` modifier. Only the public items of a module can be\naccessed from outside the module scope.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Visibility", "heading_path": ["Visibility"], "path": "mod/visibility.md", "url": "https://doc.rust-lang.org/rust-by-example/mod/visibility.html#visibility", "has_code": false, "code_tags": []}} {"id": "rust-by-example/mod/visibility.md#visibility-1", "text": "Rust by Example › Visibility\n\n```rust,editable\n// A module named `my_mod`\nmod my_mod {\n // Items in modules default to private visibility.\n fn private_function() {\n println!(\"called `my_mod::private_function()`\");\n }\n\n // Use the `pub` modifier to override default visibility.\n pub fn function() {\n println!(\"called `my_mod::function()`\");\n }\n\n // Items can access other items in the same module,\n // even when private.\n pub fn indirect_access() {\n print!(\"called `my_mod::indirect_access()`, that\\n> \");\n private_function();\n }\n\n // Modules can also be nested\n pub mod nested {\n pub fn function() {\n println!(\"called `my_mod::nested::function()`\");\n }\n\n #[allow(dead_code)]\n fn private_function() {\n println!(\"called `my_mod::nested::private_function()`\");\n }\n\n // Functions declared using `pub(in path)` syntax are only visible\n // within the given path. `path` must be a parent or ancestor module\n pub(in crate::my_mod) fn public_function_in_my_mod() {\n print!(\"called `my_mod::nested::public_function_in_my_mod()`, that\\n> \");\n public_function_in_nested();\n }\n\n // Functions declared using `pub(self)` syntax are only visible within\n // the current module, which is the same as leaving them private\n pub(self) fn public_function_in_nested() {\n println!(\"called `my_mod::nested::public_function_in_nested()`\");\n }\n\n // Functions declared using `pub(super)` syntax are only visible within\n // the parent module\n pub(super) fn public_function_in_super_mod() {\n println!(\"called `my_mod::nested::public_function_in_super_mod()`\");\n }\n }\n\n pub fn call_public_function_in_my_mod() {\n print!(\"called `my_mod::call_public_function_in_my_mod()`, that\\n> \");\n nested::public_function_in_my_mod();\n print!(\"> \");\n nested::public_function_in_super_mod();\n }\n\n // pub(crate) makes functions visible only within the current crate\n pub(crate) fn public_function_in_crate() {\n println!(\"called `my_mod::public_function_in_crate()`\");\n }\n\n // Nested modules follow the same rules for visibility\n mod private_nested {\n #[allow(dead_code)]\n pub fn function() {\n println!(\"called `my_mod::private_nested::function()`\");\n }\n\n // Private parent items will still restrict the visibility of a child item,\n // even if it is declared as visible within a bigger scope.\n #[allow(dead_code)]\n pub(crate) fn restricted_function() {\n println!(\"called `my_mod::private_nested::restricted_function()`\");\n }\n }\n}\n\nfn function() {\n println!(\"called `function()`\");\n}\n\nfn main() {\n // Modules allow disambiguation between items that have the same name.\n function();\n my_mod::function();\n\n // Public items, including those inside nested modules, can be\n // accessed from outside the parent module.\n my_mod::indirect_access();\n my_mod::nested::function();\n my_mod::call_public_function_in_my_mod();\n\n // pub(crate) items can be called from anywhere in the same crate\n my_mod::public_function_in_crate();\n\n // pub(in path) items can only be called from within the module specified\n // Error! function `public_function_in_my_mod` is private\n //my_mod::nested::public_function_in_my_mod();\n // TODO ^ Try uncommenting this line\n\n // Private items of a module cannot be directly accessed, even if\n // nested in a public module:\n\n // Error! `private_function` is private\n //my_mod::private_function();\n // TODO ^ Try uncommenting this line\n\n // Error! `private_function` is private\n //my_mod::nested::private_function();\n // TODO ^ Try uncommenting this line\n\n // Error! `private_nested` is a private module\n //my_mod::private_nested::function();\n // TODO ^ Try uncommenting this line\n\n // Error! `private_nested` is a private module\n //my_mod::private_nested::restricted_function();\n // TODO ^ Try uncommenting this line\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Visibility", "heading_path": ["Visibility"], "path": "mod/visibility.md", "url": "https://doc.rust-lang.org/rust-by-example/mod/visibility.html#visibility", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/mod/struct_visibility.md#struct-visibility-0", "text": "Rust by Example › Struct visibility\n\nStructs have an extra level of visibility with their fields. The visibility\ndefaults to private, and can be overridden with the `pub` modifier. This\nvisibility only matters when a struct is accessed from outside the module\nwhere it is defined, and has the goal of hiding information (encapsulation).\n```rust,editable\nmod my {\n // A public struct with a public field of generic type `T`\n pub struct OpenBox {\n pub contents: T,\n }\n\n // A public struct with a private field of generic type `T`\n pub struct ClosedBox {\n contents: T,\n }\n\n impl ClosedBox {\n // A public constructor method\n pub fn new(contents: T) -> ClosedBox {\n ClosedBox {\n contents: contents,\n }\n }\n }\n}\n\nfn main() {\n // Public structs with public fields can be constructed as usual\n let open_box = my::OpenBox { contents: \"public information\" };\n\n // and their fields can be normally accessed.\n println!(\"The open box contains: {}\", open_box.contents);\n\n // Public structs with private fields cannot be constructed using field names.\n // Error! `ClosedBox` has private fields\n //let closed_box = my::ClosedBox { contents: \"classified information\" };\n // TODO ^ Try uncommenting this line\n\n // However, structs with private fields can be created using\n // public constructors\n let _closed_box = my::ClosedBox::new(\"classified information\");\n\n // and the private fields of a public struct cannot be accessed.\n // Error! The `contents` field is private\n //println!(\"The closed box contains: {}\", _closed_box.contents);\n // TODO ^ Try uncommenting this line\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Struct visibility", "heading_path": ["Struct visibility"], "path": "mod/struct_visibility.md", "url": "https://doc.rust-lang.org/rust-by-example/mod/struct_visibility.html#struct-visibility", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/mod/struct_visibility.md#see-also-1", "text": "Rust by Example › Struct visibility › See also:\n\ngenerics and methods", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Struct visibility", "heading_path": ["Struct visibility", "See also:"], "path": "mod/struct_visibility.md", "url": "https://doc.rust-lang.org/rust-by-example/mod/struct_visibility.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/mod/use.md#the-use-declaration-0", "text": "Rust by Example › The `use` declaration\n\nThe `use` declaration can be used to bind a full path to a new name, for easier\naccess. It is often used like this:\n```rust,editable,ignore\nuse crate::deeply::nested::{\n my_first_function,\n my_second_function,\n AndATraitType\n};\n\nfn main() {\n my_first_function();\n}\n```\nYou can use the `as` keyword to bind imports to a different name:\n```rust,editable\n// Bind the `deeply::nested::function` path to `other_function`.\nuse deeply::nested::function as other_function;\n\nfn function() {\n println!(\"called `function()`\");\n}\n\nmod deeply {\n pub mod nested {\n pub fn function() {\n println!(\"called `deeply::nested::function()`\");\n }\n }\n}\n\nfn main() {\n // Easier access to `deeply::nested::function`\n other_function();\n\n println!(\"Entering block\");\n {\n // This is equivalent to `use deeply::nested::function as function`.\n // This `function()` will shadow the outer one.\n use crate::deeply::nested::function;\n\n // `use` bindings have a local scope. In this case, the\n // shadowing of `function()` is only in this block.\n function();\n\n println!(\"Leaving block\");\n }\n\n function();\n}\n```\nYou can also use `pub use` to re-export an item from a module, so it can be\naccessed through the module's public interface:\n```rust,editable\nmod deeply {\n pub mod nested {\n pub fn function() {\n println!(\"called `deeply::nested::function()`\");\n }\n }\n}\n\nmod cool {\n pub use crate::deeply::nested::function;\n}\n\nfn main() {\n cool::function();\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "The `use` declaration", "heading_path": ["The `use` declaration"], "path": "mod/use.md", "url": "https://doc.rust-lang.org/rust-by-example/mod/use.html#the-use-declaration", "has_code": true, "code_tags": ["rust,editable", "rust,editable,ignore"]}} {"id": "rust-by-example/mod/super.md#super-and-self-0", "text": "Rust by Example › `super` and `self`\n\nThe `super` and `self` keywords can be used in the path to remove ambiguity\nwhen accessing items and to prevent unnecessary hardcoding of paths.\n```rust,editable\nfn function() {\n println!(\"called `function()`\");\n}\n\nmod cool {\n pub fn function() {\n println!(\"called `cool::function()`\");\n }\n}\n\nmod my {\n fn function() {\n println!(\"called `my::function()`\");\n }\n\n mod cool {\n pub fn function() {\n println!(\"called `my::cool::function()`\");\n }\n }\n\n pub fn indirect_call() {\n // Let's access all the functions named `function` from this scope!\n print!(\"called `my::indirect_call()`, that\\n> \");\n\n // The `self` keyword refers to the current module scope - in this case `my`.\n // Calling `self::function()` and calling `function()` directly both give\n // the same result, because they refer to the same function.\n self::function();\n function();\n\n // We can also use `self` to access another module inside `my`:\n self::cool::function();\n\n // The `super` keyword refers to the parent scope (outside the `my` module).\n super::function();\n\n // This will bind to the `cool::function` in the *crate* scope.\n // In this case the crate scope is the outermost scope.\n {\n use crate::cool::function as root_function;\n root_function();\n }\n }\n}\n\nfn main() {\n my::indirect_call();\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`super` and `self`", "heading_path": ["`super` and `self`"], "path": "mod/super.md", "url": "https://doc.rust-lang.org/rust-by-example/mod/super.html#super-and-self", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/mod/split.md#file-hierarchy-0", "text": "Rust by Example › File hierarchy\n\nModules can be mapped to a file/directory hierarchy. Let's break down the\nvisibility example in files:\n```shell\n$ tree .\n.\n├── my\n│   ├── inaccessible.rs\n│   └── nested.rs\n├── my.rs\n└── split.rs\n```\nIn `split.rs`:\n```rust,ignore\n// This declaration will look for a file named `my.rs` and will\n// insert its contents inside a module named `my` under this scope\nmod my;\n\nfn function() {\n println!(\"called `function()`\");\n}\n\nfn main() {\n my::function();\n\n function();\n\n my::indirect_access();\n\n my::nested::function();\n}\n\n```\nIn `my.rs`:\n```rust,ignore\n// Similarly `mod inaccessible` and `mod nested` will locate the\n// `inaccessible.rs` and `nested.rs` files and insert them here under their\n// respective modules\nmod inaccessible;\npub mod nested;\n\npub fn function() {\n println!(\"called `my::function()`\");\n}\n\nfn private_function() {\n println!(\"called `my::private_function()`\");\n}\n\npub fn indirect_access() {\n print!(\"called `my::indirect_access()`, that\\n> \");\n\n private_function();\n}\n```\nIn `my/nested.rs`:\n```rust,ignore\npub fn function() {\n println!(\"called `my::nested::function()`\");\n}\n\n#[allow(dead_code)]\nfn private_function() {\n println!(\"called `my::nested::private_function()`\");\n}\n```\nIn `my/inaccessible.rs`:\n```rust,ignore\n#[allow(dead_code)]\npub fn public_function() {\n println!(\"called `my::inaccessible::public_function()`\");\n}\n```\nLet's check that things still work as before:\n```shell\n$ rustc split.rs && ./split\ncalled `my::function()`\ncalled `function()`\ncalled `my::indirect_access()`, that\ncalled `my::private_function()`\ncalled `my::nested::function()`\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "File hierarchy", "heading_path": ["File hierarchy"], "path": "mod/split.md", "url": "https://doc.rust-lang.org/rust-by-example/mod/split.html#file-hierarchy", "has_code": true, "code_tags": ["rust,ignore", "shell"]}} {"id": "rust-by-example/crates.md#crates-0", "text": "Rust by Example › Crates\n\nA crate is a compilation unit in Rust. Whenever `rustc some_file.rs` is called,\n`some_file.rs` is treated as the *crate file*. If `some_file.rs` has `mod`\ndeclarations in it, then the contents of the module files would be inserted in\nplaces where `mod` declarations in the crate file are found, *before* running\nthe compiler over it. In other words, modules do *not* get compiled\nindividually, only crates get compiled.\nA crate can be compiled into a binary or into a library. By default, `rustc`\nwill produce a binary from a crate. This behavior can be overridden by passing\nthe `--crate-type` flag to `lib`.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Crates", "heading_path": ["Crates"], "path": "crates.md", "url": "https://doc.rust-lang.org/rust-by-example/crates.html#crates", "has_code": false, "code_tags": []}} {"id": "rust-by-example/crates/lib.md#creating-a-library-0", "text": "Rust by Example › Creating a Library\n\nLet's create a library, and then see how to link it to another crate.\nIn `rary.rs`:\n```rust,ignore\npub fn public_function() {\n println!(\"called rary's `public_function()`\");\n}\n\nfn private_function() {\n println!(\"called rary's `private_function()`\");\n}\n\npub fn indirect_access() {\n print!(\"called rary's `indirect_access()`, that\\n> \");\n\n private_function();\n}\n```\n```shell\n$ rustc --crate-type=lib rary.rs\n$ ls lib*\nlibrary.rlib\n```\nLibraries get prefixed with \"lib\", and by default they get named after their\ncrate file, but this default name can be overridden by passing\nthe `--crate-name` option to `rustc` or by using the `crate_name`\nattribute.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Creating a Library", "heading_path": ["Creating a Library"], "path": "crates/lib.md", "url": "https://doc.rust-lang.org/rust-by-example/crates/lib.html#creating-a-library", "has_code": true, "code_tags": ["rust,ignore", "shell"]}} {"id": "rust-by-example/crates/using_lib.md#using-a-library-0", "text": "Rust by Example › Using a Library\n\nTo link a crate to this new library you may use `rustc`'s `--extern` flag. All\nof its items will then be imported under a module named the same as the library.\nThis module generally behaves the same way as any other module.\n```rust,ignore\n// extern crate rary; // May be required for Rust 2015 edition or earlier\n\nfn main() {\n rary::public_function();\n\n // Error! `private_function` is private\n //rary::private_function();\n\n rary::indirect_access();\n}\n```\n```txt\n# Where library.rlib is the path to the compiled library, assumed that it's\n# in the same directory here:\n$ rustc executable.rs --extern rary=library.rlib && ./executable\ncalled rary's `public_function()`\ncalled rary's `indirect_access()`, that\ncalled rary's `private_function()`\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Using a Library", "heading_path": ["Using a Library"], "path": "crates/using_lib.md", "url": "https://doc.rust-lang.org/rust-by-example/crates/using_lib.html#using-a-library", "has_code": true, "code_tags": ["rust,ignore", "txt"]}} {"id": "rust-by-example/cargo.md#cargo-0", "text": "Rust by Example › Cargo\n\n`cargo` is the official Rust package management tool. It has lots of really\nuseful features to improve code quality and developer velocity! These include\n- Dependency management and integration with crates.io (the\n official Rust package registry)\n- Awareness of unit tests\n- Awareness of benchmarks\nThis chapter will go through some quick basics, but you can find the\ncomprehensive docs in The Cargo Book.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Cargo", "heading_path": ["Cargo"], "path": "cargo.md", "url": "https://doc.rust-lang.org/rust-by-example/cargo.html#cargo", "has_code": false, "code_tags": []}} {"id": "rust-by-example/cargo/deps.md#dependencies-0", "text": "Rust by Example › Dependencies\n\nMost programs have dependencies on some libraries. If you have ever managed\ndependencies by hand, you know how much of a pain this can be. Luckily, the Rust\necosystem comes standard with `cargo`! `cargo` can manage dependencies for a\nproject.\nTo create a new Rust project,\n```sh\n# A binary\ncargo new foo\n\n# A library\ncargo new --lib bar\n```\nFor the rest of this chapter, let's assume we are making a binary, rather than\na library, but all of the concepts are the same.\nAfter the above commands, you should see a file hierarchy like this:\n```txt\n.\n├── bar\n│ ├── Cargo.toml\n│ └── src\n│ └── lib.rs\n└── foo\n ├── Cargo.toml\n └── src\n └── main.rs\n```\nThe `main.rs` is the root source file for your new `foo` project -- nothing new there.\nThe `Cargo.toml` is the config file for `cargo` for this project. If you\nlook inside it, you should see something like this:\n```toml\n[package]\nname = \"foo\"\nversion = \"0.1.0\"\nauthors = [\"mark\"]\n\n[dependencies]\n```\nThe `name` field under `[package]` determines the name of the project. This is\nused by `crates.io` if you publish the crate (more later). It is also the name\nof the output binary when you compile.\nThe `version` field is a crate version number using Semantic\nVersioning.\nThe `authors` field is a list of authors used when publishing the crate.\nThe `[dependencies]` section lets you add dependencies for your project.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Dependencies", "heading_path": ["Dependencies"], "path": "cargo/deps.md", "url": "https://doc.rust-lang.org/rust-by-example/cargo/deps.html#dependencies", "has_code": true, "code_tags": ["sh", "toml", "txt"]}} {"id": "rust-by-example/cargo/deps.md#dependencies-1", "text": "Rust by Example › Dependencies\n\nFor example, suppose that we want our program to have a great CLI. You can find\nlots of great packages on crates.io (the official Rust\npackage registry). One popular choice is clap.\nAs of this writing, the most recent published version of `clap` is `2.27.1`. To\nadd a dependency to our program, we can simply add the following to our\n`Cargo.toml` under `[dependencies]`: `clap = \"2.27.1\"`. And that's it! You can start using\n`clap` in your program.\n`cargo` also supports other types of dependencies. Here is just\na small sampling:\n```toml\n[package]\nname = \"foo\"\nversion = \"0.1.0\"\nauthors = [\"mark\"]\n\n[dependencies]\nclap = \"2.27.1\" # from crates.io\nrand = { git = \"https://github.com/rust-lang-nursery/rand\" } # from online repo\nbar = { path = \"../bar\" } # from a path in the local filesystem\n```\n`cargo` is more than a dependency manager. All of the available\nconfiguration options are listed in the format specification of\n`Cargo.toml`.\nTo build our project we can execute `cargo build` anywhere in the project\ndirectory (including subdirectories!). We can also do `cargo run` to build and\nrun. Notice that these commands will resolve all dependencies, download crates\nif needed, and build everything, including your crate. (Note that it only\nrebuilds what it has not already built, similar to `make`).\nVoila! That's all there is to it!", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Dependencies", "heading_path": ["Dependencies"], "path": "cargo/deps.md", "url": "https://doc.rust-lang.org/rust-by-example/cargo/deps.html#dependencies", "has_code": true, "code_tags": ["toml"]}} {"id": "rust-by-example/cargo/conventions.md#conventions-0", "text": "Rust by Example › Conventions\n\nIn the previous chapter, we saw the following directory hierarchy:\n```txt\nfoo\n├── Cargo.toml\n└── src\n └── main.rs\n```\nSuppose that we wanted to have two binaries in the same project, though. What\nthen?\nIt turns out that `cargo` supports this. The default binary name is `main`, as\nwe saw before, but you can add additional binaries by placing them in a `bin/`\ndirectory:\n```txt\nfoo\n├── Cargo.toml\n└── src\n ├── main.rs\n └── bin\n └── my_other_bin.rs\n```\nTo tell `cargo` to only compile or run this binary, we just pass `cargo` the\n`--bin my_other_bin` flag, where `my_other_bin` is the name of the binary we\nwant to work with.\nIn addition to extra binaries, `cargo` supports [more features] such as\nbenchmarks, tests, and examples.\nIn the next chapter, we will look more closely at tests.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Conventions", "heading_path": ["Conventions"], "path": "cargo/conventions.md", "url": "https://doc.rust-lang.org/rust-by-example/cargo/conventions.html#conventions", "has_code": true, "code_tags": ["txt"]}} {"id": "rust-by-example/cargo/test.md#testing-0", "text": "Rust by Example › Testing\n\nAs we know testing is integral to any piece of software! Rust has first-class\nsupport for unit and integration testing (see this\nchapter in TRPL).\nFrom the testing chapters linked above, we see how to write unit tests and\nintegration tests. Organizationally, we can place unit tests in the modules they\ntest and integration tests in their own `tests/` directory:\n```txt\nfoo\n├── Cargo.toml\n├── src\n│ └── main.rs\n│ └── lib.rs\n└── tests\n ├── my_test.rs\n └── my_other_test.rs\n```\nEach file in `tests` is a separate\nintegration test,\ni.e. a test that is meant to test your library as if it were being called from a dependent\ncrate.\nThe Testing chapter elaborates on the three different testing styles:\nUnit, Doc, and Integration.\n`cargo` naturally provides an easy way to run all of your tests!\n```shell\n$ cargo test\n```\nYou should see output like this:\n```shell\n$ cargo test\n Compiling blah v0.1.0 (file:///nobackup/blah)\n Finished dev [unoptimized + debuginfo] target(s) in 0.89 secs\n Running target/debug/deps/blah-d3b32b97275ec472\n\nrunning 4 tests\ntest test_bar ... ok\ntest test_baz ... ok\ntest test_foo_bar ... ok\ntest test_foo ... ok\n\ntest result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\n```\nYou can also run tests whose name matches a pattern:\n```shell\n$ cargo test test_foo\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Tests", "heading_path": ["Testing"], "path": "cargo/test.md", "url": "https://doc.rust-lang.org/rust-by-example/cargo/test.html#testing", "has_code": true, "code_tags": ["shell", "txt"]}} {"id": "rust-by-example/cargo/test.md#testing-1", "text": "Rust by Example › Testing\n\n```shell\n$ cargo test test_foo\n Compiling blah v0.1.0 (file:///nobackup/blah)\n Finished dev [unoptimized + debuginfo] target(s) in 0.35 secs\n Running target/debug/deps/blah-d3b32b97275ec472\n\nrunning 2 tests\ntest test_foo ... ok\ntest test_foo_bar ... ok\n\ntest result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 2 filtered out\n```\nOne word of caution: Cargo may run multiple tests concurrently, so make sure\nthat they don't race with each other.\nOne example of this concurrency causing issues is if two tests output to a\nfile, such as below:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Tests", "heading_path": ["Testing"], "path": "cargo/test.md", "url": "https://doc.rust-lang.org/rust-by-example/cargo/test.html#testing", "has_code": true, "code_tags": ["shell"]}} {"id": "rust-by-example/cargo/test.md#testing-2", "text": "Rust by Example › Testing\n\n```rust\n#[cfg(test)]\nmod tests {\n // Import the necessary modules\n use std::fs::OpenOptions;\n use std::io::Write;\n\n // This test writes to a file\n #[test]\n fn test_file() {\n // Opens the file ferris.txt or creates one if it doesn't exist.\n let mut file = OpenOptions::new()\n .append(true)\n .create(true)\n .open(\"ferris.txt\")\n .expect(\"Failed to open ferris.txt\");\n\n // Print \"Ferris\" 5 times.\n for _ in 0..5 {\n file.write_all(\"Ferris\\n\".as_bytes())\n .expect(\"Could not write to ferris.txt\");\n }\n }\n\n // This test tries to write to the same file\n #[test]\n fn test_file_also() {\n // Opens the file ferris.txt or creates one if it doesn't exist.\n let mut file = OpenOptions::new()\n .append(true)\n .create(true)\n .open(\"ferris.txt\")\n .expect(\"Failed to open ferris.txt\");\n\n // Print \"Corro\" 5 times.\n for _ in 0..5 {\n file.write_all(\"Corro\\n\".as_bytes())\n .expect(\"Could not write to ferris.txt\");\n }\n }\n}\n```\nAlthough the intent is to get the following:\n```shell\n$ cat ferris.txt\nFerris\nFerris\nFerris\nFerris\nFerris\nCorro\nCorro\nCorro\nCorro\nCorro\n```\nWhat actually gets put into `ferris.txt` is this:\n```shell\n$ cargo test test_file && cat ferris.txt\nCorro\nFerris\nCorro\nFerris\nCorro\nFerris\nCorro\nFerris\nCorro\nFerris\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Tests", "heading_path": ["Testing"], "path": "cargo/test.md", "url": "https://doc.rust-lang.org/rust-by-example/cargo/test.html#testing", "has_code": true, "code_tags": ["rust", "shell"]}} {"id": "rust-by-example/cargo/build_scripts.md#build-scripts-0", "text": "Rust by Example › Build Scripts\n\nSometimes a normal build from `cargo` is not enough. Perhaps your crate needs\nsome pre-requisites before `cargo` will successfully compile, things like code\ngeneration, or some native code that needs to be compiled. To solve this problem\nwe have build scripts that Cargo can run.\nTo add a build script to your package it can either be specified in the\n`Cargo.toml` as follows:\n```toml\n[package]\n...\nbuild = \"build.rs\"\n```\nOtherwise Cargo will look for a `build.rs` file in the project directory by\ndefault.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Build Scripts", "heading_path": ["Build Scripts"], "path": "cargo/build_scripts.md", "url": "https://doc.rust-lang.org/rust-by-example/cargo/build_scripts.html#build-scripts", "has_code": true, "code_tags": ["toml"]}} {"id": "rust-by-example/cargo/build_scripts.md#how-to-use-a-build-script-1", "text": "Rust by Example › Build Scripts › How to use a build script\n\nThe build script is simply another Rust file that will be compiled and invoked\nprior to compiling anything else in the package. Hence it can be used to fulfill\npre-requisites of your crate.\nCargo provides the script with inputs via environment variables [specified\nhere] that can be used.\nThe script provides output via stdout. All lines printed are written to\n`target/debug/build//output`. Further, lines prefixed with `cargo:` will be\ninterpreted by Cargo directly and hence can be used to define parameters for the\npackage's compilation.\nFor further specification and examples have a read of the\nCargo specification.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Build Scripts", "heading_path": ["Build Scripts", "How to use a build script"], "path": "cargo/build_scripts.md", "url": "https://doc.rust-lang.org/rust-by-example/cargo/build_scripts.html#how-to-use-a-build-script", "has_code": false, "code_tags": []}} {"id": "rust-by-example/attribute.md#attributes-0", "text": "Rust by Example › Attributes\n\nAn attribute is metadata applied to some module, crate or item. This metadata\ncan be used to/for:\n* conditional compilation of code\n* set crate name, version and type (binary or library)\n* disable lints (warnings)\n* enable compiler features (macros, glob imports, etc.)\n* link to a foreign library\n* mark functions as unit tests\n* mark functions that will be part of a benchmark\n* attribute like macros\nAttributes look like `#[outer_attribute]` or `#![inner_attribute]`,\nwith the difference between them being where they apply.\n* `#[outer_attribute]` applies to the item immediately\n following it. Some examples of items are: a function, a module\n declaration, a constant, a structure, an enum. Here is an example\n where attribute `#[derive(Debug)]` applies to the struct\n `Rectangle`:\n```rust\n #[derive(Debug)]\n struct Rectangle {\n width: u32,\n height: u32,\n }\n```\n* `#![inner_attribute]` applies to the enclosing item (typically a\n module or a crate). In other words, this attribute is interpreted as\n applying to the entire scope in which it's placed. Here is an example\n where `#![allow(unused_variables)]` applies to the whole crate (if\n placed in `main.rs`):\n```rust\n #![allow(unused_variables)]\n\n fn main() {\n let x = 3; // This would normally warn about an unused variable.\n }\n```\nAttributes can take arguments with different syntaxes:\n* `#[attribute = \"value\"]`\n* `#[attribute(key = \"value\")]`\n* `#[attribute(value)]`\nAttributes can have multiple values and can be separated over multiple lines, too:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Attributes", "heading_path": ["Attributes"], "path": "attribute.md", "url": "https://doc.rust-lang.org/rust-by-example/attribute.html#attributes", "has_code": true, "code_tags": ["rust"]}} {"id": "rust-by-example/attribute.md#attributes-1", "text": "Rust by Example › Attributes\n\n```rust,ignore\n#[attribute(value, value2)]\n\n\n#[attribute(value, value2, value3,\n value4, value5)]\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Attributes", "heading_path": ["Attributes"], "path": "attribute.md", "url": "https://doc.rust-lang.org/rust-by-example/attribute.html#attributes", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "rust-by-example/attribute/unused.md#dead_code-0", "text": "Rust by Example › `dead_code`\n\nThe compiler provides a `dead_code`\n*lint* that will warn\nabout unused functions. An *attribute* can be used to disable the lint.\n```rust,editable\nfn used_function() {}\n\n// `#[allow(dead_code)]` is an attribute that disables the `dead_code` lint\n#[allow(dead_code)]\nfn unused_function() {}\n\nfn noisy_unused_function() {}\n// FIXME ^ Add an attribute to suppress the warning\n\nfn main() {\n used_function();\n}\n```\nNote that in real programs, you should eliminate dead code. In these examples\nwe'll allow dead code in some places because of the interactive nature of the\nexamples.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`dead_code`", "heading_path": ["`dead_code`"], "path": "attribute/unused.md", "url": "https://doc.rust-lang.org/rust-by-example/attribute/unused.html#dead_code", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/attribute/crate.md#crates-0", "text": "Rust by Example › Crates\n\nThe `crate_type` attribute can be used to tell the compiler whether a crate is\na binary or a library (and even which type of library), and the `crate_name`\nattribute can be used to set the name of the crate.\nHowever, it is important to note that both the `crate_type` and `crate_name`\nattributes have **no** effect whatsoever when using Cargo, the Rust package\nmanager. Since Cargo is used for the majority of Rust projects, this means\nreal-world uses of `crate_type` and `crate_name` are relatively limited.\n```rust,editable\n// This crate is a library\n#![crate_type = \"lib\"]\n// The library is named \"rary\"\n#![crate_name = \"rary\"]\n\npub fn public_function() {\n println!(\"called rary's `public_function()`\");\n}\n\nfn private_function() {\n println!(\"called rary's `private_function()`\");\n}\n\npub fn indirect_access() {\n print!(\"called rary's `indirect_access()`, that\\n> \");\n\n private_function();\n}\n```\nWhen the `crate_type` attribute is used, we no longer need to pass the\n`--crate-type` flag to `rustc`.\n```shell\n$ rustc lib.rs\n$ ls lib*\nlibrary.rlib\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Crates", "heading_path": ["Crates"], "path": "attribute/crate.md", "url": "https://doc.rust-lang.org/rust-by-example/attribute/crate.html#crates", "has_code": true, "code_tags": ["rust,editable", "shell"]}} {"id": "rust-by-example/attribute/cfg.md#cfg-0", "text": "Rust by Example › `cfg`\n\nConfiguration conditional checks are possible through two different operators:\n* the `cfg` attribute: `#[cfg(...)]` in attribute position\n* the `cfg!` macro: `cfg!(...)` in boolean expressions\nWhile the former enables conditional compilation, the latter conditionally\nevaluates to `true` or `false` literals allowing for checks at run-time. Both\nutilize identical argument syntax.\n`cfg!`, unlike `#[cfg]`, does not remove any code and only evaluates to true or false. For example, all blocks in an if/else expression need to be valid when `cfg!` is used for the condition, regardless of what `cfg!` is evaluating.\n```rust,editable\n// This function only gets compiled if the target OS is linux\n#[cfg(target_os = \"linux\")]\nfn are_you_on_linux() {\n println!(\"You are running linux!\");\n}\n\n// And this function only gets compiled if the target OS is *not* linux\n#[cfg(not(target_os = \"linux\"))]\nfn are_you_on_linux() {\n println!(\"You are *not* running linux!\");\n}\n\nfn main() {\n are_you_on_linux();\n\n println!(\"Are you sure?\");\n if cfg!(target_os = \"linux\") {\n println!(\"Yes. It's definitely linux!\");\n } else {\n println!(\"Yes. It's definitely *not* linux!\");\n }\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`cfg`", "heading_path": ["`cfg`"], "path": "attribute/cfg.md", "url": "https://doc.rust-lang.org/rust-by-example/attribute/cfg.html#cfg", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/attribute/cfg.md#see-also-1", "text": "Rust by Example › `cfg` › See also:\n\nthe reference, `cfg!`, and macros.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`cfg`", "heading_path": ["`cfg`", "See also:"], "path": "attribute/cfg.md", "url": "https://doc.rust-lang.org/rust-by-example/attribute/cfg.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/attribute/cfg/custom.md#custom-0", "text": "Rust by Example › Custom\n\nSome conditionals like `target_os` are implicitly provided by `rustc`, but\ncustom conditionals must be passed to `rustc` using the `--cfg` flag.\n```rust,editable,ignore,mdbook-runnable\n#[cfg(some_condition)]\nfn conditional_function() {\n println!(\"condition met!\");\n}\n\nfn main() {\n conditional_function();\n}\n```\nTry to run this to see what happens without the custom `cfg` flag.\nWith the custom `cfg` flag:\n```shell\n$ rustc --cfg some_condition custom.rs && ./custom\ncondition met!\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Custom", "heading_path": ["Custom"], "path": "attribute/cfg/custom.md", "url": "https://doc.rust-lang.org/rust-by-example/attribute/cfg/custom.html#custom", "has_code": true, "code_tags": ["rust,editable,ignore,mdbook-runnable", "shell"]}} {"id": "rust-by-example/generics.md#generics-0", "text": "Rust by Example › Generics\n\n*Generics* is the topic of generalizing types and functionalities to broader\ncases. This is extremely useful for reducing code duplication in many ways,\nbut can call for rather involved syntax. Namely, being generic requires\ntaking great care to specify over which types a generic type\nis actually considered valid. The simplest and most common use of generics\nis for type parameters.\nA type parameter is specified as generic by the use of angle brackets and upper\ncamel case: ``. \"Generic type parameters\" are\ntypically represented as ``. In Rust, \"generic\" also describes anything that\naccepts one or more generic type parameters ``. Any type specified as a\ngeneric type parameter is generic, and everything else is concrete (non-generic).\nFor example, defining a *generic function* named `foo` that takes an argument\n`T` of any type:\n```rust,ignore\nfn foo(arg: T) { ... }\n```\nBecause `T` has been specified as a generic type parameter using ``, it\nis considered generic when used here as `(arg: T)`. This is the case even if `T`\nhas previously been defined as a `struct`.\nThis example shows some of the syntax in action:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Generics", "heading_path": ["Generics"], "path": "generics.md", "url": "https://doc.rust-lang.org/rust-by-example/generics.html#generics", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "rust-by-example/generics.md#generics-1", "text": "Rust by Example › Generics\n\n```rust,editable\n// A concrete type `A`.\nstruct A;\n\n// In defining the type `Single`, the first use of `A` is not preceded by ``.\n// Therefore, `Single` is a concrete type, and `A` is defined as above.\nstruct Single(A);\n// ^ Here is `Single`s first use of the type `A`.\n\n// Here, `` precedes the first use of `T`, so `SingleGen` is a generic type.\n// Because the type parameter `T` is generic, it could be anything, including\n// the concrete type `A` defined at the top.\nstruct SingleGen(T);\n\nfn main() {\n // `Single` is concrete and explicitly takes `A`.\n let _s = Single(A);\n\n // Create a variable `_char` of type `SingleGen`\n // and give it the value `SingleGen('a')`.\n // Here, `SingleGen` has a type parameter explicitly specified.\n let _char: SingleGen = SingleGen('a');\n\n // `SingleGen` can also have a type parameter implicitly specified:\n let _t = SingleGen(A); // Uses `A` defined at the top.\n let _i32 = SingleGen(6); // Uses `i32`.\n let _char = SingleGen('a'); // Uses `char`.\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Generics", "heading_path": ["Generics"], "path": "generics.md", "url": "https://doc.rust-lang.org/rust-by-example/generics.html#generics", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/generics.md#see-also-2", "text": "Rust by Example › Generics › See also:\n\n`structs`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Generics", "heading_path": ["Generics", "See also:"], "path": "generics.md", "url": "https://doc.rust-lang.org/rust-by-example/generics.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/generics/gen_fn.md#functions-0", "text": "Rust by Example › Functions\n\nThe same set of rules can be applied to functions: a type `T` becomes\ngeneric when preceded by ``.\nUsing generic functions sometimes requires explicitly specifying type\nparameters. This may be the case if the function is called where the return type\nis generic, or if the compiler doesn't have enough information to infer\nthe necessary type parameters.\nA function call with explicitly specified type parameters looks like:\n`fun::()`.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Functions", "heading_path": ["Functions"], "path": "generics/gen_fn.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/gen_fn.html#functions", "has_code": false, "code_tags": []}} {"id": "rust-by-example/generics/gen_fn.md#functions-1", "text": "Rust by Example › Functions\n\n```rust,editable\nstruct A; // Concrete type `A`.\nstruct S(A); // Concrete type `S`.\nstruct SGen(T); // Generic type `SGen`.\n\n// The following functions all take ownership of the variable passed into\n// them and immediately go out of scope, freeing the variable.\n\n// Define a function `reg_fn` that takes an argument `_s` of type `S`.\n// This has no `` so this is not a generic function.\nfn reg_fn(_s: S) {}\n\n// Define a function `gen_spec_t` that takes an argument `_s` of type `SGen`.\n// It has been explicitly given the type parameter `A`, but because `A` has not\n// been specified as a generic type parameter for `gen_spec_t`, it is not generic.\nfn gen_spec_t(_s: SGen) {}\n\n// Define a function `gen_spec_i32` that takes an argument `_s` of type `SGen`.\n// It has been explicitly given the type parameter `i32`, which is a specific type.\n// Because `i32` is not a generic type, this function is also not generic.\nfn gen_spec_i32(_s: SGen) {}\n\n// Define a function `generic` that takes an argument `_s` of type `SGen`.\n// Because `SGen` is preceded by ``, this function is generic over `T`.\nfn generic(_s: SGen) {}\n\nfn main() {\n // Using the non-generic functions\n reg_fn(S(A)); // Concrete type.\n gen_spec_t(SGen(A)); // Implicitly specified type parameter `A`.\n gen_spec_i32(SGen(6)); // Implicitly specified type parameter `i32`.\n\n // Explicitly specified type parameter `char` to `generic()`.\n generic::(SGen('a'));\n\n // Implicitly specified type parameter `char` to `generic()`.\n generic(SGen('c'));\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Functions", "heading_path": ["Functions"], "path": "generics/gen_fn.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/gen_fn.html#functions", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/generics/gen_fn.md#see-also-2", "text": "Rust by Example › Functions › See also:\n\nfunctions and `struct`s", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Functions", "heading_path": ["Functions", "See also:"], "path": "generics/gen_fn.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/gen_fn.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/generics/impl.md#implementation-0", "text": "Rust by Example › Implementation\n\nSimilar to functions, implementations require care to remain generic.\n```rust\nstruct S; // Concrete type `S`\nstruct GenericVal(T); // Generic type `GenericVal`\n\n// impl of GenericVal where we explicitly specify type parameters:\nimpl GenericVal {} // Specify `f32`\nimpl GenericVal {} // Specify `S` as defined above\n\n// `` Must precede the type to remain generic\nimpl GenericVal {}\n```\n```rust,editable\nstruct Val {\n val: f64,\n}\n\nstruct GenVal {\n gen_val: T,\n}\n\n// impl of Val\nimpl Val {\n fn value(&self) -> &f64 {\n &self.val\n }\n}\n\n// impl of GenVal for a generic type `T`\nimpl GenVal {\n fn value(&self) -> &T {\n &self.gen_val\n }\n}\n\nfn main() {\n let x = Val { val: 3.0 };\n let y = GenVal { gen_val: 3i32 };\n\n println!(\"{}, {}\", x.value(), y.value());\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Implementation", "heading_path": ["Implementation"], "path": "generics/impl.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/impl.html#implementation", "has_code": true, "code_tags": ["rust", "rust,editable"]}} {"id": "rust-by-example/generics/impl.md#see-also-1", "text": "Rust by Example › Implementation › See also:\n\nfunctions returning references, `impl`, and `struct`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Implementation", "heading_path": ["Implementation", "See also:"], "path": "generics/impl.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/impl.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/generics/gen_trait.md#traits-0", "text": "Rust by Example › Traits\n\nOf course `trait`s can also be generic. Here we define one which reimplements\nthe `Drop` `trait` as a generic method to `drop` itself and an input.\n```rust,editable\n// Non-copyable types.\nstruct Empty;\nstruct Null;\n\n// A trait generic over `T`.\ntrait DoubleDrop {\n // Define a method on the caller type which takes an\n // additional single parameter `T` and does nothing with it.\n fn double_drop(self, _: T);\n}\n\n// Implement `DoubleDrop` for any generic parameter `T` and\n// caller `U`.\nimpl DoubleDrop for U {\n // This method takes ownership of both passed arguments,\n // deallocating both.\n fn double_drop(self, _: T) {}\n}\n\nfn main() {\n let empty = Empty;\n let null = Null;\n\n // Deallocate `empty` and `null`.\n empty.double_drop(null);\n\n //empty;\n //null;\n // ^ TODO: Try uncommenting these lines.\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Traits", "heading_path": ["Traits"], "path": "generics/gen_trait.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/gen_trait.html#traits", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/generics/gen_trait.md#see-also-1", "text": "Rust by Example › Traits › See also:\n\n`Drop`, `struct`, and `trait`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Traits", "heading_path": ["Traits", "See also:"], "path": "generics/gen_trait.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/gen_trait.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/generics/bounds.md#bounds-0", "text": "Rust by Example › Bounds\n\nWhen working with generics, the type parameters often must use traits as *bounds* to\nstipulate what functionality a type implements. For example, the following\nexample uses the trait `Display` to print and so it requires `T` to be bound\nby `Display`; that is, `T` *must* implement `Display`.\n```rust,ignore\n// Define a function `printer` that takes a generic type `T` which\n// must implement trait `Display`.\nfn printer(t: T) {\n println!(\"{}\", t);\n}\n```\nBounding restricts the generic to types that conform to the bounds. That is:\n```rust,ignore\nstruct S(T);\n\n// Error! `Vec` does not implement `Display`. This\n// specialization will fail.\nlet s = S(vec![1]);\n```\nAnother effect of bounding is that generic instances are allowed to access the\n[methods] of traits specified in the bounds. For example:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Bounds", "heading_path": ["Bounds"], "path": "generics/bounds.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/bounds.html#bounds", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "rust-by-example/generics/bounds.md#bounds-1", "text": "Rust by Example › Bounds\n\n```rust,editable\n// A trait which implements the print marker: `{:?}`.\nuse std::fmt::Debug;\n\ntrait HasArea {\n fn area(&self) -> f64;\n}\n\nimpl HasArea for Rectangle {\n fn area(&self) -> f64 { self.length * self.height }\n}\n\n#[derive(Debug)]\nstruct Rectangle { length: f64, height: f64 }\n#[allow(dead_code)]\nstruct Triangle { length: f64, height: f64 }\n\n// The generic `T` must implement `Debug`. Regardless\n// of the type, this will work properly.\nfn print_debug(t: &T) {\n println!(\"{:?}\", t);\n}\n\n// `T` must implement `HasArea`. Any type which meets\n// the bound can access `HasArea`'s function `area`.\nfn area(t: &T) -> f64 { t.area() }\n\nfn main() {\n let rectangle = Rectangle { length: 3.0, height: 4.0 };\n let _triangle = Triangle { length: 3.0, height: 4.0 };\n\n print_debug(&rectangle);\n println!(\"Area: {}\", area(&rectangle));\n\n //print_debug(&_triangle);\n //println!(\"Area: {}\", area(&_triangle));\n // ^ TODO: Try uncommenting these.\n // | Error: Does not implement either `Debug` or `HasArea`.\n}\n```\nAs an additional note, `where` clauses can also be used to apply bounds in\nsome cases to be more expressive.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Bounds", "heading_path": ["Bounds"], "path": "generics/bounds.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/bounds.html#bounds", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/generics/bounds.md#see-also-2", "text": "Rust by Example › Bounds › See also:\n\n`std::fmt`, `struct`s, and `trait`s", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Bounds", "heading_path": ["Bounds", "See also:"], "path": "generics/bounds.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/bounds.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/generics/bounds/testcase_empty.md#testcase-empty-bounds-0", "text": "Rust by Example › Testcase: empty bounds\n\nA consequence of how bounds work is that even if a `trait` doesn't\ninclude any functionality, you can still use it as a bound. `Eq` and\n`Copy` are examples of such `trait`s from the `std` library.\n```rust,editable\nstruct Cardinal;\nstruct BlueJay;\nstruct Turkey;\n\ntrait Red {}\ntrait Blue {}\n\nimpl Red for Cardinal {}\nimpl Blue for BlueJay {}\n\n// These functions are only valid for types which implement these\n// traits. The fact that the traits are empty is irrelevant.\nfn red(_: &T) -> &'static str { \"red\" }\nfn blue(_: &T) -> &'static str { \"blue\" }\n\nfn main() {\n let cardinal = Cardinal;\n let blue_jay = BlueJay;\n let _turkey = Turkey;\n\n // `red()` won't work on a blue jay nor vice versa\n // because of the bounds.\n println!(\"A cardinal is {}\", red(&cardinal));\n println!(\"A blue jay is {}\", blue(&blue_jay));\n //println!(\"A turkey is {}\", red(&_turkey));\n // ^ TODO: Try uncommenting this line.\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Testcase: empty bounds", "heading_path": ["Testcase: empty bounds"], "path": "generics/bounds/testcase_empty.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/bounds/testcase_empty.html#testcase-empty-bounds", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/generics/bounds/testcase_empty.md#see-also-1", "text": "Rust by Example › Testcase: empty bounds › See also:\n\n`std::cmp::Eq`, `std::marker::Copy`, and `trait`s", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Testcase: empty bounds", "heading_path": ["Testcase: empty bounds", "See also:"], "path": "generics/bounds/testcase_empty.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/bounds/testcase_empty.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/generics/multi_bounds.md#multiple-bounds-0", "text": "Rust by Example › Multiple bounds\n\nMultiple bounds for a single type can be applied with a `+`. Like normal, different types are\nseparated with `,`.\n```rust,editable\nuse std::fmt::{Debug, Display};\n\nfn compare_prints(t: &T) {\n println!(\"Debug: `{:?}`\", t);\n println!(\"Display: `{}`\", t);\n}\n\nfn compare_types(t: &T, u: &U) {\n println!(\"t: `{:?}`\", t);\n println!(\"u: `{:?}`\", u);\n}\n\nfn main() {\n let string = \"words\";\n let array = [1, 2, 3];\n let vec = vec![1, 2, 3];\n\n compare_prints(&string);\n //compare_prints(&array);\n // TODO ^ Try uncommenting this.\n\n compare_types(&array, &vec);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Multiple bounds", "heading_path": ["Multiple bounds"], "path": "generics/multi_bounds.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/multi_bounds.html#multiple-bounds", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/generics/multi_bounds.md#see-also-1", "text": "Rust by Example › Multiple bounds › See also:\n\n`std::fmt` and `trait`s", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Multiple bounds", "heading_path": ["Multiple bounds", "See also:"], "path": "generics/multi_bounds.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/multi_bounds.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/generics/where.md#where-clauses-0", "text": "Rust by Example › Where clauses\n\nA bound can also be expressed using a `where` clause immediately\nbefore the opening `{`, rather than at the type's first mention.\nAdditionally, `where` clauses can apply bounds to arbitrary types,\nrather than just to type parameters.\nSome cases that a `where` clause is useful:\n* When specifying generic types and bounds separately is clearer:\n```rust,ignore\nimpl MyTrait for YourType {}\n\n// Expressing bounds with a `where` clause\nimpl MyTrait for YourType where\n A: TraitB + TraitC,\n D: TraitE + TraitF {}\n```\n* When using a `where` clause is more expressive than using normal syntax.\nThe `impl` in this example cannot be directly expressed without a `where` clause:\n```rust,editable\nuse std::fmt::Debug;\n\ntrait PrintInOption {\n fn print_in_option(self);\n}\n\n// Because we would otherwise have to express this as `T: Debug` or\n// use another method of indirect approach, this requires a `where` clause:\nimpl PrintInOption for T where\n Option: Debug {\n // We want `Option: Debug` as our bound because that is what's\n // being printed. Doing otherwise would be using the wrong bound.\n fn print_in_option(self) {\n println!(\"{:?}\", Some(self));\n }\n}\n\nfn main() {\n let vec = vec![1, 2, 3];\n\n vec.print_in_option();\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Where clauses", "heading_path": ["Where clauses"], "path": "generics/where.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/where.html#where-clauses", "has_code": true, "code_tags": ["rust,editable", "rust,ignore"]}} {"id": "rust-by-example/generics/where.md#see-also-1", "text": "Rust by Example › Where clauses › See also:\n\nRFC, `struct`, and `trait`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Where clauses", "heading_path": ["Where clauses", "See also:"], "path": "generics/where.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/where.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/generics/new_types.md#new-type-idiom-0", "text": "Rust by Example › New Type Idiom\n\nThe `newtype` idiom gives compile time guarantees that the right type of value is supplied\nto a program.\nFor example, a function that measures distance in miles, *must* be given\na value of type `Miles`.\n```rust, editable\nstruct Miles(f64);\n\nstruct Kilometers(f64);\n\nimpl Miles {\n pub fn to_kilometers(&self) -> Kilometers {\n Kilometers(self.0 * 1.609344)\n }\n}\n\nimpl Kilometers {\n pub fn to_miles(&self) -> Miles {\n Miles(self.0 / 1.609344)\n }\n}\n\nfn is_a_marathon(distance: &Miles) -> bool {\n distance.0 >= 26.2\n}\n\nfn main() {\n let distance = Miles(30.0);\n let distance_km = distance.to_kilometers();\n println!(\"Is a marathon? {}\", is_a_marathon(&distance));\n println!(\"Is a marathon? {}\", is_a_marathon(&distance_km.to_miles()));\n // println!(\"Is a marathon? {}\", is_a_marathon(&distance_km));\n}\n```\nUncomment the last print statement to observe that the type supplied must be `Miles`.\nTo obtain the `newtype`'s value as the base type, you may use the tuple or destructuring syntax like so:\n```rust, editable\nstruct Miles(f64);\n\nfn main() {\n let distance = Miles(42.0);\n let distance_as_primitive_1: f64 = distance.0; // Tuple\n let Miles(distance_as_primitive_2) = distance; // Destructuring\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "New Type Idiom", "heading_path": ["New Type Idiom"], "path": "generics/new_types.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/new_types.html#new-type-idiom", "has_code": true, "code_tags": ["rust, editable"]}} {"id": "rust-by-example/generics/new_types.md#see-also-1", "text": "Rust by Example › New Type Idiom › See also:\n\n`structs`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "New Type Idiom", "heading_path": ["New Type Idiom", "See also:"], "path": "generics/new_types.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/new_types.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/generics/assoc_items.md#associated-items-0", "text": "Rust by Example › Associated items\n\n\"Associated Items\" refers to a set of rules pertaining to `item`s\nof various types. It is an extension to `trait` generics, and allows\n`trait`s to internally define new items.\nOne such item is called an *associated type*, providing simpler usage\npatterns when the `trait` is generic over its container type.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Associated items", "heading_path": ["Associated items"], "path": "generics/assoc_items.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/assoc_items.html#associated-items", "has_code": false, "code_tags": []}} {"id": "rust-by-example/generics/assoc_items.md#see-also-1", "text": "Rust by Example › Associated items › See also:\n\nRFC", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Associated items", "heading_path": ["Associated items", "See also:"], "path": "generics/assoc_items.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/assoc_items.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/generics/assoc_items/the_problem.md#the-problem-0", "text": "Rust by Example › The Problem\n\nA `trait` that is generic over its container type has type specification\nrequirements - users of the `trait` *must* specify all of its generic types.\nIn the example below, the `Contains` `trait` allows the use of the generic\ntypes `A` and `B`. The trait is then implemented for the `Container` type,\nspecifying `i32` for `A` and `B` so that it can be used with `fn difference()`.\nBecause `Contains` is generic, we are forced to explicitly state *all* of the\ngeneric types for `fn difference()`. In practice, we want a way to express that\n`A` and `B` are determined by the *input* `C`. As you will see in the next\nsection, associated types provide exactly that capability.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "The Problem", "heading_path": ["The Problem"], "path": "generics/assoc_items/the_problem.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/assoc_items/the_problem.html#the-problem", "has_code": false, "code_tags": []}} {"id": "rust-by-example/generics/assoc_items/the_problem.md#the-problem-1", "text": "Rust by Example › The Problem\n\n```rust,editable\nstruct Container(i32, i32);\n\n// A trait which checks if 2 items are stored inside of container.\n// Also retrieves first or last value.\ntrait Contains {\n fn contains(&self, _: &A, _: &B) -> bool; // Explicitly requires `A` and `B`.\n fn first(&self) -> i32; // Doesn't explicitly require `A` or `B`.\n fn last(&self) -> i32; // Doesn't explicitly require `A` or `B`.\n}\n\nimpl Contains for Container {\n // True if the numbers stored are equal.\n fn contains(&self, number_1: &i32, number_2: &i32) -> bool {\n (&self.0 == number_1) && (&self.1 == number_2)\n }\n\n // Grab the first number.\n fn first(&self) -> i32 { self.0 }\n\n // Grab the last number.\n fn last(&self) -> i32 { self.1 }\n}\n\n// `C` contains `A` and `B`. In light of that, having to express `A` and\n// `B` again is a nuisance.\nfn difference(container: &C) -> i32 where\n C: Contains {\n container.last() - container.first()\n}\n\nfn main() {\n let number_1 = 3;\n let number_2 = 10;\n\n let container = Container(number_1, number_2);\n\n println!(\"Does container contain {} and {}: {}\",\n &number_1, &number_2,\n container.contains(&number_1, &number_2));\n println!(\"First number: {}\", container.first());\n println!(\"Last number: {}\", container.last());\n\n println!(\"The difference is: {}\", difference(&container));\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "The Problem", "heading_path": ["The Problem"], "path": "generics/assoc_items/the_problem.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/assoc_items/the_problem.html#the-problem", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/generics/assoc_items/the_problem.md#see-also-2", "text": "Rust by Example › The Problem › See also:\n\n`struct`s, and `trait`s", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "The Problem", "heading_path": ["The Problem", "See also:"], "path": "generics/assoc_items/the_problem.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/assoc_items/the_problem.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/generics/assoc_items/types.md#associated-types-0", "text": "Rust by Example › Associated types\n\nThe use of \"Associated types\" improves the overall readability of code\nby moving inner types locally into a trait as *output* types. Syntax\nfor the `trait` definition is as follows:\n```rust\n// `A` and `B` are defined in the trait via the `type` keyword.\n// (Note: `type` in this context is different from `type` when used for\n// aliases).\ntrait Contains {\n type A;\n type B;\n\n // Updated syntax to refer to these new types generically.\n fn contains(&self, _: &Self::A, _: &Self::B) -> bool;\n}\n```\nNote that functions that use the `trait` `Contains` are no longer required\nto express `A` or `B` at all:\n```rust,ignore\n// Without using associated types\nfn difference(container: &C) -> i32 where\n C: Contains { ... }\n\n// Using associated types\nfn difference(container: &C) -> i32 { ... }\n```\nLet's rewrite the example from the previous section using associated types:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Associated types", "heading_path": ["Associated types"], "path": "generics/assoc_items/types.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/assoc_items/types.html#associated-types", "has_code": true, "code_tags": ["rust", "rust,ignore"]}} {"id": "rust-by-example/generics/assoc_items/types.md#associated-types-1", "text": "Rust by Example › Associated types\n\n```rust,editable\nstruct Container(i32, i32);\n\n// A trait which checks if 2 items are stored inside of container.\n// Also retrieves first or last value.\ntrait Contains {\n // Define generic types here which methods will be able to utilize.\n type A;\n type B;\n\n fn contains(&self, _: &Self::A, _: &Self::B) -> bool;\n fn first(&self) -> i32;\n fn last(&self) -> i32;\n}\n\nimpl Contains for Container {\n // Specify what types `A` and `B` are. If the `input` type\n // is `Container(i32, i32)`, the `output` types are determined\n // as `i32` and `i32`.\n type A = i32;\n type B = i32;\n\n // `&Self::A` and `&Self::B` are also valid here.\n fn contains(&self, number_1: &i32, number_2: &i32) -> bool {\n (&self.0 == number_1) && (&self.1 == number_2)\n }\n // Grab the first number.\n fn first(&self) -> i32 { self.0 }\n\n // Grab the last number.\n fn last(&self) -> i32 { self.1 }\n}\n\nfn difference(container: &C) -> i32 {\n container.last() - container.first()\n}\n\nfn main() {\n let number_1 = 3;\n let number_2 = 10;\n\n let container = Container(number_1, number_2);\n\n println!(\"Does container contain {} and {}: {}\",\n &number_1, &number_2,\n container.contains(&number_1, &number_2));\n println!(\"First number: {}\", container.first());\n println!(\"Last number: {}\", container.last());\n\n println!(\"The difference is: {}\", difference(&container));\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Associated types", "heading_path": ["Associated types"], "path": "generics/assoc_items/types.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/assoc_items/types.html#associated-types", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/generics/phantom.md#phantom-type-parameters-0", "text": "Rust by Example › Phantom type parameters\n\nA phantom type parameter is one that doesn't show up at runtime,\nbut is checked statically (and only) at compile time.\nData types can use extra generic type parameters to act as markers\nor to perform type checking at compile time. These extra parameters\nhold no storage values, and have no runtime behavior.\nIn the following example, we combine [std::marker::PhantomData]\nwith the phantom type parameter concept to create tuples containing\ndifferent data types.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Phantom type parameters", "heading_path": ["Phantom type parameters"], "path": "generics/phantom.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/phantom.html#phantom-type-parameters", "has_code": false, "code_tags": []}} {"id": "rust-by-example/generics/phantom.md#phantom-type-parameters-1", "text": "Rust by Example › Phantom type parameters\n\n```rust,editable\nuse std::marker::PhantomData;\n\n// A phantom tuple struct which is generic over `A` with hidden parameter `B`.\n#[derive(PartialEq)] // Allow equality test for this type.\nstruct PhantomTuple(A, PhantomData);\n\n// A phantom type struct which is generic over `A` with hidden parameter `B`.\n#[derive(PartialEq)] // Allow equality test for this type.\nstruct PhantomStruct { first: A, phantom: PhantomData }\n\n// Note: Storage is allocated for generic type `A`, but not for `B`.\n// Therefore, `B` cannot be used in computations.\n\nfn main() {\n // Here, `f32` and `f64` are the hidden parameters.\n // PhantomTuple type specified as ``.\n let _tuple1: PhantomTuple = PhantomTuple('Q', PhantomData);\n // PhantomTuple type specified as ``.\n let _tuple2: PhantomTuple = PhantomTuple('Q', PhantomData);\n\n // Type specified as ``.\n let _struct1: PhantomStruct = PhantomStruct {\n first: 'Q',\n phantom: PhantomData,\n };\n // Type specified as ``.\n let _struct2: PhantomStruct = PhantomStruct {\n first: 'Q',\n phantom: PhantomData,\n };\n\n // Compile-time Error! Type mismatch so these cannot be compared:\n // println!(\"_tuple1 == _tuple2 yields: {}\",\n // _tuple1 == _tuple2);\n\n // Compile-time Error! Type mismatch so these cannot be compared:\n // println!(\"_struct1 == _struct2 yields: {}\",\n // _struct1 == _struct2);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Phantom type parameters", "heading_path": ["Phantom type parameters"], "path": "generics/phantom.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/phantom.html#phantom-type-parameters", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/generics/phantom.md#see-also-2", "text": "Rust by Example › Phantom type parameters › See also:\n\n[Derive], [struct], and tuple.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Phantom type parameters", "heading_path": ["Phantom type parameters", "See also:"], "path": "generics/phantom.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/phantom.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/generics/phantom/testcase_units.md#testcase-unit-clarification-0", "text": "Rust by Example › Testcase: unit clarification\n\nA useful method of unit conversions can be examined by implementing `Add`\nwith a phantom type parameter. The `Add` `trait` is examined below:\n```rust,ignore\n// This construction would impose: `Self + RHS = Output`\n// where RHS defaults to Self if not specified in the implementation.\npub trait Add {\n type Output;\n\n fn add(self, rhs: RHS) -> Self::Output;\n}\n\n// `Output` must be `T` so that `T + T = T`.\nimpl Add for T {\n type Output = T;\n ...\n}\n```\nThe whole implementation:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Testcase: unit clarification", "heading_path": ["Testcase: unit clarification"], "path": "generics/phantom/testcase_units.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/phantom/testcase_units.html#testcase-unit-clarification", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "rust-by-example/generics/phantom/testcase_units.md#testcase-unit-clarification-1", "text": "Rust by Example › Testcase: unit clarification\n\n```rust,editable\nuse std::ops::Add;\nuse std::marker::PhantomData;\n\n/// Create void enumerations to define unit types.\n#[derive(Debug, Clone, Copy)]\nenum Inch {}\n#[derive(Debug, Clone, Copy)]\nenum Mm {}\n\n/// `Length` is a type with phantom type parameter `Unit`,\n/// and is not generic over the length type (that is `f64`).\n///\n/// `f64` already implements the `Clone` and `Copy` traits.\n#[derive(Debug, Clone, Copy)]\nstruct Length(f64, PhantomData);\n\n/// The `Add` trait defines the behavior of the `+` operator.\nimpl Add for Length {\n type Output = Length;\n\n // add() returns a new `Length` struct containing the sum.\n fn add(self, rhs: Length) -> Length {\n // `+` calls the `Add` implementation for `f64`.\n Length(self.0 + rhs.0, PhantomData)\n }\n}\n\nfn main() {\n // Specifies `one_foot` to have phantom type parameter `Inch`.\n let one_foot: Length = Length(12.0, PhantomData);\n // `one_meter` has phantom type parameter `Mm`.\n let one_meter: Length = Length(1000.0, PhantomData);\n\n // `+` calls the `add()` method we implemented for `Length`.\n //\n // Since `Length` implements `Copy`, `add()` does not consume\n // `one_foot` and `one_meter` but copies them into `self` and `rhs`.\n let two_feet = one_foot + one_foot;\n let two_meters = one_meter + one_meter;\n\n // Addition works.\n println!(\"one foot + one_foot = {:?} in\", two_feet.0);\n println!(\"one meter + one_meter = {:?} mm\", two_meters.0);\n\n // Nonsensical operations fail as they should:\n // Compile-time Error: type mismatch.\n //let one_feter = one_foot + one_meter;\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Testcase: unit clarification", "heading_path": ["Testcase: unit clarification"], "path": "generics/phantom/testcase_units.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/phantom/testcase_units.html#testcase-unit-clarification", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/generics/phantom/testcase_units.md#see-also-2", "text": "Rust by Example › Testcase: unit clarification › See also:\n\n[Borrowing (`&`)], [Bounds (`X: Y`)], [enum], [impl & self],\n[Overloading], [ref], [Traits (`X for Y`)], and [TupleStructs].", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Testcase: unit clarification", "heading_path": ["Testcase: unit clarification", "See also:"], "path": "generics/phantom/testcase_units.md", "url": "https://doc.rust-lang.org/rust-by-example/generics/phantom/testcase_units.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/scope.md#scoping-rules-0", "text": "Rust by Example › Scoping rules\n\nScopes play an important part in ownership, borrowing, and lifetimes.\nThat is, they indicate to the compiler when borrows are valid, when\nresources can be freed, and when variables are created or destroyed.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Scoping rules", "heading_path": ["Scoping rules"], "path": "scope.md", "url": "https://doc.rust-lang.org/rust-by-example/scope.html#scoping-rules", "has_code": false, "code_tags": []}} {"id": "rust-by-example/scope/raii.md#raii-0", "text": "Rust by Example › RAII\n\nVariables in Rust do more than just hold data in the stack: they also *own*\nresources, e.g. `Box` owns memory in the heap. Rust enforces RAII\n(Resource Acquisition Is Initialization), so whenever an object goes out of\nscope, its destructor is called and its owned resources are freed.\nThis behavior shields against *resource leak* bugs, so you'll never have to\nmanually free memory or worry about memory leaks again! Here's a quick showcase:\n```rust,editable\n// raii.rs\nfn create_box() {\n // Allocate an integer on the heap\n let _box1 = Box::new(3i32);\n\n // `_box1` is destroyed here, and memory gets freed\n}\n\nfn main() {\n // Allocate an integer on the heap\n let _box2 = Box::new(5i32);\n\n // A nested scope:\n {\n // Allocate an integer on the heap\n let _box3 = Box::new(4i32);\n\n // `_box3` is destroyed here, and memory gets freed\n }\n\n // Creating lots of boxes just for fun\n // There's no need to manually free memory!\n for _ in 0u32..1_000 {\n create_box();\n }\n\n // `_box2` is destroyed here, and memory gets freed\n}\n```\nOf course, we can double check for memory errors using `valgrind`:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "RAII", "heading_path": ["RAII"], "path": "scope/raii.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/raii.html#raii", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/scope/raii.md#raii-1", "text": "Rust by Example › RAII\n\n```shell\n$ rustc raii.rs && valgrind ./raii\n==26873== Memcheck, a memory error detector\n==26873== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.\n==26873== Using Valgrind-3.9.0 and LibVEX; rerun with -h for copyright info\n==26873== Command: ./raii\n==26873==\n==26873==\n==26873== HEAP SUMMARY:\n==26873== in use at exit: 0 bytes in 0 blocks\n==26873== total heap usage: 1,013 allocs, 1,013 frees, 8,696 bytes allocated\n==26873==\n==26873== All heap blocks were freed -- no leaks are possible\n==26873==\n==26873== For counts of detected and suppressed errors, rerun with: -v\n==26873== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)\n```\nNo leaks here!", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "RAII", "heading_path": ["RAII"], "path": "scope/raii.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/raii.html#raii", "has_code": true, "code_tags": ["shell"]}} {"id": "rust-by-example/scope/raii.md#destructor-2", "text": "Rust by Example › RAII › Destructor\n\nThe notion of a destructor in Rust is provided through the [`Drop`] trait. The\ndestructor is called when the resource goes out of scope. This trait is not\nrequired to be implemented for every type, only implement it for your type if\nyou require its own destructor logic.\nRun the below example to see how the [`Drop`] trait works. When the variable in\nthe `main` function goes out of scope the custom destructor will be invoked.\n```rust,editable\nstruct ToDrop;\n\nimpl Drop for ToDrop {\n fn drop(&mut self) {\n println!(\"ToDrop is being dropped\");\n }\n}\n\nfn main() {\n let x = ToDrop;\n println!(\"Made a ToDrop!\");\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "RAII", "heading_path": ["RAII", "Destructor"], "path": "scope/raii.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/raii.html#destructor", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/scope/raii.md#see-also-3", "text": "Rust by Example › RAII › Destructor › See also:\n\nBox", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "RAII", "heading_path": ["RAII", "Destructor", "See also:"], "path": "scope/raii.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/raii.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/scope/move.md#ownership-and-moves-0", "text": "Rust by Example › Ownership and moves\n\nBecause variables are in charge of freeing their own resources,\n**resources can only have one owner**. This prevents resources\nfrom being freed more than once. Note that not all variables own\nresources (e.g. [references]).\nWhen doing assignments (`let x = y`) or passing function arguments by value\n(`foo(x)`), the *ownership* of the resources is transferred. In Rust-speak,\nthis is known as a *move*.\nAfter moving resources, the previous owner can no longer be used. This avoids\ncreating dangling pointers.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Ownership and moves", "heading_path": ["Ownership and moves"], "path": "scope/move.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/move.html#ownership-and-moves", "has_code": false, "code_tags": []}} {"id": "rust-by-example/scope/move.md#ownership-and-moves-1", "text": "Rust by Example › Ownership and moves\n\n```rust,editable\n// This function takes ownership of the heap allocated memory\nfn destroy_box(c: Box) {\n println!(\"Destroying a box that contains {}\", c);\n\n // `c` is destroyed and the memory freed\n}\n\nfn main() {\n // _Stack_ allocated integer\n let x = 5u32;\n\n // *Copy* `x` into `y` - no resources are moved\n let y = x;\n\n // Both values can be independently used\n println!(\"x is {}, and y is {}\", x, y);\n\n // `a` is a pointer to a _heap_ allocated integer\n let a = Box::new(5i32);\n\n println!(\"a contains: {}\", a);\n\n // *Move* `a` into `b`\n let b = a;\n // The pointer address of `a` is copied (not the data) into `b`.\n // Both are now pointers to the same heap allocated data, but\n // `b` now owns it.\n\n // Error! `a` can no longer access the data, because it no longer owns the\n // heap memory\n //println!(\"a contains: {}\", a);\n // TODO ^ Try uncommenting this line\n\n // This function takes ownership of the heap allocated memory from `b`\n destroy_box(b);\n\n // Since the heap memory has been freed at this point, this action would\n // result in dereferencing freed memory, but it's forbidden by the compiler\n // Error! Same reason as the previous Error\n //println!(\"b contains: {}\", b);\n // TODO ^ Try uncommenting this line\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Ownership and moves", "heading_path": ["Ownership and moves"], "path": "scope/move.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/move.html#ownership-and-moves", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/scope/move/mut.md#mutability-0", "text": "Rust by Example › Mutability\n\nMutability of data can be changed when ownership is transferred.\n```rust,editable\nfn main() {\n let immutable_box = Box::new(5u32);\n\n println!(\"immutable_box contains {}\", immutable_box);\n\n // Mutability error\n //*immutable_box = 4;\n\n // *Move* the box, changing the ownership (and mutability)\n let mut mutable_box = immutable_box;\n\n println!(\"mutable_box contains {}\", mutable_box);\n\n // Modify the contents of the box\n *mutable_box = 4;\n\n println!(\"mutable_box now contains {}\", mutable_box);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Mutability", "heading_path": ["Mutability"], "path": "scope/move/mut.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/move/mut.html#mutability", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/scope/move/partial_move.md#partial-moves-0", "text": "Rust by Example › Partial moves\n\nWithin the [destructuring] of a single variable, both `by-move` and\n`by-reference` pattern bindings can be used at the same time. Doing\nthis will result in a _partial move_ of the variable, which means\nthat parts of the variable will be moved while other parts stay. In\nsuch a case, the parent variable cannot be used afterwards as a\nwhole, however the parts that are only referenced (and not moved)\ncan still be used. Note that types that implement the\n`Drop` trait cannot be partially moved from, because\nits `drop` method would use it afterwards as a whole.\n```rust,editable\nfn main() {\n #[derive(Debug)]\n struct Person {\n name: String,\n age: Box,\n }\n\n // Error! cannot move out of a type which implements the `Drop` trait\n //impl Drop for Person {\n // fn drop(&mut self) {\n // println!(\"Dropping the person struct {:?}\", self)\n // }\n //}\n // TODO ^ Try uncommenting these lines\n\n let person = Person {\n name: String::from(\"Alice\"),\n age: Box::new(20),\n };\n\n // `name` is moved out of person, but `age` is referenced\n let Person { name, ref age } = person;\n\n println!(\"The person's age is {}\", age);\n\n println!(\"The person's name is {}\", name);\n\n // Error! borrow of partially moved value: `person` partial move occurs\n //println!(\"The person struct is {:?}\", person);\n\n // `person` cannot be used but `person.age` can be used as it is not moved\n println!(\"The person's age from person struct is {}\", person.age);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Partial moves", "heading_path": ["Partial moves"], "path": "scope/move/partial_move.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/move/partial_move.html#partial-moves", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/scope/move/partial_move.md#partial-moves-1", "text": "Rust by Example › Partial moves\n\n(In this example, we store the `age` variable on the heap to\nillustrate the partial move: deleting `ref` in the above code would\ngive an error as the ownership of `person.age` would be moved to the\nvariable `age`. If `Person.age` were stored on the stack, `ref` would\nnot be required as the definition of `age` would copy the data from\n`person.age` without moving it.)", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Partial moves", "heading_path": ["Partial moves"], "path": "scope/move/partial_move.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/move/partial_move.html#partial-moves", "has_code": false, "code_tags": []}} {"id": "rust-by-example/scope/move/partial_move.md#see-also-2", "text": "Rust by Example › Partial moves › See also:\n\ndestructuring", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Partial moves", "heading_path": ["Partial moves", "See also:"], "path": "scope/move/partial_move.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/move/partial_move.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/scope/borrow.md#borrowing-0", "text": "Rust by Example › Borrowing\n\nMost of the time, we'd like to access data without taking ownership over\nit. To accomplish this, Rust uses a *borrowing* mechanism. Instead of\npassing objects by value (`T`), objects can be passed by reference (`&T`).\nThe compiler statically guarantees (via its borrow checker) that references\n*always* point to valid objects. That is, while references to an object\nexist, the object cannot be destroyed.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Borrowing", "heading_path": ["Borrowing"], "path": "scope/borrow.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/borrow.html#borrowing", "has_code": false, "code_tags": []}} {"id": "rust-by-example/scope/borrow.md#borrowing-1", "text": "Rust by Example › Borrowing\n\n```rust,editable,ignore,mdbook-runnable\n// This function takes ownership of a box and destroys it\nfn eat_box_i32(boxed_i32: Box) {\n println!(\"Destroying box that contains {}\", boxed_i32);\n}\n\n// This function borrows an i32\nfn borrow_i32(borrowed_i32: &i32) {\n println!(\"This int is: {}\", borrowed_i32);\n}\n\nfn main() {\n // Create a boxed i32 in the heap, and an i32 on the stack\n // Remember: numbers can have arbitrary underscores added for readability\n // 5_i32 is the same as 5i32\n let boxed_i32 = Box::new(5_i32);\n let stacked_i32 = 6_i32;\n\n // Borrow the contents of the box. Ownership is not taken,\n // so the contents can be borrowed again.\n borrow_i32(&boxed_i32);\n borrow_i32(&stacked_i32);\n\n {\n // Take a reference to the data contained inside the box\n let _ref_to_i32: &i32 = &boxed_i32;\n\n // Error!\n // Can't destroy `boxed_i32` while the inner value is borrowed later in scope.\n eat_box_i32(boxed_i32);\n // FIXME ^ Comment out this line\n\n // Attempt to borrow `_ref_to_i32` after inner value is destroyed\n borrow_i32(_ref_to_i32);\n // `_ref_to_i32` goes out of scope and is no longer borrowed.\n }\n\n // `boxed_i32` can now give up ownership to `eat_box_i32` and be destroyed\n eat_box_i32(boxed_i32);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Borrowing", "heading_path": ["Borrowing"], "path": "scope/borrow.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/borrow.html#borrowing", "has_code": true, "code_tags": ["rust,editable,ignore,mdbook-runnable"]}} {"id": "rust-by-example/scope/borrow/mut.md#mutability-0", "text": "Rust by Example › Mutability\n\nMutable data can be mutably borrowed using `&mut T`. This is called\na *mutable reference* and gives read/write access to the borrower.\nIn contrast, `&T` borrows the data via an immutable reference, and\nthe borrower can read the data but not modify it:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Mutability", "heading_path": ["Mutability"], "path": "scope/borrow/mut.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/borrow/mut.html#mutability", "has_code": false, "code_tags": []}} {"id": "rust-by-example/scope/borrow/mut.md#mutability-1", "text": "Rust by Example › Mutability\n\n```rust,editable,ignore,mdbook-runnable\n#[allow(dead_code)]\n#[derive(Clone, Copy)]\nstruct Book {\n // `&'static str` is a reference to a string allocated in read only memory\n author: &'static str,\n title: &'static str,\n year: u32,\n}\n\n// This function takes a reference to a book\nfn borrow_book(book: &Book) {\n println!(\"I immutably borrowed {} - {} edition\", book.title, book.year);\n}\n\n// This function takes a reference to a mutable book and changes `year` to 2014\nfn new_edition(book: &mut Book) {\n book.year = 2014;\n println!(\"I mutably borrowed {} - {} edition\", book.title, book.year);\n}\n\nfn main() {\n // Create an immutable Book named `immutabook`\n let immutabook = Book {\n // string literals have type `&'static str`\n author: \"Douglas Hofstadter\",\n title: \"Gödel, Escher, Bach\",\n year: 1979,\n };\n\n // Create a mutable copy of `immutabook` and call it `mutabook`\n let mut mutabook = immutabook;\n\n // Immutably borrow an immutable object\n borrow_book(&immutabook);\n\n // Immutably borrow a mutable object\n borrow_book(&mutabook);\n\n // Borrow a mutable object as mutable\n new_edition(&mut mutabook);\n\n // Error! Cannot borrow an immutable object as mutable\n new_edition(&mut immutabook);\n // FIXME ^ Comment out this line\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Mutability", "heading_path": ["Mutability"], "path": "scope/borrow/mut.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/borrow/mut.html#mutability", "has_code": true, "code_tags": ["rust,editable,ignore,mdbook-runnable"]}} {"id": "rust-by-example/scope/borrow/mut.md#see-also-2", "text": "Rust by Example › Mutability › See also:\n\n`static`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Mutability", "heading_path": ["Mutability", "See also:"], "path": "scope/borrow/mut.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/borrow/mut.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/scope/borrow/alias.md#aliasing-0", "text": "Rust by Example › Aliasing\n\nData can be immutably borrowed any number of times, but while immutably\nborrowed, the original data can't be mutably borrowed. On the other hand, only\n*one* mutable borrow is allowed at a time. The original data can be borrowed\nagain only *after* the mutable reference has been used for the last time.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Aliasing", "heading_path": ["Aliasing"], "path": "scope/borrow/alias.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/borrow/alias.html#aliasing", "has_code": false, "code_tags": []}} {"id": "rust-by-example/scope/borrow/alias.md#aliasing-1", "text": "Rust by Example › Aliasing\n\n```rust,editable\nstruct Point { x: i32, y: i32, z: i32 }\n\nfn main() {\n let mut point = Point { x: 0, y: 0, z: 0 };\n\n let borrowed_point = &point;\n let another_borrow = &point;\n\n // Data can be accessed via the references and the original owner\n println!(\"Point has coordinates: ({}, {}, {})\",\n borrowed_point.x, another_borrow.y, point.z);\n\n // Error! Can't borrow `point` as mutable because it's currently\n // borrowed as immutable.\n // let mutable_borrow = &mut point;\n // TODO ^ Try uncommenting this line\n\n // The borrowed values are used again here\n println!(\"Point has coordinates: ({}, {}, {})\",\n borrowed_point.x, another_borrow.y, point.z);\n\n // The immutable references are no longer used for the rest of the code so\n // it is possible to reborrow with a mutable reference.\n let mutable_borrow = &mut point;\n\n // Change data via mutable reference\n mutable_borrow.x = 5;\n mutable_borrow.y = 2;\n mutable_borrow.z = 1;\n\n // Error! Can't borrow `point` as immutable because it's currently\n // borrowed as mutable.\n // let y = &point.y;\n // TODO ^ Try uncommenting this line\n\n // Error! Can't print because `println!` takes an immutable reference.\n // println!(\"Point Z coordinate is {}\", point.z);\n // TODO ^ Try uncommenting this line\n\n // Ok! Mutable references can be passed as immutable to `println!`\n println!(\"Point has coordinates: ({}, {}, {})\",\n mutable_borrow.x, mutable_borrow.y, mutable_borrow.z);\n\n // The mutable reference is no longer used for the rest of the code so it\n // is possible to reborrow\n let new_borrowed_point = &point;\n println!(\"Point now has coordinates: ({}, {}, {})\",\n new_borrowed_point.x, new_borrowed_point.y, new_borrowed_point.z);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Aliasing", "heading_path": ["Aliasing"], "path": "scope/borrow/alias.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/borrow/alias.html#aliasing", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/scope/borrow/ref.md#the-ref-pattern-0", "text": "Rust by Example › The ref pattern\n\nWhen doing pattern matching or destructuring via the `let` binding, the `ref`\nkeyword can be used to take references to the fields of a struct/tuple. The\nexample below shows a few instances where this can be useful:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "The ref pattern", "heading_path": ["The ref pattern"], "path": "scope/borrow/ref.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/borrow/ref.html#the-ref-pattern", "has_code": false, "code_tags": []}} {"id": "rust-by-example/scope/borrow/ref.md#the-ref-pattern-1", "text": "Rust by Example › The ref pattern\n\n```rust,editable\n#[derive(Clone, Copy)]\nstruct Point { x: i32, y: i32 }\n\nfn main() {\n let c = 'Q';\n\n // A `ref` borrow on the left side of an assignment is equivalent to\n // an `&` borrow on the right side.\n let ref ref_c1 = c;\n let ref_c2 = &c;\n\n println!(\"ref_c1 equals ref_c2: {}\", *ref_c1 == *ref_c2);\n\n let point = Point { x: 0, y: 0 };\n\n // `ref` is also valid when destructuring a struct.\n let _copy_of_x = {\n // `ref_to_x` is a reference to the `x` field of `point`.\n let Point { x: ref ref_to_x, y: _ } = point;\n\n // Return a copy of the `x` field of `point`.\n *ref_to_x\n };\n\n // A mutable copy of `point`\n let mut mutable_point = point;\n\n {\n // `ref` can be paired with `mut` to take mutable references.\n let Point { x: _, y: ref mut mut_ref_to_y } = mutable_point;\n\n // Mutate the `y` field of `mutable_point` via a mutable reference.\n *mut_ref_to_y = 1;\n }\n\n println!(\"point is ({}, {})\", point.x, point.y);\n println!(\"mutable_point is ({}, {})\", mutable_point.x, mutable_point.y);\n\n // A mutable tuple that includes a pointer\n let mut mutable_tuple = (Box::new(5u32), 3u32);\n\n {\n // Destructure `mutable_tuple` to change the value of `last`.\n let (_, ref mut last) = mutable_tuple;\n *last = 2u32;\n }\n\n println!(\"tuple is {:?}\", mutable_tuple);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "The ref pattern", "heading_path": ["The ref pattern"], "path": "scope/borrow/ref.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/borrow/ref.html#the-ref-pattern", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/scope/lifetime.md#lifetimes-0", "text": "Rust by Example › Lifetimes\n\nA *lifetime* is a construct the compiler (or more specifically, its *borrow\nchecker*) uses to ensure all borrows are valid. Specifically, a variable's\nlifetime begins when it is created and ends when it is destroyed. While\nlifetimes and scopes are often referred to together, they are not the same.\nTake, for example, the case where we borrow a variable via `&`. The\nborrow has a lifetime that is determined by where it is declared. As a result,\nthe borrow is valid as long as it ends before the lender is destroyed. However,\nthe scope of the borrow is determined by where the reference is used.\nIn the following example and in the rest of this section, we will see how\nlifetimes relate to scopes, as well as how the two differ.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Lifetimes", "heading_path": ["Lifetimes"], "path": "scope/lifetime.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/lifetime.html#lifetimes", "has_code": false, "code_tags": []}} {"id": "rust-by-example/scope/lifetime.md#lifetimes-1", "text": "Rust by Example › Lifetimes\n\n```rust,editable\n// Lifetimes are annotated below with lines denoting the creation\n// and destruction of each variable.\n// `i` has the longest lifetime because its scope entirely encloses\n// both `borrow1` and `borrow2`. The duration of `borrow1` compared\n// to `borrow2` is irrelevant since they are disjoint.\nfn main() {\n let i = 3; // Lifetime for `i` starts. ────────────────┐\n // │\n { // │\n let borrow1 = &i; // `borrow1` lifetime starts. ──┐│\n // ││\n println!(\"borrow1: {}\", borrow1); // ││\n } // `borrow1` ends. ─────────────────────────────────┘│\n // │\n // │\n { // │\n let borrow2 = &i; // `borrow2` lifetime starts. ──┐│\n // ││\n println!(\"borrow2: {}\", borrow2); // ││\n } // `borrow2` ends. ─────────────────────────────────┘│\n // │\n} // Lifetime ends. ─────────────────────────────────────┘\n```\nNote that no names or types are assigned to label lifetimes.\nThis restricts how lifetimes will be able to be used as we will see.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Lifetimes", "heading_path": ["Lifetimes"], "path": "scope/lifetime.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/lifetime.html#lifetimes", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/scope/lifetime/explicit.md#explicit-annotation-0", "text": "Rust by Example › Explicit annotation\n\nThe borrow checker uses explicit lifetime annotations to determine\nhow long references should be valid. In cases where lifetimes are not\nelided[^1], Rust requires explicit annotations to determine what the\nlifetime of a reference should be. The syntax for explicitly annotating\na lifetime uses an apostrophe character as follows:\n```rust,ignore\nfoo<'a>\n// `foo` has a lifetime parameter `'a`\n```\nSimilar to closures, using lifetimes requires generics.\nAdditionally, this lifetime syntax indicates that the lifetime of `foo`\nmay not exceed that of `'a`. Explicit annotation of a type has the form\n`&'a T` where `'a` has already been introduced.\nIn cases with multiple lifetimes, the syntax is similar:\n```rust,ignore\nfoo<'a, 'b>\n// `foo` has lifetime parameters `'a` and `'b`\n```\nIn this case, the lifetime of `foo` cannot exceed that of either `'a` *or* `'b`.\nSee the following example for explicit lifetime annotation in use:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Explicit annotation", "heading_path": ["Explicit annotation"], "path": "scope/lifetime/explicit.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/lifetime/explicit.html#explicit-annotation", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "rust-by-example/scope/lifetime/explicit.md#explicit-annotation-1", "text": "Rust by Example › Explicit annotation\n\n```rust,editable,ignore,mdbook-runnable\n// `print_refs` takes two references to `i32` which have different\n// lifetimes `'a` and `'b`. These two lifetimes must both be at\n// least as long as the function `print_refs`.\nfn print_refs<'a, 'b>(x: &'a i32, y: &'b i32) {\n println!(\"x is {} and y is {}\", x, y);\n}\n\n// A function which takes no arguments, but has a lifetime parameter `'a`.\nfn failed_borrow<'a>() {\n let _x = 12;\n\n // ERROR: `_x` does not live long enough\n let _y: &'a i32 = &_x;\n // Attempting to use the lifetime `'a` as an explicit type annotation\n // inside the function will fail because the lifetime of `&_x` is shorter\n // than that of `_y`. A short lifetime cannot be coerced into a longer one.\n}\n\nfn main() {\n // Create variables to be borrowed below.\n let (four, nine) = (4, 9);\n\n // Borrows (`&`) of both variables are passed into the function.\n print_refs(&four, &nine);\n // Any input which is borrowed must outlive the borrower.\n // In other words, the lifetime of `four` and `nine` must\n // be longer than that of `print_refs`.\n\n failed_borrow();\n // `failed_borrow` contains no references to force `'a` to be\n // longer than the lifetime of the function, but `'a` is longer.\n // Because the lifetime is never constrained, it defaults to `'static`.\n}\n```\n[^1]: [elision] implicitly annotates lifetimes and so is different.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Explicit annotation", "heading_path": ["Explicit annotation"], "path": "scope/lifetime/explicit.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/lifetime/explicit.html#explicit-annotation", "has_code": true, "code_tags": ["rust,editable,ignore,mdbook-runnable"]}} {"id": "rust-by-example/scope/lifetime/explicit.md#see-also-2", "text": "Rust by Example › Explicit annotation › See also:\n\ngenerics and closures", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Explicit annotation", "heading_path": ["Explicit annotation", "See also:"], "path": "scope/lifetime/explicit.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/lifetime/explicit.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/scope/lifetime/fn.md#functions-0", "text": "Rust by Example › Functions\n\nIgnoring [elision], function signatures with lifetimes have a few constraints:\n* any reference *must* have an annotated lifetime.\n* any reference being returned *must* have the same lifetime as an input or\nbe `static`.\nAdditionally, note that returning references without input is banned if it\nwould result in returning references to invalid data. The following example shows\noff some valid forms of functions with lifetimes:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Functions", "heading_path": ["Functions"], "path": "scope/lifetime/fn.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/lifetime/fn.html#functions", "has_code": false, "code_tags": []}} {"id": "rust-by-example/scope/lifetime/fn.md#functions-1", "text": "Rust by Example › Functions\n\n```rust,editable\n// One input reference with lifetime `'a` which must live\n// at least as long as the function.\nfn print_one<'a>(x: &'a i32) {\n println!(\"`print_one`: x is {}\", x);\n}\n\n// Mutable references are possible with lifetimes as well.\nfn add_one<'a>(x: &'a mut i32) {\n *x += 1;\n}\n\n// Multiple elements with different lifetimes. In this case, it\n// would be fine for both to have the same lifetime `'a`, but\n// in more complex cases, different lifetimes may be required.\nfn print_multi<'a, 'b>(x: &'a i32, y: &'b i32) {\n println!(\"`print_multi`: x is {}, y is {}\", x, y);\n}\n\n// Returning references that have been passed in is acceptable.\n// However, the correct lifetime must be returned.\nfn pass_x<'a, 'b>(x: &'a i32, _: &'b i32) -> &'a i32 { x }\n\n//fn invalid_output<'a>() -> &'a String { &String::from(\"foo\") }\n// The above is invalid: `'a` must live longer than the function.\n// Here, `&String::from(\"foo\")` would create a `String`, followed by a\n// reference. Then the data is dropped upon exiting the scope, leaving\n// a reference to invalid data to be returned.\n\nfn main() {\n let x = 7;\n let y = 9;\n\n print_one(&x);\n print_multi(&x, &y);\n\n let z = pass_x(&x, &y);\n print_one(z);\n\n let mut t = 3;\n add_one(&mut t);\n print_one(&t);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Functions", "heading_path": ["Functions"], "path": "scope/lifetime/fn.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/lifetime/fn.html#functions", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/scope/lifetime/fn.md#see-also-2", "text": "Rust by Example › Functions › See also:\n\nFunctions", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Functions", "heading_path": ["Functions", "See also:"], "path": "scope/lifetime/fn.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/lifetime/fn.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/scope/lifetime/methods.md#methods-0", "text": "Rust by Example › Methods\n\nMethods are annotated similarly to functions:\n```rust,editable\nstruct Owner(i32);\n\nimpl Owner {\n // Annotate lifetimes as in a standalone function.\n fn add_one<'a>(&'a mut self) { self.0 += 1; }\n fn print<'a>(&'a self) {\n println!(\"`print`: {}\", self.0);\n }\n}\n\nfn main() {\n let mut owner = Owner(18);\n\n owner.add_one();\n owner.print();\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Methods", "heading_path": ["Methods"], "path": "scope/lifetime/methods.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/lifetime/methods.html#methods", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/scope/lifetime/methods.md#see-also-1", "text": "Rust by Example › Methods › See also:\n\n[methods]", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Methods", "heading_path": ["Methods", "See also:"], "path": "scope/lifetime/methods.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/lifetime/methods.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/scope/lifetime/struct.md#structs-0", "text": "Rust by Example › Structs\n\nAnnotation of lifetimes in structures are also similar to functions:\n```rust,editable\n// A type `Borrowed` which houses a reference to an\n// `i32`. The reference to `i32` must outlive `Borrowed`.\n#[derive(Debug)]\nstruct Borrowed<'a>(&'a i32);\n\n// Similarly, both references here must outlive this structure.\n#[derive(Debug)]\nstruct NamedBorrowed<'a> {\n x: &'a i32,\n y: &'a i32,\n}\n\n// An enum which is either an `i32` or a reference to one.\n#[derive(Debug)]\nenum Either<'a> {\n Num(i32),\n Ref(&'a i32),\n}\n\nfn main() {\n let x = 18;\n let y = 15;\n\n let single = Borrowed(&x);\n let double = NamedBorrowed { x: &x, y: &y };\n let reference = Either::Ref(&x);\n let number = Either::Num(y);\n\n println!(\"x is borrowed in {:?}\", single);\n println!(\"x and y are borrowed in {:?}\", double);\n println!(\"x is borrowed in {:?}\", reference);\n println!(\"y is *not* borrowed in {:?}\", number);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Structs", "heading_path": ["Structs"], "path": "scope/lifetime/struct.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/lifetime/struct.html#structs", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/scope/lifetime/struct.md#see-also-1", "text": "Rust by Example › Structs › See also:\n\n`struct`s", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Structs", "heading_path": ["Structs", "See also:"], "path": "scope/lifetime/struct.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/lifetime/struct.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/scope/lifetime/trait.md#traits-0", "text": "Rust by Example › Traits\n\nAnnotation of lifetimes in trait methods basically are similar to functions.\nNote that `impl` may have annotation of lifetimes too.\n```rust,editable\n// A struct with annotation of lifetimes.\n#[derive(Debug)]\nstruct Borrowed<'a> {\n x: &'a i32,\n}\n\n// Annotate lifetimes to impl.\nimpl<'a> Default for Borrowed<'a> {\n fn default() -> Self {\n Self {\n x: &10,\n }\n }\n}\n\nfn main() {\n let b: Borrowed = Default::default();\n println!(\"b is {:?}\", b);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Traits", "heading_path": ["Traits"], "path": "scope/lifetime/trait.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/lifetime/trait.html#traits", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/scope/lifetime/trait.md#see-also-1", "text": "Rust by Example › Traits › See also:\n\n`trait`s", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Traits", "heading_path": ["Traits", "See also:"], "path": "scope/lifetime/trait.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/lifetime/trait.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/scope/lifetime/lifetime_bounds.md#bounds-0", "text": "Rust by Example › Bounds\n\nJust like generic types can be bounded, lifetimes (themselves generic)\nuse bounds as well. The `:` character has a slightly different meaning here,\nbut `+` is the same. Note how the following read:\n1. `T: 'a`: *All* references in `T` must outlive lifetime `'a`.\n2. `T: Trait + 'a`: Type `T` must implement trait `Trait` and *all* references\nin `T` must outlive `'a`.\nThe example below shows the above syntax in action used after keyword `where`:\n```rust,editable\nuse std::fmt::Debug; // Trait to bound with.\n\n#[derive(Debug)]\nstruct Ref<'a, T: 'a>(&'a T);\n// `Ref` contains a reference to a generic type `T` that has\n// some lifetime `'a` unknown by `Ref`. `T` is bounded such that any\n// *references* in `T` must outlive `'a`. Additionally, the lifetime\n// of `Ref` may not exceed `'a`.\n\n// A generic function which prints using the `Debug` trait.\nfn print(t: T) where\n T: Debug {\n println!(\"`print`: t is {:?}\", t);\n}\n\n// Here a reference to `T` is taken where `T` implements\n// `Debug` and all *references* in `T` outlive `'a`. In\n// addition, `'a` must outlive the function.\nfn print_ref<'a, T>(t: &'a T) where\n T: Debug + 'a {\n println!(\"`print_ref`: t is {:?}\", t);\n}\n\nfn main() {\n let x = 7;\n let ref_x = Ref(&x);\n\n print_ref(&ref_x);\n print(ref_x);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Bounds", "heading_path": ["Bounds"], "path": "scope/lifetime/lifetime_bounds.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/lifetime/lifetime_bounds.html#bounds", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/scope/lifetime/lifetime_bounds.md#see-also-1", "text": "Rust by Example › Bounds › See also:\n\ngenerics, bounds in generics, and\nmultiple bounds in generics", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Bounds", "heading_path": ["Bounds", "See also:"], "path": "scope/lifetime/lifetime_bounds.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/lifetime/lifetime_bounds.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/scope/lifetime/lifetime_coercion.md#coercion-0", "text": "Rust by Example › Coercion\n\nA longer lifetime can be coerced into a shorter one\nso that it works inside a scope it normally wouldn't work in.\nThis comes in the form of inferred coercion by the Rust compiler,\nand also in the form of declaring a lifetime difference:\n```rust,editable\n// Here, Rust infers a lifetime that is as short as possible.\n// The two references are then coerced to that lifetime.\nfn multiply<'a>(first: &'a i32, second: &'a i32) -> i32 {\n first * second\n}\n\n// `<'a: 'b, 'b>` reads as lifetime `'a` is at least as long as `'b`.\n// Here, we take in an `&'a i32` and return a `&'b i32` as a result of coercion.\nfn choose_first<'a: 'b, 'b>(first: &'a i32, _: &'b i32) -> &'b i32 {\n first\n}\n\nfn main() {\n let first = 2; // Longer lifetime\n\n {\n let second = 3; // Shorter lifetime\n\n println!(\"The product is {}\", multiply(&first, &second));\n println!(\"{} is the first\", choose_first(&first, &second));\n };\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Coercion", "heading_path": ["Coercion"], "path": "scope/lifetime/lifetime_coercion.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/lifetime/lifetime_coercion.html#coercion", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/scope/lifetime/static_lifetime.md#static-0", "text": "Rust by Example › Static\n\nRust has a few reserved lifetime names. One of those is `'static`. You\nmight encounter it in two situations:\n```rust, ignore\n// A reference with 'static lifetime:\nlet s: &'static str = \"hello world\";\n\n// 'static as part of a trait bound:\nfn generic(x: T) where T: 'static {}\n```\nBoth are related but subtly different and this is a common source for\nconfusion when learning Rust. Here are some examples for each situation:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Static", "heading_path": ["Static"], "path": "scope/lifetime/static_lifetime.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/lifetime/static_lifetime.html#static", "has_code": true, "code_tags": ["rust, ignore"]}} {"id": "rust-by-example/scope/lifetime/static_lifetime.md#reference-lifetime-1", "text": "Rust by Example › Static › Reference lifetime\n\nAs a reference lifetime `'static` indicates that the data pointed to by\nthe reference lives for the remaining lifetime of the running program.\nIt can still be coerced to a shorter lifetime.\nThere are two common ways to make a variable with `'static` lifetime, and both\nare stored in the read-only memory of the binary:\n* Make a constant with the `static` declaration.\n* Make a `string` literal which has type: `&'static str`.\nSee the following example for a display of each method:\n```rust,editable\n// Make a constant with `'static` lifetime.\nstatic NUM: i32 = 18;\n\n// Returns a reference to `NUM` where its `'static`\n// lifetime is coerced to that of the input argument.\nfn coerce_static<'a>(_: &'a i32) -> &'a i32 {\n &NUM\n}\n\nfn main() {\n {\n // Make a `string` literal and print it:\n let static_string = \"I'm in read-only memory\";\n println!(\"static_string: {}\", static_string);\n\n // When `static_string` goes out of scope, the reference\n // can no longer be used, but the data remains in the binary.\n }\n\n {\n // Make an integer to use for `coerce_static`:\n let lifetime_num = 9;\n\n // Coerce `NUM` to lifetime of `lifetime_num`:\n let coerced_static = coerce_static(&lifetime_num);\n\n println!(\"coerced_static: {}\", coerced_static);\n }\n\n println!(\"NUM: {} stays accessible!\", NUM);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Static", "heading_path": ["Static", "Reference lifetime"], "path": "scope/lifetime/static_lifetime.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/lifetime/static_lifetime.html#reference-lifetime", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/scope/lifetime/static_lifetime.md#reference-lifetime-2", "text": "Rust by Example › Static › Reference lifetime\n\nSince `'static` references only need to be valid for the _remainder_ of\na program's life, they can be created while the program is executed. Just to\ndemonstrate, the below example uses\n`Box::leak`\nto dynamically create `'static` references. In that case it definitely doesn't\nlive for the entire duration, but only from the leaking point onward.\n```rust,editable,compile_fail\nextern crate rand;\nuse rand::Fill;\n\nfn random_vec() -> &'static [u64; 100] {\n let mut rng = rand::rng();\n let mut boxed = Box::new([0; 100]);\n boxed.fill(&mut rng);\n Box::leak(boxed)\n}\n\nfn main() {\n let first: &'static [u64; 100] = random_vec();\n let second: &'static [u64; 100] = random_vec();\n assert_ne!(first, second)\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Static", "heading_path": ["Static", "Reference lifetime"], "path": "scope/lifetime/static_lifetime.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/lifetime/static_lifetime.html#reference-lifetime", "has_code": true, "code_tags": ["rust,editable,compile_fail"]}} {"id": "rust-by-example/scope/lifetime/static_lifetime.md#trait-bound-3", "text": "Rust by Example › Static › Trait bound\n\nAs a trait bound, it means the type does not contain any non-static\nreferences. Eg. the receiver can hold on to the type for as long as\nthey want and it will never become invalid until they drop it.\nIt's important to understand this means that any owned data always passes\na `'static` lifetime bound, but a reference to that owned data generally\ndoes not:\n```rust,editable,compile_fail\nuse std::fmt::Debug;\n\nfn print_it(input: impl Debug + 'static) {\n println!(\"'static value passed in is: {:?}\", input);\n}\n\nfn main() {\n // i is owned and contains no references, thus it's 'static:\n let i = 5;\n print_it(i);\n\n // oops, &i only has the lifetime defined by the scope of\n // main(), so it's not 'static:\n print_it(&i);\n}\n```\nThe compiler will tell you:\n```ignore\nerror[E0597]: `i` does not live long enough\n --> src/lib.rs:15:15\n |\n15 | print_it(&i);\n | ---------^^--\n | | |\n | | borrowed value does not live long enough\n | argument requires that `i` is borrowed for `'static`\n16 | }\n | - `i` dropped here while still borrowed\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Static", "heading_path": ["Static", "Trait bound"], "path": "scope/lifetime/static_lifetime.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/lifetime/static_lifetime.html#trait-bound", "has_code": true, "code_tags": ["ignore", "rust,editable,compile_fail"]}} {"id": "rust-by-example/scope/lifetime/static_lifetime.md#see-also-4", "text": "Rust by Example › Static › Trait bound › See also:\n\n`'static` constants", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Static", "heading_path": ["Static", "Trait bound", "See also:"], "path": "scope/lifetime/static_lifetime.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/lifetime/static_lifetime.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/scope/lifetime/elision.md#elision-0", "text": "Rust by Example › Elision\n\nSome lifetime patterns are overwhelmingly common and so the borrow checker\nwill allow you to omit them to save typing and to improve readability.\nThis is known as elision. Elision exists in Rust solely because these patterns\nare common.\nThe following code shows a few examples of elision. For a more comprehensive\ndescription of elision, see lifetime elision in the book.\n```rust,editable\n// `elided_input` and `annotated_input` essentially have identical signatures\n// because the lifetime of `elided_input` is inferred by the compiler:\nfn elided_input(x: &i32) {\n println!(\"`elided_input`: {}\", x);\n}\n\nfn annotated_input<'a>(x: &'a i32) {\n println!(\"`annotated_input`: {}\", x);\n}\n\n// Similarly, `elided_pass` and `annotated_pass` have identical signatures\n// because the lifetime is added implicitly to `elided_pass`:\nfn elided_pass(x: &i32) -> &i32 { x }\n\nfn annotated_pass<'a>(x: &'a i32) -> &'a i32 { x }\n\nfn main() {\n let x = 3;\n\n elided_input(&x);\n annotated_input(&x);\n\n println!(\"`elided_pass`: {}\", elided_pass(&x));\n println!(\"`annotated_pass`: {}\", annotated_pass(&x));\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Elision", "heading_path": ["Elision"], "path": "scope/lifetime/elision.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/lifetime/elision.html#elision", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/scope/lifetime/elision.md#see-also-1", "text": "Rust by Example › Elision › See also:\n\nelision", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Elision", "heading_path": ["Elision", "See also:"], "path": "scope/lifetime/elision.md", "url": "https://doc.rust-lang.org/rust-by-example/scope/lifetime/elision.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/trait.md#traits-0", "text": "Rust by Example › Traits\n\nA `trait` is a collection of methods defined for an unknown type:\n`Self`. They can access other methods declared in the same trait.\nTraits can be implemented for any data type. In the example below,\nwe define `Animal`, a group of methods. The `Animal` `trait` is\nthen implemented for the `Sheep` data type, allowing the use of\nmethods from `Animal` with a `Sheep`.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Traits", "heading_path": ["Traits"], "path": "trait.md", "url": "https://doc.rust-lang.org/rust-by-example/trait.html#traits", "has_code": false, "code_tags": []}} {"id": "rust-by-example/trait.md#traits-1", "text": "Rust by Example › Traits\n\n```rust,editable\nstruct Sheep { naked: bool, name: &'static str }\n\ntrait Animal {\n // Associated function signature; `Self` refers to the implementor type.\n fn new(name: &'static str) -> Self;\n\n // Method signatures; these will return a string.\n fn name(&self) -> &'static str;\n fn noise(&self) -> &'static str;\n\n // Traits can provide default method definitions.\n fn talk(&self) {\n println!(\"{} says {}\", self.name(), self.noise());\n }\n}\n\nimpl Sheep {\n fn is_naked(&self) -> bool {\n self.naked\n }\n\n fn shear(&mut self) {\n if self.is_naked() {\n // Implementor methods can use the implementor's trait methods.\n println!(\"{} is already naked...\", self.name());\n } else {\n println!(\"{} gets a haircut!\", self.name);\n\n self.naked = true;\n }\n }\n}\n\n// Implement the `Animal` trait for `Sheep`.\nimpl Animal for Sheep {\n // `Self` is the implementor type: `Sheep`.\n fn new(name: &'static str) -> Sheep {\n Sheep { name: name, naked: false }\n }\n\n fn name(&self) -> &'static str {\n self.name\n }\n\n fn noise(&self) -> &'static str {\n if self.is_naked() {\n \"baaaaah?\"\n } else {\n \"baaaaah!\"\n }\n }\n\n // Default trait methods can be overridden.\n fn talk(&self) {\n // For example, we can add some quiet contemplation.\n println!(\"{} pauses briefly... {}\", self.name, self.noise());\n }\n}\n\nfn main() {\n // Type annotation is necessary in this case.\n let mut dolly: Sheep = Animal::new(\"Dolly\");\n // TODO ^ Try removing the type annotations.\n\n dolly.talk();\n dolly.shear();\n dolly.talk();\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Traits", "heading_path": ["Traits"], "path": "trait.md", "url": "https://doc.rust-lang.org/rust-by-example/trait.html#traits", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/trait/derive.md#derive-0", "text": "Rust by Example › Derive\n\nThe compiler is capable of providing basic implementations for some traits via\nthe `#[derive]` attribute. These traits can still be\nmanually implemented if a more complex behavior is required.\nThe following is a list of derivable traits:\n* Comparison traits:\n `Eq`, `PartialEq`, `Ord`, `PartialOrd`.\n* `Clone`, to create `T` from `&T` via a copy.\n* `Copy`, to give a type 'copy semantics' instead of 'move semantics'.\n* `Hash`, to compute a hash from `&T`.\n* `Default`, to create an empty instance of a data type.\n* `Debug`, to format a value using the `{:?}` formatter.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Derive", "heading_path": ["Derive"], "path": "trait/derive.md", "url": "https://doc.rust-lang.org/rust-by-example/trait/derive.html#derive", "has_code": false, "code_tags": []}} {"id": "rust-by-example/trait/derive.md#derive-1", "text": "Rust by Example › Derive\n\n```rust,editable\n// `Centimeters`, a tuple struct that can be compared\n#[derive(PartialEq, PartialOrd)]\nstruct Centimeters(f64);\n\n// `Inches`, a tuple struct that can be printed\n#[derive(Debug)]\nstruct Inches(i32);\n\nimpl Inches {\n fn to_centimeters(&self) -> Centimeters {\n let &Inches(inches) = self;\n\n Centimeters(inches as f64 * 2.54)\n }\n}\n\n// `Seconds`, a tuple struct with no additional attributes\nstruct Seconds(i32);\n\nfn main() {\n let _one_second = Seconds(1);\n\n // Error: `Seconds` can't be printed; it doesn't implement the `Debug` trait\n //println!(\"One second looks like: {:?}\", _one_second);\n // TODO ^ Try uncommenting this line\n\n // Error: `Seconds` can't be compared; it doesn't implement the `PartialEq` trait\n //let _this_is_true = (_one_second == _one_second);\n // TODO ^ Try uncommenting this line\n\n let foot = Inches(12);\n\n println!(\"One foot equals {:?}\", foot);\n\n let meter = Centimeters(100.0);\n\n let cmp =\n if foot.to_centimeters() < meter {\n \"smaller\"\n } else {\n \"bigger\"\n };\n\n println!(\"One foot is {} than one meter.\", cmp);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Derive", "heading_path": ["Derive"], "path": "trait/derive.md", "url": "https://doc.rust-lang.org/rust-by-example/trait/derive.html#derive", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/trait/derive.md#see-also-2", "text": "Rust by Example › Derive › See also:\n\n`derive`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Derive", "heading_path": ["Derive", "See also:"], "path": "trait/derive.md", "url": "https://doc.rust-lang.org/rust-by-example/trait/derive.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/trait/dyn.md#returning-traits-with-dyn-0", "text": "Rust by Example › Returning Traits with `dyn`\n\nThe Rust compiler needs to know how much space every function's return type requires. This means all\nyour functions have to return a concrete type. Unlike other languages, if you have a trait like\n`Animal`, you can't write a function that returns `Animal`, because its different implementations\nwill need different amounts of memory.\nHowever, there's an easy workaround. Instead of returning a trait object directly, our functions\nreturn a `Box` which _contains_ some `Animal`. A `box` is just a reference to some memory in the\nheap. Because a reference has a statically-known size, and the compiler can guarantee it points to a\nheap-allocated `Animal`, we can return a trait from our function!\nRust tries to be as explicit as possible whenever it allocates memory on the heap. So if your\nfunction returns a pointer-to-trait-on-heap in this way, you need to write the return type with the\n`dyn` keyword, e.g. `Box`.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Returning Traits with `dyn`", "heading_path": ["Returning Traits with `dyn`"], "path": "trait/dyn.md", "url": "https://doc.rust-lang.org/rust-by-example/trait/dyn.html#returning-traits-with-dyn", "has_code": false, "code_tags": []}} {"id": "rust-by-example/trait/dyn.md#returning-traits-with-dyn-1", "text": "Rust by Example › Returning Traits with `dyn`\n\n```rust,editable\nstruct Sheep {}\nstruct Cow {}\n\ntrait Animal {\n // Instance method signature\n fn noise(&self) -> &'static str;\n}\n\n// Implement the `Animal` trait for `Sheep`.\nimpl Animal for Sheep {\n fn noise(&self) -> &'static str {\n \"baaaaah!\"\n }\n}\n\n// Implement the `Animal` trait for `Cow`.\nimpl Animal for Cow {\n fn noise(&self) -> &'static str {\n \"moooooo!\"\n }\n}\n\n// Returns some struct that implements Animal, but we don't know which one at compile time.\nfn random_animal(random_number: f64) -> Box {\n if random_number < 0.5 {\n Box::new(Sheep {})\n } else {\n Box::new(Cow {})\n }\n}\n\nfn main() {\n let random_number = 0.234;\n let animal = random_animal(random_number);\n println!(\"You've randomly chosen an animal, and it says {}\", animal.noise());\n}\n\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Returning Traits with `dyn`", "heading_path": ["Returning Traits with `dyn`"], "path": "trait/dyn.md", "url": "https://doc.rust-lang.org/rust-by-example/trait/dyn.html#returning-traits-with-dyn", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/trait/ops.md#operator-overloading-0", "text": "Rust by Example › Operator Overloading\n\nIn Rust, many of the operators can be overloaded via traits. That is, some operators can\nbe used to accomplish different tasks based on their input arguments. This is possible\nbecause operators are syntactic sugar for method calls. For example, the `+` operator in\n`a + b` calls the `add` method (as in `a.add(b)`). This `add` method is part of the `Add`\ntrait. Hence, the `+` operator can be used by any implementor of the `Add` trait.\nA list of the traits, such as `Add`, that overload operators can be found in `core::ops`.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Operator Overloading", "heading_path": ["Operator Overloading"], "path": "trait/ops.md", "url": "https://doc.rust-lang.org/rust-by-example/trait/ops.html#operator-overloading", "has_code": false, "code_tags": []}} {"id": "rust-by-example/trait/ops.md#operator-overloading-1", "text": "Rust by Example › Operator Overloading\n\n```rust,editable\nuse std::ops;\n\nstruct Foo;\nstruct Bar;\n\n#[derive(Debug)]\nstruct FooBar;\n\n#[derive(Debug)]\nstruct BarFoo;\n\n// The `std::ops::Add` trait is used to specify the functionality of `+`.\n// Here, we make `Add` - the trait for addition with a RHS of type `Bar`.\n// The following block implements the operation: Foo + Bar = FooBar\nimpl ops::Add for Foo {\n type Output = FooBar;\n\n fn add(self, _rhs: Bar) -> FooBar {\n println!(\"> Foo.add(Bar) was called\");\n\n FooBar\n }\n}\n\n// By reversing the types, we end up implementing non-commutative addition.\n// Here, we make `Add` - the trait for addition with a RHS of type `Foo`.\n// This block implements the operation: Bar + Foo = BarFoo\nimpl ops::Add for Bar {\n type Output = BarFoo;\n\n fn add(self, _rhs: Foo) -> BarFoo {\n println!(\"> Bar.add(Foo) was called\");\n\n BarFoo\n }\n}\n\nfn main() {\n println!(\"Foo + Bar = {:?}\", Foo + Bar);\n println!(\"Bar + Foo = {:?}\", Bar + Foo);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Operator Overloading", "heading_path": ["Operator Overloading"], "path": "trait/ops.md", "url": "https://doc.rust-lang.org/rust-by-example/trait/ops.html#operator-overloading", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/trait/ops.md#see-also-2", "text": "Rust by Example › Operator Overloading › See Also\n\nAdd, Syntax Index", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Operator Overloading", "heading_path": ["Operator Overloading", "See Also"], "path": "trait/ops.md", "url": "https://doc.rust-lang.org/rust-by-example/trait/ops.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/trait/drop.md#drop-0", "text": "Rust by Example › Drop\n\nThe `Drop` trait only has one method: `drop`, which is called automatically\nwhen an object goes out of scope. The main use of the `Drop` trait is to free the\nresources that the implementor instance owns.\n`Box`, `Vec`, `String`, `File`, and `Process` are some examples of types that\nimplement the `Drop` trait to free resources. The `Drop` trait can also be\nmanually implemented for any custom data type.\nThe following example adds a print to console to the `drop` function to announce\nwhen it is called.\n```rust,editable\nstruct Droppable {\n name: &'static str,\n}\n\n// This trivial implementation of `drop` adds a print to console.\nimpl Drop for Droppable {\n fn drop(&mut self) {\n println!(\"> Dropping {}\", self.name);\n }\n}\n\nfn main() {\n let _a = Droppable { name: \"a\" };\n\n // block A\n {\n let _b = Droppable { name: \"b\" };\n\n // block B\n {\n let _c = Droppable { name: \"c\" };\n let _d = Droppable { name: \"d\" };\n\n println!(\"Exiting block B\");\n }\n println!(\"Just exited block B\");\n\n println!(\"Exiting block A\");\n }\n println!(\"Just exited block A\");\n\n // Variable can be manually dropped using the `drop` function\n drop(_a);\n // TODO ^ Try commenting this line\n\n println!(\"end of the main function\");\n\n // `_a` *won't* be `drop`ed again here, because it already has been\n // (manually) `drop`ed\n}\n```\nFor a more practical example, here's how the `Drop` trait can be used to automatically\nclean up temporary files when they're no longer needed:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Drop", "heading_path": ["Drop"], "path": "trait/drop.md", "url": "https://doc.rust-lang.org/rust-by-example/trait/drop.html#drop", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/trait/drop.md#drop-1", "text": "Rust by Example › Drop\n\n```rust,editable\nuse std::fs::File;\nuse std::path::PathBuf;\n\nstruct TempFile {\n file: File,\n path: PathBuf,\n}\n\nimpl TempFile {\n fn new(path: PathBuf) -> std::io::Result {\n // Note: File::create() will overwrite existing files\n let file = File::create(&path)?;\n\n Ok(Self { file, path })\n }\n}\n\n// When TempFile is dropped:\n// 1. First, our custom drop implementation runs. The file is still open at this point,\n// but we can remove it from the filesystem by path.\n// 2. Then, after our drop returns, Rust automatically drops each field,\n// so File's drop runs and closes the file handle.\nimpl Drop for TempFile {\n fn drop(&mut self) {\n // Note: the File is still open here — field destructors run after this method.\n if let Err(e) = std::fs::remove_file(&self.path) {\n eprintln!(\"Failed to remove temporary file: {}\", e);\n }\n println!(\"> Dropped temporary file: {:?}\", self.path);\n // After this method returns, Rust will drop each field (including `file`),\n // which closes the underlying file handle.\n }\n}\n\nfn main() -> std::io::Result<()> {\n // Create a new scope to demonstrate drop behavior\n {\n let temp = TempFile::new(\"test.txt\".into())?;\n println!(\"Temporary file created\");\n // File will be automatically cleaned up when temp goes out of scope\n }\n println!(\"End of scope - file should be cleaned up\");\n\n // We can also manually drop if needed\n let temp2 = TempFile::new(\"another_test.txt\".into())?;\n drop(temp2); // Explicitly drop the file\n println!(\"Manually dropped file\");\n\n Ok(())\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Drop", "heading_path": ["Drop"], "path": "trait/drop.md", "url": "https://doc.rust-lang.org/rust-by-example/trait/drop.html#drop", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/trait/iter.md#iterators-0", "text": "Rust by Example › Iterators\n\nThe `Iterator` trait is used to implement iterators over collections\nsuch as arrays.\nThe trait requires only a method to be defined for the `next` element,\nwhich may be manually defined in an `impl` block or automatically\ndefined (as in arrays and ranges).\nAs a point of convenience for common situations, the `for` construct\nturns some collections into iterators using the `.into_iter()` method.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Iterators", "heading_path": ["Iterators"], "path": "trait/iter.md", "url": "https://doc.rust-lang.org/rust-by-example/trait/iter.html#iterators", "has_code": false, "code_tags": []}} {"id": "rust-by-example/trait/iter.md#iterators-1", "text": "Rust by Example › Iterators\n\n```rust,editable\nstruct Fibonacci {\n curr: u32,\n next: u32,\n}\n\n// Implement `Iterator` for `Fibonacci`.\n// The `Iterator` trait only requires a method to be defined for the `next` element,\n// and an `associated type` to declare the return type of the iterator.\nimpl Iterator for Fibonacci {\n // We can refer to this type using Self::Item\n type Item = u32;\n\n // Here, we define the sequence using `.curr` and `.next`.\n // The return type is `Option`:\n // * When the `Iterator` is finished, `None` is returned.\n // * Otherwise, the next value is wrapped in `Some` and returned.\n // We use Self::Item in the return type, so we can change\n // the type without having to update the function signatures.\n fn next(&mut self) -> Option {\n let current = self.curr;\n\n self.curr = self.next;\n self.next = current + self.next;\n\n // Since there's no endpoint to a Fibonacci sequence, the `Iterator`\n // will never return `None`, and `Some` is always returned.\n Some(current)\n }\n}\n\n// Returns a Fibonacci sequence generator\nfn fibonacci() -> Fibonacci {\n Fibonacci { curr: 0, next: 1 }\n}\n\nfn main() {\n // `0..3` is an `Iterator` that generates: 0, 1, and 2.\n let mut sequence = 0..3;\n\n println!(\"Four consecutive `next` calls on 0..3\");\n println!(\"> {:?}\", sequence.next());\n println!(\"> {:?}\", sequence.next());\n println!(\"> {:?}\", sequence.next());\n println!(\"> {:?}\", sequence.next());\n\n // `for` works through an `Iterator` until it returns `None`.\n // Each `Some` value is unwrapped and bound to a variable (here, `i`).\n println!(\"Iterate through 0..3 using `for`\");\n for i in 0..3 {\n println!(\"> {}\", i);\n }\n\n // The `take(n)` method reduces an `Iterator` to its first `n` terms.\n println!(\"The first four terms of the Fibonacci sequence are: \");\n for i in fibonacci().take(4) {\n println!(\"> {}\", i);\n }\n\n // The `skip(n)` method shortens an `Iterator` by dropping its first `n` terms.\n println!(\"The next four terms of the Fibonacci sequence are: \");\n for i in fibonacci().skip(4).take(4) {\n println!(\"> {}\", i);\n }\n\n let array = [1u32, 3, 3, 7];\n\n // The `iter` method produces an `Iterator` over an array/slice.\n println!(\"Iterate the following array {:?}\", &array);\n for i in array.iter() {\n println!(\"> {}\", i);\n }\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Iterators", "heading_path": ["Iterators"], "path": "trait/iter.md", "url": "https://doc.rust-lang.org/rust-by-example/trait/iter.html#iterators", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/trait/impl_trait.md#impl-trait-0", "text": "Rust by Example › `impl Trait`\n\n`impl Trait` can be used in two locations:\n1. as an argument type\n2. as a return type", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`impl Trait`", "heading_path": ["`impl Trait`"], "path": "trait/impl_trait.md", "url": "https://doc.rust-lang.org/rust-by-example/trait/impl_trait.html#impl-trait", "has_code": false, "code_tags": []}} {"id": "rust-by-example/trait/impl_trait.md#as-an-argument-type-1", "text": "Rust by Example › `impl Trait` › As an argument type\n\nIf your function is generic over a trait but you don't mind the specific type, you can simplify the function declaration using `impl Trait` as the type of the argument.\nFor example, consider the following code:\n```rust,editable\nfn parse_csv_document(src: R) -> std::io::Result>> {\n src.lines()\n .map(|line| {\n // For each line in the source\n line.map(|line| {\n // If the line was read successfully, process it, if not, return the error\n line.split(',') // Split the line separated by commas\n .map(|entry| String::from(entry.trim())) // Remove leading and trailing whitespace\n .collect() // Collect all strings in a row into a Vec\n })\n })\n .collect() // Collect all lines into a Vec>\n}\n```\n`parse_csv_document` is generic, allowing it to take any type which implements BufRead, such as `BufReader` or `[u8]`,\nbut it's not important what type `R` is, and `R` is only used to declare the type of `src`, so the function can also be written as:\n```rust,editable\nfn parse_csv_document(src: impl std::io::BufRead) -> std::io::Result>> {\n src.lines()\n .map(|line| {\n // For each line in the source\n line.map(|line| {\n // If the line was read successfully, process it, if not, return the error\n line.split(',') // Split the line separated by commas\n .map(|entry| String::from(entry.trim())) // Remove leading and trailing whitespace\n .collect() // Collect all strings in a row into a Vec\n })\n })\n .collect() // Collect all lines into a Vec>\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`impl Trait`", "heading_path": ["`impl Trait`", "As an argument type"], "path": "trait/impl_trait.md", "url": "https://doc.rust-lang.org/rust-by-example/trait/impl_trait.html#as-an-argument-type", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/trait/impl_trait.md#as-an-argument-type-2", "text": "Rust by Example › `impl Trait` › As an argument type\n\nNote that using `impl Trait` as an argument type means that you cannot explicitly state what form of the function you use, i.e. `parse_csv_document::(std::io::empty())` will not work with the second example.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`impl Trait`", "heading_path": ["`impl Trait`", "As an argument type"], "path": "trait/impl_trait.md", "url": "https://doc.rust-lang.org/rust-by-example/trait/impl_trait.html#as-an-argument-type", "has_code": false, "code_tags": []}} {"id": "rust-by-example/trait/impl_trait.md#as-a-return-type-3", "text": "Rust by Example › `impl Trait` › As a return type\n\nIf your function returns a type that implements `MyTrait`, you can write its\nreturn type as `-> impl MyTrait`. This can help simplify your type signatures quite a lot!\n```rust,editable\nuse std::iter;\nuse std::vec::IntoIter;\n\n// This function combines two `Vec` and returns an iterator over it.\n// Look how complicated its return type is!\nfn combine_vecs_explicit_return_type(\n v: Vec,\n u: Vec,\n) -> iter::Cycle, IntoIter>> {\n v.into_iter().chain(u.into_iter()).cycle()\n}\n\n// This is the exact same function, but its return type uses `impl Trait`.\n// Look how much simpler it is!\nfn combine_vecs(\n v: Vec,\n u: Vec,\n) -> impl Iterator {\n v.into_iter().chain(u.into_iter()).cycle()\n}\n\nfn main() {\n let v1 = vec![1, 2, 3];\n let v2 = vec![4, 5];\n let mut v3 = combine_vecs(v1, v2);\n assert_eq!(Some(1), v3.next());\n assert_eq!(Some(2), v3.next());\n assert_eq!(Some(3), v3.next());\n assert_eq!(Some(4), v3.next());\n assert_eq!(Some(5), v3.next());\n println!(\"all done\");\n}\n```\nMore importantly, some Rust types can't be written out. For example, every\nclosure has its own unnamed concrete type. Before `impl Trait` syntax, you had\nto allocate on the heap in order to return a closure. But now you can do it all\nstatically, like this:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`impl Trait`", "heading_path": ["`impl Trait`", "As a return type"], "path": "trait/impl_trait.md", "url": "https://doc.rust-lang.org/rust-by-example/trait/impl_trait.html#as-a-return-type", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/trait/impl_trait.md#as-a-return-type-4", "text": "Rust by Example › `impl Trait` › As a return type\n\n```rust,editable\n// Returns a function that adds `y` to its input\nfn make_adder_function(y: i32) -> impl Fn(i32) -> i32 {\n let closure = move |x: i32| { x + y };\n closure\n}\n\nfn main() {\n let plus_one = make_adder_function(1);\n assert_eq!(plus_one(2), 3);\n}\n```\nYou can also use `impl Trait` to return an iterator that uses `map` or `filter`\nclosures! This makes using `map` and `filter` easier. Because closure types don't\nhave names, you can't write out an explicit return type if your function returns\niterators with closures. But with `impl Trait` you can do this easily:\n```rust,editable\nfn double_positives<'a>(numbers: &'a Vec) -> impl Iterator + 'a {\n numbers\n .iter()\n .filter(|x| x > &&0)\n .map(|x| x * 2)\n}\n\nfn main() {\n let singles = vec![-3, -2, 2, 3];\n let doubles = double_positives(&singles);\n assert_eq!(doubles.collect::>(), vec![4, 6]);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`impl Trait`", "heading_path": ["`impl Trait`", "As a return type"], "path": "trait/impl_trait.md", "url": "https://doc.rust-lang.org/rust-by-example/trait/impl_trait.html#as-a-return-type", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/trait/clone.md#clone-and-copy-0", "text": "Rust by Example › Clone and Copy\n\nWhen dealing with resources, the default behavior is to transfer them during\nassignments or function calls. However, sometimes we need to make a\ncopy of the resource as well.\nThe `Clone` trait helps us do exactly this. Most commonly, we can\nuse the `.clone()` method defined by the `Clone` trait.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Clone", "heading_path": ["Clone and Copy"], "path": "trait/clone.md", "url": "https://doc.rust-lang.org/rust-by-example/trait/clone.html#clone-and-copy", "has_code": false, "code_tags": []}} {"id": "rust-by-example/trait/clone.md#copy-implicit-cloning-1", "text": "Rust by Example › Clone and Copy › Copy: Implicit Cloning\n\nThe `Copy` trait allows a type to be duplicated simply by copying bits,\nwith no additional logic required. When a type implements `Copy`, assignments\nand function calls will implicitly copy the value instead of moving it.\n**Important:** `Copy` requires `Clone` - any type that implements `Copy` must\nalso implement `Clone`. This is because `Copy` is defined as a subtrait:\n`trait Copy: Clone {}`. The `Clone` implementation for `Copy` types simply\ncopies the bits.\nNot all types can implement `Copy`. A type can only be `Copy` if:\n- All of its components are `Copy`\n- It doesn't manage external resources (like heap memory, file handles, etc.)", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Clone", "heading_path": ["Clone and Copy", "Copy: Implicit Cloning"], "path": "trait/clone.md", "url": "https://doc.rust-lang.org/rust-by-example/trait/clone.html#copy-implicit-cloning", "has_code": false, "code_tags": []}} {"id": "rust-by-example/trait/clone.md#copy-implicit-cloning-2", "text": "Rust by Example › Clone and Copy › Copy: Implicit Cloning\n\n```rust,editable\n// A unit struct without resources\n// Note: Copy requires Clone, so we must derive both\n#[derive(Debug, Clone, Copy)]\nstruct Unit;\n\n// A tuple struct with resources that implements the `Clone` trait\n// This CANNOT be Copy because Box is not Copy\n#[derive(Clone, Debug)]\nstruct Pair(Box, Box);\n\nfn main() {\n // Instantiate `Unit`\n let unit = Unit;\n // Copy `Unit` - this is an implicit copy, not a move!\n // Because Unit implements Copy, the value is duplicated automatically\n let copied_unit = unit;\n\n // Both `Unit`s can be used independently\n println!(\"original: {:?}\", unit);\n println!(\"copy: {:?}\", copied_unit);\n\n // Instantiate `Pair`\n let pair = Pair(Box::new(1), Box::new(2));\n println!(\"original: {:?}\", pair);\n\n // Move `pair` into `moved_pair`, moves resources\n // Pair does not implement Copy, so this is a move\n let moved_pair = pair;\n println!(\"moved: {:?}\", moved_pair);\n\n // Error! `pair` has lost its resources\n //println!(\"original: {:?}\", pair);\n // TODO ^ Try uncommenting this line\n\n // Clone `moved_pair` into `cloned_pair` (resources are included)\n // Unlike Copy, Clone is explicit - we must call .clone()\n let cloned_pair = moved_pair.clone();\n // Drop the moved original pair using std::mem::drop\n drop(moved_pair);\n\n // Error! `moved_pair` has been dropped\n //println!(\"moved and dropped: {:?}\", moved_pair);\n // TODO ^ Try uncommenting this line\n\n // The result from .clone() can still be used!\n println!(\"clone: {:?}\", cloned_pair);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Clone", "heading_path": ["Clone and Copy", "Copy: Implicit Cloning"], "path": "trait/clone.md", "url": "https://doc.rust-lang.org/rust-by-example/trait/clone.html#copy-implicit-cloning", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/trait/supertraits.md#supertraits-0", "text": "Rust by Example › Supertraits\n\nRust doesn't have \"inheritance\", but you can define a trait as being a superset\nof another trait. For example:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Supertraits", "heading_path": ["Supertraits"], "path": "trait/supertraits.md", "url": "https://doc.rust-lang.org/rust-by-example/trait/supertraits.html#supertraits", "has_code": false, "code_tags": []}} {"id": "rust-by-example/trait/supertraits.md#supertraits-1", "text": "Rust by Example › Supertraits\n\n```rust,editable\ntrait Person {\n fn name(&self) -> String;\n}\n\n// Person is a supertrait of Student.\n// Implementing Student requires you to also impl Person.\ntrait Student: Person {\n fn university(&self) -> String;\n}\n\ntrait Programmer {\n fn fav_language(&self) -> String;\n}\n\n// CompSciStudent (computer science student) is a subtrait of both Programmer\n// and Student. Implementing CompSciStudent requires you to impl both supertraits.\ntrait CompSciStudent: Programmer + Student {\n fn git_username(&self) -> String;\n}\n\nfn comp_sci_student_greeting(student: &dyn CompSciStudent) -> String {\n format!(\n \"My name is {} and I attend {}. My favorite language is {}. My Git username is {}\",\n student.name(),\n student.university(),\n student.fav_language(),\n student.git_username()\n )\n}\n\nstruct CSStudent {\n name: String,\n university: String,\n fav_language: String,\n git_username: String\n}\n\nimpl Programmer for CSStudent {\n fn fav_language(&self) -> String {\n self.fav_language.clone()\n }\n}\n\nimpl Student for CSStudent {\n fn university(&self) -> String {\n self.university.clone()\n }\n}\n\nimpl Person for CSStudent {\n fn name(&self) -> String {\n self.name.clone()\n }\n}\n\nimpl CompSciStudent for CSStudent {\n fn git_username(&self) -> String {\n self.git_username.clone()\n }\n}\n\nfn main() {\n let student = CSStudent {\n name: String::from(\"Alice\"),\n university: String::from(\"MIT\"),\n fav_language: String::from(\"Rust\"),\n git_username: String::from(\"alice_codes\"),\n };\n\n let greeting = comp_sci_student_greeting(&student);\n println!(\"{}\", greeting);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Supertraits", "heading_path": ["Supertraits"], "path": "trait/supertraits.md", "url": "https://doc.rust-lang.org/rust-by-example/trait/supertraits.html#supertraits", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/trait/supertraits.md#see-also-2", "text": "Rust by Example › Supertraits › See also:\n\nThe Rust Programming Language chapter on supertraits", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Supertraits", "heading_path": ["Supertraits", "See also:"], "path": "trait/supertraits.md", "url": "https://doc.rust-lang.org/rust-by-example/trait/supertraits.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/trait/disambiguating.md#disambiguating-overlapping-traits-0", "text": "Rust by Example › Disambiguating overlapping traits\n\nA type can implement many different traits. What if two traits both require\nthe same name for a function? For example, many traits might have a method\nnamed `get()`. They might even have different return types!\nGood news: because each trait implementation gets its own `impl` block, it's\nclear which trait's `get` method you're implementing.\nWhat about when it comes time to _call_ those methods? To disambiguate between\nthem, we have to use Fully Qualified Syntax.\n```rust,editable\ntrait UsernameWidget {\n // Get the selected username out of this widget\n fn get(&self) -> String;\n}\n\ntrait AgeWidget {\n // Get the selected age out of this widget\n fn get(&self) -> u8;\n}\n\n// A form with both a UsernameWidget and an AgeWidget\nstruct Form {\n username: String,\n age: u8,\n}\n\nimpl UsernameWidget for Form {\n fn get(&self) -> String {\n self.username.clone()\n }\n}\n\nimpl AgeWidget for Form {\n fn get(&self) -> u8 {\n self.age\n }\n}\n\nfn main() {\n let form = Form {\n username: \"rustacean\".to_owned(),\n age: 28,\n };\n\n // If you uncomment this line, you'll get an error saying\n // \"multiple `get` found\". Because, after all, there are multiple methods\n // named `get`.\n // println!(\"{}\", form.get());\n\n let username =

::get(&form);\n assert_eq!(\"rustacean\".to_owned(), username);\n let age = ::get(&form);\n assert_eq!(28, age);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Disambiguating overlapping traits", "heading_path": ["Disambiguating overlapping traits"], "path": "trait/disambiguating.md", "url": "https://doc.rust-lang.org/rust-by-example/trait/disambiguating.html#disambiguating-overlapping-traits", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/trait/disambiguating.md#see-also-1", "text": "Rust by Example › Disambiguating overlapping traits › See also:\n\nThe Rust Programming Language chapter on Fully Qualified syntax", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Disambiguating overlapping traits", "heading_path": ["Disambiguating overlapping traits", "See also:"], "path": "trait/disambiguating.md", "url": "https://doc.rust-lang.org/rust-by-example/trait/disambiguating.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/macros.md#macro_rules-0", "text": "Rust by Example › `macro_rules!`\n\nRust provides a powerful macro system that allows metaprogramming. As you've\nseen in previous chapters, macros look like functions, except that their name\nends with a bang `!`, but instead of generating a function call, macros are\nexpanded into source code that gets compiled with the rest of the program.\nHowever, unlike macros in C and other languages, Rust macros are expanded into\nabstract syntax trees, rather than string preprocessing, so you don't get\nunexpected precedence bugs.\nMacros can be created using the `macro_rules!` macro.\n```rust,editable\n// This is a simple macro named `say_hello`.\nmacro_rules! say_hello {\n // `()` indicates that the macro takes no argument.\n () => {\n // The macro will expand into the contents of this block.\n println!(\"Hello!\")\n };\n}\n\nfn main() {\n // This call will expand into `println!(\"Hello!\")`\n say_hello!()\n}\n```\nSo why are macros useful?\n1. Don't repeat yourself. There are many cases where you may need similar\n functionality in multiple places but with different types. Often, writing a\n macro is a useful way to avoid repeating code. (More on this later)\n2. Domain-specific languages. Macros allow you to define special syntax for a\n specific purpose. (More on this later)\n3. Variadic interfaces. Sometimes you want to define an interface that takes a\n variable number of arguments. An example is `println!` which could take any\n number of arguments, depending on the format string. (More on this later)", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "macro_rules!", "heading_path": ["`macro_rules!`"], "path": "macros.md", "url": "https://doc.rust-lang.org/rust-by-example/macros.html#macro_rules", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/macros/syntax.md#syntax-0", "text": "Rust by Example › Syntax\n\nIn following subsections, we will show how to define macros in Rust.\nThere are three basic ideas:\n- Patterns and Designators\n- Overloading\n- Repetition", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Syntax", "heading_path": ["Syntax"], "path": "macros/syntax.md", "url": "https://doc.rust-lang.org/rust-by-example/macros/syntax.html#syntax", "has_code": false, "code_tags": []}} {"id": "rust-by-example/macros/designators.md#designators-0", "text": "Rust by Example › Designators\n\nThe arguments of a macro are prefixed by a dollar sign `$` and type annotated\nwith a *designator*:\n```rust,editable\nmacro_rules! create_function {\n // This macro takes an argument of designator `ident` and\n // creates a function named `$func_name`.\n // The `ident` designator is used for variable/function names.\n ($func_name:ident) => {\n fn $func_name() {\n // The `stringify!` macro converts an `ident` into a string.\n println!(\"You called {:?}()\",\n stringify!($func_name));\n }\n };\n}\n\n// Create functions named `foo` and `bar` with the above macro.\ncreate_function!(foo);\ncreate_function!(bar);\n\nmacro_rules! print_result {\n // This macro takes an expression of type `expr` and prints\n // it as a string along with its result.\n // The `expr` designator is used for expressions.\n ($expression:expr) => {\n // `stringify!` will convert the expression *as it is* into a string.\n println!(\"{:?} = {:?}\",\n stringify!($expression),\n $expression);\n };\n}\n\nfn main() {\n foo();\n bar();\n\n print_result!(1u32 + 1);\n\n // Recall that blocks are expressions too!\n print_result!({\n let x = 1u32;\n\n x * x + 2 * x - 1\n });\n}\n```\nThese are some of the available designators:\n* `block`\n* `expr` is used for expressions\n* `ident` is used for variable/function names\n* `item`\n* `literal` is used for literal constants\n* `pat` (*pattern*)\n* `path`\n* `stmt` (*statement*)\n* `tt` (*token tree*)\n* `ty` (*type*)\n* `vis` (*visibility qualifier*)", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Designators", "heading_path": ["Designators"], "path": "macros/designators.md", "url": "https://doc.rust-lang.org/rust-by-example/macros/designators.html#designators", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/macros/designators.md#designators-1", "text": "Rust by Example › Designators\n\nFor a complete list, see the [Rust Reference].", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Designators", "heading_path": ["Designators"], "path": "macros/designators.md", "url": "https://doc.rust-lang.org/rust-by-example/macros/designators.html#designators", "has_code": false, "code_tags": []}} {"id": "rust-by-example/macros/overload.md#overload-0", "text": "Rust by Example › Overload\n\nMacros can be overloaded to accept different combinations of arguments.\nIn that regard, `macro_rules!` can work similarly to a match block:\n```rust,editable\n// `test!` will compare `$left` and `$right`\n// in different ways depending on how you invoke it:\nmacro_rules! test {\n // Arguments don't need to be separated by a comma.\n // Any template can be used!\n ($left:expr; and $right:expr) => {\n println!(\"{:?} and {:?} is {:?}\",\n stringify!($left),\n stringify!($right),\n $left && $right)\n };\n // ^ each arm must end with a semicolon.\n ($left:expr; or $right:expr) => {\n println!(\"{:?} or {:?} is {:?}\",\n stringify!($left),\n stringify!($right),\n $left || $right)\n };\n}\n\nfn main() {\n test!(1i32 + 1 == 2i32; and 2i32 * 2 == 4i32);\n test!(true; or false);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Overload", "heading_path": ["Overload"], "path": "macros/overload.md", "url": "https://doc.rust-lang.org/rust-by-example/macros/overload.html#overload", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/macros/repeat.md#repeat-0", "text": "Rust by Example › Repeat\n\nMacros can use `+` in the argument list to indicate that an argument may\nrepeat at least once, or `*`, to indicate that the argument may repeat zero or\nmore times.\nIn the following example, surrounding the matcher with `$(...),+` will\nmatch one or more expression, separated by commas.\nAlso note that the semicolon is optional on the last case.\n```rust,editable\n// `find_min!` will calculate the minimum of any number of arguments.\nmacro_rules! find_min {\n // Base case:\n ($x:expr) => ($x);\n // `$x` followed by at least one `$y,`\n ($x:expr, $($y:expr),+) => (\n // Call `find_min!` on the tail `$y`\n std::cmp::min($x, find_min!($($y),+))\n )\n}\n\nfn main() {\n println!(\"{}\", find_min!(1));\n println!(\"{}\", find_min!(1 + 2, 2));\n println!(\"{}\", find_min!(5, 2 * 3, 4));\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Repeat", "heading_path": ["Repeat"], "path": "macros/repeat.md", "url": "https://doc.rust-lang.org/rust-by-example/macros/repeat.html#repeat", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/macros/dry.md#dry-dont-repeat-yourself-0", "text": "Rust by Example › DRY (Don't Repeat Yourself)\n\nMacros allow writing DRY code by factoring out the common parts of functions\nand/or test suites. Here is an example that implements and tests the `+=`, `*=`\nand `-=` operators on `Vec`:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "DRY (Don't Repeat Yourself)", "heading_path": ["DRY (Don't Repeat Yourself)"], "path": "macros/dry.md", "url": "https://doc.rust-lang.org/rust-by-example/macros/dry.html#dry-dont-repeat-yourself", "has_code": false, "code_tags": []}} {"id": "rust-by-example/macros/dry.md#dry-dont-repeat-yourself-1", "text": "Rust by Example › DRY (Don't Repeat Yourself)\n\n```rust,editable\nuse std::ops::{Add, Mul, Sub};\n\nmacro_rules! assert_equal_len {\n // The `tt` (token tree) designator is used for\n // operators and tokens.\n ($a:expr, $b:expr, $func:ident, $op:tt) => {\n assert!($a.len() == $b.len(),\n \"{:?}: dimension mismatch: {:?} {:?} {:?}\",\n stringify!($func),\n ($a.len(),),\n stringify!($op),\n ($b.len(),));\n };\n}\n\nmacro_rules! op {\n ($func:ident, $bound:ident, $op:tt, $method:ident) => {\n fn $func + Copy>(xs: &mut Vec, ys: &Vec) {\n assert_equal_len!(xs, ys, $func, $op);\n\n for (x, y) in xs.iter_mut().zip(ys.iter()) {\n *x = $bound::$method(*x, *y);\n // *x = x.$method(*y);\n }\n }\n };\n}\n\n// Implement `add_assign`, `mul_assign`, and `sub_assign` functions.\nop!(add_assign, Add, +=, add);\nop!(mul_assign, Mul, *=, mul);\nop!(sub_assign, Sub, -=, sub);\n\nmod test {\n use std::iter;\n macro_rules! test {\n ($func:ident, $x:expr, $y:expr, $z:expr) => {\n #[test]\n fn $func() {\n for size in 0usize..10 {\n let mut x: Vec<_> = iter::repeat($x).take(size).collect();\n let y: Vec<_> = iter::repeat($y).take(size).collect();\n let z: Vec<_> = iter::repeat($z).take(size).collect();\n\n super::$func(&mut x, &y);\n\n assert_eq!(x, z);\n }\n }\n };\n }\n\n // Test `add_assign`, `mul_assign`, and `sub_assign`.\n test!(add_assign, 1u32, 2u32, 3u32);\n test!(mul_assign, 2u32, 3u32, 6u32);\n test!(sub_assign, 3u32, 2u32, 1u32);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "DRY (Don't Repeat Yourself)", "heading_path": ["DRY (Don't Repeat Yourself)"], "path": "macros/dry.md", "url": "https://doc.rust-lang.org/rust-by-example/macros/dry.html#dry-dont-repeat-yourself", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/macros/dry.md#dry-dont-repeat-yourself-2", "text": "Rust by Example › DRY (Don't Repeat Yourself)\n\n```shell\n$ rustc --test dry.rs && ./dry\nrunning 3 tests\ntest test::mul_assign ... ok\ntest test::add_assign ... ok\ntest test::sub_assign ... ok\n\ntest result: ok. 3 passed; 0 failed; 0 ignored; 0 measured\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "DRY (Don't Repeat Yourself)", "heading_path": ["DRY (Don't Repeat Yourself)"], "path": "macros/dry.md", "url": "https://doc.rust-lang.org/rust-by-example/macros/dry.html#dry-dont-repeat-yourself", "has_code": true, "code_tags": ["shell"]}} {"id": "rust-by-example/macros/dsl.md#domain-specific-languages-dsls-0", "text": "Rust by Example › Domain Specific Languages (DSLs)\n\nA DSL is a mini \"language\" embedded in a Rust macro. It is completely valid\nRust because the macro system expands into normal Rust constructs, but it looks\nlike a small language. This allows you to define concise or intuitive syntax for\nsome special functionality (within bounds).\nSuppose that I want to define a little calculator API. I would like to supply\nan expression and have the output printed to console.\n```rust,editable\nmacro_rules! calculate {\n (eval $e:expr) => {\n {\n let val: usize = $e; // Force types to be unsigned integers\n println!(\"{} = {}\", stringify!{$e}, val);\n }\n };\n}\n\nfn main() {\n calculate! {\n eval 1 + 2 // hehehe `eval` is _not_ a Rust keyword!\n }\n\n calculate! {\n eval (1 + 2) * (3 / 4)\n }\n}\n```\nOutput:\n```txt\n1 + 2 = 3\n(1 + 2) * (3 / 4) = 0\n```\nThis was a very simple example, but much more complex interfaces have been\ndeveloped, such as `lazy_static` or\n`clap`.\nAlso, note the two pairs of braces in the macro. The outer ones are\npart of the syntax of `macro_rules!`, in addition to `()` or `[]`.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "DSL (Domain Specific Languages)", "heading_path": ["Domain Specific Languages (DSLs)"], "path": "macros/dsl.md", "url": "https://doc.rust-lang.org/rust-by-example/macros/dsl.html#domain-specific-languages-dsls", "has_code": true, "code_tags": ["rust,editable", "txt"]}} {"id": "rust-by-example/macros/variadics.md#variadic-interfaces-0", "text": "Rust by Example › Variadic Interfaces\n\nA _variadic_ interface takes an arbitrary number of arguments. For example,\n`println!` can take an arbitrary number of arguments, as determined by the\nformat string.\nWe can extend our `calculate!` macro from the previous section to be variadic:\n```rust,editable\nmacro_rules! calculate {\n // The pattern for a single `eval`\n (eval $e:expr) => {\n {\n let val: usize = $e; // Force types to be integers\n println!(\"{} = {}\", stringify!{$e}, val);\n }\n };\n\n // Decompose multiple `eval`s recursively\n (eval $e:expr, $(eval $es:expr),+) => {{\n calculate! { eval $e }\n calculate! { $(eval $es),+ }\n }};\n}\n\nfn main() {\n calculate! { // Look ma! Variadic `calculate!`!\n eval 1 + 2,\n eval 3 + 4,\n eval (2 * 3) + 1\n }\n}\n```\nOutput:\n```txt\n1 + 2 = 3\n3 + 4 = 7\n(2 * 3) + 1 = 7\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Variadics", "heading_path": ["Variadic Interfaces"], "path": "macros/variadics.md", "url": "https://doc.rust-lang.org/rust-by-example/macros/variadics.html#variadic-interfaces", "has_code": true, "code_tags": ["rust,editable", "txt"]}} {"id": "rust-by-example/error.md#error-handling-0", "text": "Rust by Example › Error handling\n\nError handling is the process of handling the possibility of failure. For\nexample, failing to read a file and then continuing to use that *bad* input\nwould clearly be problematic. Noticing and explicitly managing those errors\nsaves the rest of the program from various pitfalls.\nThere are various ways to deal with errors in Rust, which are described in the\nfollowing subchapters. They all have more or less subtle differences and different\nuse cases. As a rule of thumb:\nAn explicit `panic` is mainly useful for tests and dealing with unrecoverable errors.\nFor prototyping it can be useful, for example when dealing with functions that\nhaven't been implemented yet, but in those cases the more descriptive `unimplemented`\nis better. In tests `panic` is a reasonable way to explicitly fail.\nThe `Option` type is for when a value is optional or when the lack of a value is\nnot an error condition. For example the parent of a directory - `/` and `C:` don't\nhave one. When dealing with `Option`s, `unwrap` is fine for prototyping and cases\nwhere it's absolutely certain that there is guaranteed to be a value. However `expect`\nis more useful since it lets you specify an error message in case something goes\nwrong anyway.\nWhen there is a chance that things do go wrong and the caller has to deal with the\nproblem, use `Result`. You can `unwrap` and `expect` them as well (please don't\ndo that unless it's a test or quick prototype).\nFor a more rigorous discussion of error handling, refer to the error\nhandling section in the official book.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Error handling", "heading_path": ["Error handling"], "path": "error.md", "url": "https://doc.rust-lang.org/rust-by-example/error.html#error-handling", "has_code": false, "code_tags": []}} {"id": "rust-by-example/error/panic.md#panic-0", "text": "Rust by Example › `panic`\n\nThe simplest error handling mechanism we will see is `panic`. It prints an\nerror message, starts unwinding the stack, and usually exits the program.\nHere, we explicitly call `panic` on our error condition:\n```rust,editable,ignore,mdbook-runnable\nfn drink(beverage: &str) {\n // You shouldn't drink too many sugary beverages.\n if beverage == \"lemonade\" { panic!(\"AAAaaaaa!!!!\"); }\n\n println!(\"Some refreshing {} is all I need.\", beverage);\n}\n\nfn main() {\n drink(\"water\");\n drink(\"lemonade\");\n drink(\"still water\");\n}\n```\nThe first call to `drink` works. The second panics and thus the third is never called.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`panic`", "heading_path": ["`panic`"], "path": "error/panic.md", "url": "https://doc.rust-lang.org/rust-by-example/error/panic.html#panic", "has_code": true, "code_tags": ["rust,editable,ignore,mdbook-runnable"]}} {"id": "rust-by-example/error/abort_unwind.md#abort-and-unwind-0", "text": "Rust by Example › `abort` and `unwind`\n\nThe previous section illustrates the error handling mechanism `panic`. Different code paths can be conditionally compiled based on the panic setting. The current values available are `unwind` and `abort`.\nBuilding on the prior lemonade example, we explicitly use the panic strategy to exercise different lines of code.\n```rust,editable,mdbook-runnable\nfn drink(beverage: &str) {\n // You shouldn't drink too much sugary beverages.\n if beverage == \"lemonade\" {\n if cfg!(panic = \"abort\") {\n println!(\"This is not your party. Run!!!!\");\n } else {\n println!(\"Spit it out!!!!\");\n }\n } else {\n println!(\"Some refreshing {} is all I need.\", beverage);\n }\n}\n\nfn main() {\n drink(\"water\");\n drink(\"lemonade\");\n}\n```\nHere is another example focusing on rewriting `drink()` and explicitly use the `unwind` keyword.\n```rust,editable\n#[cfg(panic = \"unwind\")]\nfn ah() {\n println!(\"Spit it out!!!!\");\n}\n\n#[cfg(not(panic = \"unwind\"))]\nfn ah() {\n println!(\"This is not your party. Run!!!!\");\n}\n\nfn drink(beverage: &str) {\n if beverage == \"lemonade\" {\n ah();\n } else {\n println!(\"Some refreshing {} is all I need.\", beverage);\n }\n}\n\nfn main() {\n drink(\"water\");\n drink(\"lemonade\");\n}\n```\nThe panic strategy can be set from the command line by using `abort` or `unwind`.\n```console\nrustc lemonade.rs -C panic=abort\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`abort` & `unwind`", "heading_path": ["`abort` and `unwind`"], "path": "error/abort_unwind.md", "url": "https://doc.rust-lang.org/rust-by-example/error/abort_unwind.html#abort-and-unwind", "has_code": true, "code_tags": ["console", "rust,editable", "rust,editable,mdbook-runnable"]}} {"id": "rust-by-example/error/option_unwrap.md#option--unwrap-0", "text": "Rust by Example › `Option` & `unwrap`\n\nIn the last example, we showed that we can induce program failure at will.\nWe told our program to `panic` if we drink a sugary lemonade.\nBut what if we expect _some_ drink but don't receive one?\nThat case would be just as bad, so it needs to be handled!\nWe _could_ test this against the null string (`\"\"`) as we do with a lemonade.\nSince we're using Rust, let's instead have the compiler point out cases\nwhere there's no drink.\nAn `enum` called `Option` in the `std` library is used when absence is a\npossibility. It manifests itself as one of two \"options\":\n* `Some(T)`: An element of type `T` was found\n* `None`: No element was found\nThese cases can either be explicitly handled via `match` or implicitly with\n`unwrap`. Implicit handling will either return the inner element or `panic`.\nNote that it's possible to manually customize `panic` with expect,\nbut `unwrap` otherwise leaves us with a less meaningful output than explicit\nhandling. In the following example, explicit handling yields a more\ncontrolled result while retaining the option to `panic` if desired.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`Option` & `unwrap`", "heading_path": ["`Option` & `unwrap`"], "path": "error/option_unwrap.md", "url": "https://doc.rust-lang.org/rust-by-example/error/option_unwrap.html#option--unwrap", "has_code": false, "code_tags": []}} {"id": "rust-by-example/error/option_unwrap.md#option--unwrap-1", "text": "Rust by Example › `Option` & `unwrap`\n\n```rust,editable,ignore,mdbook-runnable\n// The adult has seen it all, and can handle any drink well.\n// All drinks are handled explicitly using `match`.\nfn give_adult(drink: Option<&str>) {\n // Specify a course of action for each case.\n match drink {\n Some(\"lemonade\") => println!(\"Yuck! Too sugary.\"),\n Some(inner) => println!(\"{}? How nice.\", inner),\n None => println!(\"No drink? Oh well.\"),\n }\n}\n\n// Others will `panic` before drinking sugary drinks.\n// All drinks are handled implicitly using `unwrap`.\nfn drink(drink: Option<&str>) {\n // `unwrap` returns a `panic` when it receives a `None`.\n let inside = drink.unwrap();\n if inside == \"lemonade\" { panic!(\"AAAaaaaa!!!!\"); }\n\n println!(\"I love {}s!!!!!\", inside);\n}\n\nfn main() {\n let water = Some(\"water\");\n let lemonade = Some(\"lemonade\");\n let void = None;\n\n give_adult(water);\n give_adult(lemonade);\n give_adult(void);\n\n let coffee = Some(\"coffee\");\n let nothing = None;\n\n drink(coffee);\n drink(nothing);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`Option` & `unwrap`", "heading_path": ["`Option` & `unwrap`"], "path": "error/option_unwrap.md", "url": "https://doc.rust-lang.org/rust-by-example/error/option_unwrap.html#option--unwrap", "has_code": true, "code_tags": ["rust,editable,ignore,mdbook-runnable"]}} {"id": "rust-by-example/error/option_unwrap/question_mark.md#unpacking-options-with--0", "text": "Rust by Example › Unpacking options with `?`\n\nYou can unpack `Option`s by using `match` statements, but it's often easier to\nuse the `?` operator. If `x` is an `Option`, then evaluating `x?` will return\nthe underlying value if `x` is `Some`, otherwise it will terminate whatever\nfunction is being executed and return `None`.\n```rust,ignore\nfn next_birthday(current_age: Option) -> Option {\n // If `current_age` is `None`, this returns `None`.\n // If `current_age` is `Some`, the inner `u8` value + 1\n // gets assigned to `next_age`\n let next_age: u8 = current_age? + 1;\n Some(format!(\"Next year I will be {}\", next_age))\n}\n```\nYou can chain many `?`s together to make your code much more readable.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Unpacking options with `?`", "heading_path": ["Unpacking options with `?`"], "path": "error/option_unwrap/question_mark.md", "url": "https://doc.rust-lang.org/rust-by-example/error/option_unwrap/question_mark.html#unpacking-options-with-", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "rust-by-example/error/option_unwrap/question_mark.md#unpacking-options-with--1", "text": "Rust by Example › Unpacking options with `?`\n\n```rust,editable\nstruct Person {\n job: Option,\n}\n\n#[derive(Clone, Copy)]\nstruct Job {\n phone_number: Option,\n}\n\n#[derive(Clone, Copy)]\n#[allow(dead_code)]\nstruct PhoneNumber {\n area_code: Option,\n number: u32,\n}\n\nimpl Person {\n\n // Gets the area code of the phone number of the person's job, if it exists.\n fn work_phone_area_code(&self) -> Option {\n // This would need many nested `match` statements without the `?` operator.\n // It would take a lot more code - try writing it yourself and see which\n // is easier.\n self.job?.phone_number?.area_code\n }\n}\n\nfn main() {\n let p = Person {\n job: Some(Job {\n phone_number: Some(PhoneNumber {\n area_code: Some(61),\n number: 439222222,\n }),\n }),\n };\n\n assert_eq!(p.work_phone_area_code(), Some(61));\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Unpacking options with `?`", "heading_path": ["Unpacking options with `?`"], "path": "error/option_unwrap/question_mark.md", "url": "https://doc.rust-lang.org/rust-by-example/error/option_unwrap/question_mark.html#unpacking-options-with-", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/error/option_unwrap/map.md#combinators-map-0", "text": "Rust by Example › Combinators: `map`\n\n`match` is a valid method for handling `Option`s. However, you may\neventually find heavy usage tedious, especially with operations only valid\nwith an input. In these cases, combinators can be used to\nmanage control flow in a modular fashion.\n`Option` has a built in method called `map()`, a combinator for the simple\nmapping of `Some -> Some` and `None -> None`. Multiple `map()` calls can be\nchained together for even more flexibility.\nIn the following example, `process()` replaces all functions previous\nto it while staying compact.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Combinators: `map`", "heading_path": ["Combinators: `map`"], "path": "error/option_unwrap/map.md", "url": "https://doc.rust-lang.org/rust-by-example/error/option_unwrap/map.html#combinators-map", "has_code": false, "code_tags": []}} {"id": "rust-by-example/error/option_unwrap/map.md#combinators-map-1", "text": "Rust by Example › Combinators: `map`\n\n```rust,editable\n#![allow(dead_code)]\n\n#[derive(Debug)] enum Food { Apple, Carrot, Potato }\n\n#[derive(Debug)] struct Peeled(Food);\n#[derive(Debug)] struct Chopped(Food);\n#[derive(Debug)] struct Cooked(Food);\n\n// Peeling food. If there isn't any, then return `None`.\n// Otherwise, return the peeled food.\nfn peel(food: Option) -> Option {\n match food {\n Some(food) => Some(Peeled(food)),\n None => None,\n }\n}\n\n// Chopping food. If there isn't any, then return `None`.\n// Otherwise, return the chopped food.\nfn chop(peeled: Option) -> Option {\n match peeled {\n Some(Peeled(food)) => Some(Chopped(food)),\n None => None,\n }\n}\n\n// Cooking food. Here, we showcase `map()` instead of `match` for case handling.\nfn cook(chopped: Option) -> Option {\n chopped.map(|Chopped(food)| Cooked(food))\n}\n\n// A function to peel, chop, and cook food all in sequence.\n// We chain multiple uses of `map()` to simplify the code.\nfn process(food: Option) -> Option {\n food.map(|f| Peeled(f))\n .map(|Peeled(f)| Chopped(f))\n .map(|Chopped(f)| Cooked(f))\n}\n\n// Check whether there's food or not before trying to eat it!\nfn eat(food: Option) {\n match food {\n Some(food) => println!(\"Mmm. I love {:?}\", food),\n None => println!(\"Oh no! It wasn't edible.\"),\n }\n}\n\nfn main() {\n let apple = Some(Food::Apple);\n let carrot = Some(Food::Carrot);\n let potato = None;\n\n let cooked_apple = cook(chop(peel(apple)));\n let cooked_carrot = cook(chop(peel(carrot)));\n // Let's try the simpler looking `process()` now.\n let cooked_potato = process(potato);\n\n eat(cooked_apple);\n eat(cooked_carrot);\n eat(cooked_potato);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Combinators: `map`", "heading_path": ["Combinators: `map`"], "path": "error/option_unwrap/map.md", "url": "https://doc.rust-lang.org/rust-by-example/error/option_unwrap/map.html#combinators-map", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/error/option_unwrap/map.md#see-also-2", "text": "Rust by Example › Combinators: `map` › See also:\n\nclosures, `Option`, `Option::map()`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Combinators: `map`", "heading_path": ["Combinators: `map`", "See also:"], "path": "error/option_unwrap/map.md", "url": "https://doc.rust-lang.org/rust-by-example/error/option_unwrap/map.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/error/option_unwrap/and_then.md#combinators-and_then-0", "text": "Rust by Example › Combinators: `and_then`\n\n`map()` was described as a chainable way to simplify `match` statements.\nHowever, using `map()` on a function that returns an `Option` results\nin the nested `Option>`. Chaining multiple calls together can\nthen become confusing. That's where another combinator called `and_then()`,\nknown in some languages as flatmap, comes in.\n`and_then()` calls its function input with the wrapped value and returns the result. If the `Option` is `None`, then it returns `None` instead.\nIn the following example, `cookable_v3()` results in an `Option`.\nUsing `map()` instead of `and_then()` would have given an\n`Option>`, which is an invalid type for `eat()`.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Combinators: `and_then`", "heading_path": ["Combinators: `and_then`"], "path": "error/option_unwrap/and_then.md", "url": "https://doc.rust-lang.org/rust-by-example/error/option_unwrap/and_then.html#combinators-and_then", "has_code": false, "code_tags": []}} {"id": "rust-by-example/error/option_unwrap/and_then.md#combinators-and_then-1", "text": "Rust by Example › Combinators: `and_then`\n\n```rust,editable\n#![allow(dead_code)]\n\n#[derive(Debug)] enum Food { CordonBleu, Steak, Sushi }\n#[derive(Debug)] enum Day { Monday, Tuesday, Wednesday }\n\n// We don't have the ingredients to make Sushi.\nfn have_ingredients(food: Food) -> Option {\n match food {\n Food::Sushi => None,\n _ => Some(food),\n }\n}\n\n// We have the recipe for everything except Cordon Bleu.\nfn have_recipe(food: Food) -> Option {\n match food {\n Food::CordonBleu => None,\n _ => Some(food),\n }\n}\n\n// To make a dish, we need both the recipe and the ingredients.\n// We can represent the logic with a chain of `match`es:\nfn cookable_v1(food: Food) -> Option {\n match have_recipe(food) {\n None => None,\n Some(food) => have_ingredients(food),\n }\n}\n\n// This can conveniently be rewritten more compactly with `and_then()`:\nfn cookable_v3(food: Food) -> Option {\n have_recipe(food).and_then(have_ingredients)\n}\n\n// Otherwise we'd need to `flatten()` an `Option>`\n// to get an `Option`:\nfn cookable_v2(food: Food) -> Option {\n have_recipe(food).map(have_ingredients).flatten()\n}\n\nfn eat(food: Food, day: Day) {\n match cookable_v3(food) {\n Some(food) => println!(\"Yay! On {:?} we get to eat {:?}.\", day, food),\n None => println!(\"Oh no. We don't get to eat on {:?}?\", day),\n }\n}\n\nfn main() {\n let (cordon_bleu, steak, sushi) = (Food::CordonBleu, Food::Steak, Food::Sushi);\n\n eat(cordon_bleu, Day::Monday);\n eat(steak, Day::Tuesday);\n eat(sushi, Day::Wednesday);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Combinators: `and_then`", "heading_path": ["Combinators: `and_then`"], "path": "error/option_unwrap/and_then.md", "url": "https://doc.rust-lang.org/rust-by-example/error/option_unwrap/and_then.html#combinators-and_then", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/error/option_unwrap/and_then.md#see-also-2", "text": "Rust by Example › Combinators: `and_then` › See also:\n\nclosures, `Option`, `Option::and_then()`, and `Option::flatten()`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Combinators: `and_then`", "heading_path": ["Combinators: `and_then`", "See also:"], "path": "error/option_unwrap/and_then.md", "url": "https://doc.rust-lang.org/rust-by-example/error/option_unwrap/and_then.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/error/option_unwrap/defaults.md#unpacking-options-and-defaults-0", "text": "Rust by Example › Unpacking options and defaults\n\nThere is more than one way to unpack an `Option` and fall back on a default if it is `None`. To choose the one that meets our needs, we need to consider the following:\n* do we need eager or lazy evaluation?\n* do we need to keep the original empty value intact, or modify it in place?", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Defaults: `or`, `or_else`, `get_or_insert`, `get_or_insert_with`", "heading_path": ["Unpacking options and defaults"], "path": "error/option_unwrap/defaults.md", "url": "https://doc.rust-lang.org/rust-by-example/error/option_unwrap/defaults.html#unpacking-options-and-defaults", "has_code": false, "code_tags": []}} {"id": "rust-by-example/error/option_unwrap/defaults.md#or-is-chainable-evaluates-eagerly-keeps-empty-value-intact-1", "text": "Rust by Example › Unpacking options and defaults › `or()` is chainable, evaluates eagerly, keeps empty value intact\n\n`or()`is chainable and eagerly evaluates its argument, as is shown in the following example. Note that because `or`'s arguments are evaluated eagerly, the variable passed to `or` is moved.\n```rust,editable\n#[derive(Debug)]\nenum Fruit { Apple, Orange, Banana, Kiwi, Lemon }\n\nfn main() {\n let apple = Some(Fruit::Apple);\n let orange = Some(Fruit::Orange);\n let no_fruit: Option = None;\n\n let first_available_fruit = no_fruit.or(orange).or(apple);\n println!(\"first_available_fruit: {:?}\", first_available_fruit);\n // first_available_fruit: Some(Orange)\n\n // `or` moves its argument.\n // In the example above, `or(orange)` returned a `Some`, so `or(apple)` was not invoked.\n // But the variable named `apple` has been moved regardless, and cannot be used anymore.\n // println!(\"Variable apple was moved, so this line won't compile: {:?}\", apple);\n // TODO: uncomment the line above to see the compiler error\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Defaults: `or`, `or_else`, `get_or_insert`, `get_or_insert_with`", "heading_path": ["Unpacking options and defaults", "`or()` is chainable, evaluates eagerly, keeps empty value intact"], "path": "error/option_unwrap/defaults.md", "url": "https://doc.rust-lang.org/rust-by-example/error/option_unwrap/defaults.html#or-is-chainable-evaluates-eagerly-keeps-empty-value-intact", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/error/option_unwrap/defaults.md#or_else-is-chainable-evaluates-lazily-keeps-empty-value-intact-2", "text": "Rust by Example › Unpacking options and defaults › `or_else()` is chainable, evaluates lazily, keeps empty value intact\n\nAnother alternative is to use `or_else`, which is also chainable, and evaluates lazily, as is shown in the following example:\n```rust,editable\n#[derive(Debug)]\nenum Fruit { Apple, Orange, Banana, Kiwi, Lemon }\n\nfn main() {\n let no_fruit: Option = None;\n let get_kiwi_as_fallback = || {\n println!(\"Providing kiwi as fallback\");\n Some(Fruit::Kiwi)\n };\n let get_lemon_as_fallback = || {\n println!(\"Providing lemon as fallback\");\n Some(Fruit::Lemon)\n };\n\n let first_available_fruit = no_fruit\n .or_else(get_kiwi_as_fallback)\n .or_else(get_lemon_as_fallback);\n println!(\"first_available_fruit: {:?}\", first_available_fruit);\n // Providing kiwi as fallback\n // first_available_fruit: Some(Kiwi)\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Defaults: `or`, `or_else`, `get_or_insert`, `get_or_insert_with`", "heading_path": ["Unpacking options and defaults", "`or_else()` is chainable, evaluates lazily, keeps empty value intact"], "path": "error/option_unwrap/defaults.md", "url": "https://doc.rust-lang.org/rust-by-example/error/option_unwrap/defaults.html#or_else-is-chainable-evaluates-lazily-keeps-empty-value-intact", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/error/option_unwrap/defaults.md#get_or_insert-evaluates-eagerly-modifies-empty-value-in-place-3", "text": "Rust by Example › Unpacking options and defaults › `get_or_insert()` evaluates eagerly, modifies empty value in place\n\nTo make sure that an `Option` contains a value, we can use `get_or_insert` to modify it in place with a fallback value, as is shown in the following example. Note that `get_or_insert` eagerly evaluates its parameter, so variable `apple` is moved:\n```rust,editable\n#[derive(Debug)]\nenum Fruit { Apple, Orange, Banana, Kiwi, Lemon }\n\nfn main() {\n let mut my_fruit: Option = None;\n let apple = Fruit::Apple;\n let first_available_fruit = my_fruit.get_or_insert(apple);\n println!(\"first_available_fruit is: {:?}\", first_available_fruit);\n println!(\"my_fruit is: {:?}\", my_fruit);\n // first_available_fruit is: Apple\n // my_fruit is: Some(Apple)\n //println!(\"Variable named `apple` is moved: {:?}\", apple);\n // TODO: uncomment the line above to see the compiler error\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Defaults: `or`, `or_else`, `get_or_insert`, `get_or_insert_with`", "heading_path": ["Unpacking options and defaults", "`get_or_insert()` evaluates eagerly, modifies empty value in place"], "path": "error/option_unwrap/defaults.md", "url": "https://doc.rust-lang.org/rust-by-example/error/option_unwrap/defaults.html#get_or_insert-evaluates-eagerly-modifies-empty-value-in-place", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/error/option_unwrap/defaults.md#get_or_insert_with-evaluates-lazily-modifies-empty-value-in-place-4", "text": "Rust by Example › Unpacking options and defaults › `get_or_insert_with()` evaluates lazily, modifies empty value in place\n\nInstead of explicitly providing a value to fall back on, we can pass a closure to `get_or_insert_with`, as follows:\n```rust,editable\n#[derive(Debug)]\nenum Fruit { Apple, Orange, Banana, Kiwi, Lemon }\n\nfn main() {\n let mut my_fruit: Option = None;\n let get_lemon_as_fallback = || {\n println!(\"Providing lemon as fallback\");\n Fruit::Lemon\n };\n let first_available_fruit = my_fruit\n .get_or_insert_with(get_lemon_as_fallback);\n println!(\"first_available_fruit is: {:?}\", first_available_fruit);\n println!(\"my_fruit is: {:?}\", my_fruit);\n // Providing lemon as fallback\n // first_available_fruit is: Lemon\n // my_fruit is: Some(Lemon)\n\n // If the Option has a value, it is left unchanged, and the closure is not invoked\n let mut my_apple = Some(Fruit::Apple);\n let should_be_apple = my_apple.get_or_insert_with(get_lemon_as_fallback);\n println!(\"should_be_apple is: {:?}\", should_be_apple);\n println!(\"my_apple is unchanged: {:?}\", my_apple);\n // The output is a follows. Note that the closure `get_lemon_as_fallback` is not invoked\n // should_be_apple is: Apple\n // my_apple is unchanged: Some(Apple)\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Defaults: `or`, `or_else`, `get_or_insert`, `get_or_insert_with`", "heading_path": ["Unpacking options and defaults", "`get_or_insert_with()` evaluates lazily, modifies empty value in place"], "path": "error/option_unwrap/defaults.md", "url": "https://doc.rust-lang.org/rust-by-example/error/option_unwrap/defaults.html#get_or_insert_with-evaluates-lazily-modifies-empty-value-in-place", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/error/option_unwrap/defaults.md#see-also-5", "text": "Rust by Example › Unpacking options and defaults › `get_or_insert_with()` evaluates lazily, modifies empty value in place › See also:\n\n`closures`, `get_or_insert`, `get_or_insert_with`, `moved variables`, `or`, `or_else`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Defaults: `or`, `or_else`, `get_or_insert`, `get_or_insert_with`", "heading_path": ["Unpacking options and defaults", "`get_or_insert_with()` evaluates lazily, modifies empty value in place", "See also:"], "path": "error/option_unwrap/defaults.md", "url": "https://doc.rust-lang.org/rust-by-example/error/option_unwrap/defaults.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/error/result.md#result-0", "text": "Rust by Example › `Result`\n\n`Result` is a richer version of the `Option` type that\ndescribes possible *error* instead of possible *absence*.\nThat is, `Result` could have one of two outcomes:\n* `Ok(T)`: An element `T` was found\n* `Err(E)`: An error was found with element `E`\nBy convention, the expected outcome is `Ok` while the unexpected outcome is `Err`.\nLike `Option`, `Result` has many methods associated with it. `unwrap()`, for\nexample, either yields the element `T` or `panic`s. For case handling,\nthere are many combinators between `Result` and `Option` that overlap.\nIn working with Rust, you will likely encounter methods that return the\n`Result` type, such as the `parse()` method. It might not always\nbe possible to parse a string into the other type, so `parse()` returns a\n`Result` indicating possible failure.\nLet's see what happens when we successfully and unsuccessfully `parse()` a string:\n```rust,editable,ignore,mdbook-runnable\nfn multiply(first_number_str: &str, second_number_str: &str) -> i32 {\n // Let's try using `unwrap()` to get the number out. Will it bite us?\n let first_number = first_number_str.parse::().unwrap();\n let second_number = second_number_str.parse::().unwrap();\n first_number * second_number\n}\n\nfn main() {\n let twenty = multiply(\"10\", \"2\");\n println!(\"double is {}\", twenty);\n\n let tt = multiply(\"t\", \"2\");\n println!(\"double is {}\", tt);\n}\n```\nIn the unsuccessful case, `parse()` leaves us with an error for `unwrap()`\nto `panic` on. Additionally, the `panic` exits our program and provides an\nunpleasant error message.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`Result`", "heading_path": ["`Result`"], "path": "error/result.md", "url": "https://doc.rust-lang.org/rust-by-example/error/result.html#result", "has_code": true, "code_tags": ["rust,editable,ignore,mdbook-runnable"]}} {"id": "rust-by-example/error/result.md#result-1", "text": "Rust by Example › `Result`\n\nTo improve the quality of our error message, we should be more specific\nabout the return type and consider explicitly handling the error.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`Result`", "heading_path": ["`Result`"], "path": "error/result.md", "url": "https://doc.rust-lang.org/rust-by-example/error/result.html#result", "has_code": false, "code_tags": []}} {"id": "rust-by-example/error/result.md#using-result-in-main-2", "text": "Rust by Example › `Result` › Using `Result` in `main`\n\nThe `Result` type can also be the return type of the `main` function if\nspecified explicitly. Typically the `main` function will be of the form:\n```rust\nfn main() {\n println!(\"Hello World!\");\n}\n```\nHowever `main` is also able to have a return type of `Result`. If an error\noccurs within the `main` function it will return an error code and print a debug\nrepresentation of the error (using the [`Debug`] trait). The following example\nshows such a scenario and touches on aspects covered in [the following section].\n```rust,editable\nuse std::num::ParseIntError;\n\nfn main() -> Result<(), ParseIntError> {\n let number_str = \"10\";\n let number = match number_str.parse::() {\n Ok(number) => number,\n Err(e) => return Err(e),\n };\n println!(\"{}\", number);\n Ok(())\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`Result`", "heading_path": ["`Result`", "Using `Result` in `main`"], "path": "error/result.md", "url": "https://doc.rust-lang.org/rust-by-example/error/result.html#using-result-in-main", "has_code": true, "code_tags": ["rust", "rust,editable"]}} {"id": "rust-by-example/error/result/result_map.md#map-for-result-0", "text": "Rust by Example › `map` for `Result`\n\nPanicking in the previous example's `multiply` does not make for robust code.\nGenerally, we want to return the error to the caller so it can decide what is\nthe right way to respond to errors.\nWe first need to know what kind of error type we are dealing with. To determine\nthe `Err` type, we look to `parse()`, which is implemented with the\n`FromStr` trait for `i32`. As a result, the `Err` type is\nspecified as `ParseIntError`.\nIn the example below, the straightforward `match` statement leads to code\nthat is overall more cumbersome.\n```rust,editable\nuse std::num::ParseIntError;\n\n// With the return type rewritten, we use pattern matching without `unwrap()`.\nfn multiply(first_number_str: &str, second_number_str: &str) -> Result {\n match first_number_str.parse::() {\n Ok(first_number) => {\n match second_number_str.parse::() {\n Ok(second_number) => {\n Ok(first_number * second_number)\n },\n Err(e) => Err(e),\n }\n },\n Err(e) => Err(e),\n }\n}\n\nfn print(result: Result) {\n match result {\n Ok(n) => println!(\"n is {}\", n),\n Err(e) => println!(\"Error: {}\", e),\n }\n}\n\nfn main() {\n // This still presents a reasonable answer.\n let twenty = multiply(\"10\", \"2\");\n print(twenty);\n\n // The following now provides a much more helpful error message.\n let tt = multiply(\"t\", \"2\");\n print(tt);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`map` for `Result`", "heading_path": ["`map` for `Result`"], "path": "error/result/result_map.md", "url": "https://doc.rust-lang.org/rust-by-example/error/result/result_map.html#map-for-result", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/error/result/result_map.md#map-for-result-1", "text": "Rust by Example › `map` for `Result`\n\nLuckily, `Option`'s `map`, `and_then`, and many other combinators are also\nimplemented for `Result`. `Result` contains a complete listing.\n```rust,editable\nuse std::num::ParseIntError;\n\n// As with `Option`, we can use combinators such as `map()`.\n// This function is otherwise identical to the one above and reads:\n// Multiply if both values can be parsed from str, otherwise pass on the error.\nfn multiply(first_number_str: &str, second_number_str: &str) -> Result {\n first_number_str.parse::().and_then(|first_number| {\n second_number_str.parse::().map(|second_number| first_number * second_number)\n })\n}\n\nfn print(result: Result) {\n match result {\n Ok(n) => println!(\"n is {}\", n),\n Err(e) => println!(\"Error: {}\", e),\n }\n}\n\nfn main() {\n // This still presents a reasonable answer.\n let twenty = multiply(\"10\", \"2\");\n print(twenty);\n\n // The following now provides a much more helpful error message.\n let tt = multiply(\"t\", \"2\");\n print(tt);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`map` for `Result`", "heading_path": ["`map` for `Result`"], "path": "error/result/result_map.md", "url": "https://doc.rust-lang.org/rust-by-example/error/result/result_map.html#map-for-result", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/error/result/result_alias.md#aliases-for-result-0", "text": "Rust by Example › aliases for `Result`\n\nHow about when we want to reuse a specific `Result` type many times?\nRecall that Rust allows us to create aliases. Conveniently,\nwe can define one for the specific `Result` in question.\nAt a module level, creating aliases can be particularly helpful. Errors\nfound in a specific module often have the same `Err` type, so a single alias\ncan succinctly define *all* associated `Results`. This is so useful that the\n`std` library even supplies one: `io::Result`!\nHere's a quick example to show off the syntax:\n```rust,editable\nuse std::num::ParseIntError;\n\n// Define a generic alias for a `Result` with the error type `ParseIntError`.\ntype AliasedResult = Result;\n\n// Use the above alias to refer to our specific `Result` type.\nfn multiply(first_number_str: &str, second_number_str: &str) -> AliasedResult {\n first_number_str.parse::().and_then(|first_number| {\n second_number_str.parse::().map(|second_number| first_number * second_number)\n })\n}\n\n// Here, the alias again allows us to save some space.\nfn print(result: AliasedResult) {\n match result {\n Ok(n) => println!(\"n is {}\", n),\n Err(e) => println!(\"Error: {}\", e),\n }\n}\n\nfn main() {\n print(multiply(\"10\", \"2\"));\n print(multiply(\"t\", \"2\"));\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "aliases for `Result`", "heading_path": ["aliases for `Result`"], "path": "error/result/result_alias.md", "url": "https://doc.rust-lang.org/rust-by-example/error/result/result_alias.html#aliases-for-result", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/error/result/result_alias.md#see-also-1", "text": "Rust by Example › aliases for `Result` › See also:\n\n`io::Result`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "aliases for `Result`", "heading_path": ["aliases for `Result`", "See also:"], "path": "error/result/result_alias.md", "url": "https://doc.rust-lang.org/rust-by-example/error/result/result_alias.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/error/result/early_returns.md#early-returns-0", "text": "Rust by Example › Early returns\n\nIn the previous example, we explicitly handled the errors using combinators.\nAnother way to deal with this case analysis is to use a combination of\n`match` statements and *early returns*.\nThat is, we can simply stop executing the function and return the error if\none occurs. For some, this form of code can be easier to both read and\nwrite. Consider this version of the previous example, rewritten using early returns:\n```rust,editable\nuse std::num::ParseIntError;\n\nfn multiply(first_number_str: &str, second_number_str: &str) -> Result {\n let first_number = match first_number_str.parse::() {\n Ok(first_number) => first_number,\n Err(e) => return Err(e),\n };\n\n let second_number = match second_number_str.parse::() {\n Ok(second_number) => second_number,\n Err(e) => return Err(e),\n };\n\n Ok(first_number * second_number)\n}\n\nfn print(result: Result) {\n match result {\n Ok(n) => println!(\"n is {}\", n),\n Err(e) => println!(\"Error: {}\", e),\n }\n}\n\nfn main() {\n print(multiply(\"10\", \"2\"));\n print(multiply(\"t\", \"2\"));\n}\n```\nAt this point, we've learned to explicitly handle errors using combinators\nand early returns. While we generally want to avoid panicking, explicitly\nhandling all of our errors is cumbersome.\nIn the next section, we'll introduce `?` for the cases where we simply\nneed to `unwrap` without possibly inducing `panic`.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Early returns", "heading_path": ["Early returns"], "path": "error/result/early_returns.md", "url": "https://doc.rust-lang.org/rust-by-example/error/result/early_returns.html#early-returns", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/error/result/enter_question_mark.md#introducing--0", "text": "Rust by Example › Introducing `?`\n\nSometimes we just want the simplicity of `unwrap` without the possibility of\na `panic`. Until now, `unwrap` has forced us to nest deeper and deeper when\nwhat we really wanted was to get the variable *out*. This is exactly the purpose of `?`.\nUpon finding an `Err`, there are two valid actions to take:\n1. `panic!` which we already decided to try to avoid if possible\n2. `return` because an `Err` means it cannot be handled\n`?` is *almost*[^†] exactly equivalent to an `unwrap` which `return`s\ninstead of `panic`king on `Err`s. Let's see how we can simplify the earlier\nexample that used combinators:\n```rust,editable\nuse std::num::ParseIntError;\n\nfn multiply(first_number_str: &str, second_number_str: &str) -> Result {\n let first_number = first_number_str.parse::()?;\n let second_number = second_number_str.parse::()?;\n\n Ok(first_number * second_number)\n}\n\nfn print(result: Result) {\n match result {\n Ok(n) => println!(\"n is {}\", n),\n Err(e) => println!(\"Error: {}\", e),\n }\n}\n\nfn main() {\n print(multiply(\"10\", \"2\"));\n print(multiply(\"t\", \"2\"));\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Introducing `?`", "heading_path": ["Introducing `?`"], "path": "error/result/enter_question_mark.md", "url": "https://doc.rust-lang.org/rust-by-example/error/result/enter_question_mark.html#introducing-", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/error/result/enter_question_mark.md#the-try-macro-1", "text": "Rust by Example › Introducing `?` › The `try!` macro\n\nBefore there was `?`, the same functionality was achieved with the `try!` macro.\nThe `?` operator is now recommended, but you may still find `try!` when looking\nat older code. The same `multiply` function from the previous example\nwould look like this using `try!`:\n```rust,editable,edition2015\n// To compile and run this example without errors, while using Cargo, change the value\n// of the `edition` field, in the `[package]` section of the `Cargo.toml` file, to \"2015\".\n\nuse std::num::ParseIntError;\n\nfn multiply(first_number_str: &str, second_number_str: &str) -> Result {\n let first_number = try!(first_number_str.parse::());\n let second_number = try!(second_number_str.parse::());\n\n Ok(first_number * second_number)\n}\n\nfn print(result: Result) {\n match result {\n Ok(n) => println!(\"n is {}\", n),\n Err(e) => println!(\"Error: {}\", e),\n }\n}\n\nfn main() {\n print(multiply(\"10\", \"2\"));\n print(multiply(\"t\", \"2\"));\n}\n```\n[^†]: See re-enter ? for more details.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Introducing `?`", "heading_path": ["Introducing `?`", "The `try!` macro"], "path": "error/result/enter_question_mark.md", "url": "https://doc.rust-lang.org/rust-by-example/error/result/enter_question_mark.html#the-try-macro", "has_code": true, "code_tags": ["rust,editable,edition2015"]}} {"id": "rust-by-example/error/multiple_error_types.md#multiple-error-types-0", "text": "Rust by Example › Multiple error types\n\nThe previous examples have always been very convenient; `Result`s interact\nwith other `Result`s and `Option`s interact with other `Option`s.\nSometimes an `Option` needs to interact with a `Result`, or a\n`Result` needs to interact with a `Result`. In those\ncases, we want to manage our different error types in a way that makes them\ncomposable and easy to interact with.\nIn the following code, two instances of `unwrap` generate different error\ntypes. `Vec::first` returns an `Option`, while `parse::` returns a\n`Result`:\n```rust,editable,ignore,mdbook-runnable\nfn double_first(vec: Vec<&str>) -> i32 {\n let first = vec.first().unwrap(); // Generate error 1\n 2 * first.parse::().unwrap() // Generate error 2\n}\n\nfn main() {\n let numbers = vec![\"42\", \"93\", \"18\"];\n let empty = vec![];\n let strings = vec![\"tofu\", \"93\", \"18\"];\n\n println!(\"The first doubled is {}\", double_first(numbers));\n\n println!(\"The first doubled is {}\", double_first(empty));\n // Error 1: the input vector is empty\n\n println!(\"The first doubled is {}\", double_first(strings));\n // Error 2: the element doesn't parse to a number\n}\n```\nOver the next sections, we'll see several strategies for handling these kind of problems.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Multiple error types", "heading_path": ["Multiple error types"], "path": "error/multiple_error_types.md", "url": "https://doc.rust-lang.org/rust-by-example/error/multiple_error_types.html#multiple-error-types", "has_code": true, "code_tags": ["rust,editable,ignore,mdbook-runnable"]}} {"id": "rust-by-example/error/multiple_error_types/option_result.md#pulling-results-out-of-options-0", "text": "Rust by Example › Pulling `Result`s out of `Option`s\n\nThe most basic way of handling mixed error types is to just embed them in each\nother.\n```rust,editable\nuse std::num::ParseIntError;\n\nfn double_first(vec: Vec<&str>) -> Option> {\n vec.first().map(|first| {\n first.parse::().map(|n| 2 * n)\n })\n}\n\nfn main() {\n let numbers = vec![\"42\", \"93\", \"18\"];\n let empty = vec![];\n let strings = vec![\"tofu\", \"93\", \"18\"];\n\n println!(\"The first doubled is {:?}\", double_first(numbers));\n\n println!(\"The first doubled is {:?}\", double_first(empty));\n // Error 1: the input vector is empty\n\n println!(\"The first doubled is {:?}\", double_first(strings));\n // Error 2: the element doesn't parse to a number\n}\n```\nThere are times when we'll want to stop processing on errors (like with\n`?`) but keep going when the `Option` is `None`. The `transpose` function comes in handy to swap the `Result` and `Option`.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Pulling `Result`s out of `Option`s", "heading_path": ["Pulling `Result`s out of `Option`s"], "path": "error/multiple_error_types/option_result.md", "url": "https://doc.rust-lang.org/rust-by-example/error/multiple_error_types/option_result.html#pulling-results-out-of-options", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/error/multiple_error_types/option_result.md#pulling-results-out-of-options-1", "text": "Rust by Example › Pulling `Result`s out of `Option`s\n\n```rust,editable\nuse std::num::ParseIntError;\n\nfn double_first(vec: Vec<&str>) -> Result, ParseIntError> {\n let opt = vec.first().map(|first| {\n first.parse::().map(|n| 2 * n)\n });\n\n opt.transpose()\n}\n\nfn main() {\n let numbers = vec![\"42\", \"93\", \"18\"];\n let empty = vec![];\n let strings = vec![\"tofu\", \"93\", \"18\"];\n\n println!(\"The first doubled is {:?}\", double_first(numbers));\n println!(\"The first doubled is {:?}\", double_first(empty));\n println!(\"The first doubled is {:?}\", double_first(strings));\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Pulling `Result`s out of `Option`s", "heading_path": ["Pulling `Result`s out of `Option`s"], "path": "error/multiple_error_types/option_result.md", "url": "https://doc.rust-lang.org/rust-by-example/error/multiple_error_types/option_result.html#pulling-results-out-of-options", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/error/multiple_error_types/define_error_type.md#defining-an-error-type-0", "text": "Rust by Example › Defining an error type\n\nSometimes it simplifies the code to mask all of the different errors with a\nsingle type of error. We'll show this with a custom error.\nRust allows us to define our own error types. In general, a \"good\" error type:\n* Represents different errors with the same type\n* Presents nice error messages to the user\n* Is easy to compare with other types\n * Good: `Err(EmptyVec)`\n * Bad: `Err(\"Please use a vector with at least one element\".to_owned())`\n* Can hold information about the error\n * Good: `Err(BadChar(c, position))`\n * Bad: `Err(\"+ cannot be used here\".to_owned())`\n* Composes well with other errors", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Defining an error type", "heading_path": ["Defining an error type"], "path": "error/multiple_error_types/define_error_type.md", "url": "https://doc.rust-lang.org/rust-by-example/error/multiple_error_types/define_error_type.html#defining-an-error-type", "has_code": false, "code_tags": []}} {"id": "rust-by-example/error/multiple_error_types/define_error_type.md#defining-an-error-type-1", "text": "Rust by Example › Defining an error type\n\n```rust,editable\nuse std::fmt;\n\ntype Result = std::result::Result;\n\n// Define our error types. These may be customized for our error handling cases.\n// Now we will be able to write our own errors, defer to an underlying error\n// implementation, or do something in between.\n#[derive(Debug, Clone)]\nstruct DoubleError;\n\n// Generation of an error is completely separate from how it is displayed.\n// There's no need to be concerned about cluttering complex logic with the display style.\n//\n// Note that we don't store any extra info about the errors. This means we can't state\n// which string failed to parse without modifying our types to carry that information.\nimpl fmt::Display for DoubleError {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f, \"invalid first item to double\")\n }\n}\n\nfn double_first(vec: Vec<&str>) -> Result {\n vec.first()\n // Change the error to our new type.\n .ok_or(DoubleError)\n .and_then(|s| {\n s.parse::()\n // Update to the new error type here also.\n .map_err(|_| DoubleError)\n .map(|i| 2 * i)\n })\n}\n\nfn print(result: Result) {\n match result {\n Ok(n) => println!(\"The first doubled is {}\", n),\n Err(e) => println!(\"Error: {}\", e),\n }\n}\n\nfn main() {\n let numbers = vec![\"42\", \"93\", \"18\"];\n let empty = vec![];\n let strings = vec![\"tofu\", \"93\", \"18\"];\n\n print(double_first(numbers));\n print(double_first(empty));\n print(double_first(strings));\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Defining an error type", "heading_path": ["Defining an error type"], "path": "error/multiple_error_types/define_error_type.md", "url": "https://doc.rust-lang.org/rust-by-example/error/multiple_error_types/define_error_type.html#defining-an-error-type", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/error/multiple_error_types/boxing_errors.md#boxing-errors-0", "text": "Rust by Example › `Box`ing errors\n\nA way to write simple code while preserving the original errors is to `Box`\nthem. The drawback is that the underlying error type is only known at runtime and not\nstatically determined.\nThe stdlib helps in boxing our errors by having `Box` implement conversion from\nany type that implements the `Error` trait into the trait object `Box`,\nvia `From`.\n```rust,editable\nuse std::error;\nuse std::fmt;\n\n// Change the alias to use `Box`.\ntype Result = std::result::Result>;\n\n#[derive(Debug, Clone)]\nstruct EmptyVec;\n\nimpl fmt::Display for EmptyVec {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f, \"invalid first item to double\")\n }\n}\n\nimpl error::Error for EmptyVec {}\n\nfn double_first(vec: Vec<&str>) -> Result {\n vec.first()\n .ok_or_else(|| EmptyVec.into()) // Converts to Box using Into trait.\n .and_then(|s| {\n s.parse::()\n .map_err(From::from) // Converts to Box using From::from fn pointer.\n .map(|i| 2 * i)\n })\n}\n\nfn print(result: Result) {\n match result {\n Ok(n) => println!(\"The first doubled is {}\", n),\n Err(e) => println!(\"Error: {}\", e),\n }\n}\n\nfn main() {\n let numbers = vec![\"42\", \"93\", \"18\"];\n let empty = vec![];\n let strings = vec![\"tofu\", \"93\", \"18\"];\n\n print(double_first(numbers));\n print(double_first(empty));\n print(double_first(strings));\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`Box`ing errors", "heading_path": ["`Box`ing errors"], "path": "error/multiple_error_types/boxing_errors.md", "url": "https://doc.rust-lang.org/rust-by-example/error/multiple_error_types/boxing_errors.html#boxing-errors", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/error/multiple_error_types/boxing_errors.md#see-also-1", "text": "Rust by Example › `Box`ing errors › See also:\n\nDynamic dispatch and `Error` trait", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`Box`ing errors", "heading_path": ["`Box`ing errors", "See also:"], "path": "error/multiple_error_types/boxing_errors.md", "url": "https://doc.rust-lang.org/rust-by-example/error/multiple_error_types/boxing_errors.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/error/multiple_error_types/reenter_question_mark.md#other-uses-of--0", "text": "Rust by Example › Other uses of `?`\n\nNotice in the previous example that our immediate reaction to calling\n`parse` is to `map` the error from a library error into a boxed\nerror:\n```rust,ignore\n.and_then(|s| s.parse::())\n .map_err(|e| e.into())\n```\nSince this is a simple and common operation, it would be convenient if it\ncould be elided. Alas, because `and_then` is not sufficiently flexible, it\ncannot. However, we can instead use `?`.\n`?` was previously explained as either `unwrap` or `return Err(err)`.\nThis is only mostly true. It actually means `unwrap` or\n`return Err(From::from(err))`. Since `From::from` is a conversion utility\nbetween different types, this means that if you `?` where the error is\nconvertible to the return type, it will convert automatically.\nHere, we rewrite the previous example using `?`. As a result, the\n`map_err` will go away when `From::from` is implemented for our error type:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Other uses of `?`", "heading_path": ["Other uses of `?`"], "path": "error/multiple_error_types/reenter_question_mark.md", "url": "https://doc.rust-lang.org/rust-by-example/error/multiple_error_types/reenter_question_mark.html#other-uses-of-", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "rust-by-example/error/multiple_error_types/reenter_question_mark.md#other-uses-of--1", "text": "Rust by Example › Other uses of `?`\n\n```rust,editable\nuse std::error;\nuse std::fmt;\n\n// Change the alias to use `Box`.\ntype Result = std::result::Result>;\n\n#[derive(Debug)]\nstruct EmptyVec;\n\nimpl fmt::Display for EmptyVec {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f, \"invalid first item to double\")\n }\n}\n\nimpl error::Error for EmptyVec {}\n\n// The same structure as before but rather than chain all `Results`\n// and `Options` along, we `?` to get the inner value out immediately.\nfn double_first(vec: Vec<&str>) -> Result {\n let first = vec.first().ok_or(EmptyVec)?;\n let parsed = first.parse::()?;\n Ok(2 * parsed)\n}\n\nfn print(result: Result) {\n match result {\n Ok(n) => println!(\"The first doubled is {}\", n),\n Err(e) => println!(\"Error: {}\", e),\n }\n}\n\nfn main() {\n let numbers = vec![\"42\", \"93\", \"18\"];\n let empty = vec![];\n let strings = vec![\"tofu\", \"93\", \"18\"];\n\n print(double_first(numbers));\n print(double_first(empty));\n print(double_first(strings));\n}\n```\nThis is actually fairly clean now. Compared with the original `panic`, it\nis very similar to replacing the `unwrap` calls with `?` except that the\nreturn types are `Result`. As a result, they must be destructured at the\ntop level.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Other uses of `?`", "heading_path": ["Other uses of `?`"], "path": "error/multiple_error_types/reenter_question_mark.md", "url": "https://doc.rust-lang.org/rust-by-example/error/multiple_error_types/reenter_question_mark.html#other-uses-of-", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/error/multiple_error_types/reenter_question_mark.md#see-also-2", "text": "Rust by Example › Other uses of `?` › See also:\n\n`From::from` and `?`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Other uses of `?`", "heading_path": ["Other uses of `?`", "See also:"], "path": "error/multiple_error_types/reenter_question_mark.md", "url": "https://doc.rust-lang.org/rust-by-example/error/multiple_error_types/reenter_question_mark.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/error/multiple_error_types/wrap_error.md#wrapping-errors-0", "text": "Rust by Example › Wrapping errors\n\nAn alternative to boxing errors is to wrap them in your own error type.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Wrapping errors", "heading_path": ["Wrapping errors"], "path": "error/multiple_error_types/wrap_error.md", "url": "https://doc.rust-lang.org/rust-by-example/error/multiple_error_types/wrap_error.html#wrapping-errors", "has_code": false, "code_tags": []}} {"id": "rust-by-example/error/multiple_error_types/wrap_error.md#wrapping-errors-1", "text": "Rust by Example › Wrapping errors\n\n```rust,editable\nuse std::error;\nuse std::error::Error;\nuse std::num::ParseIntError;\nuse std::fmt;\n\ntype Result = std::result::Result;\n\n#[derive(Debug)]\nenum DoubleError {\n EmptyVec,\n // We will defer to the parse error implementation for their error.\n // Supplying extra info requires adding more data to the type.\n Parse(ParseIntError),\n}\n\nimpl fmt::Display for DoubleError {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n match *self {\n DoubleError::EmptyVec =>\n write!(f, \"please use a vector with at least one element\"),\n // The wrapped error contains additional information and is available\n // via the source() method.\n DoubleError::Parse(..) =>\n write!(f, \"the provided string could not be parsed as int\"),\n }\n }\n}\n\nimpl error::Error for DoubleError {\n fn source(&self) -> Option<&(dyn error::Error + 'static)> {\n match *self {\n DoubleError::EmptyVec => None,\n // The cause is the underlying implementation error type. Is implicitly\n // cast to the trait object `&error::Error`. This works because the\n // underlying type already implements the `Error` trait.\n DoubleError::Parse(ref e) => Some(e),\n }\n }\n}\n\n// Implement the conversion from `ParseIntError` to `DoubleError`.\n// This will be automatically called by `?` if a `ParseIntError`\n// needs to be converted into a `DoubleError`.\nimpl From for DoubleError {\n fn from(err: ParseIntError) -> DoubleError {\n DoubleError::Parse(err)\n }\n}\n\nfn double_first(vec: Vec<&str>) -> Result {\n let first = vec.first().ok_or(DoubleError::EmptyVec)?;\n // Here we implicitly use the `ParseIntError` implementation of `From` (which\n // we defined above) in order to create a `DoubleError`.\n let parsed = first.parse::()?;\n\n Ok(2 * parsed)\n}\n\nfn print(result: Result) {\n match result {\n Ok(n) => println!(\"The first doubled is {}\", n),\n Err(e) => {\n println!(\"Error: {}\", e);\n if let Some(source) = e.source() {\n println!(\" Caused by: {}\", source);\n }\n },\n }\n}\n\nfn main() {\n let numbers = vec![\"42\", \"93\", \"18\"];\n let empty = vec![];\n let strings = vec![\"tofu\", \"93\", \"18\"];\n\n print(double_first(numbers));\n print(double_first(empty));\n print(double_first(strings));\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Wrapping errors", "heading_path": ["Wrapping errors"], "path": "error/multiple_error_types/wrap_error.md", "url": "https://doc.rust-lang.org/rust-by-example/error/multiple_error_types/wrap_error.html#wrapping-errors", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/error/multiple_error_types/wrap_error.md#wrapping-errors-2", "text": "Rust by Example › Wrapping errors\n\nThis adds a bit more boilerplate for handling errors and might not be needed in\nall applications. There are some libraries that can take care of the boilerplate\nfor you.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Wrapping errors", "heading_path": ["Wrapping errors"], "path": "error/multiple_error_types/wrap_error.md", "url": "https://doc.rust-lang.org/rust-by-example/error/multiple_error_types/wrap_error.html#wrapping-errors", "has_code": false, "code_tags": []}} {"id": "rust-by-example/error/multiple_error_types/wrap_error.md#see-also-3", "text": "Rust by Example › Wrapping errors › See also:\n\n`From::from` and `Enums`\n`Crates for handling errors`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Wrapping errors", "heading_path": ["Wrapping errors", "See also:"], "path": "error/multiple_error_types/wrap_error.md", "url": "https://doc.rust-lang.org/rust-by-example/error/multiple_error_types/wrap_error.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/error/iter_result.md#iterating-over-results-0", "text": "Rust by Example › Iterating over `Result`s\n\nAn `Iter::map` operation might fail, for example:\n```rust,editable\nfn main() {\n let strings = vec![\"tofu\", \"93\", \"18\"];\n let numbers: Vec<_> = strings\n .into_iter()\n .map(|s| s.parse::())\n .collect();\n println!(\"Results: {:?}\", numbers);\n}\n```\nLet's step through strategies for handling this.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Iterating over `Result`s", "heading_path": ["Iterating over `Result`s"], "path": "error/iter_result.md", "url": "https://doc.rust-lang.org/rust-by-example/error/iter_result.html#iterating-over-results", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/error/iter_result.md#ignore-the-failed-items-with-filter_map-1", "text": "Rust by Example › Iterating over `Result`s › Ignore the failed items with `filter_map()`\n\n`filter_map` calls a function and filters out the results that are `None`.\n```rust,editable\nfn main() {\n let strings = vec![\"tofu\", \"93\", \"18\"];\n let numbers: Vec<_> = strings\n .into_iter()\n .filter_map(|s| s.parse::().ok())\n .collect();\n println!(\"Results: {:?}\", numbers);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Iterating over `Result`s", "heading_path": ["Iterating over `Result`s", "Ignore the failed items with `filter_map()`"], "path": "error/iter_result.md", "url": "https://doc.rust-lang.org/rust-by-example/error/iter_result.html#ignore-the-failed-items-with-filter_map", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/error/iter_result.md#collect-the-failed-items-with-map_err-and-filter_map-2", "text": "Rust by Example › Iterating over `Result`s › Collect the failed items with `map_err()` and `filter_map()`\n\n`map_err` calls a function with the error, so by adding that to the previous\n`filter_map` solution we can save them off to the side while iterating.\n```rust,editable\nfn main() {\n let strings = vec![\"42\", \"tofu\", \"93\", \"999\", \"18\"];\n let mut errors = vec![];\n let numbers: Vec<_> = strings\n .into_iter()\n .map(|s| s.parse::())\n .filter_map(|r| r.map_err(|e| errors.push(e)).ok())\n .collect();\n println!(\"Numbers: {:?}\", numbers);\n println!(\"Errors: {:?}\", errors);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Iterating over `Result`s", "heading_path": ["Iterating over `Result`s", "Collect the failed items with `map_err()` and `filter_map()`"], "path": "error/iter_result.md", "url": "https://doc.rust-lang.org/rust-by-example/error/iter_result.html#collect-the-failed-items-with-map_err-and-filter_map", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/error/iter_result.md#fail-the-entire-operation-with-collect-3", "text": "Rust by Example › Iterating over `Result`s › Fail the entire operation with `collect()`\n\n`Result` implements `FromIterator` so that a vector of results (`Vec>`)\ncan be turned into a result with a vector (`Result, E>`). Once an\n`Result::Err` is found, the iteration will terminate.\n```rust,editable\nfn main() {\n let strings = vec![\"tofu\", \"93\", \"18\"];\n let numbers: Result, _> = strings\n .into_iter()\n .map(|s| s.parse::())\n .collect();\n println!(\"Results: {:?}\", numbers);\n}\n```\nThis same technique can be used with `Option`.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Iterating over `Result`s", "heading_path": ["Iterating over `Result`s", "Fail the entire operation with `collect()`"], "path": "error/iter_result.md", "url": "https://doc.rust-lang.org/rust-by-example/error/iter_result.html#fail-the-entire-operation-with-collect", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/error/iter_result.md#collect-all-valid-values-and-failures-with-partition-4", "text": "Rust by Example › Iterating over `Result`s › Collect all valid values and failures with `partition()`\n\n```rust,editable\nfn main() {\n let strings = vec![\"tofu\", \"93\", \"18\"];\n let (numbers, errors): (Vec<_>, Vec<_>) = strings\n .into_iter()\n .map(|s| s.parse::())\n .partition(Result::is_ok);\n println!(\"Numbers: {:?}\", numbers);\n println!(\"Errors: {:?}\", errors);\n}\n```\nWhen you look at the results, you'll note that everything is still wrapped in\n`Result`. A little more boilerplate is needed for this.\n```rust,editable\nfn main() {\n let strings = vec![\"tofu\", \"93\", \"18\"];\n let (numbers, errors): (Vec<_>, Vec<_>) = strings\n .into_iter()\n .map(|s| s.parse::())\n .partition(Result::is_ok);\n let numbers: Vec<_> = numbers.into_iter().map(Result::unwrap).collect();\n let errors: Vec<_> = errors.into_iter().map(Result::unwrap_err).collect();\n println!(\"Numbers: {:?}\", numbers);\n println!(\"Errors: {:?}\", errors);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Iterating over `Result`s", "heading_path": ["Iterating over `Result`s", "Collect all valid values and failures with `partition()`"], "path": "error/iter_result.md", "url": "https://doc.rust-lang.org/rust-by-example/error/iter_result.html#collect-all-valid-values-and-failures-with-partition", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/std.md#std-library-types-0", "text": "Rust by Example › Std library types\n\nThe `std` library provides many custom types which expands drastically on\nthe `primitives`. Some of these include:\n* growable `String`s like: `\"hello world\"`\n* growable vectors: `[1, 2, 3]`\n* optional types: `Option`\n* error handling types: `Result`\n* heap allocated pointers: `Box`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Std library types", "heading_path": ["Std library types"], "path": "std.md", "url": "https://doc.rust-lang.org/rust-by-example/std.html#std-library-types", "has_code": false, "code_tags": []}} {"id": "rust-by-example/std.md#see-also-1", "text": "Rust by Example › Std library types › See also:\n\n[primitives] and the std library", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Std library types", "heading_path": ["Std library types", "See also:"], "path": "std.md", "url": "https://doc.rust-lang.org/rust-by-example/std.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/std/box.md#box-stack-and-heap-0", "text": "Rust by Example › Box, stack and heap\n\nAll values in Rust are stack allocated by default. Values can be *boxed*\n(allocated on the heap) by creating a `Box`. A box is a smart pointer to a\nheap allocated value of type `T`. When a box goes out of scope, its destructor\nis called, the inner object is destroyed, and the memory on the heap is freed.\nBoxed values can be dereferenced using the `*` operator; this removes one layer\nof indirection.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Box, stack and heap", "heading_path": ["Box, stack and heap"], "path": "std/box.md", "url": "https://doc.rust-lang.org/rust-by-example/std/box.html#box-stack-and-heap", "has_code": false, "code_tags": []}} {"id": "rust-by-example/std/box.md#box-stack-and-heap-1", "text": "Rust by Example › Box, stack and heap\n\n```rust,editable\nuse std::mem;\n\n#[allow(dead_code)]\n#[derive(Debug, Clone, Copy)]\nstruct Point {\n x: f64,\n y: f64,\n}\n\n// A Rectangle can be specified by where its top left and bottom right\n// corners are in space\n#[allow(dead_code)]\nstruct Rectangle {\n top_left: Point,\n bottom_right: Point,\n}\n\nfn origin() -> Point {\n Point { x: 0.0, y: 0.0 }\n}\n\nfn boxed_origin() -> Box {\n // Allocate this point on the heap, and return a pointer to it\n Box::new(Point { x: 0.0, y: 0.0 })\n}\n\nfn main() {\n // (all the type annotations are superfluous)\n // Stack allocated variables\n let point: Point = origin();\n let rectangle: Rectangle = Rectangle {\n top_left: origin(),\n bottom_right: Point { x: 3.0, y: -4.0 }\n };\n\n // Heap allocated rectangle\n let boxed_rectangle: Box = Box::new(Rectangle {\n top_left: origin(),\n bottom_right: Point { x: 3.0, y: -4.0 },\n });\n\n // The output of functions can be boxed\n let boxed_point: Box = Box::new(origin());\n\n // Double indirection\n let box_in_a_box: Box> = Box::new(boxed_origin());\n\n println!(\"Point occupies {} bytes on the stack\",\n mem::size_of_val(&point));\n println!(\"Rectangle occupies {} bytes on the stack\",\n mem::size_of_val(&rectangle));\n\n // box size == pointer size\n println!(\"Boxed point occupies {} bytes on the stack\",\n mem::size_of_val(&boxed_point));\n println!(\"Boxed rectangle occupies {} bytes on the stack\",\n mem::size_of_val(&boxed_rectangle));\n println!(\"Boxed box occupies {} bytes on the stack\",\n mem::size_of_val(&box_in_a_box));\n\n // Copy the data contained in `boxed_point` into `unboxed_point`\n let unboxed_point: Point = *boxed_point;\n println!(\"Unboxed point occupies {} bytes on the stack\",\n mem::size_of_val(&unboxed_point));\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Box, stack and heap", "heading_path": ["Box, stack and heap"], "path": "std/box.md", "url": "https://doc.rust-lang.org/rust-by-example/std/box.html#box-stack-and-heap", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/std/vec.md#vectors-0", "text": "Rust by Example › Vectors\n\nVectors are re-sizable arrays. Like slices, their size is not known at compile\ntime, but they can grow or shrink at any time. A vector is represented using\n3 parameters:\n- pointer to the data\n- length\n- capacity\nThe capacity indicates how much memory is reserved for the vector. The vector\ncan grow as long as the length is smaller than the capacity. When this threshold\nneeds to be surpassed, the vector is reallocated with a larger capacity.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Vectors", "heading_path": ["Vectors"], "path": "std/vec.md", "url": "https://doc.rust-lang.org/rust-by-example/std/vec.html#vectors", "has_code": false, "code_tags": []}} {"id": "rust-by-example/std/vec.md#vectors-1", "text": "Rust by Example › Vectors\n\n```rust,editable,ignore,mdbook-runnable\nfn main() {\n // Iterators can be collected into vectors\n let collected_iterator: Vec = (0..10).collect();\n println!(\"Collected (0..10) into: {:?}\", collected_iterator);\n\n // The `vec!` macro can be used to initialize a vector\n let mut xs = vec![1i32, 2, 3];\n println!(\"Initial vector: {:?}\", xs);\n\n // Insert new element at the end of the vector\n println!(\"Push 4 into the vector\");\n xs.push(4);\n println!(\"Vector: {:?}\", xs);\n\n // Error! Immutable vectors can't grow\n collected_iterator.push(0);\n // FIXME ^ Comment out this line\n\n // The `len` method yields the number of elements currently stored in a vector\n println!(\"Vector length: {}\", xs.len());\n\n // Indexing is done using the square brackets (indexing starts at 0)\n println!(\"Second element: {}\", xs[1]);\n\n // `pop` removes the last element from the vector and returns it\n println!(\"Pop last element: {:?}\", xs.pop());\n\n // Out of bounds indexing yields a panic\n println!(\"Fourth element: {}\", xs[3]);\n // FIXME ^ Comment out this line\n\n // `Vector`s can be easily iterated over\n println!(\"Contents of xs:\");\n for x in xs.iter() {\n println!(\"> {}\", x);\n }\n\n // A `Vector` can also be iterated over while the iteration\n // count is enumerated in a separate variable (`i`)\n for (i, x) in xs.iter().enumerate() {\n println!(\"In position {} we have value {}\", i, x);\n }\n\n // Thanks to `iter_mut`, mutable `Vector`s can also be iterated\n // over in a way that allows modifying each value\n for x in xs.iter_mut() {\n *x *= 3;\n }\n println!(\"Updated vector: {:?}\", xs);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Vectors", "heading_path": ["Vectors"], "path": "std/vec.md", "url": "https://doc.rust-lang.org/rust-by-example/std/vec.html#vectors", "has_code": true, "code_tags": ["rust,editable,ignore,mdbook-runnable"]}} {"id": "rust-by-example/std/vec.md#vectors-2", "text": "Rust by Example › Vectors\n\nMore `Vec` methods can be found under the\nstd::vec module", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Vectors", "heading_path": ["Vectors"], "path": "std/vec.md", "url": "https://doc.rust-lang.org/rust-by-example/std/vec.html#vectors", "has_code": false, "code_tags": []}} {"id": "rust-by-example/std/str.md#strings-0", "text": "Rust by Example › Strings\n\nThe two most used string types in Rust are `String` and `&str`.\nA `String` is stored as a vector of bytes (`Vec`), but guaranteed to\nalways be a valid UTF-8 sequence. `String` is heap allocated, growable and not\nnull terminated.\n`&str` is a slice (`&[u8]`) that always points to a valid UTF-8 sequence, and\ncan be used to view into a `String`, just like `&[T]` is a view into `Vec`.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Strings", "heading_path": ["Strings"], "path": "std/str.md", "url": "https://doc.rust-lang.org/rust-by-example/std/str.html#strings", "has_code": false, "code_tags": []}} {"id": "rust-by-example/std/str.md#strings-1", "text": "Rust by Example › Strings\n\n```rust,editable\nfn main() {\n // (all the type annotations are superfluous)\n // A reference to a string allocated in read only memory\n let pangram: &'static str = \"the quick brown fox jumps over the lazy dog\";\n println!(\"Pangram: {}\", pangram);\n\n // Iterate over words in reverse, no new string is allocated\n println!(\"Words in reverse\");\n for word in pangram.split_whitespace().rev() {\n println!(\"> {}\", word);\n }\n\n // Copy chars into a vector, sort and remove duplicates\n let mut chars: Vec = pangram.chars().collect();\n chars.sort();\n chars.dedup();\n\n // Create an empty and growable `String`\n let mut string = String::new();\n for c in chars {\n // Insert a char at the end of string\n string.push(c);\n // Insert a string at the end of string\n string.push_str(\", \");\n }\n\n // The trimmed string is a slice to the original string, hence no new\n // allocation is performed\n let chars_to_trim: &[char] = &[' ', ','];\n let trimmed_str: &str = string.trim_matches(chars_to_trim);\n println!(\"Used characters: {}\", trimmed_str);\n\n // Heap allocate a string\n let alice = String::from(\"I like dogs\");\n // Allocate new memory and store the modified string there\n let bob: String = alice.replace(\"dog\", \"cat\");\n\n println!(\"Alice says: {}\", alice);\n println!(\"Bob says: {}\", bob);\n}\n```\nMore `str`/`String` methods can be found under the\nstd::str and\nstd::string\nmodules", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Strings", "heading_path": ["Strings"], "path": "std/str.md", "url": "https://doc.rust-lang.org/rust-by-example/std/str.html#strings", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/std/str.md#literals-and-escapes-2", "text": "Rust by Example › Strings › Literals and escapes\n\nThere are multiple ways to write string literals with special characters in them.\nAll result in a similar `&str` so it's best to use the form that is the most\nconvenient to write. Similarly there are multiple ways to write byte string literals,\nwhich all result in `&[u8; N]`.\nGenerally special characters are escaped with a backslash character: `\\`.\nThis way you can add any character to your string, even unprintable ones\nand ones that you don't know how to type. If you want a literal backslash,\nescape it with another one: `\\\\`\nString or character literal delimiters occurring within a literal must be escaped: `\"\\\"\"`, `'\\''`.\n```rust,editable\nfn main() {\n // You can use escapes to write bytes by their hexadecimal values...\n let byte_escape = \"I'm writing \\x52\\x75\\x73\\x74!\";\n println!(\"What are you doing\\x3F (\\\\x3F means ?) {}\", byte_escape);\n\n // ...or Unicode code points.\n let unicode_codepoint = \"\\u{211D}\";\n let character_name = \"\\\"DOUBLE-STRUCK CAPITAL R\\\"\";\n\n println!(\"Unicode character {} (U+211D) is called {}\",\n unicode_codepoint, character_name );\n\n\n let long_string = \"String literals\n can span multiple lines.\n The linebreak and indentation here ->\\\n <- can be escaped too!\";\n println!(\"{}\", long_string);\n}\n```\nSometimes there are just too many characters that need to be escaped or it's just\nmuch more convenient to write a string out as-is. This is where raw string literals come into play.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Strings", "heading_path": ["Strings", "Literals and escapes"], "path": "std/str.md", "url": "https://doc.rust-lang.org/rust-by-example/std/str.html#literals-and-escapes", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/std/str.md#literals-and-escapes-3", "text": "Rust by Example › Strings › Literals and escapes\n\n```rust, editable\nfn main() {\n let raw_str = r\"Escapes don't work here: \\x3F \\u{211D}\";\n println!(\"{}\", raw_str);\n\n // If you need quotes in a raw string, add a pair of #s\n let quotes = r#\"And then I said: \"There is no escape!\"\"#;\n println!(\"{}\", quotes);\n\n // If you need \"# in your string, just use more #s in the delimiter.\n // You can use up to 255 #s.\n let longer_delimiter = r###\"A string with \"# in it. And even \"##!\"###;\n println!(\"{}\", longer_delimiter);\n}\n```\nWant a string that's not UTF-8? (Remember, `str` and `String` must be valid UTF-8).\nOr maybe you want an array of bytes that's mostly text? Byte strings to the rescue!", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Strings", "heading_path": ["Strings", "Literals and escapes"], "path": "std/str.md", "url": "https://doc.rust-lang.org/rust-by-example/std/str.html#literals-and-escapes", "has_code": true, "code_tags": ["rust, editable"]}} {"id": "rust-by-example/std/str.md#literals-and-escapes-4", "text": "Rust by Example › Strings › Literals and escapes\n\n```rust, editable\nuse std::str;\n\nfn main() {\n // Note that this is not actually a `&str`\n let bytestring: &[u8; 21] = b\"this is a byte string\";\n\n // Byte arrays don't have the `Display` trait, so printing them is a bit limited\n println!(\"A byte string: {:?}\", bytestring);\n\n // Byte strings can have byte escapes...\n let escaped = b\"\\x52\\x75\\x73\\x74 as bytes\";\n // ...but no unicode escapes\n // let escaped = b\"\\u{211D} is not allowed\";\n println!(\"Some escaped bytes: {:?}\", escaped);\n\n\n // Raw byte strings work just like raw strings\n let raw_bytestring = br\"\\u{211D} is not escaped here\";\n println!(\"{:?}\", raw_bytestring);\n\n // Converting a byte array to `str` can fail\n if let Ok(my_str) = str::from_utf8(raw_bytestring) {\n println!(\"And the same as text: '{}'\", my_str);\n }\n\n let _quotes = br#\"You can also use \"fancier\" formatting, \\\n like with normal raw strings\"#;\n\n // Byte strings don't have to be UTF-8\n let shift_jis = b\"\\x82\\xe6\\x82\\xa8\\x82\\xb1\\x82\\xbb\"; // \"ようこそ\" in SHIFT-JIS\n\n // But then they can't always be converted to `str`\n match str::from_utf8(shift_jis) {\n Ok(my_str) => println!(\"Conversion successful: '{}'\", my_str),\n Err(e) => println!(\"Conversion failed: {:?}\", e),\n };\n}\n```\nFor conversions between character encodings check out the encoding crate.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Strings", "heading_path": ["Strings", "Literals and escapes"], "path": "std/str.md", "url": "https://doc.rust-lang.org/rust-by-example/std/str.html#literals-and-escapes", "has_code": true, "code_tags": ["rust, editable"]}} {"id": "rust-by-example/std/str.md#literals-and-escapes-5", "text": "Rust by Example › Strings › Literals and escapes\n\nA more detailed listing of the ways to write string literals and escape characters\nis given in the 'Tokens' chapter of the Rust Reference.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Strings", "heading_path": ["Strings", "Literals and escapes"], "path": "std/str.md", "url": "https://doc.rust-lang.org/rust-by-example/std/str.html#literals-and-escapes", "has_code": false, "code_tags": []}} {"id": "rust-by-example/std/option.md#option-0", "text": "Rust by Example › `Option`\n\nSometimes it's desirable to catch the failure of some parts of a program\ninstead of calling `panic!`; this can be accomplished using the `Option` enum.\nThe `Option` enum has two variants:\n* `None`, to indicate failure or lack of value, and\n* `Some(value)`, a tuple struct that wraps a `value` with type `T`.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`Option`", "heading_path": ["`Option`"], "path": "std/option.md", "url": "https://doc.rust-lang.org/rust-by-example/std/option.html#option", "has_code": false, "code_tags": []}} {"id": "rust-by-example/std/option.md#option-1", "text": "Rust by Example › `Option`\n\n```rust,editable,ignore,mdbook-runnable\n// An integer division that doesn't `panic!`\nfn checked_division(dividend: i32, divisor: i32) -> Option {\n if divisor == 0 {\n // Failure is represented as the `None` variant\n None\n } else {\n // Result is wrapped in a `Some` variant\n Some(dividend / divisor)\n }\n}\n\n// This function handles a division that may not succeed\nfn try_division(dividend: i32, divisor: i32) {\n // `Option` values can be pattern matched, just like other enums\n match checked_division(dividend, divisor) {\n None => println!(\"{} / {} failed!\", dividend, divisor),\n Some(quotient) => {\n println!(\"{} / {} = {}\", dividend, divisor, quotient)\n },\n }\n}\n\nfn main() {\n try_division(4, 2);\n try_division(1, 0);\n\n // Binding `None` to a variable needs to be type annotated\n let none: Option = None;\n let _equivalent_none = None::;\n\n let optional_float = Some(0f32);\n\n // Unwrapping a `Some` variant will extract the value wrapped.\n println!(\"{:?} unwraps to {:?}\", optional_float, optional_float.unwrap());\n\n // Unwrapping a `None` variant will `panic!`\n println!(\"{:?} unwraps to {:?}\", none, none.unwrap());\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`Option`", "heading_path": ["`Option`"], "path": "std/option.md", "url": "https://doc.rust-lang.org/rust-by-example/std/option.html#option", "has_code": true, "code_tags": ["rust,editable,ignore,mdbook-runnable"]}} {"id": "rust-by-example/std/result.md#result-0", "text": "Rust by Example › `Result`\n\nWe've seen that the `Option` enum can be used as a return value from functions\nthat may fail, where `None` can be returned to indicate failure. However,\nsometimes it is important to express *why* an operation failed. To do this we\nhave the `Result` enum.\nThe `Result` enum has two variants:\n* `Ok(value)` which indicates that the operation succeeded, and wraps the\n `value` returned by the operation. (`value` has type `T`)\n* `Err(why)`, which indicates that the operation failed, and wraps `why`,\n which (hopefully) explains the cause of the failure. (`why` has type `E`)", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`Result`", "heading_path": ["`Result`"], "path": "std/result.md", "url": "https://doc.rust-lang.org/rust-by-example/std/result.html#result", "has_code": false, "code_tags": []}} {"id": "rust-by-example/std/result.md#result-1", "text": "Rust by Example › `Result`\n\n```rust,editable,ignore,mdbook-runnable\nmod checked {\n // Mathematical \"errors\" we want to catch\n #[derive(Debug)]\n pub enum MathError {\n DivisionByZero,\n NonPositiveLogarithm,\n NegativeSquareRoot,\n }\n\n pub type MathResult = Result;\n\n pub fn div(x: f64, y: f64) -> MathResult {\n if y == 0.0 {\n // This operation would `fail`, instead let's return the reason of\n // the failure wrapped in `Err`\n Err(MathError::DivisionByZero)\n } else {\n // This operation is valid, return the result wrapped in `Ok`\n Ok(x / y)\n }\n }\n\n pub fn sqrt(x: f64) -> MathResult {\n if x < 0.0 {\n Err(MathError::NegativeSquareRoot)\n } else {\n Ok(x.sqrt())\n }\n }\n\n pub fn ln(x: f64) -> MathResult {\n if x <= 0.0 {\n Err(MathError::NonPositiveLogarithm)\n } else {\n Ok(x.ln())\n }\n }\n}\n\n// `op(x, y)` === `sqrt(ln(x / y))`\nfn op(x: f64, y: f64) -> f64 {\n // This is a three level match pyramid!\n match checked::div(x, y) {\n Err(why) => panic!(\"{:?}\", why),\n Ok(ratio) => match checked::ln(ratio) {\n Err(why) => panic!(\"{:?}\", why),\n Ok(ln) => match checked::sqrt(ln) {\n Err(why) => panic!(\"{:?}\", why),\n Ok(sqrt) => sqrt,\n },\n },\n }\n}\n\nfn main() {\n // Will this fail?\n println!(\"{}\", op(1.0, 10.0));\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`Result`", "heading_path": ["`Result`"], "path": "std/result.md", "url": "https://doc.rust-lang.org/rust-by-example/std/result.html#result", "has_code": true, "code_tags": ["rust,editable,ignore,mdbook-runnable"]}} {"id": "rust-by-example/std/result/question_mark.md#section-0", "text": "Rust by Example › `?`\n\nChaining results using match can get pretty untidy; luckily, the `?` operator\ncan be used to make things pretty again. `?` is used at the end of an expression\nreturning a `Result`, and is equivalent to a match expression, where the\n`Err(err)` branch expands to an early `return Err(From::from(err))`, and the `Ok(ok)`\nbranch expands to an `ok` expression.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`?`", "heading_path": ["`?`"], "path": "std/result/question_mark.md", "url": "https://doc.rust-lang.org/rust-by-example/std/result/question_mark.html", "has_code": false, "code_tags": []}} {"id": "rust-by-example/std/result/question_mark.md#section-1", "text": "Rust by Example › `?`\n\n```rust,editable,ignore,mdbook-runnable\nmod checked {\n #[derive(Debug)]\n enum MathError {\n DivisionByZero,\n NonPositiveLogarithm,\n NegativeSquareRoot,\n }\n\n type MathResult = Result;\n\n fn div(x: f64, y: f64) -> MathResult {\n if y == 0.0 {\n Err(MathError::DivisionByZero)\n } else {\n Ok(x / y)\n }\n }\n\n fn sqrt(x: f64) -> MathResult {\n if x < 0.0 {\n Err(MathError::NegativeSquareRoot)\n } else {\n Ok(x.sqrt())\n }\n }\n\n fn ln(x: f64) -> MathResult {\n if x <= 0.0 {\n Err(MathError::NonPositiveLogarithm)\n } else {\n Ok(x.ln())\n }\n }\n\n // Intermediate function\n fn op_(x: f64, y: f64) -> MathResult {\n // if `div` \"fails\", then `DivisionByZero` will be `return`ed\n let ratio = div(x, y)?;\n\n // if `ln` \"fails\", then `NonPositiveLogarithm` will be `return`ed\n let ln = ln(ratio)?;\n\n sqrt(ln)\n }\n\n pub fn op(x: f64, y: f64) {\n match op_(x, y) {\n Err(why) => panic!(\"{}\", match why {\n MathError::NonPositiveLogarithm\n => \"logarithm of non-positive number\",\n MathError::DivisionByZero\n => \"division by zero\",\n MathError::NegativeSquareRoot\n => \"square root of negative number\",\n }),\n Ok(value) => println!(\"{}\", value),\n }\n }\n}\n\nfn main() {\n checked::op(1.0, 10.0);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`?`", "heading_path": ["`?`"], "path": "std/result/question_mark.md", "url": "https://doc.rust-lang.org/rust-by-example/std/result/question_mark.html", "has_code": true, "code_tags": ["rust,editable,ignore,mdbook-runnable"]}} {"id": "rust-by-example/std/result/question_mark.md#section-2", "text": "Rust by Example › `?`\n\nBe sure to check the documentation,\nas there are many methods to map/compose `Result`.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`?`", "heading_path": ["`?`"], "path": "std/result/question_mark.md", "url": "https://doc.rust-lang.org/rust-by-example/std/result/question_mark.html", "has_code": false, "code_tags": []}} {"id": "rust-by-example/std/panic.md#panic-0", "text": "Rust by Example › `panic!`\n\nThe `panic!` macro can be used to generate a panic and start unwinding\nits stack. While unwinding, the runtime will take care of freeing all the\nresources *owned* by the thread by calling the destructor of all its objects.\nSince we are dealing with programs with only one thread, `panic!` will cause the\nprogram to report the panic message and exit.\n```rust,editable,ignore,mdbook-runnable\n// Re-implementation of integer division (/)\nfn division(dividend: i32, divisor: i32) -> i32 {\n if divisor == 0 {\n // Division by zero triggers a panic\n panic!(\"division by zero\");\n } else {\n dividend / divisor\n }\n}\n\n// The `main` task\nfn main() {\n // Heap allocated integer\n let _x = Box::new(0i32);\n\n // This operation will trigger a task failure\n division(3, 0);\n\n println!(\"This point won't be reached!\");\n\n // `_x` should get destroyed at this point\n}\n```\nLet's check that `panic!` doesn't leak memory.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`panic!`", "heading_path": ["`panic!`"], "path": "std/panic.md", "url": "https://doc.rust-lang.org/rust-by-example/std/panic.html#panic", "has_code": true, "code_tags": ["rust,editable,ignore,mdbook-runnable"]}} {"id": "rust-by-example/std/panic.md#panic-1", "text": "Rust by Example › `panic!`\n\n```shell\n$ rustc panic.rs && valgrind ./panic\n==4401== Memcheck, a memory error detector\n==4401== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.\n==4401== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info\n==4401== Command: ./panic\n==4401==\nthread '
' panicked at 'division by zero', panic.rs:5\n==4401==\n==4401== HEAP SUMMARY:\n==4401== in use at exit: 0 bytes in 0 blocks\n==4401== total heap usage: 18 allocs, 18 frees, 1,648 bytes allocated\n==4401==\n==4401== All heap blocks were freed -- no leaks are possible\n==4401==\n==4401== For counts of detected and suppressed errors, rerun with: -v\n==4401== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`panic!`", "heading_path": ["`panic!`"], "path": "std/panic.md", "url": "https://doc.rust-lang.org/rust-by-example/std/panic.html#panic", "has_code": true, "code_tags": ["shell"]}} {"id": "rust-by-example/std/hash.md#hashmap-0", "text": "Rust by Example › HashMap\n\nWhere vectors store values by an integer index, `HashMap`s store values by key.\n`HashMap` keys can be booleans, integers, strings,\nor any other type that implements the `Eq` and `Hash` traits.\nMore on this in the next section.\nLike vectors, `HashMap`s are growable, but HashMaps can also shrink themselves\nwhen they have excess space.\nYou can create a HashMap with a certain starting capacity using\n`HashMap::with_capacity(uint)`, or use `HashMap::new()` to get a HashMap\nwith a default initial capacity (recommended).", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "HashMap", "heading_path": ["HashMap"], "path": "std/hash.md", "url": "https://doc.rust-lang.org/rust-by-example/std/hash.html#hashmap", "has_code": false, "code_tags": []}} {"id": "rust-by-example/std/hash.md#hashmap-1", "text": "Rust by Example › HashMap\n\n```rust,editable\nuse std::collections::HashMap;\n\nfn call(number: &str) -> &str {\n match number {\n \"798-1364\" => \"We're sorry, the call cannot be completed as dialed.\n Please hang up and try again.\",\n \"645-7689\" => \"Hello, this is Mr. Awesome's Pizza. My name is Fred.\n What can I get for you today?\",\n _ => \"Hi! Who is this again?\"\n }\n}\n\nfn main() {\n let mut contacts = HashMap::new();\n\n contacts.insert(\"Daniel\", \"798-1364\");\n contacts.insert(\"Ashley\", \"645-7689\");\n contacts.insert(\"Katie\", \"435-8291\");\n contacts.insert(\"Robert\", \"956-1745\");\n\n // Takes a reference and returns Option<&V>\n match contacts.get(&\"Daniel\") {\n Some(&number) => println!(\"Calling Daniel: {}\", call(number)),\n _ => println!(\"Don't have Daniel's number.\"),\n }\n\n // `HashMap::insert()` returns `None`\n // if the inserted value is new, `Some(value)` otherwise\n contacts.insert(\"Daniel\", \"164-6743\");\n\n match contacts.get(&\"Ashley\") {\n Some(&number) => println!(\"Calling Ashley: {}\", call(number)),\n _ => println!(\"Don't have Ashley's number.\"),\n }\n\n contacts.remove(&\"Ashley\");\n\n // `HashMap::iter()` returns an iterator that yields\n // (&'a key, &'a value) pairs in arbitrary order.\n for (contact, &number) in contacts.iter() {\n println!(\"Calling {}: {}\", contact, call(number));\n }\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "HashMap", "heading_path": ["HashMap"], "path": "std/hash.md", "url": "https://doc.rust-lang.org/rust-by-example/std/hash.html#hashmap", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/std/hash.md#hashmap-2", "text": "Rust by Example › HashMap\n\nFor more information on how hashing and hash maps\n(sometimes called hash tables) work, have a look at\nHash Table Wikipedia", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "HashMap", "heading_path": ["HashMap"], "path": "std/hash.md", "url": "https://doc.rust-lang.org/rust-by-example/std/hash.html#hashmap", "has_code": false, "code_tags": []}} {"id": "rust-by-example/std/hash/alt_key_types.md#alternatecustom-key-types-0", "text": "Rust by Example › Alternate/custom key types\n\nAny type that implements the `Eq` and `Hash` traits can be a key in `HashMap`.\nThis includes:\n* `bool` (though not very useful since there are only two possible keys)\n* `int`, `uint`, and all variations thereof\n* `String` and `&str` (protip: you can have a `HashMap` keyed by `String`\nand call `.get()` with an `&str`)\nNote that `f32` and `f64` do *not* implement `Hash`,\nlikely because floating-point precision errors\nwould make using them as hashmap keys horribly error-prone.\nAll collection classes implement `Eq` and `Hash`\nif their contained type also respectively implements `Eq` and `Hash`.\nFor example, `Vec` will implement `Hash` if `T` implements `Hash`.\nYou can easily implement `Eq` and `Hash` for a custom type with just one line:\n`#[derive(PartialEq, Eq, Hash)]`\nThe compiler will do the rest. If you want more control over the details,\nyou can implement `Eq` and/or `Hash` yourself.\nThis guide will not cover the specifics of implementing `Hash`.\nTo play around with using a `struct` in `HashMap`,\nlet's try making a very simple user logon system:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Alternate/custom key types", "heading_path": ["Alternate/custom key types"], "path": "std/hash/alt_key_types.md", "url": "https://doc.rust-lang.org/rust-by-example/std/hash/alt_key_types.html#alternatecustom-key-types", "has_code": false, "code_tags": []}} {"id": "rust-by-example/std/hash/alt_key_types.md#alternatecustom-key-types-1", "text": "Rust by Example › Alternate/custom key types\n\n```rust,editable\nuse std::collections::HashMap;\n\n// Eq requires that you derive PartialEq on the type.\n#[derive(PartialEq, Eq, Hash)]\nstruct Account<'a>{\n username: &'a str,\n password: &'a str,\n}\n\nstruct AccountInfo<'a>{\n name: &'a str,\n email: &'a str,\n}\n\ntype Accounts<'a> = HashMap, AccountInfo<'a>>;\n\nfn try_logon<'a>(accounts: &Accounts<'a>,\n username: &'a str, password: &'a str){\n println!(\"Username: {}\", username);\n println!(\"Password: {}\", password);\n println!(\"Attempting logon...\");\n\n let logon = Account {\n username,\n password,\n };\n\n match accounts.get(&logon) {\n Some(account_info) => {\n println!(\"Successful logon!\");\n println!(\"Name: {}\", account_info.name);\n println!(\"Email: {}\", account_info.email);\n },\n _ => println!(\"Login failed!\"),\n }\n}\n\nfn main(){\n let mut accounts: Accounts = HashMap::new();\n\n let account = Account {\n username: \"j.everyman\",\n password: \"password123\",\n };\n\n let account_info = AccountInfo {\n name: \"John Everyman\",\n email: \"j.everyman@email.com\",\n };\n\n accounts.insert(account, account_info);\n\n try_logon(&accounts, \"j.everyman\", \"psasword123\");\n\n try_logon(&accounts, \"j.everyman\", \"password123\");\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Alternate/custom key types", "heading_path": ["Alternate/custom key types"], "path": "std/hash/alt_key_types.md", "url": "https://doc.rust-lang.org/rust-by-example/std/hash/alt_key_types.html#alternatecustom-key-types", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/std/hash/hashset.md#hashset-0", "text": "Rust by Example › HashSet\n\nConsider a `HashSet` as a `HashMap` where we just care about the keys (\n`HashSet` is, in actuality, just a wrapper around `HashMap`).\n\"What's the point of that?\" you ask. \"I could just store the keys in a `Vec`.\"\nA `HashSet`'s unique feature is that\nit is guaranteed to not have duplicate elements.\nThat's the contract that any set collection fulfills.\n`HashSet` is just one implementation. (see also: `BTreeSet`)\nIf you insert a value that is already present in the `HashSet`,\n(i.e. the new value is equal to the existing and they both have the same hash),\nthen the new value will replace the old.\nThis is great for when you never want more than one of something,\nor when you want to know if you've already got something.\nBut sets can do more than that.\nSets have 4 primary operations (all of the following calls return an iterator):\n* `union`: get all the unique elements in both sets.\n* `difference`: get all the elements that are in the first set but not the second.\n* `intersection`: get all the elements that are only in *both* sets.\n* `symmetric_difference`:\nget all the elements that are in one set or the other, but *not* both.\nTry all of these in the following example:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "HashSet", "heading_path": ["HashSet"], "path": "std/hash/hashset.md", "url": "https://doc.rust-lang.org/rust-by-example/std/hash/hashset.html#hashset", "has_code": false, "code_tags": []}} {"id": "rust-by-example/std/hash/hashset.md#hashset-1", "text": "Rust by Example › HashSet\n\n```rust,editable,ignore,mdbook-runnable\nuse std::collections::HashSet;\n\nfn main() {\n let mut a: HashSet = vec![1i32, 2, 3].into_iter().collect();\n let mut b: HashSet = vec![2i32, 3, 4].into_iter().collect();\n\n assert!(a.insert(4));\n assert!(a.contains(&4));\n\n // `HashSet::insert()` returns false if\n // there was a value already present.\n assert!(b.insert(4), \"Value 4 is already in set B!\");\n // FIXME ^ Comment out this line\n\n b.insert(5);\n\n // If a collection's element type implements `Debug`,\n // then the collection implements `Debug`.\n // It usually prints its elements in the format `[elem1, elem2, ...]`\n println!(\"A: {:?}\", a);\n println!(\"B: {:?}\", b);\n\n // Print [1, 2, 3, 4, 5] in arbitrary order\n println!(\"Union: {:?}\", a.union(&b).collect::>());\n\n // This should print [1]\n println!(\"Difference: {:?}\", a.difference(&b).collect::>());\n\n // Print [2, 3, 4] in arbitrary order.\n println!(\"Intersection: {:?}\", a.intersection(&b).collect::>());\n\n // Print [1, 5]\n println!(\"Symmetric Difference: {:?}\",\n a.symmetric_difference(&b).collect::>());\n}\n```\n(Examples are adapted from the documentation.)", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "HashSet", "heading_path": ["HashSet"], "path": "std/hash/hashset.md", "url": "https://doc.rust-lang.org/rust-by-example/std/hash/hashset.html#hashset", "has_code": true, "code_tags": ["rust,editable,ignore,mdbook-runnable"]}} {"id": "rust-by-example/std/rc.md#rc-0", "text": "Rust by Example › `Rc`\n\nWhen multiple ownership is needed, `Rc`(Reference Counting) can be used. `Rc`\nkeeps track of the number of the references which means the number of owners of\nthe value wrapped inside an `Rc`.\nReference count of an `Rc` increases by 1 whenever an `Rc` is cloned, and\ndecreases by 1 whenever one cloned `Rc` is dropped out of the scope. When an\n`Rc`'s reference count becomes zero (which means there are no remaining owners),\nboth the `Rc` and the value are all dropped.\nCloning an `Rc` never performs a deep copy. Cloning creates just another pointer\nto the wrapped value, and increments the count.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`Rc`", "heading_path": ["`Rc`"], "path": "std/rc.md", "url": "https://doc.rust-lang.org/rust-by-example/std/rc.html#rc", "has_code": false, "code_tags": []}} {"id": "rust-by-example/std/rc.md#rc-1", "text": "Rust by Example › `Rc`\n\n```rust,editable\nuse std::rc::Rc;\n\nfn main() {\n let rc_examples = \"Rc examples\".to_string();\n {\n println!(\"--- rc_a is created ---\");\n\n let rc_a: Rc = Rc::new(rc_examples);\n println!(\"Reference Count of rc_a: {}\", Rc::strong_count(&rc_a));\n\n {\n println!(\"--- rc_a is cloned to rc_b ---\");\n\n let rc_b: Rc = Rc::clone(&rc_a);\n println!(\"Reference Count of rc_b: {}\", Rc::strong_count(&rc_b));\n println!(\"Reference Count of rc_a: {}\", Rc::strong_count(&rc_a));\n\n // Two `Rc`s are equal if their inner values are equal\n println!(\"rc_a and rc_b are equal: {}\", rc_a.eq(&rc_b));\n\n // We can use methods of a value directly\n println!(\"Length of the value inside rc_a: {}\", rc_a.len());\n println!(\"Value of rc_b: {}\", rc_b);\n\n println!(\"--- rc_b is dropped out of scope ---\");\n }\n\n println!(\"Reference Count of rc_a: {}\", Rc::strong_count(&rc_a));\n\n println!(\"--- rc_a is dropped out of scope ---\");\n }\n\n // Error! `rc_examples` already moved into `rc_a`\n // And when `rc_a` is dropped, `rc_examples` is dropped together\n // println!(\"rc_examples: {}\", rc_examples);\n // TODO ^ Try uncommenting this line\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`Rc`", "heading_path": ["`Rc`"], "path": "std/rc.md", "url": "https://doc.rust-lang.org/rust-by-example/std/rc.html#rc", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/std/rc.md#see-also-2", "text": "Rust by Example › `Rc` › See also:\n\nstd::rc and std::sync::arc.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`Rc`", "heading_path": ["`Rc`", "See also:"], "path": "std/rc.md", "url": "https://doc.rust-lang.org/rust-by-example/std/rc.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/std/arc.md#arc-0", "text": "Rust by Example › Arc\n\nWhen shared ownership between threads is needed, `Arc`(Atomically Reference\nCounted) can be used. This struct, via the `Clone` implementation can create\na reference pointer for the location of a value in the memory heap while\nincreasing the reference counter. As it shares ownership between threads, when\nthe last reference pointer to a value is out of scope, the variable is dropped.\n```rust,editable\nuse std::time::Duration;\nuse std::sync::Arc;\nuse std::thread;\n\nfn main() {\n // This variable declaration is where its value is specified.\n let apple = Arc::new(\"the same apple\");\n\n for _ in 0..10 {\n // Here there is no value specification as it is a pointer to a\n // reference in the memory heap.\n let apple = Arc::clone(&apple);\n\n thread::spawn(move || {\n // As Arc was used, threads can be spawned using the value allocated\n // in the Arc variable pointer's location.\n println!(\"{:?}\", apple);\n });\n }\n\n // Make sure all Arc instances are printed from spawned threads.\n thread::sleep(Duration::from_secs(1));\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`Arc`", "heading_path": ["Arc"], "path": "std/arc.md", "url": "https://doc.rust-lang.org/rust-by-example/std/arc.html#arc", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/std_misc.md#std-misc-0", "text": "Rust by Example › Std misc\n\nMany other types are provided by the std library to support\nthings such as:\n* Threads\n* Channels\n* File I/O\nThese expand beyond what the [primitives] provide.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Std misc", "heading_path": ["Std misc"], "path": "std_misc.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc.html#std-misc", "has_code": false, "code_tags": []}} {"id": "rust-by-example/std_misc.md#see-also-1", "text": "Rust by Example › Std misc › See also:\n\n[primitives] and the std library", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Std misc", "heading_path": ["Std misc", "See also:"], "path": "std_misc.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/std_misc/threads.md#threads-0", "text": "Rust by Example › Threads\n\nRust provides a mechanism for spawning native OS threads via the `spawn`\nfunction, the argument of this function is a moving closure.\n```rust,editable\nuse std::thread;\n\nconst NTHREADS: u32 = 10;\n\n// This is the `main` thread\nfn main() {\n // Make a vector to hold the children which are spawned.\n let mut children = vec![];\n\n for i in 0..NTHREADS {\n // Spin up another thread\n children.push(thread::spawn(move || {\n println!(\"this is thread number {}\", i);\n }));\n }\n\n for child in children {\n // Wait for the thread to finish. Returns a result.\n let _ = child.join();\n }\n}\n```\nThese threads will be scheduled by the OS.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Threads", "heading_path": ["Threads"], "path": "std_misc/threads.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc/threads.html#threads", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/std_misc/threads/testcase_mapreduce.md#testcase-map-reduce-0", "text": "Rust by Example › Testcase: map-reduce\n\nRust makes it very easy to parallelize data processing, without many of the headaches traditionally associated with such an attempt.\nThe standard library provides great threading primitives out of the box.\nThese, combined with Rust's concept of Ownership and aliasing rules, automatically prevent\ndata races.\nThe aliasing rules (one writable reference XOR many readable references) automatically prevent\nyou from manipulating state that is visible to other threads. (Where synchronization is needed,\nthere are synchronization\nprimitives like `Mutex`es or `Channel`s.)\nIn this example, we will calculate the sum of all digits in a block of numbers.\nWe will do this by parcelling out chunks of the block into different threads. Each thread will sum\nits tiny block of digits, and subsequently we will sum the intermediate sums produced by each\nthread.\nNote that, although we're passing references across thread boundaries, Rust understands that we're\nonly passing read-only references, and that thus no unsafety or data races can occur. Also because\nthe references we're passing have `'static` lifetimes, Rust understands that our data won't be\ndestroyed while these threads are still running. (When you need to share non-`static` data between\nthreads, you can use a smart pointer like `Arc` to keep the data alive and avoid non-`static`\nlifetimes.)", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Testcase: map-reduce", "heading_path": ["Testcase: map-reduce"], "path": "std_misc/threads/testcase_mapreduce.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc/threads/testcase_mapreduce.html#testcase-map-reduce", "has_code": false, "code_tags": []}} {"id": "rust-by-example/std_misc/threads/testcase_mapreduce.md#testcase-map-reduce-1", "text": "Rust by Example › Testcase: map-reduce\n\n```rust,editable\nuse std::thread;\n\n// This is the `main` thread\nfn main() {\n\n // This is our data to process.\n // We will calculate the sum of all digits via a threaded map-reduce algorithm.\n // Each whitespace separated chunk will be handled in a different thread.\n //\n // TODO: see what happens to the output if you insert spaces!\n let data = \"86967897737416471853297327050364959\n11861322575564723963297542624962850\n70856234701860851907960690014725639\n38397966707106094172783238747669219\n52380795257888236525459303330302837\n58495327135744041048897885734297812\n69920216438980873548808413720956532\n16278424637452589860345374828574668\";\n\n // Make a vector to hold the child-threads which we will spawn.\n let mut children = vec![];\n\n /*************************************************************************\n * \"Map\" phase\n *\n * Divide our data into segments, and apply initial processing\n ************************************************************************/\n\n // split our data into segments for individual calculation\n // each chunk will be a reference (&str) into the actual data\n let chunked_data = data.split_whitespace();\n\n // Iterate over the data segments.\n // .enumerate() adds the current loop index to whatever is iterated\n // the resulting tuple \"(index, element)\" is then immediately\n // \"destructured\" into two variables, \"i\" and \"data_segment\" with a\n // \"destructuring assignment\"\n for (i, data_segment) in chunked_data.enumerate() {\n println!(\"data segment {} is \\\"{}\\\"\", i, data_segment);\n\n // Process each data segment in a separate thread\n //\n // spawn() returns a handle to the new thread,\n // which we MUST keep to access the returned value\n //\n // 'move || -> u32' is syntax for a closure that:\n // * takes no arguments ('||')\n // * takes ownership of its captured variables ('move') and\n // * returns an unsigned 32-bit integer ('-> u32')\n //\n // Rust is smart enough to infer the '-> u32' from\n // the closure itself so we could have left that out.\n //\n // TODO: try removing the 'move' and see what happens\n children.push(thread::spawn(move || -> u32 {\n // Calculate the intermediate sum of this segment:\n let result = data_segment\n // iterate over the characters of our segment..\n .chars()\n // .. convert text-characters to their number value..\n .map(|c| c.to_digit(10).expect(\"should be a digit\"))\n // .. and sum the resulting iterator of numbers\n .sum();\n\n // println! locks stdout, so no text-interleaving occurs\n println!(\"processed segment {}, result={}\", i, result);\n\n // \"return\" not needed, because Rust is an \"expression language\", the\n // last evaluated expression in each block is automatically its value.\n result\n\n }));\n }\n\n\n /*************************************************************************\n * \"Reduce\" phase\n *\n * Collect our intermediate results, and combine them into a final result\n ************************************************************************/\n\n // combine each thread's intermediate results into a single final sum.\n //\n // we use the \"turbofish\" ::<> to provide sum() with a type hint.\n //\n // TODO: try without the turbofish, by instead explicitly\n // specifying the type of final_result\n let final_result = children.into_iter().map(|c| c.join().unwrap()).sum::();\n\n println!(\"Final sum result: {}\", final_result);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Testcase: map-reduce", "heading_path": ["Testcase: map-reduce"], "path": "std_misc/threads/testcase_mapreduce.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc/threads/testcase_mapreduce.html#testcase-map-reduce", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/std_misc/threads/testcase_mapreduce.md#assignments-2", "text": "Rust by Example › Testcase: map-reduce › Assignments\n\nIt is not wise to let our number of threads depend on user inputted data.\nWhat if the user decides to insert a lot of spaces? Do we _really_ want to spawn 2,000 threads?\nModify the program so that the data is always chunked into a limited number of chunks,\ndefined by a static constant at the beginning of the program.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Testcase: map-reduce", "heading_path": ["Testcase: map-reduce", "Assignments"], "path": "std_misc/threads/testcase_mapreduce.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc/threads/testcase_mapreduce.html#assignments", "has_code": false, "code_tags": []}} {"id": "rust-by-example/std_misc/threads/testcase_mapreduce.md#see-also-3", "text": "Rust by Example › Testcase: map-reduce › See also:\n\n* Threads\n* vectors and iterators\n* closures, move semantics and `move` closures\n* destructuring assignments\n* turbofish notation to help type inference\n* unwrap vs. expect\n* enumerate", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Testcase: map-reduce", "heading_path": ["Testcase: map-reduce", "See also:"], "path": "std_misc/threads/testcase_mapreduce.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc/threads/testcase_mapreduce.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/std_misc/channels.md#channels-0", "text": "Rust by Example › Channels\n\nRust provides asynchronous `channels` for communication between threads. Channels\nallow a unidirectional flow of information between two end-points: the\n`Sender` and the `Receiver`.\n```rust,editable\nuse std::sync::mpsc::{Sender, Receiver};\nuse std::sync::mpsc;\nuse std::thread;\n\nstatic NTHREADS: i32 = 3;\n\nfn main() {\n // Channels have two endpoints: the `Sender` and the `Receiver`,\n // where `T` is the type of the message to be transferred\n // (type annotation is superfluous)\n let (tx, rx): (Sender, Receiver) = mpsc::channel();\n let mut children = Vec::new();\n\n for id in 0..NTHREADS {\n // The sender endpoint can be copied\n let thread_tx = tx.clone();\n\n // Each thread will send its id via the channel\n let child = thread::spawn(move || {\n // The thread takes ownership over `thread_tx`\n // Each thread queues a message in the channel\n thread_tx.send(id).unwrap();\n\n // Sending is a non-blocking operation, the thread will continue\n // immediately after sending its message\n println!(\"thread {} finished\", id);\n });\n\n children.push(child);\n }\n\n // Here, all the messages are collected\n let mut ids = Vec::with_capacity(NTHREADS as usize);\n for _ in 0..NTHREADS {\n // The `recv` method picks a message from the channel\n // `recv` will block the current thread if there are no messages available\n ids.push(rx.recv());\n }\n\n // Wait for the threads to complete any remaining work\n for child in children {\n child.join().expect(\"oops! the child thread panicked\");\n }\n\n // Show the order in which the messages were sent\n println!(\"{:?}\", ids);\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Channels", "heading_path": ["Channels"], "path": "std_misc/channels.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc/channels.html#channels", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/std_misc/path.md#path-0", "text": "Rust by Example › Path\n\nThe `Path` type represents file paths in the underlying filesystem. Across all\nplatforms there is a single `std::path::Path` that abstracts over\nplatform-specific path semantics and separators. Bring it into scope with\n`use std::path::Path;` when needed.\nA `Path` can be created from an `OsStr`, and provides several methods to get\ninformation from the file/directory the path points to.\nA `Path` is immutable. The owned version of `Path` is `PathBuf`. The relation\nbetween `Path` and `PathBuf` is similar to that of `str` and `String`:\na `PathBuf` can be mutated in-place, and can be dereferenced to a `Path`.\nNote that a `Path` is *not* internally represented as an UTF-8 string, but\ninstead is stored as an `OsString`. Therefore, converting a `Path` to a `&str`\nis *not* free and may fail (an `Option` is returned). However, a `Path` can be\nfreely converted to an `OsString` or `&OsStr` using `into_os_string` and\n`as_os_str`, respectively.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Path", "heading_path": ["Path"], "path": "std_misc/path.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc/path.html#path", "has_code": false, "code_tags": []}} {"id": "rust-by-example/std_misc/path.md#path-1", "text": "Rust by Example › Path\n\n```rust,editable\nuse std::path::Path;\n\nfn main() {\n // Create a `Path` from an `&'static str`\n let path = Path::new(\".\");\n\n // The `display` method returns a `Display`able structure\n let _display = path.display();\n\n // `join` merges a path with a byte container using the OS specific\n // separator, and returns a `PathBuf`\n let mut new_path = path.join(\"a\").join(\"b\");\n\n // `push` extends the `PathBuf` with a `&Path`\n new_path.push(\"c\");\n new_path.push(\"myfile.tar.gz\");\n\n // `set_file_name` updates the file name of the `PathBuf`\n new_path.set_file_name(\"package.tgz\");\n\n // Convert the `PathBuf` into a string slice\n match new_path.to_str() {\n None => panic!(\"new path is not a valid UTF-8 sequence\"),\n Some(s) => println!(\"new path is {}\", s),\n }\n}\n```\nBe sure to check other `Path` methods and the `Metadata` struct.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Path", "heading_path": ["Path"], "path": "std_misc/path.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc/path.html#path", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/std_misc/path.md#see-also-2", "text": "Rust by Example › Path › See also:\n\nOsStr and Metadata.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Path", "heading_path": ["Path", "See also:"], "path": "std_misc/path.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc/path.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/std_misc/file.md#file-io-0", "text": "Rust by Example › File I/O\n\nThe `File` struct represents a file that has been opened (it wraps a file\ndescriptor), and gives read and/or write access to the underlying file.\nSince many things can go wrong when doing file I/O, all the `File` methods\nreturn the `io::Result` type, which is an alias for `Result`.\nThis makes the failure of all I/O operations *explicit*. Thanks to this, the\nprogrammer can see all the failure paths, and is encouraged to handle them in\na proactive manner.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "File I/O", "heading_path": ["File I/O"], "path": "std_misc/file.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc/file.html#file-io", "has_code": false, "code_tags": []}} {"id": "rust-by-example/std_misc/file/open.md#open-0", "text": "Rust by Example › `open`\n\nThe `open` function can be used to open a file in read-only mode.\nA `File` owns a resource, the file descriptor and takes care of closing the\nfile when it is `drop`ed.\n```rust,editable,ignore\nuse std::fs::File;\nuse std::io::prelude::*;\nuse std::path::Path;\n\nfn main() {\n // Create a path to the desired file\n let path = Path::new(\"hello.txt\");\n let display = path.display();\n\n // Open the path in read-only mode, returns `io::Result`\n let mut file = match File::open(&path) {\n Err(why) => panic!(\"couldn't open {}: {}\", display, why),\n Ok(file) => file,\n };\n\n // Read the file contents into a string, returns `io::Result`\n let mut s = String::new();\n match file.read_to_string(&mut s) {\n Err(why) => panic!(\"couldn't read {}: {}\", display, why),\n Ok(_) => print!(\"{} contains:\\n{}\", display, s),\n }\n\n // `file` goes out of scope, and the \"hello.txt\" file gets closed\n}\n```\nHere's the expected successful output:\n```shell\n$ echo \"Hello World!\" > hello.txt\n$ rustc open.rs && ./open\nhello.txt contains:\nHello World!\n```\n(You are encouraged to test the previous example under different failure\nconditions: `hello.txt` doesn't exist, or `hello.txt` is not readable,\netc.)", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`open`", "heading_path": ["`open`"], "path": "std_misc/file/open.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc/file/open.html#open", "has_code": true, "code_tags": ["rust,editable,ignore", "shell"]}} {"id": "rust-by-example/std_misc/file/create.md#create-0", "text": "Rust by Example › `create`\n\nThe `create` function opens a file in write-only mode. If the file\nalready existed, the old content is destroyed. Otherwise, a new file is\ncreated.\n```rust,ignore\nstatic LOREM_IPSUM: &str =\n \"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod\ntempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,\nquis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo\nconsequat. Duis aute irure dolor in reprehenderit in voluptate velit esse\ncillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non\nproident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n\";\n\nuse std::fs::File;\nuse std::io::prelude::*;\nuse std::path::Path;\n\nfn main() {\n let path = Path::new(\"lorem_ipsum.txt\");\n let display = path.display();\n\n // Open a file in write-only mode, returns `io::Result`\n let mut file = match File::create(&path) {\n Err(why) => panic!(\"couldn't create {}: {}\", display, why),\n Ok(file) => file,\n };\n\n // Write the `LOREM_IPSUM` string to `file`, returns `io::Result<()>`\n match file.write_all(LOREM_IPSUM.as_bytes()) {\n Err(why) => panic!(\"couldn't write to {}: {}\", display, why),\n Ok(_) => println!(\"successfully wrote to {}\", display),\n }\n}\n```\nHere's the expected successful output:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`create`", "heading_path": ["`create`"], "path": "std_misc/file/create.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc/file/create.html#create", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "rust-by-example/std_misc/file/create.md#create-1", "text": "Rust by Example › `create`\n\n```shell\n$ rustc create.rs && ./create\nsuccessfully wrote to lorem_ipsum.txt\n\n$ cat lorem_ipsum.txt\nLorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod\ntempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,\nquis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo\nconsequat. Duis aute irure dolor in reprehenderit in voluptate velit esse\ncillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non\nproident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n```\n(As in the previous example, you are encouraged to test this example under\nfailure conditions.)\nThe [`OpenOptions`] struct can be used to configure how a file is opened.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`create`", "heading_path": ["`create`"], "path": "std_misc/file/create.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc/file/create.html#create", "has_code": true, "code_tags": ["shell"]}} {"id": "rust-by-example/std_misc/file/read_lines.md#a-naive-approach-0", "text": "Rust by Example › `read_lines` › A naive approach\n\nThis might be a reasonable first attempt for a beginner's first\nimplementation for reading lines from a file.\n```rust,no_run\nuse std::fs::read_to_string;\n\nfn read_lines(filename: &str) -> Vec {\n let mut result = Vec::new();\n\n for line in read_to_string(filename).unwrap().lines() {\n result.push(line.to_string())\n }\n\n result\n}\n```\nSince the method `lines()` returns an iterator over the lines in the file,\nwe can also perform a map inline and collect the results, yielding a more\nconcise and fluent expression.\n```rust,no_run\nuse std::fs::read_to_string;\n\nfn read_lines(filename: &str) -> Vec {\n read_to_string(filename)\n .unwrap() // panic on possible file-reading errors\n .lines() // split the string into an iterator of string slices\n .map(String::from) // make each slice into a string\n .collect() // gather them together into a vector\n}\n```\nNote that in both examples above, we must convert the `&str` reference\nreturned from `lines()` to the owned type `String`, using `.to_string()`\nand `String::from` respectively.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`read_lines`", "heading_path": ["`read_lines`", "A naive approach"], "path": "std_misc/file/read_lines.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc/file/read_lines.html#a-naive-approach", "has_code": true, "code_tags": ["rust,no_run"]}} {"id": "rust-by-example/std_misc/file/read_lines.md#a-more-efficient-approach-1", "text": "Rust by Example › `read_lines` › A more efficient approach\n\nHere we pass ownership of the open `File` to a `BufReader` struct. `BufReader` uses an internal\nbuffer to reduce intermediate allocations.\nWe also update `read_lines` to return an iterator instead of allocating new\n`String` objects in memory for each line.\n```rust,no_run\nuse std::fs::File;\nuse std::io::{self, BufRead};\nuse std::path::Path;\n\nfn main() {\n // File hosts.txt must exist in the current path\n if let Ok(lines) = read_lines(\"./hosts.txt\") {\n // Consumes the iterator, returns an (Optional) String\n for line in lines.map_while(Result::ok) {\n println!(\"{}\", line);\n }\n }\n}\n\n// The output is wrapped in a Result to allow matching on errors.\n// Returns an Iterator to the Reader of the lines of the file.\nfn read_lines

(filename: P) -> io::Result>>\nwhere P: AsRef, {\n let file = File::open(filename)?;\n Ok(io::BufReader::new(file).lines())\n}\n```\nRunning this program simply prints the lines individually.\n```shell\n$ echo -e \"127.0.0.1\\n192.168.0.1\\n\" > hosts.txt\n$ rustc read_lines.rs && ./read_lines\n127.0.0.1\n192.168.0.1\n```\n(Note that since `File::open` expects a generic `AsRef` as argument, we define our\ngeneric `read_lines()` method with the same generic constraint, using the `where` keyword.)\nThis process is more efficient than creating a `String` in memory with all of the file's\ncontents. This can especially cause performance issues when working with larger files.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "`read_lines`", "heading_path": ["`read_lines`", "A more efficient approach"], "path": "std_misc/file/read_lines.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc/file/read_lines.html#a-more-efficient-approach", "has_code": true, "code_tags": ["rust,no_run", "shell"]}} {"id": "rust-by-example/std_misc/process.md#child-processes-0", "text": "Rust by Example › Child processes\n\nThe `process::Output` struct represents the output of a finished child process,\nand the `process::Command` struct is a process builder.\n```rust,editable,ignore\nuse std::process::Command;\n\nfn main() {\n let output = Command::new(\"rustc\")\n .arg(\"--version\")\n .output().unwrap_or_else(|e| {\n panic!(\"failed to execute process: {}\", e)\n });\n\n if output.status.success() {\n let s = String::from_utf8_lossy(&output.stdout);\n\n print!(\"rustc succeeded and stdout was:\\n{}\", s);\n } else {\n let s = String::from_utf8_lossy(&output.stderr);\n\n print!(\"rustc failed and stderr was:\\n{}\", s);\n }\n}\n```\n(You are encouraged to try the previous example with an incorrect flag passed\nto `rustc`)", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Child processes", "heading_path": ["Child processes"], "path": "std_misc/process.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc/process.html#child-processes", "has_code": true, "code_tags": ["rust,editable,ignore"]}} {"id": "rust-by-example/std_misc/process/pipe.md#pipes-0", "text": "Rust by Example › Pipes\n\nThe `std::process::Child` struct represents a child process, and exposes the\n`stdin`, `stdout` and `stderr` handles for interaction with the underlying\nprocess via pipes.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Pipes", "heading_path": ["Pipes"], "path": "std_misc/process/pipe.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc/process/pipe.html#pipes", "has_code": false, "code_tags": []}} {"id": "rust-by-example/std_misc/process/pipe.md#pipes-1", "text": "Rust by Example › Pipes\n\n```rust,ignore\nuse std::io::prelude::*;\nuse std::process::{Command, Stdio};\n\nstatic PANGRAM: &'static str =\n\"the quick brown fox jumps over the lazy dog\\n\";\n\nfn main() {\n // Spawn the `wc` command\n let mut cmd = if cfg!(target_family = \"windows\") {\n let mut cmd = Command::new(\"powershell\");\n cmd.arg(\"-Command\").arg(\"$input | Measure-Object -Line -Word -Character\");\n cmd\n } else {\n Command::new(\"wc\")\n };\n let process = match cmd\n .stdin(Stdio::piped())\n .stdout(Stdio::piped())\n .spawn() {\n Err(why) => panic!(\"couldn't spawn wc: {}\", why),\n Ok(process) => process,\n };\n\n // Write a string to the `stdin` of `wc`.\n //\n // `stdin` has type `Option`, but since we know this instance\n // must have one, we can directly `unwrap` it.\n match process.stdin.unwrap().write_all(PANGRAM.as_bytes()) {\n Err(why) => panic!(\"couldn't write to wc stdin: {}\", why),\n Ok(_) => println!(\"sent pangram to wc\"),\n }\n\n // Because `stdin` does not live after the above calls, it is `drop`ed,\n // and the pipe is closed.\n //\n // This is very important, otherwise `wc` wouldn't start processing the\n // input we just sent.\n\n // The `stdout` field also has type `Option` so must be unwrapped.\n let mut s = String::new();\n match process.stdout.unwrap().read_to_string(&mut s) {\n Err(why) => panic!(\"couldn't read wc stdout: {}\", why),\n Ok(_) => print!(\"wc responded with:\\n{}\", s),\n }\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Pipes", "heading_path": ["Pipes"], "path": "std_misc/process/pipe.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc/process/pipe.html#pipes", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "rust-by-example/std_misc/process/wait.md#wait-0", "text": "Rust by Example › Wait\n\nIf you'd like to wait for a `process::Child` to finish, you must call\n`Child::wait`, which will return a `process::ExitStatus`.\n```rust,ignore\nuse std::process::Command;\n\nfn main() {\n let mut child = Command::new(\"sleep\").arg(\"5\").spawn().unwrap();\n let _result = child.wait().unwrap();\n\n println!(\"reached end of main\");\n}\n```\n```bash\n$ rustc wait.rs && ./wait\n# `wait` keeps running for 5 seconds until the `sleep 5` command finishes\nreached end of main\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Wait", "heading_path": ["Wait"], "path": "std_misc/process/wait.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc/process/wait.html#wait", "has_code": true, "code_tags": ["bash", "rust,ignore"]}} {"id": "rust-by-example/std_misc/fs.md#filesystem-operations-0", "text": "Rust by Example › Filesystem Operations\n\nThe `std::fs` module contains several functions that deal with the filesystem.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Filesystem Operations", "heading_path": ["Filesystem Operations"], "path": "std_misc/fs.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc/fs.html#filesystem-operations", "has_code": false, "code_tags": []}} {"id": "rust-by-example/std_misc/fs.md#filesystem-operations-1", "text": "Rust by Example › Filesystem Operations\n\n```rust,ignore\nuse std::fs;\nuse std::fs::{File, OpenOptions};\nuse std::io;\nuse std::io::prelude::*;\n#[cfg(target_family = \"unix\")]\nuse std::os::unix;\n#[cfg(target_family = \"windows\")]\nuse std::os::windows;\nuse std::path::Path;\n\n// A simple implementation of `% cat path`\nfn cat(path: &Path) -> io::Result {\n let mut f = File::open(path)?;\n let mut s = String::new();\n match f.read_to_string(&mut s) {\n Ok(_) => Ok(s),\n Err(e) => Err(e),\n }\n}\n\n// A simple implementation of `% echo s > path`\nfn echo(s: &str, path: &Path) -> io::Result<()> {\n let mut f = File::create(path)?;\n\n f.write_all(s.as_bytes())\n}\n\n// A simple implementation of `% touch path` (ignores existing files)\nfn touch(path: &Path) -> io::Result<()> {\n match OpenOptions::new().create(true).write(true).open(path) {\n Ok(_) => Ok(()),\n Err(e) => Err(e),\n }\n}\n\nfn main() {\n println!(\"`mkdir a`\");\n // Create a directory, returns `io::Result<()>`\n match fs::create_dir(\"a\") {\n Err(why) => println!(\"! {:?}\", why.kind()),\n Ok(_) => {},\n }\n\n println!(\"`echo hello > a/b.txt`\");\n // The previous match can be simplified using the `unwrap_or_else` method\n echo(\"hello\", &Path::new(\"a/b.txt\")).unwrap_or_else(|why| {\n println!(\"! {:?}\", why.kind());\n });\n\n println!(\"`mkdir -p a/c/d`\");\n // Recursively create a directory, returns `io::Result<()>`\n fs::create_dir_all(\"a/c/d\").unwrap_or_else(|why| {\n println!(\"! {:?}\", why.kind());\n });\n\n println!(\"`touch a/c/e.txt`\");\n touch(&Path::new(\"a/c/e.txt\")).unwrap_or_else(|why| {\n println!(\"! {:?}\", why.kind());\n });\n\n println!(\"`ln -s ../b.txt a/c/b.txt`\");\n // Create a symbolic link, returns `io::Result<()>`\n #[cfg(target_family = \"unix\")] {\n unix::fs::symlink(\"../b.txt\", \"a/c/b.txt\").unwrap_or_else(|why| {\n println!(\"! {:?}\", why.kind());\n });\n }\n #[cfg(target_family = \"windows\")] {\n windows::fs::symlink_file(\"../b.txt\", \"a/c/b.txt\").unwrap_or_else(|why| {\n println!(\"! {:?}\", why.to_string());\n });\n }\n\n println!(\"`cat a/c/b.txt`\");\n match cat(&Path::new(\"a/c/b.txt\")) {\n Err(why) => println!(\"! {:?}\", why.kind()),\n Ok(s) => println!(\"> {}\", s),\n }\n\n println!(\"`ls a`\");\n // Read the contents of a directory, returns `io::Result>`\n match fs::read_dir(\"a\") {\n Err(why) => println!(\"! {:?}\", why.kind()),\n Ok(paths) => for path in paths {\n println!(\"> {:?}\", path.unwrap().path());\n },\n }\n\n println!(\"`rm a/c/e.txt`\");\n // Remove a file, returns `io::Result<()>`\n fs::remove_file(\"a/c/e.txt\").unwrap_or_else(|why| {\n println!(\"! {:?}\", why.kind());\n });\n\n println!(\"`rmdir a/c/d`\");\n // Remove an empty directory, returns `io::Result<()>`\n fs::remove_dir(\"a/c/d\").unwrap_or_else(|why| {\n println!(\"! {:?}\", why.kind());\n });\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Filesystem Operations", "heading_path": ["Filesystem Operations"], "path": "std_misc/fs.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc/fs.html#filesystem-operations", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "rust-by-example/std_misc/fs.md#filesystem-operations-2", "text": "Rust by Example › Filesystem Operations\n\nHere's the expected successful output:\n```shell\n$ rustc fs.rs && ./fs\n`mkdir a`\n`echo hello > a/b.txt`\n`mkdir -p a/c/d`\n`touch a/c/e.txt`\n`ln -s ../b.txt a/c/b.txt`\n`cat a/c/b.txt`\nhello\n`ls a`\n\"a/b.txt\"\n\"a/c\"\n`rm a/c/e.txt`\n`rmdir a/c/d`\n```\nAnd the final state of the `a` directory is:\n```shell\n$ tree a\na\n|-- b.txt\n`-- c\n `-- b.txt -> ../b.txt\n\n1 directory, 2 files\n```\nAn alternative way to define the function `cat` is with `?` notation:\n```rust,ignore\nfn cat(path: &Path) -> io::Result {\n let mut f = File::open(path)?;\n let mut s = String::new();\n f.read_to_string(&mut s)?;\n Ok(s)\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Filesystem Operations", "heading_path": ["Filesystem Operations"], "path": "std_misc/fs.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc/fs.html#filesystem-operations", "has_code": true, "code_tags": ["rust,ignore", "shell"]}} {"id": "rust-by-example/std_misc/fs.md#see-also-3", "text": "Rust by Example › Filesystem Operations › See also:\n\n`cfg!`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Filesystem Operations", "heading_path": ["Filesystem Operations", "See also:"], "path": "std_misc/fs.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc/fs.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/std_misc/arg.md#standard-library-0", "text": "Rust by Example › Program arguments › Standard Library\n\nThe command line arguments can be accessed using `std::env::args`, which\nreturns an iterator that yields a `String` for each argument:\n```rust,editable\nuse std::env;\n\nfn main() {\n let args: Vec = env::args().collect();\n\n // The first argument is the path that was used to call the program.\n println!(\"My path is {}.\", args[0]);\n\n // The rest of the arguments are the passed command line parameters.\n // Call the program like this:\n // $ ./args arg1 arg2\n println!(\"I got {:?} arguments: {:?}.\", args.len() - 1, &args[1..]);\n}\n```\n```shell\n$ ./args 1 2 3\nMy path is ./args.\nI got 3 arguments: [\"1\", \"2\", \"3\"].\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Program arguments", "heading_path": ["Program arguments", "Standard Library"], "path": "std_misc/arg.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc/arg.html#standard-library", "has_code": true, "code_tags": ["rust,editable", "shell"]}} {"id": "rust-by-example/std_misc/arg.md#crates-1", "text": "Rust by Example › Program arguments › Crates\n\nAlternatively, there are numerous crates that can provide extra functionality\nwhen creating command-line applications. One of the more popular command line\nargument crates being [`clap`].", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Program arguments", "heading_path": ["Program arguments", "Crates"], "path": "std_misc/arg.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc/arg.html#crates", "has_code": false, "code_tags": []}} {"id": "rust-by-example/std_misc/arg/matching.md#argument-parsing-0", "text": "Rust by Example › Argument parsing\n\nMatching can be used to parse simple arguments:\n```rust,ignore\nuse std::env;\n\nfn increase(number: i32) {\n println!(\"{}\", number + 1);\n}\n\nfn decrease(number: i32) {\n println!(\"{}\", number - 1);\n}\n\nfn help() {\n println!(\"usage:\nmatch_args \n Check whether given string is the answer.\nmatch_args {{increase|decrease}} \n Increase or decrease given integer by one.\");\n}\n\nfn main() {\n let args: Vec = env::args().collect();\n\n match args.len() {\n // no arguments passed\n 1 => {\n println!(\"My name is 'match_args'. Try passing some arguments!\");\n },\n // one argument passed\n 2 => {\n match args[1].parse() {\n Ok(42) => println!(\"This is the answer!\"),\n _ => println!(\"This is not the answer.\"),\n }\n },\n // one command and one argument passed\n 3 => {\n let cmd = &args[1];\n let num = &args[2];\n // parse the number\n let number: i32 = match num.parse() {\n Ok(n) => {\n n\n },\n Err(_) => {\n eprintln!(\"error: second argument not an integer\");\n help();\n return;\n },\n };\n // parse the command\n match &cmd[..] {\n \"increase\" => increase(number),\n \"decrease\" => decrease(number),\n _ => {\n eprintln!(\"error: invalid command\");\n help();\n },\n }\n },\n // all the other cases\n _ => {\n // show a help message\n help();\n }\n }\n}\n```\nIf you named your program `match_args.rs` and compile it like this `rustc\nmatch_args.rs`, you can execute it as follows:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Argument parsing", "heading_path": ["Argument parsing"], "path": "std_misc/arg/matching.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc/arg/matching.html#argument-parsing", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "rust-by-example/std_misc/arg/matching.md#argument-parsing-1", "text": "Rust by Example › Argument parsing\n\n```shell\n$ ./match_args Rust\nThis is not the answer.\n$ ./match_args 42\nThis is the answer!\n$ ./match_args do something\nerror: second argument not an integer\nusage:\nmatch_args \n Check whether given string is the answer.\nmatch_args {increase|decrease} \n Increase or decrease given integer by one.\n$ ./match_args do 42\nerror: invalid command\nusage:\nmatch_args \n Check whether given string is the answer.\nmatch_args {increase|decrease} \n Increase or decrease given integer by one.\n$ ./match_args increase 42\n43\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Argument parsing", "heading_path": ["Argument parsing"], "path": "std_misc/arg/matching.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc/arg/matching.html#argument-parsing", "has_code": true, "code_tags": ["shell"]}} {"id": "rust-by-example/std_misc/ffi.md#foreign-function-interface-0", "text": "Rust by Example › Foreign Function Interface\n\nRust provides a Foreign Function Interface (FFI) to C libraries. Foreign\nfunctions must be declared inside an `extern` block annotated with a `#[link]`\nattribute containing the name of the foreign library.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Foreign Function Interface", "heading_path": ["Foreign Function Interface"], "path": "std_misc/ffi.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc/ffi.html#foreign-function-interface", "has_code": false, "code_tags": []}} {"id": "rust-by-example/std_misc/ffi.md#foreign-function-interface-1", "text": "Rust by Example › Foreign Function Interface\n\n```rust,ignore\nuse std::fmt;\n\n// this extern block links to the libm library\n#[cfg(target_family = \"windows\")]\n#[link(name = \"msvcrt\")]\nextern {\n // this is a foreign function\n // that computes the square root of a single precision complex number\n fn csqrtf(z: Complex) -> Complex;\n\n fn ccosf(z: Complex) -> Complex;\n}\n#[cfg(target_family = \"unix\")]\n#[link(name = \"m\")]\nextern {\n // this is a foreign function\n // that computes the square root of a single precision complex number\n fn csqrtf(z: Complex) -> Complex;\n\n fn ccosf(z: Complex) -> Complex;\n}\n\n// Since calling foreign functions is considered unsafe,\n// it's common to write safe wrappers around them.\nfn cos(z: Complex) -> Complex {\n unsafe { ccosf(z) }\n}\n\nfn main() {\n // z = -1 + 0i\n let z = Complex { re: -1., im: 0. };\n\n // calling a foreign function is an unsafe operation\n let z_sqrt = unsafe { csqrtf(z) };\n\n println!(\"the square root of {:?} is {:?}\", z, z_sqrt);\n\n // calling safe API wrapped around unsafe operation\n println!(\"cos({:?}) = {:?}\", z, cos(z));\n}\n\n// Minimal implementation of single precision complex numbers\n#[repr(C)]\n#[derive(Clone, Copy)]\nstruct Complex {\n re: f32,\n im: f32,\n}\n\nimpl fmt::Debug for Complex {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n if self.im < 0. {\n write!(f, \"{}-{}i\", self.re, -self.im)\n } else {\n write!(f, \"{}+{}i\", self.re, self.im)\n }\n }\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Foreign Function Interface", "heading_path": ["Foreign Function Interface"], "path": "std_misc/ffi.md", "url": "https://doc.rust-lang.org/rust-by-example/std_misc/ffi.html#foreign-function-interface", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "rust-by-example/testing.md#testing-0", "text": "Rust by Example › Testing\n\nRust is a programming language that cares a lot about correctness and it\nincludes support for writing software tests within the language itself.\nTesting comes in three styles:\n* Unit testing.\n* Doc testing.\n* Integration testing.\nAlso Rust has support for specifying additional dependencies for tests:\n* Dev-dependencies", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Testing", "heading_path": ["Testing"], "path": "testing.md", "url": "https://doc.rust-lang.org/rust-by-example/testing.html#testing", "has_code": false, "code_tags": []}} {"id": "rust-by-example/testing.md#see-also-1", "text": "Rust by Example › Testing › See Also\n\n* The Book chapter on testing\n* API Guidelines on doc-testing", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Testing", "heading_path": ["Testing", "See Also"], "path": "testing.md", "url": "https://doc.rust-lang.org/rust-by-example/testing.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/testing/unit_testing.md#unit-testing-0", "text": "Rust by Example › Unit testing\n\nTests are Rust functions that verify that the non-test code is functioning in\nthe expected manner. The bodies of test functions typically perform some setup,\nrun the code we want to test, then assert whether the results are what we\nexpect.\nMost unit tests go into a `tests` mod with the `#[cfg(test)]` attribute.\nTest functions are marked with the `#[test]` attribute.\nTests fail when something in the test function panics. There are some\nhelper macros:\n* `assert!(expression)` - panics if expression evaluates to `false`.\n* `assert_eq!(left, right)` and `assert_ne!(left, right)` - testing left and\n right expressions for equality and inequality respectively.\n```rust,ignore\npub fn add(a: i32, b: i32) -> i32 {\n a + b\n}\n\n// This is a really bad adding function, its purpose is to fail in this\n// example.\n#[allow(dead_code)]\nfn bad_add(a: i32, b: i32) -> i32 {\n a - b\n}\n\n#[cfg(test)]\nmod tests {\n // Note this useful idiom: importing names from outer (for mod tests) scope.\n use super::*;\n\n #[test]\n fn test_add() {\n assert_eq!(add(1, 2), 3);\n }\n\n #[test]\n fn test_bad_add() {\n // This assert would fire and test will fail.\n // Please note, that private functions can be tested too!\n assert_eq!(bad_add(1, 2), 3);\n }\n}\n```\nTests can be run with `cargo test`.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Unit testing", "heading_path": ["Unit testing"], "path": "testing/unit_testing.md", "url": "https://doc.rust-lang.org/rust-by-example/testing/unit_testing.html#unit-testing", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "rust-by-example/testing/unit_testing.md#unit-testing-1", "text": "Rust by Example › Unit testing\n\n```shell\n$ cargo test\n\nrunning 2 tests\ntest tests::test_bad_add ... FAILED\ntest tests::test_add ... ok\n\nfailures:\n\n---- tests::test_bad_add stdout ----\n thread 'tests::test_bad_add' panicked at 'assertion failed: `(left == right)`\n left: `-1`,\n right: `3`', src/lib.rs:21:8\nnote: Run with `RUST_BACKTRACE=1` for a backtrace.\n\n\nfailures:\n tests::test_bad_add\n\ntest result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Unit testing", "heading_path": ["Unit testing"], "path": "testing/unit_testing.md", "url": "https://doc.rust-lang.org/rust-by-example/testing/unit_testing.html#unit-testing", "has_code": true, "code_tags": ["shell"]}} {"id": "rust-by-example/testing/unit_testing.md#tests-and--2", "text": "Rust by Example › Unit testing › Tests and `?`\n\nNone of the previous unit test examples had a return type. But in Rust 2018,\nyour unit tests can return `Result<()>`, which lets you use `?` in them! This\ncan make them much more concise.\n```rust,editable\nfn sqrt(number: f64) -> Result {\n if number >= 0.0 {\n Ok(number.powf(0.5))\n } else {\n Err(\"negative floats don't have square roots\".to_owned())\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn test_sqrt() -> Result<(), String> {\n let x = 4.0;\n assert_eq!(sqrt(x)?.powf(2.0), x);\n Ok(())\n }\n}\n```\nSee \"The Edition Guide\" for more details.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Unit testing", "heading_path": ["Unit testing", "Tests and `?`"], "path": "testing/unit_testing.md", "url": "https://doc.rust-lang.org/rust-by-example/testing/unit_testing.html#tests-and-", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/testing/unit_testing.md#testing-panics-3", "text": "Rust by Example › Unit testing › Testing panics\n\nTo check functions that should panic under certain circumstances, use attribute\n`#[should_panic]`. This attribute accepts optional parameter `expected = ` with\nthe text of the panic message. If your function can panic in multiple ways, it helps\nmake sure your test is testing the correct panic.\n**Note**: Rust also allows a shorthand form `#[should_panic = \"message\"]`, which works\nexactly like `#[should_panic(expected = \"message\")]`. Both are valid; the latter is more commonly\nused and is considered more explicit.\n```rust,ignore\npub fn divide_non_zero_result(a: u32, b: u32) -> u32 {\n if b == 0 {\n panic!(\"Divide-by-zero error\");\n } else if a < b {\n panic!(\"Divide result is zero\");\n }\n a / b\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn test_divide() {\n assert_eq!(divide_non_zero_result(10, 2), 5);\n }\n\n #[test]\n #[should_panic]\n fn test_any_panic() {\n divide_non_zero_result(1, 0);\n }\n\n #[test]\n #[should_panic(expected = \"Divide result is zero\")]\n fn test_specific_panic() {\n divide_non_zero_result(1, 10);\n }\n\n #[test]\n #[should_panic = \"Divide result is zero\"] // This also works\n fn test_specific_panic_shorthand() {\n divide_non_zero_result(1, 10);\n }\n}\n```\nRunning these tests gives us:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Unit testing", "heading_path": ["Unit testing", "Testing panics"], "path": "testing/unit_testing.md", "url": "https://doc.rust-lang.org/rust-by-example/testing/unit_testing.html#testing-panics", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "rust-by-example/testing/unit_testing.md#testing-panics-4", "text": "Rust by Example › Unit testing › Testing panics\n\n```shell\n$ cargo test\n\nrunning 4 tests\ntest tests::test_any_panic ... ok\ntest tests::test_divide ... ok\ntest tests::test_specific_panic ... ok\ntest tests::test_specific_panic_shorthand ... ok\n\ntest result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\n\n Doc-tests tmp-test-should-panic\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Unit testing", "heading_path": ["Unit testing", "Testing panics"], "path": "testing/unit_testing.md", "url": "https://doc.rust-lang.org/rust-by-example/testing/unit_testing.html#testing-panics", "has_code": true, "code_tags": ["shell"]}} {"id": "rust-by-example/testing/unit_testing.md#running-specific-tests-5", "text": "Rust by Example › Unit testing › Running specific tests\n\nTo run specific tests one may specify the test name to `cargo test` command.\n```shell\n$ cargo test test_any_panic\nrunning 1 test\ntest tests::test_any_panic ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 3 filtered out\n\n Doc-tests tmp-test-should-panic\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\n```\nTo run multiple tests one may specify part of a test name that matches all the\ntests that should be run.\n```shell\n$ cargo test panic\nrunning 3 tests\ntest tests::test_any_panic ... ok\ntest tests::test_specific_panic ... ok\ntest tests::test_specific_panic_shorthand ... ok\n\ntest result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out\n\n Doc-tests tmp-test-should-panic\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Unit testing", "heading_path": ["Unit testing", "Running specific tests"], "path": "testing/unit_testing.md", "url": "https://doc.rust-lang.org/rust-by-example/testing/unit_testing.html#running-specific-tests", "has_code": true, "code_tags": ["shell"]}} {"id": "rust-by-example/testing/unit_testing.md#ignoring-tests-6", "text": "Rust by Example › Unit testing › Ignoring tests\n\nTests can be marked with the `#[ignore]` attribute to exclude some tests. Or to run\nthem with command `cargo test -- --ignored`\n```rust,ignore\npub fn add(a: i32, b: i32) -> i32 {\n a + b\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn test_add() {\n assert_eq!(add(2, 2), 4);\n }\n\n #[test]\n fn test_add_hundred() {\n assert_eq!(add(100, 2), 102);\n assert_eq!(add(2, 100), 102);\n }\n\n #[test]\n #[ignore]\n fn ignored_test() {\n assert_eq!(add(0, 0), 0);\n }\n}\n```\n```shell\n$ cargo test\nrunning 3 tests\ntest tests::ignored_test ... ignored\ntest tests::test_add ... ok\ntest tests::test_add_hundred ... ok\n\ntest result: ok. 2 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out\n\n Doc-tests tmp-ignore\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\n\n$ cargo test -- --ignored\nrunning 1 test\ntest tests::ignored_test ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\n\n Doc-tests tmp-ignore\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Unit testing", "heading_path": ["Unit testing", "Ignoring tests"], "path": "testing/unit_testing.md", "url": "https://doc.rust-lang.org/rust-by-example/testing/unit_testing.html#ignoring-tests", "has_code": true, "code_tags": ["rust,ignore", "shell"]}} {"id": "rust-by-example/testing/doc_testing.md#documentation-testing-0", "text": "Rust by Example › Documentation testing\n\nThe primary way of documenting a Rust project is through annotating the source\ncode. Documentation comments are written in\nCommonMark Markdown specification and support code blocks in them.\nRust takes care about correctness, so these code blocks are compiled and used\nas documentation tests.\n```rust,ignore\n/// First line is a short summary describing function.\n///\n/// The next lines present detailed documentation. Code blocks start with\n/// triple backquotes and have implicit `fn main()` inside\n/// and `extern crate `. Assume we're testing a `playground` library\n/// crate or using the Playground's Test action:\n///\n/// ```\n/// let result = playground::add(2, 3);\n/// assert_eq!(result, 5);\n/// ```\npub fn add(a: i32, b: i32) -> i32 {\n a + b\n}\n\n/// Usually doc comments may include sections \"Examples\", \"Panics\" and \"Failures\".\n///\n/// The next function divides two numbers.\n///\n/// # Examples\n///\n/// ```\n/// let result = playground::div(10, 2);\n/// assert_eq!(result, 5);\n/// ```\n///\n/// # Panics\n///\n/// The function panics if the second argument is zero.\n///\n/// ```rust,should_panic\n/// // panics on division by zero\n/// playground::div(10, 0);\n/// ```\npub fn div(a: i32, b: i32) -> i32 {\n if b == 0 {\n panic!(\"Divide-by-zero error\");\n }\n\n a / b\n}\n```\nCode blocks in documentation are automatically tested\nwhen running the regular `cargo test` command:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Documentation testing", "heading_path": ["Documentation testing"], "path": "testing/doc_testing.md", "url": "https://doc.rust-lang.org/rust-by-example/testing/doc_testing.html#documentation-testing", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "rust-by-example/testing/doc_testing.md#documentation-testing-1", "text": "Rust by Example › Documentation testing\n\n```shell\n$ cargo test\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\n\n Doc-tests playground\n\nrunning 3 tests\ntest src/lib.rs - add (line 7) ... ok\ntest src/lib.rs - div (line 21) ... ok\ntest src/lib.rs - div (line 31) ... ok\n\ntest result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Documentation testing", "heading_path": ["Documentation testing"], "path": "testing/doc_testing.md", "url": "https://doc.rust-lang.org/rust-by-example/testing/doc_testing.html#documentation-testing", "has_code": true, "code_tags": ["shell"]}} {"id": "rust-by-example/testing/doc_testing.md#motivation-behind-documentation-tests-2", "text": "Rust by Example › Documentation testing › Motivation behind documentation tests\n\nThe main purpose of documentation tests is to serve as examples that exercise\nthe functionality, which is one of the most important\nguidelines. It allows using examples from docs as\ncomplete code snippets. But using `?` makes compilation fail since `main`\nreturns `unit`. The ability to hide some source lines from documentation comes\nto the rescue: one may write `fn try_main() -> Result<(), ErrorType>`, hide it\nand `unwrap` it in hidden `main`. Sounds complicated? Here's an example:\n```rust,ignore\n/// Using hidden `try_main` in doc tests.\n///\n/// ```\n/// # // hidden lines start with `#` symbol, but they're still compilable!\n/// # fn try_main() -> Result<(), String> { // line that wraps the body shown in doc\n/// let res = playground::try_div(10, 2)?;\n/// # Ok(()) // returning from try_main\n/// # }\n/// # fn main() { // starting main that'll unwrap()\n/// # try_main().unwrap(); // calling try_main and unwrapping\n/// # // so that test will panic in case of error\n/// # }\n/// ```\npub fn try_div(a: i32, b: i32) -> Result {\n if b == 0 {\n Err(String::from(\"Divide-by-zero\"))\n } else {\n Ok(a / b)\n }\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Documentation testing", "heading_path": ["Documentation testing", "Motivation behind documentation tests"], "path": "testing/doc_testing.md", "url": "https://doc.rust-lang.org/rust-by-example/testing/doc_testing.html#motivation-behind-documentation-tests", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "rust-by-example/testing/doc_testing.md#see-also-3", "text": "Rust by Example › Documentation testing › See Also\n\n* RFC505 on documentation style\n* API Guidelines on documentation guidelines", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Documentation testing", "heading_path": ["Documentation testing", "See Also"], "path": "testing/doc_testing.md", "url": "https://doc.rust-lang.org/rust-by-example/testing/doc_testing.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/testing/integration_testing.md#integration-testing-0", "text": "Rust by Example › Integration testing\n\nUnit tests are testing one module in isolation at a time: they're small\nand can test private code. Integration tests are external to your crate and use\nonly its public interface in the same way any other code would. Their purpose is\nto test that many parts of your library work correctly together.\nCargo looks for integration tests in `tests` directory next to `src`.\nFile `src/lib.rs`:\n```rust,ignore\n// Define this in a crate called `adder`.\npub fn add(a: i32, b: i32) -> i32 {\n a + b\n}\n```\nFile with test: `tests/integration_test.rs`:\n```rust,ignore\n#[test]\nfn test_add() {\n assert_eq!(adder::add(3, 2), 5);\n}\n```\nRunning tests with `cargo test` command:\n```shell\n$ cargo test\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\n\n Running target/debug/deps/integration_test-bcd60824f5fbfe19\n\nrunning 1 test\ntest test_add ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\n\n Doc-tests adder\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\n```\nEach Rust source file in the `tests` directory is compiled as a separate crate. In\norder to share some code between integration tests we can make a module with public\nfunctions, importing and using it within tests.\nFile `tests/common/mod.rs`:\n```rust,ignore\npub fn setup() {\n // some setup code, like creating required files/directories, starting\n // servers, etc.\n}\n```\nFile with test: `tests/integration_test.rs`", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Integration testing", "heading_path": ["Integration testing"], "path": "testing/integration_testing.md", "url": "https://doc.rust-lang.org/rust-by-example/testing/integration_testing.html#integration-testing", "has_code": true, "code_tags": ["rust,ignore", "shell"]}} {"id": "rust-by-example/testing/integration_testing.md#integration-testing-1", "text": "Rust by Example › Integration testing\n\n```rust,ignore\n// importing common module.\nmod common;\n\n#[test]\nfn test_add() {\n // using common code.\n common::setup();\n assert_eq!(adder::add(3, 2), 5);\n}\n```\nCreating the module as `tests/common.rs` also works, but is not recommended\nbecause the test runner will treat the file as a test crate and try to run tests\ninside it.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Integration testing", "heading_path": ["Integration testing"], "path": "testing/integration_testing.md", "url": "https://doc.rust-lang.org/rust-by-example/testing/integration_testing.html#integration-testing", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "rust-by-example/testing/dev_dependencies.md#development-dependencies-0", "text": "Rust by Example › Development dependencies\n\nSometimes there is a need to have dependencies for tests (or examples,\nor benchmarks) only. Such dependencies are added to `Cargo.toml` in the\n`[dev-dependencies]` section. These dependencies are not propagated to other\npackages which depend on this package.\nOne such example is `pretty_assertions`, which extends standard `assert_eq!` and `assert_ne!` macros, to provide colorful diff.\nFile `Cargo.toml`:\n```toml\n# standard crate data is left out\n[dev-dependencies]\npretty_assertions = \"1\"\n```\nFile `src/lib.rs`:\n```rust,ignore\npub fn add(a: i32, b: i32) -> i32 {\n a + b\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use pretty_assertions::assert_eq; // crate for test-only use. Cannot be used in non-test code.\n\n #[test]\n fn test_add() {\n assert_eq!(add(2, 3), 5);\n }\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Dev-dependencies", "heading_path": ["Development dependencies"], "path": "testing/dev_dependencies.md", "url": "https://doc.rust-lang.org/rust-by-example/testing/dev_dependencies.html#development-dependencies", "has_code": true, "code_tags": ["rust,ignore", "toml"]}} {"id": "rust-by-example/testing/dev_dependencies.md#see-also-1", "text": "Rust by Example › Development dependencies › See Also\n\nCargo docs on specifying dependencies.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Dev-dependencies", "heading_path": ["Development dependencies", "See Also"], "path": "testing/dev_dependencies.md", "url": "https://doc.rust-lang.org/rust-by-example/testing/dev_dependencies.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/unsafe.md#unsafe-operations-0", "text": "Rust by Example › Unsafe Operations\n\nAs an introduction to this section, to borrow from the official docs,\n\"one should try to minimize the amount of unsafe code in a code base.\" With that\nin mind, let's get started! Unsafe annotations in Rust are used to bypass\nprotections put in place by the compiler; specifically, there are four primary\nthings that unsafe is used for:\n* dereferencing raw pointers\n* calling functions or methods which are `unsafe` (including calling a function\n over FFI, see a previous chapter of the book)\n* accessing or modifying static mutable variables\n* implementing unsafe traits", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Unsafe Operations", "heading_path": ["Unsafe Operations"], "path": "unsafe.md", "url": "https://doc.rust-lang.org/rust-by-example/unsafe.html#unsafe-operations", "has_code": false, "code_tags": []}} {"id": "rust-by-example/unsafe.md#raw-pointers-1", "text": "Rust by Example › Unsafe Operations › Raw Pointers\n\nRaw pointers `*` and references `&T` function similarly, but references are\nalways safe because they are guaranteed to point to valid data due to the\nborrow checker. Dereferencing a raw pointer can only be done through an unsafe\nblock.\n```rust,editable\nfn main() {\n let raw_p: *const u32 = &10;\n\n unsafe {\n assert!(*raw_p == 10);\n }\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Unsafe Operations", "heading_path": ["Unsafe Operations", "Raw Pointers"], "path": "unsafe.md", "url": "https://doc.rust-lang.org/rust-by-example/unsafe.html#raw-pointers", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/unsafe.md#calling-unsafe-functions-2", "text": "Rust by Example › Unsafe Operations › Calling Unsafe Functions\n\nSome functions can be declared as `unsafe`, meaning it is the programmer's\nresponsibility to ensure correctness instead of the compiler's. One example\nof this is [`std::slice::from_raw_parts`] which will create a slice given a\npointer to the first element and a length.\n```rust,editable\nuse std::slice;\n\nfn main() {\n let some_vector = vec![1, 2, 3, 4];\n\n let pointer = some_vector.as_ptr();\n let length = some_vector.len();\n\n unsafe {\n let my_slice: &[u32] = slice::from_raw_parts(pointer, length);\n\n assert_eq!(some_vector.as_slice(), my_slice);\n }\n}\n```\nFor `slice::from_raw_parts`, one of the assumptions which *must* be upheld is\nthat the pointer passed in points to valid memory and that the memory pointed to\nis of the correct type. If these invariants aren't upheld then the program's\nbehaviour is undefined and there is no knowing what will happen.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Unsafe Operations", "heading_path": ["Unsafe Operations", "Calling Unsafe Functions"], "path": "unsafe.md", "url": "https://doc.rust-lang.org/rust-by-example/unsafe.html#calling-unsafe-functions", "has_code": true, "code_tags": ["rust,editable"]}} {"id": "rust-by-example/unsafe/asm.md#inline-assembly-0", "text": "Rust by Example › Inline assembly\n\nRust provides support for inline assembly via the `asm!` macro.\nIt can be used to embed handwritten assembly in the assembly output generated by the compiler.\nGenerally this should not be necessary, but might be where the required performance or timing\ncannot be otherwise achieved. Accessing low level hardware primitives, e.g. in kernel code, may also demand this functionality.\n**Note**: the examples here are given in x86/x86-64 assembly, but other architectures are also supported.\nInline assembly is currently supported on the following architectures:\n- x86 and x86-64\n- ARM\n- AArch64\n- RISC-V", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Inline assembly", "heading_path": ["Inline assembly"], "path": "unsafe/asm.md", "url": "https://doc.rust-lang.org/rust-by-example/unsafe/asm.html#inline-assembly", "has_code": false, "code_tags": []}} {"id": "rust-by-example/unsafe/asm.md#basic-usage-1", "text": "Rust by Example › Inline assembly › Basic usage\n\nLet us start with the simplest possible example:\n```rust\nuse std::arch::asm;\n\nunsafe {\n asm!(\"nop\");\n}\n```\nThis will insert a NOP (no operation) instruction into the assembly generated by the compiler.\nNote that all `asm!` invocations have to be inside an `unsafe` block, as they could insert\narbitrary instructions and break various invariants. The instructions to be inserted are listed\nin the first argument of the `asm!` macro as a string literal.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Basic usage"], "path": "unsafe/asm.md", "url": "https://doc.rust-lang.org/rust-by-example/unsafe/asm.html#basic-usage", "has_code": true, "code_tags": ["rust"]}} {"id": "rust-by-example/unsafe/asm.md#inputs-and-outputs-2", "text": "Rust by Example › Inline assembly › Inputs and outputs\n\nNow inserting an instruction that does nothing is rather boring. Let us do something that\nactually acts on data:\n```rust\nuse std::arch::asm;\n\nlet x: u64;\nunsafe {\n asm!(\"mov {}, 5\", out(reg) x);\n}\nassert_eq!(x, 5);\n```\nThis will write the value `5` into the `u64` variable `x`.\nYou can see that the string literal we use to specify instructions is actually a template string.\nIt is governed by the same rules as Rust format strings.\nThe arguments that are inserted into the template however look a bit different than you may\nbe familiar with. First we need to specify if the variable is an input or an output of the\ninline assembly. In this case it is an output. We declared this by writing `out`.\nWe also need to specify in what kind of register the assembly expects the variable.\nIn this case we put it in an arbitrary general purpose register by specifying `reg`.\nThe compiler will choose an appropriate register to insert into\nthe template and will read the variable from there after the inline assembly finishes executing.\nLet us see another example that also uses an input:\n```rust\nuse std::arch::asm;\n\nlet i: u64 = 3;\nlet o: u64;\nunsafe {\n asm!(\n \"mov {0}, {1}\",\n \"add {0}, 5\",\n out(reg) o,\n in(reg) i,\n );\n}\nassert_eq!(o, 8);\n```\nThis will add `5` to the input in variable `i` and write the result to variable `o`.\nThe particular way this assembly does this is first copying the value from `i` to the output,\nand then adding `5` to it.\nThe example shows a few things:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Inputs and outputs"], "path": "unsafe/asm.md", "url": "https://doc.rust-lang.org/rust-by-example/unsafe/asm.html#inputs-and-outputs", "has_code": true, "code_tags": ["rust"]}} {"id": "rust-by-example/unsafe/asm.md#inputs-and-outputs-3", "text": "Rust by Example › Inline assembly › Inputs and outputs\n\nFirst, we can see that `asm!` allows multiple template string arguments; each\none is treated as a separate line of assembly code, as if they were all joined\ntogether with newlines between them. This makes it easy to format assembly\ncode.\nSecond, we can see that inputs are declared by writing `in` instead of `out`.\nThird, we can see that we can specify an argument number, or name as in any format string.\nFor inline assembly templates this is particularly useful as arguments are often used more than once.\nFor more complex inline assembly using this facility is generally recommended, as it improves\nreadability, and allows reordering instructions without changing the argument order.\nWe can further refine the above example to avoid the `mov` instruction:\n```rust\nuse std::arch::asm;\n\nlet mut x: u64 = 3;\nunsafe {\n asm!(\"add {0}, 5\", inout(reg) x);\n}\nassert_eq!(x, 8);\n```\nWe can see that `inout` is used to specify an argument that is both input and output.\nThis is different from specifying an input and output separately in that it is guaranteed to assign both to the same register.\nIt is also possible to specify different variables for the input and output parts of an `inout` operand:\n```rust\nuse std::arch::asm;\n\nlet x: u64 = 3;\nlet y: u64;\nunsafe {\n asm!(\"add {0}, 5\", inout(reg) x => y);\n}\nassert_eq!(y, 8);\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Inputs and outputs"], "path": "unsafe/asm.md", "url": "https://doc.rust-lang.org/rust-by-example/unsafe/asm.html#inputs-and-outputs", "has_code": true, "code_tags": ["rust"]}} {"id": "rust-by-example/unsafe/asm.md#late-output-operands-4", "text": "Rust by Example › Inline assembly › Late output operands\n\nThe Rust compiler is conservative with its allocation of operands. It is assumed that an `out`\ncan be written at any time, and can therefore not share its location with any other argument.\nHowever, to guarantee optimal performance it is important to use as few registers as possible,\nso they won't have to be saved and reloaded around the inline assembly block.\nTo achieve this Rust provides a `lateout` specifier. This can be used on any output that is\nwritten only after all inputs have been consumed. There is also an `inlateout` variant of this\nspecifier.\nHere is an example where `inlateout` *cannot* be used in `release` mode or other optimized cases:\n```rust\nuse std::arch::asm;\n\nlet mut a: u64 = 4;\nlet b: u64 = 4;\nlet c: u64 = 4;\nunsafe {\n asm!(\n \"add {0}, {1}\",\n \"add {0}, {2}\",\n inout(reg) a,\n in(reg) b,\n in(reg) c,\n );\n}\nassert_eq!(a, 12);\n```\nIn unoptimized cases (e.g. `Debug` mode), replacing `inout(reg) a` with `inlateout(reg) a` in the\nabove example can continue to give the expected result. However, with `release` mode or other\noptimized cases, using `inlateout(reg) a` can instead lead to the final value `a = 16`, causing the\nassertion to fail.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Late output operands"], "path": "unsafe/asm.md", "url": "https://doc.rust-lang.org/rust-by-example/unsafe/asm.html#late-output-operands", "has_code": true, "code_tags": ["rust"]}} {"id": "rust-by-example/unsafe/asm.md#late-output-operands-5", "text": "Rust by Example › Inline assembly › Late output operands\n\nThis is because in optimized cases, the compiler is free to allocate the same register for inputs\n`b` and `c` since it knows that they have the same value. Furthermore, when `inlateout` is used, `a`\nand `c` could be allocated to the same register, in which case the first `add` instruction would\noverwrite the initial load from variable `c`. This is in contrast to how using `inout(reg) a`\nensures a separate register is allocated for `a`.\nHowever, the following example can use `inlateout` since the output is only modified after all input\nregisters have been read:\n```rust\nuse std::arch::asm;\n\nlet mut a: u64 = 4;\nlet b: u64 = 4;\nunsafe {\n asm!(\"add {0}, {1}\", inlateout(reg) a, in(reg) b);\n}\nassert_eq!(a, 8);\n```\nAs you can see, this assembly fragment will still work correctly if `a` and `b` are assigned to the same register.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Late output operands"], "path": "unsafe/asm.md", "url": "https://doc.rust-lang.org/rust-by-example/unsafe/asm.html#late-output-operands", "has_code": true, "code_tags": ["rust"]}} {"id": "rust-by-example/unsafe/asm.md#explicit-register-operands-6", "text": "Rust by Example › Inline assembly › Explicit register operands\n\nSome instructions require that the operands be in a specific register.\nTherefore, Rust inline assembly provides some more specific constraint specifiers.\nWhile `reg` is generally available on any architecture, explicit registers are highly architecture specific. E.g. for x86 the general purpose registers `eax`, `ebx`, `ecx`, `edx`, `ebp`, `esi`, and `edi` among others can be addressed by their name.\n```rust,no_run\nuse std::arch::asm;\n\nlet cmd = 0xd1;\nunsafe {\n asm!(\"out 0x64, eax\", in(\"eax\") cmd);\n}\n```\nIn this example we call the `out` instruction to output the content of the `cmd` variable to port `0x64`. Since the `out` instruction only accepts `eax` (and its sub registers) as operand we had to use the `eax` constraint specifier.\n**Note**: unlike other operand types, explicit register operands cannot be used in the template string: you can't use `{}` and should write the register name directly instead. Also, they must appear at the end of the operand list after all other operand types.\nConsider this example which uses the x86 `mul` instruction:\n```rust\nuse std::arch::asm;\n\nfn mul(a: u64, b: u64) -> u128 {\n let lo: u64;\n let hi: u64;\n\n unsafe {\n asm!(\n // The x86 mul instruction takes rax as an implicit input and writes\n // the 128-bit result of the multiplication to rax:rdx.\n \"mul {}\",\n in(reg) a,\n inlateout(\"rax\") b => lo,\n lateout(\"rdx\") hi\n );\n }\n\n ((hi as u128) << 64) + lo as u128\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Explicit register operands"], "path": "unsafe/asm.md", "url": "https://doc.rust-lang.org/rust-by-example/unsafe/asm.html#explicit-register-operands", "has_code": true, "code_tags": ["rust", "rust,no_run"]}} {"id": "rust-by-example/unsafe/asm.md#explicit-register-operands-7", "text": "Rust by Example › Inline assembly › Explicit register operands\n\nThis uses the `mul` instruction to multiply two 64-bit inputs with a 128-bit result.\nThe only explicit operand is a register, that we fill from the variable `a`.\nThe second operand is implicit, and must be the `rax` register, which we fill from the variable `b`.\nThe lower 64 bits of the result are stored in `rax` from which we fill the variable `lo`.\nThe higher 64 bits are stored in `rdx` from which we fill the variable `hi`.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Explicit register operands"], "path": "unsafe/asm.md", "url": "https://doc.rust-lang.org/rust-by-example/unsafe/asm.html#explicit-register-operands", "has_code": false, "code_tags": []}} {"id": "rust-by-example/unsafe/asm.md#clobbered-registers-8", "text": "Rust by Example › Inline assembly › Clobbered registers\n\nIn many cases inline assembly will modify state that is not needed as an output.\nUsually this is either because we have to use a scratch register in the assembly or because instructions modify state that we don't need to further examine.\nThis state is generally referred to as being \"clobbered\".\nWe need to tell the compiler about this since it may need to save and restore this state around the inline assembly block.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Clobbered registers"], "path": "unsafe/asm.md", "url": "https://doc.rust-lang.org/rust-by-example/unsafe/asm.html#clobbered-registers", "has_code": false, "code_tags": []}} {"id": "rust-by-example/unsafe/asm.md#clobbered-registers-9", "text": "Rust by Example › Inline assembly › Clobbered registers\n\n```rust\nuse std::arch::asm;\n\nfn main() {\n // three entries of four bytes each\n let mut name_buf = [0_u8; 12];\n // String is stored as ascii in ebx, edx, ecx in order\n // Because ebx is reserved, the asm needs to preserve the value of it.\n // So we push and pop it around the main asm.\n // 64 bit mode on 64 bit processors does not allow pushing/popping of\n // 32 bit registers (like ebx), so we have to use the extended rbx register instead.\n\n unsafe {\n asm!(\n \"push rbx\",\n \"cpuid\",\n \"mov [rdi], ebx\",\n \"mov [rdi + 4], edx\",\n \"mov [rdi + 8], ecx\",\n \"pop rbx\",\n // We use a pointer to an array for storing the values to simplify\n // the Rust code at the cost of a couple more asm instructions\n // This is more explicit with how the asm works however, as opposed\n // to explicit register outputs such as `out(\"ecx\") val`\n // The *pointer itself* is only an input even though it's written behind\n in(\"rdi\") name_buf.as_mut_ptr(),\n // select cpuid 0, also specify eax as clobbered\n inout(\"eax\") 0 => _,\n // cpuid clobbers these registers too\n out(\"ecx\") _,\n out(\"edx\") _,\n );\n }\n\n let name = core::str::from_utf8(&name_buf).unwrap();\n println!(\"CPU Manufacturer ID: {}\", name);\n}\n\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Clobbered registers"], "path": "unsafe/asm.md", "url": "https://doc.rust-lang.org/rust-by-example/unsafe/asm.html#clobbered-registers", "has_code": true, "code_tags": ["rust"]}} {"id": "rust-by-example/unsafe/asm.md#clobbered-registers-10", "text": "Rust by Example › Inline assembly › Clobbered registers\n\nIn the example above we use the `cpuid` instruction to read the CPU manufacturer ID.\nThis instruction writes to `eax` with the maximum supported `cpuid` argument and `ebx`, `edx`, and `ecx` with the CPU manufacturer ID as ASCII bytes in that order.\nEven though `eax` is never read we still need to tell the compiler that the register has been modified so that the compiler can save any values that were in these registers before the asm. This is done by declaring it as an output but with `_` instead of a variable name, which indicates that the output value is to be discarded.\nThis code also works around the limitation that `ebx` is a reserved register by LLVM. That means that LLVM assumes that it has full control over the register and it must be restored to its original state before exiting the asm block, so it cannot be used as an input or output **except** if the compiler uses it to fulfill a general register class (e.g. `in(reg)`). This makes `reg` operands dangerous when using reserved registers as we could unknowingly corrupt our input or output because they share the same register.\nTo work around this we use `rdi` to store the pointer to the output array, save `ebx` via `push`, read from `ebx` inside the asm block into the array and then restore `ebx` to its original state via `pop`. The `push` and `pop` use the full 64-bit `rbx` version of the register to ensure that the entire register is saved. On 32 bit targets the code would instead use `ebx` in the `push`/`pop`.\nThis can also be used with a general register class to obtain a scratch register for use inside the asm code:", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Clobbered registers"], "path": "unsafe/asm.md", "url": "https://doc.rust-lang.org/rust-by-example/unsafe/asm.html#clobbered-registers", "has_code": false, "code_tags": []}} {"id": "rust-by-example/unsafe/asm.md#clobbered-registers-11", "text": "Rust by Example › Inline assembly › Clobbered registers\n\n```rust\nuse std::arch::asm;\n\n// Multiply x by 6 using shifts and adds\nlet mut x: u64 = 4;\nunsafe {\n asm!(\n \"mov {tmp}, {x}\",\n \"shl {tmp}, 1\",\n \"shl {x}, 2\",\n \"add {x}, {tmp}\",\n x = inout(reg) x,\n tmp = out(reg) _,\n );\n}\nassert_eq!(x, 4 * 6);\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Clobbered registers"], "path": "unsafe/asm.md", "url": "https://doc.rust-lang.org/rust-by-example/unsafe/asm.html#clobbered-registers", "has_code": true, "code_tags": ["rust"]}} {"id": "rust-by-example/unsafe/asm.md#symbol-operands-and-abi-clobbers-12", "text": "Rust by Example › Inline assembly › Symbol operands and ABI clobbers\n\nBy default, `asm!` assumes that any register not specified as an output will have its contents preserved by the assembly code. The [`clobber_abi`] argument to `asm!` tells the compiler to automatically insert the necessary clobber operands according to the given calling convention ABI: any register which is not fully preserved in that ABI will be treated as clobbered. Multiple `clobber_abi` arguments may be provided and all clobbers from all specified ABIs will be inserted.\n```rust\nuse std::arch::asm;\n\nextern \"C\" fn foo(arg: i32) -> i32 {\n println!(\"arg = {}\", arg);\n arg * 2\n}\n\nfn call_foo(arg: i32) -> i32 {\n unsafe {\n let result;\n asm!(\n \"call {}\",\n // Function pointer to call\n in(reg) foo,\n // 1st argument in rdi\n in(\"rdi\") arg,\n // Return value in rax\n out(\"rax\") result,\n // Mark all registers which are not preserved by the \"C\" calling\n // convention as clobbered.\n clobber_abi(\"C\"),\n );\n result\n }\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Symbol operands and ABI clobbers"], "path": "unsafe/asm.md", "url": "https://doc.rust-lang.org/rust-by-example/unsafe/asm.html#symbol-operands-and-abi-clobbers", "has_code": true, "code_tags": ["rust"]}} {"id": "rust-by-example/unsafe/asm.md#register-template-modifiers-13", "text": "Rust by Example › Inline assembly › Register template modifiers\n\nIn some cases, fine control is needed over the way a register name is formatted when inserted into the template string. This is needed when an architecture's assembly language has several names for the same register, each typically being a \"view\" over a subset of the register (e.g. the low 32 bits of a 64-bit register).\nBy default the compiler will always choose the name that refers to the full register size (e.g. `rax` on x86-64, `eax` on x86, etc).\nThis default can be overridden by using modifiers on the template string operands, just like you would with format strings:\n```rust\nuse std::arch::asm;\n\nlet mut x: u16 = 0xab;\n\nunsafe {\n asm!(\"mov {0:h}, {0:l}\", inout(reg_abcd) x);\n}\n\nassert_eq!(x, 0xabab);\n```\nIn this example, we use the `reg_abcd` register class to restrict the register allocator to the 4 legacy x86 registers (`ax`, `bx`, `cx`, `dx`) of which the first two bytes can be addressed independently.\nLet us assume that the register allocator has chosen to allocate `x` in the `ax` register.\nThe `h` modifier will emit the register name for the high byte of that register and the `l` modifier will emit the register name for the low byte. The asm code will therefore be expanded as `mov ah, al` which copies the low byte of the value into the high byte.\nIf you use a smaller data type (e.g. `u16`) with an operand and forget to use template modifiers, the compiler will emit a warning and suggest the correct modifier to use.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Register template modifiers"], "path": "unsafe/asm.md", "url": "https://doc.rust-lang.org/rust-by-example/unsafe/asm.html#register-template-modifiers", "has_code": true, "code_tags": ["rust"]}} {"id": "rust-by-example/unsafe/asm.md#memory-address-operands-14", "text": "Rust by Example › Inline assembly › Memory address operands\n\nSometimes assembly instructions require operands passed via memory addresses/memory locations.\nYou have to manually use the memory address syntax specified by the target architecture.\nFor example, on x86/x86_64 using Intel assembly syntax, you should wrap inputs/outputs in `[]` to indicate they are memory operands:\n```rust\nuse std::arch::asm;\n\nfn load_fpu_control_word(control: u16) {\n unsafe {\n asm!(\"fldcw [{}]\", in(reg) &control, options(nostack));\n }\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Memory address operands"], "path": "unsafe/asm.md", "url": "https://doc.rust-lang.org/rust-by-example/unsafe/asm.html#memory-address-operands", "has_code": true, "code_tags": ["rust"]}} {"id": "rust-by-example/unsafe/asm.md#labels-15", "text": "Rust by Example › Inline assembly › Labels\n\nAny reuse of a named label, local or otherwise, can result in an assembler or linker error or may cause other strange behavior. Reuse of a named label can happen in a variety of ways including:\n- explicitly: using a label more than once in one `asm!` block, or multiple times across blocks.\n- implicitly via inlining: the compiler is allowed to instantiate multiple copies of an `asm!` block, for example when the function containing it is inlined in multiple places.\n- implicitly via LTO: LTO can cause code from *other crates* to be placed in the same codegen unit, and so could bring in arbitrary labels.\nAs a consequence, you should only use GNU assembler **numeric** [local labels] inside inline assembly code. Defining symbols in assembly code may lead to assembler and/or linker errors due to duplicate symbol definitions.\nMoreover, on x86 when using the default Intel syntax, due to [an LLVM bug], you shouldn't use labels exclusively made of `0` and `1` digits, e.g. `0`, `11` or `101010`, as they may end up being interpreted as binary values. Using `options(att_syntax)` will avoid any ambiguity, but that affects the syntax of the *entire* `asm!` block. (See Options, below, for more on `options`.)\n```rust\nuse std::arch::asm;\n\nlet mut a = 0;\nunsafe {\n asm!(\n \"mov {0}, 10\",\n \"2:\",\n \"sub {0}, 1\",\n \"cmp {0}, 3\",\n \"jle 2f\",\n \"jmp 2b\",\n \"2:\",\n \"add {0}, 2\",\n out(reg) a\n );\n}\nassert_eq!(a, 5);\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Labels"], "path": "unsafe/asm.md", "url": "https://doc.rust-lang.org/rust-by-example/unsafe/asm.html#labels", "has_code": true, "code_tags": ["rust"]}} {"id": "rust-by-example/unsafe/asm.md#labels-16", "text": "Rust by Example › Inline assembly › Labels\n\nThis will decrement the `{0}` register value from 10 to 3, then add 2 and store it in `a`.\nThis example shows a few things:\n- First, that the same number can be used as a label multiple times in the same inline block.\n- Second, that when a numeric label is used as a reference (as an instruction operand, for example), the suffixes “b” (“backward”) or ”f” (“forward”) should be added to the numeric label. It will then refer to the nearest label defined by this number in this direction.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Labels"], "path": "unsafe/asm.md", "url": "https://doc.rust-lang.org/rust-by-example/unsafe/asm.html#labels", "has_code": false, "code_tags": []}} {"id": "rust-by-example/unsafe/asm.md#options-options-17", "text": "Rust by Example › Inline assembly › Options {#options}\n\nBy default, an inline assembly block is treated the same way as an external FFI function call with a custom calling convention: it may read/write memory, have observable side effects, etc. However, in many cases it is desirable to give the compiler more information about what the assembly code is actually doing so that it can optimize better.\nLet's take our previous example of an `add` instruction:\n```rust\nuse std::arch::asm;\n\nlet mut a: u64 = 4;\nlet b: u64 = 4;\nunsafe {\n asm!(\n \"add {0}, {1}\",\n inlateout(reg) a, in(reg) b,\n options(pure, nomem, nostack),\n );\n}\nassert_eq!(a, 8);\n```\nOptions can be provided as an optional final argument to the `asm!` macro. We specified three options here:\n- `pure` means that the asm code has no observable side effects and that its output depends only on its inputs. This allows the compiler optimizer to call the inline asm fewer times or even eliminate it entirely.\n- `nomem` means that the asm code does not read or write to memory. By default the compiler will assume that inline assembly can read or write any memory address that is accessible to it (e.g. through a pointer passed as an operand, or a global).\n- `nostack` means that the asm code does not push any data onto the stack. This allows the compiler to use optimizations such as the stack red zone on x86-64 to avoid stack pointer adjustments.\nThese allow the compiler to better optimize code using `asm!`, for example by eliminating pure `asm!` blocks whose outputs are not needed.\nSee the reference for the full list of available options and their effects.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Inline assembly", "heading_path": ["Inline assembly", "Options {#options}"], "path": "unsafe/asm.md", "url": "https://doc.rust-lang.org/rust-by-example/unsafe/asm.html#options-options", "has_code": true, "code_tags": ["rust"]}} {"id": "rust-by-example/compatibility.md#compatibility-0", "text": "Rust by Example › Compatibility\n\nThe Rust language is evolving rapidly, and because of this certain compatibility\nissues can arise, despite efforts to ensure forwards-compatibility wherever\npossible.\n* Raw identifiers", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Compatibility", "heading_path": ["Compatibility"], "path": "compatibility.md", "url": "https://doc.rust-lang.org/rust-by-example/compatibility.html#compatibility", "has_code": false, "code_tags": []}} {"id": "rust-by-example/compatibility/raw_identifiers.md#raw-identifiers-0", "text": "Rust by Example › Raw identifiers\n\nRust, like many programming languages, has the concept of \"keywords\".\nThese identifiers mean something to the language, and so you cannot use them in\nplaces like variable names, function names, and other places.\nRaw identifiers let you use keywords where they would not normally be allowed.\nThis is particularly useful when Rust introduces new keywords, and a library\nusing an older edition of Rust has a variable or function with the same name\nas a keyword introduced in a newer edition.\nFor example, consider a crate `foo` compiled with the 2015 edition of Rust that\nexports a function named `try`. This keyword is reserved for a new feature in\nthe 2018 edition, so without raw identifiers, we would have no way to name the\nfunction.\n```rust,ignore\nextern crate foo;\n\nfn main() {\n foo::try();\n}\n```\nYou'll get this error:\n```text\nerror: expected identifier, found keyword `try`\n --> src/main.rs:4:4\n |\n4 | foo::try();\n | ^^^ expected identifier, found keyword\n```\nYou can write this with a raw identifier:\n```rust,ignore\nextern crate foo;\n\nfn main() {\n foo::r#try();\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Raw identifiers", "heading_path": ["Raw identifiers"], "path": "compatibility/raw_identifiers.md", "url": "https://doc.rust-lang.org/rust-by-example/compatibility/raw_identifiers.html#raw-identifiers", "has_code": true, "code_tags": ["rust,ignore", "text"]}} {"id": "rust-by-example/meta.md#meta-0", "text": "Rust by Example › Meta\n\nSome topics aren't exactly relevant to how your program runs but provide you\ntooling or infrastructure support which just makes things better for\neveryone. These topics include:\n- Documentation: Generate library documentation for users via the included\n `rustdoc`.\n- Playground: Integrate the Rust Playground in your documentation.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Meta", "heading_path": ["Meta"], "path": "meta.md", "url": "https://doc.rust-lang.org/rust-by-example/meta.html#meta", "has_code": false, "code_tags": []}} {"id": "rust-by-example/meta/doc.md#documentation-0", "text": "Rust by Example › Documentation\n\nUse `cargo doc` to build documentation in `target/doc`, `cargo doc --open`\nwill automatically open it in your web browser.\nUse `cargo test` to run all tests (including documentation tests), and `cargo\ntest --doc` to only run documentation tests.\nThese commands will appropriately invoke `rustdoc` (and `rustc`) as required.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Documentation", "heading_path": ["Documentation"], "path": "meta/doc.md", "url": "https://doc.rust-lang.org/rust-by-example/meta/doc.html#documentation", "has_code": false, "code_tags": []}} {"id": "rust-by-example/meta/doc.md#doc-comments-1", "text": "Rust by Example › Documentation › Doc comments\n\nDoc comments are very useful for big projects that require documentation. When\nrunning `rustdoc`, these are the comments that get compiled into\ndocumentation. They are denoted by a `///`, and support [Markdown].\n````rust,editable,ignore\n#![crate_name = \"doc\"]\n/// A human being is represented here\npub struct Person {\n /// A person must have a name, no matter how much Juliet may hate it\n name: String,\n}\nimpl Person {\n /// Creates a person with the given name.\n ///\n /// # Examples\n ///\n /// ```\n /// // You can have rust code between fences inside the comments\n /// // If you pass --test to `rustdoc`, it will even test it for you!\n /// use doc::Person;\n /// let person = Person::new(\"name\");\n /// ```\n pub fn new(name: &str) -> Person {\n Person {\n name: name.to_string(),\n }\n }\n /// Gives a friendly hello!\n ///\n /// Says \"Hello, name\" to the `Person` it is called on.\n pub fn hello(&self) {\n println!(\"Hello, {}!\", self.name);\n }\n}\nfn main() {\n let john = Person::new(\"John\");\n john.hello();\n}\n````\nTo run the tests, first build the code as a library, then tell `rustdoc` where\nto find the library so it can link it into each doctest program:\n```shell\n$ rustc doc.rs --crate-type lib\n$ rustdoc --test --extern doc=\"libdoc.rlib\" doc.rs\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Documentation", "heading_path": ["Documentation", "Doc comments"], "path": "meta/doc.md", "url": "https://doc.rust-lang.org/rust-by-example/meta/doc.html#doc-comments", "has_code": true, "code_tags": ["shell"]}} {"id": "rust-by-example/meta/doc.md#doc-attributes-2", "text": "Rust by Example › Documentation › Doc attributes\n\nBelow are a few examples of the most common `#[doc]` attributes used with\n`rustdoc`.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Documentation", "heading_path": ["Documentation", "Doc attributes"], "path": "meta/doc.md", "url": "https://doc.rust-lang.org/rust-by-example/meta/doc.html#doc-attributes", "has_code": false, "code_tags": []}} {"id": "rust-by-example/meta/doc.md#inline-3", "text": "Rust by Example › Documentation › Doc attributes › `inline`\n\nUsed to inline docs, instead of linking out to separate page.\n```rust,ignore\n#[doc(inline)]\npub use bar::Bar;\n\n/// bar docs\npub mod bar {\n /// the docs for Bar\n pub struct Bar;\n}\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Documentation", "heading_path": ["Documentation", "Doc attributes", "`inline`"], "path": "meta/doc.md", "url": "https://doc.rust-lang.org/rust-by-example/meta/doc.html#inline", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "rust-by-example/meta/doc.md#no_inline-4", "text": "Rust by Example › Documentation › Doc attributes › `no_inline`\n\nUsed to prevent linking out to separate page or anywhere.\n```rust,ignore\n// Example from libcore/prelude\n#[doc(no_inline)]\npub use crate::mem::drop;\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Documentation", "heading_path": ["Documentation", "Doc attributes", "`no_inline`"], "path": "meta/doc.md", "url": "https://doc.rust-lang.org/rust-by-example/meta/doc.html#no_inline", "has_code": true, "code_tags": ["rust,ignore"]}} {"id": "rust-by-example/meta/doc.md#hidden-5", "text": "Rust by Example › Documentation › Doc attributes › `hidden`\n\nUsing this tells `rustdoc` not to include this in documentation:\n```rust,editable,ignore\n// Example from the futures-rs library\n#[doc(hidden)]\npub use self::async_await::*;\n```\nFor documentation, `rustdoc` is widely used by the community. It's what is used\nto generate the std library docs.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Documentation", "heading_path": ["Documentation", "Doc attributes", "`hidden`"], "path": "meta/doc.md", "url": "https://doc.rust-lang.org/rust-by-example/meta/doc.html#hidden", "has_code": true, "code_tags": ["rust,editable,ignore"]}} {"id": "rust-by-example/meta/doc.md#see-also-6", "text": "Rust by Example › Documentation › Doc attributes › See also:\n\n- The Rust Book: Making Useful Documentation Comments\n- The rustdoc Book\n- The Reference: Doc comments\n- RFC 1574: API Documentation Conventions\n- RFC 1946: Relative links to other items from doc comments (intra-rustdoc links)\n- Is there any documentation style guide for comments? (reddit)", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Documentation", "heading_path": ["Documentation", "Doc attributes", "See also:"], "path": "meta/doc.md", "url": "https://doc.rust-lang.org/rust-by-example/meta/doc.html#see-also", "has_code": false, "code_tags": []}} {"id": "rust-by-example/meta/playground.md#playground-0", "text": "Rust by Example › Playground\n\nThe Rust Playground is a way to experiment with\nRust code through a web interface.", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Playground", "heading_path": ["Playground"], "path": "meta/playground.md", "url": "https://doc.rust-lang.org/rust-by-example/meta/playground.html#playground", "has_code": false, "code_tags": []}} {"id": "rust-by-example/meta/playground.md#using-it-with-mdbook-1", "text": "Rust by Example › Playground › Using it with `mdbook`\n\nIn `mdbook`, you can make code examples playable and editable.\n```rust,editable\nfn main() {\n println!(\"Hello World!\");\n}\n```\nThis allows the reader to both run your code sample, but also modify and tweak\nit. The key here is the adding of the word `editable` to your codefence block\nseparated by a comma.\n````markdown\n```rust,editable\n//...place your code here\n```\n````\nAdditionally, you can add `ignore` if you want `mdbook` to skip your code when\nit builds and tests.\n````markdown\n```rust,editable,ignore\n//...place your code here\n```\n````", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Playground", "heading_path": ["Playground", "Using it with `mdbook`"], "path": "meta/playground.md", "url": "https://doc.rust-lang.org/rust-by-example/meta/playground.html#using-it-with-mdbook", "has_code": true, "code_tags": ["rust,editable", "rust,editable,ignore"]}} {"id": "rust-by-example/meta/playground.md#using-it-with-docs-2", "text": "Rust by Example › Playground › Using it with docs\n\nYou may have noticed in some of the official Rust docs a\nbutton that says \"Run\", which opens the code sample up in a new tab in Rust\nPlayground. This feature is enabled if you use the `#[doc]` attribute called\n`html_playground_url`.\n```text\n#![doc(html_playground_url = \"https://play.rust-lang.org/\")]\n//! ```\n//! println!(\"Hello World\");\n//! ```\n```", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Playground", "heading_path": ["Playground", "Using it with docs"], "path": "meta/playground.md", "url": "https://doc.rust-lang.org/rust-by-example/meta/playground.html#using-it-with-docs", "has_code": true, "code_tags": ["text"]}} {"id": "rust-by-example/meta/playground.md#see-also-3", "text": "Rust by Example › Playground › Using it with docs › See also:\n\n- The Rust Playground\n- The Rust Playground On Github\n- The rustdoc Book", "metadata": {"book": "rust-by-example", "book_title": "Rust by Example", "part": "Summary", "chapter": "Playground", "heading_path": ["Playground", "Using it with docs", "See also:"], "path": "meta/playground.md", "url": "https://doc.rust-lang.org/rust-by-example/meta/playground.html#see-also", "has_code": false, "code_tags": []}}