1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2024-12-04 03:25:08 +02:00

Merge pull request #142 from fbornhofen/speaker-notes-fbornhofen

Add example for underscore syntax with generics (type-inference.md)
This commit is contained in:
Martin Geisler 2023-01-10 17:46:20 +01:00 committed by GitHub
commit c994340a8f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -20,3 +20,25 @@ fn main() {
// takes_u32(y);
}
```
<details>
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:
```rust,editable
fn main() {
let mut v = Vec::new();
v.push((10, false));
v.push((20, true));
println!("v: {v:?}");
let vv = v.iter().collect::<std::collections::HashSet<_>>();
println!("vv: {vv:?}");
}
```
[`collect`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.collect) relies on `FromIterator`, which [`HashSet`](https://doc.rust-lang.org/std/iter/trait.FromIterator.html) implements.
</details>