├── Cargo.toml ├── Cargo.lock └── src └── main.rs /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "sandbox-rust-generics" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "sandbox-rust-generics" 7 | version = "0.1.0" 8 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | 3 | 4 | let msg = add_strs(String::from("Hello, "), String::from("World!")); 5 | dbg!(msg); 6 | 7 | let sum = add_nums(1, 1); 8 | dbg!(sum); 9 | 10 | let another_sum = add_generic(2, 2); 11 | dbg!(another_sum); 12 | 13 | let p1 = Point {x: 10, y: 10}; 14 | let p2 = Point {x: 10, y: 10}; 15 | let p3 = add_generic(p1, p2); 16 | dbg!(p3); 17 | 18 | } 19 | 20 | // a function which adds two strings 21 | fn add_strs(s1: String, s2: String) -> String { 22 | s1 + &s2 23 | } 24 | 25 | // a function which adds two numbers 26 | fn add_nums(x: i32, y: i32) -> i32 { 27 | x + y 28 | } 29 | 30 | // a generic function which can handle both String and i32 (along with other types 31 | fn add_generic>(x: T, y: T) -> T { 32 | x + y 33 | } 34 | 35 | // a custom type we might want to add 36 | #[derive(Debug)] 37 | struct Point { 38 | x: i32, 39 | y: i32, 40 | } 41 | 42 | // implementing add on our custom type 43 | impl std::ops::Add for Point { 44 | type Output = Point; 45 | 46 | fn add(self, other: Point) -> Point { 47 | Point { 48 | x: self.x + other.x, 49 | y: self.y + other.y, 50 | } 51 | } 52 | } 53 | 54 | --------------------------------------------------------------------------------