This repository contains the source of "The Rust Programming Language" book.

Overview

The Rust Programming Language

Build Status

This repository contains the source of "The Rust Programming Language" book.

The book is available in dead-tree form from No Starch Press.

You can also read the book for free online. Please see the book as shipped with the latest stable, beta, or nightly Rust releases. Be aware that issues in those versions may have been fixed in this repository already, as those releases are updated less frequently.

See the releases to download just the code of all the code listings that appear in the book.

Requirements

Building the book requires mdBook, ideally the same version that rust-lang/rust uses in this file. To get it:

$ cargo install mdbook --vers [version-num]

Building

To build the book, type:

$ mdbook build

The output will be in the book subdirectory. To check it out, open it in your web browser.

Firefox:

$ firefox book/index.html                       # Linux
$ open -a "Firefox" book/index.html             # OS X
$ Start-Process "firefox.exe" .\book\index.html # Windows (PowerShell)
$ start firefox.exe .\book\index.html           # Windows (Cmd)

Chrome:

$ google-chrome book/index.html                 # Linux
$ open -a "Google Chrome" book/index.html       # OS X
$ Start-Process "chrome.exe" .\book\index.html  # Windows (PowerShell)
$ start chrome.exe .\book\index.html            # Windows (Cmd)

To run the tests:

$ mdbook test

Contributing

We'd love your help! Please see CONTRIBUTING.md to learn about the kinds of contributions we're looking for.

Because the book is printed, and because we want to keep the online version of the book close to the print version when possible, it may take longer than you're used to for us to address your issue or pull request.

So far, we've been doing a larger revision to coincide with Rust Editions. Between those larger revisions, we will only be correcting errors. If your issue or pull request isn't strictly fixing an error, it might sit until the next time that we're working on a large revision: expect on the order of months or years. Thank you for your patience!

Translations

We'd love help translating the book! See the Translations label to join in efforts that are currently in progress. Open a new issue to start working on a new language! We're waiting on mdbook support for multiple languages before we merge any in, but feel free to start!

Spellchecking

To scan source files for spelling errors, you can use the spellcheck.sh script available in the ci directory. It needs a dictionary of valid words, which is provided in ci/dictionary.txt. If the script produces a false positive (say, you used word BTreeMap which the script considers invalid), you need to add this word to ci/dictionary.txt (keep the sorted order for consistency).

