Created
May 5, 2022 14:47
-
-
Save soyart/f4881107d111f6bd000b3632ea8326ee to your computer and use it in GitHub Desktop.
My practice code for https://doc.rust-lang.org/book/ch10-00-generics.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| fn get_largest<T: PartialOrd + Copy>(v: Vec<T>) -> T { | |
| let mut largest = v[0]; | |
| for item in v { | |
| if largest > item { | |
| largest = item | |
| }; | |
| }; | |
| largest | |
| } | |
| fn get_largest_move<T:PartialOrd + Clone>(v: Vec<T>) -> T { | |
| let mut largest = &v[0]; | |
| for item in &v { | |
| if largest > item { | |
| largest = item; | |
| } | |
| }; | |
| largest.clone() | |
| } | |
| #[derive(Debug)] | |
| struct UniformPoint<T> { | |
| x: T, | |
| y: T, | |
| } | |
| // If T implements Copy, Copy when returning. | |
| impl<T: Copy> UniformPoint<T> { | |
| fn get_x(&self) -> T { | |
| self.x | |
| } | |
| fn get_y(&self) -> T { | |
| self.y | |
| } | |
| } | |
| #[derive(Debug)] | |
| struct MessedPoint<T, U> { | |
| x: T, | |
| y: U, | |
| } | |
| // T, U represents the types of the fields | |
| // of the object the method is called on. | |
| impl<T: Copy, U: Copy> MessedPoint<T, U> { | |
| fn clone(&self) -> MessedPoint<T,U> { | |
| MessedPoint{ | |
| x: self.x, | |
| y: self.y, | |
| } | |
| } | |
| fn mix<V, W>(self, other: MessedPoint<V, W>) -> MessedPoint<T, W> { | |
| MessedPoint{ | |
| x: self.x, | |
| y: other.y, | |
| } | |
| } | |
| } | |
| fn main() { | |
| println!("{}", get_largest(vec!(2, 3, 4, 69))); | |
| println!("{}", get_largest(vec!('a', 'b', 'A', 'B'))); | |
| println!("{}", get_largest_move( | |
| vec!( | |
| String::from("kuy"), | |
| String::from("hee"), | |
| String::from("nom"), | |
| ), | |
| )); | |
| let p = UniformPoint{x: 1, y:2}; | |
| let _ = p.get_x() + p.get_y(); // Copies x from p and give it to _ | |
| let mp1 = MessedPoint{x:1, y: "kuy"}; | |
| let mp2 = MessedPoint{x:"hee", y:69.}; | |
| // mp3 has String as y, which prevents it from accessing the generic impl block | |
| let mp3 = MessedPoint{x:"hehe", y: String::from("this")}; | |
| println!("mp1 {:?}", mp1); | |
| println!("mp2 {:?}", mp2); | |
| println!("mp1.mix(mp2) = {:?}", mp1.clone().mix(mp2.clone())); | |
| println!("mp2.mix(mp1) = {:?}", mp2.clone().mix(mp1.clone())); | |
| println!("mp3.mix(mp2) = {:?}", mp2.clone().mix(mp3)); // mp1 and mp2 are moved after calling mix | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment