From 9c871de2eb40b549d5cc2aad94f2847e0b623b3b Mon Sep 17 00:00:00 2001 From: Matthias Endler Date: Fri, 13 Nov 2026 23:27:20 +0100 Subject: [PATCH] Clarify early function calls, setup, and float formatting --- examples/00_numbers_in_rust/1_intro.md | 38 +++++++++++++++++++ .../00_numbers_in_rust/6_what_we_learned.md | 30 +++++++++++---- examples/01_strings_str_and_chars/1_intro.md | 17 +++++++++ .../6_what_we_learned.md | 10 +++-- 4 files changed, 84 insertions(+), 11 deletions(-) diff --git a/examples/00_numbers_in_rust/1_intro.md b/examples/00_numbers_in_rust/1_intro.md index 77df165..4c58a04 100644 --- a/examples/00_numbers_in_rust/1_intro.md +++ b/examples/00_numbers_in_rust/1_intro.md @@ -3,6 +3,14 @@ *The integer told the float, “You’re being irrational.” The float replied, “At least I have a point.”* +> [!TIP] +> +> Prefer your own editor? Clone [the course repo](https://github.com/corrode/course) +> and follow the [local setup instructions](https://github.com/corrode/course#how-it-works). +> You'll need Rust and Cargo installed to run the exercises locally. +> Staying in the browser? Vim users can turn on **Vim Keybindings** in Settings +> in the top bar. Your choice is saved in this browser. + In Rust, numbers don't always get along. Numeric types are kept distinct, and Rust won't let you mix them without an explicit conversion. @@ -20,6 +28,36 @@ let price: f64 = 19.99; // floating point (f32 is the smaller one) These are the numeric types you'll encounter most often. What makes Rust different is how strictly it treats them. +## Calling Functions and Methods + +To call a function, put its arguments in parentheses after its name: + +```rust +fn half(number: u32) -> u32 { + number / 2 +} + +let number = half(84); +assert_eq!(number, 42); + +let text = number.to_string(); +assert_eq!(text, "42"); +``` + +`fn` defines the function, `number: u32` is its parameter, and `-> u32` is its +return type. The final expression, without a semicolon, is the returned value. +`half(84)` calls the function with `84` as its argument. + +A *method* is called on a value with a dot: `number.to_string()` turns the number +into a `String`. The value before the dot is the *receiver*. This method needs +no extra arguments, but others do: `number.saturating_add(10)` adds `10` without +overflowing, as we'll see next. + +The docs may list the conversion method as `u32::to_string`. +`number.to_string()` calls it on your value. You can also write +`u32::to_string(&number)`, but you need the `&`: this method borrows its receiver. +Dot syntax takes care of that borrow for you. We'll cover borrowing later. + ## Integer Overflow Languages handle integer overflow differently: Java wraps, Python's integers diff --git a/examples/00_numbers_in_rust/6_what_we_learned.md b/examples/00_numbers_in_rust/6_what_we_learned.md index 1216cfb..51df6d1 100644 --- a/examples/00_numbers_in_rust/6_what_we_learned.md +++ b/examples/00_numbers_in_rust/6_what_we_learned.md @@ -5,15 +5,29 @@ fallback when parsing failed. ## What We Learned +- Call a function with `function(arguments)` and a method with + `value.method(arguments)`. For example, + [`number.to_string()`](https://doc.rust-lang.org/std/string/trait.ToString.html#tymethod.to_string) + turns a number into a `String`. - If you add two numbers and the result doesn't fit the type, Rust panics in debug builds and wraps in release builds. When overflow is possible, pick the - behavior you want: `saturating_add` (clamp), `checked_add` (return an - `Option`), or `wrapping_add` (wrap around). + behavior you want: + [`saturating_add`](https://doc.rust-lang.org/std/primitive.u8.html#method.saturating_add) + (clamp), + [`checked_add`](https://doc.rust-lang.org/std/primitive.u8.html#method.checked_add) + (return an `Option`), or + [`wrapping_add`](https://doc.rust-lang.org/std/primitive.u8.html#method.wrapping_add) + (wrap around). - Rust never mixes numeric types for you. If the types don't match, you must - convert them explicitly. `as` casts may lose information; `.into()` handles - infallible conversions, while `.try_into()` returns a `Result` when a - conversion can fail. -- `as u32` on a float truncates toward zero (`1.7 as u32` is `1`); `f64::round` + convert them explicitly. `as` casts may lose information; + [`.into()`](https://doc.rust-lang.org/std/convert/trait.Into.html#tymethod.into) + handles infallible conversions, while + [`.try_into()`](https://doc.rust-lang.org/std/convert/trait.TryInto.html#tymethod.try_into) + returns a `Result` when a conversion can fail. +- `as u32` on a float truncates toward zero (`1.7 as u32` is `1`); + [`f64::round`](https://doc.rust-lang.org/std/primitive.f64.html#method.round) rounds to the nearest integer. We used truncation for the damage example. -- `str::parse()` turns text into a value of the type you ask for. It returns a - `Result`, and `.unwrap_or(...)` supplies a fallback when parsing fails. +- [`str::parse`](https://doc.rust-lang.org/std/primitive.str.html#method.parse) + turns text into a value of the type you ask for. It returns a `Result`, and + [`.unwrap_or(...)`](https://doc.rust-lang.org/std/result/enum.Result.html#method.unwrap_or) + supplies a fallback when parsing fails. diff --git a/examples/01_strings_str_and_chars/1_intro.md b/examples/01_strings_str_and_chars/1_intro.md index a9b9770..dc8c199 100644 --- a/examples/01_strings_str_and_chars/1_intro.md +++ b/examples/01_strings_str_and_chars/1_intro.md @@ -81,6 +81,23 @@ pulls the variables from the surrounding scope. You can also pass arguments explicitly: `format!("{}: {} in stock", item, quantity)`. The exclamation mark (`!`) means `format!` is a macro rather than a regular function call. +For a float, add `:.2` to display exactly two digits after the decimal point: + +```rust +let temperature: f64 = 21.375; +let label = format!("{temperature:.2} °C"); +assert_eq!(label, "21.38 °C"); +assert_eq!(temperature, 21.375); +``` + +This rounds the *displayed text*, not the stored number. You can also write +`format!("{:.2} °C", temperature)`. Use the same precision with `println!` if +you want to print rather than build a `String`. Trailing zeros are included: +`format!("{:.2}", 21.0)` produces `"21.00"`. + +If you need a rounded number for a calculation instead, `.round()` returns a +float rounded to the nearest integer. It doesn't set a display precision. + ## Consuming an Iterator The simplest way to consume an iterator is a `for` loop: diff --git a/examples/01_strings_str_and_chars/6_what_we_learned.md b/examples/01_strings_str_and_chars/6_what_we_learned.md index 1994802..3af8bea 100644 --- a/examples/01_strings_str_and_chars/6_what_we_learned.md +++ b/examples/01_strings_str_and_chars/6_what_we_learned.md @@ -8,9 +8,13 @@ walked a string character by character. - `&str` is a borrowed view into UTF-8 text; `String` is an owned, growable buffer; `char` is one Unicode scalar value. Functions that read text can take a `&str`, while functions that produce new text return a `String`. -- `str::len` returns the byte length. Use `s.chars().count()` when you want the - number of `char` values. -- `str::chars()` returns an iterator. You can use it in a loop or with iterator +- `format!("{value:.2}")` formats a float with two decimal places, rounding the + displayed text without changing the stored value. +- [`str::len`](https://doc.rust-lang.org/std/primitive.str.html#method.len) + returns the byte length. Use `s.chars().count()` when you want the number of + `char` values. +- [`str::chars`](https://doc.rust-lang.org/std/primitive.str.html#method.chars) + returns an iterator. You can use it in a loop or with iterator methods: `for c in s.chars()`, `s.chars().any(...)`, `s.chars().count()`, and so on. - Case conversion (`to_uppercase`, `to_lowercase`) returns a new `String`. It