Comments
  • start of error handling

    start of error handling

    I started on the error handling chapter. I feel... okay about it. I dunno.

    I decided to go with an example that we start with a panic, and then convert to a result. I think this draws the connection a bit better than showing two totally different examples, but at the downside of showing function panic that probably shouldn't. Reasonable folks may differ on this tradeoff; I'm open to arguments.

    I decided to stop here rather than go on to all the From stuff, because I wanted to make sure that this was on track first. Should we use a different example? Is the length of time spent talking about panic vs abort a waste of time right here? How should I end up demonstrating try!, just making another dummy function from main()?

    opened by steveklabnik 28
  • Are 'variable bindings' valuable?

    Are 'variable bindings' valuable?

    Instead of talking about variable bindings, would it be better to use the term variables (like other languages) and explain the rest in terms of references?

    Let's explore. Are variable bindings:

    • a core concept
    • a way of explaining/thinking about what's happening
    • an implementation detail

    Variable (mathematics): (from Wikipedia) In elementary mathematics, a variable is an alphabetic character representing a number, called the value of the variable, which is either arbitrary or not fully specified or unknown.

    Variable (computer science): (from Wikipedia) In computer programming, a variable or scalar is a storage location paired with an associated symbolic name (an identifier), which contains some known or unknown quantity of information referred to as a value. The variable name is the usual way to reference the stored value; this separation of name and content allows the name to be used independently of the exact information it represents. The identifier in computer source code can be bound to a value during run time, and the value of the variable may thus change during the course of program execution.

    Variable: (my definition) A symbolic name that represents a value or reference.

    Niko Matsakis uses the terms variables and references in his into_rust() videos and I'm not confused. Even rustc's error messages use the term variable.

    So what is a variable binding and how is it different from a variable? In writing about this, it became clear that after 2 years following Rust, I still don't know. Some possibilities:

    • A variable implies changeability/mutability, so we need a different concept to make immutability clear.
    • A value/reference is a separate concept from the symbolic name we use to represent it.
    • A separate concept is needed to explain why an immutable variable can contain a mutable reference.
    • To make it clear that moving a variable binding does not necessarily mean copying its memory.
    • To make it clear that declaring a binding does not necessarily mean copying or allocating memory.

    Am I missing an aspect to the variable bindings concept?

    I think saying a variable is bound to a value or bound to a reference is a great way of expressing it, but does it really mean something different to a variable contains a value or contains a reference?

    Does a distinction between variable bindings and variables need to be drawn?

    opened by elahn 27
  • Single webpage / pdf / epub / mobi

    Single webpage / pdf / epub / mobi

    Is there the possibility of having a version of the Book in a single web page or pdf format? I want to search across the chapters and having them be separate links makes this difficult to do so.

    Enhancement Online only blocked upstream 
    opened by hjr3 27
  • Start modules _again_

    Start modules _again_

    This time, drop all the crate stuff.

    This example is still abstract, but is based off the original stuff that cargo new generates for you. @carols10cents @jonathandturner what do you think?

    opened by steveklabnik 27
  • chapter 10: generics

    chapter 10: generics

    Reviewers: Please read the added text for these chapters and leave any comments you have on this PR! Thank you for your help!

    Carol TODO:

    • [x] Add filenames to code examples where it makes sense
    • [x] Switch underscores used for emphasis to asterisks for consistency
    opened by steveklabnik 25
  • Explain alarmed ferris convention in chapter 1 for code that doesn't compile on purpose

    Explain alarmed ferris convention in chapter 1 for code that doesn't compile on purpose

    This example from Learn Rust doesn't work -

    extern crate rand;
    
    use std::io;
    use std::cmp::Ordering;
    use rand::Rng;
    
    fn main() {
        println!("Guess the number!");
    
        let secret_number = rand::thread_rng().gen_range(1, 101);
    
        println!("The secret number is: {}", secret_number);
    
        println!("Please input your guess.");
    
        let mut guess = String::new();
    
        io::stdin().read_line(&mut guess)
            .ok()
            .expect("failed to read line");
    
        println!("You guessed: {}", guess);
    
        match guess.cmp(&secret_number) {
            Ordering::Less    => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal   => println!("You win!"),
        }
    }
    

    I am using Rust 1.5 on OSX and the example doesn't work on Rust playground either.

    Bug Online only 
    opened by diptanu 24
  • "This page has moved" shouldn't have status code 200

    Google and other search engines are still serving search results from the first edition of the book; for example, this link was the first result for "rust ownership". I noticed that they're being served up with a status code of 200 - should this be 301 or 410 to let them be purged from the index and replaced with a current URL?

    Online only E-help-wanted 
    opened by mistydemeo 22
  • Guessing Game rand example doesn't compile

    Guessing Game rand example doesn't compile

    Versions

    Book:

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

    rustc: rustc 1.31.0 (abe02cefd 2018-12-04)

    cargo: cargo 1.31.0 (339d9f9c8 2018-11-16)

    What is the issue:

    When going through the Guessing Game tutorial:

    Listing 2-3 contains some code that should use rand:

    use std::io;
    use rand::Rng;
    
    fn main() {
        println!("Guess the number!");
    
        let secret_number = rand::thread_rng().gen_range(1, 101);
    
        println!("The secret number is: {}", secret_number);
    
        println!("Please input your guess.");
    
        let mut guess = String::new();
    
        io::stdin().read_line(&mut guess)
            .expect("Failed to read line");
    
        println!("You guessed: {}", guess);
    }
    

    This code does not compile, with the following errors:

    azvorygi@bit-shifter:~/Code/rst$ cargo run
       Compiling rst v0.1.0 (/users/azvorygi/Code/rst)                                                                                                                                            
    error[E0432]: unresolved import `rand`                                                                                                                                                        
     --> src/main.rs:2:5                                                                                                                                                                          
      |                                                                                                                                                                                           
    2 | use rand::Rng;                                                                                                                                                                            
      |     ^^^^ maybe a missing `extern crate rand;`?                                                                                                                                            
                                                                                                                                                                                                  
    warning: unused import: `rand::Rng`                                                                                                                                                           
     --> src/main.rs:2:5                                                                                                                                                                          
      |                                                                                                                                                                                           
    2 | use rand::Rng;                                                                                                                                                                            
      |     ^^^^^^^^^                                                                                                                                                                             
      |                                                                                                                                                                                           
      = note: #[warn(unused_imports)] on by default                                                                                                                                               
                                                                                                                                                                                                  
    error[E0599]: no method named `gen_range` found for type `rand::ThreadRng` in the current scope                                                                                               
     --> src/main.rs:7:44                                                                                                                                                                         
      |                                                                                                                                                                                           
    7 |     let secret_number = rand::thread_rng().gen_range(1, 101);                                                                                                                             
      |                                            ^^^^^^^^^                                                                                                                                      
      |                                                                                                                                                                                           
      = help: items from traits can only be used if the trait is in scope                                                                                                                         
    help: the following trait is implemented but not in scope, perhaps add a `use` for it:                                                                                                        
      |                                                                                                                                                                                           
    1 | use rand::Rng;                                                                                                                                                                            
      |                                                                                                                                                                                           
                                                                                                                                                                                                  
    error: aborting due to 2 previous errors                                                                                                                                                      
                                                                                                                                                                                                  
    Some errors occurred: E0432, E0599.                                                                                                                                                           
    For more information about an error, try `rustc --explain E0432`.                                                                                                                             
    error: Could not compile `rst`.                                                                                                                                                               
    

    This is of course after adding the following to my Cargo.toml:

    [dependencies]
    rand = "0.3.14"
    

    Here's a github repo with my repo when it is breaking: https://github.com/zvory/guessing-game-breaking

    opened by zvory 21
  • Script to lint for copypasta'd file paths that should be generic

    Script to lint for copypasta'd file paths that should be generic

    One thing we do when showing errors is show file:///projects/bindings in Cargo's output. It'd be nice to somehow catch that this is always the text we use, as it's really easy to copy/paste something and forget to change it.

    Enhancement E-easy E-help-wanted 
    opened by steveklabnik 21
  • Not the best example in

    Not the best example in "6.3 Concise Control Flow with if let".

    Hey guys!

    First of all - thank you very much for the great language and the great book. I'm new to coding, so I'm sorry if anything (or everything) I say is stupid.

    At least for me, there is a very bad example in the "6.3 Concise Control Flow with if let" chapter. It says:

    if let Some(3) = some_u8_value {
        println!("three");
    }
    

    I had been somewhat at a loss as to why or how this expression is any better than say

    if Some(3) == some_u8_value {
        println!("three");
    }
    

    and it took me some time to come to the conclusion that in this particular case it probably isn't better at all, if not worse for arguably "weird" (for me in that state of mind) syntax. By weird, I mean that at the time the part after "if" looked like

    let 3 = x

    for me, which had just turned my head around :)

    Long story short, I think it is more clear to explain "if let" through use of unwrapping the optional value (if it is there), like so:

    if let Some(x) = some_u8_value {
        println!("The unwrapped value is {}", x);
    }
    

    I hope that makes sense.

    Enhancement 
    opened by andywwright 19
  • Document the loop_break_value feature

    Document the loop_break_value feature

    This pull requests adds a section in the new features appendix about the loop_break_value feature (which should be stabilized after all the documentation is ready), tracked in issue rust-lang/rust#37339.

    I reused the basic example I made for Rust by Example, but if something more realistic (maybe with threads and channels) is OK here I'm happy to change it.

    opened by pietroalbini 17
  • Chapter 15-05: Incorrect interpretation of compiler error

    Chapter 15-05: Incorrect interpretation of compiler error

    • I have searched open and closed issues and pull requests for duplicates, using these search terms:
      • Messenger
      • 15
      • &mut self
    • I have checked the latest main branch to see if this has already been fixed, in this file:
      • https://github.com/rust-lang/book/blob/2bd5d42c9956369132228da6409f0e68da56c51a/src/ch15-05-interior-mutability.md?plain=1#L195
      • https://github.com/rust-lang/book/blob/2bd5d42c9956369132228da6409f0e68da56c51a/listings/ch15-smart-pointers/listing-15-21/output.txt#L6

    URL to the section(s) of the book with this problem: https://doc.rust-lang.org/book/ch15-05-interior-mutability.html#a-use-case-for-interior-mutability-mock-objects

    Description of the problem:

    The following sentence is incorrect:

    We also can’t take the suggestion from the error text to use &mut self instead, because then the signature of send wouldn’t match the signature in the Messenger trait definition

    because the suggestion of the compiler is to modify Line 2, the signature in the Messenger trait definition itself, NOT Line 57 which is the implementation of send in MockMessenger.

    Suggested fix:

    We also can't take the suggestion from the error text to use &mut self instead, because we are testing an API and it's not a good idea to modify the API for the sole purpose of testing. Usually, the test engineers do not have permission to modify the API they're testing.

    opened by kingh0730 0
  • suggestion to clarify the scope of references

    suggestion to clarify the scope of references

    To clarify the scope of references, I suggest the comment should be moved after the "let r3 = &mut s;" statement. "println!("{}", r1);" or "println!("{}", r2);" is possible before "let r3 = &mut s;" .

    opened by daejungkim 1
  • Swap inconsistent `assert_eq!` argument order in testing chapter

    Swap inconsistent `assert_eq!` argument order in testing chapter

    The chapter starts off by using assert_eq!(…); with assert_eq!(actual, expected); argument ordering, but then suddenly swaps the order to assert_eq!(expected, actual); with assert_eq!(4, add_two(2));

    Further more it then states …

    We could write the assertion in this test as assert_eq!(add_two(2), 4), which would result in the same failure message that displays `` assertion failed: (left == right).

    … which seems weird as in the chapter assert_eq!(4, add_two(2)) actually is the odd one out, not assert_eq!(add_two(2), 4).

    By swapping the args the message of "which would result in the same failure message" remains true, but the text feels a bit more consistent and predictable.

    opened by regexident 0
  • CH 15 Section 06 -- Detailing the stack overflow error.

    CH 15 Section 06 -- Detailing the stack overflow error.

    • I have searched open and closed issues and pull requests for duplicates, using these search terms:
      • "15"
      • "15.6"
    • I have checked the latest main branch to see if this has already been fixed, in this file:
      • main/src/ch15-06-reference-cycles.md

    URL to the section(s) of the book with this problem:

    • https://doc.rust-lang.org/book/ch15-06-reference-cycles.html

    Description of the problem: The quoted text below informs the user that the code commented out in the second attached image will cause a stack overflow error if executed. Overall, the book does an amazing job at teaching Rust to the reader, but in this section, it fails to explain why exactly this stack overflow error occurs. Stack overflow errors often stem from recursive logic bugs, but no such logic exists in those code snippets which makes the cause of the error difficult to ascertain.

    image image

    ... "If you uncomment the last println! and run the program, Rust will try to print this cycle with a pointing to b pointing to a and so forth until it overflows the stack. "

    Suggested fix: I feel that a quick discussion of how the error relates to the Debug trait would greatly benefit this section and provide users with some extra detail to aid in their understanding of the language. image

    opened by seantronsen 0
  • Improvement of Chapter 13.3 Guidance with optional flags (Tasks from 12.5)

    Improvement of Chapter 13.3 Guidance with optional flags (Tasks from 12.5)

    Thanks for the book and all the work that went into it! I really appreciate it.

    Following might be an idea for an improvement of chapter 13.3.

    In earlier sections, tasks were given and later picked up on again. Here, in section 12.5, one of the tasks was:

    [...] try controlling case sensitivity through either a command line argument or an environment variable.

    The solution for me was the use of optional flags (-i, --ignore-case, --case-sensitive)

    After the changes from 13.3 using an iterator, a solution for the optional flags is needed, to make the program and unit tests work again.

    I think, it would be nice if the chapter 13.3 picks up on the tasks from chapter 12.5 and helps (or gives hints) with a solution for optional arguments.

    I tried to find a solution, while keeping the focus on the topic of iterators. But I believe, it's not the most elegant one.

      pub fn build(mut args: impl Iterator<Item = String>
        ) -> Result<Config, &'static str> {
    
            
            // decide that one or the other takes precedence (arg > env)
            // Default: it is off
            // ENV can put it on
            // Arg can overrrule env
            let mut ignore_case = env::var("IGNORE_CASE").is_ok();
            let mut query:String = String::new();
            let mut file_path:String = String::new();
    
    
            args.next(); // ignore program name
            while None != match args.next() {
                    Some(arg) => {
    
                        println!("Arg is: {arg}");
                        if arg.eq("-i") || arg.eq("--ignore-case"){
                            ignore_case = true;
                        }else if arg.eq("--case-sensitive"){
                            ignore_case = false
                        }else{
                            if query.is_empty(){
                                query = arg
                            }else if file_path.is_empty() {
                                file_path = arg
                            }
                        }
                        Some(true,)
                    },
                    _ => None,
                }  {
                    dbg!("Still parsing config..");   
                }
    
            if query.is_empty() || file_path.is_empty(){
                return Err("Too many arguments!");
            }else{
                return Ok(Config{ query, file_path, ignore_case })
            }
        }    
    }
    
    opened by InRiPa 0
Releases(rand-0.8)
Owner
The Rust Programming Language
The Rust Programming Language
This Repo Contains my Week Long Journey Trying to Learn Rust Programming Language 🦀.

the-rust-way This Repo Contains my Week Long Journey Trying to Learn Rust Programming Language ?? . ?? Thanks to all Wonderful Contributors Thanks a l

Kanishk Pachauri 7 Oct 20, 2022
A repository for showcasing my knowledge of the Rust programming language, and continuing to learn the language.

Learning Rust I started learning the Rust programming language before using GitHub, but increased its usage afterwards. I have found it to be a fast a

Sean P. Myrick V19.1.7.2 2 Nov 8, 2022
clone of grep cli written in Rust. From Chapter 12 of the Rust Programming Language book

minigrep is a clone of the grep cli in rust Minigrep will find a query string in a file. To test it out, clone the project and run cargo run body poem

Raunak Singh 1 Dec 14, 2021
A minimal version of 'grep' implemented in Rust. Exercise in the "The Rust Programming Language" book.

Minigrep - A simple grep-like tool implemented in Rust This simple CLI tool searches for a given pattern in a specified file and as a result, it print

Filip Szutkowski 3 Mar 15, 2024
The ray tracer challenge in rust - Repository to follow my development of "The Raytracer Challenge" book by Jamis Buck in the language Rust

