tag, the compiler can enforce different rules—e.g. you can't add a string to a number, but you can add two numbers
together.
If leveraged correctly, types can prevent whole classes of runtime bugs.
-
Nailing the basics with a few exercises will get the language flowing under your fingers.
When we move on to more complex topics, such as traits and ownership, you'll be able to focus on the new concepts
without getting bogged down by the syntax or other trivial details.
-
In the example above, each branch of the `if` evaluates to a string literal,
which is then assigned to the `message` variable.\
The only requirement is that both `if` branches return the same type.
-
- How to execute conditional logic via comparisons and `if`/`else` expressions
It looks like you're ready to tackle factorials!
-
- Memory management: stack, heap, pointers, data layout, destructors
- Modules and visibility
- Strings
-
The function call syntax makes it quite clear that `ticket` is being used as `self`, the first parameter of the method,
but it's definitely more verbose. Prefer the method call syntax when possible.
-
Nonetheless, it can be useful in some cases, like when writing unit tests. You might have noticed
that most of our test modules start with a `use super::*;` statement to bring all the items from the parent module
(the one being tested) into scope.
-
`Configuration` is public, but you can only access the `version` field from within the same crate.
The `active` field, instead, is private and can only be accessed from within the same module or one of its submodules.
-
ticket.set_description("New description".into());
ticket.set_status("In Progress".into());
```
-
We've covered a lot of foundational Rust concepts in this chapter.\
Before moving on, let's go through one last exercise to consolidate what we've learned.
You'll have minimal guidance this time—just the exercise description and the tests to guide you.
-
Since we'll be talking about conversions, we'll seize the opportunity to plug some of the "knowledge gaps"
from the previous chapter—e.g. what is `"A title"`, exactly? Time to learn more about slices too!
-
each function signature is a contract between the caller and the callee, and the terms must be explicitly stated.
This allows for better error messages, better documentation, less unintentional breakages across versions,
and faster compilation times.
-
**matches exactly** the one you're returning a reference to.\
If a method returns a `&str`, instead, you have a lot more freedom: you're just saying that _somewhere_ there's a
bunch of text data and that a subset of it matches what you need, therefore you're returning a reference to it.
-
is defined on both `T` and `U`, which one will be called?
We'll examine later in the course the "safest" use cases for deref coercion: smart pointers.
-
`str`, as we just saw, is not `Sized`.\
`&str` is `Sized` though! We know its size at compile time: two `usize`s, one for the pointer
and one for the length.
-
- Specified in the variable declaration with a type annotation (e.g. `let title: String = "A title".into();`)
`.into()` will work out of the box as long as the compiler can infer the target type from the context without ambiguity.
-
The compiler implements `Clone` for `MyType` as you would expect: it clones each field of `MyType` individually and
then constructs a new `MyType` instance using the cloned fields.\
Remember that you can use `cargo expand` (or your IDE) to explore the code generated by `derive` macros.
-
2 | #[derive(Clone, Copy)]
| ^^^^ `Copy` not allowed on types with destructors
```
-
Before moving on, let's go through one last exercise to consolidate what we've learned.
You'll have minimal guidance this time—just the exercise description and the tests to guide you.
-
- The `Error` trait, to mark error types
- The `TryFrom` and `TryInto` traits, for fallible conversions
- Rust's package system, explaining what's a library, what's a binary, how to use third-party crates
-
```
`enum`, just like `struct`, defines **a new Rust type**.
-
```
The `_` pattern matches anything that wasn't matched by the previous patterns.
-
Both `if let` and `let/else` are idiomatic Rust constructs.\
Use them as you see fit to improve the readability of your code,
but don't overdo it: `match` is always there when you need it.
-
```
Tuples are a convenient way of grouping values together when you can't be bothered to define a dedicated struct type.
-
Keep in mind, though, that panics exist. They aren't tracked by the type system, just like exceptions in other languages.
But they're meant for **unrecoverable errors** and should be used sparingly.
-
Err(err) => eprintln!("Error: {}", err),
}
```
-
while `Debug` provides a low-level representation that's more suitable to developers and service operators.\
That's why `Debug` can be automatically implemented using the `#[derive(Debug)]` attribute, while `Display`
**requires** a manual implementation.
-
```bash
cargo new my-library --lib
```
-
```
We've been using a few of these throughout the book to shorten our tests.
-
- `#[derive(thiserror::Error)]`: this is the syntax to derive the `Error` trait for a custom error type, helped by `thiserror`.
- `#[error("{0}")]`: this is the syntax to define a `Display` implementation for each variant of the custom error type.
`{0}` is replaced by the zero-th field of the variant (`String`, in this case) when the error is displayed.
-
Just like `From` and `Into`, `TryFrom` and `TryInto` are dual traits.\
If you implement `TryFrom` for a type, you get `TryInto` for free.
-
You can use the `?` operator to shorten your error handling code significantly.\
In particular, the `?` operator will automatically convert the error type of the fallible operation into the error type
of the function, if a conversion is possible (i.e. if there is a suitable `From` implementation)
-