diff --git a/codes/rust_lang/part04/src/main.rs b/codes/rust_lang/part04/src/main.rs index a8625d6763f2120e2da107d022e01c6c572f8fc0..92ab3d9a80efe713a1489c34f26bd3dbadcd4fac 100644 --- a/codes/rust_lang/part04/src/main.rs +++ b/codes/rust_lang/part04/src/main.rs @@ -76,12 +76,44 @@ impl<T: PartialEq> PartialEq for SomethingOrNothing<T> { } } +impl<T: Clone> Clone for SomethingOrNothing<T> { + fn clone(&self) -> Self { + match self { + SomethingOrNothing::Nothing => SomethingOrNothing::Nothing, + SomethingOrNothing::Something(val) => SomethingOrNothing::Something(val.clone()), + } + } +} + +impl<T: Copy> Copy for SomethingOrNothing<T> {} + // If we remove Copy, we have a problem with the t in tab // in the computation of the minimum. trait Minimum: Copy { fn min(self, rhs: Self) -> Self; } +impl<T: Minimum> Minimum for SomethingOrNothing<T> { + fn min(self, rhs: Self) -> Self { + match (self, rhs) { + (SomethingOrNothing::Nothing, SomethingOrNothing::Nothing) => { + SomethingOrNothing::Nothing + } + (SomethingOrNothing::Something(lhs), SomethingOrNothing::Something(rhs)) => { + SomethingOrNothing::Something(lhs.min(rhs)) + } + (SomethingOrNothing::Nothing, SomethingOrNothing::Something(rhs)) => { + SomethingOrNothing::Something(rhs) + } + (SomethingOrNothing::Something(lhs), SomethingOrNothing::Nothing) => { + SomethingOrNothing::Something(lhs) + } + } + } +} + +// i32 is Copyable as a very basic type as f32, f64, etc. +// Arrays for example are not copyable. impl Minimum for i32 { fn min(self, rhs: Self) -> Self { if self < rhs { @@ -123,10 +155,7 @@ fn find_min<T: Minimum>(tab: [T; SIZE]) -> ([T; SIZE], SomethingOrNothing<T>) { let mut min = SomethingOrNothing::Nothing; // Here is T is not Copyable tab is consumed and cannot be returned for t in tab { - match min { - SomethingOrNothing::Nothing => min = SomethingOrNothing::Something(t), - SomethingOrNothing::Something(val) => min = SomethingOrNothing::Something(val.min(t)), - } + min = min.min(SomethingOrNothing::Something(t)); } (tab, min) }