The Ray Tracer Challenge This repository contains all the code written, while step by implementing Ray Tracer, based on the book "The Ray Tracer Chall

Jakob Westhoff 54 Dec 25, 2022
Source code for the book Rust in Action

Welcome to Rust in Action source code This source code repository is a companion to the Rust in Action book available from Manning Publications. Suppo

Rust in Action 1.3k Dec 30, 2022
This repo contains the schedule for summer paper meetup

21' Summer ?? Paper Meetup Annoucement ?? 6/21/2021: our first summer love paper meetup will start on July 10th, 2021. Papers to contribute ?? Check o

msft system virtual meetup 24 Sep 22, 2022
This project contains small exercises to get you used to reading and writing Rust code

rustlings ?? ❤️ Greetings and welcome to rustlings. This project contains small exercises to get you used to reading and writing Rust code. This inclu

Cynthia Tran 1 May 24, 2022
Elemental System Designs is an open source project to document system architecture design of popular apps and open source projects that we want to study

Elemental System Designs is an open source project to document system architecture design of popular apps and open source projects that we want to study

Jason Shin 9 Apr 10, 2022
A library for extracting #[no_mangle] pub extern "C" functions (https://docs.rust-embedded.org/book/interoperability/rust-with-c.html#no_mangle)

A library for extracting #[no_mangle] pub extern "C" functions In order to expose a function with C binary interface for interoperability with other p

