From f359056cac6487f735a4b698ad7889b68a318733 Mon Sep 17 00:00:00 2001 From: sunface Date: Fri, 4 Mar 2022 10:54:59 +0800 Subject: [PATCH] add generics.md --- solutions/generics-traits/generics.md | 48 ++++++++++++++++++++++++- src/generics-traits/generics.md | 50 ++++++++++++++++++++++++++- 2 files changed, 96 insertions(+), 2 deletions(-) diff --git a/solutions/generics-traits/generics.md b/solutions/generics-traits/generics.md index 7516660..cf9a5d5 100644 --- a/solutions/generics-traits/generics.md +++ b/solutions/generics-traits/generics.md @@ -85,4 +85,50 @@ fn main() { let y = Val{ val: "hello".to_string()}; println!("{}, {}", x.value(), y.value()); } -``` \ No newline at end of file +``` + +6. +```rust +struct Point { + x: T, + y: U, +} + +impl Point { + fn mixup(self, other: Point) -> Point { + Point { + x: self.x, + y: other.y, + } + } +} + +fn main() { + let p1 = Point { x: 5, y: 10 }; + let p2 = Point { x: "Hello", y: '中'}; + + let p3 = p1.mixup(p2); + + assert_eq!(p3.x, 5); + assert_eq!(p3.y, '中'); +} +``` + +7. +```rust +struct Point { + x: T, + y: T, +} + +impl Point { + fn distance_from_origin(&self) -> f32 { + (self.x.powi(2) + self.y.powi(2)).sqrt() + } +} + +fn main() { + let p = Point{x: 5.0_f32, y: 10.0_f32}; + println!("{}",p.distance_from_origin()) +} +``` diff --git a/src/generics-traits/generics.md b/src/generics-traits/generics.md index 2e8f2b0..2e9604b 100644 --- a/src/generics-traits/generics.md +++ b/src/generics-traits/generics.md @@ -95,4 +95,52 @@ fn main() { println!("{}, {}", x.value(), y.value()); } ``` -> You can find the solutions [here](https://github.com/sunface/rust-by-practice)(under the solutions path), but only use it when you need it \ No newline at end of file + +### Method +6. 🌟🌟🌟 + +```rust,editable +struct Point { + x: T, + y: U, +} + +impl Point { + // implement mixup to make it work, DON'T modify other code + fn mixup +} + +fn main() { + let p1 = Point { x: 5, y: 10 }; + let p2 = Point { x: "Hello", y: '中'}; + + let p3 = p1.mixup(p2); + + assert_eq!(p3.x, 5); + assert_eq!(p3.y, '中'); +} +``` + +7. 🌟🌟 +```rust,editable + +// make the code work +struct Point { + x: T, + y: T, +} + +impl Point { + fn distance_from_origin(&self) -> f32 { + (self.x.powi(2) + self.y.powi(2)).sqrt() + } +} + +fn main() { + let p = Point{x: 5, y: 10}; + println!("{}",p.distance_from_origin()) +} +``` + +> You can find the solutions [here](https://github.com/sunface/rust-by-practice)(under the solutions path), but only use it when you need it +