This is the Rust course used by the Android team at Google. It provides you the material to quickly teach Rust to everyone.

Overview

Comprehensive Rust 🦀

This repository has the source code for Comprehensive Rust 🦀 , a four day Rust course developed by the Android team. The course covers all aspects of Rust, from basic syntax to generics and error handling. It also includes Android-specific content on the last day.

Read the course at https://google.github.io/comprehensive-rust/.

Building

The course is built using mdBook and its Svgbob plugin. Install both tools with

$ cargo install mdbook
$ cargo install mdbook-svgbob

Then run

$ mdbook test

to test all included Rust snippets. Run

$ mdbook serve

to start a web server with the course. You'll find the content on http://localhost:3000. You can use mdbook build to create a static version of the course in the book/ directory.

Contact

For questions or comments, please contact Martin Geisler or start a discussion on GitHub. We would love to hear from you.

Comments
  • Corrected 1 or 2 typos

    Corrected 1 or 2 typos

    missing verb : "The goal of the course to teach you Rust." -> "The goal of the course is to teach you Rust."

    missing of ? : "to cover all it" -> "to cover all of it" for this one, I'm not a native english speaker but it seems more correct to me. I'll let you check :)

    opened by LLyaudet 4
  • Misc doc fixes

    Misc doc fixes

    List of changes:

    • fix typos found via codespell -S target -L crate
    • ignore Cargo.lock
    • hide dollar signs used before commands without output for easier copy and paste in Github
    opened by kianmeng 4
  • Better Test Case for Day 2 Polygon Exercise

    Better Test Case for Day 2 Polygon Exercise

    test_shape_circumferences() is testing the circumference of a Polygon with only 2 points in total. However, according to the the general definition:

    "A polygon is a closed figure where the sides are all line segments. Each side must intersect exactly two others sides but only at their endpoints. The sides must be noncollinear and have a common endpoint."

    In short, a valid polygon is supposed to have at least 3 points.

    Proposal

    To avoid ambiguity (i.e., users might implement circumference() with an early-return condition like points.len() < 3 and end up with test failure), let's add one more point to the test case.

    NewTestCase.png

    opened by der3318 3
  • Specify Unicode encoding

    Specify Unicode encoding

    Page: https://google.github.io/comprehensive-rust/hello-world.html

    It states Rust strings can contain Unicode characters. This is not super helpful. We need to know what encoding is supported by the string literal. Most C++ compilers will assume UTF-8 as the encoding by default. It will be helpful if this page can state the encoding.

    opened by bibhas2 3
  • Inform about rustup.sh installation

    Inform about rustup.sh installation

    Hello :wave:

    Thanks for creating this guide! I've one discussion that I want to make:

    At the start, during the setup/installation phase, it seems to currently recommend installing rust's tools using the built-in packages from apt repository

    https://github.com/google/comprehensive-rust/blob/b411aa688a46c2b90d5eb5aaa0f891e4843a66c6/src/cargo.md?plain=1#L8-L12

    I think this might be fine, since this is more familiar with peoples that are just getting started (I know I did this once). Though I think it might be better to also include the "standard" way of installing the tools, since it would make it easier for when latest stable/beta/nightly versions are available (via $ rustup update)

    $ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
    
    opened by taufik-rama 3
  • Unsafe Rust

    Unsafe Rust

    Unsafe Rust is mentioned in the course; pls add links to the material on Unsafe Rust to the respective place in the course where unsafe Rust is mentioned

    opened by MaschitaG 2
  • Typo in Tuple Structs

    Typo in Tuple Structs

    https://google.github.io/comprehensive-rust/structs/tuple-structs.html

    struct PoundOfForce(f64);
    struct Newtons(f64);
    
    fn compute_thruster_force() -> PoundOfForce {
        todo!("Ask a rocket scientist at NASA")
    }
    
    fn set_thruster_force(force: Newtons) {
        // ...
    }
    
    fn main() {
        let force = compute_thruster_force();
        set_thruster_force(force);
    }
    

    compile with cargo run shows:

    ❯ cargo run
       Compiling exercise v0.1.0 (/Users/z/code/exercise)
    error[E0308]: mismatched types
      --> src/main.rs:14:24
       |
    14 |     set_thruster_force(force);
       |     ------------------ ^^^^^ expected struct `Newtons`, found struct `PoundOfForce`
       |     |
       |     arguments to this function are incorrect
       |
    note: function defined here
      --> src/main.rs:8:4
       |
    8  | fn set_thruster_force(force: Newtons) {
       |    ^^^^^^^^^^^^^^^^^^ --------------
    
    For more information about this error, try `rustc --explain E0308`.
    error: could not compile `exercise` due to previous error
    

    So this maybe a typo in the code?

    opened by livrth 2
  • [ERROR] (mdbook::utils): Error: Couldn't open SUMMARY.md in

    [ERROR] (mdbook::utils): Error: Couldn't open SUMMARY.md in "/home/user1/cargo/src" directory

    I created an empty directory called cargo in my home directory. Inside it I successfully ran:

    $ cargo install mdbook
    $ cargo install mdbook-svgbob
    

    And then tried to run:

    $ mdbook test
    $ mdbook serve
    

    But both commands above (test and serve) gives me the same error:

    2022-12-26 13:34:39 [ERROR] (mdbook::utils): Error: Couldn't open SUMMARY.md in "/home/user1/cargo/src" directory
    2022-12-26 13:34:39 [ERROR] (mdbook::utils): 	Caused By: No such file or directory (os error 2)
    
    opened by llagerlof 2
  • Note that

    Note that "Android" means "AOSP" and not "Android app"

    I’d strongly suggest, in https://google.github.io/comprehensive-rust/welcome.html , to explicitely note that the Android part considers how to contribute to Android source code, using Android build system. On first reading, the way I saw it presented on twitter, and in this page, I thought that this was aimed for the Android developers which, for some reason, wanted to write part of their app in Rust.

    I’ll immediately admit that a reader could guess it is not actually for app developer, as the two sentences indicate OASP.

    Building Android components in Rust. AIDL servers and clients.

    The trouble being that, if you’re not used to working on Android source code, you may not know what AIDL is, and that it’s not a Rust specific term you’ll learn later.

    Personally, I admit that, since AnkiDroid, an Android app, is already using Rust for its backend and Kotlin for its front-end, I was wondering whether I could learn things to improve our system. I guess it won’t be the case.

    And with this, I believe it’s the last PR/issue you’ll get from me. Thanks for making this public

    opened by Arthur-Milchior 2
  • Dark Mode SVG Text Fix

    Dark Mode SVG Text Fix

    Currently, SVG text in many of the diagrams appears as black on dark blue in dark mode. The SVG text elements currently receive the default color, black:

    Light mode: image

    Dark mode: image

    This PR suggests a one-liner CSS fix to apply the foreground css variable (var(--fg)) to the svg text element to make svg text legible and accessible. This is bundled into the output using the additional-css property in mdbook's config book.toml.

    This is probably something that could be fixed upstream in mdbook/mdbook-svgbob sometime, but this patch would fix it for current usability.

    opened by nofurtherinformation 2
  • `mdbook test` fails on commit 26404744

    `mdbook test` fails on commit 26404744

    Followed the README to run mdbook test and got the following error.

    2022-12-22 23:35:37 [ERROR] (mdbook::book): rustdoc returned an error:
    
    --- stdout
    
    running 2 tests
    test /var/folders/3h/t8595zjd10l4248jh4z21h8r0000gn/T/mdbook-ozrGSf/concurrency/scoped-threads.md - Scoped_Threads (line 19) ... FAILED
    test /var/folders/3h/t8595zjd10l4248jh4z21h8r0000gn/T/mdbook-ozrGSf/concurrency/scoped-threads.md - Scoped_Threads (line 5) - compile fail ... ok
    
    failures:
    
    ---- /var/folders/3h/t8595zjd10l4248jh4z21h8r0000gn/T/mdbook-ozrGSf/concurrency/scoped-threads.md - Scoped_Threads (line 19) stdout ----
    error[E0658]: use of unstable library feature 'scoped_threads'
     --> /var/folders/3h/t8595zjd10l4248jh4z21h8r0000gn/T/mdbook-ozrGSf/concurrency/scoped-threads.md:25:5
      |
    7 |     thread::scope(|scope| {
      |     ^^^^^^^^^^^^^
      |
      = note: see issue #93203 <https://github.com/rust-lang/rust/issues/93203> for more information
    
    error[E0658]: use of unstable library feature 'scoped_threads'
     --> /var/folders/3h/t8595zjd10l4248jh4z21h8r0000gn/T/mdbook-ozrGSf/concurrency/scoped-threads.md:26:15
      |
    8 |         scope.spawn(|| {
      |               ^^^^^
      |
      = note: see issue #93203 <https://github.com/rust-lang/rust/issues/93203> for more information
    
    error: aborting due to 2 previous errors
    
    For more information about this error, try `rustc --explain E0658`.
    Couldn't compile the test.
    
    failures:
        /var/folders/3h/t8595zjd10l4248jh4z21h8r0000gn/T/mdbook-ozrGSf/concurrency/scoped-threads.md - Scoped_Threads (line 19)
    
    test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.04s
    
    
    --- stderr
    
    opened by luandy64 2
  • example in chapter `Ownership` seems not correct

    example in chapter `Ownership` seems not correct

    In Ownership chapter we give one example to indicate that variable will be dropped at the end of scope.

    
    struct Point(i32, i32);
    
    fn main() {
        {
            let p = Point(3, 4);
            println!("x: {}", p.0);
        }
        println!("y: {}", p.1);
    }
    
    

    But actually the rustc’s complaining is

        Blocking waiting for file lock on package cache
       Compiling exercise v0.1.0 (/home/coder/project/exercise)
    error[E0425]: cannot find value `p` in this scope
     --> src/main.rs:8:23
      |
    8 |     println!("y: {}", p.1);
      |                       ^ not found in this scope
    
    For more information about this error, try `rustc --explain E0425`.
    error: could not compile `exercise` due to previous error
    

    I believe this example may cause confusion.

    opened by Yansongsongsong 2
  • Don't silence warnings in exercises

    Don't silence warnings in exercises

    All the exercises start with something like

    // TODO: remove this when you're done with your implementation.
    #![allow(unused_variables, dead_code)]
    

    You're training people that it's normal and a good idea to ignore warnings during development. Instead, continue to emphasize what you mention in passing elsewhere -- Rust has great compiler errors!

    Of course it's going to have a lot of warnings at the start since you've given them incomplete code. You can

    • Just let them deal with it
    • Or mention RUSTFLAGS=-A... cargo ... perhaps

    But you shouldn't imply ignoring warnings until you're "done with your implementation" is a good idea, or IMO that ignoring warnings in your source code (as opposed to a command line flag) is a good idea.

    opened by QuineDot 1
  • Suggestions: Misc

    Suggestions: Misc

    I think you should show the Option and Result definitions here. They'll see the variants everywhere in Rust.


    Clarify that a HashMap doesn't have to be keyed with a &str or String (unlike a JSON object, say).


    Here, I was going to mention that the lifetime can be explicit in some cases... but upon reconsideration that's probably not worth getting into. However, perhaps you should mention that lifetimes with the same name must indeed be equal. This will matter a lot should they every run into some &'a mut Thing<'a> errors.

    But also on that page and on this one, you say

    Read &'a Point as “a borrowed Point which is valid for at least the lifetime a”.

    That can be misinterpreted as "the borrow is valid for at least 'a", as opposed to "the Point is valid for at least 'a". I.e. it might given the mistaken impression that a borrow can be lengthened.


    The getters and setters here aren't very idiomatic. First of all, nothing here is public -- everything must be in the same module -- so you'd just access the fields directly. Second of all, instead of a getter an infallible setter, if the struct was public, you'd probably just make those fields public too. If the fields actually have invariants, the setters shouldn't be infallible, but instead return a Result<_, _>.

    More generally, it may give the impression that using getters and setters is idiomatic (even in the same module).


    Perhaps note this list of receivers is non-exhaustive. E.g. Box<Self>.


    I don't know that "omitted" is the right term for mod in_another_file;. Also perhaps note that (except perhaps for test modules) separate files is the norm.

    opened by QuineDot 1
  • Trait Objects memory diagram uses different order for different cells

    Trait Objects memory diagram uses different order for different cells

    https://google.github.io/comprehensive-rust/generics/trait-objects.html has this diagram:

    https://github.com/google/comprehensive-rust/blob/c212a473ba4d060b209b654c0dd403328d6e137f/src/generics/trait-objects.md?plain=1#L41-L67

    Quoting https://doc.rust-lang.org/reference/types/trait-object.html

    Each instance of a pointer to a trait object includes:

    • a pointer to an instance of a type T that implements SomeTrait
    • a virtual method table, often just called a vtable, which contains, for each method of SomeTrait and its supertraits that T implements, a pointer to T's implementation (i.e. a function pointer).

    It seems the diagram here draws one object as (instance, vtable) and the second as (vtable, instance). Consistency would help, and based on https://doc.rust-lang.org/reference/types/trait-object.html it seems (instance, vtable) is the safer assumption.

    waiting 
    opened by tv42 4
  • Suggestion: Globals and state

    Suggestion: Globals and state

    You say:

    Global state is managed with static and constant variables.

    But consts can't manage a state. Statics can... but preferably only with interior mutability of some sort. Your examples have no actual managing of state.

    You do say "We will look at mutating static data in the chapter on Unsafe Rust", and indeed have a page on static mut.

    That slide should just be deleted. It's so nigh-on impossible to get right even for experts that there's a push for its deprecation. Definitely no introduction to Rust should convey that it might be reasonable thing to reach for.


    What should take its place? A more accurate portrayal of how global state is actually done in safe idiomatic Rust.

    First, it usually isn't! Pass your state around, use an Arc<Mutex<_>> or the like.

    But when it is, it's done with interior mutability. static atomics, thread local RefCell, once_cell (eventually to be part of std, lazy_static.


    If you must leave in static mut, at least cover Once. But really that's just a tedious and error prone way of building up things like once_cell manually. In practice people just use once_cell and similar instead of rolling their own.

    Reaching for unsafe to do global state yourself is just a bad idea.

    opened by QuineDot 1
Owner
Google
Google ❤️ Open Source
Google
Rust Programming Fundamentals - one course to rule them all, one course to find them...

Ultimate Rust Crash Course This is the companion repository for the Ultimate Rust Crash Course published online, presented live at O'Reilly virtual ev

Nathan Stocks 1.3k Jan 8, 2023
A peer-reviewed collection of articles/talks/repos which teach concise, idiomatic Rust.

This repository collects resources for writing clean, idiomatic Rust code. Please bring your own. ?? Idiomatic coding means following the conventions

Matthias 4.2k Dec 30, 2022
A tool & library to help you with the compiler course.

Compiler Course Helper Support: eliminate left recursion (require grammar with no cycles or ϵ-production) calculate nullable, first sets, follow, sets

水夕 4 May 2, 2022
Rust Language Learning material

RustMaterial Rust Language Learning material Rust Rust is blazingly fast systems programming language that prevents segfaults and guarantees thread sa

Udhay Prakash Pethakamsetty 1 Jan 6, 2022
The best Intermediate Rust course out there!

Ultimate Rust 2: Intermediate Concepts This is the companion repository for the Ultimate Rust 2: Intermediate Concepts (the followup to the popular Ul

Nathan Stocks 155 Jan 4, 2023
Free Rust 🦀 course in English 🇬🇧

Learn Rust ?? Free Rust ?? course in English ???? This course was inspired by Dcode Before starting to learn a programming language, you need to under

Skwal 10 Jul 5, 2022
Rust Crash Course, by BPB Publications

Rust Crash Course Grasp the fundamentals of programming in Rust and put your knowledge to use. This is the repository for Rust Crash Course ,published

BPB Online 9 Nov 26, 2022
P523 is a classic compiler course taught by R. Kent Dybvig.

P523 is a classic compiler course taught by R. Kent Dybvig. This repo implements the course using Rust, provides a framework to help you master P523.

Sirius Demon 44 Dec 26, 2022
:crab: 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

The Rust Programming Language 33.1k Jan 2, 2023
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
A webapp that reads your articles to you while you're on the subway

ReadToMyShoe Video Demo A website that reads articles to you, even when you're offline. Still in early development. This is a full-stack Rust webapp,

Michael Rosenberg 20 Dec 10, 2022
A tray application for Windows that gives you push notifications and instant downloads of new posts, messages and stories posted by models you subscribe to on Onlyfans.

OF-notifier A tray application for Windows that gives you push notifications and instant downloads of new posts, messages and stories posted by models

Gentlemen Mercenary 10 Dec 20, 2022
Tests a wide variety of N64 features, from common to hardware quirks. Written in Rust. Executes quickly.

n64-systemtest Tests a wide variety of N64 features, from common to hardware quirks. Written in Rust. Executes quickly. n64-systemtest is a test rom t

null 37 Jan 7, 2023
Quickly set up a `probe-run` + `defmt` + `flip-link` embedded project

app-template Quickly set up a probe-run + defmt + flip-link embedded project Dependencies 1. flip-link: $ cargo install flip-link 2. probe-run: $ # ma

Knurling 201 Dec 29, 2022
Rust 核心库和标准库的源码级中文翻译,可作为 IDE 工具的智能提示 (Rust core library and standard library translation. can be used as IntelliSense for IDE tools)

Rust 标准库中文版 这是翻译 Rust 库 的地方, 相关源代码来自于 https://github.com/rust-lang/rust。 如果您不会说英语,那么拥有使用中文的文档至关重要,即使您会说英语,使用母语也仍然能让您感到愉快。Rust 标准库是高质量的,不管是新手还是老手,都可以从中

wtklbm 493 Jan 4, 2023
A set of Zero Knowledge modules, written in Rust and designed to be used in other system programming environments.

Zerokit A set of Zero Knowledge modules, written in Rust and designed to be used in other system programming environments. Initial scope Focus on RLN

vac 44 Dec 27, 2022
A relatively simple puzzle generator application written in Rust and used via Javascript

Puzzlip Basic Overview This is a relatively simple puzzle generator application written in Rust and used via Javascript in https://puzzlip.com. If you

Nenad 5 Dec 7, 2022
🦀 Rust crate that allows creating weighted prefix trees that can be used in autocomplete

weighted_trie ?? Rust crate that allows creating weighted prefix trees that can be used in autocomplete Released API Docs Quickstart To use weigthed-t

Alexander Osipenko 8 Mar 1, 2023
Elton is a benchmark utility written in rust aimed to be used to benchmark HTTP calls.

Elton Elton is an HTTP Benchmark utility with options to be used within an HTTP interface. Installation Elton is currently available via Docker or by

Emil Priver 5 Sep 22, 2023