Dmitrii - Demenev 0 Feb 17, 2022
Book - Actix user guides

User guides Actix User Guide Actix API Documentation (Development) Actix API Documentation (Releases) Actix Web User Guide Actix Web API Documentation

Actix 185 Dec 25, 2022
Complete code for the larger example programs from the book.

Code Examples for Programming Rust This repository contains complete code for the larger example programs from the book “Programming Rust”, by Jim Bla

Programming Rust 670 Jan 1, 2023
Code to follow along the "Zero To Production" book on API development in Rust.

Zero To Production / Code (Chapter 10 - Part 1) Zero To Production In Rust is an opinionated introduction to backend development using Rust. This repo

Luca Palmieri 2.8k Dec 31, 2022
Rust crate to implement a counterpart to the PBRT book's (3rd edition) C++ code.

Rust crate to implement a counterpart to the PBRT book's (3rd edition) C++ code.

Jan Walter 763 Dec 27, 2022
High Assurance Rust - A free book about developing secure and robust systems software.

High Assurance Rust - A free book about developing secure and robust systems software.

Tiemoko Ballo 1.1k Jan 9, 2023
Learn programming with Rust as a first language (book)

Learn programming with Rust as first language This is a book to learn programming from scratch. Read the book here: https://deavid.github.io/lprfl/ LI

David Martínez Martí 2 May 21, 2022
Majestic Lisp book and implementation, in Brazillian Portuguese.

Majestic Lisp Criado e desenvolvido por Lucas S. Vieira <lucasvieira at protonmail dot com>. Seja bem-vindo(a) a Majestic Lisp, um dialeto de Lisp cuj

Lucas Vieira 3 Oct 26, 2022
Search and read 'The Rust Book' from the terminal

TheBook TheBook is a command line utility that allows you to SEARCH and READ The Rust Programming Language (popularly known as 'The Book' ) from the t

0xHiro 技術者 239 Jan 4, 2023
Generate SUMMARY.md files based on your book's file structure

mdbook-autosummary Generate a SUMMARY.md for your mdBook based on your folder structure! Warning The implementation is hacky and has several limitatio

Hyper 3 Sep 30, 2023