diff --git a/generics/Cargo.toml b/generics/Cargo.toml new file mode 100644 index 0000000..5776289 --- /dev/null +++ b/generics/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "generics" +version = "0.1.0" +authors = ["laurens "] +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..bde79ce --- /dev/null +++ b/generics/src/main.rs @@ -0,0 +1,34 @@ +struct Point { + x: T, + y: U, +} + +impl Point { + // Different types of Point's + fn mixup(self, other: Point) -> Point { + Point { + x: self.x, + y: other.y, + } + } +} + +impl Point { + // Specific types of Point's + fn distance_from_origin(self) -> f32 { + (self.x.powi(2) + self.y.powi(2)).sqrt() + } +} + +fn main() { + 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); + + let p4 = Point { x: 1.0, y: 1.0 }; + + println!("distance: {}", p4.distance_from_origin()); +}