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

revamped traits

parent bd583e6a
No related branches found
No related tags found
13 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,!9Adds part03 traits and genericity,!8Adds part04 comments and tests
Pipeline #25260 passed
/// In part03 we introduce `Enums` (also known as `Algebraic Data Types`), `Pattern Matching`,
/// and `Static Functions`.
/// In part03 we introduce genericity through traits and in particular, [Copy],
/// [Clone], [std::fmt::Display] .
enum SomethingOrNothing<T> {
Nothing,
......@@ -17,12 +17,42 @@ impl<T: std::fmt::Display> 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 {
......@@ -55,10 +85,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 to comment