1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-07-04 05:40:29 +02:00

Various small fixes (#1556)

Plus one more substantial comment on casting.
This commit is contained in:
Marshall Pierce
2023-12-05 16:06:42 -07:00
committed by GitHub
parent 8f9902cc3e
commit 6c5061bb90
16 changed files with 23 additions and 21 deletions

View File

@ -20,6 +20,11 @@ The results of `as` are _always_ defined in Rust and consistent across
platforms. This might not match your intuition for changing sign or casting to
a smaller type -- check the docs, and comment for clarity.
Casting with `as` is a relatively sharp tool that is easy to use incorrectly, and can be a source of subtle bugs as future maintenance work changes the types that are used or the ranges of values in types. Casts are best used only when the intent is to indicate unconditional truncation (e.g. selecting the bottom 32 bits of a `u64` with `as u32`, regardless of what was in the high bits).
For infallible casts (e.g. `u32` to `u64`), prefer using `From` or `Into` over `as`
to confirm that the cast is in fact infallible. For fallible casts, `TryFrom` and `TryInto` are available when you want to handle casts that fit differently from those that don't.
<details>
Consider taking a break after this slide.

View File

@ -45,9 +45,9 @@ fn main() {
* 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]
* The partial struct initialization works nicely with default.
* The 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].
</details>

View File

@ -11,7 +11,7 @@ fn main() {
let s = String::from("hello");
let addr = std::net::Ipv4Addr::from([127, 0, 0, 1]);
let one = i16::from(true);
let bigger = i32::from(123i16);
let bigger = i32::from(123_i16);
println!("{s}, {addr}, {one}, {bigger}");
}
```
@ -23,7 +23,7 @@ fn main() {
let s: String = "hello".into();
let addr: std::net::Ipv4Addr = [127, 0, 0, 1].into();
let one: i16 = true.into();
let bigger: i32 = 123i16.into();
let bigger: i32 = 123_i16.into();
println!("{s}, {addr}, {one}, {bigger}");
}
```