diff options
author | Jordan Gong <jordan.gong@protonmail.com> | 2020-09-02 19:37:03 +0800 |
---|---|---|
committer | Jordan Gong <jordan.gong@protonmail.com> | 2020-09-02 19:37:03 +0800 |
commit | a8a40420b4106d66bdf1c447388404896dccd494 (patch) | |
tree | e63be572e0db936a2ed1e59d577c5e5e130068df /generics/src/main.rs | |
parent | eeb7ceeff94b9bac0fb629ad393e7113a04f31c1 (diff) |
Generalize redundant code
Diffstat (limited to 'generics/src/main.rs')
-rw-r--r-- | generics/src/main.rs | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/generics/src/main.rs b/generics/src/main.rs new file mode 100644 index 0000000..776f563 --- /dev/null +++ b/generics/src/main.rs @@ -0,0 +1,52 @@ +fn main() { + { + struct Point<T> { + x: T, + y: T, + } + + impl<T> Point<T> { + fn x(&self) -> &T { + &self.x + } + } + + // implement a particular concrete type + impl Point<f32> { + fn distance_from_origin(&self) -> f32 { + (self.x.powi(2) + self.y.powi(2)).sqrt() + } + } + + let p = Point { x: 5, y: 10 }; + println!("p.x = {}", p.x()); + + let p2 = Point { x: 1.0, y: 4.0 }; + println!( + "distance between p2 and origin: {}", + p2.distance_from_origin() + ); + } + { + struct Point<T, U> { + x: T, + y: U, + } + + impl<T, U> Point<T, U> { + fn mixup<V, W>(self, other: Point<V, W>) -> Point<T, W> { + Point { + x: self.x, + y: other.y, + } + } + } + + let p1 = Point { x: 5, y: 10.4 }; + let p2 = Point { x: "Hello", y: 'c' }; + + let p3 = p1.mixup(p2); + + println!("p3.x = {}, p3.y = {}", p3.x, p3.y); + } +} |