diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 160efc7ae836..4fe90df51d3c 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -1,7 +1,9 @@ # Summary + [Welcome to Comprehensive Rust 🦀](index.md) + - [Running the Course](running-the-course.md) - [Course Structure](running-the-course/course-structure.md) - [Keyboard Shortcuts](running-the-course/keyboard-shortcuts.md) @@ -11,10 +13,9 @@ - [Code Samples](cargo/code-samples.md) - [Running Cargo Locally](cargo/running-locally.md) - # Day 1: Morning ----- +--- - [Welcome](welcome-day-1.md) - [What is Rust?](welcome-day-1/what-is-rust.md) @@ -74,7 +75,7 @@ # Day 2: Morning ----- +--- - [Welcome](welcome-day-2.md) @@ -126,10 +127,9 @@ - [Iterators and Ownership](exercises/day-2/iterators-and-ownership.md) - [Strings and Iterators](exercises/day-2/strings-iterators.md) - # Day 3: Morning ----- +--- - [Welcome](welcome-day-3.md) - [Generics](generics.md) @@ -184,10 +184,9 @@ - [Exercises](exercises/day-3/afternoon.md) - [Safe FFI Wrapper](exercises/day-3/safe-ffi-wrapper.md) - # Android ----- +--- - [Welcome](android.md) - [Setup](android/setup.md) @@ -210,10 +209,9 @@ - [With Java](android/interoperability/java.md) - [Exercises](exercises/android/morning.md) - # Bare Metal: Morning ----- +--- - [Welcome](bare-metal.md) - [no_std](bare-metal/no_std.md) @@ -260,10 +258,9 @@ - [Exercises](exercises/bare-metal/afternoon.md) - [RTC Driver](exercises/bare-metal/rtc.md) - # Concurrency: Morning ----- +--- - [Welcome](concurrency.md) - [Threads](concurrency/threads.md) @@ -304,19 +301,17 @@ - [Dining Philosophers](exercises/concurrency/dining-philosophers-async.md) - [Broadcast Chat Application](exercises/concurrency/chat-app.md) - # Final Words ----- +--- - [Thanks!](thanks.md) - [Other Resources](other-resources.md) - [Credits](credits.md) - # Solutions ----- +--- - [Solutions](exercises/solutions.md) - [Day 1 Morning](exercises/day-1/solutions-morning.md) diff --git a/src/android/aidl.md b/src/android/aidl.md index a055ce0486ac..fe0c055e61aa 100644 --- a/src/android/aidl.md +++ b/src/android/aidl.md @@ -1,7 +1,9 @@ # AIDL -The [Android Interface Definition Language -(AIDL)](https://developer.android.com/guide/components/aidl) is supported in Rust: +The +[Android Interface Definition Language +(AIDL)](https://developer.android.com/guide/components/aidl) is supported in +Rust: -* Rust code can call existing AIDL servers, -* You can create new AIDL servers in Rust. +- Rust code can call existing AIDL servers, +- You can create new AIDL servers in Rust. diff --git a/src/android/aidl/client.md b/src/android/aidl/client.md index 01d4249ecf45..85af8adb2f7b 100644 --- a/src/android/aidl/client.md +++ b/src/android/aidl/client.md @@ -2,13 +2,13 @@ Finally, we can create a Rust client for our new service. -*birthday_service/src/client.rs*: +_birthday_service/src/client.rs_: ```rust,ignore {{#include birthday_service/src/client.rs:main}} ``` -*birthday_service/Android.bp*: +_birthday_service/Android.bp_: ```javascript {{#include birthday_service/Android.bp:birthday_client}} diff --git a/src/android/aidl/implementation.md b/src/android/aidl/implementation.md index 899930165cf2..ed94853464fa 100644 --- a/src/android/aidl/implementation.md +++ b/src/android/aidl/implementation.md @@ -2,13 +2,13 @@ We can now implement the AIDL service: -*birthday_service/src/lib.rs*: +_birthday_service/src/lib.rs_: ```rust,ignore {{#include birthday_service/src/lib.rs:IBirthdayService}} ``` -*birthday_service/Android.bp*: +_birthday_service/Android.bp_: ```javascript {{#include birthday_service/Android.bp:libbirthdayservice}} diff --git a/src/android/aidl/interface.md b/src/android/aidl/interface.md index fd754852bada..f1380049ddca 100644 --- a/src/android/aidl/interface.md +++ b/src/android/aidl/interface.md @@ -2,13 +2,13 @@ You declare the API of your service using an AIDL interface: -*birthday_service/aidl/com/example/birthdayservice/IBirthdayService.aidl*: +_birthday_service/aidl/com/example/birthdayservice/IBirthdayService.aidl_: ```java {{#include birthday_service/aidl/com/example/birthdayservice/IBirthdayService.aidl:IBirthdayService}} ``` -*birthday_service/aidl/Android.bp*: +_birthday_service/aidl/Android.bp_: ```javascript {{#include birthday_service/aidl/Android.bp}} diff --git a/src/android/aidl/server.md b/src/android/aidl/server.md index de9217a0dceb..d3af1807394f 100644 --- a/src/android/aidl/server.md +++ b/src/android/aidl/server.md @@ -2,13 +2,13 @@ Finally, we can create a server which exposes the service: -*birthday_service/src/server.rs*: +_birthday_service/src/server.rs_: ```rust,ignore {{#include birthday_service/src/server.rs:main}} ``` -*birthday_service/Android.bp*: +_birthday_service/Android.bp_: ```javascript {{#include birthday_service/Android.bp:birthday_server}} diff --git a/src/android/build-rules.md b/src/android/build-rules.md index a451e8046ef5..8ac8e79f4242 100644 --- a/src/android/build-rules.md +++ b/src/android/build-rules.md @@ -3,7 +3,7 @@ The Android build system (Soong) supports Rust via a number of modules: | Module Type | Description | -|-------------------|----------------------------------------------------------------------------------------------------| +| ----------------- | -------------------------------------------------------------------------------------------------- | | `rust_binary` | Produces a Rust binary. | | `rust_library` | Produces a Rust library, and provides both `rlib` and `dylib` variants. | | `rust_ffi` | Produces a Rust C library usable by `cc` modules, and provides both static and shared variants. | diff --git a/src/android/build-rules/library.md b/src/android/build-rules/library.md index 880004b03dae..46c3b60e309c 100644 --- a/src/android/build-rules/library.md +++ b/src/android/build-rules/library.md @@ -4,8 +4,8 @@ You use `rust_library` to create a new Rust library for Android. Here we declare a dependency on two libraries: -* `libgreeting`, which we define below, -* `libtextwrap`, which is a crate already vendored in +- `libgreeting`, which we define below, +- `libtextwrap`, which is a crate already vendored in [`external/rust/crates/`][crates]. [crates]: https://cs.android.com/android/platform/superproject/+/master:external/rust/crates/ diff --git a/src/android/interoperability.md b/src/android/interoperability.md index 4f665f2f9996..9436af43c18d 100644 --- a/src/android/interoperability.md +++ b/src/android/interoperability.md @@ -3,8 +3,8 @@ Rust has excellent support for interoperability with other languages. This means that you can: -* Call Rust functions from other languages. -* Call functions written in other languages from Rust. +- Call Rust functions from other languages. +- Call functions written in other languages from Rust. When you call functions in a foreign language we say that you're using a _foreign function interface_, also known as FFI. diff --git a/src/android/interoperability/cpp.md b/src/android/interoperability/cpp.md index 3a523db18877..64b5729507e0 100644 --- a/src/android/interoperability/cpp.md +++ b/src/android/interoperability/cpp.md @@ -15,18 +15,19 @@ See the [CXX tutorial][2] for an full example of using this. - Walk the students through the tutorial step by step. -- Highlight how CXX presents a clean interface without unsafe code in _both languages_. +- Highlight how CXX presents a clean interface without unsafe code in _both + languages_. -- Show the correspondence between [Rust and C++ types](https://cxx.rs/bindings.html): +- Show the correspondence between + [Rust and C++ types](https://cxx.rs/bindings.html): - - Explain how a Rust `String` cannot map to a C++ `std::string` - (the latter does not uphold the UTF-8 invariant). Show that - despite being different types, `rust::String` in C++ can be - easily constructed from a C++ `std::string`, making it very - ergonomic to use. + - Explain how a Rust `String` cannot map to a C++ `std::string` (the latter + does not uphold the UTF-8 invariant). Show that despite being different + types, `rust::String` in C++ can be easily constructed from a C++ + `std::string`, making it very ergonomic to use. - - Explain that a Rust function returning `Result` becomes a - function which throws a `E` exception in C++ (and vice versa). + - Explain that a Rust function returning `Result` becomes a function + which throws a `E` exception in C++ (and vice versa). diff --git a/src/android/interoperability/java.md b/src/android/interoperability/java.md index dde7d7a4d574..0841a65bb220 100644 --- a/src/android/interoperability/java.md +++ b/src/android/interoperability/java.md @@ -1,8 +1,9 @@ # Interoperability with Java -Java can load shared objects via [Java Native Interface -(JNI)](https://en.wikipedia.org/wiki/Java_Native_Interface). The [`jni` -crate](https://docs.rs/jni/) allows you to create a compatible library. +Java can load shared objects via +[Java Native Interface (JNI)](https://en.wikipedia.org/wiki/Java_Native_Interface). +The [`jni` crate](https://docs.rs/jni/) allows you to create a compatible +library. First, we create a Rust function to export to Java: diff --git a/src/android/interoperability/with-c.md b/src/android/interoperability/with-c.md index 152fa695c643..1f1083eac5a1 100644 --- a/src/android/interoperability/with-c.md +++ b/src/android/interoperability/with-c.md @@ -17,8 +17,8 @@ fn main() { } ``` -We already saw this in the [Safe FFI Wrapper -exercise](../../exercises/day-3/safe-ffi-wrapper.md). +We already saw this in the +[Safe FFI Wrapper exercise](../../exercises/day-3/safe-ffi-wrapper.md). > This assumes full knowledge of the target platform. Not recommended for > production. diff --git a/src/android/interoperability/with-c/bindgen/c-library.md b/src/android/interoperability/with-c/bindgen/c-library.md index 01ddb6dba71a..53f16a95ceaa 100644 --- a/src/android/interoperability/with-c/bindgen/c-library.md +++ b/src/android/interoperability/with-c/bindgen/c-library.md @@ -17,4 +17,3 @@ _interoperability/c/libbirthday/libbirthday.c_: ```c {{#include c/libbirthday/libbirthday.c}} ``` - diff --git a/src/android/interoperability/with-c/hand-written.md b/src/android/interoperability/with-c/hand-written.md index abf68e634fcd..56f0f240be2d 100644 --- a/src/android/interoperability/with-c/hand-written.md +++ b/src/android/interoperability/with-c/hand-written.md @@ -14,8 +14,8 @@ fn main() { } ``` -We already saw this in the [Safe FFI Wrapper -exercise](../../exercises/day-3/safe-ffi-wrapper.md). +We already saw this in the +[Safe FFI Wrapper exercise](../../exercises/day-3/safe-ffi-wrapper.md). > This assumes full knowledge of the target platform. Not recommended for > production. diff --git a/src/android/interoperability/with-c/rust.md b/src/android/interoperability/with-c/rust.md index 31dd12f634e2..5a045dfbc1cb 100644 --- a/src/android/interoperability/with-c/rust.md +++ b/src/android/interoperability/with-c/rust.md @@ -34,7 +34,6 @@ _interoperability/rust/analyze/Android.bp_ {{#include rust/analyze/Android.bp}} ``` - Build, push, and run the binary on your device: ```shell @@ -43,7 +42,8 @@ Build, push, and run the binary on your device:
-`#[no_mangle]` disables Rust's usual name mangling, so the exported symbol will just be the name of -the function. You can also use `#[export_name = "some_name"]` to specify whatever name you want. +`#[no_mangle]` disables Rust's usual name mangling, so the exported symbol will +just be the name of the function. You can also use +`#[export_name = "some_name"]` to specify whatever name you want.
diff --git a/src/android/setup.md b/src/android/setup.md index 407e75c585d3..0789d4d77917 100644 --- a/src/android/setup.md +++ b/src/android/setup.md @@ -9,5 +9,6 @@ lunch aosp_cf_x86_64_phone-userdebug acloud create ``` -Please see the [Android Developer -Codelab](https://source.android.com/docs/setup/start) for details. +Please see the +[Android Developer Codelab](https://source.android.com/docs/setup/start) for +details. diff --git a/src/async.md b/src/async.md index 28d39cfd8b51..4aee5cc31d2e 100644 --- a/src/async.md +++ b/src/async.md @@ -8,18 +8,18 @@ very low and operating systems provide primitives for efficiently identifying I/O that is able to proceed. Rust's asynchronous operation is based on "futures", which represent work that -may be completed in the future. Futures are "polled" until they signal that -they are complete. +may be completed in the future. Futures are "polled" until they signal that they +are complete. Futures are polled by an async runtime, and several different runtimes are available. ## Comparisons - * Python has a similar model in its `asyncio`. However, its `Future` type is - callback-based, and not polled. Async Python programs require a "loop", - similar to a runtime in Rust. +- Python has a similar model in its `asyncio`. However, its `Future` type is + callback-based, and not polled. Async Python programs require a "loop", + similar to a runtime in Rust. - * JavaScript's `Promise` is similar, but again callback-based. The language - runtime implements the event loop, so many of the details of Promise - resolution are hidden. +- JavaScript's `Promise` is similar, but again callback-based. The language + runtime implements the event loop, so many of the details of Promise + resolution are hidden. diff --git a/src/async/async-await.md b/src/async/async-await.md index 790603385456..b80d19b42604 100644 --- a/src/async/async-await.md +++ b/src/async/async-await.md @@ -24,25 +24,25 @@ fn main() { Key points: -* Note that this is a simplified example to show the syntax. There is no long +- Note that this is a simplified example to show the syntax. There is no long running operation or any real concurrency in it! -* What is the return type of an async call? - * Use `let future: () = async_main(10);` in `main` to see the type. +- What is the return type of an async call? + - Use `let future: () = async_main(10);` in `main` to see the type. -* The "async" keyword is syntactic sugar. The compiler replaces the return type - with a future. +- The "async" keyword is syntactic sugar. The compiler replaces the return type + with a future. -* You cannot make `main` async, without additional instructions to the compiler +- You cannot make `main` async, without additional instructions to the compiler on how to use the returned future. -* You need an executor to run async code. `block_on` blocks the current thread - until the provided future has run to completion. +- You need an executor to run async code. `block_on` blocks the current thread + until the provided future has run to completion. -* `.await` asynchronously waits for the completion of another operation. Unlike +- `.await` asynchronously waits for the completion of another operation. Unlike `block_on`, `.await` doesn't block the current thread. -* `.await` can only be used inside an `async` function (or block; these are - introduced later). +- `.await` can only be used inside an `async` function (or block; these are + introduced later). diff --git a/src/async/channels.md b/src/async/channels.md index 5a58361875e5..301c0ab2b090 100644 --- a/src/async/channels.md +++ b/src/async/channels.md @@ -32,18 +32,18 @@ async fn main() {
-* Change the channel size to `3` and see how it affects the execution. +- Change the channel size to `3` and see how it affects the execution. -* Overall, the interface is similar to the `sync` channels as seen in the +- Overall, the interface is similar to the `sync` channels as seen in the [morning class](concurrency/channels.md). -* Try removing the `std::mem::drop` call. What happens? Why? +- Try removing the `std::mem::drop` call. What happens? Why? -* The [Flume](https://docs.rs/flume/latest/flume/) crate has channels that +- The [Flume](https://docs.rs/flume/latest/flume/) crate has channels that implement both `sync` and `async` `send` and `recv`. This can be convenient for complex applications with both IO and heavy CPU processing tasks. -* What makes working with `async` channels preferable is the ability to combine +- What makes working with `async` channels preferable is the ability to combine them with other `future`s to combine them and create complex control flow.
diff --git a/src/async/control-flow/join.md b/src/async/control-flow/join.md index 4a93e5c7c145..0d1015e87197 100644 --- a/src/async/control-flow/join.md +++ b/src/async/control-flow/join.md @@ -1,8 +1,8 @@ # Join -A join operation waits until all of a set of futures are ready, and -returns a collection of their results. This is similar to `Promise.all` in -JavaScript or `asyncio.gather` in Python. +A join operation waits until all of a set of futures are ready, and returns a +collection of their results. This is similar to `Promise.all` in JavaScript or +`asyncio.gather` in Python. ```rust,editable,compile_fail use anyhow::Result; @@ -35,16 +35,17 @@ async fn main() { Copy this example into your prepared `src/main.rs` and run it from there. -* For multiple futures of disjoint types, you can use `std::future::join!` but +- For multiple futures of disjoint types, you can use `std::future::join!` but you must know how many futures you will have at compile time. This is currently in the `futures` crate, soon to be stabilised in `std::future`. -* The risk of `join` is that one of the futures may never resolve, this would - cause your program to stall. +- The risk of `join` is that one of the futures may never resolve, this would + cause your program to stall. -* You can also combine `join_all` with `join!` for instance to join all requests +- You can also combine `join_all` with `join!` for instance to join all requests to an http service as well as a database query. Try adding a `tokio::time::sleep` to the future, using `futures::join!`. This is not a - timeout (that requires `select!`, explained in the next chapter), but demonstrates `join!`. + timeout (that requires `select!`, explained in the next chapter), but + demonstrates `join!`. diff --git a/src/async/control-flow/select.md b/src/async/control-flow/select.md index ba42aa2dbb80..00ebbcf451da 100644 --- a/src/async/control-flow/select.md +++ b/src/async/control-flow/select.md @@ -2,8 +2,8 @@ A select operation waits until any of a set of futures is ready, and responds to that future's result. In JavaScript, this is similar to `Promise.race`. In -Python, it compares to `asyncio.wait(task_set, -return_when=asyncio.FIRST_COMPLETED)`. +Python, it compares to +`asyncio.wait(task_set, return_when=asyncio.FIRST_COMPLETED)`. Similar to a match statement, the body of `select!` has a number of arms, each of the form `pattern = future => statement`. When the `future` is ready, the @@ -59,21 +59,21 @@ async fn main() {
-* In this example, we have a race between a cat and a dog. +- In this example, we have a race between a cat and a dog. `first_animal_to_finish_race` listens to both channels and will pick whichever - arrives first. Since the dog takes 50ms, it wins against the cat that - take 500ms seconds. + arrives first. Since the dog takes 50ms, it wins against the cat that take + 500ms seconds. -* You can use `oneshot` channels in this example as the channels are supposed to +- You can use `oneshot` channels in this example as the channels are supposed to receive only one `send`. -* Try adding a deadline to the race, demonstrating selecting different sorts of +- Try adding a deadline to the race, demonstrating selecting different sorts of futures. -* Note that `select!` drops unmatched branches, which cancels their futures. - It is easiest to use when every execution of `select!` creates new futures. +- Note that `select!` drops unmatched branches, which cancels their futures. It + is easiest to use when every execution of `select!` creates new futures. - * An alternative is to pass `&mut future` instead of the future itself, but - this can lead to issues, further discussed in the pinning slide. + - An alternative is to pass `&mut future` instead of the future itself, but + this can lead to issues, further discussed in the pinning slide.
diff --git a/src/async/futures.md b/src/async/futures.md index d9d4347c667e..60b38b78449f 100644 --- a/src/async/futures.md +++ b/src/async/futures.md @@ -1,8 +1,8 @@ # Futures -[`Future`](https://doc.rust-lang.org/std/future/trait.Future.html) -is a trait, implemented by objects that represent an operation that may not be -complete yet. A future can be polled, and `poll` returns a +[`Future`](https://doc.rust-lang.org/std/future/trait.Future.html) is a trait, +implemented by objects that represent an operation that may not be complete yet. +A future can be polled, and `poll` returns a [`Poll`](https://doc.rust-lang.org/std/task/enum.Poll.html). ```rust @@ -29,16 +29,16 @@ pause until that Future is ready, and then evaluates to its output.
-* The `Future` and `Poll` types are implemented exactly as shown; click the +- The `Future` and `Poll` types are implemented exactly as shown; click the links to show the implementations in the docs. -* We will not get to `Pin` and `Context`, as we will focus on writing async +- We will not get to `Pin` and `Context`, as we will focus on writing async code, rather than building new async primitives. Briefly: - * `Context` allows a Future to schedule itself to be polled again when an + - `Context` allows a Future to schedule itself to be polled again when an event occurs. - * `Pin` ensures that the Future isn't moved in memory, so that pointers into + - `Pin` ensures that the Future isn't moved in memory, so that pointers into that future remain valid. This is required to allow references to remain valid after an `.await`. diff --git a/src/async/pitfalls.md b/src/async/pitfalls.md index b025ef5b60c2..924c9c1cc727 100644 --- a/src/async/pitfalls.md +++ b/src/async/pitfalls.md @@ -1,6 +1,8 @@ # Pitfalls of async/await -Async / await provides convenient and efficient abstraction for concurrent asynchronous programming. However, the async/await model in Rust also comes with its share of pitfalls and footguns. We illustrate some of them in this chapter: +Async / await provides convenient and efficient abstraction for concurrent +asynchronous programming. However, the async/await model in Rust also comes with +its share of pitfalls and footguns. We illustrate some of them in this chapter: - [Blocking the Executor](pitfalls/blocking-executor.md) - [Pin](pitfalls/pin.md) diff --git a/src/async/pitfalls/async-traits.md b/src/async/pitfalls/async-traits.md index a4ea8a011cbf..626f485f7a1e 100644 --- a/src/async/pitfalls/async-traits.md +++ b/src/async/pitfalls/async-traits.md @@ -1,8 +1,10 @@ # Async Traits -Async methods in traits are not yet supported in the stable channel ([An experimental feature exists in nightly and should be stabilized in the mid term.](https://blog.rust-lang.org/inside-rust/2022/11/17/async-fn-in-trait-nightly.html)) +Async methods in traits are not yet supported in the stable channel +([An experimental feature exists in nightly and should be stabilized in the mid term.](https://blog.rust-lang.org/inside-rust/2022/11/17/async-fn-in-trait-nightly.html)) -The crate [async_trait](https://docs.rs/async-trait/latest/async_trait/) provides a workaround through a macro: +The crate [async_trait](https://docs.rs/async-trait/latest/async_trait/) +provides a workaround through a macro: ```rust,editable,compile_fail use async_trait::async_trait; @@ -46,18 +48,18 @@ async fn main() { } ``` -
+
-* `async_trait` is easy to use, but note that it's using heap allocations to +- `async_trait` is easy to use, but note that it's using heap allocations to achieve this. This heap allocation has performance overhead. -* The challenges in language support for `async trait` are deep Rust and +- The challenges in language support for `async trait` are deep Rust and probably not worth describing in-depth. Niko Matsakis did a good job of - explaining them in [this - post](https://smallcultfollowing.com/babysteps/blog/2019/10/26/async-fn-in-traits-are-hard/) + explaining them in + [this post](https://smallcultfollowing.com/babysteps/blog/2019/10/26/async-fn-in-traits-are-hard/) if you are interested in digging deeper. -* Try creating a new sleeper struct that will sleep for a random amount of time +- Try creating a new sleeper struct that will sleep for a random amount of time and adding it to the Vec.
diff --git a/src/async/pitfalls/blocking-executor.md b/src/async/pitfalls/blocking-executor.md index cfbfb4675fd4..2ec6d1fb4f50 100644 --- a/src/async/pitfalls/blocking-executor.md +++ b/src/async/pitfalls/blocking-executor.md @@ -1,8 +1,8 @@ # Blocking the executor -Most async runtimes only allow IO tasks to run concurrently. -This means that CPU blocking tasks will block the executor and prevent other tasks from being executed. -An easy workaround is to use async equivalent methods where possible. +Most async runtimes only allow IO tasks to run concurrently. This means that CPU +blocking tasks will block the executor and prevent other tasks from being +executed. An easy workaround is to use async equivalent methods where possible. ```rust,editable,compile_fail use futures::future::join_all; @@ -26,25 +26,25 @@ async fn main() {
-* Run the code and see that the sleeps happen consecutively rather than +- Run the code and see that the sleeps happen consecutively rather than concurrently. -* The `"current_thread"` flavor puts all tasks on a single thread. This makes the - effect more obvious, but the bug is still present in the multi-threaded +- The `"current_thread"` flavor puts all tasks on a single thread. This makes + the effect more obvious, but the bug is still present in the multi-threaded flavor. -* Switch the `std::thread::sleep` to `tokio::time::sleep` and await its result. +- Switch the `std::thread::sleep` to `tokio::time::sleep` and await its result. -* Another fix would be to `tokio::task::spawn_blocking` which spawns an actual +- Another fix would be to `tokio::task::spawn_blocking` which spawns an actual thread and transforms its handle into a future without blocking the executor. -* You should not think of tasks as OS threads. They do not map 1 to 1 and most +- You should not think of tasks as OS threads. They do not map 1 to 1 and most executors will allow many tasks to run on a single OS thread. This is particularly problematic when interacting with other libraries via FFI, where that library might depend on thread-local storage or map to specific OS threads (e.g., CUDA). Prefer `tokio::task::spawn_blocking` in such situations. -* Use sync mutexes with care. Holding a mutex over an `.await` may cause another +- Use sync mutexes with care. Holding a mutex over an `.await` may cause another task to block, and that task may be running on the same thread.
diff --git a/src/async/pitfalls/cancellation.md b/src/async/pitfalls/cancellation.md index 8969b7f4bd54..d9cf52a960f2 100644 --- a/src/async/pitfalls/cancellation.md +++ b/src/async/pitfalls/cancellation.md @@ -1,9 +1,9 @@ # Cancellation -Dropping a future implies it can never be polled again. This is called *cancellation* -and it can occur at any `await` point. Care is needed to ensure the system works -correctly even when futures are cancelled. For example, it shouldn't deadlock or -lose data. +Dropping a future implies it can never be polled again. This is called +_cancellation_ and it can occur at any `await` point. Care is needed to ensure +the system works correctly even when futures are cancelled. For example, it +shouldn't deadlock or lose data. ```rust,editable,compile_fail use std::io::{self, ErrorKind}; @@ -69,46 +69,49 @@ async fn main() -> std::io::Result<()> {
-* The compiler doesn't help with cancellation-safety. You need to read API +- The compiler doesn't help with cancellation-safety. You need to read API documentation and consider what state your `async fn` holds. -* Unlike `panic` and `?`, cancellation is part of normal control flow - (vs error-handling). +- Unlike `panic` and `?`, cancellation is part of normal control flow (vs + error-handling). -* The example loses parts of the string. +- The example loses parts of the string. - * Whenever the `tick()` branch finishes first, `next()` and its `buf` are dropped. + - Whenever the `tick()` branch finishes first, `next()` and its `buf` are + dropped. - * `LinesReader` can be made cancellation-safe by makeing `buf` part of the struct: - ```rust,compile_fail - struct LinesReader { - stream: DuplexStream, - bytes: Vec, - buf: [u8; 1], - } + - `LinesReader` can be made cancellation-safe by makeing `buf` part of the + struct: + ```rust,compile_fail + struct LinesReader { + stream: DuplexStream, + bytes: Vec, + buf: [u8; 1], + } - impl LinesReader { - fn new(stream: DuplexStream) -> Self { - Self { stream, bytes: Vec::new(), buf: [0] } - } - async fn next(&mut self) -> io::Result> { - // prefix buf and bytes with self. - // ... - let raw = std::mem::take(&mut self.bytes); - let s = String::from_utf8(raw) - // ... - } + impl LinesReader { + fn new(stream: DuplexStream) -> Self { + Self { stream, bytes: Vec::new(), buf: [0] } + } + async fn next(&mut self) -> io::Result> { + // prefix buf and bytes with self. + // ... + let raw = std::mem::take(&mut self.bytes); + let s = String::from_utf8(raw) + // ... } - ``` + } + ``` -* [`Interval::tick`](https://docs.rs/tokio/latest/tokio/time/struct.Interval.html#method.tick) - is cancellation-safe because it keeps track of whether a tick has been 'delivered'. +- [`Interval::tick`](https://docs.rs/tokio/latest/tokio/time/struct.Interval.html#method.tick) + is cancellation-safe because it keeps track of whether a tick has been + 'delivered'. -* [`AsyncReadExt::read`](https://docs.rs/tokio/latest/tokio/io/trait.AsyncReadExt.html#method.read) +- [`AsyncReadExt::read`](https://docs.rs/tokio/latest/tokio/io/trait.AsyncReadExt.html#method.read) is cancellation-safe because it either returns or doesn't read data. -* [`AsyncBufReadExt::read_line`](https://docs.rs/tokio/latest/tokio/io/trait.AsyncBufReadExt.html#method.read_line) - is similar to the example and *isn't* cancellation-safe. See its documentation +- [`AsyncBufReadExt::read_line`](https://docs.rs/tokio/latest/tokio/io/trait.AsyncBufReadExt.html#method.read_line) + is similar to the example and _isn't_ cancellation-safe. See its documentation for details and alternatives.
diff --git a/src/async/pitfalls/pin.md b/src/async/pitfalls/pin.md index a6b92112d171..bf002df070a9 100644 --- a/src/async/pitfalls/pin.md +++ b/src/async/pitfalls/pin.md @@ -1,9 +1,9 @@ # Pin When you await a future, all local variables (that would ordinarily be stored on -a stack frame) are instead stored in the Future for the current async block. If your -future has pointers to data on the stack, those pointers might get invalidated. -This is unsafe. +a stack frame) are instead stored in the Future for the current async block. If +your future has pointers to data on the stack, those pointers might get +invalidated. This is unsafe. Therefore, you must guarantee that the addresses your future points to don't change. That is why we need to `pin` futures. Using the same future repeatedly @@ -65,48 +65,49 @@ async fn main() {
-* You may recognize this as an example of the actor pattern. Actors - typically call `select!` in a loop. +- You may recognize this as an example of the actor pattern. Actors typically + call `select!` in a loop. -* This serves as a summation of a few of the previous lessons, so take your time +- This serves as a summation of a few of the previous lessons, so take your time with it. - * Naively add a `_ = sleep(Duration::from_millis(100)) => { println!(..) }` - to the `select!`. This will never execute. Why? + - Naively add a `_ = sleep(Duration::from_millis(100)) => { println!(..) }` to + the `select!`. This will never execute. Why? - * Instead, add a `timeout_fut` containing that future outside of the `loop`: + - Instead, add a `timeout_fut` containing that future outside of the `loop`: - ```rust,compile_fail - let mut timeout_fut = sleep(Duration::from_millis(100)); - loop { - select! { - .., - _ = timeout_fut => { println!(..); }, - } + ```rust,compile_fail + let mut timeout_fut = sleep(Duration::from_millis(100)); + loop { + select! { + .., + _ = timeout_fut => { println!(..); }, } - ``` - * This still doesn't work. Follow the compiler errors, adding `&mut` to the - `timeout_fut` in the `select!` to work around the move, then using - `Box::pin`: - - ```rust,compile_fail - let mut timeout_fut = Box::pin(sleep(Duration::from_millis(100))); - loop { - select! { - .., - _ = &mut timeout_fut => { println!(..); }, - } + } + ``` + - This still doesn't work. Follow the compiler errors, adding `&mut` to the + `timeout_fut` in the `select!` to work around the move, then using + `Box::pin`: + + ```rust,compile_fail + let mut timeout_fut = Box::pin(sleep(Duration::from_millis(100))); + loop { + select! { + .., + _ = &mut timeout_fut => { println!(..); }, } - ``` + } + ``` - * This compiles, but once the timeout expires it is `Poll::Ready` on every - iteration (a fused future would help with this). Update to reset - `timeout_fut` every time it expires. + - This compiles, but once the timeout expires it is `Poll::Ready` on every + iteration (a fused future would help with this). Update to reset + `timeout_fut` every time it expires. -* Box allocates on the heap. In some cases, `std::pin::pin!` (only recently +- Box allocates on the heap. In some cases, `std::pin::pin!` (only recently stabilized, with older code often using `tokio::pin!`) is also an option, but that is difficult to use for a future that is reassigned. -* Another alternative is to not use `pin` at all but spawn another task that will send to a `oneshot` channel every 100ms. +- Another alternative is to not use `pin` at all but spawn another task that + will send to a `oneshot` channel every 100ms.
diff --git a/src/async/runtimes.md b/src/async/runtimes.md index 9d2888aa5425..6b03541b796d 100644 --- a/src/async/runtimes.md +++ b/src/async/runtimes.md @@ -1,15 +1,15 @@ # Runtimes -A *runtime* provides support for performing operations asynchronously (a -*reactor*) and is responsible for executing futures (an *executor*). Rust does not have a -"built-in" runtime, but several options are available: +A _runtime_ provides support for performing operations asynchronously (a +_reactor_) and is responsible for executing futures (an _executor_). Rust does +not have a "built-in" runtime, but several options are available: - * [Tokio](https://tokio.rs/): performant, with a well-developed ecosystem of - functionality like [Hyper](https://hyper.rs/) for HTTP or - [Tonic](https://github.com/hyperium/tonic) for gRPC. - * [async-std](https://async.rs/): aims to be a "std for async", and includes a - basic runtime in `async::task`. - * [smol](https://docs.rs/smol/latest/smol/): simple and lightweight +- [Tokio](https://tokio.rs/): performant, with a well-developed ecosystem of + functionality like [Hyper](https://hyper.rs/) for HTTP or + [Tonic](https://github.com/hyperium/tonic) for gRPC. +- [async-std](https://async.rs/): aims to be a "std for async", and includes a + basic runtime in `async::task`. +- [smol](https://docs.rs/smol/latest/smol/): simple and lightweight Several larger applications have their own runtimes. For example, [Fuchsia](https://fuchsia.googlesource.com/fuchsia/+/refs/heads/main/src/lib/fuchsia-async/src/lib.rs) @@ -17,11 +17,11 @@ already has one.
-* Note that of the listed runtimes, only Tokio is supported in the Rust +- Note that of the listed runtimes, only Tokio is supported in the Rust playground. The playground also does not permit any I/O, so most interesting async things can't run in the playground. -* Futures are "inert" in that they do not do anything (not even start an I/O +- Futures are "inert" in that they do not do anything (not even start an I/O operation) unless there is an executor polling them. This differs from JS Promises, for example, which will run to completion even if they are never used. diff --git a/src/async/runtimes/tokio.md b/src/async/runtimes/tokio.md index c9dfbd485e2b..73a7bc179239 100644 --- a/src/async/runtimes/tokio.md +++ b/src/async/runtimes/tokio.md @@ -1,11 +1,10 @@ # Tokio +Tokio provides: -Tokio provides: - -* A multi-threaded runtime for executing asynchronous code. -* An asynchronous version of the standard library. -* A large ecosystem of libraries. +- A multi-threaded runtime for executing asynchronous code. +- An asynchronous version of the standard library. +- A large ecosystem of libraries. ```rust,editable,compile_fail use tokio::time; @@ -30,20 +29,20 @@ async fn main() {
-* With the `tokio::main` macro we can now make `main` async. +- With the `tokio::main` macro we can now make `main` async. -* The `spawn` function creates a new, concurrent "task". +- The `spawn` function creates a new, concurrent "task". -* Note: `spawn` takes a `Future`, you don't call `.await` on `count_to`. +- Note: `spawn` takes a `Future`, you don't call `.await` on `count_to`. **Further exploration:** -* Why does `count_to` not (usually) get to 10? This is an example of async +- Why does `count_to` not (usually) get to 10? This is an example of async cancellation. `tokio::spawn` returns a handle which can be awaited to wait until it finishes. -* Try `count_to(10).await` instead of spawning. +- Try `count_to(10).await` instead of spawning. -* Try awaiting the task returned from `tokio::spawn`. +- Try awaiting the task returned from `tokio::spawn`.
diff --git a/src/async/tasks.md b/src/async/tasks.md index 942d7c1ad894..ecace38ec5b4 100644 --- a/src/async/tasks.md +++ b/src/async/tasks.md @@ -51,13 +51,14 @@ async fn main() -> io::Result<()> { Copy this example into your prepared `src/main.rs` and run it from there. -* Ask students to visualize what the state of the example server would be with a +- Ask students to visualize what the state of the example server would be with a few connected clients. What tasks exist? What are their Futures? -* This is the first time we've seen an `async` block. This is similar to a +- This is the first time we've seen an `async` block. This is similar to a closure, but does not take any arguments. Its return value is a Future, - similar to an `async fn`. + similar to an `async fn`. -* Refactor the async block into a function, and improve the error handling using `?`. +- Refactor the async block into a function, and improve the error handling using + `?`.
diff --git a/src/bare-metal.md b/src/bare-metal.md index 2900efb76f9a..a84987461449 100644 --- a/src/bare-metal.md +++ b/src/bare-metal.md @@ -1,21 +1,23 @@ # Welcome to Bare Metal Rust -This is a standalone one-day course about bare-metal Rust, aimed at people who are familiar with the -basics of Rust (perhaps from completing the Comprehensive Rust course), and ideally also have some -experience with bare-metal programming in some other language such as C. +This is a standalone one-day course about bare-metal Rust, aimed at people who +are familiar with the basics of Rust (perhaps from completing the Comprehensive +Rust course), and ideally also have some experience with bare-metal programming +in some other language such as C. -Today we will talk about 'bare-metal' Rust: running Rust code without an OS underneath us. This will -be divided into several parts: +Today we will talk about 'bare-metal' Rust: running Rust code without an OS +underneath us. This will be divided into several parts: - What is `no_std` Rust? - Writing firmware for microcontrollers. - Writing bootloader / kernel code for application processors. - Some useful crates for bare-metal Rust development. -For the microcontroller part of the course we will use the [BBC micro:bit](https://microbit.org/) v2 -as an example. It's a [development board](https://tech.microbit.org/hardware/) based on the Nordic -nRF51822 microcontroller with some LEDs and buttons, an I2C-connected accelerometer and compass, and -an on-board SWD debugger. +For the microcontroller part of the course we will use the +[BBC micro:bit](https://microbit.org/) v2 as an example. It's a +[development board](https://tech.microbit.org/hardware/) based on the Nordic +nRF51822 microcontroller with some LEDs and buttons, an I2C-connected +accelerometer and compass, and an on-board SWD debugger. To get started, install some tools we'll need later. On gLinux or Debian: diff --git a/src/bare-metal/alloc.md b/src/bare-metal/alloc.md index e600b79994cb..91dac1a53ea4 100644 --- a/src/bare-metal/alloc.md +++ b/src/bare-metal/alloc.md @@ -9,14 +9,16 @@ To use `alloc` you must implement a
-* `buddy_system_allocator` is a third-party crate implementing a basic buddy system allocator. Other - crates are available, or you can write your own or hook into your existing allocator. -* The const parameter of `LockedHeap` is the max order of the allocator; i.e. in this case it can - allocate regions of up to 2**32 bytes. -* If any crate in your dependency tree depends on `alloc` then you must have exactly one global - allocator defined in your binary. Usually this is done in the top-level binary crate. -* `extern crate panic_halt as _` is necessary to ensure that the `panic_halt` crate is linked in so - we get its panic handler. -* This example will build but not run, as it doesn't have an entry point. +- `buddy_system_allocator` is a third-party crate implementing a basic buddy + system allocator. Other crates are available, or you can write your own or + hook into your existing allocator. +- The const parameter of `LockedHeap` is the max order of the allocator; i.e. in + this case it can allocate regions of up to 2**32 bytes. +- If any crate in your dependency tree depends on `alloc` then you must have + exactly one global allocator defined in your binary. Usually this is done in + the top-level binary crate. +- `extern crate panic_halt as _` is necessary to ensure that the `panic_halt` + crate is linked in so we get its panic handler. +- This example will build but not run, as it doesn't have an entry point.
diff --git a/src/bare-metal/android.md b/src/bare-metal/android.md index c5fb523becba..f36d613528d0 100644 --- a/src/bare-metal/android.md +++ b/src/bare-metal/android.md @@ -1,8 +1,9 @@ # Android -To build a bare-metal Rust binary in AOSP, you need to use a `rust_ffi_static` Soong rule to build -your Rust code, then a `cc_binary` with a linker script to produce the binary itself, and then a -`raw_binary` to convert the ELF to a raw binary ready to be run. +To build a bare-metal Rust binary in AOSP, you need to use a `rust_ffi_static` +Soong rule to build your Rust code, then a `cc_binary` with a linker script to +produce the binary itself, and then a `raw_binary` to convert the ELF to a raw +binary ready to be run. ```soong rust_ffi_static { diff --git a/src/bare-metal/android/vmbase.md b/src/bare-metal/android/vmbase.md index 2e70dc231fd3..1114a0010aa8 100644 --- a/src/bare-metal/android/vmbase.md +++ b/src/bare-metal/android/vmbase.md @@ -1,7 +1,8 @@ # vmbase -For VMs running under crosvm on aarch64, the [vmbase][1] library provides a linker script and useful -defaults for the build rules, along with an entry point, UART console logging and more. +For VMs running under crosvm on aarch64, the [vmbase][1] library provides a +linker script and useful defaults for the build rules, along with an entry +point, UART console logging and more. ```rust,compile_fail #![no_main] @@ -18,9 +19,10 @@ pub fn main(arg0: u64, arg1: u64, arg2: u64, arg3: u64) {
-* The `main!` macro marks your main function, to be called from the `vmbase` entry point. -* The `vmbase` entry point handles console initialisation, and issues a PSCI_SYSTEM_OFF to shutdown - the VM if your main function returns. +- The `main!` macro marks your main function, to be called from the `vmbase` + entry point. +- The `vmbase` entry point handles console initialisation, and issues a + PSCI_SYSTEM_OFF to shutdown the VM if your main function returns.
diff --git a/src/bare-metal/aps.md b/src/bare-metal/aps.md index 8e937fbe3818..73c94e41ca12 100644 --- a/src/bare-metal/aps.md +++ b/src/bare-metal/aps.md @@ -1,15 +1,17 @@ # Application processors -So far we've talked about microcontrollers, such as the Arm Cortex-M series. Now let's try writing -something for Cortex-A. For simplicity we'll just work with QEMU's aarch64 +So far we've talked about microcontrollers, such as the Arm Cortex-M series. Now +let's try writing something for Cortex-A. For simplicity we'll just work with +QEMU's aarch64 ['virt'](https://qemu-project.gitlab.io/qemu/system/arm/virt.html) board.
-* Broadly speaking, microcontrollers don't have an MMU or multiple levels of privilege (exception - levels on Arm CPUs, rings on x86), while application processors do. -* QEMU supports emulating various different machines or board models for each architecture. The - 'virt' board doesn't correspond to any particular real hardware, but is designed purely for - virtual machines. +- Broadly speaking, microcontrollers don't have an MMU or multiple levels of + privilege (exception levels on Arm CPUs, rings on x86), while application + processors do. +- QEMU supports emulating various different machines or board models for each + architecture. The 'virt' board doesn't correspond to any particular real + hardware, but is designed purely for virtual machines.
diff --git a/src/bare-metal/aps/better-uart.md b/src/bare-metal/aps/better-uart.md index 99ceb51df77e..f87fca7c4020 100644 --- a/src/bare-metal/aps/better-uart.md +++ b/src/bare-metal/aps/better-uart.md @@ -1,8 +1,8 @@ # A better UART driver -The PL011 actually has [a bunch more registers][1], and adding offsets to construct pointers to access -them is error-prone and hard to read. Plus, some of them are bit fields which would be nice to -access in a structured way. +The PL011 actually has [a bunch more registers][1], and adding offsets to +construct pointers to access them is error-prone and hard to read. Plus, some of +them are bit fields which would be nice to access in a structured way. | Offset | Register name | Width | | ------ | ------------- | ----- | diff --git a/src/bare-metal/aps/better-uart/bitflags.md b/src/bare-metal/aps/better-uart/bitflags.md index 0ee6c0c5a9b1..891cd2e0592e 100644 --- a/src/bare-metal/aps/better-uart/bitflags.md +++ b/src/bare-metal/aps/better-uart/bitflags.md @@ -1,6 +1,7 @@ # Bitflags -The [`bitflags`](https://crates.io/crates/bitflags) crate is useful for working with bitflags. +The [`bitflags`](https://crates.io/crates/bitflags) crate is useful for working +with bitflags. ```rust,editable,compile_fail {{#include ../examples/src/pl011.rs:Flags}} @@ -8,7 +9,7 @@ The [`bitflags`](https://crates.io/crates/bitflags) crate is useful for working
-* The `bitflags!` macro creates a newtype something like `Flags(u16)`, along with a bunch of method - implementations to get and set flags. +- The `bitflags!` macro creates a newtype something like `Flags(u16)`, along + with a bunch of method implementations to get and set flags.
diff --git a/src/bare-metal/aps/better-uart/driver.md b/src/bare-metal/aps/better-uart/driver.md index 28bad722076d..64c432edf203 100644 --- a/src/bare-metal/aps/better-uart/driver.md +++ b/src/bare-metal/aps/better-uart/driver.md @@ -8,7 +8,7 @@ Now let's use the new `Registers` struct in our driver.
-* Note the use of `addr_of!` / `addr_of_mut!` to get pointers to individual fields without creating - an intermediate reference, which would be unsound. +- Note the use of `addr_of!` / `addr_of_mut!` to get pointers to individual + fields without creating an intermediate reference, which would be unsound.
diff --git a/src/bare-metal/aps/better-uart/registers.md b/src/bare-metal/aps/better-uart/registers.md index e4d336781d7f..c2d26fa8d742 100644 --- a/src/bare-metal/aps/better-uart/registers.md +++ b/src/bare-metal/aps/better-uart/registers.md @@ -8,9 +8,10 @@ We can use a struct to represent the memory layout of the UART's registers.
-* [`#[repr(C)]`](https://doc.rust-lang.org/reference/type-layout.html#the-c-representation) tells - the compiler to lay the struct fields out in order, following the same rules as C. This is - necessary for our struct to have a predictable layout, as default Rust representation allows the - compiler to (among other things) reorder fields however it sees fit. +- [`#[repr(C)]`](https://doc.rust-lang.org/reference/type-layout.html#the-c-representation) + tells the compiler to lay the struct fields out in order, following the same + rules as C. This is necessary for our struct to have a predictable layout, as + default Rust representation allows the compiler to (among other things) + reorder fields however it sees fit.
diff --git a/src/bare-metal/aps/better-uart/using.md b/src/bare-metal/aps/better-uart/using.md index 5089224c3d8b..159c8e3db479 100644 --- a/src/bare-metal/aps/better-uart/using.md +++ b/src/bare-metal/aps/better-uart/using.md @@ -1,7 +1,7 @@ # Using it -Let's write a small program using our driver to write to the serial console, and echo incoming -bytes. +Let's write a small program using our driver to write to the serial console, and +echo incoming bytes. ```rust,editable,compile_fail {{#include ../examples/src/main_improved.rs:main}} @@ -9,8 +9,9 @@ bytes.
-* As in the [inline assembly](../inline-assembly.md) example, this `main` function is called from our - entry point code in `entry.S`. See the speaker notes there for details. -* Run the example in QEMU with `make qemu` under `src/bare-metal/aps/examples`. +- As in the [inline assembly](../inline-assembly.md) example, this `main` + function is called from our entry point code in `entry.S`. See the speaker + notes there for details. +- Run the example in QEMU with `make qemu` under `src/bare-metal/aps/examples`.
diff --git a/src/bare-metal/aps/entry-point.md b/src/bare-metal/aps/entry-point.md index 91dbaa431cc0..671a3a0eb79b 100644 --- a/src/bare-metal/aps/entry-point.md +++ b/src/bare-metal/aps/entry-point.md @@ -8,28 +8,36 @@ Before we can start running Rust code, we need to do some initialisation.
-* This is the same as it would be for C: initialising the processor state, zeroing the BSS, and - setting up the stack pointer. - * The BSS (block starting symbol, for historical reasons) is the part of the object file which - containing statically allocated variables which are initialised to zero. They are omitted from - the image, to avoid wasting space on zeroes. The compiler assumes that the loader will take care - of zeroing them. -* The BSS may already be zeroed, depending on how memory is initialised and the image is loaded, but - we zero it to be sure. -* We need to enable the MMU and cache before reading or writing any memory. If we don't: - * Unaligned accesses will fault. We build the Rust code for the `aarch64-unknown-none` target - which sets `+strict-align` to prevent the compiler generating unaligned accesses, so it should - be fine in this case, but this is not necessarily the case in general. - * If it were running in a VM, this can lead to cache coherency issues. The problem is that the VM - is accessing memory directly with the cache disabled, while the host has cachable aliases to the - same memory. Even if the host doesn't explicitly access the memory, speculative accesses can - lead to cache fills, and then changes from one or the other will get lost when the cache is - cleaned or the VM enables the cache. (Cache is keyed by physical address, not VA or IPA.) -* For simplicity, we just use a hardcoded pagetable (see `idmap.S`) which identity maps the first 1 - GiB of address space for devices, the next 1 GiB for DRAM, and another 1 GiB higher up for more - devices. This matches the memory layout that QEMU uses. -* We also set up the exception vector (`vbar_el1`), which we'll see more about later. -* All examples this afternoon assume we will be running at exception level 1 (EL1). If you need to - run at a different exception level you'll need to modify `entry.S` accordingly. +- This is the same as it would be for C: initialising the processor state, + zeroing the BSS, and setting up the stack pointer. + - The BSS (block starting symbol, for historical reasons) is the part of the + object file which containing statically allocated variables which are + initialised to zero. They are omitted from the image, to avoid wasting space + on zeroes. The compiler assumes that the loader will take care of zeroing + them. +- The BSS may already be zeroed, depending on how memory is initialised and the + image is loaded, but we zero it to be sure. +- We need to enable the MMU and cache before reading or writing any memory. If + we don't: + - Unaligned accesses will fault. We build the Rust code for the + `aarch64-unknown-none` target which sets `+strict-align` to prevent the + compiler generating unaligned accesses, so it should be fine in this case, + but this is not necessarily the case in general. + - If it were running in a VM, this can lead to cache coherency issues. The + problem is that the VM is accessing memory directly with the cache disabled, + while the host has cachable aliases to the same memory. Even if the host + doesn't explicitly access the memory, speculative accesses can lead to cache + fills, and then changes from one or the other will get lost when the cache + is cleaned or the VM enables the cache. (Cache is keyed by physical address, + not VA or IPA.) +- For simplicity, we just use a hardcoded pagetable (see `idmap.S`) which + identity maps the first 1 GiB of address space for devices, the next 1 GiB for + DRAM, and another 1 GiB higher up for more devices. This matches the memory + layout that QEMU uses. +- We also set up the exception vector (`vbar_el1`), which we'll see more about + later. +- All examples this afternoon assume we will be running at exception level 1 + (EL1). If you need to run at a different exception level you'll need to modify + `entry.S` accordingly.
diff --git a/src/bare-metal/aps/exceptions.md b/src/bare-metal/aps/exceptions.md index cfe06b90e16c..ea0dd0895235 100644 --- a/src/bare-metal/aps/exceptions.md +++ b/src/bare-metal/aps/exceptions.md @@ -1,9 +1,10 @@ # Exceptions -AArch64 defines an exception vector table with 16 entries, for 4 types of exceptions (synchronous, -IRQ, FIQ, SError) from 4 states (current EL with SP0, current EL with SPx, lower EL using AArch64, -lower EL using AArch32). We implement this in assembly to save volatile registers to the stack -before calling into Rust code: +AArch64 defines an exception vector table with 16 entries, for 4 types of +exceptions (synchronous, IRQ, FIQ, SError) from 4 states (current EL with SP0, +current EL with SPx, lower EL using AArch64, lower EL using AArch32). We +implement this in assembly to save volatile registers to the stack before +calling into Rust code: ```rust,editable,compile_fail {{#include examples/src/exceptions.rs:exceptions}} @@ -11,16 +12,17 @@ before calling into Rust code:
-* EL is exception level; all our examples this afternoon run in EL1. -* For simplicity we aren't distinguishing between SP0 and SPx for the current EL exceptions, or - between AArch32 and AArch64 for the lower EL exceptions. -* For this example we just log the exception and power down, as we don't expect any of them to - actually happen. -* We can think of exception handlers and our main execution context more or less like different - threads. [`Send` and `Sync`][1] will control what we can share between them, just like with threads. - For example, if we want to share some value between exception handlers and the rest of the - program, and it's `Send` but not `Sync`, then we'll need to wrap it in something like a `Mutex` - and put it in a static. +- EL is exception level; all our examples this afternoon run in EL1. +- For simplicity we aren't distinguishing between SP0 and SPx for the current EL + exceptions, or between AArch32 and AArch64 for the lower EL exceptions. +- For this example we just log the exception and power down, as we don't expect + any of them to actually happen. +- We can think of exception handlers and our main execution context more or less + like different threads. [`Send` and `Sync`][1] will control what we can share + between them, just like with threads. For example, if we want to share some + value between exception handlers and the rest of the program, and it's `Send` + but not `Sync`, then we'll need to wrap it in something like a `Mutex` and put + it in a static.
diff --git a/src/bare-metal/aps/inline-assembly.md b/src/bare-metal/aps/inline-assembly.md index f17bccaf7a01..6b65bff65dd4 100644 --- a/src/bare-metal/aps/inline-assembly.md +++ b/src/bare-metal/aps/inline-assembly.md @@ -1,30 +1,35 @@ # Inline assembly -Sometimes we need to use assembly to do things that aren't possible with Rust code. For example, -to make an HVC to tell the firmware to power off the system: +Sometimes we need to use assembly to do things that aren't possible with Rust +code. For example, to make an HVC to tell +the firmware to power off the system: ```rust,editable,compile_fail {{#include examples/src/main_psci.rs:main}} ``` -(If you actually want to do this, use the [`smccc`][1] crate which has wrappers for all these functions.) +(If you actually want to do this, use the [`smccc`][1] crate which has wrappers +for all these functions.)
-* PSCI is the Arm Power State Coordination Interface, a standard set of functions to manage system - and CPU power states, among other things. It is implemented by EL3 firmware and hypervisors on - many systems. -* The `0 => _` syntax means initialise the register to 0 before running the inline assembly code, - and ignore its contents afterwards. We need to use `inout` rather than `in` because the call could - potentially clobber the contents of the registers. -* This `main` function needs to be `#[no_mangle]` and `extern "C"` because it is called from our - entry point in `entry.S`. -* `_x0`–`_x3` are the values of registers `x0`–`x3`, which are conventionally used by the bootloader - to pass things like a pointer to the device tree. According to the standard aarch64 calling - convention (which is what `extern "C"` specifies to use), registers `x0`–`x7` are used for the - first 8 arguments passed to a function, so `entry.S` doesn't need to do anything special except - make sure it doesn't change these registers. -* Run the example in QEMU with `make qemu_psci` under `src/bare-metal/aps/examples`. +- PSCI is the Arm Power State Coordination Interface, a standard set of + functions to manage system and CPU power states, among other things. It is + implemented by EL3 firmware and hypervisors on many systems. +- The `0 => _` syntax means initialise the register to 0 before running the + inline assembly code, and ignore its contents afterwards. We need to use + `inout` rather than `in` because the call could potentially clobber the + contents of the registers. +- This `main` function needs to be `#[no_mangle]` and `extern "C"` because it is + called from our entry point in `entry.S`. +- `_x0`–`_x3` are the values of registers `x0`–`x3`, which are conventionally + used by the bootloader to pass things like a pointer to the device tree. + According to the standard aarch64 calling convention (which is what + `extern "C"` specifies to use), registers `x0`–`x7` are used for the first 8 + arguments passed to a function, so `entry.S` doesn't need to do anything + special except make sure it doesn't change these registers. +- Run the example in QEMU with `make qemu_psci` under + `src/bare-metal/aps/examples`.
diff --git a/src/bare-metal/aps/logging.md b/src/bare-metal/aps/logging.md index 8a72bab597e2..0d11f62212c0 100644 --- a/src/bare-metal/aps/logging.md +++ b/src/bare-metal/aps/logging.md @@ -1,7 +1,7 @@ # Logging -It would be nice to be able to use the logging macros from the [`log`][1] crate. We can do this by -implementing the `Log` trait. +It would be nice to be able to use the logging macros from the [`log`][1] crate. +We can do this by implementing the `Log` trait. ```rust,editable,compile_fail {{#include examples/src/logger.rs:main}} @@ -9,7 +9,8 @@ implementing the `Log` trait.
-* The unwrap in `log` is safe because we initialise `LOGGER` before calling `set_logger`. +- The unwrap in `log` is safe because we initialise `LOGGER` before calling + `set_logger`.
diff --git a/src/bare-metal/aps/logging/using.md b/src/bare-metal/aps/logging/using.md index a2e150057a54..0d559a2036d8 100644 --- a/src/bare-metal/aps/logging/using.md +++ b/src/bare-metal/aps/logging/using.md @@ -8,7 +8,8 @@ We need to initialise the logger before we use it.
-* Note that our panic handler can now log details of panics. -* Run the example in QEMU with `make qemu_logger` under `src/bare-metal/aps/examples`. +- Note that our panic handler can now log details of panics. +- Run the example in QEMU with `make qemu_logger` under + `src/bare-metal/aps/examples`.
diff --git a/src/bare-metal/aps/mmio.md b/src/bare-metal/aps/mmio.md index 4c63731d0db2..47b81df4d7df 100644 --- a/src/bare-metal/aps/mmio.md +++ b/src/bare-metal/aps/mmio.md @@ -1,17 +1,21 @@ # Volatile memory access for MMIO - * Use `pointer::read_volatile` and `pointer::write_volatile`. - * Never hold a reference. - * `addr_of!` lets you get fields of structs without creating an intermediate reference. +- Use `pointer::read_volatile` and `pointer::write_volatile`. +- Never hold a reference. +- `addr_of!` lets you get fields of structs without creating an intermediate + reference.
- * Volatile access: read or write operations may have side-effects, so prevent the compiler or - hardware from reordering, duplicating or eliding them. - * Usually if you write and then read, e.g. via a mutable reference, the compiler may assume that - the value read is the same as the value just written, and not bother actually reading memory. - * Some existing crates for volatile access to hardware do hold references, but this is unsound. - Whenever a reference exist, the compiler may choose to dereference it. - * Use the `addr_of!` macro to get struct field pointers from a pointer to the struct. +- Volatile access: read or write operations may have side-effects, so prevent + the compiler or hardware from reordering, duplicating or eliding them. + - Usually if you write and then read, e.g. via a mutable reference, the + compiler may assume that the value read is the same as the value just + written, and not bother actually reading memory. +- Some existing crates for volatile access to hardware do hold references, but + this is unsound. Whenever a reference exist, the compiler may choose to + dereference it. +- Use the `addr_of!` macro to get struct field pointers from a pointer to the + struct.
diff --git a/src/bare-metal/aps/other-projects.md b/src/bare-metal/aps/other-projects.md index ed0af1b485b4..799dcf8366b8 100644 --- a/src/bare-metal/aps/other-projects.md +++ b/src/bare-metal/aps/other-projects.md @@ -1,29 +1,31 @@ # Other projects - * [oreboot](https://github.com/oreboot/oreboot) - * "coreboot without the C" - * Supports x86, aarch64 and RISC-V. - * Relies on LinuxBoot rather than having many drivers itself. - * [Rust RaspberryPi OS tutorial](https://github.com/rust-embedded/rust-raspberrypi-OS-tutorials) - * Initialisation, UART driver, simple bootloader, JTAG, exception levels, exception handling, - page tables - * Some dodginess around cache maintenance and initialisation in Rust, not necessarily a good - example to copy for production code. - * [`cargo-call-stack`](https://crates.io/crates/cargo-call-stack) - * Static analysis to determine maximum stack usage. +- [oreboot](https://github.com/oreboot/oreboot) + - "coreboot without the C" + - Supports x86, aarch64 and RISC-V. + - Relies on LinuxBoot rather than having many drivers itself. +- [Rust RaspberryPi OS tutorial](https://github.com/rust-embedded/rust-raspberrypi-OS-tutorials) + - Initialisation, UART driver, simple bootloader, JTAG, exception levels, + exception handling, page tables + - Some dodginess around cache maintenance and initialisation in Rust, not + necessarily a good example to copy for production code. +- [`cargo-call-stack`](https://crates.io/crates/cargo-call-stack) + - Static analysis to determine maximum stack usage.
-* The RaspberryPi OS tutorial runs Rust code before the MMU and caches are enabled. This will read - and write memory (e.g. the stack). However: - * Without the MMU and cache, unaligned accesses will fault. It builds with `aarch64-unknown-none` - which sets `+strict-align` to prevent the compiler generating unaligned accesses so it should be - alright, but this is not necessarily the case in general. - * If it were running in a VM, this can lead to cache coherency issues. The problem is that the VM - is accessing memory directly with the cache disabled, while the host has cachable aliases to the - same memory. Even if the host doesn't explicitly access the memory, speculative accesses can - lead to cache fills, and then changes from one or the other will get lost. Again this is alright - in this particular case (running directly on the hardware with no hypervisor), but isn't a good - pattern in general. +- The RaspberryPi OS tutorial runs Rust code before the MMU and caches are + enabled. This will read and write memory (e.g. the stack). However: + - Without the MMU and cache, unaligned accesses will fault. It builds with + `aarch64-unknown-none` which sets `+strict-align` to prevent the compiler + generating unaligned accesses so it should be alright, but this is not + necessarily the case in general. + - If it were running in a VM, this can lead to cache coherency issues. The + problem is that the VM is accessing memory directly with the cache disabled, + while the host has cachable aliases to the same memory. Even if the host + doesn't explicitly access the memory, speculative accesses can lead to cache + fills, and then changes from one or the other will get lost. Again this is + alright in this particular case (running directly on the hardware with no + hypervisor), but isn't a good pattern in general.
diff --git a/src/bare-metal/aps/uart.md b/src/bare-metal/aps/uart.md index e18933faf1e8..5f9ec9461888 100644 --- a/src/bare-metal/aps/uart.md +++ b/src/bare-metal/aps/uart.md @@ -8,16 +8,18 @@ The QEMU 'virt' machine has a [PL011][1] UART, so let's write a driver for that.
-* Note that `Uart::new` is unsafe while the other methods are safe. This is because as long as the - caller of `Uart::new` guarantees that its safety requirements are met (i.e. that there is only - ever one instance of the driver for a given UART, and nothing else aliasing its address space), - then it is always safe to call `write_byte` later because we can assume the necessary +- Note that `Uart::new` is unsafe while the other methods are safe. This is + because as long as the caller of `Uart::new` guarantees that its safety + requirements are met (i.e. that there is only ever one instance of the driver + for a given UART, and nothing else aliasing its address space), then it is + always safe to call `write_byte` later because we can assume the necessary preconditions. -* We could have done it the other way around (making `new` safe but `write_byte` unsafe), but that - would be much less convenient to use as every place that calls `write_byte` would need to reason - about the safety -* This is a common pattern for writing safe wrappers of unsafe code: moving the burden of proof for - soundness from a large number of places to a smaller number of places. +- We could have done it the other way around (making `new` safe but `write_byte` + unsafe), but that would be much less convenient to use as every place that + calls `write_byte` would need to reason about the safety +- This is a common pattern for writing safe wrappers of unsafe code: moving the + burden of proof for soundness from a large number of places to a smaller + number of places. diff --git a/src/bare-metal/aps/uart/traits.md b/src/bare-metal/aps/uart/traits.md index 95b5f7499c6e..1f69e9ffa44c 100644 --- a/src/bare-metal/aps/uart/traits.md +++ b/src/bare-metal/aps/uart/traits.md @@ -1,6 +1,7 @@ # More traits -We derived the `Debug` trait. It would be useful to implement a few more traits too. +We derived the `Debug` trait. It would be useful to implement a few more traits +too. ```rust,editable,compile_fail {{#include ../examples/src/pl011_minimal.rs:Traits}} @@ -8,7 +9,9 @@ We derived the `Debug` trait. It would be useful to implement a few more traits
-* Implementing `Write` lets us use the `write!` and `writeln!` macros with our `Uart` type. -* Run the example in QEMU with `make qemu_minimal` under `src/bare-metal/aps/examples`. +- Implementing `Write` lets us use the `write!` and `writeln!` macros with our + `Uart` type. +- Run the example in QEMU with `make qemu_minimal` under + `src/bare-metal/aps/examples`.
diff --git a/src/bare-metal/microcontrollers.md b/src/bare-metal/microcontrollers.md index 17c9a2db8e98..f00d42f07326 100644 --- a/src/bare-metal/microcontrollers.md +++ b/src/bare-metal/microcontrollers.md @@ -1,17 +1,19 @@ # Microcontrollers -The `cortex_m_rt` crate provides (among other things) a reset handler for Cortex M microcontrollers. +The `cortex_m_rt` crate provides (among other things) a reset handler for Cortex +M microcontrollers. ```rust,editable,compile_fail {{#include microcontrollers/examples/src/bin/minimal.rs:Example}} ``` -Next we'll look at how to access peripherals, with increasing levels of abstraction. +Next we'll look at how to access peripherals, with increasing levels of +abstraction.
-* The `cortex_m_rt::entry` macro requires that the function have type `fn() -> !`, because returning - to the reset handler doesn't make sense. -* Run the example with `cargo embed --bin minimal` +- The `cortex_m_rt::entry` macro requires that the function have type + `fn() -> !`, because returning to the reset handler doesn't make sense. +- Run the example with `cargo embed --bin minimal`
diff --git a/src/bare-metal/microcontrollers/board-support.md b/src/bare-metal/microcontrollers/board-support.md index a6b1a5fd7cd5..58c4f78c3bec 100644 --- a/src/bare-metal/microcontrollers/board-support.md +++ b/src/bare-metal/microcontrollers/board-support.md @@ -1,6 +1,7 @@ # Board support crates -Board support crates provide a further level of wrapping for a specific board for convenience. +Board support crates provide a further level of wrapping for a specific board +for convenience. ```rust,editable,compile_fail {{#include examples/src/bin/board_support.rs:Example}} @@ -8,11 +9,11 @@ Board support crates provide a further level of wrapping for a specific board fo
- * In this case the board support crate is just providing more useful names, and a bit of - initialisation. - * The crate may also include drivers for some on-board devices outside of the microcontroller - itself. - * `microbit-v2` includes a simple driver for the LED matrix. +- In this case the board support crate is just providing more useful names, and + a bit of initialisation. +- The crate may also include drivers for some on-board devices outside of the + microcontroller itself. + - `microbit-v2` includes a simple driver for the LED matrix. Run the example with: diff --git a/src/bare-metal/microcontrollers/embedded-hal.md b/src/bare-metal/microcontrollers/embedded-hal.md index d1d325e83c52..5e8c3da90de8 100644 --- a/src/bare-metal/microcontrollers/embedded-hal.md +++ b/src/bare-metal/microcontrollers/embedded-hal.md @@ -1,23 +1,25 @@ # `embedded-hal` -The [`embedded-hal`](https://crates.io/crates/embedded-hal) crate provides a number of traits -covering common microcontroller peripherals. +The [`embedded-hal`](https://crates.io/crates/embedded-hal) crate provides a +number of traits covering common microcontroller peripherals. - * GPIO - * ADC - * I2C, SPI, UART, CAN - * RNG - * Timers - * Watchdogs +- GPIO +- ADC +- I2C, SPI, UART, CAN +- RNG +- Timers +- Watchdogs Other crates then implement -[drivers](https://github.com/rust-embedded/awesome-embedded-rust#driver-crates) in terms of these -traits, e.g. an accelerometer driver might need an I2C or SPI bus implementation. +[drivers](https://github.com/rust-embedded/awesome-embedded-rust#driver-crates) +in terms of these traits, e.g. an accelerometer driver might need an I2C or SPI +bus implementation.
- * There are implementations for many microcontrollers, as well as other platforms such as Linux on -Raspberry Pi. - * There is work in progress on an `async` version of `embedded-hal`, but it isn't stable yet. +- There are implementations for many microcontrollers, as well as other + platforms such as Linux on Raspberry Pi. +- There is work in progress on an `async` version of `embedded-hal`, but it + isn't stable yet.
diff --git a/src/bare-metal/microcontrollers/hals.md b/src/bare-metal/microcontrollers/hals.md index 642e0adca3d6..9b9b3d206a87 100644 --- a/src/bare-metal/microcontrollers/hals.md +++ b/src/bare-metal/microcontrollers/hals.md @@ -1,8 +1,9 @@ # HAL crates -[HAL crates](https://github.com/rust-embedded/awesome-embedded-rust#hal-implementation-crates) for -many microcontrollers provide wrappers around various peripherals. These generally implement traits -from [`embedded-hal`](https://crates.io/crates/embedded-hal). +[HAL crates](https://github.com/rust-embedded/awesome-embedded-rust#hal-implementation-crates) +for many microcontrollers provide wrappers around various peripherals. These +generally implement traits from +[`embedded-hal`](https://crates.io/crates/embedded-hal). ```rust,editable,compile_fail {{#include examples/src/bin/hal.rs:Example}} @@ -10,9 +11,9 @@ from [`embedded-hal`](https://crates.io/crates/embedded-hal).
- * `set_low` and `set_high` are methods on the `embedded_hal` `OutputPin` trait. - * HAL crates exist for many Cortex-M and RISC-V devices, including various STM32, GD32, nRF, NXP, - MSP430, AVR and PIC microcontrollers. +- `set_low` and `set_high` are methods on the `embedded_hal` `OutputPin` trait. +- HAL crates exist for many Cortex-M and RISC-V devices, including various + STM32, GD32, nRF, NXP, MSP430, AVR and PIC microcontrollers. Run the example with: diff --git a/src/bare-metal/microcontrollers/mmio.md b/src/bare-metal/microcontrollers/mmio.md index 57f37119e702..426083fb91ac 100644 --- a/src/bare-metal/microcontrollers/mmio.md +++ b/src/bare-metal/microcontrollers/mmio.md @@ -1,7 +1,7 @@ # Raw MMIO -Most microcontrollers access peripherals via memory-mapped IO. Let's try turning on an LED on our -micro:bit: +Most microcontrollers access peripherals via memory-mapped IO. Let's try turning +on an LED on our micro:bit: ```rust,editable,compile_fail {{#include examples/src/bin/mmio.rs:Example}} @@ -9,7 +9,8 @@ micro:bit:
-* GPIO 0 pin 21 is connected to the first column of the LED matrix, and pin 28 to the first row. +- GPIO 0 pin 21 is connected to the first column of the LED matrix, and pin 28 + to the first row. Run the example with: diff --git a/src/bare-metal/microcontrollers/other-projects.md b/src/bare-metal/microcontrollers/other-projects.md index d653c93ee690..8434b02ff298 100644 --- a/src/bare-metal/microcontrollers/other-projects.md +++ b/src/bare-metal/microcontrollers/other-projects.md @@ -1,26 +1,29 @@ # Other projects - * [RTIC](https://rtic.rs/) - * "Real-Time Interrupt-driven Concurrency" - * Shared resource management, message passing, task scheduling, timer queue - * [Embassy](https://embassy.dev/) - * `async` executors with priorities, timers, networking, USB - * [TockOS](https://www.tockos.org/documentation/getting-started) - * Security-focused RTOS with preemptive scheduling and Memory Protection Unit support - * [Hubris](https://hubris.oxide.computer/) - * Microkernel RTOS from Oxide Computer Company with memory protection, unprivileged drivers, IPC - * [Bindings for FreeRTOS](https://github.com/lobaro/FreeRTOS-rust) - * Some platforms have `std` implementations, e.g. - [esp-idf](https://esp-rs.github.io/book/overview/using-the-standard-library.html). +- [RTIC](https://rtic.rs/) + - "Real-Time Interrupt-driven Concurrency" + - Shared resource management, message passing, task scheduling, timer queue +- [Embassy](https://embassy.dev/) + - `async` executors with priorities, timers, networking, USB +- [TockOS](https://www.tockos.org/documentation/getting-started) + - Security-focused RTOS with preemptive scheduling and Memory Protection Unit + support +- [Hubris](https://hubris.oxide.computer/) + - Microkernel RTOS from Oxide Computer Company with memory protection, + unprivileged drivers, IPC +- [Bindings for FreeRTOS](https://github.com/lobaro/FreeRTOS-rust) +- Some platforms have `std` implementations, e.g. + [esp-idf](https://esp-rs.github.io/book/overview/using-the-standard-library.html).
- * RTIC can be considered either an RTOS or a concurrency framework. - * It doesn't include any HALs. - * It uses the Cortex-M NVIC (Nested Virtual Interrupt Controller) for scheduling rather than a - proper kernel. - * Cortex-M only. - * Google uses TockOS on the Haven microcontroller for Titan security keys. - * FreeRTOS is mostly written in C, but there are Rust bindings for writing applications. +- RTIC can be considered either an RTOS or a concurrency framework. + - It doesn't include any HALs. + - It uses the Cortex-M NVIC (Nested Virtual Interrupt Controller) for + scheduling rather than a proper kernel. + - Cortex-M only. +- Google uses TockOS on the Haven microcontroller for Titan security keys. +- FreeRTOS is mostly written in C, but there are Rust bindings for writing + applications.
diff --git a/src/bare-metal/microcontrollers/pacs.md b/src/bare-metal/microcontrollers/pacs.md index 86e0b0d7204a..2ecb30f299a0 100644 --- a/src/bare-metal/microcontrollers/pacs.md +++ b/src/bare-metal/microcontrollers/pacs.md @@ -1,8 +1,8 @@ # Peripheral Access Crates -[`svd2rust`](https://crates.io/crates/svd2rust) generates mostly-safe Rust wrappers for -memory-mapped peripherals from [CMSIS-SVD](https://www.keil.com/pack/doc/CMSIS/SVD/html/index.html) -files. +[`svd2rust`](https://crates.io/crates/svd2rust) generates mostly-safe Rust +wrappers for memory-mapped peripherals from +[CMSIS-SVD](https://www.keil.com/pack/doc/CMSIS/SVD/html/index.html) files. ```rust,editable,compile_fail {{#include examples/src/bin/pac.rs:Example}} @@ -10,15 +10,17 @@ files.
-* SVD (System View Description) files are XML files typically provided by silicon vendors which - describe the memory map of the device. - * They are organised by peripheral, register, field and value, with names, descriptions, addresses - and so on. - * SVD files are often buggy and incomplete, so there are various projects which patch the - mistakes, add missing details, and publish the generated crates. -* `cortex-m-rt` provides the vector table, among other things. -* If you `cargo install cargo-binutils` then you can run - `cargo objdump --bin pac -- -d --no-show-raw-insn` to see the resulting binary. +- SVD (System View Description) files are XML files typically provided by + silicon vendors which describe the memory map of the device. + - They are organised by peripheral, register, field and value, with names, + descriptions, addresses and so on. + - SVD files are often buggy and incomplete, so there are various projects + which patch the mistakes, add missing details, and publish the generated + crates. +- `cortex-m-rt` provides the vector table, among other things. +- If you `cargo install cargo-binutils` then you can run + `cargo objdump --bin pac -- -d --no-show-raw-insn` to see the resulting + binary. Run the example with: diff --git a/src/bare-metal/microcontrollers/probe-rs.md b/src/bare-metal/microcontrollers/probe-rs.md index a995477e66ab..19cdad0cc1ba 100644 --- a/src/bare-metal/microcontrollers/probe-rs.md +++ b/src/bare-metal/microcontrollers/probe-rs.md @@ -1,29 +1,35 @@ # `probe-rs`, `cargo-embed` -[probe-rs](https://probe.rs/) is a handy toolset for embedded debugging, like OpenOCD but better -integrated. +[probe-rs](https://probe.rs/) is a handy toolset for embedded debugging, like +OpenOCD but better integrated. -* SWD and JTAG via CMSIS-DAP, ST-Link and J-Link probes -* GDB stub and Microsoft DAP server -* Cargo integration +- SWD and JTAG via CMSIS-DAP, ST-Link and + J-Link probes +- GDB stub and Microsoft DAP server +- Cargo integration `cargo-embed` is a cargo subcommand to build and flash binaries, log -RTT output and connect GDB. It's configured by an -`Embed.toml` file in your project directory. +RTT output and connect GDB. It's +configured by an `Embed.toml` file in your project directory.
-* [CMSIS-DAP](https://arm-software.github.io/CMSIS_5/DAP/html/index.html) is an Arm standard - protocol over USB for an in-circuit debugger to access the CoreSight Debug Access Port of various - Arm Cortex processors. It's what the on-board debugger on the BBC micro:bit uses. -* ST-Link is a range of in-circuit debuggers from ST Microelectronics, J-Link is a range from - SEGGER. -* The Debug Access Port is usually either a 5-pin JTAG interface or 2-pin Serial Wire Debug. -* probe-rs is a library which you can integrate into your own tools if you want to. -* The [Microsoft Debug Adapter Protocol](https://microsoft.github.io/debug-adapter-protocol/) lets - VSCode and other IDEs debug code running on any supported microcontroller. -* cargo-embed is a binary built using the probe-rs library. -* RTT (Real Time Transfers) is a mechanism to transfer data between the debug host and the target - through a number of ringbuffers. +- [CMSIS-DAP](https://arm-software.github.io/CMSIS_5/DAP/html/index.html) is an + Arm standard protocol over USB for an in-circuit debugger to access the + CoreSight Debug Access Port of various Arm Cortex processors. It's what the + on-board debugger on the BBC micro:bit uses. +- ST-Link is a range of in-circuit debuggers from ST Microelectronics, J-Link is + a range from SEGGER. +- The Debug Access Port is usually either a 5-pin JTAG interface or 2-pin Serial + Wire Debug. +- probe-rs is a library which you can integrate into your own tools if you want + to. +- The + [Microsoft Debug Adapter Protocol](https://microsoft.github.io/debug-adapter-protocol/) + lets VSCode and other IDEs debug code running on any supported + microcontroller. +- cargo-embed is a binary built using the probe-rs library. +- RTT (Real Time Transfers) is a mechanism to transfer data between the debug + host and the target through a number of ringbuffers.
diff --git a/src/bare-metal/microcontrollers/type-state.md b/src/bare-metal/microcontrollers/type-state.md index 5829b171d473..0ed4edf0c214 100644 --- a/src/bare-metal/microcontrollers/type-state.md +++ b/src/bare-metal/microcontrollers/type-state.md @@ -6,15 +6,17 @@
- * Pins don't implement `Copy` or `Clone`, so only one instance of each can exist. Once a pin is - moved out of the port struct nobody else can take it. - * Changing the configuration of a pin consumes the old pin instance, so you can’t keep use the old - instance afterwards. - * The type of a value indicates the state that it is in: e.g. in this case, the configuration state - of a GPIO pin. This encodes the state machine into the type system, and ensures that you don't - try to use a pin in a certain way without properly configuring it first. Illegal state - transitions are caught at compile time. - * You can call `is_high` on an input pin and `set_high` on an output pin, but not vice-versa. - * Many HAL crates follow this pattern. +- Pins don't implement `Copy` or `Clone`, so only one instance of each can + exist. Once a pin is moved out of the port struct nobody else can take it. +- Changing the configuration of a pin consumes the old pin instance, so you + can’t keep use the old instance afterwards. +- The type of a value indicates the state that it is in: e.g. in this case, the + configuration state of a GPIO pin. This encodes the state machine into the + type system, and ensures that you don't try to use a pin in a certain way + without properly configuring it first. Illegal state transitions are caught at + compile time. +- You can call `is_high` on an input pin and `set_high` on an output pin, but + not vice-versa. +- Many HAL crates follow this pattern.
diff --git a/src/bare-metal/minimal.md b/src/bare-metal/minimal.md index d96ff34df66c..b46bf9d851be 100644 --- a/src/bare-metal/minimal.md +++ b/src/bare-metal/minimal.md @@ -14,13 +14,13 @@ fn panic(_panic: &PanicInfo) -> ! {
-* This will compile to an empty binary. -* `std` provides a panic handler; without it we must provide our own. -* It can also be provided by another crate, such as `panic-halt`. -* Depending on the target, you may need to compile with `panic = "abort"` to avoid an error about - `eh_personality`. -* Note that there is no `main` or any other entry point; it's up to you to define your own entry - point. This will typically involve a linker script and some assembly code to set things up ready - for Rust code to run. +- This will compile to an empty binary. +- `std` provides a panic handler; without it we must provide our own. +- It can also be provided by another crate, such as `panic-halt`. +- Depending on the target, you may need to compile with `panic = "abort"` to + avoid an error about `eh_personality`. +- Note that there is no `main` or any other entry point; it's up to you to + define your own entry point. This will typically involve a linker script and + some assembly code to set things up ready for Rust code to run.
diff --git a/src/bare-metal/no_std.md b/src/bare-metal/no_std.md index 9ea4d5df86a2..4f984e7f0760 100644 --- a/src/bare-metal/no_std.md +++ b/src/bare-metal/no_std.md @@ -3,7 +3,7 @@ @@ -21,37 +21,37 @@ @@ -59,7 +59,7 @@
-* `HashMap` depends on RNG. -* `std` re-exports the contents of both `core` and `alloc`. +- `HashMap` depends on RNG. +- `std` re-exports the contents of both `core` and `alloc`.
diff --git a/src/bare-metal/useful-crates.md b/src/bare-metal/useful-crates.md index d544efe6dde4..393017738775 100644 --- a/src/bare-metal/useful-crates.md +++ b/src/bare-metal/useful-crates.md @@ -1,3 +1,4 @@ # Useful crates -We'll go over a few crates which solve some common problems in bare-metal programming. +We'll go over a few crates which solve some common problems in bare-metal +programming. diff --git a/src/bare-metal/useful-crates/aarch64-paging.md b/src/bare-metal/useful-crates/aarch64-paging.md index 1d8097863397..dbf5f4c09564 100644 --- a/src/bare-metal/useful-crates/aarch64-paging.md +++ b/src/bare-metal/useful-crates/aarch64-paging.md @@ -1,7 +1,7 @@ # `aarch64-paging` -The [`aarch64-paging`][1] crate lets you create page tables according to the AArch64 Virtual Memory -System Architecture. +The [`aarch64-paging`][1] crate lets you create page tables according to the +AArch64 Virtual Memory System Architecture. ```rust,editable,compile_fail use aarch64_paging::{ @@ -25,10 +25,11 @@ idmap.activate();
-* For now it only supports EL1, but support for other exception levels should be straightforward to - add. -* This is used in Android for the [Protected VM Firmware][2]. -* There's no easy way to run this example, as it needs to run on real hardware or under QEMU. +- For now it only supports EL1, but support for other exception levels should be + straightforward to add. +- This is used in Android for the [Protected VM Firmware][2]. +- There's no easy way to run this example, as it needs to run on real hardware + or under QEMU.
diff --git a/src/bare-metal/useful-crates/buddy_system_allocator.md b/src/bare-metal/useful-crates/buddy_system_allocator.md index 61efb6a379a6..d8e084a1df11 100644 --- a/src/bare-metal/useful-crates/buddy_system_allocator.md +++ b/src/bare-metal/useful-crates/buddy_system_allocator.md @@ -1,9 +1,10 @@ # `buddy_system_allocator` -[`buddy_system_allocator`][1] is a third-party crate implementing a basic buddy system allocator. -It can be used both for [`LockedHeap`][2] implementing [`GlobalAlloc`][3] so you can use the -standard `alloc` crate (as we saw [before][4]), or for allocating other address space. For example, -we might want to allocate MMIO space for PCI BARs: +[`buddy_system_allocator`][1] is a third-party crate implementing a basic buddy +system allocator. It can be used both for [`LockedHeap`][2] implementing +[`GlobalAlloc`][3] so you can use the standard `alloc` crate (as we saw +[before][4]), or for allocating other address space. For example, we might want +to allocate MMIO space for PCI BARs: ```rust,editable,compile_fail {{#include allocator-example/src/main.rs:main}} @@ -11,9 +12,10 @@ we might want to allocate MMIO space for PCI BARs:
-* PCI BARs always have alignment equal to their size. -* Run the example with `cargo run` under `src/bare-metal/useful-crates/allocator-example/`. (It won't - run in the Playground because of the crate dependency.) +- PCI BARs always have alignment equal to their size. +- Run the example with `cargo run` under + `src/bare-metal/useful-crates/allocator-example/`. (It won't run in the + Playground because of the crate dependency.)
diff --git a/src/bare-metal/useful-crates/spin.md b/src/bare-metal/useful-crates/spin.md index 77ded7db9a51..b7099b5b71b5 100644 --- a/src/bare-metal/useful-crates/spin.md +++ b/src/bare-metal/useful-crates/spin.md @@ -1,10 +1,11 @@ # `spin` -`std::sync::Mutex` and the other synchronisation primitives from `std::sync` are not available in -`core` or `alloc`. How can we manage synchronisation or interior mutability, such as for sharing -state between different CPUs? +`std::sync::Mutex` and the other synchronisation primitives from `std::sync` are +not available in `core` or `alloc`. How can we manage synchronisation or +interior mutability, such as for sharing state between different CPUs? -The [`spin`][1] crate provides spinlock-based equivalents of many of these primitives. +The [`spin`][1] crate provides spinlock-based equivalents of many of these +primitives. ```rust,editable,compile_fail use spin::mutex::SpinMutex; @@ -20,12 +21,12 @@ fn main() {
-* Be careful to avoid deadlock if you take locks in interrupt handlers. -* `spin` also has a ticket lock mutex implementation; equivalents of `RwLock`, `Barrier` and `Once` - from `std::sync`; and `Lazy` for lazy initialisation. -* The [`once_cell`][2] crate also has some useful types for late initialisation with a slightly - different approach to `spin::once::Once`. -* The Rust Playground includes `spin`, so this example will run fine inline. +- Be careful to avoid deadlock if you take locks in interrupt handlers. +- `spin` also has a ticket lock mutex implementation; equivalents of `RwLock`, + `Barrier` and `Once` from `std::sync`; and `Lazy` for lazy initialisation. +- The [`once_cell`][2] crate also has some useful types for late initialisation + with a slightly different approach to `spin::once::Once`. +- The Rust Playground includes `spin`, so this example will run fine inline.
diff --git a/src/bare-metal/useful-crates/tinyvec.md b/src/bare-metal/useful-crates/tinyvec.md index 5522fd6fa95b..38f2d98984de 100644 --- a/src/bare-metal/useful-crates/tinyvec.md +++ b/src/bare-metal/useful-crates/tinyvec.md @@ -1,9 +1,9 @@ # `tinyvec` -Sometimes you want something which can be resized like a `Vec`, but without heap allocation. -[`tinyvec`][1] provides this: a vector backed by an array or slice, which could be statically -allocated or on the stack, which keeps track of how many elements are used and panics if you try to -use more than are allocated. +Sometimes you want something which can be resized like a `Vec`, but without heap +allocation. [`tinyvec`][1] provides this: a vector backed by an array or slice, +which could be statically allocated or on the stack, which keeps track of how +many elements are used and panics if you try to use more than are allocated. ```rust,editable,compile_fail use tinyvec::{array_vec, ArrayVec}; @@ -20,8 +20,9 @@ fn main() {
-* `tinyvec` requires that the element type implement `Default` for initialisation. -* The Rust Playground includes `tinyvec`, so this example will run fine inline. +- `tinyvec` requires that the element type implement `Default` for + initialisation. +- The Rust Playground includes `tinyvec`, so this example will run fine inline.
diff --git a/src/bare-metal/useful-crates/zerocopy.md b/src/bare-metal/useful-crates/zerocopy.md index fe3df8a71452..744dbc225c76 100644 --- a/src/bare-metal/useful-crates/zerocopy.md +++ b/src/bare-metal/useful-crates/zerocopy.md @@ -1,24 +1,27 @@ # `zerocopy` -The [`zerocopy`][1] crate (from Fuchsia) provides traits and macros for safely converting between -byte sequences and other types. +The [`zerocopy`][1] crate (from Fuchsia) provides traits and macros for safely +converting between byte sequences and other types. ```rust,editable,compile_fail {{#include zerocopy-example/src/main.rs:main}} ``` -This is not suitable for MMIO (as it doesn't use volatile reads and writes), but can be useful for -working with structures shared with hardware e.g. by DMA, or sent over some external interface. +This is not suitable for MMIO (as it doesn't use volatile reads and writes), but +can be useful for working with structures shared with hardware e.g. by DMA, or +sent over some external interface.
-* `FromBytes` can be implemented for types for which any byte pattern is valid, and so can safely be - converted from an untrusted sequence of bytes. -* Attempting to derive `FromBytes` for these types would fail, because `RequestType` doesn't use all - possible u32 values as discriminants, so not all byte patterns are valid. -* `zerocopy::byteorder` has types for byte-order aware numeric primitives. -* Run the example with `cargo run` under `src/bare-metal/useful-crates/zerocopy-example/`. (It won't - run in the Playground because of the crate dependency.) +- `FromBytes` can be implemented for types for which any byte pattern is valid, + and so can safely be converted from an untrusted sequence of bytes. +- Attempting to derive `FromBytes` for these types would fail, because + `RequestType` doesn't use all possible u32 values as discriminants, so not all + byte patterns are valid. +- `zerocopy::byteorder` has types for byte-order aware numeric primitives. +- Run the example with `cargo run` under + `src/bare-metal/useful-crates/zerocopy-example/`. (It won't run in the + Playground because of the crate dependency.)
diff --git a/src/basic-syntax.md b/src/basic-syntax.md index 96a361109af3..66b3b7394441 100644 --- a/src/basic-syntax.md +++ b/src/basic-syntax.md @@ -2,8 +2,8 @@ Much of the Rust syntax will be familiar to you from C, C++ or Java: -* Blocks and scopes are delimited by curly braces. -* Line comments are started with `//`, block comments are delimited by `/* ... - */`. -* Keywords like `if` and `while` work the same. -* Variable assignment is done with `=`, comparison is done with `==`. +- Blocks and scopes are delimited by curly braces. +- Line comments are started with `//`, block comments are delimited by + `/* ... */`. +- Keywords like `if` and `while` work the same. +- Variable assignment is done with `=`, comparison is done with `==`. diff --git a/src/basic-syntax/compound-types.md b/src/basic-syntax/compound-types.md index 9b66f5920b26..b715396e75bd 100644 --- a/src/basic-syntax/compound-types.md +++ b/src/basic-syntax/compound-types.md @@ -1,7 +1,7 @@ # Compound Types | | Types | Literals | -|--------|-------------------------------|-----------------------------------| +| ------ | ----------------------------- | --------------------------------- | | Arrays | `[T; N]` | `[20, 30, 40]`, `[0; 3]` | | Tuples | `()`, `(T,)`, `(T1, T2)`, ... | `()`, `('x',)`, `('x', 1.2)`, ... | @@ -31,32 +31,35 @@ Key points: Arrays: -* A value of the array type `[T; N]` holds `N` (a compile-time constant) elements of the same type `T`. - Note that the length of the array is *part of its type*, which means that `[u8; 3]` and - `[u8; 4]` are considered two different types. +- A value of the array type `[T; N]` holds `N` (a compile-time constant) + elements of the same type `T`. Note that the length of the array is _part of + its type_, which means that `[u8; 3]` and `[u8; 4]` are considered two + different types. -* We can use literals to assign values to arrays. +- We can use literals to assign values to arrays. -* In the main function, the print statement asks for the debug implementation with the `?` format - parameter: `{}` gives the default output, `{:?}` gives the debug output. We - could also have used `{a}` and `{a:?}` without specifying the value after the - format string. +- In the main function, the print statement asks for the debug implementation + with the `?` format parameter: `{}` gives the default output, `{:?}` gives the + debug output. We could also have used `{a}` and `{a:?}` without specifying the + value after the format string. -* Adding `#`, eg `{a:#?}`, invokes a "pretty printing" format, which can be easier to read. +- Adding `#`, eg `{a:#?}`, invokes a "pretty printing" format, which can be + easier to read. Tuples: -* Like arrays, tuples have a fixed length. +- Like arrays, tuples have a fixed length. -* Tuples group together values of different types into a compound type. +- Tuples group together values of different types into a compound type. -* Fields of a tuple can be accessed by the period and the index of the value, e.g. `t.0`, `t.1`. +- Fields of a tuple can be accessed by the period and the index of the value, + e.g. `t.0`, `t.1`. -* The empty tuple `()` is also known as the "unit type". It is both a type, and +- The empty tuple `()` is also known as the "unit type". It is both a type, and the only valid value of that type - that is to say both the type and its value are expressed as `()`. It is used to indicate, for example, that a function or - expression has no return value, as we'll see in a future slide. - * You can think of it as `void` that can be familiar to you from other - programming languages. + expression has no return value, as we'll see in a future slide. + - You can think of it as `void` that can be familiar to you from other + programming languages. diff --git a/src/basic-syntax/functions-interlude.md b/src/basic-syntax/functions-interlude.md index caa170659173..0fd5ef5d193d 100644 --- a/src/basic-syntax/functions-interlude.md +++ b/src/basic-syntax/functions-interlude.md @@ -2,12 +2,12 @@ Overloading is not supported: -* Each function has a single implementation: - * Always takes a fixed number of parameters. - * Always takes a single set of parameter types. -* Default values are not supported: - * All call sites have the same number of arguments. - * Macros are sometimes used as an alternative. +- Each function has a single implementation: + - Always takes a fixed number of parameters. + - Always takes a single set of parameter types. +- Default values are not supported: + - All call sites have the same number of arguments. + - Macros are sometimes used as an alternative. However, function parameters can be generic: @@ -24,8 +24,8 @@ fn main() {
-* When using generics, the standard library's `Into` can provide a kind of limited - polymorphism on argument types. We will see more details in a later section. +- When using generics, the standard library's `Into` can provide a kind of + limited polymorphism on argument types. We will see more details in a later + section.
- diff --git a/src/basic-syntax/functions.md b/src/basic-syntax/functions.md index 3858f5e92a78..f2dff613fc25 100644 --- a/src/basic-syntax/functions.md +++ b/src/basic-syntax/functions.md @@ -1,6 +1,7 @@ # Functions -A Rust version of the famous [FizzBuzz](https://en.wikipedia.org/wiki/Fizz_buzz) interview question: +A Rust version of the famous [FizzBuzz](https://en.wikipedia.org/wiki/Fizz_buzz) +interview question: ```rust,editable fn main() { @@ -32,10 +33,15 @@ fn print_fizzbuzz_to(n: u32) {
-* We refer in `main` to a function written below. Neither forward declarations nor headers are necessary. -* Declaration parameters are followed by a type (the reverse of some programming languages), then a return type. -* The last expression in a function body (or any block) becomes the return value. Simply omit the `;` at the end of the expression. -* Some functions have no return value, and return the 'unit type', `()`. The compiler will infer this if the `-> ()` return type is omitted. -* The range expression in the `for` loop in `print_fizzbuzz_to()` contains `=n`, which causes it to include the upper bound. +- We refer in `main` to a function written below. Neither forward declarations + nor headers are necessary. +- Declaration parameters are followed by a type (the reverse of some programming + languages), then a return type. +- The last expression in a function body (or any block) becomes the return + value. Simply omit the `;` at the end of the expression. +- Some functions have no return value, and return the 'unit type', `()`. The + compiler will infer this if the `-> ()` return type is omitted. +- The range expression in the `for` loop in `print_fizzbuzz_to()` contains `=n`, + which causes it to include the upper bound.
diff --git a/src/basic-syntax/methods.md b/src/basic-syntax/methods.md index 67a6a3d94226..754c79444e06 100644 --- a/src/basic-syntax/methods.md +++ b/src/basic-syntax/methods.md @@ -27,21 +27,24 @@ fn main() { } ``` -* We will look much more at methods in today's exercise and in tomorrow's class. +- We will look much more at methods in today's exercise and in tomorrow's class.
- Add a static method called `Rectangle::new` and call this from `main`: - ```rust,editable,compile_fail - fn new(width: u32, height: u32) -> Rectangle { - Rectangle { width, height } - } - ``` + ```rust,editable,compile_fail + fn new(width: u32, height: u32) -> Rectangle { + Rectangle { width, height } + } + ``` -- While _technically_, Rust does not have custom constructors, static methods are commonly used to initialize structs (but don't have to). - The actual constructor, `Rectangle { width, height }`, could be called directly. See the [Rustnomicon](https://doc.rust-lang.org/nomicon/constructors.html). +- While _technically_, Rust does not have custom constructors, static methods + are commonly used to initialize structs (but don't have to). The actual + constructor, `Rectangle { width, height }`, could be called directly. See the + [Rustnomicon](https://doc.rust-lang.org/nomicon/constructors.html). -- Add a `Rectangle::square(width: u32)` constructor to illustrate that such static methods can take arbitrary parameters. +- Add a `Rectangle::square(width: u32)` constructor to illustrate that such + static methods can take arbitrary parameters.
diff --git a/src/basic-syntax/references-dangling.md b/src/basic-syntax/references-dangling.md index deb8c18b8a78..417cfd1ca755 100644 --- a/src/basic-syntax/references-dangling.md +++ b/src/basic-syntax/references-dangling.md @@ -13,7 +13,7 @@ fn main() { } ``` -* A reference is said to "borrow" the value it refers to. -* Rust is tracking the lifetimes of all references to ensure they live long +- A reference is said to "borrow" the value it refers to. +- Rust is tracking the lifetimes of all references to ensure they live long enough. -* We will talk more about borrowing when we get to ownership. +- We will talk more about borrowing when we get to ownership. diff --git a/src/basic-syntax/references.md b/src/basic-syntax/references.md index b03fd6316f4f..70a25db43689 100644 --- a/src/basic-syntax/references.md +++ b/src/basic-syntax/references.md @@ -13,17 +13,20 @@ fn main() { Some notes: -* We must dereference `ref_x` when assigning to it, similar to C and C++ pointers. -* Rust will auto-dereference in some cases, in particular when invoking - methods (try `ref_x.count_ones()`). -* References that are declared as `mut` can be bound to different values over their lifetime. +- We must dereference `ref_x` when assigning to it, similar to C and C++ + pointers. +- Rust will auto-dereference in some cases, in particular when invoking methods + (try `ref_x.count_ones()`). +- References that are declared as `mut` can be bound to different values over + their lifetime.
Key points: -* Be sure to note the difference between `let mut ref_x: &i32` and `let ref_x: - &mut i32`. The first one represents a mutable reference which can be bound to - different values, while the second represents a reference to a mutable value. +- Be sure to note the difference between `let mut ref_x: &i32` and + `let ref_x: &mut i32`. The first one represents a mutable reference which can + be bound to different values, while the second represents a reference to a + mutable value.
diff --git a/src/basic-syntax/rustdoc.md b/src/basic-syntax/rustdoc.md index b42c73a22d66..b12a2cefccf6 100644 --- a/src/basic-syntax/rustdoc.md +++ b/src/basic-syntax/rustdoc.md @@ -21,16 +21,17 @@ idiomatic to document all public items in an API using this pattern.
-* Show students the generated docs for the `rand` crate at +- Show students the generated docs for the `rand` crate at [`docs.rs/rand`](https://docs.rs/rand). -* This course does not include rustdoc on slides, just to save space, but in +- This course does not include rustdoc on slides, just to save space, but in real code they should be present. -* Inner doc comments are discussed later (in the page on modules) and need not +- Inner doc comments are discussed later (in the page on modules) and need not be addressed here. -* Rustdoc comments can contain code snippets that we can run and test using `cargo test`. - We will discuss these tests in the [Testing section](../testing/doc-tests.html). +- Rustdoc comments can contain code snippets that we can run and test using + `cargo test`. We will discuss these tests in the + [Testing section](../testing/doc-tests.html).
diff --git a/src/basic-syntax/scalar-types.md b/src/basic-syntax/scalar-types.md index 059de2bc40e4..d5c51b956903 100644 --- a/src/basic-syntax/scalar-types.md +++ b/src/basic-syntax/scalar-types.md @@ -1,7 +1,7 @@ # Scalar Types | | Types | Literals | -|------------------------|--------------------------------------------|--------------------------------| +| ---------------------- | ------------------------------------------ | ------------------------------ | | Signed integers | `i8`, `i16`, `i32`, `i64`, `i128`, `isize` | `-10`, `0`, `1_000`, `123_i64` | | Unsigned integers | `u8`, `u16`, `u32`, `u64`, `u128`, `usize` | `0`, `123`, `10_u16` | | Floating point numbers | `f32`, `f64` | `3.14`, `-10.0e20`, `2_f32` | @@ -11,18 +11,18 @@ The types have widths as follows: -* `iN`, `uN`, and `fN` are _N_ bits wide, -* `isize` and `usize` are the width of a pointer, -* `char` is 32 bits wide, -* `bool` is 8 bits wide. +- `iN`, `uN`, and `fN` are _N_ bits wide, +- `isize` and `usize` are the width of a pointer, +- `char` is 32 bits wide, +- `bool` is 8 bits wide.
There are a few syntaxes which are not shown above: -- Raw strings allow you to create a `&str` value with escapes disabled: `r"\n" - == "\\\\n"`. You can embed double-quotes by using an equal amount of `#` on - either side of the quotes: +- Raw strings allow you to create a `&str` value with escapes disabled: + `r"\n" == "\\n"`. You can embed double-quotes by using an equal amount of `#` + on either side of the quotes: ```rust,editable fn main() { @@ -40,7 +40,8 @@ There are a few syntaxes which are not shown above: } ``` -- All underscores in numbers can be left out, they are for legibility only. - So `1_000` can be written as `1000` (or `10_00`), and `123_i64` can be written as `123i64`. +- All underscores in numbers can be left out, they are for legibility only. So + `1_000` can be written as `1000` (or `10_00`), and `123_i64` can be written as + `123i64`.
diff --git a/src/basic-syntax/scopes-shadowing.md b/src/basic-syntax/scopes-shadowing.md index 2009178b11e2..ef0d34791229 100644 --- a/src/basic-syntax/scopes-shadowing.md +++ b/src/basic-syntax/scopes-shadowing.md @@ -22,10 +22,15 @@ fn main() {
-* Definition: Shadowing is different from mutation, because after shadowing both variable's memory locations exist at the same time. Both are available under the same name, depending where you use it in the code. -* A shadowing variable can have a different type. -* Shadowing looks obscure at first, but is convenient for holding on to values after `.unwrap()`. -* The following code demonstrates why the compiler can't simply reuse memory locations when shadowing an immutable variable in a scope, even if the type does not change. +- Definition: Shadowing is different from mutation, because after shadowing both + variable's memory locations exist at the same time. Both are available under + the same name, depending where you use it in the code. +- A shadowing variable can have a different type. +- Shadowing looks obscure at first, but is convenient for holding on to values + after `.unwrap()`. +- The following code demonstrates why the compiler can't simply reuse memory + locations when shadowing an immutable variable in a scope, even if the type + does not change. ```rust,editable fn main() { diff --git a/src/basic-syntax/slices.md b/src/basic-syntax/slices.md index edab4573bb78..545ff32e118a 100644 --- a/src/basic-syntax/slices.md +++ b/src/basic-syntax/slices.md @@ -13,24 +13,35 @@ fn main() { } ``` -* Slices borrow data from the sliced type. -* Question: What happens if you modify `a[3]` right before printing `s`? +- Slices borrow data from the sliced type. +- Question: What happens if you modify `a[3]` right before printing `s`?
-* We create a slice by borrowing `a` and specifying the starting and ending indexes in brackets. +- We create a slice by borrowing `a` and specifying the starting and ending + indexes in brackets. -* If the slice starts at index 0, Rust’s range syntax allows us to drop the starting index, meaning that `&a[0..a.len()]` and `&a[..a.len()]` are identical. - -* The same is true for the last index, so `&a[2..a.len()]` and `&a[2..]` are identical. +- If the slice starts at index 0, Rust’s range syntax allows us to drop the + starting index, meaning that `&a[0..a.len()]` and `&a[..a.len()]` are + identical. -* To easily create a slice of the full array, we can therefore use `&a[..]`. +- The same is true for the last index, so `&a[2..a.len()]` and `&a[2..]` are + identical. + +- To easily create a slice of the full array, we can therefore use `&a[..]`. + +- `s` is a reference to a slice of `i32`s. Notice that the type of `s` + (`&[i32]`) no longer mentions the array length. This allows us to perform + computation on slices of different sizes. + +- Slices always borrow from another object. In this example, `a` has to remain + 'alive' (in scope) for at least as long as our slice. + +- The question about modifying `a[3]` can spark an interesting discussion, but + the answer is that for memory safety reasons you cannot do it through `a` at + this point in the execution, but you can read the data from both `a` and `s` + safely. It works before you created the slice, and again after the `println`, + when the slice is no longer used. More details will be explained in the borrow + checker section. -* `s` is a reference to a slice of `i32`s. Notice that the type of `s` (`&[i32]`) no longer mentions the array length. This allows us to perform computation on slices of different sizes. - -* Slices always borrow from another object. In this example, `a` has to remain 'alive' (in scope) for at least as long as our slice. - -* The question about modifying `a[3]` can spark an interesting discussion, but the answer is that for memory safety reasons - you cannot do it through `a` at this point in the execution, but you can read the data from both `a` and `s` safely. - It works before you created the slice, and again after the `println`, when the slice is no longer used. More details will be explained in the borrow checker section.
diff --git a/src/basic-syntax/static-and-const.md b/src/basic-syntax/static-and-const.md index 2d437302d22b..13461e2bef66 100644 --- a/src/basic-syntax/static-and-const.md +++ b/src/basic-syntax/static-and-const.md @@ -1,7 +1,7 @@ # Static and Constant Variables -Static and constant variables are two different ways to create globally-scoped values that -cannot be moved or reallocated during the execution of the program. +Static and constant variables are two different ways to create globally-scoped +values that cannot be moved or reallocated during the execution of the program. ## `const` @@ -28,11 +28,13 @@ fn main() { According to the [Rust RFC Book][1] these are inlined upon use. -Only functions marked `const` can be called at compile time to generate `const` values. `const` functions can however be called at runtime. +Only functions marked `const` can be called at compile time to generate `const` +values. `const` functions can however be called at runtime. ## `static` -Static variables will live during the whole execution of the program, and therefore will not move: +Static variables will live during the whole execution of the program, and +therefore will not move: ```rust,editable static BANNER: &str = "Welcome to RustOS 3.14"; @@ -42,34 +44,40 @@ fn main() { } ``` -As noted in the [Rust RFC Book][1], these are not inlined upon use and have an actual associated memory location. This is useful for unsafe and -embedded code, and the variable lives through the entirety of the program execution. -When a globally-scoped value does not have a reason to need object identity, `const` is generally preferred. +As noted in the [Rust RFC Book][1], these are not inlined upon use and have an +actual associated memory location. This is useful for unsafe and embedded code, +and the variable lives through the entirety of the program execution. When a +globally-scoped value does not have a reason to need object identity, `const` is +generally preferred. -Because `static` variables are accessible from any thread, they must be `Sync`. Interior mutability -is possible through a [`Mutex`](https://doc.rust-lang.org/std/sync/struct.Mutex.html), atomic or -similar. It is also possible to have mutable statics, but they require manual synchronisation so any -access to them requires `unsafe` code. We will look at -[mutable statics](../unsafe/mutable-static-variables.md) in the chapter on Unsafe Rust. +Because `static` variables are accessible from any thread, they must be `Sync`. +Interior mutability is possible through a +[`Mutex`](https://doc.rust-lang.org/std/sync/struct.Mutex.html), atomic or +similar. It is also possible to have mutable statics, but they require manual +synchronisation so any access to them requires `unsafe` code. We will look at +[mutable statics](../unsafe/mutable-static-variables.md) in the chapter on +Unsafe Rust.
-* Mention that `const` behaves semantically similar to C++'s `constexpr`. -* `static`, on the other hand, is much more similar to a `const` or mutable global variable in C++. -* `static` provides object identity: an address in memory and state as required by types with interior mutability such as `Mutex`. -* It isn't super common that one would need a runtime evaluated constant, but it is helpful and safer than using a static. -* `thread_local` data can be created with the macro `std::thread_local`. - -### Properties table: - -| Property | Static | Constant | -|---|---|---| -| Has an address in memory | Yes | No (inlined) | -| Lives for the entire duration of the program | Yes | No | -| Can be mutable | Yes (unsafe) | No | -| Evaluated at compile time | Yes (initialised at compile time) | Yes | -| Inlined wherever it is used | No | Yes | - +- Mention that `const` behaves semantically similar to C++'s `constexpr`. +- `static`, on the other hand, is much more similar to a `const` or mutable + global variable in C++. +- `static` provides object identity: an address in memory and state as required + by types with interior mutability such as `Mutex`. +- It isn't super common that one would need a runtime evaluated constant, but it + is helpful and safer than using a static. +- `thread_local` data can be created with the macro `std::thread_local`. + +### Properties table: + +| Property | Static | Constant | +| -------------------------------------------- | --------------------------------- | ------------ | +| Has an address in memory | Yes | No (inlined) | +| Lives for the entire duration of the program | Yes | No | +| Can be mutable | Yes (unsafe) | No | +| Evaluated at compile time | Yes (initialised at compile time) | Yes | +| Inlined wherever it is used | No | Yes |
diff --git a/src/basic-syntax/string-slices.md b/src/basic-syntax/string-slices.md index bb7bdddf3638..671fe614475d 100644 --- a/src/basic-syntax/string-slices.md +++ b/src/basic-syntax/string-slices.md @@ -19,26 +19,31 @@ fn main() { Rust terminology: -* `&str` an immutable reference to a string slice. -* `String` a mutable string buffer. +- `&str` an immutable reference to a string slice. +- `String` a mutable string buffer.
-* `&str` introduces a string slice, which is an immutable reference to UTF-8 encoded string data - stored in a block of memory. String literals (`”Hello”`), are stored in the program’s binary. +- `&str` introduces a string slice, which is an immutable reference to UTF-8 + encoded string data stored in a block of memory. String literals (`”Hello”`), + are stored in the program’s binary. -* Rust’s `String` type is a wrapper around a vector of bytes. As with a `Vec`, it is owned. - -* As with many other types `String::from()` creates a string from a string literal; `String::new()` - creates a new empty string, to which string data can be added using the `push()` and `push_str()` methods. +- Rust’s `String` type is a wrapper around a vector of bytes. As with a + `Vec`, it is owned. + +- As with many other types `String::from()` creates a string from a string + literal; `String::new()` creates a new empty string, to which string data can + be added using the `push()` and `push_str()` methods. + +- The `format!()` macro is a convenient way to generate an owned string from + dynamic values. It accepts the same format specification as `println!()`. + +- You can borrow `&str` slices from `String` via `&` and optionally range + selection. + +- For C++ programmers: think of `&str` as `const char*` from C++, but the one + that always points to a valid string in memory. Rust `String` is a rough + equivalent of `std::string` from C++ (main difference: it can only contain + UTF-8 encoded bytes and will never use a small-string optimization). -* The `format!()` macro is a convenient way to generate an owned string from dynamic values. It - accepts the same format specification as `println!()`. - -* You can borrow `&str` slices from `String` via `&` and optionally range selection. - -* For C++ programmers: think of `&str` as `const char*` from C++, but the one that always points - to a valid string in memory. Rust `String` is a rough equivalent of `std::string` from C++ - (main difference: it can only contain UTF-8 encoded bytes and will never use a small-string optimization). -
diff --git a/src/basic-syntax/type-inference.md b/src/basic-syntax/type-inference.md index 526e3b21a661..8963d23e7f7d 100644 --- a/src/basic-syntax/type-inference.md +++ b/src/basic-syntax/type-inference.md @@ -23,13 +23,17 @@ fn main() {
-This slide demonstrates how the Rust compiler infers types based on constraints given by variable declarations and usages. - -It is very important to emphasize that variables declared like this are not of some sort of dynamic "any type" that can -hold any data. The machine code generated by such declaration is identical to the explicit declaration of a type. -The compiler does the job for us and helps us write more concise code. +This slide demonstrates how the Rust compiler infers types based on constraints +given by variable declarations and usages. -The following code tells the compiler to copy into a certain generic container without the code ever explicitly specifying the contained type, using `_` as a placeholder: +It is very important to emphasize that variables declared like this are not of +some sort of dynamic "any type" that can hold any data. The machine code +generated by such declaration is identical to the explicit declaration of a +type. The compiler does the job for us and helps us write more concise code. + +The following code tells the compiler to copy into a certain generic container +without the code ever explicitly specifying the contained type, using `_` as a +placeholder: ```rust,editable fn main() { @@ -43,6 +47,11 @@ fn main() { } ``` -[`collect`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.collect) relies on [`FromIterator`](https://doc.rust-lang.org/std/iter/trait.FromIterator.html), which [`HashSet`](https://doc.rust-lang.org/std/collections/struct.HashSet.html#impl-FromIterator%3CT%3E-for-HashSet%3CT,+S%3E) implements. +[`collect`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.collect) +relies on +[`FromIterator`](https://doc.rust-lang.org/std/iter/trait.FromIterator.html), +which +[`HashSet`](https://doc.rust-lang.org/std/collections/struct.HashSet.html#impl-FromIterator%3CT%3E-for-HashSet%3CT,+S%3E) +implements.
diff --git a/src/basic-syntax/variables.md b/src/basic-syntax/variables.md index 82ec653a0529..f5d68bef0874 100644 --- a/src/basic-syntax/variables.md +++ b/src/basic-syntax/variables.md @@ -14,6 +14,7 @@ fn main() {
-* Due to type inference the `i32` is optional. We will gradually show the types less and less as the course progresses. +- Due to type inference the `i32` is optional. We will gradually show the types + less and less as the course progresses.
diff --git a/src/cargo.md b/src/cargo.md index 6f8bf2aab163..3989edcac313 100644 --- a/src/cargo.md +++ b/src/cargo.md @@ -1,27 +1,36 @@ # Using Cargo -When you start reading about Rust, you will soon meet [Cargo](https://doc.rust-lang.org/cargo/), the standard tool -used in the Rust ecosystem to build and run Rust applications. Here we want to -give a brief overview of what Cargo is and how it fits into the wider ecosystem -and how it fits into this training. +When you start reading about Rust, you will soon meet +[Cargo](https://doc.rust-lang.org/cargo/), the standard tool used in the Rust +ecosystem to build and run Rust applications. Here we want to give a brief +overview of what Cargo is and how it fits into the wider ecosystem and how it +fits into this training. ## Installation > **Please follow the instructions on .** -This will give you the Cargo build tool (`cargo`) and the Rust compiler (`rustc`). You will also get `rustup`, a command line utility that you can use to install/switch toolchains, setup cross compilation, etc. +This will give you the Cargo build tool (`cargo`) and the Rust compiler +(`rustc`). You will also get `rustup`, a command line utility that you can use +to install/switch toolchains, setup cross compilation, etc.
-* On Debian/Ubuntu, you can also install Cargo, the Rust source and the [Rust formatter][6] via `apt`. However, this gets you an outdated rust version and may lead to unexpected behavior. The command would be: +- On Debian/Ubuntu, you can also install Cargo, the Rust source and the + [Rust formatter][6] via `apt`. However, this gets you an outdated rust version + and may lead to unexpected behavior. The command would be: ```shell sudo apt install cargo rust-src rustfmt ``` -* We suggest using [VS Code][2] to edit the code (but any LSP compatible editor works with rust-analyzer[3]). +- We suggest using [VS Code][2] to edit the code (but any LSP compatible editor + works with rust-analyzer[3]). -* Some folks also like to use the [JetBrains][4] family of IDEs, which do their own analysis but have their own tradeoffs. If you prefer them, you can install the [Rust Plugin][5]. Please take note that as of January 2023 debugging only works on the CLion version of the JetBrains IDEA suite. +- Some folks also like to use the [JetBrains][4] family of IDEs, which do their + own analysis but have their own tradeoffs. If you prefer them, you can install + the [Rust Plugin][5]. Please take note that as of January 2023 debugging only + works on the CLion version of the JetBrains IDEA suite.
diff --git a/src/cargo/code-samples.md b/src/cargo/code-samples.md index 95fca6d96896..02ab93ac4443 100644 --- a/src/cargo/code-samples.md +++ b/src/cargo/code-samples.md @@ -21,15 +21,14 @@ text box.
-Most code samples are editable like shown above. A few code samples -are not editable for various reasons: +Most code samples are editable like shown above. A few code samples are not +editable for various reasons: -* The embedded playgrounds cannot execute unit tests. Copy-paste the - code and open it in the real Playground to demonstrate unit tests. +- The embedded playgrounds cannot execute unit tests. Copy-paste the code and + open it in the real Playground to demonstrate unit tests. -* The embedded playgrounds lose their state the moment you navigate - away from the page! This is the reason that the students should - solve the exercises using a local Rust installation or via the - Playground. +- The embedded playgrounds lose their state the moment you navigate away from + the page! This is the reason that the students should solve the exercises + using a local Rust installation or via the Playground.
diff --git a/src/cargo/running-locally.md b/src/cargo/running-locally.md index 55d526746c99..78898ad4124b 100644 --- a/src/cargo/running-locally.md +++ b/src/cargo/running-locally.md @@ -1,9 +1,10 @@ # Running Code Locally with Cargo If you want to experiment with the code on your own system, then you will need -to first install Rust. Do this by following the [instructions in the Rust -Book][1]. This should give you a working `rustc` and `cargo`. At the time of -writing, the latest stable Rust release has these version numbers: +to first install Rust. Do this by following the +[instructions in the Rust Book][1]. This should give you a working `rustc` and +`cargo`. At the time of writing, the latest stable Rust release has these +version numbers: ```shell % rustc --version @@ -14,47 +15,47 @@ cargo 1.69.0 (6e9a83356 2023-04-12) You can use any later version too since Rust maintains backwards compatibility. -With this in place, follow these steps to build a Rust binary from one -of the examples in this training: +With this in place, follow these steps to build a Rust binary from one of the +examples in this training: 1. Click the "Copy to clipboard" button on the example you want to copy. 2. Use `cargo new exercise` to create a new `exercise/` directory for your code: - ```shell - $ cargo new exercise - Created binary (application) `exercise` package - ``` + ```shell + $ cargo new exercise + Created binary (application) `exercise` package + ``` 3. Navigate into `exercise/` and use `cargo run` to build and run your binary: - ```shell - $ cd exercise - $ cargo run - Compiling exercise v0.1.0 (/home/mgeisler/tmp/exercise) - Finished dev [unoptimized + debuginfo] target(s) in 0.75s - Running `target/debug/exercise` - Hello, world! - ``` + ```shell + $ cd exercise + $ cargo run + Compiling exercise v0.1.0 (/home/mgeisler/tmp/exercise) + Finished dev [unoptimized + debuginfo] target(s) in 0.75s + Running `target/debug/exercise` + Hello, world! + ``` 4. Replace the boiler-plate code in `src/main.rs` with your own code. For example, using the example on the previous page, make `src/main.rs` look like - ```rust - fn main() { - println!("Edit me!"); - } - ``` + ```rust + fn main() { + println!("Edit me!"); + } + ``` 5. Use `cargo run` to build and run your updated binary: - ```shell - $ cargo run - Compiling exercise v0.1.0 (/home/mgeisler/tmp/exercise) - Finished dev [unoptimized + debuginfo] target(s) in 0.24s - Running `target/debug/exercise` - Edit me! - ``` + ```shell + $ cargo run + Compiling exercise v0.1.0 (/home/mgeisler/tmp/exercise) + Finished dev [unoptimized + debuginfo] target(s) in 0.24s + Running `target/debug/exercise` + Edit me! + ``` 6. Use `cargo check` to quickly check your project for errors, use `cargo build` to compile it without running it. You will find the output in `target/debug/` @@ -69,8 +70,8 @@ of the examples in this training:
-Try to encourage the class participants to install Cargo and use a -local editor. It will make their life easier since they will have a -normal development environment. +Try to encourage the class participants to install Cargo and use a local editor. +It will make their life easier since they will have a normal development +environment.
diff --git a/src/cargo/rust-ecosystem.md b/src/cargo/rust-ecosystem.md index a9ae01a3f11e..367f0e4509e6 100644 --- a/src/cargo/rust-ecosystem.md +++ b/src/cargo/rust-ecosystem.md @@ -2,15 +2,15 @@ The Rust ecosystem consists of a number of tools, of which the main ones are: -* `rustc`: the Rust compiler which turns `.rs` files into binaries and other +- `rustc`: the Rust compiler which turns `.rs` files into binaries and other intermediate formats. -* `cargo`: the Rust dependency manager and build tool. Cargo knows how to - download dependencies, usually hosted on , and it will pass them to - `rustc` when building your project. Cargo also comes with a built-in test - runner which is used to execute unit tests. +- `cargo`: the Rust dependency manager and build tool. Cargo knows how to + download dependencies, usually hosted on , and it will pass + them to `rustc` when building your project. Cargo also comes with a built-in + test runner which is used to execute unit tests. -* `rustup`: the Rust toolchain installer and updater. This tool is used to +- `rustup`: the Rust toolchain installer and updater. This tool is used to install and update `rustc` and `cargo` when new versions of Rust is released. In addition, `rustup` can also download documentation for the standard library. You can have multiple versions of Rust installed at once and `rustup` @@ -20,52 +20,51 @@ The Rust ecosystem consists of a number of tools, of which the main ones are: Key points: -* Rust has a rapid release schedule with a new release coming out - every six weeks. New releases maintain backwards compatibility with - old releases --- plus they enable new functionality. +- Rust has a rapid release schedule with a new release coming out every six + weeks. New releases maintain backwards compatibility with old releases --- + plus they enable new functionality. -* There are three release channels: "stable", "beta", and "nightly". +- There are three release channels: "stable", "beta", and "nightly". -* New features are being tested on "nightly", "beta" is what becomes - "stable" every six weeks. +- New features are being tested on "nightly", "beta" is what becomes "stable" + every six weeks. -* Dependencies can also be resolved from alternative [registries], git, folders, and more. +- Dependencies can also be resolved from alternative [registries], git, folders, + and more. -* Rust also has [editions]: the current edition is Rust 2021. Previous - editions were Rust 2015 and Rust 2018. +- Rust also has [editions]: the current edition is Rust 2021. Previous editions + were Rust 2015 and Rust 2018. - * The editions are allowed to make backwards incompatible changes to - the language. + - The editions are allowed to make backwards incompatible changes to the + language. - * To prevent breaking code, editions are opt-in: you select the - edition for your crate via the `Cargo.toml` file. + - To prevent breaking code, editions are opt-in: you select the edition for + your crate via the `Cargo.toml` file. - * To avoid splitting the ecosystem, Rust compilers can mix code - written for different editions. + - To avoid splitting the ecosystem, Rust compilers can mix code written for + different editions. - * Mention that it is quite rare to ever use the compiler directly not through `cargo` (most users never do). + - Mention that it is quite rare to ever use the compiler directly not through + `cargo` (most users never do). - * It might be worth alluding that Cargo itself is an extremely powerful and comprehensive tool. It is capable of many advanced features including but not limited to: - * Project/package structure - * [workspaces] - * Dev Dependencies and Runtime Dependency management/caching - * [build scripting] - * [global installation] - * It is also extensible with sub command plugins as well (such as [cargo clippy]). - * Read more from the [official Cargo Book] + - It might be worth alluding that Cargo itself is an extremely powerful and + comprehensive tool. It is capable of many advanced features including but + not limited to: + - Project/package structure + - [workspaces] + - Dev Dependencies and Runtime Dependency management/caching + - [build scripting] + - [global installation] + - It is also extensible with sub command plugins as well (such as + [cargo clippy]). + - Read more from the [official Cargo Book] [editions]: https://doc.rust-lang.org/edition-guide/ - [workspaces]: https://doc.rust-lang.org/cargo/reference/workspaces.html - [build scripting]: https://doc.rust-lang.org/cargo/reference/build-scripts.html - [global installation]: https://doc.rust-lang.org/cargo/commands/cargo-install.html - [cargo clippy]: https://github.com/rust-lang/rust-clippy - [official Cargo Book]: https://doc.rust-lang.org/cargo/ - [registries]: https://doc.rust-lang.org/cargo/reference/registries.html
diff --git a/src/concurrency/channels.md b/src/concurrency/channels.md index be2250979aeb..507866b8f021 100644 --- a/src/concurrency/channels.md +++ b/src/concurrency/channels.md @@ -24,9 +24,10 @@ fn main() {
-* `mpsc` stands for Multi-Producer, Single-Consumer. `Sender` and `SyncSender` implement `Clone` (so - you can make multiple producers) but `Receiver` does not. -* `send()` and `recv()` return `Result`. If they return `Err`, it means the counterpart `Sender` or - `Receiver` is dropped and the channel is closed. +- `mpsc` stands for Multi-Producer, Single-Consumer. `Sender` and `SyncSender` + implement `Clone` (so you can make multiple producers) but `Receiver` does + not. +- `send()` and `recv()` return `Result`. If they return `Err`, it means the + counterpart `Sender` or `Receiver` is dropped and the channel is closed.
diff --git a/src/concurrency/channels/bounded.md b/src/concurrency/channels/bounded.md index ca919ad9e5ce..83eec8687c6a 100644 --- a/src/concurrency/channels/bounded.md +++ b/src/concurrency/channels/bounded.md @@ -27,9 +27,13 @@ fn main() { ```
- -* Calling `send` will block the current thread until there is space in the channel for the new message. The thread can be blocked indefinitely if there is nobody who reads from the channel. -* A call to `send` will abort with an error (that is why it returns `Result`) if the channel is closed. A channel is closed when the receiver is dropped. -* A bounded channel with a size of zero is called a "rendezvous channel". Every send will block the current thread until another thread calls `read`. - + +- Calling `send` will block the current thread until there is space in the + channel for the new message. The thread can be blocked indefinitely if there + is nobody who reads from the channel. +- A call to `send` will abort with an error (that is why it returns `Result`) if + the channel is closed. A channel is closed when the receiver is dropped. +- A bounded channel with a size of zero is called a "rendezvous channel". Every + send will block the current thread until another thread calls `read`. +
diff --git a/src/concurrency/scoped-threads.md b/src/concurrency/scoped-threads.md index 95680e068f90..911cb3f2c542 100644 --- a/src/concurrency/scoped-threads.md +++ b/src/concurrency/scoped-threads.md @@ -36,8 +36,10 @@ fn main() { [1]: https://doc.rust-lang.org/std/thread/fn.scope.html
- -* The reason for that is that when the `thread::scope` function completes, all the threads are guaranteed to be joined, so they can return borrowed data. -* Normal Rust borrowing rules apply: you can either borrow mutably by one thread, or immutably by any number of threads. - + +- The reason for that is that when the `thread::scope` function completes, all + the threads are guaranteed to be joined, so they can return borrowed data. +- Normal Rust borrowing rules apply: you can either borrow mutably by one + thread, or immutably by any number of threads. +
diff --git a/src/concurrency/send-sync.md b/src/concurrency/send-sync.md index d253c72a7acb..055533ec869d 100644 --- a/src/concurrency/send-sync.md +++ b/src/concurrency/send-sync.md @@ -1,15 +1,16 @@ # `Send` and `Sync` -How does Rust know to forbid shared access across thread? The answer is in two traits: +How does Rust know to forbid shared access across thread? The answer is in two +traits: -* [`Send`][1]: a type `T` is `Send` if it is safe to move a `T` across a thread +- [`Send`][1]: a type `T` is `Send` if it is safe to move a `T` across a thread boundary. -* [`Sync`][2]: a type `T` is `Sync` if it is safe to move a `&T` across a thread +- [`Sync`][2]: a type `T` is `Sync` if it is safe to move a `&T` across a thread boundary. -`Send` and `Sync` are [unsafe traits][3]. The compiler will automatically derive them for your types -as long as they only contain `Send` and `Sync` types. You can also implement them manually when you -know it is valid. +`Send` and `Sync` are [unsafe traits][3]. The compiler will automatically derive +them for your types as long as they only contain `Send` and `Sync` types. You +can also implement them manually when you know it is valid. [1]: https://doc.rust-lang.org/std/marker/trait.Send.html [2]: https://doc.rust-lang.org/std/marker/trait.Sync.html @@ -17,7 +18,8 @@ know it is valid.
-* One can think of these traits as markers that the type has certain thread-safety properties. -* They can be used in the generic constraints as normal traits. - +- One can think of these traits as markers that the type has certain + thread-safety properties. +- They can be used in the generic constraints as normal traits. +
diff --git a/src/concurrency/send-sync/examples.md b/src/concurrency/send-sync/examples.md index 8c8f92ad7b78..8142f45b0ec1 100644 --- a/src/concurrency/send-sync/examples.md +++ b/src/concurrency/send-sync/examples.md @@ -4,12 +4,12 @@ Most types you come across are `Send + Sync`: -* `i8`, `f32`, `bool`, `char`, `&str`, ... -* `(T1, T2)`, `[T; N]`, `&[T]`, `struct { x: T }`, ... -* `String`, `Option`, `Vec`, `Box`, ... -* `Arc`: Explicitly thread-safe via atomic reference count. -* `Mutex`: Explicitly thread-safe via internal locking. -* `AtomicBool`, `AtomicU8`, ...: Uses special atomic instructions. +- `i8`, `f32`, `bool`, `char`, `&str`, ... +- `(T1, T2)`, `[T; N]`, `&[T]`, `struct { x: T }`, ... +- `String`, `Option`, `Vec`, `Box`, ... +- `Arc`: Explicitly thread-safe via atomic reference count. +- `Mutex`: Explicitly thread-safe via internal locking. +- `AtomicBool`, `AtomicU8`, ...: Uses special atomic instructions. The generic types are typically `Send + Sync` when the type parameters are `Send + Sync`. @@ -19,23 +19,23 @@ The generic types are typically `Send + Sync` when the type parameters are These types can be moved to other threads, but they're not thread-safe. Typically because of interior mutability: -* `mpsc::Sender` -* `mpsc::Receiver` -* `Cell` -* `RefCell` +- `mpsc::Sender` +- `mpsc::Receiver` +- `Cell` +- `RefCell` ## `!Send + Sync` These types are thread-safe, but they cannot be moved to another thread: -* `MutexGuard`: Uses OS level primitives which must be deallocated on the +- `MutexGuard`: Uses OS level primitives which must be deallocated on the thread which created them. ## `!Send + !Sync` These types are not thread-safe and cannot be moved to other threads: -* `Rc`: each `Rc` has a reference to an `RcBox`, which contains a +- `Rc`: each `Rc` has a reference to an `RcBox`, which contains a non-atomic reference count. -* `*const T`, `*mut T`: Rust assumes raw pointers may have special - concurrency considerations. +- `*const T`, `*mut T`: Rust assumes raw pointers may have special concurrency + considerations. diff --git a/src/concurrency/send-sync/sync.md b/src/concurrency/send-sync/sync.md index 75ca77ea4132..ea490bcb1d13 100644 --- a/src/concurrency/send-sync/sync.md +++ b/src/concurrency/send-sync/sync.md @@ -11,8 +11,14 @@ More precisely, the definition is:
-This statement is essentially a shorthand way of saying that if a type is thread-safe for shared use, it is also thread-safe to pass references of it across threads. - -This is because if a type is Sync it means that it can be shared across multiple threads without the risk of data races or other synchronization issues, so it is safe to move it to another thread. A reference to the type is also safe to move to another thread, because the data it references can be accessed from any thread safely. +This statement is essentially a shorthand way of saying that if a type is +thread-safe for shared use, it is also thread-safe to pass references of it +across threads. + +This is because if a type is Sync it means that it can be shared across multiple +threads without the risk of data races or other synchronization issues, so it is +safe to move it to another thread. A reference to the type is also safe to move +to another thread, because the data it references can be accessed from any +thread safely.
diff --git a/src/concurrency/shared_state.md b/src/concurrency/shared_state.md index 73b5d1013112..de84078a4125 100644 --- a/src/concurrency/shared_state.md +++ b/src/concurrency/shared_state.md @@ -3,9 +3,9 @@ Rust uses the type system to enforce synchronization of shared data. This is primarily done via two types: -* [`Arc`][1], atomic reference counted `T`: handles sharing between threads and - takes care to deallocate `T` when the last reference is dropped, -* [`Mutex`][2]: ensures mutually exclusive access to the `T` value. +- [`Arc`][1], atomic reference counted `T`: handles sharing between threads + and takes care to deallocate `T` when the last reference is dropped, +- [`Mutex`][2]: ensures mutually exclusive access to the `T` value. [1]: https://doc.rust-lang.org/std/sync/struct.Arc.html [2]: https://doc.rust-lang.org/std/sync/struct.Mutex.html diff --git a/src/concurrency/shared_state/arc.md b/src/concurrency/shared_state/arc.md index cdd82c559474..bc64a6c2974e 100644 --- a/src/concurrency/shared_state/arc.md +++ b/src/concurrency/shared_state/arc.md @@ -26,13 +26,14 @@ fn main() {
-* `Arc` stands for "Atomic Reference Counted", a thread safe version of `Rc` that uses atomic - operations. -* `Arc` implements `Clone` whether or not `T` does. It implements `Send` and `Sync` if - and only if `T` implements them both. -* `Arc::clone()` has the cost of atomic operations that get executed, but after that the use of the - `T` is free. -* Beware of reference cycles, `Arc` does not use a garbage collector to detect them. - * `std::sync::Weak` can help. +- `Arc` stands for "Atomic Reference Counted", a thread safe version of `Rc` + that uses atomic operations. +- `Arc` implements `Clone` whether or not `T` does. It implements `Send` and + `Sync` if and only if `T` implements them both. +- `Arc::clone()` has the cost of atomic operations that get executed, but after + that the use of the `T` is free. +- Beware of reference cycles, `Arc` does not use a garbage collector to detect + them. + - `std::sync::Weak` can help.
diff --git a/src/concurrency/shared_state/example.md b/src/concurrency/shared_state/example.md index 0cbb1a72cd2f..2219b700172a 100644 --- a/src/concurrency/shared_state/example.md +++ b/src/concurrency/shared_state/example.md @@ -21,7 +21,7 @@ fn main() {
Possible solution: - + ```rust,editable use std::sync::{Arc, Mutex}; use std::thread; @@ -45,12 +45,16 @@ fn main() { println!("v: {v:?}"); } ``` - + Notable parts: -* `v` is wrapped in both `Arc` and `Mutex`, because their concerns are orthogonal. - * Wrapping a `Mutex` in an `Arc` is a common pattern to share mutable state between threads. -* `v: Arc<_>` needs to be cloned as `v2` before it can be moved into another thread. Note `move` was added to the lambda signature. -* Blocks are introduced to narrow the scope of the `LockGuard` as much as possible. +- `v` is wrapped in both `Arc` and `Mutex`, because their concerns are + orthogonal. + - Wrapping a `Mutex` in an `Arc` is a common pattern to share mutable state + between threads. +- `v: Arc<_>` needs to be cloned as `v2` before it can be moved into another + thread. Note `move` was added to the lambda signature. +- Blocks are introduced to narrow the scope of the `LockGuard` as much as + possible.
diff --git a/src/concurrency/shared_state/mutex.md b/src/concurrency/shared_state/mutex.md index 8fc7d45f072b..f6dc8eef014d 100644 --- a/src/concurrency/shared_state/mutex.md +++ b/src/concurrency/shared_state/mutex.md @@ -27,19 +27,22 @@ implementation. [3]: https://doc.rust-lang.org/std/sync/struct.Arc.html
- -* `Mutex` in Rust looks like a collection with just one element - the protected data. - * It is not possible to forget to acquire the mutex before accessing the protected data. -* You can get an `&mut T` from an `&Mutex` by taking the lock. The `MutexGuard` ensures that the - `&mut T` doesn't outlive the lock being held. -* `Mutex` implements both `Send` and `Sync` iff (if and only if) `T` implements `Send`. -* A read-write lock counterpart - `RwLock`. -* Why does `lock()` return a `Result`? - * If the thread that held the `Mutex` panicked, the `Mutex` becomes "poisoned" to signal that - the data it protected might be in an inconsistent state. Calling `lock()` on a poisoned mutex - fails with a [`PoisonError`]. You can call `into_inner()` on the error to recover the data - regardless. - -[`PoisonError`]: https://doc.rust-lang.org/std/sync/struct.PoisonError.html - + +- `Mutex` in Rust looks like a collection with just one element - the protected + data. + - It is not possible to forget to acquire the mutex before accessing the + protected data. +- You can get an `&mut T` from an `&Mutex` by taking the lock. The + `MutexGuard` ensures that the `&mut T` doesn't outlive the lock being held. +- `Mutex` implements both `Send` and `Sync` iff (if and only if) `T` + implements `Send`. +- A read-write lock counterpart - `RwLock`. +- Why does `lock()` return a `Result`? + - If the thread that held the `Mutex` panicked, the `Mutex` becomes "poisoned" + to signal that the data it protected might be in an inconsistent state. + Calling `lock()` on a poisoned mutex fails with a [`PoisonError`]. You can + call `into_inner()` on the error to recover the data regardless. + +[`PoisonError`]: https://doc.rust-lang.org/std/sync/struct.PoisonError.html +
diff --git a/src/concurrency/threads.md b/src/concurrency/threads.md index 6ba67e14d9b1..87a2a5143781 100644 --- a/src/concurrency/threads.md +++ b/src/concurrency/threads.md @@ -21,23 +21,23 @@ fn main() { } ``` -* Threads are all daemon threads, the main thread does not wait for them. -* Thread panics are independent of each other. - * Panics can carry a payload, which can be unpacked with `downcast_ref`. +- Threads are all daemon threads, the main thread does not wait for them. +- Thread panics are independent of each other. + - Panics can carry a payload, which can be unpacked with `downcast_ref`.
Key points: -* Notice that the thread is stopped before it reaches 10 — the main thread is +- Notice that the thread is stopped before it reaches 10 — the main thread is not waiting. -* Use `let handle = thread::spawn(...)` and later `handle.join()` to wait for +- Use `let handle = thread::spawn(...)` and later `handle.join()` to wait for the thread to finish. -* Trigger a panic in the thread, notice how this doesn't affect `main`. +- Trigger a panic in the thread, notice how this doesn't affect `main`. -* Use the `Result` return value from `handle.join()` to get access to the panic +- Use the `Result` return value from `handle.join()` to get access to the panic payload. This is a good time to talk about [`Any`]. [`Any`]: https://doc.rust-lang.org/std/any/index.html diff --git a/src/control-flow/blocks.md b/src/control-flow/blocks.md index c734837d7d9b..1035246d28d7 100644 --- a/src/control-flow/blocks.md +++ b/src/control-flow/blocks.md @@ -1,8 +1,7 @@ # Blocks -A block in Rust contains a sequence of expressions. -Each block has a value and a type, -which are those of the last expression of the block: +A block in Rust contains a sequence of expressions. Each block has a value and a +type, which are those of the last expression of the block: ```rust,editable fn main() { @@ -41,7 +40,9 @@ fn main() {
Key Points: -* The point of this slide is to show that blocks have a type and value in Rust. -* You can show how the value of the block changes by changing the last line in the block. For instance, adding/removing a semicolon or using a `return`. - + +- The point of this slide is to show that blocks have a type and value in Rust. +- You can show how the value of the block changes by changing the last line in + the block. For instance, adding/removing a semicolon or using a `return`. +
diff --git a/src/control-flow/break-continue.md b/src/control-flow/break-continue.md index aac48a4ca05d..64729942182d 100644 --- a/src/control-flow/break-continue.md +++ b/src/control-flow/break-continue.md @@ -1,8 +1,9 @@ # `break` and `continue` -- If you want to exit a loop early, use [`break`](https://doc.rust-lang.org/reference/expressions/loop-expr.html#break-expressions), -- If you want to immediately start -the next iteration use [`continue`](https://doc.rust-lang.org/reference/expressions/loop-expr.html#continue-expressions). +- If you want to exit a loop early, use + [`break`](https://doc.rust-lang.org/reference/expressions/loop-expr.html#break-expressions), +- If you want to immediately start the next iteration use + [`continue`](https://doc.rust-lang.org/reference/expressions/loop-expr.html#continue-expressions). Both `continue` and `break` can optionally take a label argument which is used to break out of nested loops: diff --git a/src/control-flow/for-expressions.md b/src/control-flow/for-expressions.md index e6ae73eae743..2fdef2040351 100644 --- a/src/control-flow/for-expressions.md +++ b/src/control-flow/for-expressions.md @@ -21,10 +21,12 @@ fn main() { You can use `break` and `continue` here as usual.
- -* Index iteration is not a special syntax in Rust for just that case. -* `(0..10)` is a range that implements an `Iterator` trait. -* `step_by` is a method that returns another `Iterator` that skips every other element. -* Modify the elements in the vector and explain the compiler errors. Change vector `v` to be mutable and the for loop to `for x in v.iter_mut()`. + +- Index iteration is not a special syntax in Rust for just that case. +- `(0..10)` is a range that implements an `Iterator` trait. +- `step_by` is a method that returns another `Iterator` that skips every other + element. +- Modify the elements in the vector and explain the compiler errors. Change + vector `v` to be mutable and the for loop to `for x in v.iter_mut()`.
diff --git a/src/control-flow/if-expressions.md b/src/control-flow/if-expressions.md index 3a45e4ced8fd..7795c7db4394 100644 --- a/src/control-flow/if-expressions.md +++ b/src/control-flow/if-expressions.md @@ -1,7 +1,7 @@ # `if` expressions -You use [`if` -expressions](https://doc.rust-lang.org/reference/expressions/if-expr.html#if-expressions) +You use +[`if` expressions](https://doc.rust-lang.org/reference/expressions/if-expr.html#if-expressions) exactly like `if` statements in other languages: ```rust,editable @@ -18,7 +18,6 @@ fn main() { In addition, you can use `if` as an expression. The last expression of each block becomes the value of the `if` expression: - ```rust,editable fn main() { let mut x = 10; @@ -32,6 +31,8 @@ fn main() {
-Because `if` is an expression and must have a particular type, both of its branch blocks must have the same type. Consider showing what happens if you add `;` after `x / 2` in the second example. - +Because `if` is an expression and must have a particular type, both of its +branch blocks must have the same type. Consider showing what happens if you add +`;` after `x / 2` in the second example. +
diff --git a/src/control-flow/if-let-expressions.md b/src/control-flow/if-let-expressions.md index c84cc38c21cb..50aafe435cb7 100644 --- a/src/control-flow/if-let-expressions.md +++ b/src/control-flow/if-let-expressions.md @@ -1,7 +1,7 @@ # `if let` expressions -The [`if let` -expression](https://doc.rust-lang.org/reference/expressions/if-expr.html#if-let-expressions) +The +[`if let` expression](https://doc.rust-lang.org/reference/expressions/if-expr.html#if-let-expressions) lets you execute different code depending on whether a value matches a pattern: ```rust,editable @@ -20,22 +20,28 @@ Rust.
-* Unlike `match`, `if let` does not have to cover all branches. This can make it more concise than `match`. -* A common usage is handling `Some` values when working with `Option`. -* Unlike `match`, `if let` does not support guard clauses for pattern matching. -* Since 1.65, a similar [let-else](https://doc.rust-lang.org/rust-by-example/flow_control/let_else.html) construct allows to do a destructuring assignment, or if it fails, execute a block which is required to abort normal control flow (with `panic`/`return`/`break`/`continue`): +- Unlike `match`, `if let` does not have to cover all branches. This can make it + more concise than `match`. +- A common usage is handling `Some` values when working with `Option`. +- Unlike `match`, `if let` does not support guard clauses for pattern matching. +- Since 1.65, a similar + [let-else](https://doc.rust-lang.org/rust-by-example/flow_control/let_else.html) + construct allows to do a destructuring assignment, or if it fails, execute a + block which is required to abort normal control flow (with + `panic`/`return`/`break`/`continue`): - ```rust,editable - fn main() { - println!("{:?}", second_word_to_upper("foo bar")); - } - - fn second_word_to_upper(s: &str) -> Option { - let mut it = s.split(' '); - let (Some(_), Some(item)) = (it.next(), it.next()) else { - return None; - }; - Some(item.to_uppercase()) - } + ```rust,editable + fn main() { + println!("{:?}", second_word_to_upper("foo bar")); + } + + fn second_word_to_upper(s: &str) -> Option { + let mut it = s.split(' '); + let (Some(_), Some(item)) = (it.next(), it.next()) else { + return None; + }; + Some(item.to_uppercase()) + } + ```
diff --git a/src/control-flow/loop-expressions.md b/src/control-flow/loop-expressions.md index faaecdb4f951..4ad39e5d4dd7 100644 --- a/src/control-flow/loop-expressions.md +++ b/src/control-flow/loop-expressions.md @@ -1,6 +1,7 @@ # `loop` expressions -Finally, there is a [`loop` keyword](https://doc.rust-lang.org/reference/expressions/loop-expr.html#infinite-loops) +Finally, there is a +[`loop` keyword](https://doc.rust-lang.org/reference/expressions/loop-expr.html#infinite-loops) which creates an endless loop. Here you must either `break` or `return` to stop the loop: @@ -23,9 +24,9 @@ fn main() { ```
- -* Break the `loop` with a value (e.g. `break 8`) and print it out. -* Note that `loop` is the only looping construct which returns a non-trivial + +- Break the `loop` with a value (e.g. `break 8`) and print it out. +- Note that `loop` is the only looping construct which returns a non-trivial value. This is because it's guaranteed to be entered at least once (unlike `while` and `for` loops). diff --git a/src/control-flow/match-expressions.md b/src/control-flow/match-expressions.md index b410ca7ef7ef..dbb1f0f579a3 100644 --- a/src/control-flow/match-expressions.md +++ b/src/control-flow/match-expressions.md @@ -1,6 +1,7 @@ # `match` expressions -The [`match` keyword](https://doc.rust-lang.org/reference/expressions/match-expr.html) +The +[`match` keyword](https://doc.rust-lang.org/reference/expressions/match-expr.html) is used to match a value against one or more patterns. In that sense, it works like a series of `if let` expressions: @@ -25,9 +26,12 @@ Rust.
-* Save the match expression to a variable and print it out. -* Remove `.as_deref()` and explain the error. - * `std::env::args().next()` returns an `Option`, but we cannot match against `String`. - * `as_deref()` transforms an `Option` to `Option<&T::Target>`. In our case, this turns `Option` into `Option<&str>`. - * We can now use pattern matching to match against the `&str` inside `Option`. +- Save the match expression to a variable and print it out. +- Remove `.as_deref()` and explain the error. + - `std::env::args().next()` returns an `Option`, but we cannot match + against `String`. + - `as_deref()` transforms an `Option` to `Option<&T::Target>`. In our case, + this turns `Option` into `Option<&str>`. + - We can now use pattern matching to match against the `&str` inside `Option`. +
diff --git a/src/control-flow/while-expressions.md b/src/control-flow/while-expressions.md index 1ad351e4cbc0..1526eca60ca2 100644 --- a/src/control-flow/while-expressions.md +++ b/src/control-flow/while-expressions.md @@ -1,6 +1,7 @@ # `while` loops -The [`while` keyword](https://doc.rust-lang.org/reference/expressions/loop-expr.html#predicate-loops) +The +[`while` keyword](https://doc.rust-lang.org/reference/expressions/loop-expr.html#predicate-loops) works very similar to other languages: ```rust,editable @@ -16,4 +17,3 @@ fn main() { println!("Final x: {x}"); } ``` - diff --git a/src/control-flow/while-let-expressions.md b/src/control-flow/while-let-expressions.md index a93883c9b134..e8d194ec9320 100644 --- a/src/control-flow/while-let-expressions.md +++ b/src/control-flow/while-let-expressions.md @@ -1,6 +1,7 @@ # `while let` loops -Like with `if let`, there is a [`while let`](https://doc.rust-lang.org/reference/expressions/loop-expr.html#predicate-pattern-loops) +Like with `if let`, there is a +[`while let`](https://doc.rust-lang.org/reference/expressions/loop-expr.html#predicate-pattern-loops) variant which repeatedly tests a value against a pattern: ```rust,editable @@ -14,16 +15,19 @@ fn main() { } ``` -Here the iterator returned by `v.into_iter()` will return a `Option` on every -call to `next()`. It returns `Some(x)` until it is done, after which it will -return `None`. The `while let` lets us keep iterating through all items. +Here the iterator returned by `v.into_iter()` will return a `Option` on +every call to `next()`. It returns `Some(x)` until it is done, after which it +will return `None`. The `while let` lets us keep iterating through all items. See [pattern matching](../pattern-matching.md) for more details on patterns in Rust.
-* Point out that the `while let` loop will keep going as long as the value matches the pattern. -* You could rewrite the `while let` loop as an infinite loop with an if statement that breaks when there is no value to unwrap for `iter.next()`. The `while let` provides syntactic sugar for the above scenario. - +- Point out that the `while let` loop will keep going as long as the value + matches the pattern. +- You could rewrite the `while let` loop as an infinite loop with an if + statement that breaks when there is no value to unwrap for `iter.next()`. The + `while let` provides syntactic sugar for the above scenario. +
diff --git a/src/credits.md b/src/credits.md index 99475f0bdc42..8b9568e02ccb 100644 --- a/src/credits.md +++ b/src/credits.md @@ -11,15 +11,15 @@ details. ## Rust by Example -Some examples and exercises have been copied and adapted from [Rust by -Example](https://doc.rust-lang.org/rust-by-example/). Please see the +Some examples and exercises have been copied and adapted from +[Rust by Example](https://doc.rust-lang.org/rust-by-example/). Please see the `third_party/rust-by-example/` directory for details, including the license terms. ## Rust on Exercism -Some exercises have been copied and adapted from [Rust on -Exercism](https://exercism.org/tracks/rust). Please see the +Some exercises have been copied and adapted from +[Rust on Exercism](https://exercism.org/tracks/rust). Please see the `third_party/rust-on-exercism/` directory for details, including the license terms. diff --git a/src/enums.md b/src/enums.md index ed59fdd4e0e4..4ec886cc0527 100644 --- a/src/enums.md +++ b/src/enums.md @@ -1,7 +1,7 @@ # Enums -The `enum` keyword allows the creation of a type which has a few -different variants: +The `enum` keyword allows the creation of a type which has a few different +variants: ```rust,editable fn generate_random_number() -> i32 { @@ -30,13 +30,18 @@ fn main() { ```
- + Key Points: -* Enumerations allow you to collect a set of values under one type -* This page offers an enum type `CoinFlip` with two variants `Heads` and `Tails`. You might note the namespace when using variants. -* This might be a good time to compare Structs and Enums: - * In both, you can have a simple version without fields (unit struct) or one with different types of fields (variant payloads). - * In both, associated functions are defined within an `impl` block. - * You could even implement the different variants of an enum with separate structs but then they wouldn’t be the same type as they would if they were all defined in an enum. +- Enumerations allow you to collect a set of values under one type +- This page offers an enum type `CoinFlip` with two variants `Heads` and + `Tails`. You might note the namespace when using variants. +- This might be a good time to compare Structs and Enums: + - In both, you can have a simple version without fields (unit struct) or one + with different types of fields (variant payloads). + - In both, associated functions are defined within an `impl` block. + - You could even implement the different variants of an enum with separate + structs but then they wouldn’t be the same type as they would if they were + all defined in an enum. +
diff --git a/src/enums/sizes.md b/src/enums/sizes.md index 1c94b0bd68f4..5c03ed861935 100644 --- a/src/enums/sizes.md +++ b/src/enums/sizes.md @@ -21,134 +21,139 @@ fn main() { } ``` -* See the [Rust Reference](https://doc.rust-lang.org/reference/type-layout.html). +- See the + [Rust Reference](https://doc.rust-lang.org/reference/type-layout.html).
- + Key Points: - * Internally Rust is using a field (discriminant) to keep track of the enum variant. - - * You can control the discriminant if needed (e.g., for compatibility with C): - - ```rust,editable - #[repr(u32)] - enum Bar { - A, // 0 - B = 10000, - C, // 10001 - } - - fn main() { - println!("A: {}", Bar::A as u32); - println!("B: {}", Bar::B as u32); - println!("C: {}", Bar::C as u32); - } - ``` - - Without `repr`, the discriminant type takes 2 bytes, because 10001 fits 2 - bytes. - - - * Try out other types such as - - * `dbg_size!(bool)`: size 1 bytes, align: 1 bytes, - * `dbg_size!(Option)`: size 1 bytes, align: 1 bytes (niche optimization, see below), - * `dbg_size!(&i32)`: size 8 bytes, align: 8 bytes (on a 64-bit machine), - * `dbg_size!(Option<&i32>)`: size 8 bytes, align: 8 bytes (null pointer optimization, see below). - - * Niche optimization: Rust will merge unused bit patterns for the enum - discriminant. - - * Null pointer optimization: For [some - types](https://doc.rust-lang.org/std/option/#representation), Rust guarantees - that `size_of::()` equals `size_of::>()`. - - Example code if you want to show how the bitwise representation *may* look like in practice. - It's important to note that the compiler provides no guarantees regarding this representation, therefore this is totally unsafe. - - ```rust,editable - use std::mem::transmute; - - macro_rules! dbg_bits { - ($e:expr, $bit_type:ty) => { - println!("- {}: {:#x}", stringify!($e), transmute::<_, $bit_type>($e)); - }; - } - - fn main() { - // TOTALLY UNSAFE. Rust provides no guarantees about the bitwise - // representation of types. - unsafe { - println!("Bitwise representation of bool"); - dbg_bits!(false, u8); - dbg_bits!(true, u8); - - println!("Bitwise representation of Option"); - dbg_bits!(None::, u8); - dbg_bits!(Some(false), u8); - dbg_bits!(Some(true), u8); - - println!("Bitwise representation of Option>"); - dbg_bits!(Some(Some(false)), u8); - dbg_bits!(Some(Some(true)), u8); - dbg_bits!(Some(None::), u8); - dbg_bits!(None::>, u8); - - println!("Bitwise representation of Option<&i32>"); - dbg_bits!(None::<&i32>, usize); - dbg_bits!(Some(&0i32), usize); - } - } - ``` - - More complex example if you want to discuss what happens when we chain more than 256 `Option`s together. - - ```rust,editable - #![recursion_limit = "1000"] - - use std::mem::transmute; - - macro_rules! dbg_bits { - ($e:expr, $bit_type:ty) => { - println!("- {}: {:#x}", stringify!($e), transmute::<_, $bit_type>($e)); - }; - } - - // Macro to wrap a value in 2^n Some() where n is the number of "@" signs. - // Increasing the recursion limit is required to evaluate this macro. - macro_rules! many_options { - ($value:expr) => { Some($value) }; - ($value:expr, @) => { - Some(Some($value)) - }; - ($value:expr, @ $($more:tt)+) => { - many_options!(many_options!($value, $($more)+), $($more)+) - }; - } - - fn main() { - // TOTALLY UNSAFE. Rust provides no guarantees about the bitwise - // representation of types. - unsafe { - assert_eq!(many_options!(false), Some(false)); - assert_eq!(many_options!(false, @), Some(Some(false))); - assert_eq!(many_options!(false, @@), Some(Some(Some(Some(false))))); - - println!("Bitwise representation of a chain of 128 Option's."); - dbg_bits!(many_options!(false, @@@@@@@), u8); - dbg_bits!(many_options!(true, @@@@@@@), u8); - - println!("Bitwise representation of a chain of 256 Option's."); - dbg_bits!(many_options!(false, @@@@@@@@), u16); - dbg_bits!(many_options!(true, @@@@@@@@), u16); - - println!("Bitwise representation of a chain of 257 Option's."); - dbg_bits!(many_options!(Some(false), @@@@@@@@), u16); - dbg_bits!(many_options!(Some(true), @@@@@@@@), u16); - dbg_bits!(many_options!(None::, @@@@@@@@), u16); - } - } - ``` +- Internally Rust is using a field (discriminant) to keep track of the enum + variant. + +- You can control the discriminant if needed (e.g., for compatibility with C): + + ```rust,editable + #[repr(u32)] + enum Bar { + A, // 0 + B = 10000, + C, // 10001 + } + + fn main() { + println!("A: {}", Bar::A as u32); + println!("B: {}", Bar::B as u32); + println!("C: {}", Bar::C as u32); + } + ``` + + Without `repr`, the discriminant type takes 2 bytes, because 10001 fits 2 + bytes. + +- Try out other types such as + + - `dbg_size!(bool)`: size 1 bytes, align: 1 bytes, + - `dbg_size!(Option)`: size 1 bytes, align: 1 bytes (niche optimization, + see below), + - `dbg_size!(&i32)`: size 8 bytes, align: 8 bytes (on a 64-bit machine), + - `dbg_size!(Option<&i32>)`: size 8 bytes, align: 8 bytes (null pointer + optimization, see below). + +- Niche optimization: Rust will merge unused bit patterns for the enum + discriminant. + +- Null pointer optimization: For + [some types](https://doc.rust-lang.org/std/option/#representation), Rust + guarantees that `size_of::()` equals `size_of::>()`. + + Example code if you want to show how the bitwise representation _may_ look + like in practice. It's important to note that the compiler provides no + guarantees regarding this representation, therefore this is totally unsafe. + + ```rust,editable + use std::mem::transmute; + + macro_rules! dbg_bits { + ($e:expr, $bit_type:ty) => { + println!("- {}: {:#x}", stringify!($e), transmute::<_, $bit_type>($e)); + }; + } + + fn main() { + // TOTALLY UNSAFE. Rust provides no guarantees about the bitwise + // representation of types. + unsafe { + println!("Bitwise representation of bool"); + dbg_bits!(false, u8); + dbg_bits!(true, u8); + + println!("Bitwise representation of Option"); + dbg_bits!(None::, u8); + dbg_bits!(Some(false), u8); + dbg_bits!(Some(true), u8); + + println!("Bitwise representation of Option>"); + dbg_bits!(Some(Some(false)), u8); + dbg_bits!(Some(Some(true)), u8); + dbg_bits!(Some(None::), u8); + dbg_bits!(None::>, u8); + + println!("Bitwise representation of Option<&i32>"); + dbg_bits!(None::<&i32>, usize); + dbg_bits!(Some(&0i32), usize); + } + } + ``` + + More complex example if you want to discuss what happens when we chain more + than 256 `Option`s together. + + ```rust,editable + #![recursion_limit = "1000"] + + use std::mem::transmute; + + macro_rules! dbg_bits { + ($e:expr, $bit_type:ty) => { + println!("- {}: {:#x}", stringify!($e), transmute::<_, $bit_type>($e)); + }; + } + + // Macro to wrap a value in 2^n Some() where n is the number of "@" signs. + // Increasing the recursion limit is required to evaluate this macro. + macro_rules! many_options { + ($value:expr) => { Some($value) }; + ($value:expr, @) => { + Some(Some($value)) + }; + ($value:expr, @ $($more:tt)+) => { + many_options!(many_options!($value, $($more)+), $($more)+) + }; + } + + fn main() { + // TOTALLY UNSAFE. Rust provides no guarantees about the bitwise + // representation of types. + unsafe { + assert_eq!(many_options!(false), Some(false)); + assert_eq!(many_options!(false, @), Some(Some(false))); + assert_eq!(many_options!(false, @@), Some(Some(Some(Some(false))))); + + println!("Bitwise representation of a chain of 128 Option's."); + dbg_bits!(many_options!(false, @@@@@@@), u8); + dbg_bits!(many_options!(true, @@@@@@@), u8); + + println!("Bitwise representation of a chain of 256 Option's."); + dbg_bits!(many_options!(false, @@@@@@@@), u16); + dbg_bits!(many_options!(true, @@@@@@@@), u16); + + println!("Bitwise representation of a chain of 257 Option's."); + dbg_bits!(many_options!(Some(false), @@@@@@@@), u16); + dbg_bits!(many_options!(Some(true), @@@@@@@@), u16); + dbg_bits!(many_options!(None::, @@@@@@@@), u16); + } + } + ```
diff --git a/src/enums/variant-payloads.md b/src/enums/variant-payloads.md index 3c13565684b6..d3b6adb8d51e 100644 --- a/src/enums/variant-payloads.md +++ b/src/enums/variant-payloads.md @@ -9,14 +9,24 @@ You can define richer enums where the variants carry data. You can then use the
-* The values in the enum variants can only be accessed after being pattern matched. The pattern binds references to the fields in the "match arm" after the `=>`. - * The expression is matched against the patterns from top to bottom. There is no fall-through like in C or C++. - * The match expression has a value. The value is the last expression in the match arm which was executed. - * Starting from the top we look for what pattern matches the value then run the code following the arrow. Once we find a match, we stop. -* Demonstrate what happens when the search is inexhaustive. Note the advantage the Rust compiler provides by confirming when all cases are handled. -* `match` inspects a hidden discriminant field in the `enum`. -* It is possible to retrieve the discriminant by calling `std::mem::discriminant()` - * This is useful, for example, if implementing `PartialEq` for structs where comparing field values doesn't affect equality. -* `WebEvent::Click { ... }` is not exactly the same as `WebEvent::Click(Click)` with a top level `struct Click { ... }`. The inlined version cannot implement traits, for example. - +- The values in the enum variants can only be accessed after being pattern + matched. The pattern binds references to the fields in the "match arm" after + the `=>`. + - The expression is matched against the patterns from top to bottom. There is + no fall-through like in C or C++. + - The match expression has a value. The value is the last expression in the + match arm which was executed. + - Starting from the top we look for what pattern matches the value then run + the code following the arrow. Once we find a match, we stop. +- Demonstrate what happens when the search is inexhaustive. Note the advantage + the Rust compiler provides by confirming when all cases are handled. +- `match` inspects a hidden discriminant field in the `enum`. +- It is possible to retrieve the discriminant by calling + `std::mem::discriminant()` + - This is useful, for example, if implementing `PartialEq` for structs where + comparing field values doesn't affect equality. +- `WebEvent::Click { ... }` is not exactly the same as `WebEvent::Click(Click)` + with a top level `struct Click { ... }`. The inlined version cannot implement + traits, for example. +
diff --git a/src/error-handling.md b/src/error-handling.md index ed93e0b4f6b5..93f7d60a309d 100644 --- a/src/error-handling.md +++ b/src/error-handling.md @@ -2,6 +2,5 @@ Error handling in Rust is done using explicit control flow: -* Functions that can have errors list this in their return type, -* There are no exceptions. - +- Functions that can have errors list this in their return type, +- There are no exceptions. diff --git a/src/error-handling/converting-error-types-example.md b/src/error-handling/converting-error-types-example.md index 1e83b47013bc..2dc7f5c05724 100644 --- a/src/error-handling/converting-error-types-example.md +++ b/src/error-handling/converting-error-types-example.md @@ -49,13 +49,18 @@ fn main() { Key points: -* The `username` variable can be either `Ok(string)` or `Err(error)`. -* Use the `fs::write` call to test out the different scenarios: no file, empty file, file with username. +- The `username` variable can be either `Ok(string)` or `Err(error)`. +- Use the `fs::write` call to test out the different scenarios: no file, empty + file, file with username. -It is good practice for all error types that don't need to be `no_std` to implement `std::error::Error`, which requires `Debug` and `Display`. The `Error` crate for `core` is only available in [nightly](https://github.com/rust-lang/rust/issues/103765), so not fully `no_std` compatible yet. +It is good practice for all error types that don't need to be `no_std` to +implement `std::error::Error`, which requires `Debug` and `Display`. The `Error` +crate for `core` is only available in +[nightly](https://github.com/rust-lang/rust/issues/103765), so not fully +`no_std` compatible yet. -It's generally helpful for them to implement `Clone` and `Eq` too where possible, to make -life easier for tests and consumers of your library. In this case we can't easily do so, because -`io::Error` doesn't implement them. +It's generally helpful for them to implement `Clone` and `Eq` too where +possible, to make life easier for tests and consumers of your library. In this +case we can't easily do so, because `io::Error` doesn't implement them.
diff --git a/src/error-handling/converting-error-types.md b/src/error-handling/converting-error-types.md index 9e8b958183e8..b5c2a0cbba7f 100644 --- a/src/error-handling/converting-error-types.md +++ b/src/error-handling/converting-error-types.md @@ -1,6 +1,7 @@ # Converting Error Types -The effective expansion of `?` is a little more complicated than previously indicated: +The effective expansion of `?` is a little more complicated than previously +indicated: ```rust,ignore expression? diff --git a/src/error-handling/deriving-error-enums.md b/src/error-handling/deriving-error-enums.md index 1b18ae0f169c..4be1ab111f3b 100644 --- a/src/error-handling/deriving-error-enums.md +++ b/src/error-handling/deriving-error-enums.md @@ -36,9 +36,9 @@ fn main() {
-`thiserror`'s derive macro automatically implements `std::error::Error`, and optionally `Display` -(if the `#[error(...)]` attributes are provided) and `From` (if the `#[from]` attribute is added). -It also works for structs. +`thiserror`'s derive macro automatically implements `std::error::Error`, and +optionally `Display` (if the `#[error(...)]` attributes are provided) and `From` +(if the `#[from]` attribute is added). It also works for structs. It doesn't affect your public API, which makes it good for libraries. diff --git a/src/error-handling/dynamic-errors.md b/src/error-handling/dynamic-errors.md index dd5b0ae0c5fb..7da59aa786f8 100644 --- a/src/error-handling/dynamic-errors.md +++ b/src/error-handling/dynamic-errors.md @@ -1,7 +1,8 @@ # Dynamic Error Types -Sometimes we want to allow any type of error to be returned without writing our own enum covering -all the different possibilities. `std::error::Error` makes this easy. +Sometimes we want to allow any type of error to be returned without writing our +own enum covering all the different possibilities. `std::error::Error` makes +this easy. ```rust,editable,compile_fail use std::fs; @@ -33,9 +34,9 @@ fn main() {
-This saves on code, but gives up the ability to cleanly handle different error cases differently in -the program. As such it's generally not a good idea to use `Box` in the public API of a -library, but it can be a good option in a program where you just want to display the error message -somewhere. +This saves on code, but gives up the ability to cleanly handle different error +cases differently in the program. As such it's generally not a good idea to use +`Box` in the public API of a library, but it can be a good option in +a program where you just want to display the error message somewhere.
diff --git a/src/error-handling/error-contexts.md b/src/error-handling/error-contexts.md index 50fb59481115..09757c46a41a 100644 --- a/src/error-handling/error-contexts.md +++ b/src/error-handling/error-contexts.md @@ -1,8 +1,8 @@ # Adding Context to Errors The widely used [anyhow](https://docs.rs/anyhow/) crate can help you add -contextual information to your errors and allows you to have fewer -custom error types: +contextual information to your errors and allows you to have fewer custom error +types: ```rust,editable,compile_fail use std::{fs, io}; @@ -32,11 +32,13 @@ fn main() {
-* `anyhow::Result` is a type alias for `Result`. -* `anyhow::Error` is essentially a wrapper around `Box`. As such it's again generally not - a good choice for the public API of a library, but is widely used in applications. -* Actual error type inside of it can be extracted for examination if necessary. -* Functionality provided by `anyhow::Result` may be familiar to Go developers, as it provides - similar usage patterns and ergonomics to `(T, error)` from Go. +- `anyhow::Result` is a type alias for `Result`. +- `anyhow::Error` is essentially a wrapper around `Box`. As such it's + again generally not a good choice for the public API of a library, but is + widely used in applications. +- Actual error type inside of it can be extracted for examination if necessary. +- Functionality provided by `anyhow::Result` may be familiar to Go + developers, as it provides similar usage patterns and ergonomics to + `(T, error)` from Go.
diff --git a/src/error-handling/panic-unwind.md b/src/error-handling/panic-unwind.md index 2f5213e5f3ea..19be76d20701 100644 --- a/src/error-handling/panic-unwind.md +++ b/src/error-handling/panic-unwind.md @@ -18,6 +18,6 @@ fn main() { } ``` -* This can be useful in servers which should keep running even if a single +- This can be useful in servers which should keep running even if a single request crashes. -* This does not work if `panic = 'abort'` is set in your `Cargo.toml`. +- This does not work if `panic = 'abort'` is set in your `Cargo.toml`. diff --git a/src/error-handling/panics.md b/src/error-handling/panics.md index df91c63ffd3e..65f6392b7893 100644 --- a/src/error-handling/panics.md +++ b/src/error-handling/panics.md @@ -9,6 +9,6 @@ fn main() { } ``` -* Panics are for unrecoverable and unexpected errors. - * Panics are symptoms of bugs in the program. -* Use non-panicking APIs (such as `Vec::get`) if crashing is not acceptable. +- Panics are for unrecoverable and unexpected errors. + - Panics are symptoms of bugs in the program. +- Use non-panicking APIs (such as `Vec::get`) if crashing is not acceptable. diff --git a/src/error-handling/result.md b/src/error-handling/result.md index 88d163652c9f..849659ce9009 100644 --- a/src/error-handling/result.md +++ b/src/error-handling/result.md @@ -24,10 +24,12 @@ fn main() {
- * As with `Option`, the successful value sits inside of `Result`, forcing the developer to - explicitly extract it. This encourages error checking. In the case where an error should never happen, - `unwrap()` or `expect()` can be called, and this is a signal of the developer intent too. - * `Result` documentation is a recommended read. Not during the course, but it is worth mentioning. - It contains a lot of convenience methods and functions that help functional-style programming. - +- As with `Option`, the successful value sits inside of `Result`, forcing the + developer to explicitly extract it. This encourages error checking. In the + case where an error should never happen, `unwrap()` or `expect()` can be + called, and this is a signal of the developer intent too. +- `Result` documentation is a recommended read. Not during the course, but it is + worth mentioning. It contains a lot of convenience methods and functions that + help functional-style programming. +
diff --git a/src/error-handling/try-operator.md b/src/error-handling/try-operator.md index b7e91bbc4751..6278c07727c0 100644 --- a/src/error-handling/try-operator.md +++ b/src/error-handling/try-operator.md @@ -47,14 +47,18 @@ fn main() { Key points: -* The `username` variable can be either `Ok(string)` or `Err(error)`. -* Use the `fs::write` call to test out the different scenarios: no file, empty file, file with username. -* The return type of the function has to be compatible with the nested functions it calls. For instance, -a function returning a `Result` can only apply the `?` operator on a function returning a -`Result`. It cannot apply the `?` operator on a function returning an `Option` or `Result` -unless `OtherErr` implements `From`. Reciprocally, a function returning an `Option` can only apply the `?` operator -on a function returning an `Option`. - * You can convert incompatible types into one another with the different `Option` and `Result` methods - such as `Option::ok_or`, `Result::ok`, `Result::err`. +- The `username` variable can be either `Ok(string)` or `Err(error)`. +- Use the `fs::write` call to test out the different scenarios: no file, empty + file, file with username. +- The return type of the function has to be compatible with the nested functions + it calls. For instance, a function returning a `Result` can only apply + the `?` operator on a function returning a `Result`. It cannot + apply the `?` operator on a function returning an `Option` or + `Result` unless `OtherErr` implements `From`. Reciprocally, + a function returning an `Option` can only apply the `?` operator on a + function returning an `Option`. + - You can convert incompatible types into one another with the different + `Option` and `Result` methods such as `Option::ok_or`, `Result::ok`, + `Result::err`.
diff --git a/src/exercises/android/morning.md b/src/exercises/android/morning.md index b339b3bd10d6..026a278c8cc4 100644 --- a/src/exercises/android/morning.md +++ b/src/exercises/android/morning.md @@ -3,9 +3,9 @@ This is a group exercise: We will look at one of the projects you work with and try to integrate some Rust into it. Some suggestions: -* Call your AIDL service with a client written in Rust. +- Call your AIDL service with a client written in Rust. -* Move a function from your project to Rust and call it. +- Move a function from your project to Rust and call it.
diff --git a/src/exercises/bare-metal/compass.md b/src/exercises/bare-metal/compass.md index ec3e5cf3e6d2..4a1e2a455502 100644 --- a/src/exercises/bare-metal/compass.md +++ b/src/exercises/bare-metal/compass.md @@ -1,27 +1,30 @@ # Compass -We will read the direction from an I2C compass, and log the readings to a serial port. If you have -time, try displaying it on the LEDs somehow too, or use the buttons somehow. +We will read the direction from an I2C compass, and log the readings to a serial +port. If you have time, try displaying it on the LEDs somehow too, or use the +buttons somehow. Hints: -- Check the documentation for the [`lsm303agr`](https://docs.rs/lsm303agr/latest/lsm303agr/) and - [`microbit-v2`](https://docs.rs/microbit-v2/latest/microbit/) crates, as well as the - [micro:bit hardware](https://tech.microbit.org/hardware/). +- Check the documentation for the + [`lsm303agr`](https://docs.rs/lsm303agr/latest/lsm303agr/) and + [`microbit-v2`](https://docs.rs/microbit-v2/latest/microbit/) crates, as well + as the [micro:bit hardware](https://tech.microbit.org/hardware/). - The LSM303AGR Inertial Measurement Unit is connected to the internal I2C bus. - TWI is another name for I2C, so the I2C master peripheral is called TWIM. -- The LSM303AGR driver needs something implementing the `embedded_hal::blocking::i2c::WriteRead` - trait. The - [`microbit::hal::Twim`](https://docs.rs/microbit-v2/latest/microbit/hal/struct.Twim.html) struct - implements this. -- You have a [`microbit::Board`](https://docs.rs/microbit-v2/latest/microbit/struct.Board.html) +- The LSM303AGR driver needs something implementing the + `embedded_hal::blocking::i2c::WriteRead` trait. The + [`microbit::hal::Twim`](https://docs.rs/microbit-v2/latest/microbit/hal/struct.Twim.html) + struct implements this. +- You have a + [`microbit::Board`](https://docs.rs/microbit-v2/latest/microbit/struct.Board.html) struct with fields for the various pins and peripherals. - You can also look at the - [nRF52833 datasheet](https://infocenter.nordicsemi.com/pdf/nRF52833_PS_v1.5.pdf) if you want, but - it shouldn't be necessary for this exercise. + [nRF52833 datasheet](https://infocenter.nordicsemi.com/pdf/nRF52833_PS_v1.5.pdf) + if you want, but it shouldn't be necessary for this exercise. -Download the [exercise template](../../comprehensive-rust-exercises.zip) and look in the `compass` -directory for the following files. +Download the [exercise template](../../comprehensive-rust-exercises.zip) and +look in the `compass` directory for the following files. `src/main.rs`: diff --git a/src/exercises/bare-metal/morning.md b/src/exercises/bare-metal/morning.md index e4c01bc0b461..1549aaa6e317 100644 --- a/src/exercises/bare-metal/morning.md +++ b/src/exercises/bare-metal/morning.md @@ -1,6 +1,7 @@ # Exercises -We will read the direction from an I2C compass, and log the readings to a serial port. +We will read the direction from an I2C compass, and log the readings to a serial +port.
diff --git a/src/exercises/bare-metal/rtc.md b/src/exercises/bare-metal/rtc.md index 609f697a1baa..e84aa29b4bcf 100644 --- a/src/exercises/bare-metal/rtc.md +++ b/src/exercises/bare-metal/rtc.md @@ -1,20 +1,23 @@ # RTC driver -The QEMU aarch64 virt machine has a [PL031][1] real-time clock at 0x9010000. For this exercise, you -should write a driver for it. - -1. Use it to print the current time to the serial console. You can use the [`chrono`][2] crate for - date/time formatting. -2. Use the match register and raw interrupt status to busy-wait until a given time, e.g. 3 seconds - in the future. (Call [`core::hint::spin_loop`][3] inside the loop.) -3. _Extension if you have time:_ Enable and handle the interrupt generated by the RTC match. You can - use the driver provided in the [`arm-gic`][4] crate to configure the Arm Generic Interrupt Controller. +The QEMU aarch64 virt machine has a [PL031][1] real-time clock at 0x9010000. For +this exercise, you should write a driver for it. + +1. Use it to print the current time to the serial console. You can use the + [`chrono`][2] crate for date/time formatting. +2. Use the match register and raw interrupt status to busy-wait until a given + time, e.g. 3 seconds in the future. (Call [`core::hint::spin_loop`][3] inside + the loop.) +3. _Extension if you have time:_ Enable and handle the interrupt generated by + the RTC match. You can use the driver provided in the [`arm-gic`][4] crate to + configure the Arm Generic Interrupt Controller. - Use the RTC interrupt, which is wired to the GIC as `IntId::spi(2)`. - - Once the interrupt is enabled, you can put the core to sleep via `arm_gic::wfi()`, which will cause the core to sleep until it receives an interrupt. - + - Once the interrupt is enabled, you can put the core to sleep via + `arm_gic::wfi()`, which will cause the core to sleep until it receives an + interrupt. -Download the [exercise template](../../comprehensive-rust-exercises.zip) and look in the `rtc` -directory for the following files. +Download the [exercise template](../../comprehensive-rust-exercises.zip) and +look in the `rtc` directory for the following files. `src/main.rs`: @@ -34,7 +37,8 @@ directory for the following files. {{#include rtc/src/main.rs:main_end}} ``` -`src/exceptions.rs` (you should only need to change this for the 3rd part of the exercise): +`src/exceptions.rs` (you should only need to change this for the 3rd part of the +exercise): diff --git a/src/exercises/concurrency/afternoon.md b/src/exercises/concurrency/afternoon.md index 281c61e4d6ea..00a0fd189a66 100644 --- a/src/exercises/concurrency/afternoon.md +++ b/src/exercises/concurrency/afternoon.md @@ -2,10 +2,10 @@ To practice your Async Rust skills, we have again two exercises for you: -* Dining philosophers: we already saw this problem in the morning. This time - you are going to implement it with Async Rust. +- Dining philosophers: we already saw this problem in the morning. This time you + are going to implement it with Async Rust. -* A Broadcast Chat Application: this is a larger project that allows you +- A Broadcast Chat Application: this is a larger project that allows you experiment with more advanced Async Rust features.
diff --git a/src/exercises/concurrency/chat-app.md b/src/exercises/concurrency/chat-app.md index 5a0e75164e13..d39dc7ce16be 100644 --- a/src/exercises/concurrency/chat-app.md +++ b/src/exercises/concurrency/chat-app.md @@ -1,14 +1,13 @@ # Broadcast Chat Application -In this exercise, we want to use our new knowledge to implement a broadcast -chat application. We have a chat server that the clients connect to and publish -their messages. The client reads user messages from the standard input, and -sends them to the server. The chat server broadcasts each message that it -receives to all the clients. +In this exercise, we want to use our new knowledge to implement a broadcast chat +application. We have a chat server that the clients connect to and publish their +messages. The client reads user messages from the standard input, and sends them +to the server. The chat server broadcasts each message that it receives to all +the clients. For this, we use [a broadcast channel][1] on the server, and -[`tokio_websockets`][2] for the communication between the client and the -server. +[`tokio_websockets`][2] for the communication between the client and the server. Create a new Cargo project and add the following dependencies: @@ -21,31 +20,31 @@ Create a new Cargo project and add the following dependencies: ``` ## The required APIs + You are going to need the following functions from `tokio` and [`tokio_websockets`][2]. Spend a few minutes to familiarize yourself with the -API. +API. - [WebsocketStream::next()][3]: for asynchronously reading messages from a Websocket Stream. - [SinkExt::send()][4] implemented by `WebsocketStream`: for asynchronously sending messages on a Websocket Stream. -- [Lines::next_line()][5]: for asynchronously reading user messages - from the standard input. +- [Lines::next_line()][5]: for asynchronously reading user messages from the + standard input. - [Sender::subscribe()][6]: for subscribing to a broadcast channel. - ## Two binaries -Normally in a Cargo project, you can have only one binary, and one -`src/main.rs` file. In this project, we need two binaries. One for the client, -and one for the server. You could potentially make them two separate Cargo -projects, but we are going to put them in a single Cargo project with two -binaries. For this to work, the client and the server code should go under -`src/bin` (see the [documentation][7]). +Normally in a Cargo project, you can have only one binary, and one `src/main.rs` +file. In this project, we need two binaries. One for the client, and one for the +server. You could potentially make them two separate Cargo projects, but we are +going to put them in a single Cargo project with two binaries. For this to work, +the client and the server code should go under `src/bin` (see the +[documentation][7]). Copy the following server and client code into `src/bin/server.rs` and `src/bin/client.rs`, respectively. Your task is to complete these files as -described below. +described below. `src/bin/server.rs`: @@ -74,6 +73,7 @@ described below. ``` ## Running the binaries + Run the server with: ```shell @@ -88,16 +88,16 @@ cargo run --bin client ## Tasks -* Implement the `handle_connection` function in `src/bin/server.rs`. - * Hint: Use `tokio::select!` for concurrently performing two tasks in a +- Implement the `handle_connection` function in `src/bin/server.rs`. + - Hint: Use `tokio::select!` for concurrently performing two tasks in a continuous loop. One task receives messages from the client and broadcasts them. The other sends messages received by the server to the client. -* Complete the main function in `src/bin/client.rs`. - * Hint: As before, use `tokio::select!` in a continuous loop for concurrently +- Complete the main function in `src/bin/client.rs`. + - Hint: As before, use `tokio::select!` in a continuous loop for concurrently performing two tasks: (1) reading user messages from standard input and sending them to the server, and (2) receiving messages from the server, and displaying them for the user. -* Optional: Once you are done, change the code to broadcast messages to all +- Optional: Once you are done, change the code to broadcast messages to all clients, but the sender of the message. [1]: https://docs.rs/tokio/latest/tokio/sync/broadcast/fn.channel.html diff --git a/src/exercises/concurrency/dining-philosophers-async.md b/src/exercises/concurrency/dining-philosophers-async.md index 611c1c93616d..fe70f1fc0a63 100644 --- a/src/exercises/concurrency/dining-philosophers-async.md +++ b/src/exercises/concurrency/dining-philosophers-async.md @@ -4,9 +4,9 @@ See [dining philosophers](dining-philosophers.md) for a description of the problem. As before, you will need a local -[Cargo installation](../../cargo/running-locally.md) for this exercise. Copy -the code below to a file called `src/main.rs`, fill out the blanks, and test -that `cargo run` does not deadlock: +[Cargo installation](../../cargo/running-locally.md) for this exercise. Copy the +code below to a file called `src/main.rs`, fill out the blanks, and test that +`cargo run` does not deadlock: @@ -32,8 +32,8 @@ that `cargo run` does not deadlock: } ``` -Since this time you are using Async Rust, you'll need a `tokio` dependency. -You can use the following `Cargo.toml`: +Since this time you are using Async Rust, you'll need a `tokio` dependency. You +can use the following `Cargo.toml`: @@ -44,14 +44,14 @@ version = "0.1.0" edition = "2021" [dependencies] -tokio = {version = "1.26.0", features = ["sync", "time", "macros", "rt-multi-thread"]} +tokio = { version = "1.26.0", features = ["sync", "time", "macros", "rt-multi-thread"] } ``` -Also note that this time you have to use the `Mutex` and the `mpsc` module -from the `tokio` crate. +Also note that this time you have to use the `Mutex` and the `mpsc` module from +the `tokio` crate.
-* Can you make your implementation single-threaded? +- Can you make your implementation single-threaded?
diff --git a/src/exercises/concurrency/link-checker.md b/src/exercises/concurrency/link-checker.md index a5ba6ab488b8..de7e953089e9 100644 --- a/src/exercises/concurrency/link-checker.md +++ b/src/exercises/concurrency/link-checker.md @@ -78,9 +78,9 @@ cargo run ## Tasks -* Use threads to check the links in parallel: send the URLs to be checked to a +- Use threads to check the links in parallel: send the URLs to be checked to a channel and let a few threads check the URLs in parallel. -* Extend this to recursively extract links from all pages on the +- Extend this to recursively extract links from all pages on the `www.google.org` domain. Put an upper limit of 100 pages or so so that you don't end up being blocked by the site. diff --git a/src/exercises/concurrency/morning.md b/src/exercises/concurrency/morning.md index 039f1056dc72..313c733665ce 100644 --- a/src/exercises/concurrency/morning.md +++ b/src/exercises/concurrency/morning.md @@ -2,9 +2,9 @@ Let us practice our new concurrency skills with -* Dining philosophers: a classic problem in concurrency. +- Dining philosophers: a classic problem in concurrency. -* Multi-threaded link checker: a larger project where you'll use Cargo to +- Multi-threaded link checker: a larger project where you'll use Cargo to download dependencies and then check links in parallel.
diff --git a/src/exercises/concurrency/solutions-afternoon.md b/src/exercises/concurrency/solutions-afternoon.md index 3ccf76b8911e..4f35fffdda5a 100644 --- a/src/exercises/concurrency/solutions-afternoon.md +++ b/src/exercises/concurrency/solutions-afternoon.md @@ -23,4 +23,3 @@ ```rust,compile_fail {{#include chat-async/src/bin/client.rs}} ``` - diff --git a/src/exercises/day-1/afternoon.md b/src/exercises/day-1/afternoon.md index 31e2f66e5df6..85ad5f88fc66 100644 --- a/src/exercises/day-1/afternoon.md +++ b/src/exercises/day-1/afternoon.md @@ -2,9 +2,9 @@ We will look at two things: -* The Luhn algorithm, +- The Luhn algorithm, -* An exercise on pattern matching. +- An exercise on pattern matching.
diff --git a/src/exercises/day-1/for-loops.md b/src/exercises/day-1/for-loops.md index de45c3195ad0..d8fa10882943 100644 --- a/src/exercises/day-1/for-loops.md +++ b/src/exercises/day-1/for-loops.md @@ -70,23 +70,22 @@ Could you use `&[i32]` slices instead of hard-coded 3 × 3 matrices for your argument and return types? Something like `&[&[i32]]` for a two-dimensional slice-of-slices. Why or why not? - See the [`ndarray` crate](https://docs.rs/ndarray/) for a production quality implementation.
-The solution and the answer to the bonus section are available in the +The solution and the answer to the bonus section are available in the [Solution](solutions-morning.md#arrays-and-for-loops) section. -The use of the reference `&array` within `for n in &array` is a subtle -preview of issues of ownership that will come later in the afternoon. +The use of the reference `&array` within `for n in &array` is a subtle preview +of issues of ownership that will come later in the afternoon. Without the `&`... -* The loop would have been one that consumes the array. This is a - change [introduced in the 2021 - Edition](https://doc.rust-lang.org/edition-guide/rust-2021/IntoIterator-for-arrays.html). -* An implicit array copy would have occured. Since `i32` is a copy type, then + +- The loop would have been one that consumes the array. This is a change + [introduced in the 2021 Edition](https://doc.rust-lang.org/edition-guide/rust-2021/IntoIterator-for-arrays.html). +- An implicit array copy would have occured. Since `i32` is a copy type, then `[i32; 3]` is also a copy type.
diff --git a/src/exercises/day-1/implicit-conversions.md b/src/exercises/day-1/implicit-conversions.md index c2fe972ac54c..c37251ab6f4a 100644 --- a/src/exercises/day-1/implicit-conversions.md +++ b/src/exercises/day-1/implicit-conversions.md @@ -1,7 +1,7 @@ # Implicit Conversions -Rust will not automatically apply _implicit conversions_ between types ([unlike -C++][3]). You can see this in a program like this: +Rust will not automatically apply _implicit conversions_ between types +([unlike C++][3]). You can see this in a program like this: ```rust,editable,compile_fail fn multiply(x: i16, y: i16) -> i16 { @@ -23,12 +23,13 @@ Implementing these traits is how a type expresses that it can be converted into another type. The standard library has an implementation of `From for i16`, which means -that we can convert a variable `x` of type `i8` to an `i16` by calling +that we can convert a variable `x` of type `i8` to an `i16` by calling `i16::from(x)`. Or, simpler, with `x.into()`, because `From for i16` implementation automatically create an implementation of `Into for i8`. -The same applies for your own `From` implementations for your own types, so it is -sufficient to only implement `From` to get a respective `Into` implementation automatically. +The same applies for your own `From` implementations for your own types, so it +is sufficient to only implement `From` to get a respective `Into` implementation +automatically. 1. Execute the above program and look at the compiler error. diff --git a/src/exercises/day-1/luhn.md b/src/exercises/day-1/luhn.md index ca8a49e8b32f..e02f556bde44 100644 --- a/src/exercises/day-1/luhn.md +++ b/src/exercises/day-1/luhn.md @@ -4,24 +4,23 @@ The [Luhn algorithm](https://en.wikipedia.org/wiki/Luhn_algorithm) is used to validate credit card numbers. The algorithm takes a string as input and does the following to validate the credit card number: -* Ignore all spaces. Reject number with less than two digits. +- Ignore all spaces. Reject number with less than two digits. -* Moving from **right to left**, double every second digit: for the number `1234`, - we double `3` and `1`. For the number `98765`, we double `6` and `8`. +- Moving from **right to left**, double every second digit: for the number + `1234`, we double `3` and `1`. For the number `98765`, we double `6` and `8`. -* After doubling a digit, sum the digits. So doubling `7` becomes `14` which +- After doubling a digit, sum the digits. So doubling `7` becomes `14` which becomes `5`. -* Sum all the undoubled and doubled digits. +- Sum all the undoubled and doubled digits. -* The credit card number is valid if the sum ends with `0`. +- The credit card number is valid if the sum ends with `0`. Copy the code below to and implement the function. Try to solve the problem the "simple" way first, using `for` loops and integers. Then, revisit the solution and try to implement it with iterators. - ```rust // TODO: remove this when you're done with your implementation. #![allow(unused_variables, dead_code)] diff --git a/src/exercises/day-1/morning.md b/src/exercises/day-1/morning.md index bbda973d094a..fa455339ec06 100644 --- a/src/exercises/day-1/morning.md +++ b/src/exercises/day-1/morning.md @@ -2,19 +2,19 @@ In these exercises, we will explore two parts of Rust: -* Implicit conversions between types. +- Implicit conversions between types. -* Arrays and `for` loops. +- Arrays and `for` loops.
A few things to consider while solving the exercises: -* Use a local Rust installation, if possible. This way you can get +- Use a local Rust installation, if possible. This way you can get auto-completion in your editor. See the page about [Using Cargo] for details on installing Rust. -* Alternatively, use the Rust Playground. +- Alternatively, use the Rust Playground. The code snippets are not editable on purpose: the inline code snippets lose their state if you navigate away from the page. @@ -22,7 +22,6 @@ their state if you navigate away from the page. After looking at the exercises, you can look at the [solutions] provided. [solutions]: solutions-morning.md - [Using Cargo]: ../../cargo.md
diff --git a/src/exercises/day-1/solutions-morning.md b/src/exercises/day-1/solutions-morning.md index 6b218a649520..bc730641ab27 100644 --- a/src/exercises/day-1/solutions-morning.md +++ b/src/exercises/day-1/solutions-morning.md @@ -7,13 +7,21 @@ ```rust {{#include for-loops.rs}} ``` + ### Bonus question -It requires more advanced concepts. It might seem that we could use a slice-of-slices (`&[&[i32]]`) as the input type to transpose and thus make our function handle any size of matrix. However, this quickly breaks down: the return type cannot be `&[&[i32]]` since it needs to own the data you return. +It requires more advanced concepts. It might seem that we could use a +slice-of-slices (`&[&[i32]]`) as the input type to transpose and thus make our +function handle any size of matrix. However, this quickly breaks down: the +return type cannot be `&[&[i32]]` since it needs to own the data you return. -You can attempt to use something like `Vec>`, but this doesn't work out-of-the-box either: it's hard to convert from `Vec>` to `&[&[i32]]` so now you cannot easily use `pretty_print` either. +You can attempt to use something like `Vec>`, but this doesn't work +out-of-the-box either: it's hard to convert from `Vec>` to `&[&[i32]]` +so now you cannot easily use `pretty_print` either. -Once we get to traits and generics, we'll be able to use the [`std::convert::AsRef`][1] trait to abstract over anything that can be referenced as a slice. +Once we get to traits and generics, we'll be able to use the +[`std::convert::AsRef`][1] trait to abstract over anything that can be +referenced as a slice. ```rust use std::convert::AsRef; @@ -42,6 +50,7 @@ fn main() { } ``` -In addition, the type itself would not enforce that the child slices are of the same length, so such variable could contain an invalid matrix. +In addition, the type itself would not enforce that the child slices are of the +same length, so such variable could contain an invalid matrix. [1]: https://doc.rust-lang.org/std/convert/trait.AsRef.html diff --git a/src/exercises/day-2/book-library.md b/src/exercises/day-2/book-library.md index 23954e9a39f9..fa76978f616a 100644 --- a/src/exercises/day-2/book-library.md +++ b/src/exercises/day-2/book-library.md @@ -39,7 +39,7 @@ Use this to model a library's book collection. Copy the code below to ```
- + [Solution](solutions-afternoon.md#designing-a-library)
diff --git a/src/exercises/day-2/iterators-and-ownership.md b/src/exercises/day-2/iterators-and-ownership.md index 8dda0575d4a5..1b58ceab0c21 100644 --- a/src/exercises/day-2/iterators-and-ownership.md +++ b/src/exercises/day-2/iterators-and-ownership.md @@ -59,16 +59,16 @@ pub trait IntoIterator { } ``` -The syntax here means that every implementation of `IntoIterator` must -declare two types: +The syntax here means that every implementation of `IntoIterator` must declare +two types: -* `Item`: the type we iterate over, such as `i8`, -* `IntoIter`: the `Iterator` type returned by the `into_iter` method. +- `Item`: the type we iterate over, such as `i8`, +- `IntoIter`: the `Iterator` type returned by the `into_iter` method. Note that `IntoIter` and `Item` are linked: the iterator must have the same `Item` type, which means that it returns `Option` -Like before, what is the type returned by the iterator? +Like before, what is the type returned by the iterator? ```rust,editable,compile_fail fn main() { @@ -102,9 +102,8 @@ fn main() { What is the type of `word` in each loop? -Experiment with the code above and then consult the documentation for [`impl -IntoIterator for -&Vec`](https://doc.rust-lang.org/std/vec/struct.Vec.html#impl-IntoIterator-for-%26'a+Vec%3CT,+A%3E) -and [`impl IntoIterator for -Vec`](https://doc.rust-lang.org/std/vec/struct.Vec.html#impl-IntoIterator-for-Vec%3CT,+A%3E) +Experiment with the code above and then consult the documentation for +[`impl IntoIterator for &Vec`](https://doc.rust-lang.org/std/vec/struct.Vec.html#impl-IntoIterator-for-%26'a+Vec%3CT,+A%3E) +and +[`impl IntoIterator for Vec`](https://doc.rust-lang.org/std/vec/struct.Vec.html#impl-IntoIterator-for-Vec%3CT,+A%3E) to check your answers. diff --git a/src/exercises/day-2/morning.md b/src/exercises/day-2/morning.md index e31cce6a1674..504e13b61f1e 100644 --- a/src/exercises/day-2/morning.md +++ b/src/exercises/day-2/morning.md @@ -2,9 +2,9 @@ We will look at implementing methods in two contexts: -* Storing books and querying the collection +- Storing books and querying the collection -* Keeping track of health statistics for patients +- Keeping track of health statistics for patients
diff --git a/src/exercises/day-2/strings-iterators.md b/src/exercises/day-2/strings-iterators.md index fd92acdf9808..e7c8f184dcf3 100644 --- a/src/exercises/day-2/strings-iterators.md +++ b/src/exercises/day-2/strings-iterators.md @@ -8,7 +8,6 @@ matches a full segment. See the unit tests below. Copy the following code to and make the tests pass. Try avoiding allocating a `Vec` for your intermediate results: - ```rust // TODO: remove this when you're done with your implementation. #![allow(unused_variables, dead_code)] diff --git a/src/exercises/day-3/afternoon.md b/src/exercises/day-3/afternoon.md index 0cb403408b8a..bf72e006b357 100644 --- a/src/exercises/day-3/afternoon.md +++ b/src/exercises/day-3/afternoon.md @@ -2,8 +2,8 @@ Let us build a safe wrapper for reading directory content! -For this exercise, we suggest using a local dev environment instead -of the Playground. This will allow you to run your binary on your own machine. +For this exercise, we suggest using a local dev environment instead of the +Playground. This will allow you to run your binary on your own machine. To get started, follow the [running locally] instructions. diff --git a/src/exercises/day-3/morning.md b/src/exercises/day-3/morning.md index 974ec1534583..4ef5284b24f7 100644 --- a/src/exercises/day-3/morning.md +++ b/src/exercises/day-3/morning.md @@ -2,7 +2,8 @@ We will design a classical GUI library using traits and trait objects. -We will also look at enum dispatch with an exercise involving points and polygons. +We will also look at enum dispatch with an exercise involving points and +polygons.
diff --git a/src/exercises/day-3/points-polygons.md b/src/exercises/day-3/points-polygons.md index 73bfe9e5a375..8afbd3f9af59 100644 --- a/src/exercises/day-3/points-polygons.md +++ b/src/exercises/day-3/points-polygons.md @@ -42,12 +42,15 @@ fn main() {}
-Since the method signatures are missing from the problem statements, the key part -of the exercise is to specify those correctly. You don't have to modify the tests. +Since the method signatures are missing from the problem statements, the key +part of the exercise is to specify those correctly. You don't have to modify the +tests. Other interesting parts of the exercise: - -* Derive a `Copy` trait for some structs, as in tests the methods sometimes don't borrow their arguments. -* Discover that `Add` trait must be implemented for two objects to be addable via "+". Note that we do not discuss generics until Day 3. + +- Derive a `Copy` trait for some structs, as in tests the methods sometimes + don't borrow their arguments. +- Discover that `Add` trait must be implemented for two objects to be addable + via "+". Note that we do not discuss generics until Day 3.
diff --git a/src/exercises/day-3/safe-ffi-wrapper.md b/src/exercises/day-3/safe-ffi-wrapper.md index 9ee5bd5e5a65..5a3f04a21d2f 100644 --- a/src/exercises/day-3/safe-ffi-wrapper.md +++ b/src/exercises/day-3/safe-ffi-wrapper.md @@ -6,15 +6,15 @@ functions you would use from C to read the filenames of a directory. You will want to consult the manual pages: -* [`opendir(3)`](https://man7.org/linux/man-pages/man3/opendir.3.html) -* [`readdir(3)`](https://man7.org/linux/man-pages/man3/readdir.3.html) -* [`closedir(3)`](https://man7.org/linux/man-pages/man3/closedir.3.html) +- [`opendir(3)`](https://man7.org/linux/man-pages/man3/opendir.3.html) +- [`readdir(3)`](https://man7.org/linux/man-pages/man3/readdir.3.html) +- [`closedir(3)`](https://man7.org/linux/man-pages/man3/closedir.3.html) You will also want to browse the [`std::ffi`] module. There you find a number of string types which you need for the exercise: | Types | Encoding | Use | -|----------------------------|----------------|--------------------------------| +| -------------------------- | -------------- | ------------------------------ | | [`str`] and [`String`] | UTF-8 | Text processing in Rust | | [`CStr`] and [`CString`] | NUL-terminated | Communicating with C functions | | [`OsStr`] and [`OsString`] | OS-specific | Communicating with the OS | @@ -23,13 +23,15 @@ You will convert between all these types: - `&str` to `CString`: you need to allocate space for a trailing `\0` character, - `CString` to `*const i8`: you need a pointer to call C functions, -- `*const i8` to `&CStr`: you need something which can find the trailing `\0` character, -- `&CStr` to `&[u8]`: a slice of bytes is the universal interface for "some unknow data", +- `*const i8` to `&CStr`: you need something which can find the trailing `\0` + character, +- `&CStr` to `&[u8]`: a slice of bytes is the universal interface for "some + unknow data", - `&[u8]` to `&OsStr`: `&OsStr` is a step towards `OsString`, use - [`OsStrExt`](https://doc.rust-lang.org/std/os/unix/ffi/trait.OsStrExt.html) - to create it, -- `&OsStr` to `OsString`: you need to clone the data in `&OsStr` to be able to return it and call - `readdir` again. + [`OsStrExt`](https://doc.rust-lang.org/std/os/unix/ffi/trait.OsStrExt.html) to + create it, +- `&OsStr` to `OsString`: you need to clone the data in `&OsStr` to be able to + return it and call `readdir` again. The [Nomicon] also has a very useful chapter about FFI. diff --git a/src/exercises/day-3/simple-gui.md b/src/exercises/day-3/simple-gui.md index 2d35ef150e12..e514f6732aee 100644 --- a/src/exercises/day-3/simple-gui.md +++ b/src/exercises/day-3/simple-gui.md @@ -5,10 +5,10 @@ trait objects. We will have a number of widgets in our library: -* `Window`: has a `title` and contains other widgets. -* `Button`: has a `label` and a callback function which is invoked when the +- `Window`: has a `title` and contains other widgets. +- `Button`: has a `label` and a callback function which is invoked when the button is pressed. -* `Label`: has a `label`. +- `Label`: has a `label`. The widgets will implement a `Widget` trait, see below. diff --git a/src/exercises/solutions.md b/src/exercises/solutions.md index 333eb92dffac..c8569c18de93 100644 --- a/src/exercises/solutions.md +++ b/src/exercises/solutions.md @@ -2,10 +2,9 @@ You will find solutions to the exercises on the following pages. -Feel free to ask questions about the solutions [on -GitHub](https://github.com/google/comprehensive-rust/discussions). Let us know -if you have a different or better solution than what is presented here. - +Feel free to ask questions about the solutions +[on GitHub](https://github.com/google/comprehensive-rust/discussions). Let us +know if you have a different or better solution than what is presented here. > **Note:** Please ignore the `// ANCHOR: label` and `// ANCHOR_END: label` > comments you see in the solutions. They are there to make it possible to diff --git a/src/generics.md b/src/generics.md index ed787eb5bdbb..0b267669fced 100644 --- a/src/generics.md +++ b/src/generics.md @@ -1,5 +1,4 @@ # Generics Rust support generics, which lets you abstract algorithms or data structures -(such as sorting or a binary tree) -over the types used or stored. +(such as sorting or a binary tree) over the types used or stored. diff --git a/src/generics/data-types.md b/src/generics/data-types.md index 4fa706a09de7..db37f75661f6 100644 --- a/src/generics/data-types.md +++ b/src/generics/data-types.md @@ -18,8 +18,8 @@ fn main() {
-* Try declaring a new variable `let p = Point { x: 5, y: 10.0 };`. +- Try declaring a new variable `let p = Point { x: 5, y: 10.0 };`. -* Fix the code to allow points that have elements of different types. +- Fix the code to allow points that have elements of different types. -
\ No newline at end of file +
diff --git a/src/generics/methods.md b/src/generics/methods.md index 66bc4058fafe..96cffeab1273 100644 --- a/src/generics/methods.md +++ b/src/generics/methods.md @@ -22,10 +22,13 @@ fn main() {
-* *Q:* Why `T` is specified twice in `impl Point {}`? Isn't that redundant? - * This is because it is a generic implementation section for generic type. They are independently generic. - * It means these methods are defined for any `T`. - * It is possible to write `impl Point { .. }`. - * `Point` is still generic and you can use `Point`, but methods in this block will only be available for `Point`. +- _Q:_ Why `T` is specified twice in `impl Point {}`? Isn't that + redundant? + - This is because it is a generic implementation section for generic type. + They are independently generic. + - It means these methods are defined for any `T`. + - It is possible to write `impl Point { .. }`. + - `Point` is still generic and you can use `Point`, but methods in this + block will only be available for `Point`.
diff --git a/src/hello-world.md b/src/hello-world.md index b0ade14f8548..0f049157ca39 100644 --- a/src/hello-world.md +++ b/src/hello-world.md @@ -11,11 +11,11 @@ fn main() { What you see: -* Functions are introduced with `fn`. -* Blocks are delimited by curly braces like in C and C++. -* The `main` function is the entry point of the program. -* Rust has hygienic macros, `println!` is an example of this. -* Rust strings are UTF-8 encoded and can contain any Unicode character. +- Functions are introduced with `fn`. +- Blocks are delimited by curly braces like in C and C++. +- The `main` function is the entry point of the program. +- Rust has hygienic macros, `println!` is an example of this. +- Rust strings are UTF-8 encoded and can contain any Unicode character.
@@ -24,20 +24,21 @@ a ton of it over the next three days so we start small with something familiar. Key points: -* Rust is very much like other languages in the C/C++/Java tradition. It is - imperative and it doesn't try to reinvent things unless - absolutely necessary. +- Rust is very much like other languages in the C/C++/Java tradition. It is + imperative and it doesn't try to reinvent things unless absolutely necessary. -* Rust is modern with full support for things like Unicode. +- Rust is modern with full support for things like Unicode. -* Rust uses macros for situations where you want to have a variable number of +- Rust uses macros for situations where you want to have a variable number of arguments (no function [overloading](basic-syntax/functions-interlude.md)). -* Macros being 'hygienic' means they don't accidentally capture identifiers from +- Macros being 'hygienic' means they don't accidentally capture identifiers from the scope they are used in. Rust macros are actually only [partially hygienic](https://veykril.github.io/tlborm/decl-macros/minutiae/hygiene.html). -* Rust is multi-paradigm. For example, it has powerful [object-oriented programming features](https://doc.rust-lang.org/book/ch17-00-oop.html), - and, while it is not a functional language, it includes a range of [functional concepts](https://doc.rust-lang.org/book/ch13-00-functional-features.html). +- Rust is multi-paradigm. For example, it has powerful + [object-oriented programming features](https://doc.rust-lang.org/book/ch17-00-oop.html), + and, while it is not a functional language, it includes a range of + [functional concepts](https://doc.rust-lang.org/book/ch13-00-functional-features.html).
diff --git a/src/hello-world/small-example.md b/src/hello-world/small-example.md index c4322767dc2a..462624234149 100644 --- a/src/hello-world/small-example.md +++ b/src/hello-world/small-example.md @@ -26,21 +26,22 @@ inputs. Key points: -* Explain that all variables are statically typed. Try removing `i32` to trigger +- Explain that all variables are statically typed. Try removing `i32` to trigger type inference. Try with `i8` instead and trigger a runtime integer overflow. -* Change `let mut x` to `let x`, discuss the compiler error. +- Change `let mut x` to `let x`, discuss the compiler error. -* Show how `print!` gives a compilation error if the arguments don't match the +- Show how `print!` gives a compilation error if the arguments don't match the format string. -* Show how you need to use `{}` as a placeholder if you want to print an +- Show how you need to use `{}` as a placeholder if you want to print an expression which is more complex than just a single variable. -* Show the students the standard library, show them how to search for `std::fmt` +- Show the students the standard library, show them how to search for `std::fmt` which has the rules of the formatting mini-language. It's important that the students become familiar with searching in the standard library. - - * In a shell `rustup doc std::fmt` will open a browser on the local std::fmt documentation + + - In a shell `rustup doc std::fmt` will open a browser on the local std::fmt + documentation
diff --git a/src/index.md b/src/index.md index c301c1226ce2..2b839591a8b9 100644 --- a/src/index.md +++ b/src/index.md @@ -4,50 +4,49 @@ [![GitHub contributors](https://img.shields.io/github/contributors/google/comprehensive-rust?style=flat-square)](https://github.com/google/comprehensive-rust/graphs/contributors) [![GitHub stars](https://img.shields.io/github/stars/google/comprehensive-rust?style=flat-square)](https://github.com/google/comprehensive-rust/stargazers) -This is a free Rust course developed by the Android team at Google. The course covers -the full spectrum of Rust, from basic syntax to advanced topics like generics -and error handling. +This is a free Rust course developed by the Android team at Google. The course +covers the full spectrum of Rust, from basic syntax to advanced topics like +generics and error handling. > The latest version of the course can be found at -> . If you are reading -> somewhere else, please check there for updates. +> . If you are reading somewhere +> else, please check there for updates. The goal of the course is to teach you Rust. We assume you don't know anything about Rust and hope to: -* Give you a comprehensive understanding of the Rust syntax and language. -* Enable you to modify existing programs and write new programs in Rust. -* Show you common Rust idioms. +- Give you a comprehensive understanding of the Rust syntax and language. +- Enable you to modify existing programs and write new programs in Rust. +- Show you common Rust idioms. We call the first three course days Rust Fundamentals. Building on this, you're invited to dive into one or more specialized topics: -* [Android](android.md): a half-day course on using Rust for Android platform +- [Android](android.md): a half-day course on using Rust for Android platform development (AOSP). This includes interoperability with C, C++, and Java. -* [Bare-metal](bare-metal.md): a whole-day class on using Rust for bare-metal +- [Bare-metal](bare-metal.md): a whole-day class on using Rust for bare-metal (embedded) development. Both microcontrollers and application processors are covered. -* [Concurrency](concurrency.md): a whole-day class on concurrency in Rust. We +- [Concurrency](concurrency.md): a whole-day class on concurrency in Rust. We cover both classical concurrency (preemptively scheduling using threads and - mutexes) and async/await concurrency (cooperative multitasking using - futures). - + mutexes) and async/await concurrency (cooperative multitasking using futures). ## Non-Goals Rust is a large language and we won't be able to cover all of it in a few days. Some non-goals of this course are: -* Learning how to develop macros: please see [Chapter 19.5 in the Rust - Book](https://doc.rust-lang.org/book/ch19-06-macros.html) and [Rust by - Example](https://doc.rust-lang.org/rust-by-example/macros.html) instead. +- Learning how to develop macros: please see + [Chapter 19.5 in the Rust Book](https://doc.rust-lang.org/book/ch19-06-macros.html) + and [Rust by Example](https://doc.rust-lang.org/rust-by-example/macros.html) + instead. ## Assumptions -The course assumes that you already know how to program. Rust is a statically-typed -language and we will sometimes make comparisons with C and C++ to better -explain or contrast the Rust approach. +The course assumes that you already know how to program. Rust is a +statically-typed language and we will sometimes make comparisons with C and C++ +to better explain or contrast the Rust approach. If you know how to program in a dynamically-typed language such as Python or JavaScript, then you will be able to follow along just fine too. diff --git a/src/memory-management.md b/src/memory-management.md index a1a8e999001c..9d434aaec266 100644 --- a/src/memory-management.md +++ b/src/memory-management.md @@ -2,12 +2,13 @@ Traditionally, languages have fallen into two broad categories: -* Full control via manual memory management: C, C++, Pascal, ... -* Full safety via automatic memory management at runtime: Java, Python, Go, Haskell, ... +- Full control via manual memory management: C, C++, Pascal, ... +- Full safety via automatic memory management at runtime: Java, Python, Go, + Haskell, ... Rust offers a new mix: -> Full control *and* safety via compile time enforcement of correct memory +> Full control _and_ safety via compile time enforcement of correct memory > management. It does this with an explicit ownership concept. diff --git a/src/memory-management/garbage-collection.md b/src/memory-management/garbage-collection.md index 8902d5507991..482cff00c5bc 100644 --- a/src/memory-management/garbage-collection.md +++ b/src/memory-management/garbage-collection.md @@ -3,8 +3,8 @@ An alternative to manual and scope-based memory management is automatic memory management: -* The programmer never allocates or deallocates memory explicitly. -* A garbage collector finds unused memory and deallocates it for the programmer. +- The programmer never allocates or deallocates memory explicitly. +- A garbage collector finds unused memory and deallocates it for the programmer. ## Java Example diff --git a/src/memory-management/manual.md b/src/memory-management/manual.md index 0e7f88e6d621..4f8036c3ee11 100644 --- a/src/memory-management/manual.md +++ b/src/memory-management/manual.md @@ -2,7 +2,8 @@ You allocate and deallocate heap memory yourself. -If not done with care, this can lead to crashes, bugs, security vulnerabilities, and memory leaks. +If not done with care, this can lead to crashes, bugs, security vulnerabilities, +and memory leaks. ## C Example @@ -19,5 +20,6 @@ void foo(size_t n) { ``` Memory is leaked if the function returns early between `malloc` and `free`: the -pointer is lost and we cannot deallocate the memory. -Worse, freeing the pointer twice, or accessing a freed pointer can lead to exploitable security vulnerabilities. +pointer is lost and we cannot deallocate the memory. Worse, freeing the pointer +twice, or accessing a freed pointer can lead to exploitable security +vulnerabilities. diff --git a/src/memory-management/rust.md b/src/memory-management/rust.md index 7d8223918425..7fcdb46d121d 100644 --- a/src/memory-management/rust.md +++ b/src/memory-management/rust.md @@ -2,17 +2,25 @@ Memory management in Rust is a mix: -* Safe and correct like Java, but without a garbage collector. -* Scope-based like C++, but the compiler enforces full adherence. -* A Rust user can choose the right abstraction for the situation, some even have no cost at runtime like C. +- Safe and correct like Java, but without a garbage collector. +- Depending on which abstraction (or combination of abstractions) you choose, + can be a single unique pointer, reference counted, or atomically reference + counted. +- Scope-based like C++, but the compiler enforces full adherence. +- A Rust user can choose the right abstraction for the situation, some even have + no cost at runtime like C. Rust achieves this by modeling _ownership_ explicitly.
-* If asked how at this point, you can mention that in Rust this is usually handled by RAII wrapper types such as [Box], [Vec], [Rc], or [Arc]. These encapsulate ownership and memory allocation via various means, and prevent the potential errors in C. +- If asked how at this point, you can mention that in Rust this is usually + handled by RAII wrapper types such as [Box], [Vec], [Rc], or [Arc]. These + encapsulate ownership and memory allocation via various means, and prevent the + potential errors in C. -* You may be asked about destructors here, the [Drop] trait is the Rust equivalent. +- You may be asked about destructors here, the [Drop] trait is the Rust + equivalent.
diff --git a/src/memory-management/scope-based.md b/src/memory-management/scope-based.md index 3cbf34b56c46..8a7cce94be1b 100644 --- a/src/memory-management/scope-based.md +++ b/src/memory-management/scope-based.md @@ -17,10 +17,10 @@ void say_hello(std::unique_ptr person) { } ``` -* The `std::unique_ptr` object is allocated on the stack, and points to - memory allocated on the heap. -* At the end of `say_hello`, the `std::unique_ptr` destructor will run. -* The destructor frees the `Person` object it points to. +- The `std::unique_ptr` object is allocated on the stack, and points to memory + allocated on the heap. +- At the end of `say_hello`, the `std::unique_ptr` destructor will run. +- The destructor frees the `Person` object it points to. Special move constructors are used when passing ownership to a function: diff --git a/src/memory-management/stack-vs-heap.md b/src/memory-management/stack-vs-heap.md index 59c931460481..38ab94b97cff 100644 --- a/src/memory-management/stack-vs-heap.md +++ b/src/memory-management/stack-vs-heap.md @@ -1,12 +1,12 @@ # The Stack vs The Heap -* Stack: Continuous area of memory for local variables. - * Values have fixed sizes known at compile time. - * Extremely fast: just move a stack pointer. - * Easy to manage: follows function calls. - * Great memory locality. +- Stack: Continuous area of memory for local variables. + - Values have fixed sizes known at compile time. + - Extremely fast: just move a stack pointer. + - Easy to manage: follows function calls. + - Great memory locality. -* Heap: Storage of values outside of function calls. - * Values have dynamic sizes determined at runtime. - * Slightly slower than the stack: some book-keeping needed. - * No guarantee of memory locality. +- Heap: Storage of values outside of function calls. + - Values have dynamic sizes determined at runtime. + - Slightly slower than the stack: some book-keeping needed. + - No guarantee of memory locality. diff --git a/src/memory-management/stack.md b/src/memory-management/stack.md index 62d7cbd89bfc..a5866c0edd39 100644 --- a/src/memory-management/stack.md +++ b/src/memory-management/stack.md @@ -25,26 +25,30 @@ fn main() {
-* Mention that a `String` is backed by a `Vec`, so it has a capacity and length and can grow if mutable via reallocation on the heap. - -* If students ask about it, you can mention that the underlying memory is heap allocated using the [System Allocator] and custom allocators can be implemented using the [Allocator API] - -* We can inspect the memory layout with `unsafe` code. However, you should point out that this is rightfully unsafe! - - ```rust,editable - fn main() { - let mut s1 = String::from("Hello"); - s1.push(' '); - s1.push_str("world"); - // DON'T DO THIS AT HOME! For educational purposes only. - // String provides no guarantees about its layout, so this could lead to - // undefined behavior. - unsafe { - let (ptr, capacity, len): (usize, usize, usize) = std::mem::transmute(s1); - println!("ptr = {ptr:#x}, len = {len}, capacity = {capacity}"); - } - } - ``` +- Mention that a `String` is backed by a `Vec`, so it has a capacity and length + and can grow if mutable via reallocation on the heap. + +- If students ask about it, you can mention that the underlying memory is heap + allocated using the [System Allocator] and custom allocators can be + implemented using the [Allocator API] + +- We can inspect the memory layout with `unsafe` code. However, you should point + out that this is rightfully unsafe! + + ```rust,editable + fn main() { + let mut s1 = String::from("Hello"); + s1.push(' '); + s1.push_str("world"); + // DON'T DO THIS AT HOME! For educational purposes only. + // String provides no guarantees about its layout, so this could lead to + // undefined behavior. + unsafe { + let (ptr, capacity, len): (usize, usize, usize) = std::mem::transmute(s1); + println!("ptr = {ptr:#x}, len = {len}, capacity = {capacity}"); + } + } + ```
diff --git a/src/methods.md b/src/methods.md index a922b5ca9576..1552fb115ebc 100644 --- a/src/methods.md +++ b/src/methods.md @@ -28,14 +28,22 @@ fn main() {
Key Points: -* It can be helpful to introduce methods by comparing them to functions. - * Methods are called on an instance of a type (such as a struct or enum), the first parameter represents the instance as `self`. - * Developers may choose to use methods to take advantage of method receiver syntax and to help keep them more organized. By using methods we can keep all the implementation code in one predictable place. -* Point out the use of the keyword `self`, a method receiver. - * Show that it is an abbreviated term for `self: Self` and perhaps show how the struct name could also be used. - * Explain that `Self` is a type alias for the type the `impl` block is in and can be used elsewhere in the block. - * Note how `self` is used like other structs and dot notation can be used to refer to individual fields. - * This might be a good time to demonstrate how the `&self` differs from `self` by modifying the code and trying to run say_hello twice. -* We describe the distinction between method receivers next. + +- It can be helpful to introduce methods by comparing them to functions. + - Methods are called on an instance of a type (such as a struct or enum), the + first parameter represents the instance as `self`. + - Developers may choose to use methods to take advantage of method receiver + syntax and to help keep them more organized. By using methods we can keep + all the implementation code in one predictable place. +- Point out the use of the keyword `self`, a method receiver. + - Show that it is an abbreviated term for `self: Self` and perhaps show how + the struct name could also be used. + - Explain that `Self` is a type alias for the type the `impl` block is in and + can be used elsewhere in the block. + - Note how `self` is used like other structs and dot notation can be used to + refer to individual fields. + - This might be a good time to demonstrate how the `&self` differs from `self` + by modifying the code and trying to run say_hello twice. +- We describe the distinction between method receivers next.
diff --git a/src/methods/example.md b/src/methods/example.md index 1ee19b10b89f..e4bb7de51a62 100644 --- a/src/methods/example.md +++ b/src/methods/example.md @@ -42,12 +42,18 @@ fn main() { ```
- + Key Points: -* All four methods here use a different method receiver. - * You can point out how that changes what the function can do with the variable values and if/how it can be used again in `main`. - * You can showcase the error that appears when trying to call `finish` twice. -* Note that although the method receivers are different, the non-static functions are called the same way in the main body. Rust enables automatic referencing and dereferencing when calling methods. Rust automatically adds in the `&`, `*`, `muts` so that that object matches the method signature. -* You might point out that `print_laps` is using a vector that is iterated over. We describe vectors in more detail in the afternoon. + +- All four methods here use a different method receiver. + - You can point out how that changes what the function can do with the + variable values and if/how it can be used again in `main`. + - You can showcase the error that appears when trying to call `finish` twice. +- Note that although the method receivers are different, the non-static + functions are called the same way in the main body. Rust enables automatic + referencing and dereferencing when calling methods. Rust automatically adds in + the `&`, `*`, `muts` so that that object matches the method signature. +- You might point out that `print_laps` is using a vector that is iterated over. + We describe vectors in more detail in the afternoon.
diff --git a/src/methods/receiver.md b/src/methods/receiver.md index 6ef789be1186..6387a7a347f1 100644 --- a/src/methods/receiver.md +++ b/src/methods/receiver.md @@ -3,16 +3,16 @@ The `&self` above indicates that the method borrows the object immutably. There are other possible receivers for a method: -* `&self`: borrows the object from the caller using a shared and immutable +- `&self`: borrows the object from the caller using a shared and immutable reference. The object can be used again afterwards. -* `&mut self`: borrows the object from the caller using a unique and mutable +- `&mut self`: borrows the object from the caller using a unique and mutable reference. The object can be used again afterwards. -* `self`: takes ownership of the object and moves it away from the caller. The - method becomes the owner of the object. The object will be dropped (deallocated) - when the method returns, unless its ownership is explicitly +- `self`: takes ownership of the object and moves it away from the caller. The + method becomes the owner of the object. The object will be dropped + (deallocated) when the method returns, unless its ownership is explicitly transmitted. Complete ownership does not automatically mean mutability. -* `mut self`: same as above, but the method can mutate the object. -* No receiver: this becomes a static method on the struct. Typically used to +- `mut self`: same as above, but the method can mutate the object. +- No receiver: this becomes a static method on the struct. Typically used to create constructors which are called `new` by convention. Beyond variants on `self`, there are also @@ -20,9 +20,10 @@ Beyond variants on `self`, there are also allowed to be receiver types, such as `Box`.
- -Consider emphasizing "shared and immutable" and "unique and mutable". These constraints always come -together in Rust due to borrow checker rules, and `self` is no exception. It isn't possible to -reference a struct from multiple locations and call a mutating (`&mut self`) method on it. - + +Consider emphasizing "shared and immutable" and "unique and mutable". These +constraints always come together in Rust due to borrow checker rules, and `self` +is no exception. It isn't possible to reference a struct from multiple locations +and call a mutating (`&mut self`) method on it. +
diff --git a/src/modules.md b/src/modules.md index bf208d6f15f2..24ecc824ff58 100644 --- a/src/modules.md +++ b/src/modules.md @@ -25,8 +25,10 @@ fn main() {
-* Packages provide functionality and include a `Cargo.toml` file that describes how to build a bundle of 1+ crates. -* Crates are a tree of modules, where a binary crate creates an executable and a library crate compiles to a library. -* Modules define organization, scope, and are the focus of this section. +- Packages provide functionality and include a `Cargo.toml` file that describes + how to build a bundle of 1+ crates. +- Crates are a tree of modules, where a binary crate creates an executable and a + library crate compiles to a library. +- Modules define organization, scope, and are the focus of this section.
diff --git a/src/modules/filesystem.md b/src/modules/filesystem.md index b935ec2ff6e7..3fa08669e2f8 100644 --- a/src/modules/filesystem.md +++ b/src/modules/filesystem.md @@ -7,12 +7,13 @@ mod garden; ``` This tells rust that the `garden` module content is found at `src/garden.rs`. -Similarly, a `garden::vegetables` module can be found at `src/garden/vegetables.rs`. +Similarly, a `garden::vegetables` module can be found at +`src/garden/vegetables.rs`. The `crate` root is in: -* `src/lib.rs` (for a library crate) -* `src/main.rs` (for a binary crate) +- `src/lib.rs` (for a library crate) +- `src/main.rs` (for a binary crate) Modules defined in files can be documented, too, using "inner doc comments". These document the item that contains them -- in this case, a module. @@ -34,12 +35,13 @@ pub fn harvest(garden: &mut Garden) { todo!() }
-* Before Rust 2018, modules needed to be located at `module/mod.rs` instead of `module.rs`, and this is still a working alternative for editions after 2018. +- Before Rust 2018, modules needed to be located at `module/mod.rs` instead of + `module.rs`, and this is still a working alternative for editions after 2018. -* The main reason to introduce `filename.rs` as alternative to `filename/mod.rs` +- The main reason to introduce `filename.rs` as alternative to `filename/mod.rs` was because many files named `mod.rs` can be hard to distinguish in IDEs. -* Deeper nesting can use folders, even if the main module is a file: +- Deeper nesting can use folders, even if the main module is a file: ```ignore src/ @@ -49,14 +51,14 @@ pub fn harvest(garden: &mut Garden) { todo!() } └── sub_module.rs ``` -* The place rust will look for modules can be changed with a compiler directive: +- The place rust will look for modules can be changed with a compiler directive: ```rust,ignore #[path = "some/path.rs"] mod some_module; ``` - This is useful, for example, if you would like to place tests for a module in a file named - `some_module_test.rs`, similar to the convention in Go. + This is useful, for example, if you would like to place tests for a module in + a file named `some_module_test.rs`, similar to the convention in Go.
diff --git a/src/modules/paths.md b/src/modules/paths.md index bf4b9546c5f5..36aeb73f9b5b 100644 --- a/src/modules/paths.md +++ b/src/modules/paths.md @@ -3,15 +3,15 @@ Paths are resolved as follows: 1. As a relative path: - * `foo` or `self::foo` refers to `foo` in the current module, - * `super::foo` refers to `foo` in the parent module. + - `foo` or `self::foo` refers to `foo` in the current module, + - `super::foo` refers to `foo` in the parent module. 2. As an absolute path: - * `crate::foo` refers to `foo` in the root of the current crate, - * `bar::foo` refers to `foo` in the `bar` crate. + - `crate::foo` refers to `foo` in the root of the current crate, + - `bar::foo` refers to `foo` in the `bar` crate. -A module can bring symbols from another module into scope with `use`. -You will typically see something like this at the top of each module: +A module can bring symbols from another module into scope with `use`. You will +typically see something like this at the top of each module: ```rust,editable use std::collections::HashSet; diff --git a/src/modules/visibility.md b/src/modules/visibility.md index 2525f2ad1ba9..36436612cad0 100644 --- a/src/modules/visibility.md +++ b/src/modules/visibility.md @@ -2,9 +2,9 @@ Modules are a privacy boundary: -* Module items are private by default (hides implementation details). -* Parent and sibling items are always visible. -* In other words, if an item is visible in module `foo`, it's visible in all the +- Module items are private by default (hides implementation details). +- Parent and sibling items are always visible. +- In other words, if an item is visible in module `foo`, it's visible in all the descendants of `foo`. ```rust,editable @@ -36,13 +36,16 @@ fn main() {
-* Use the `pub` keyword to make modules public. +- Use the `pub` keyword to make modules public. -Additionally, there are advanced `pub(...)` specifiers to restrict the scope of public visibility. +Additionally, there are advanced `pub(...)` specifiers to restrict the scope of +public visibility. -* See the [Rust Reference](https://doc.rust-lang.org/reference/visibility-and-privacy.html#pubin-path-pubcrate-pubsuper-and-pubself). -* Configuring `pub(crate)` visibility is a common pattern. -* Less commonly, you can give visibility to a specific path. -* In any case, visibility must be granted to an ancestor module (and all of its descendants). +- See the + [Rust Reference](https://doc.rust-lang.org/reference/visibility-and-privacy.html#pubin-path-pubcrate-pubsuper-and-pubself). +- Configuring `pub(crate)` visibility is a common pattern. +- Less commonly, you can give visibility to a specific path. +- In any case, visibility must be granted to an ancestor module (and all of its + descendants).
diff --git a/src/other-resources.md b/src/other-resources.md index 7376c288eb2a..5e858c49e8f7 100644 --- a/src/other-resources.md +++ b/src/other-resources.md @@ -7,55 +7,53 @@ online. The Rust project hosts many resources. These cover Rust in general: -* [The Rust Programming Language](https://doc.rust-lang.org/book/): the +- [The Rust Programming Language](https://doc.rust-lang.org/book/): the canonical free book about Rust. Covers the language in detail and includes a few projects for people to build. -* [Rust By Example](https://doc.rust-lang.org/rust-by-example/): covers the Rust +- [Rust By Example](https://doc.rust-lang.org/rust-by-example/): covers the Rust syntax via a series of examples which showcase different constructs. Sometimes includes small exercises where you are asked to expand on the code in the examples. -* [Rust Standard Library](https://doc.rust-lang.org/std/): full documentation of +- [Rust Standard Library](https://doc.rust-lang.org/std/): full documentation of the standard library for Rust. -* [The Rust Reference](https://doc.rust-lang.org/reference/): an incomplete book +- [The Rust Reference](https://doc.rust-lang.org/reference/): an incomplete book which describes the Rust grammar and memory model. More specialized guides hosted on the official Rust site: -* [The Rustonomicon](https://doc.rust-lang.org/nomicon/): covers unsafe Rust, +- [The Rustonomicon](https://doc.rust-lang.org/nomicon/): covers unsafe Rust, including working with raw pointers and interfacing with other languages (FFI). -* [Asynchronous Programming in Rust](https://rust-lang.github.io/async-book/): +- [Asynchronous Programming in Rust](https://rust-lang.github.io/async-book/): covers the new asynchronous programming model which was introduced after the Rust Book was written. -* [The Embedded Rust Book](https://doc.rust-lang.org/stable/embedded-book/): an +- [The Embedded Rust Book](https://doc.rust-lang.org/stable/embedded-book/): an introduction to using Rust on embedded devices without an operating system. ## Unofficial Learning Material A small selection of other guides and tutorial for Rust: -* [Learn Rust the Dangerous Way](http://cliffle.com/p/dangerust/): covers Rust +- [Learn Rust the Dangerous Way](http://cliffle.com/p/dangerust/): covers Rust from the perspective of low-level C programmers. -* [Rust for Embedded C - Programmers](https://docs.opentitan.org/doc/ug/rust_for_c/): covers Rust from - the perspective of developers who write firmware in C. -* [Rust for professionals](https://overexact.com/rust-for-professionals/): +- [Rust for Embedded C Programmers](https://docs.opentitan.org/doc/ug/rust_for_c/): + covers Rust from the perspective of developers who write firmware in C. +- [Rust for professionals](https://overexact.com/rust-for-professionals/): covers the syntax of Rust using side-by-side comparisons with other languages such as C, C++, Java, JavaScript, and Python. -* [Rust on Exercism](https://exercism.org/tracks/rust): 100+ exercises to help +- [Rust on Exercism](https://exercism.org/tracks/rust): 100+ exercises to help you learn Rust. -* [Ferrous Teaching - Material](https://ferrous-systems.github.io/teaching-material/index.html): a - series of small presentations covering both basic and advanced part of the +- [Ferrous Teaching Material](https://ferrous-systems.github.io/teaching-material/index.html): + a series of small presentations covering both basic and advanced part of the Rust language. Other topics such as WebAssembly, and async/await are also covered. -* [Beginner's Series to - Rust](https://docs.microsoft.com/en-us/shows/beginners-series-to-rust/) and - [Take your first steps with - Rust](https://docs.microsoft.com/en-us/learn/paths/rust-first-steps/): two - Rust guides aimed at new developers. The first is a set of 35 videos and the - second is a set of 11 modules which covers Rust syntax and basic constructs. -* [Learn Rust With Entirely Too Many Linked +- [Beginner's Series to Rust](https://docs.microsoft.com/en-us/shows/beginners-series-to-rust/) + and + [Take your first steps with Rust](https://docs.microsoft.com/en-us/learn/paths/rust-first-steps/): + two Rust guides aimed at new developers. The first is a set of 35 videos and + the second is a set of 11 modules which covers Rust syntax and basic + constructs. +- [Learn Rust With Entirely Too Many Linked Lists](https://rust-unofficial.github.io/too-many-lists/): in-depth exploration of Rust's memory management rules, through implementing a few different types of list structures. diff --git a/src/ownership.md b/src/ownership.md index db7830140b0d..eb33580ffdf2 100644 --- a/src/ownership.md +++ b/src/ownership.md @@ -15,6 +15,6 @@ fn main() { } ``` -* At the end of the scope, the variable is _dropped_ and the data is freed. -* A destructor can run here to free up resources. -* We say that the variable _owns_ the value. +- At the end of the scope, the variable is _dropped_ and the data is freed. +- A destructor can run here to free up resources. +- We say that the variable _owns_ the value. diff --git a/src/ownership/borrowing.md b/src/ownership/borrowing.md index 767c6dd2c435..ec208871e4a4 100644 --- a/src/ownership/borrowing.md +++ b/src/ownership/borrowing.md @@ -19,13 +19,19 @@ fn main() { } ``` -* The `add` function _borrows_ two points and returns a new point. -* The caller retains ownership of the inputs. +- The `add` function _borrows_ two points and returns a new point. +- The caller retains ownership of the inputs.
Notes on stack returns: -* Demonstrate that the return from `add` is cheap because the compiler can eliminate the copy operation. Change the above code to print stack addresses and run it on the [Playground] or look at the assembly in [Godbolt](https://rust.godbolt.org/). In the "DEBUG" optimization level, the addresses should change, while they stay the same when changing to the "RELEASE" setting: + +- Demonstrate that the return from `add` is cheap because the compiler can + eliminate the copy operation. Change the above code to print stack addresses + and run it on the [Playground] or look at the assembly in + [Godbolt](https://rust.godbolt.org/). In the "DEBUG" optimization level, the + addresses should change, while they stay the same when changing to the + "RELEASE" setting: ```rust,editable #[derive(Debug)] @@ -45,8 +51,11 @@ Notes on stack returns: println!("{p1:?} + {p2:?} = {p3:?}"); } ``` -* The Rust compiler can do return value optimization (RVO). -* In C++, copy elision has to be defined in the language specification because constructors can have side effects. In Rust, this is not an issue at all. If RVO did not happen, Rust will always perform a simple and efficient `memcpy` copy. +- The Rust compiler can do return value optimization (RVO). +- In C++, copy elision has to be defined in the language specification because + constructors can have side effects. In Rust, this is not an issue at all. If + RVO did not happen, Rust will always perform a simple and efficient `memcpy` + copy.
diff --git a/src/ownership/copy-clone.md b/src/ownership/copy-clone.md index 43b7c69a0866..24023a6d1414 100644 --- a/src/ownership/copy-clone.md +++ b/src/ownership/copy-clone.md @@ -27,25 +27,30 @@ fn main() { } ``` -* After the assignment, both `p1` and `p2` own their own data. -* We can also use `p1.clone()` to explicitly copy the data. +- After the assignment, both `p1` and `p2` own their own data. +- We can also use `p1.clone()` to explicitly copy the data.
Copying and cloning are not the same thing: -* Copying refers to bitwise copies of memory regions and does not work on arbitrary objects. -* Copying does not allow for custom logic (unlike copy constructors in C++). -* Cloning is a more general operation and also allows for custom behavior by implementing the `Clone` trait. -* Copying does not work on types that implement the `Drop` trait. +- Copying refers to bitwise copies of memory regions and does not work on + arbitrary objects. +- Copying does not allow for custom logic (unlike copy constructors in C++). +- Cloning is a more general operation and also allows for custom behavior by + implementing the `Clone` trait. +- Copying does not work on types that implement the `Drop` trait. In the above example, try the following: -* Add a `String` field to `struct Point`. It will not compile because `String` is not a `Copy` type. -* Remove `Copy` from the `derive` attribute. The compiler error is now in the `println!` for `p1`. -* Show that it works if you clone `p1` instead. +- Add a `String` field to `struct Point`. It will not compile because `String` + is not a `Copy` type. +- Remove `Copy` from the `derive` attribute. The compiler error is now in the + `println!` for `p1`. +- Show that it works if you clone `p1` instead. + +If students ask about `derive`, it is sufficient to say that this is a way to +generate code in Rust at compile time. In this case the default implementations +of `Copy` and `Clone` traits are generated. -If students ask about `derive`, it is sufficient to say that this is a way to generate code in Rust -at compile time. In this case the default implementations of `Copy` and `Clone` traits are generated. -
diff --git a/src/ownership/double-free-modern-cpp.md b/src/ownership/double-free-modern-cpp.md index 55f3b9883902..50f91843ecf2 100644 --- a/src/ownership/double-free-modern-cpp.md +++ b/src/ownership/double-free-modern-cpp.md @@ -1,4 +1,4 @@ -# Extra Work in Modern C++ +# Extra Work in Modern C++ Modern C++ solves this differently: @@ -7,12 +7,11 @@ std::string s1 = "Cpp"; std::string s2 = s1; // Duplicate the data in s1. ``` -* The heap data from `s1` is duplicated and `s2` gets its own independent copy. -* When `s1` and `s2` go out of scope, they each free their own memory. +- The heap data from `s1` is duplicated and `s2` gets its own independent copy. +- When `s1` and `s2` go out of scope, they each free their own memory. Before copy-assignment: - ```bob Stack Heap .- - - - - - - - - - - - - -. .- - - - - - - - - - - -. diff --git a/src/ownership/lifetimes-data-structures.md b/src/ownership/lifetimes-data-structures.md index db7adbc16b3f..519727d40321 100644 --- a/src/ownership/lifetimes-data-structures.md +++ b/src/ownership/lifetimes-data-structures.md @@ -22,9 +22,18 @@ fn main() {
-* In the above example, the annotation on `Highlight` enforces that the data underlying the contained `&str` lives at least as long as any instance of `Highlight` that uses that data. -* If `text` is consumed before the end of the lifetime of `fox` (or `dog`), the borrow checker throws an error. -* Types with borrowed data force users to hold on to the original data. This can be useful for creating lightweight views, but it generally makes them somewhat harder to use. -* When possible, make data structures own their data directly. -* Some structs with multiple references inside can have more than one lifetime annotation. This can be necessary if there is a need to describe lifetime relationships between the references themselves, in addition to the lifetime of the struct itself. Those are very advanced use cases. +- In the above example, the annotation on `Highlight` enforces that the data + underlying the contained `&str` lives at least as long as any instance of + `Highlight` that uses that data. +- If `text` is consumed before the end of the lifetime of `fox` (or `dog`), the + borrow checker throws an error. +- Types with borrowed data force users to hold on to the original data. This can + be useful for creating lightweight views, but it generally makes them somewhat + harder to use. +- When possible, make data structures own their data directly. +- Some structs with multiple references inside can have more than one lifetime + annotation. This can be necessary if there is a need to describe lifetime + relationships between the references themselves, in addition to the lifetime + of the struct itself. Those are very advanced use cases. +
diff --git a/src/ownership/lifetimes-function-calls.md b/src/ownership/lifetimes-function-calls.md index 43bbc5ef857c..fa621072b936 100644 --- a/src/ownership/lifetimes-function-calls.md +++ b/src/ownership/lifetimes-function-calls.md @@ -18,17 +18,18 @@ fn main() { } ``` -* `'a` is a generic parameter, it is inferred by the compiler. -* Lifetimes start with `'` and `'a` is a typical default name. -* Read `&'a Point` as "a borrowed `Point` which is valid for at least the +- `'a` is a generic parameter, it is inferred by the compiler. +- Lifetimes start with `'` and `'a` is a typical default name. +- Read `&'a Point` as "a borrowed `Point` which is valid for at least the lifetime `a`". - * The _at least_ part is important when parameters are in different scopes. + - The _at least_ part is important when parameters are in different scopes.
In the above example, try the following: -* Move the declaration of `p2` and `p3` into a new scope (`{ ... }`), resulting in the following code: +- Move the declaration of `p2` and `p3` into a new scope (`{ ... }`), resulting + in the following code: ```rust,ignore #[derive(Debug)] struct Point(i32, i32); @@ -49,12 +50,16 @@ In the above example, try the following: ``` Note how this does not compile since `p3` outlives `p2`. -* Reset the workspace and change the function signature to `fn left_most<'a, 'b>(p1: &'a Point, p2: &'a Point) -> &'b Point`. This will not compile because the relationship between the lifetimes `'a` and `'b` is unclear. -* Another way to explain it: - * Two references to two values are borrowed by a function and the function returns - another reference. - * It must have come from one of those two inputs (or from a global variable). - * Which one is it? The compiler needs to know, so at the call site the returned reference is not used - for longer than a variable from where the reference came from. +- Reset the workspace and change the function signature to + `fn left_most<'a, 'b>(p1: &'a Point, p2: &'a Point) -> &'b Point`. This will + not compile because the relationship between the lifetimes `'a` and `'b` is + unclear. +- Another way to explain it: + - Two references to two values are borrowed by a function and the function + returns another reference. + - It must have come from one of those two inputs (or from a global variable). + - Which one is it? The compiler needs to know, so at the call site the + returned reference is not used for longer than a variable from where the + reference came from.
diff --git a/src/ownership/lifetimes.md b/src/ownership/lifetimes.md index 606d1116a527..414422403fff 100644 --- a/src/ownership/lifetimes.md +++ b/src/ownership/lifetimes.md @@ -2,14 +2,14 @@ A borrowed value has a _lifetime_: -* The lifetime can be implicit: `add(p1: &Point, p2: &Point) -> Point`. -* Lifetimes can also be explicit: `&'a Point`, `&'document str`. -* Read `&'a Point` as "a borrowed `Point` which is valid for at least the +- The lifetime can be implicit: `add(p1: &Point, p2: &Point) -> Point`. +- Lifetimes can also be explicit: `&'a Point`, `&'document str`. +- Read `&'a Point` as "a borrowed `Point` which is valid for at least the lifetime `a`". -* Lifetimes are always inferred by the compiler: you cannot assign a lifetime +- Lifetimes are always inferred by the compiler: you cannot assign a lifetime yourself. - * Lifetime annotations create constraints; the compiler verifies that there is + - Lifetime annotations create constraints; the compiler verifies that there is a valid solution. -* Lifetimes for function arguments and return values must be fully specified, - but Rust allows lifetimes to be elided in most cases with [a few simple - rules](https://doc.rust-lang.org/nomicon/lifetime-elision.html). +- Lifetimes for function arguments and return values must be fully specified, + but Rust allows lifetimes to be elided in most cases with + [a few simple rules](https://doc.rust-lang.org/nomicon/lifetime-elision.html). diff --git a/src/ownership/move-semantics.md b/src/ownership/move-semantics.md index ecea9163c398..7d1e906abc9b 100644 --- a/src/ownership/move-semantics.md +++ b/src/ownership/move-semantics.md @@ -11,19 +11,22 @@ fn main() { } ``` -* The assignment of `s1` to `s2` transfers ownership. -* When `s1` goes out of scope, nothing happens: it does not own anything. -* When `s2` goes out of scope, the string data is freed. -* There is always _exactly_ one variable binding which owns a value. +- The assignment of `s1` to `s2` transfers ownership. +- When `s1` goes out of scope, nothing happens: it does not own anything. +- When `s2` goes out of scope, the string data is freed. +- There is always _exactly_ one variable binding which owns a value.
-* Mention that this is the opposite of the defaults in C++, which copies by value unless you use `std::move` (and the move constructor is defined!). +- Mention that this is the opposite of the defaults in C++, which copies by + value unless you use `std::move` (and the move constructor is defined!). -* It is only the ownership that moves. Whether any machine code is generated to manipulate the data itself is a matter of optimization, and such copies are aggressively optimized away. +- It is only the ownership that moves. Whether any machine code is generated to + manipulate the data itself is a matter of optimization, and such copies are + aggressively optimized away. -* Simple values (such as integers) can be marked `Copy` (see later slides). +- Simple values (such as integers) can be marked `Copy` (see later slides). -* In Rust, clones are explicit (by using `clone`). +- In Rust, clones are explicit (by using `clone`).
diff --git a/src/ownership/moved-strings-rust.md b/src/ownership/moved-strings-rust.md index b3c0659244df..0f451bf57dbe 100644 --- a/src/ownership/moved-strings-rust.md +++ b/src/ownership/moved-strings-rust.md @@ -7,8 +7,8 @@ fn main() { } ``` -* The heap data from `s1` is reused for `s2`. -* When `s1` goes out of scope, nothing happens (it has been moved from). +- The heap data from `s1` is reused for `s2`. +- When `s1` goes out of scope, nothing happens (it has been moved from). Before move to `s2`: diff --git a/src/ownership/moves-function-calls.md b/src/ownership/moves-function-calls.md index e30f21264b4f..715f04ba4abc 100644 --- a/src/ownership/moves-function-calls.md +++ b/src/ownership/moves-function-calls.md @@ -17,10 +17,15 @@ fn main() {
-* With the first call to `say_hello`, `main` gives up ownership of `name`. Afterwards, `name` cannot be used anymore within `main`. -* The heap memory allocated for `name` will be freed at the end of the `say_hello` function. -* `main` can retain ownership if it passes `name` as a reference (`&name`) and if `say_hello` accepts a reference as a parameter. -* Alternatively, `main` can pass a clone of `name` in the first call (`name.clone()`). -* Rust makes it harder than C++ to inadvertently create copies by making move semantics the default, and by forcing programmers to make clones explicit. +- With the first call to `say_hello`, `main` gives up ownership of `name`. + Afterwards, `name` cannot be used anymore within `main`. +- The heap memory allocated for `name` will be freed at the end of the + `say_hello` function. +- `main` can retain ownership if it passes `name` as a reference (`&name`) and + if `say_hello` accepts a reference as a parameter. +- Alternatively, `main` can pass a clone of `name` in the first call + (`name.clone()`). +- Rust makes it harder than C++ to inadvertently create copies by making move + semantics the default, and by forcing programmers to make clones explicit.
diff --git a/src/ownership/shared-unique-borrows.md b/src/ownership/shared-unique-borrows.md index 6c8419b55487..59811b19faa9 100644 --- a/src/ownership/shared-unique-borrows.md +++ b/src/ownership/shared-unique-borrows.md @@ -2,8 +2,8 @@ Rust puts constraints on the ways you can borrow values: -* You can have one or more `&T` values at any given time, _or_ -* You can have exactly one `&mut T` value. +- You can have one or more `&T` values at any given time, _or_ +- You can have exactly one `&mut T` value. ```rust,editable,compile_fail fn main() { @@ -22,8 +22,12 @@ fn main() {
-* The above code does not compile because `a` is borrowed as mutable (through `c`) and as immutable (through `b`) at the same time. -* Move the `println!` statement for `b` before the scope that introduces `c` to make the code compile. -* After that change, the compiler realizes that `b` is only ever used before the new mutable borrow of `a` through `c`. This is a feature of the borrow checker called "non-lexical lifetimes". +- The above code does not compile because `a` is borrowed as mutable (through + `c`) and as immutable (through `b`) at the same time. +- Move the `println!` statement for `b` before the scope that introduces `c` to + make the code compile. +- After that change, the compiler realizes that `b` is only ever used before the + new mutable borrow of `a` through `c`. This is a feature of the borrow checker + called "non-lexical lifetimes".
diff --git a/src/pattern-matching.md b/src/pattern-matching.md index 8be4a9a91cd5..f1bcd1f9280f 100644 --- a/src/pattern-matching.md +++ b/src/pattern-matching.md @@ -21,15 +21,19 @@ fn main() { The `_` pattern is a wildcard pattern which matches any value.
- + Key Points: -* You might point out how some specific characters are being used when in a pattern - * `|` as an `or` - * `..` can expand as much as it needs to be - * `1..=5` represents an inclusive range - * `_` is a wild card -* It can be useful to show how binding works, by for instance replacing a wildcard character with a variable, or removing the quotes around `q`. -* You can demonstrate matching on a reference. -* This might be a good time to bring up the concept of irrefutable patterns, as the term can show up in error messages. - + +- You might point out how some specific characters are being used when in a + pattern + - `|` as an `or` + - `..` can expand as much as it needs to be + - `1..=5` represents an inclusive range + - `_` is a wild card +- It can be useful to show how binding works, by for instance replacing a + wildcard character with a variable, or removing the quotes around `q`. +- You can demonstrate matching on a reference. +- This might be a good time to bring up the concept of irrefutable patterns, as + the term can show up in error messages. +
diff --git a/src/pattern-matching/destructuring-arrays.md b/src/pattern-matching/destructuring-arrays.md index fdf7ec237289..dc36bf570869 100644 --- a/src/pattern-matching/destructuring-arrays.md +++ b/src/pattern-matching/destructuring-arrays.md @@ -6,32 +6,32 @@ You can destructure arrays, tuples, and slices by matching on their elements: {{#include ../../third_party/rust-by-example/destructuring-arrays.rs}} ``` -
-* Destructuring of slices of unknown length also works with patterns of fixed length. - - - ```rust,editable - fn main() { - inspect(&[0, -2, 3]); - inspect(&[0, -2, 3, 4]); - } - - #[rustfmt::skip] - fn inspect(slice: &[i32]) { - println!("Tell me about {slice:?}"); - match slice { - &[0, y, z] => println!("First is 0, y = {y}, and z = {z}"), - &[1, ..] => println!("First is 1 and the rest were ignored"), - _ => println!("All elements were ignored"), - } - } - ``` - -* Create a new pattern using `_` to represent an element. -* Add more values to the array. -* Point out that how `..` will expand to account for different number of elements. -* Show matching against the tail with patterns `[.., b]` and `[a@..,b]` +- Destructuring of slices of unknown length also works with patterns of fixed + length. + + ```rust,editable + fn main() { + inspect(&[0, -2, 3]); + inspect(&[0, -2, 3, 4]); + } + + #[rustfmt::skip] + fn inspect(slice: &[i32]) { + println!("Tell me about {slice:?}"); + match slice { + &[0, y, z] => println!("First is 0, y = {y}, and z = {z}"), + &[1, ..] => println!("First is 1 and the rest were ignored"), + _ => println!("All elements were ignored"), + } + } + ``` + +- Create a new pattern using `_` to represent an element. +- Add more values to the array. +- Point out that how `..` will expand to account for different number of + elements. +- Show matching against the tail with patterns `[.., b]` and `[a@..,b]`
diff --git a/src/pattern-matching/destructuring-enums.md b/src/pattern-matching/destructuring-enums.md index 378cef761cb8..ce403631744a 100644 --- a/src/pattern-matching/destructuring-enums.md +++ b/src/pattern-matching/destructuring-enums.md @@ -33,7 +33,11 @@ arm, `half` is bound to the value inside the `Ok` variant. In the second arm,
Key points: -* The `if`/`else` expression is returning an enum that is later unpacked with a `match`. -* You can try adding a third variant to the enum definition and displaying the errors when running the code. Point out the places where your code is now inexhaustive and how the compiler tries to give you hints. + +- The `if`/`else` expression is returning an enum that is later unpacked with a + `match`. +- You can try adding a third variant to the enum definition and displaying the + errors when running the code. Point out the places where your code is now + inexhaustive and how the compiler tries to give you hints.
diff --git a/src/pattern-matching/destructuring-structs.md b/src/pattern-matching/destructuring-structs.md index 67fbb2119c45..257b221e26fe 100644 --- a/src/pattern-matching/destructuring-structs.md +++ b/src/pattern-matching/destructuring-structs.md @@ -5,12 +5,13 @@ You can also destructure `structs`: ```rust,editable {{#include ../../third_party/rust-by-example/destructuring-structs.rs}} ``` +
-* Change the literal values in `foo` to match with the other patterns. -* Add a new field to `Foo` and make changes to the pattern as needed. -* The distinction between a capture and a constant expression can be hard to - spot. Try changing the `2` in the second arm to a variable, and see that it subtly - doesn't work. Change it to a `const` and see it working again. +- Change the literal values in `foo` to match with the other patterns. +- Add a new field to `Foo` and make changes to the pattern as needed. +- The distinction between a capture and a constant expression can be hard to + spot. Try changing the `2` in the second arm to a variable, and see that it + subtly doesn't work. Change it to a `const` and see it working again.
diff --git a/src/pattern-matching/match-guards.md b/src/pattern-matching/match-guards.md index ce04e50ad6d1..529127b694af 100644 --- a/src/pattern-matching/match-guards.md +++ b/src/pattern-matching/match-guards.md @@ -10,9 +10,15 @@ expression which will be executed if the pattern matches:
Key Points: -* Match guards as a separate syntax feature are important and necessary when we wish to concisely express more complex ideas than patterns alone would allow. -* They are not the same as separate `if` expression inside of the match arm. An `if` expression inside of the branch block (after `=>`) happens after the match arm is selected. Failing the `if` condition inside of that block won't result in other arms -of the original `match` expression being considered. -* You can use the variables defined in the pattern in your if expression. -* The condition defined in the guard applies to every expression in a pattern with an `|`. + +- Match guards as a separate syntax feature are important and necessary when we + wish to concisely express more complex ideas than patterns alone would allow. +- They are not the same as separate `if` expression inside of the match arm. An + `if` expression inside of the branch block (after `=>`) happens after the + match arm is selected. Failing the `if` condition inside of that block won't + result in other arms of the original `match` expression being considered. +- You can use the variables defined in the pattern in your if expression. +- The condition defined in the guard applies to every expression in a pattern + with an `|`. +
diff --git a/src/running-the-course.md b/src/running-the-course.md index e75d721ce36c..31a693dc77e7 100644 --- a/src/running-the-course.md +++ b/src/running-the-course.md @@ -5,13 +5,12 @@ Here is a bit of background information about how we've been running the course internally at Google. -We typically run classes from 10:00 am to 4:00 pm, with a 1 hour lunch -break in the middle. This leaves 2.5 hours for the morning class and -2.5 hours for the afternoon class. Note that this is just a -recommendation: you can also spend 3 hour on the morning session to -give people more time for exercises. The downside of longer session is -that people can become very tired after 6 full hours of class in the -afternoon. +We typically run classes from 10:00 am to 4:00 pm, with a 1 hour lunch break in +the middle. This leaves 2.5 hours for the morning class and 2.5 hours for the +afternoon class. Note that this is just a recommendation: you can also spend 3 +hour on the morning session to give people more time for exercises. The downside +of longer session is that people can become very tired after 6 full hours of +class in the afternoon. Before you run the course, you will want to: @@ -21,32 +20,32 @@ Before you run the course, you will want to: popup (click the link with a little arrow next to "Speaker Notes"). This way you have a clean screen to present to the class. -1. Decide on the dates. Since the course takes at least three full days, we recommend that you - schedule the days over two weeks. Course participants have said that - they find it helpful to have a gap in the course since it helps them process - all the information we give them. +1. Decide on the dates. Since the course takes at least three full days, we + recommend that you schedule the days over two weeks. Course participants have + said that they find it helpful to have a gap in the course since it helps + them process all the information we give them. 1. Find a room large enough for your in-person participants. We recommend a class size of 15-25 people. That's small enough that people are comfortable asking questions --- it's also small enough that one instructor will have - time to answer the questions. Make sure the room has _desks_ for yourself and for the - students: you will all need to be able to sit and work with your laptops. - In particular, you will be doing a lot of live-coding as an instructor, so a lectern won't - be very helpful for you. + time to answer the questions. Make sure the room has _desks_ for yourself and + for the students: you will all need to be able to sit and work with your + laptops. In particular, you will be doing a lot of live-coding as an + instructor, so a lectern won't be very helpful for you. 1. On the day of your course, show up to the room a little early to set things up. We recommend presenting directly using `mdbook serve` running on your - laptop (see the [installation instructions][3]). This ensures optimal performance with no lag as you change pages. - Using your laptop will also allow you to fix typos as you or the course - participants spot them. - -1. Let people solve the exercises by themselves or in small groups. - We typically spend 30-45 minutes on exercises in the morning and in the afternoon (including time to review the solutions). - Make sure to - ask people if they're stuck or if there is anything you can help with. When - you see that several people have the same problem, call it out to the class - and offer a solution, e.g., by showing people where to find the relevant - information in the standard library. + laptop (see the [installation instructions][3]). This ensures optimal + performance with no lag as you change pages. Using your laptop will also + allow you to fix typos as you or the course participants spot them. + +1. Let people solve the exercises by themselves or in small groups. We typically + spend 30-45 minutes on exercises in the morning and in the afternoon + (including time to review the solutions). Make sure to ask people if they're + stuck or if there is anything you can help with. When you see that several + people have the same problem, call it out to the class and offer a solution, + e.g., by showing people where to find the relevant information in the + standard library. That is all, good luck running the course! We hope it will be as much fun for you as it has been for us! diff --git a/src/running-the-course/course-structure.md b/src/running-the-course/course-structure.md index 15c6ff02569a..cb0a8cdff7f7 100644 --- a/src/running-the-course/course-structure.md +++ b/src/running-the-course/course-structure.md @@ -4,12 +4,13 @@ ## Rust Fundamentals -The first three days make up [Rust Fundaments](../welcome-day-1.md). -The days are fast paced and we cover a lot of ground: +The first three days make up [Rust Fundaments](../welcome-day-1.md). The days +are fast paced and we cover a lot of ground: -* Day 1: Basic Rust, syntax, control flow, creating and consuming values. -* Day 2: Memory management, ownership, compound data types, and the standard library. -* Day 3: Generics, traits, error handling, testing, and unsafe Rust. +- Day 1: Basic Rust, syntax, control flow, creating and consuming values. +- Day 2: Memory management, ownership, compound data types, and the standard + library. +- Day 3: Generics, traits, error handling, testing, and unsafe Rust. ## Deep Dives @@ -18,14 +19,14 @@ specialized topics: ### Rust in Android -The [Rust in Android](../android.md) deep dive is a half-day course on using Rust for -Android platform development. This includes interoperability with C, C++, and -Java. +The [Rust in Android](../android.md) deep dive is a half-day course on using +Rust for Android platform development. This includes interoperability with C, +C++, and Java. -You will need an [AOSP checkout][1]. Make a checkout of the [course -repository][2] on the same machine and move the `src/android/` directory into -the root of your AOSP checkout. This will ensure that the Android build system -sees the `Android.bp` files in `src/android/`. +You will need an [AOSP checkout][1]. Make a checkout of the +[course repository][2] on the same machine and move the `src/android/` directory +into the root of your AOSP checkout. This will ensure that the Android build +system sees the `Android.bp` files in `src/android/`. Ensure that `adb sync` works with your emulator or real device and pre-build all Android examples using `src/android/build_all.sh`. Read the script to see the @@ -36,19 +37,19 @@ commands it runs and make sure they work when you run them by hand. ### Bare-Metal Rust -The [Bare-Metal Rust](../bare-metal.md) deep dive is a full day class on using Rust for -bare-metal (embedded) development. Both microcontrollers and application -processors are covered. +The [Bare-Metal Rust](../bare-metal.md) deep dive is a full day class on using +Rust for bare-metal (embedded) development. Both microcontrollers and +application processors are covered. -For the microcontroller part, you will need to buy the [BBC -micro:bit](https://microbit.org/) v2 development board ahead of time. Everybody -will need to install a number of packages as described on the [welcome -page](../bare-metal.md). +For the microcontroller part, you will need to buy the +[BBC micro:bit](https://microbit.org/) v2 development board ahead of time. +Everybody will need to install a number of packages as described on the +[welcome page](../bare-metal.md). ### Concurrency in Rust -The [Concurrency in Rust](../concurrency.md) deep dive is a full day class on classical -as well as `async`/`await` concurrency. +The [Concurrency in Rust](../concurrency.md) deep dive is a full day class on +classical as well as `async`/`await` concurrency. You will need a fresh crate set up and the dependencies downloaded and ready to go. You can then copy/paste the examples into `src/main.rs` to experiment with diff --git a/src/running-the-course/keyboard-shortcuts.md b/src/running-the-course/keyboard-shortcuts.md index 08a66ac1e319..2e2132067e13 100644 --- a/src/running-the-course/keyboard-shortcuts.md +++ b/src/running-the-course/keyboard-shortcuts.md @@ -2,7 +2,7 @@ There are several useful keyboard shortcuts in mdBook: -* Arrow-Left: Navigate to the previous page. -* Arrow-Right: Navigate to the next page. -* Ctrl + Enter: Execute the code sample that has focus. -* s: Activate the search bar. +- Arrow-Left: Navigate to the previous page. +- Arrow-Right: Navigate to the next page. +- Ctrl + Enter: Execute the code sample that has focus. +- s: Activate the search bar. diff --git a/src/running-the-course/translations.md b/src/running-the-course/translations.md index f1d399042200..d04dcf0d0e55 100644 --- a/src/running-the-course/translations.md +++ b/src/running-the-course/translations.md @@ -3,8 +3,9 @@ The course has been translated into other languages by a set of wonderful volunteers: -* [Brazilian Portuguese][pt-BR] by [@rastringer], [@hugojacob], [@joaovicmendes] and [@henrif75]. -* [Korean][ko] by [@keispace], [@jiyongp] and [@jooyunghan]. +- [Brazilian Portuguese][pt-BR] by [@rastringer], [@hugojacob], [@joaovicmendes] + and [@henrif75]. +- [Korean][ko] by [@keispace], [@jiyongp] and [@jooyunghan]. Use the language picker in the top-right corner to switch between languages. @@ -13,10 +14,10 @@ Use the language picker in the top-right corner to switch between languages. There is a large number of in-progress translations. We link to the most recently updated translations: -* [Bengali][bn] by [@raselmandol]. -* [French][fr] by [@KookaS] and [@vcaen]. -* [German][de] by [@Throvn] and [@ronaldfw]. -* [Japanese][ja] by [@CoinEZ-JPN] and [@momotaro1105]. +- [Bengali][bn] by [@raselmandol]. +- [French][fr] by [@KookaS] and [@vcaen]. +- [German][de] by [@Throvn] and [@ronaldfw]. +- [Japanese][ja] by [@CoinEZ-JPN] and [@momotaro1105]. If you want to help with this effort, please see [our instructions] for how to get going. Translations are coordinated on the [issue tracker]. @@ -27,7 +28,6 @@ get going. Translations are coordinated on the [issue tracker]. [ja]: https://google.github.io/comprehensive-rust/ja/ [ko]: https://google.github.io/comprehensive-rust/ko/ [pt-BR]: https://google.github.io/comprehensive-rust/pt-BR/ - [@CoinEZ-JPN]: https://github.com/CoinEZ [@KookaS]: https://github.com/KookaS [@Throvn]: https://github.com/Throvn @@ -42,6 +42,5 @@ get going. Translations are coordinated on the [issue tracker]. [@vcaen]: https://github.com/vcaen [@joaovicmendes]: https://github.com/joaovicmendes [@henrif75]: https://github.com/henrif75 - [our instructions]: https://github.com/google/comprehensive-rust/blob/main/TRANSLATIONS.md [issue tracker]: https://github.com/google/comprehensive-rust/issues/282 diff --git a/src/std.md b/src/std.md index 048b74045229..2e91b9101c7c 100644 --- a/src/std.md +++ b/src/std.md @@ -6,26 +6,28 @@ smoothly because they both use the same `String` type. The common vocabulary types include: -* [`Option` and `Result`](std/option-result.md) types: used for optional values +- [`Option` and `Result`](std/option-result.md) types: used for optional values and [error handling](error-handling.md). -* [`String`](std/string.md): the default string type used for owned data. +- [`String`](std/string.md): the default string type used for owned data. -* [`Vec`](std/vec.md): a standard extensible vector. +- [`Vec`](std/vec.md): a standard extensible vector. -* [`HashMap`](std/hashmap.md): a hash map type with a configurable hashing +- [`HashMap`](std/hashmap.md): a hash map type with a configurable hashing algorithm. -* [`Box`](std/box.md): an owned pointer for heap-allocated data. +- [`Box`](std/box.md): an owned pointer for heap-allocated data. -* [`Rc`](std/rc.md): a shared reference-counted pointer for heap-allocated data. +- [`Rc`](std/rc.md): a shared reference-counted pointer for heap-allocated data.
- - * In fact, Rust contains several layers of the Standard Library: `core`, `alloc` and `std`. - * `core` includes the most basic types and functions that don't depend on `libc`, allocator or - even the presence of an operating system. - * `alloc` includes types which require a global heap allocator, such as `Vec`, `Box` and `Arc`. - * Embedded Rust applications often only use `core`, and sometimes `alloc`. + +- In fact, Rust contains several layers of the Standard Library: `core`, `alloc` + and `std`. +- `core` includes the most basic types and functions that don't depend on + `libc`, allocator or even the presence of an operating system. +- `alloc` includes types which require a global heap allocator, such as `Vec`, + `Box` and `Arc`. +- Embedded Rust applications often only use `core`, and sometimes `alloc`.
diff --git a/src/std/box-recursive.md b/src/std/box-recursive.md index bc7273ef2993..bc8cc2b4a6c5 100644 --- a/src/std/box-recursive.md +++ b/src/std/box-recursive.md @@ -30,12 +30,15 @@ fn main() {
-* If `Box` was not used and we attempted to embed a `List` directly into the `List`, -the compiler would not compute a fixed size of the struct in memory (`List` would be of infinite size). +- If `Box` was not used and we attempted to embed a `List` directly into the + `List`, the compiler would not compute a fixed size of the struct in memory + (`List` would be of infinite size). -* `Box` solves this problem as it has the same size as a regular pointer and just points at the next -element of the `List` in the heap. +- `Box` solves this problem as it has the same size as a regular pointer and + just points at the next element of the `List` in the heap. + +- Remove the `Box` in the List definition and show the compiler error. + "Recursive with indirection" is a hint you might want to use a Box or + reference of some kind, instead of storing a value directly. -* Remove the `Box` in the List definition and show the compiler error. "Recursive with indirection" is a hint you might want to use a Box or reference of some kind, instead of storing a value directly. -
diff --git a/src/std/box.md b/src/std/box.md index cbd187c698a9..c1ab2238a6e4 100644 --- a/src/std/box.md +++ b/src/std/box.md @@ -9,7 +9,6 @@ fn main() { } ``` - ```bob Stack Heap .- - - - - - -. .- - - - - - -. @@ -23,17 +22,23 @@ fn main() { `- - - - - - -' `- - - - - - -' ``` -`Box` implements `Deref`, which means that you can [call methods -from `T` directly on a `Box`][2]. +`Box` implements `Deref`, which means that you can +[call methods from `T` directly on a `Box`][2]. [1]: https://doc.rust-lang.org/std/boxed/struct.Box.html [2]: https://doc.rust-lang.org/std/ops/trait.Deref.html#more-on-deref-coercion
-* `Box` is like `std::unique_ptr` in C++, except that it's guaranteed to be not null. -* In the above example, you can even leave out the `*` in the `println!` statement thanks to `Deref`. -* A `Box` can be useful when you: - * have a type whose size that can't be known at compile time, but the Rust compiler wants to know an exact size. - * want to transfer ownership of a large amount of data. To avoid copying large amounts of data on the stack, instead store the data on the heap in a `Box` so only the pointer is moved. +- `Box` is like `std::unique_ptr` in C++, except that it's guaranteed to be not + null. +- In the above example, you can even leave out the `*` in the `println!` + statement thanks to `Deref`. +- A `Box` can be useful when you: + - have a type whose size that can't be known at compile time, but the Rust + compiler wants to know an exact size. + - want to transfer ownership of a large amount of data. To avoid copying large + amounts of data on the stack, instead store the data on the heap in a `Box` + so only the pointer is moved. +
diff --git a/src/std/cell.md b/src/std/cell.md index 39bb3a473668..0df044a2fef1 100644 --- a/src/std/cell.md +++ b/src/std/cell.md @@ -2,7 +2,7 @@ [`Cell`](https://doc.rust-lang.org/std/cell/struct.Cell.html) and [`RefCell`](https://doc.rust-lang.org/std/cell/struct.RefCell.html) implement -what Rust calls *interior mutability:* mutation of values in an immutable +what Rust calls _interior mutability:_ mutation of values in an immutable context. `Cell` is typically used for simple types, as it requires copying or moving @@ -44,9 +44,17 @@ fn main() {
-* If we were using `Cell` instead of `RefCell` in this example, we would have to move the `Node` out of the `Rc` to push children, then move it back in. This is safe because there's always one, un-referenced value in the cell, but it's not ergonomic. -* To do anything with a Node, you must call a `RefCell` method, usually `borrow` or `borrow_mut`. -* Demonstrate that reference loops can be created by adding `root` to `subtree.children` (don't try to print it!). -* To demonstrate a runtime panic, add a `fn inc(&mut self)` that increments `self.value` and calls the same method on its children. This will panic in the presence of the reference loop, with `thread 'main' panicked at 'already borrowed: BorrowMutError'`. +- If we were using `Cell` instead of `RefCell` in this example, we would have to + move the `Node` out of the `Rc` to push children, then move it back in. This + is safe because there's always one, un-referenced value in the cell, but it's + not ergonomic. +- To do anything with a Node, you must call a `RefCell` method, usually `borrow` + or `borrow_mut`. +- Demonstrate that reference loops can be created by adding `root` to + `subtree.children` (don't try to print it!). +- To demonstrate a runtime panic, add a `fn inc(&mut self)` that increments + `self.value` and calls the same method on its children. This will panic in the + presence of the reference loop, with + `thread 'main' panicked at 'already borrowed: BorrowMutError'`.
diff --git a/src/std/hashmap.md b/src/std/hashmap.md index dcc3e7c2c8b5..e8d0f9d52644 100644 --- a/src/std/hashmap.md +++ b/src/std/hashmap.md @@ -35,33 +35,42 @@ fn main() {
-* `HashMap` is not defined in the prelude and needs to be brought into scope. -* Try the following lines of code. The first line will see if a book is in the hashmap and if not return an alternative value. The second line will insert the alternative value in the hashmap if the book is not found. +- `HashMap` is not defined in the prelude and needs to be brought into scope. +- Try the following lines of code. The first line will see if a book is in the + hashmap and if not return an alternative value. The second line will insert + the alternative value in the hashmap if the book is not found. - ```rust,ignore - let pc1 = page_counts - .get("Harry Potter and the Sorcerer's Stone ") - .unwrap_or(&336); - let pc2 = page_counts - .entry("The Hunger Games".to_string()) - .or_insert(374); - ``` -* Unlike `vec!`, there is unfortunately no standard `hashmap!` macro. - * Although, since Rust 1.56, HashMap implements [`From<[(K, V); N]>`][1], which allows us to easily initialize a hash map from a literal array: + ```rust,ignore + let pc1 = page_counts + .get("Harry Potter and the Sorcerer's Stone ") + .unwrap_or(&336); + let pc2 = page_counts + .entry("The Hunger Games".to_string()) + .or_insert(374); + ``` +- Unlike `vec!`, there is unfortunately no standard `hashmap!` macro. + - Although, since Rust 1.56, HashMap implements [`From<[(K, V); N]>`][1], + which allows us to easily initialize a hash map from a literal array: - ```rust,ignore - let page_counts = HashMap::from([ - ("Harry Potter and the Sorcerer's Stone".to_string(), 336), - ("The Hunger Games".to_string(), 374), - ]); - ``` + ```rust,ignore + let page_counts = HashMap::from([ + ("Harry Potter and the Sorcerer's Stone".to_string(), 336), + ("The Hunger Games".to_string(), 374), + ]); + ``` - * Alternatively HashMap can be built from any `Iterator` which yields key-value tuples. -* We are showing `HashMap`, and avoid using `&str` as key to make examples easier. Using references in collections can, of course, be done, - but it can lead into complications with the borrow checker. - * Try removing `to_string()` from the example above and see if it still compiles. Where do you think we might run into issues? +- Alternatively HashMap can be built from any `Iterator` which yields key-value + tuples. +- We are showing `HashMap`, and avoid using `&str` as key to make + examples easier. Using references in collections can, of course, be done, but + it can lead into complications with the borrow checker. + - Try removing `to_string()` from the example above and see if it still + compiles. Where do you think we might run into issues? -* This type has several "method-specific" return types, such as `std::collections::hash_map::Keys`. These types often appear in searches of the Rust docs. Show students the docs for this type, and the helpful link back to the `keys` method. +- This type has several "method-specific" return types, such as + `std::collections::hash_map::Keys`. These types often appear in searches of + the Rust docs. Show students the docs for this type, and the helpful link back + to the `keys` method. [1]: https://doc.rust-lang.org/std/collections/hash_map/struct.HashMap.html#impl-From%3C%5B(K,+V);+N%5D%3E-for-HashMap%3CK,+V,+RandomState%3E diff --git a/src/std/option-result.md b/src/std/option-result.md index ff53500c00fd..679b52c0647a 100644 --- a/src/std/option-result.md +++ b/src/std/option-result.md @@ -15,11 +15,13 @@ fn main() {
-* `Option` and `Result` are widely used not just in the standard library. -* `Option<&T>` has zero space overhead compared to `&T`. -* `Result` is the standard type to implement error handling as we will see on Day 3. -* `binary_search` returns `Result`. - * If found, `Result::Ok` holds the index where the element is found. - * Otherwise, `Result::Err` contains the index where such an element should be inserted. +- `Option` and `Result` are widely used not just in the standard library. +- `Option<&T>` has zero space overhead compared to `&T`. +- `Result` is the standard type to implement error handling as we will see on + Day 3. +- `binary_search` returns `Result`. + - If found, `Result::Ok` holds the index where the element is found. + - Otherwise, `Result::Err` contains the index where such an element should be + inserted.
diff --git a/src/std/rc.md b/src/std/rc.md index 73e887e387a4..bd9335eff680 100644 --- a/src/std/rc.md +++ b/src/std/rc.md @@ -15,9 +15,9 @@ fn main() { } ``` -* See [`Arc`][2] and [`Mutex`][3] if you are in a multi-threaded context. -* You can *downgrade* a shared pointer into a [`Weak`][4] pointer to create cycles - that will get dropped. +- See [`Arc`][2] and [`Mutex`][3] if you are in a multi-threaded context. +- You can _downgrade_ a shared pointer into a [`Weak`][4] pointer to create + cycles that will get dropped. [1]: https://doc.rust-lang.org/std/rc/struct.Rc.html [2]: ../concurrency/shared_state/arc.md @@ -26,13 +26,17 @@ fn main() {
-* `Rc`'s count ensures that its contained value is valid for as long as there are references. -* `Rc` in Rust is like `std::shared_ptr` in C++. -* `Rc::clone` is cheap: it creates a pointer to the same allocation and increases the reference count. Does not make a deep clone and can generally be ignored when looking for performance issues in code. -* `make_mut` actually clones the inner value if necessary ("clone-on-write") and returns a mutable reference. -* Use `Rc::strong_count` to check the reference count. -* `Rc::downgrade` gives you a *weakly reference-counted* object to - create cycles that will be dropped properly (likely in combination with - `RefCell`, on the next slide). +- `Rc`'s count ensures that its contained value is valid for as long as there + are references. +- `Rc` in Rust is like `std::shared_ptr` in C++. +- `Rc::clone` is cheap: it creates a pointer to the same allocation and + increases the reference count. Does not make a deep clone and can generally be + ignored when looking for performance issues in code. +- `make_mut` actually clones the inner value if necessary ("clone-on-write") and + returns a mutable reference. +- Use `Rc::strong_count` to check the reference count. +- `Rc::downgrade` gives you a _weakly reference-counted_ object to create cycles + that will be dropped properly (likely in combination with `RefCell`, on the + next slide).
diff --git a/src/std/string.md b/src/std/string.md index 9128ee1338fb..4dd693a98c2d 100644 --- a/src/std/string.md +++ b/src/std/string.md @@ -19,24 +19,35 @@ fn main() { } ``` -`String` implements [`Deref`][2], which means that you can call all -`str` methods on a `String`. +`String` implements [`Deref`][2], which means that you can call +all `str` methods on a `String`. [1]: https://doc.rust-lang.org/std/string/struct.String.html [2]: https://doc.rust-lang.org/std/string/struct.String.html#deref-methods-str
-* `String::new` returns a new empty string, use `String::with_capacity` when you know how much data you want to push to the string. -* `String::len` returns the size of the `String` in bytes (which can be different from its length in characters). -* `String::chars` returns an iterator over the actual characters. Note that a `char` can be different from what a human will consider a "character" due to [grapheme clusters](https://docs.rs/unicode-segmentation/latest/unicode_segmentation/struct.Graphemes.html). -* When people refer to strings they could either be talking about `&str` or `String`. -* When a type implements `Deref`, the compiler will let you transparently call methods from `T`. - * `String` implements `Deref` which transparently gives it access to `str`'s methods. - * Write and compare `let s3 = s1.deref();` and `let s3 = &*s1`;. -* `String` is implemented as a wrapper around a vector of bytes, many of the operations you see supported on vectors are also supported on `String`, but with some extra guarantees. -* Compare the different ways to index a `String`: - * To a character by using `s3.chars().nth(i).unwrap()` where `i` is in-bound, out-of-bounds. - * To a substring by using `s3[0..4]`, where that slice is on character boundaries or not. +- `String::new` returns a new empty string, use `String::with_capacity` when you + know how much data you want to push to the string. +- `String::len` returns the size of the `String` in bytes (which can be + different from its length in characters). +- `String::chars` returns an iterator over the actual characters. Note that a + `char` can be different from what a human will consider a "character" due to + [grapheme clusters](https://docs.rs/unicode-segmentation/latest/unicode_segmentation/struct.Graphemes.html). +- When people refer to strings they could either be talking about `&str` or + `String`. +- When a type implements `Deref`, the compiler will let you + transparently call methods from `T`. + - `String` implements `Deref` which transparently gives it + access to `str`'s methods. + - Write and compare `let s3 = s1.deref();` and `let s3 = &*s1`;. +- `String` is implemented as a wrapper around a vector of bytes, many of the + operations you see supported on vectors are also supported on `String`, but + with some extra guarantees. +- Compare the different ways to index a `String`: + - To a character by using `s3.chars().nth(i).unwrap()` where `i` is in-bound, + out-of-bounds. + - To a substring by using `s3[0..4]`, where that slice is on character + boundaries or not.
diff --git a/src/std/vec.md b/src/std/vec.md index 9ce781572a8e..34491189384a 100644 --- a/src/std/vec.md +++ b/src/std/vec.md @@ -34,16 +34,18 @@ methods on a `Vec`.
-* `Vec` is a type of collection, along with `String` and `HashMap`. The data it contains is stored - on the heap. This means the amount of data doesn't need to be known at compile time. It can grow - or shrink at runtime. -* Notice how `Vec` is a generic type too, but you don't have to specify `T` explicitly. As always - with Rust type inference, the `T` was established during the first `push` call. -* `vec![...]` is a canonical macro to use instead of `Vec::new()` and it supports adding initial - elements to the vector. -* To index the vector you use `[` `]`, but they will panic if out of bounds. Alternatively, using - `get` will return an `Option`. The `pop` function will remove the last element. -* Show iterating over a vector and mutating the value: +- `Vec` is a type of collection, along with `String` and `HashMap`. The data it + contains is stored on the heap. This means the amount of data doesn't need to + be known at compile time. It can grow or shrink at runtime. +- Notice how `Vec` is a generic type too, but you don't have to specify `T` + explicitly. As always with Rust type inference, the `T` was established during + the first `push` call. +- `vec![...]` is a canonical macro to use instead of `Vec::new()` and it + supports adding initial elements to the vector. +- To index the vector you use `[` `]`, but they will panic if out of bounds. + Alternatively, using `get` will return an `Option`. The `pop` function will + remove the last element. +- Show iterating over a vector and mutating the value: `for e in &mut v { *e += 50; }`
diff --git a/src/structs.md b/src/structs.md index 633573c539aa..b90e02565e42 100644 --- a/src/structs.md +++ b/src/structs.md @@ -30,13 +30,19 @@ fn main() { Key Points: -* Structs work like in C or C++. - * Like in C++, and unlike in C, no typedef is needed to define a type. - * Unlike in C++, there is no inheritance between structs. -* Methods are defined in an `impl` block, which we will see in following slides. -* This may be a good time to let people know there are different types of structs. - * Zero-sized structs `e.g., struct Foo;` might be used when implementing a trait on some type but don’t have any data that you want to store in the value itself. - * The next slide will introduce Tuple structs, used when the field names are not important. -* The syntax `..peter` allows us to copy the majority of the fields from the old struct without having to explicitly type it all out. It must always be the last element. +- Structs work like in C or C++. + - Like in C++, and unlike in C, no typedef is needed to define a type. + - Unlike in C++, there is no inheritance between structs. +- Methods are defined in an `impl` block, which we will see in following slides. +- This may be a good time to let people know there are different types of + structs. + - Zero-sized structs `e.g., struct Foo;` might be used when implementing a + trait on some type but don’t have any data that you want to store in the + value itself. + - The next slide will introduce Tuple structs, used when the field names are + not important. +- The syntax `..peter` allows us to copy the majority of the fields from the old + struct without having to explicitly type it all out. It must always be the + last element.
diff --git a/src/structs/field-shorthand.md b/src/structs/field-shorthand.md index 4b5ff253d156..3fba8d46b044 100644 --- a/src/structs/field-shorthand.md +++ b/src/structs/field-shorthand.md @@ -24,49 +24,52 @@ fn main() {
-* The `new` function could be written using `Self` as a type, as it is interchangeable with the struct type name +- The `new` function could be written using `Self` as a type, as it is + interchangeable with the struct type name - ```rust,editable - #[derive(Debug)] - struct Person { - name: String, - age: u8, - } - impl Person { - fn new(name: String, age: u8) -> Self { - Self { name, age } - } - } - ``` -* Implement the `Default` trait for the struct. Define some fields and use the default values for the other fields. + ```rust,editable + #[derive(Debug)] + struct Person { + name: String, + age: u8, + } + impl Person { + fn new(name: String, age: u8) -> Self { + Self { name, age } + } + } + ``` +- Implement the `Default` trait for the struct. Define some fields and use the + default values for the other fields. - ```rust,editable - #[derive(Debug)] - struct Person { - name: String, - age: u8, - } - impl Default for Person { - fn default() -> Person { - Person { - name: "Bot".to_string(), - age: 0, - } - } - } - fn create_default() { - let tmp = Person { - ..Person::default() - }; - let tmp = Person { - name: "Sam".to_string(), - ..Person::default() - }; - } - ``` + ```rust,editable + #[derive(Debug)] + struct Person { + name: String, + age: u8, + } + impl Default for Person { + fn default() -> Person { + Person { + name: "Bot".to_string(), + age: 0, + } + } + } + fn create_default() { + let tmp = Person { + ..Person::default() + }; + let tmp = Person { + name: "Sam".to_string(), + ..Person::default() + }; + } + ``` -* Methods are defined in the `impl` block. -* Use struct update syntax to define a new structure using `peter`. Note that the variable `peter` will no longer be accessible afterwards. -* Use `{:#?}` when printing structs to request the `Debug` representation. +- Methods are defined in the `impl` block. +- Use struct update syntax to define a new structure using `peter`. Note that + the variable `peter` will no longer be accessible afterwards. +- Use `{:#?}` when printing structs to request the `Debug` representation.
diff --git a/src/structs/tuple-structs.md b/src/structs/tuple-structs.md index eba10c1ad5e7..fa171cbea971 100644 --- a/src/structs/tuple-structs.md +++ b/src/structs/tuple-structs.md @@ -29,16 +29,22 @@ fn main() { let force = compute_thruster_force(); set_thruster_force(force); } - ```
-* Newtypes are a great way to encode additional information about the value in a primitive type, for example: - * The number is measured in some units: `Newtons` in the example above. - * The value passed some validation when it was created, so you no longer have to validate it again at every use: 'PhoneNumber(String)` or `OddNumber(u32)`. -* Demonstrate how to add a `f64` value to a `Newtons` type by accessing the single field in the newtype. - * Rust generally doesn’t like inexplicit things, like automatic unwrapping or for instance using booleans as integers. - * Operator overloading is discussed on Day 3 (generics). -* The example is a subtle reference to the [Mars Climate Orbiter](https://en.wikipedia.org/wiki/Mars_Climate_Orbiter) failure. +- Newtypes are a great way to encode additional information about the value in a + primitive type, for example: + - The number is measured in some units: `Newtons` in the example above. + - The value passed some validation when it was created, so you no longer have + to validate it again at every use: 'PhoneNumber(String)`or`OddNumber(u32)`. +- Demonstrate how to add a `f64` value to a `Newtons` type by accessing the + single field in the newtype. + - Rust generally doesn’t like inexplicit things, like automatic unwrapping or + for instance using booleans as integers. + - Operator overloading is discussed on Day 3 (generics). +- The example is a subtle reference to the + [Mars Climate Orbiter](https://en.wikipedia.org/wiki/Mars_Climate_Orbiter) + failure. +
diff --git a/src/testing.md b/src/testing.md index 16f6793509ea..cfaf5b340984 100644 --- a/src/testing.md +++ b/src/testing.md @@ -2,6 +2,6 @@ Rust and Cargo come with a simple unit test framework: -* Unit tests are supported throughout your code. +- Unit tests are supported throughout your code. -* Integration tests are supported via the `tests/` directory. +- Integration tests are supported via the `tests/` directory. diff --git a/src/testing/doc-tests.md b/src/testing/doc-tests.md index 86e9e968c483..5c659dabbe86 100644 --- a/src/testing/doc-tests.md +++ b/src/testing/doc-tests.md @@ -2,7 +2,7 @@ Rust has built-in support for documentation tests: -```rust +````rust /// Shortens a string to the given length. /// /// ``` @@ -13,8 +13,9 @@ Rust has built-in support for documentation tests: pub fn shorten_string(s: &str, length: usize) -> &str { &s[..std::cmp::min(length, s.len())] } -``` +```` -* Code blocks in `///` comments are automatically seen as Rust code. -* The code will be compiled and executed as part of `cargo test`. -* Test the above code on the [Rust Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=3ce2ad13ea1302f6572cb15cd96becf0). +- Code blocks in `///` comments are automatically seen as Rust code. +- The code will be compiled and executed as part of `cargo test`. +- Test the above code on the + [Rust Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=3ce2ad13ea1302f6572cb15cd96becf0). diff --git a/src/testing/test-modules.md b/src/testing/test-modules.md index a89bd098b352..f2ecb8229cfa 100644 --- a/src/testing/test-modules.md +++ b/src/testing/test-modules.md @@ -23,5 +23,5 @@ mod tests { } ``` -* This lets you unit test private helpers. -* The `#[cfg(test)]` attribute is only active when you run `cargo test`. +- This lets you unit test private helpers. +- The `#[cfg(test)]` attribute is only active when you run `cargo test`. diff --git a/src/testing/useful-crates.md b/src/testing/useful-crates.md index 7435643d6c39..c504c8082b51 100644 --- a/src/testing/useful-crates.md +++ b/src/testing/useful-crates.md @@ -4,6 +4,8 @@ Rust comes with only basic support for writing tests. Here are some additional crates which we recommend for writing tests: -* [googletest](https://docs.rs/googletest): Comprehensive test assertion library in the tradition of GoogleTest for C++. -* [proptest](https://docs.rs/proptest): Property-based testing for Rust. -* [rstest](https://docs.rs/rstest): Support for fixtures and parameterised tests. +- [googletest](https://docs.rs/googletest): Comprehensive test assertion library + in the tradition of GoogleTest for C++. +- [proptest](https://docs.rs/proptest): Property-based testing for Rust. +- [rstest](https://docs.rs/rstest): Support for fixtures and parameterised + tests. diff --git a/src/thanks.md b/src/thanks.md index c7c2103116e8..c63c69267a43 100644 --- a/src/thanks.md +++ b/src/thanks.md @@ -5,6 +5,5 @@ was useful. We've had a lot of fun putting the course together. The course is not perfect, so if you spotted any mistakes or have ideas for improvements, please get in -[contact with us on -GitHub](https://github.com/google/comprehensive-rust/discussions). We would love -to hear from you. +[contact with us on GitHub](https://github.com/google/comprehensive-rust/discussions). +We would love to hear from you. diff --git a/src/traits/closures.md b/src/traits/closures.md index c09cce6cf129..4274017beb7b 100644 --- a/src/traits/closures.md +++ b/src/traits/closures.md @@ -31,24 +31,25 @@ fn main() {
-An `Fn` (e.g. `add_3`) neither consumes nor mutates captured values, or perhaps captures -nothing at all. It can be called multiple times concurrently. +An `Fn` (e.g. `add_3`) neither consumes nor mutates captured values, or perhaps +captures nothing at all. It can be called multiple times concurrently. -An `FnMut` (e.g. `accumulate`) might mutate captured values. You can call it multiple times, -but not concurrently. +An `FnMut` (e.g. `accumulate`) might mutate captured values. You can call it +multiple times, but not concurrently. -If you have an `FnOnce` (e.g. `multiply_sum`), you may only call it once. It might consume -captured values. +If you have an `FnOnce` (e.g. `multiply_sum`), you may only call it once. It +might consume captured values. -`FnMut` is a subtype of `FnOnce`. `Fn` is a subtype of `FnMut` and `FnOnce`. I.e. you can use an -`FnMut` wherever an `FnOnce` is called for, and you can use an `Fn` wherever an `FnMut` or `FnOnce` -is called for. +`FnMut` is a subtype of `FnOnce`. `Fn` is a subtype of `FnMut` and `FnOnce`. +I.e. you can use an `FnMut` wherever an `FnOnce` is called for, and you can use +an `Fn` wherever an `FnMut` or `FnOnce` is called for. -The compiler also infers `Copy` (e.g. for `add_3`) and `Clone` (e.g. `multiply_sum`), -depending on what the closure captures. +The compiler also infers `Copy` (e.g. for `add_3`) and `Clone` (e.g. +`multiply_sum`), depending on what the closure captures. + +By default, closures will capture by reference if they can. The `move` keyword +makes them capture by value. -By default, closures will capture by reference if they can. The `move` keyword makes them capture -by value. ```rust,editable fn make_greeter(prefix: String) -> impl Fn(&str) { return move |name| println!("{} {}", prefix, name) diff --git a/src/traits/default-methods.md b/src/traits/default-methods.md index d48a314004fa..d25dc1413ad0 100644 --- a/src/traits/default-methods.md +++ b/src/traits/default-methods.md @@ -29,32 +29,34 @@ fn main() {
-* Traits may specify pre-implemented (default) methods and methods that users are required to - implement themselves. Methods with default implementations can rely on required methods. +- Traits may specify pre-implemented (default) methods and methods that users + are required to implement themselves. Methods with default implementations can + rely on required methods. + +- Move method `not_equals` to a new trait `NotEquals`. + +- Make `Equals` a super trait for `NotEquals`. + ```rust,editable,compile_fail + trait NotEquals: Equals { + fn not_equals(&self, other: &Self) -> bool { + !self.equals(other) + } + } + ``` + +- Provide a blanket implementation of `NotEquals` for `Equals`. + ```rust,editable,compile_fail + trait NotEquals { + fn not_equals(&self, other: &Self) -> bool; + } + + impl NotEquals for T where T: Equals { + fn not_equals(&self, other: &Self) -> bool { + !self.equals(other) + } + } + ``` + - With the blanket implementation, you no longer need `Equals` as a super + trait for `NotEqual`. -* Move method `not_equals` to a new trait `NotEquals`. - -* Make `Equals` a super trait for `NotEquals`. - ```rust,editable,compile_fail - trait NotEquals: Equals { - fn not_equals(&self, other: &Self) -> bool { - !self.equals(other) - } - } - ``` - -* Provide a blanket implementation of `NotEquals` for `Equals`. - ```rust,editable,compile_fail - trait NotEquals { - fn not_equals(&self, other: &Self) -> bool; - } - - impl NotEquals for T where T: Equals { - fn not_equals(&self, other: &Self) -> bool { - !self.equals(other) - } - } - ``` - * With the blanket implementation, you no longer need `Equals` as a super trait for `NotEqual`. -
diff --git a/src/traits/default.md b/src/traits/default.md index 321116e9b314..f8f9fada53c9 100644 --- a/src/traits/default.md +++ b/src/traits/default.md @@ -32,20 +32,22 @@ fn main() { let nothing: Option = None; println!("{:#?}", nothing.unwrap_or_default()); } - ```
- * It can be implemented directly or it can be derived via `#[derive(Default)]`. - * A derived implementation will produce a value where all fields are set to their default values. - * This means all types in the struct must implement `Default` too. - * Standard Rust types often implement `Default` with reasonable values (e.g. `0`, `""`, etc). - * The partial struct copy works nicely with default. - * Rust standard library is aware that types can implement `Default` and provides convenience methods that use it. - * the `..` syntax is called [struct update syntax][2] +- It can be implemented directly or it can be derived via `#[derive(Default)]`. +- A derived implementation will produce a value where all fields are set to + their default values. + - This means all types in the struct must implement `Default` too. +- Standard Rust types often implement `Default` with reasonable values (e.g. + `0`, `""`, etc). +- The partial struct copy works nicely with default. +- Rust standard library is aware that types can implement `Default` and provides + convenience methods that use it. +- the `..` syntax is called [struct update syntax][2]
[1]: https://doc.rust-lang.org/std/default/trait.Default.html -[2]: https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax \ No newline at end of file +[2]: https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax diff --git a/src/traits/deriving-traits.md b/src/traits/deriving-traits.md index 843f6009573c..b2e3ea487110 100644 --- a/src/traits/deriving-traits.md +++ b/src/traits/deriving-traits.md @@ -1,6 +1,7 @@ # Deriving Traits -Rust derive macros work by automatically generating code that implements the specified traits for a data structure. +Rust derive macros work by automatically generating code that implements the +specified traits for a data structure. You can let the compiler derive a number of traits as follows: diff --git a/src/traits/drop.md b/src/traits/drop.md index 7e9af839b2b7..e199916f6070 100644 --- a/src/traits/drop.md +++ b/src/traits/drop.md @@ -1,6 +1,7 @@ # The `Drop` Trait -Values which implement [`Drop`][1] can specify code to run when they go out of scope: +Values which implement [`Drop`][1] can specify code to run when they go out of +scope: ```rust,editable struct Droppable { @@ -33,11 +34,10 @@ fn main() { Discussion points: -* Why doesn't `Drop::drop` take `self`? - * Short-answer: If it did, `std::mem::drop` would be called at the end of - the block, resulting in another call to `Drop::drop`, and a stack - overflow! -* Try replacing `drop(a)` with `a.drop()`. +- Why doesn't `Drop::drop` take `self`? + - Short-answer: If it did, `std::mem::drop` would be called at the end of the + block, resulting in another call to `Drop::drop`, and a stack overflow! +- Try replacing `drop(a)` with `a.drop()`.
diff --git a/src/traits/from-into.md b/src/traits/from-into.md index fe4804410211..540ca16087e2 100644 --- a/src/traits/from-into.md +++ b/src/traits/from-into.md @@ -25,11 +25,14 @@ fn main() { ```
- -* That's why it is common to only implement `From`, as your type will get `Into` implementation too. -* When declaring a function argument input type like "anything that can be converted into a `String`", the rule is opposite, you should use `Into`. - Your function will accept types that implement `From` and those that _only_ implement `Into`. - + +- That's why it is common to only implement `From`, as your type will get `Into` + implementation too. +- When declaring a function argument input type like "anything that can be + converted into a `String`", the rule is opposite, you should use `Into`. Your + function will accept types that implement `From` and those that _only_ + implement `Into`. +
[1]: https://doc.rust-lang.org/std/convert/trait.From.html diff --git a/src/traits/from-iterator.md b/src/traits/from-iterator.md index 4fa3ac9c4a12..7db305b47c14 100644 --- a/src/traits/from-iterator.md +++ b/src/traits/from-iterator.md @@ -15,10 +15,7 @@ fn main() {
`Iterator` implements -`fn collect(self) -> B -where - B: FromIterator, - Self: Sized` +`fn collect(self) -> B where B: FromIterator, Self: Sized` There are also implementations which let you do cool things like convert an `Iterator>` into a `Result, E>`. diff --git a/src/traits/impl-trait.md b/src/traits/impl-trait.md index c48348dc5549..7fe53143c38c 100644 --- a/src/traits/impl-trait.md +++ b/src/traits/impl-trait.md @@ -16,29 +16,32 @@ fn main() { } ``` -* `impl Trait` allows you to work with types which you cannot name. +- `impl Trait` allows you to work with types which you cannot name.
The meaning of `impl Trait` is a bit different in the different positions. -* For a parameter, `impl Trait` is like an anonymous generic parameter with a trait bound. +- For a parameter, `impl Trait` is like an anonymous generic parameter with a + trait bound. -* For a return type, it means that the return type is some concrete type that implements the trait, - without naming the type. This can be useful when you don't want to expose the concrete type in a - public API. +- For a return type, it means that the return type is some concrete type that + implements the trait, without naming the type. This can be useful when you + don't want to expose the concrete type in a public API. Inference is hard in return position. A function returning `impl Foo` picks the concrete type it returns, without writing it out in the source. A function returning a generic type like `collect() -> B` can return any type - satisfying `B`, and the caller may need to choose one, such as with `let x: - Vec<_> = foo.collect()` or with the turbofish, `foo.collect::>()`. - -This example is great, because it uses `impl Display` twice. It helps to explain that -nothing here enforces that it is _the same_ `impl Display` type. If we used a single -`T: Display`, it would enforce the constraint that input `T` and return `T` type are the same type. -It would not work for this particular function, as the type we expect as input is likely not -what `format!` returns. If we wanted to do the same via `: Display` syntax, we'd need two -independent generic parameters. + satisfying `B`, and the caller may need to choose one, such as with + `let x: Vec<_> = foo.collect()` or with the turbofish, + `foo.collect::>()`. + +This example is great, because it uses `impl Display` twice. It helps to explain +that nothing here enforces that it is _the same_ `impl Display` type. If we used +a single `T: Display`, it would enforce the constraint that input `T` and return +`T` type are the same type. It would not work for this particular function, as +the type we expect as input is likely not what `format!` returns. If we wanted +to do the same via `: Display` syntax, we'd need two independent generic +parameters.
diff --git a/src/traits/important-traits.md b/src/traits/important-traits.md index b7ce73623ef5..5dcbb40cb939 100644 --- a/src/traits/important-traits.md +++ b/src/traits/important-traits.md @@ -2,12 +2,12 @@ We will now look at some of the most common traits of the Rust standard library: -* [`Iterator`][1] and [`IntoIterator`][2] used in `for` loops, -* [`From`][3] and [`Into`][4] used to convert values, -* [`Read`][5] and [`Write`][6] used for IO, -* [`Add`][7], [`Mul`][8], ... used for operator overloading, and -* [`Drop`][9] used for defining destructors. -* [`Default`][10] used to construct a default instance of a type. +- [`Iterator`][1] and [`IntoIterator`][2] used in `for` loops, +- [`From`][3] and [`Into`][4] used to convert values, +- [`Read`][5] and [`Write`][6] used for IO, +- [`Add`][7], [`Mul`][8], ... used for operator overloading, and +- [`Drop`][9] used for defining destructors. +- [`Default`][10] used to construct a default instance of a type. [1]: https://doc.rust-lang.org/std/iter/trait.Iterator.html [2]: https://doc.rust-lang.org/std/iter/trait.IntoIterator.html diff --git a/src/traits/iterator.md b/src/traits/iterator.md index b730c3541662..867aea949827 100644 --- a/src/traits/iterator.md +++ b/src/traits/iterator.md @@ -29,15 +29,15 @@ fn main() {
-* The `Iterator` trait implements many common functional programming operations over collections - (e.g. `map`, `filter`, `reduce`, etc). This is the trait where you can find all the documentation - about them. In Rust these functions should produce the code as efficient as equivalent imperative - implementations. - -* `IntoIterator` is the trait that makes for loops work. It is implemented by collection types such as - `Vec` and references to them such as `&Vec` and `&[T]`. Ranges also implement it. This is why - you can iterate over a vector with `for i in some_vec { .. }` but - `some_vec.next()` doesn't exist. +- The `Iterator` trait implements many common functional programming operations + over collections (e.g. `map`, `filter`, `reduce`, etc). This is the trait + where you can find all the documentation about them. In Rust these functions + should produce the code as efficient as equivalent imperative implementations. + +- `IntoIterator` is the trait that makes for loops work. It is implemented by + collection types such as `Vec` and references to them such as `&Vec` and + `&[T]`. Ranges also implement it. This is why you can iterate over a vector + with `for i in some_vec { .. }` but `some_vec.next()` doesn't exist.
diff --git a/src/traits/operators.md b/src/traits/operators.md index 99e78394786b..bf3fd6f57157 100644 --- a/src/traits/operators.md +++ b/src/traits/operators.md @@ -25,16 +25,16 @@ fn main() { Discussion points: -* You could implement `Add` for `&Point`. In which situations is that useful? - * Answer: `Add:add` consumes `self`. If type `T` for which you are - overloading the operator is not `Copy`, you should consider overloading - the operator for `&T` as well. This avoids unnecessary cloning on the - call site. -* Why is `Output` an associated type? Could it be made a type parameter of the method? - * Short answer: Function type parameters are controlled by the caller, but - associated types (like `Output`) are controlled by the implementor of a - trait. -* You could implement `Add` for two different types, e.g. +- You could implement `Add` for `&Point`. In which situations is that useful? + - Answer: `Add:add` consumes `self`. If type `T` for which you are overloading + the operator is not `Copy`, you should consider overloading the operator for + `&T` as well. This avoids unnecessary cloning on the call site. +- Why is `Output` an associated type? Could it be made a type parameter of the + method? + - Short answer: Function type parameters are controlled by the caller, but + associated types (like `Output`) are controlled by the implementor of a + trait. +- You could implement `Add` for two different types, e.g. `impl Add<(i32, i32)> for Point` would add a tuple to a `Point`.
diff --git a/src/traits/trait-bounds.md b/src/traits/trait-bounds.md index 9e5f5eb6dcff..3259e28e5ab9 100644 --- a/src/traits/trait-bounds.md +++ b/src/traits/trait-bounds.md @@ -33,7 +33,7 @@ fn main() {
Show a `where` clause, students will encounter it when reading code. - + ```rust,ignore fn duplicate(a: T) -> (T, T) where @@ -43,8 +43,9 @@ where } ``` -* It declutters the function signature if you have many parameters. -* It has additional features making it more powerful. - * If someone asks, the extra feature is that the type on the left of ":" can be arbitrary, like `Option`. - +- It declutters the function signature if you have many parameters. +- It has additional features making it more powerful. + - If someone asks, the extra feature is that the type on the left of ":" can + be arbitrary, like `Option`. +
diff --git a/src/traits/trait-objects.md b/src/traits/trait-objects.md index 584c819c848c..ed0a7f387f05 100644 --- a/src/traits/trait-objects.md +++ b/src/traits/trait-objects.md @@ -36,7 +36,6 @@ fn main() { } ``` - Memory layout after allocating `pets`: ```bob @@ -64,20 +63,24 @@ Memory layout after allocating `pets`: : +----------------------+ : : : '- - - - - - - - - - - - - - - - - - - - - - -' - ```
-* Types that implement a given trait may be of different sizes. This makes it impossible to have things like `Vec` in the example above. -* `dyn Pet` is a way to tell the compiler about a dynamically sized type that implements `Pet`. -* In the example, `pets` holds *fat pointers* to objects that implement `Pet`. The fat pointer consists of two components, a pointer to the actual object and a pointer to the virtual method table for the `Pet` implementation of that particular object. -* Compare these outputs in the above example: - ```rust,ignore - println!("{} {}", std::mem::size_of::(), std::mem::size_of::()); - println!("{} {}", std::mem::size_of::<&Dog>(), std::mem::size_of::<&Cat>()); - println!("{}", std::mem::size_of::<&dyn Pet>()); - println!("{}", std::mem::size_of::>()); - ``` +- Types that implement a given trait may be of different sizes. This makes it + impossible to have things like `Vec` in the example above. +- `dyn Pet` is a way to tell the compiler about a dynamically sized type that + implements `Pet`. +- In the example, `pets` holds _fat pointers_ to objects that implement `Pet`. + The fat pointer consists of two components, a pointer to the actual object and + a pointer to the virtual method table for the `Pet` implementation of that + particular object. +- Compare these outputs in the above example: + ```rust,ignore + println!("{} {}", std::mem::size_of::(), std::mem::size_of::()); + println!("{} {}", std::mem::size_of::<&Dog>(), std::mem::size_of::<&Cat>()); + println!("{}", std::mem::size_of::<&dyn Pet>()); + println!("{}", std::mem::size_of::>()); + ```
diff --git a/src/unsafe.md b/src/unsafe.md index bbbab83b4e2e..a6f1e6c47bc3 100644 --- a/src/unsafe.md +++ b/src/unsafe.md @@ -2,22 +2,22 @@ The Rust language has two parts: -* **Safe Rust:** memory safe, no undefined behavior possible. -* **Unsafe Rust:** can trigger undefined behavior if preconditions are violated. +- **Safe Rust:** memory safe, no undefined behavior possible. +- **Unsafe Rust:** can trigger undefined behavior if preconditions are violated. We will be seeing mostly safe Rust in this course, but it's important to know what Unsafe Rust is. -Unsafe code is usually small and isolated, and its correctness should be carefully -documented. It is usually wrapped in a safe abstraction layer. +Unsafe code is usually small and isolated, and its correctness should be +carefully documented. It is usually wrapped in a safe abstraction layer. Unsafe Rust gives you access to five new capabilities: -* Dereference raw pointers. -* Access or modify mutable static variables. -* Access `union` fields. -* Call `unsafe` functions, including `extern` functions. -* Implement `unsafe` traits. +- Dereference raw pointers. +- Access or modify mutable static variables. +- Access `union` fields. +- Call `unsafe` functions, including `extern` functions. +- Implement `unsafe` traits. We will briefly cover unsafe capabilities next. For full details, please see [Chapter 19.1 in the Rust Book](https://doc.rust-lang.org/book/ch19-01-unsafe-rust.html) diff --git a/src/unsafe/extern-functions.md b/src/unsafe/extern-functions.md index bc7f2eb6f51c..e7c5cb64a09e 100644 --- a/src/unsafe/extern-functions.md +++ b/src/unsafe/extern-functions.md @@ -18,9 +18,9 @@ fn main() {
-This is usually only a problem for extern functions which do things with pointers which might -violate Rust's memory model, but in general any C function might have undefined behaviour under any -arbitrary circumstances. +This is usually only a problem for extern functions which do things with +pointers which might violate Rust's memory model, but in general any C function +might have undefined behaviour under any arbitrary circumstances. The `"C"` in this example is the ABI; [other ABIs are available too](https://doc.rust-lang.org/reference/items/external-blocks.html). diff --git a/src/unsafe/mutable-static-variables.md b/src/unsafe/mutable-static-variables.md index 75cf49e3732a..ffc241b6e6ea 100644 --- a/src/unsafe/mutable-static-variables.md +++ b/src/unsafe/mutable-static-variables.md @@ -29,7 +29,8 @@ fn main() {
-Using a mutable static is generally a bad idea, but there are some cases where it might make sense -in low-level `no_std` code, such as implementing a heap allocator or working with some C APIs. +Using a mutable static is generally a bad idea, but there are some cases where +it might make sense in low-level `no_std` code, such as implementing a heap +allocator or working with some C APIs.
diff --git a/src/unsafe/raw-pointers.md b/src/unsafe/raw-pointers.md index f2175660ce9b..23a1edd0369f 100644 --- a/src/unsafe/raw-pointers.md +++ b/src/unsafe/raw-pointers.md @@ -24,19 +24,20 @@ fn main() {
-It is good practice (and required by the Android Rust style guide) to write a comment for each -`unsafe` block explaining how the code inside it satisfies the safety requirements of the unsafe -operations it is doing. +It is good practice (and required by the Android Rust style guide) to write a +comment for each `unsafe` block explaining how the code inside it satisfies the +safety requirements of the unsafe operations it is doing. In the case of pointer dereferences, this means that the pointers must be [_valid_](https://doc.rust-lang.org/std/ptr/index.html#safety), i.e.: - * The pointer must be non-null. - * The pointer must be _dereferenceable_ (within the bounds of a single allocated object). - * The object must not have been deallocated. - * There must not be concurrent accesses to the same location. - * If the pointer was obtained by casting a reference, the underlying object must be live and no - reference may be used to access the memory. +- The pointer must be non-null. +- The pointer must be _dereferenceable_ (within the bounds of a single allocated + object). +- The object must not have been deallocated. +- There must not be concurrent accesses to the same location. +- If the pointer was obtained by casting a reference, the underlying object must + be live and no reference may be used to access the memory. In most cases the pointer must also be properly aligned. diff --git a/src/unsafe/unions.md b/src/unsafe/unions.md index 02f03e0fa481..67421260bd38 100644 --- a/src/unsafe/unions.md +++ b/src/unsafe/unions.md @@ -18,11 +18,12 @@ fn main() {
-Unions are very rarely needed in Rust as you can usually use an enum. They are occasionally needed -for interacting with C library APIs. +Unions are very rarely needed in Rust as you can usually use an enum. They are +occasionally needed for interacting with C library APIs. If you just want to reinterpret bytes as a different type, you probably want -[`std::mem::transmute`](https://doc.rust-lang.org/stable/std/mem/fn.transmute.html) or a safe -wrapper such as the [`zerocopy`](https://crates.io/crates/zerocopy) crate. +[`std::mem::transmute`](https://doc.rust-lang.org/stable/std/mem/fn.transmute.html) +or a safe wrapper such as the [`zerocopy`](https://crates.io/crates/zerocopy) +crate.
diff --git a/src/unsafe/unsafe-traits.md b/src/unsafe/unsafe-traits.md index 060b63bf08ca..77c390d48338 100644 --- a/src/unsafe/unsafe-traits.md +++ b/src/unsafe/unsafe-traits.md @@ -1,7 +1,7 @@ # Implementing Unsafe Traits -Like with functions, you can mark a trait as `unsafe` if the implementation must guarantee -particular conditions to avoid undefined behaviour. +Like with functions, you can mark a trait as `unsafe` if the implementation must +guarantee particular conditions to avoid undefined behaviour. For example, the `zerocopy` crate has an unsafe trait that looks [something like this](https://docs.rs/zerocopy/latest/zerocopy/trait.AsBytes.html): @@ -27,8 +27,8 @@ unsafe impl AsBytes for u32 {}
-There should be a `# Safety` section on the Rustdoc for the trait explaining the requirements for -the trait to be safely implemented. +There should be a `# Safety` section on the Rustdoc for the trait explaining the +requirements for the trait to be safely implemented. The actual safety section for `AsBytes` is rather longer and more complicated. diff --git a/src/unsafe/writing-unsafe-functions.md b/src/unsafe/writing-unsafe-functions.md index e1ea3f7de4e6..3bdf4dad04aa 100644 --- a/src/unsafe/writing-unsafe-functions.md +++ b/src/unsafe/writing-unsafe-functions.md @@ -1,7 +1,7 @@ # Writing Unsafe Functions -You can mark your own functions as `unsafe` if they require particular conditions to avoid undefined -behaviour. +You can mark your own functions as `unsafe` if they require particular +conditions to avoid undefined behaviour. ```rust,editable /// Swaps the values pointed to by the given pointers. @@ -30,9 +30,11 @@ fn main() {
-We wouldn't actually use pointers for this because it can be done safely with references. +We wouldn't actually use pointers for this because it can be done safely with +references. -Note that unsafe code is allowed within an unsafe function without an `unsafe` block. We can -prohibit this with `#[deny(unsafe_op_in_unsafe_fn)]`. Try adding it and see what happens. +Note that unsafe code is allowed within an unsafe function without an `unsafe` +block. We can prohibit this with `#[deny(unsafe_op_in_unsafe_fn)]`. Try adding +it and see what happens.
diff --git a/src/welcome-day-1.md b/src/welcome-day-1.md index 39cea21b0ed5..bbe99dcc22eb 100644 --- a/src/welcome-day-1.md +++ b/src/welcome-day-1.md @@ -1,30 +1,29 @@ # Welcome to Day 1 -This is the first day of Rust Fundamentals. We will cover a lot of ground -today: +This is the first day of Rust Fundamentals. We will cover a lot of ground today: -* Basic Rust syntax: variables, scalar and compound types, enums, structs, +- Basic Rust syntax: variables, scalar and compound types, enums, structs, references, functions, and methods. -* Control flow constructs: `if`, `if let`, `while`, `while let`, `break`, and +- Control flow constructs: `if`, `if let`, `while`, `while let`, `break`, and `continue`. -* Pattern matching: destructuring enums, structs, and arrays. +- Pattern matching: destructuring enums, structs, and arrays.
Please remind the students that: -* They should ask questions when they get them, don't save them to the end. -* The class is meant to be interactive and discussions are very much encouraged! - * As an instructor, you should try to keep the discussions relevant, i.e., - keep the discussions related to how Rust does things vs some other language. - It can be hard to find the right balance, but err on the side of allowing +- They should ask questions when they get them, don't save them to the end. +- The class is meant to be interactive and discussions are very much encouraged! + - As an instructor, you should try to keep the discussions relevant, i.e., + keep the discussions related to how Rust does things vs some other language. + It can be hard to find the right balance, but err on the side of allowing discussions since they engage people much more than one-way communication. -* The questions will likely mean that we talk about things ahead of the slides. - * This is perfectly okay! Repetition is an important part of learning. Remember - that the slides are just a support and you are free to skip them as you - like. +- The questions will likely mean that we talk about things ahead of the slides. + - This is perfectly okay! Repetition is an important part of learning. + Remember that the slides are just a support and you are free to skip them as + you like. The idea for the first day is to show _just enough_ of Rust to be able to speak about the famous borrow checker. The way Rust handles memory is a major feature @@ -33,8 +32,8 @@ and we should show students this right away. If you're teaching this in a classroom, this is a good place to go over the schedule. We suggest splitting the day into two parts (following the slides): -* Morning: 9:00 to 12:00, -* Afternoon: 13:00 to 16:00. +- Morning: 9:00 to 12:00, +- Afternoon: 13:00 to 16:00. You can of course adjust this as necessary. Please make sure to include breaks, we recommend a break every hour! diff --git a/src/welcome-day-1/what-is-rust.md b/src/welcome-day-1/what-is-rust.md index 3e821720b2ad..0c0914f268c1 100644 --- a/src/welcome-day-1/what-is-rust.md +++ b/src/welcome-day-1/what-is-rust.md @@ -2,29 +2,28 @@ Rust is a new programming language which had its [1.0 release in 2015][1]: -* Rust is a statically compiled language in a similar role as C++ - * `rustc` uses LLVM as its backend. -* Rust supports many [platforms and - architectures](https://doc.rust-lang.org/nightly/rustc/platform-support.html): - * x86, ARM, WebAssembly, ... - * Linux, Mac, Windows, ... -* Rust is used for a wide range of devices: - * firmware and boot loaders, - * smart displays, - * mobile phones, - * desktops, - * servers. - +- Rust is a statically compiled language in a similar role as C++ + - `rustc` uses LLVM as its backend. +- Rust supports many + [platforms and architectures](https://doc.rust-lang.org/nightly/rustc/platform-support.html): + - x86, ARM, WebAssembly, ... + - Linux, Mac, Windows, ... +- Rust is used for a wide range of devices: + - firmware and boot loaders, + - smart displays, + - mobile phones, + - desktops, + - servers.
Rust fits in the same area as C++: -* High flexibility. -* High level of control. -* Can be scaled down to very constrained devices such as microcontrollers. -* Has no runtime or garbage collection. -* Focuses on reliability and safety without sacrificing performance. +- High flexibility. +- High level of control. +- Can be scaled down to very constrained devices such as microcontrollers. +- Has no runtime or garbage collection. +- Focuses on reliability and safety without sacrificing performance.
diff --git a/src/welcome-day-2.md b/src/welcome-day-2.md index a86e6dbeca18..a7a3005c262c 100644 --- a/src/welcome-day-2.md +++ b/src/welcome-day-2.md @@ -2,14 +2,14 @@ Now that we have seen a fair amount of Rust, we will continue with: -* Memory management: stack vs heap, manual memory management, scope-based memory +- Memory management: stack vs heap, manual memory management, scope-based memory management, and garbage collection. -* Ownership: move semantics, copying and cloning, borrowing, and lifetimes. +- Ownership: move semantics, copying and cloning, borrowing, and lifetimes. -* Structs and methods. +- Structs and methods. -* The Standard Library: `String`, `Option` and `Result`, `Vec`, `HashMap`, `Rc` +- The Standard Library: `String`, `Option` and `Result`, `Vec`, `HashMap`, `Rc` and `Arc`. -* Modules: visibility, paths, and filesystem hierarchy. +- Modules: visibility, paths, and filesystem hierarchy. diff --git a/src/welcome-day-3.md b/src/welcome-day-3.md index 8e2fcf685023..cb38c13ca175 100644 --- a/src/welcome-day-3.md +++ b/src/welcome-day-3.md @@ -2,15 +2,15 @@ Today, we will cover some more advanced topics of Rust: -* Traits: deriving traits, default methods, and important standard library +- Traits: deriving traits, default methods, and important standard library traits. -* Generics: generic data types, generic methods, monomorphization, and trait +- Generics: generic data types, generic methods, monomorphization, and trait objects. -* Error handling: panics, `Result`, and the try operator `?`. +- Error handling: panics, `Result`, and the try operator `?`. -* Testing: unit tests, documentation tests, and integration tests. +- Testing: unit tests, documentation tests, and integration tests. -* Unsafe Rust: raw pointers, static variables, unsafe functions, and extern +- Unsafe Rust: raw pointers, static variables, unsafe functions, and extern functions. diff --git a/src/why-rust.md b/src/why-rust.md index 3a16eafc46c5..ea78672dab96 100644 --- a/src/why-rust.md +++ b/src/why-rust.md @@ -2,23 +2,23 @@ Some unique selling points of Rust: -* Compile time memory safety. -* Lack of undefined runtime behavior. -* Modern language features. +- Compile time memory safety. +- Lack of undefined runtime behavior. +- Modern language features.
Make sure to ask the class which languages they have experience with. Depending on the answer you can highlight different features of Rust: -* Experience with C or C++: Rust eliminates a whole class of _runtime errors_ +- Experience with C or C++: Rust eliminates a whole class of _runtime errors_ via the borrow checker. You get performance like in C and C++, but you don't have the memory unsafety issues. In addition, you get a modern language with constructs like pattern matching and built-in dependency management. -* Experience with Java, Go, Python, JavaScript...: You get the same memory safety - as in those languages, plus a similar high-level language feeling. In addition - you get fast and predictable performance like C and C++ (no garbage collector) - as well as access to low-level hardware (should you need it) +- Experience with Java, Go, Python, JavaScript...: You get the same memory + safety as in those languages, plus a similar high-level language feeling. In + addition you get fast and predictable performance like C and C++ (no garbage + collector) as well as access to low-level hardware (should you need it)
diff --git a/src/why-rust/compile-time.md b/src/why-rust/compile-time.md index a34187215ee4..e653a71dd441 100644 --- a/src/why-rust/compile-time.md +++ b/src/why-rust/compile-time.md @@ -2,31 +2,29 @@ Static memory management at compile time: -* No uninitialized variables. -* No memory leaks (_mostly_, see notes). -* No double-frees. -* No use-after-free. -* No `NULL` pointers. -* No forgotten locked mutexes. -* No data races between threads. -* No iterator invalidation. +- No uninitialized variables. +- No memory leaks (_mostly_, see notes). +- No double-frees. +- No use-after-free. +- No `NULL` pointers. +- No forgotten locked mutexes. +- No data races between threads. +- No iterator invalidation.
-It is possible to produce memory leaks in (safe) Rust. Some examples -are: +It is possible to produce memory leaks in (safe) Rust. Some examples are: -* You can use [`Box::leak`] to leak a pointer. A use of this could - be to get runtime-initialized and runtime-sized static variables -* You can use [`std::mem::forget`] to make the compiler "forget" about - a value (meaning the destructor is never run). -* You can also accidentally create a [reference cycle] with `Rc` or - `Arc`. -* In fact, some will consider infinitely populating a collection a memory - leak and Rust does not protect from those. +- You can use [`Box::leak`] to leak a pointer. A use of this could be to get + runtime-initialized and runtime-sized static variables +- You can use [`std::mem::forget`] to make the compiler "forget" about a value + (meaning the destructor is never run). +- You can also accidentally create a [reference cycle] with `Rc` or `Arc`. +- In fact, some will consider infinitely populating a collection a memory leak + and Rust does not protect from those. -For the purpose of this course, "No memory leaks" should be understood -as "Pretty much no *accidental* memory leaks". +For the purpose of this course, "No memory leaks" should be understood as +"Pretty much no _accidental_ memory leaks". [`Box::leak`]: https://doc.rust-lang.org/std/boxed/struct.Box.html#method.leak [`std::mem::forget`]: https://doc.rust-lang.org/std/mem/fn.forget.html diff --git a/src/why-rust/modern.md b/src/why-rust/modern.md index c87613331d03..55833416c355 100644 --- a/src/why-rust/modern.md +++ b/src/why-rust/modern.md @@ -4,43 +4,43 @@ Rust is built with all the experience gained in the last decades. ## Language Features -* Enums and pattern matching. -* Generics. -* No overhead FFI. -* Zero-cost abstractions. +- Enums and pattern matching. +- Generics. +- No overhead FFI. +- Zero-cost abstractions. ## Tooling -* Great compiler errors. -* Built-in dependency manager. -* Built-in support for testing. -* Excellent Language Server Protocol support. +- Great compiler errors. +- Built-in dependency manager. +- Built-in support for testing. +- Excellent Language Server Protocol support.
Key points: -* Zero-cost abstractions, similar to C++, means that you don't have to 'pay' - for higher-level programming constructs with memory or CPU. For example, - writing a loop using `for` should result in roughly the same low level - instructions as using the `.iter().fold()` construct. +- Zero-cost abstractions, similar to C++, means that you don't have to 'pay' for + higher-level programming constructs with memory or CPU. For example, writing a + loop using `for` should result in roughly the same low level instructions as + using the `.iter().fold()` construct. -* It may be worth mentioning that Rust enums are 'Algebraic Data Types', also +- It may be worth mentioning that Rust enums are 'Algebraic Data Types', also known as 'sum types', which allow the type system to express things like `Option` and `Result`. -* Remind people to read the errors --- many developers have gotten used to +- Remind people to read the errors --- many developers have gotten used to ignore lengthy compiler output. The Rust compiler is significantly more talkative than other compilers. It will often provide you with _actionable_ feedback, ready to copy-paste into your code. -* The Rust standard library is small compared to languages like Java, Python, +- The Rust standard library is small compared to languages like Java, Python, and Go. Rust does not come with several things you might consider standard and essential: - * a random number generator, but see [rand]. - * support for SSL or TLS, but see [rusttls]. - * support for JSON, but see [serde_json]. + - a random number generator, but see [rand]. + - support for SSL or TLS, but see [rusttls]. + - support for JSON, but see [serde_json]. The reasoning behind this is that functionality in the standard library cannot go away, so it has to be very stable. For the examples above, the Rust @@ -54,9 +54,9 @@ Key points: Discovering good third-party crates can be a problem. Sites like help with this by letting you compare health metrics for crates to find a good and trusted one. - -* [rust-analyzer] is a well supported LSP implementation used in major - IDEs and text editors. + +- [rust-analyzer] is a well supported LSP implementation used in major IDEs and + text editors. [rand]: https://docs.rs/rand/ [rusttls]: https://docs.rs/rustls/ diff --git a/src/why-rust/runtime.md b/src/why-rust/runtime.md index efabc3d24839..e00c4dfa2d9a 100644 --- a/src/why-rust/runtime.md +++ b/src/why-rust/runtime.md @@ -2,22 +2,23 @@ No undefined behavior at runtime: -* Array access is bounds checked. -* Integer overflow is defined (panic or wrap-around). +- Array access is bounds checked. +- Integer overflow is defined (panic or wrap-around).
Key points: -* Integer overflow is defined via the [`overflow-checks`](https://doc.rust-lang.org/rustc/codegen-options/index.html#overflow-checks) - compile-time flag. If enabled, the program will panic (a controlled - crash of the program), otherwise you get wrap-around - semantics. By default, you get panics in debug mode (`cargo build`) - and wrap-around in release mode (`cargo build --release`). +- Integer overflow is defined via the + [`overflow-checks`](https://doc.rust-lang.org/rustc/codegen-options/index.html#overflow-checks) + compile-time flag. If enabled, the program will panic (a controlled crash of + the program), otherwise you get wrap-around semantics. By default, you get + panics in debug mode (`cargo build`) and wrap-around in release mode + (`cargo build --release`). -* Bounds checking cannot be disabled with a compiler flag. It can also - not be disabled directly with the `unsafe` keyword. However, - `unsafe` allows you to call functions such as `slice::get_unchecked` - which does not do bounds checking. +- Bounds checking cannot be disabled with a compiler flag. It can also not be + disabled directly with the `unsafe` keyword. However, `unsafe` allows you to + call functions such as `slice::get_unchecked` which does not do bounds + checking.
- + `core`
-* Slices, `&str`, `CStr` -* `NonZeroU8`... -* `Option`, `Result` -* `Display`, `Debug`, `write!`... -* `Iterator` -* `panic!`, `assert_eq!`... -* `NonNull` and all the usual pointer-related functions -* `Future` and `async`/`await` -* `fence`, `AtomicBool`, `AtomicPtr`, `AtomicU32`... -* `Duration` +- Slices, `&str`, `CStr` +- `NonZeroU8`... +- `Option`, `Result` +- `Display`, `Debug`, `write!`... +- `Iterator` +- `panic!`, `assert_eq!`... +- `NonNull` and all the usual pointer-related functions +- `Future` and `async`/`await` +- `fence`, `AtomicBool`, `AtomicPtr`, `AtomicU32`... +- `Duration` -* `Box`, `Cow`, `Arc`, `Rc` -* `Vec`, `BinaryHeap`, `BtreeMap`, `LinkedList`, `VecDeque` -* `String`, `CString`, `format!` +- `Box`, `Cow`, `Arc`, `Rc` +- `Vec`, `BinaryHeap`, `BtreeMap`, `LinkedList`, `VecDeque` +- `String`, `CString`, `format!` -* `Error` -* `HashMap` -* `Mutex`, `Condvar`, `Barrier`, `Once`, `RwLock`, `mpsc` -* `File` and the rest of `fs` -* `println!`, `Read`, `Write`, `Stdin`, `Stdout` and the rest of `io` -* `Path`, `OsString` -* `net` -* `Command`, `Child`, `ExitCode` -* `spawn`, `sleep` and the rest of `thread` -* `SystemTime`, `Instant` +- `Error` +- `HashMap` +- `Mutex`, `Condvar`, `Barrier`, `Once`, `RwLock`, `mpsc` +- `File` and the rest of `fs` +- `println!`, `Read`, `Write`, `Stdin`, `Stdout` and the rest of `io` +- `Path`, `OsString` +- `net` +- `Command`, `Child`, `ExitCode` +- `spawn`, `sleep` and the rest of `thread` +- `SystemTime`, `Instant`