From 1c9b0af2da377b7a47b1efb2bce53fe1666c7995 Mon Sep 17 00:00:00 2001 From: Hammy Date: Sun, 16 Jan 2022 02:44:53 +0000 Subject: [PATCH] Add generics --- book/generics/Cargo.toml | 8 ++++++ book/generics/src/main.rs | 55 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 book/generics/Cargo.toml create mode 100644 book/generics/src/main.rs diff --git a/book/generics/Cargo.toml b/book/generics/Cargo.toml new file mode 100644 index 0000000..2a85b1d --- /dev/null +++ b/book/generics/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "generics" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/book/generics/src/main.rs b/book/generics/src/main.rs new file mode 100644 index 0000000..109112b --- /dev/null +++ b/book/generics/src/main.rs @@ -0,0 +1,55 @@ +use core::alloc; + +struct List { + list: Vec, +} + +impl List { + fn sum(&self) -> usize { + self.list.iter().sum() + } +} + +impl List { + fn sum(&self) -> String { + let mut merged_string = String::new(); + for element in &self.list { + merged_string.push_str(element.as_str()); + } + merged_string + } +} + +struct Point { + x: T, + y: T, +} + +impl Point { + fn x(&self) -> &T { + &self.x + } +} + +impl Point { + fn distance_from_origin(&self) -> f32 { + (self.x.powi(2) + self.y.powi(2)).sqrt() + } +} + +fn main() { + let list_one = List { list: vec![1, 2, 3, 4, 5] }; + let list_two = List { list: vec![String::from("hello"), String::from(" world")] }; + + let sum = list_one.sum(); + let merged = list_two.sum(); + + println!("Sum -> {}", sum); + println!("Merged -> {}", merged); + + let p_one = Point { x: 5, y: 10 }; + let p_two = Point { x: 5.0, y: 10.0 }; + + println!("p_one.x = {}", p_one.x()); + println!("p_two.distance_from_origin = {}", p_two.distance_from_origin()); +}