From a8a40420b4106d66bdf1c447388404896dccd494 Mon Sep 17 00:00:00 2001 From: Jordan Gong Date: Wed, 2 Sep 2020 19:37:03 +0800 Subject: Generalize redundant code --- generics/.gitignore | 18 ++++++++++++++++++ generics/Cargo.toml | 9 +++++++++ generics/src/main.rs | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 79 insertions(+) create mode 100644 generics/.gitignore create mode 100644 generics/Cargo.toml create mode 100644 generics/src/main.rs diff --git a/generics/.gitignore b/generics/.gitignore new file mode 100644 index 0000000..e629269 --- /dev/null +++ b/generics/.gitignore @@ -0,0 +1,18 @@ + +# Created by https://www.toptal.com/developers/gitignore/api/rust +# Edit at https://www.toptal.com/developers/gitignore?templates=rust + +### Rust ### +# Generated by Cargo +# will have compiled files and executables +/target/ + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk + +# End of https://www.toptal.com/developers/gitignore/api/rust + diff --git a/generics/Cargo.toml b/generics/Cargo.toml new file mode 100644 index 0000000..5d46e6b --- /dev/null +++ b/generics/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "generics" +version = "0.1.0" +authors = ["Jordan Gong "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] 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 { + x: T, + y: T, + } + + impl Point { + fn x(&self) -> &T { + &self.x + } + } + + // implement a particular concrete type + impl Point { + 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 { + x: T, + y: U, + } + + impl Point { + fn mixup(self, other: Point) -> Point { + 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); + } +} -- cgit v1.2.3