Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions examples/00_numbers_in_rust/1_intro.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down
30 changes: 22 additions & 8 deletions examples/00_numbers_in_rust/6_what_we_learned.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
17 changes: 17 additions & 0 deletions examples/01_strings_str_and_chars/1_intro.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
10 changes: 7 additions & 3 deletions examples/01_strings_str_and_chars/6_what_we_learned.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading