From 26997957c68408a7330608cd2a81d5a6c6d8549f Mon Sep 17 00:00:00 2001 From: Orestis <orestis.malaspinas@pm.me> Date: Mon, 3 Jul 2023 09:27:39 +0200 Subject: [PATCH] adapted to traits from part03 --- codes/rust_lang/part04/src/main.rs | 37 ++++++++++++++++++++++++++---- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/codes/rust_lang/part04/src/main.rs b/codes/rust_lang/part04/src/main.rs index a8625d6..92ab3d9 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) } -- GitLab