Skip to content

Commit

Permalink
feat: add Associated Type Bounds
Browse files Browse the repository at this point in the history
  • Loading branch information
katopz committed Oct 13, 2023
1 parent 60f3777 commit 1d8b678
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
- [Callback](rust/r3/callback.md)
- [Async](rust/r3/async.md)
- [Iterators](rust/r3/iterators.md)
- [Associated Type Bounds](rust/r3/associated-type-bounds.md)
- [R2 - Expert](rust/r2/mod.md)
- [Hello Github Action](rust/r2/hello-github-action.md)
- [Hello Actix CloudRun](rust/r2/hello-actix-cloudrun.md)
Expand Down
67 changes: 67 additions & 0 deletions src/rust/r3/associated-type-bounds.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Associated Type Bounds

```rust,editable
// Define a trait `AnimalTrait` with an associated type `A`.
trait AnimalTrait {
// Associated type for the animal's type (e.g., Cat).
type A;
// A method to create an instance of the animal.
fn create() -> Self;
// A method to get the name of the animal.
fn name(&self) -> &str;
}
// Define a struct `Cat` that implements the `AnimalTrait` trait.
struct Cat;
impl AnimalTrait for Cat {
type A = Cat;
fn create() -> Self {
Cat
}
fn name(&self) -> &str {
"Cat"
}
}
// Define a struct `Dog` that implements the `AnimalTrait` trait.
struct Dog;
impl AnimalTrait for Dog {
type A = Dog;
fn create() -> Self {
Dog
}
fn name(&self) -> &str {
"Dog"
}
}
// This will look fancy a bit.
fn adopt_cat<T>(cat: T)
where
// Here it is an 👇 Associated Type Bounds.
T: AnimalTrait<A = Cat>,
{
let cat_instance = T::create();
let cat_name = cat_instance.name();
println!("Adopted a {} named {}", cat.name(), cat_name);
}
fn main() {
// Call the `adopt_cat` function, passing a `Cat` instance.
adopt_cat(Cat);
// 😱 Attempt to call the `adopt_cat` function with a `Dog` instance.
// 👇 This will result in a compilation error.
// adopt_cat(Dog);
// --------- ^^^ type mismatch resolving `<Dog as AnimalTrait>::A == Cat`
}
```

0 comments on commit 1d8b678

Please sign in to comment.