Skip to content
Snippets Groups Projects
Verified Commit 26997957 authored by orestis.malaspin's avatar orestis.malaspin
Browse files

adapted to traits from part03

parent be5b1aa8
No related branches found
No related tags found
12 merge requests!34Switches part05 and part06,!31Adds part05summary,!26Adds part04 in summaries,!24Part03summary,!22Summary of part 2 is now done,!19Adds summary for part01 and array is copy,!14Adds summary text for part00,!13Adds part08 illustrates Vec and iterators,!12Adds part07 on the use of Vec and Error Handling,!11Adds part06 featuring modules and doc tests,!10Adds part05 borrowing and ownership,!8Adds part04 comments and tests
Pipeline #25262 passed
......@@ -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)
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment