|
8 | 8 | // - Marker traits: traits used to expression contraits on generic types that can be caputured in any other trivial way, Size and Copy |
9 | 9 | // - Public Vocabulary Trait: they are not magival to the compiler but using them mirrors convetional solutions for common problems, Default, AsRed, AsMut, Borrow and BorrowMut |
10 | 10 |
|
| 11 | +use std::fmt::Debug; |
| 12 | + |
11 | 13 | fn main() { |
12 | 14 | // Traits, Description |
13 | 15 | // Drop: Clean up code rust runs automatically when a value is dropped |
@@ -129,4 +131,67 @@ fn main() { |
129 | 131 |
|
130 | 132 | let my_box = MyBox(10); |
131 | 133 | assert_eq!(10, *my_box); // *(my_box.deref()) |
| 134 | + |
| 135 | + #[derive(Debug)] |
| 136 | + struct Selector<T> { |
| 137 | + elements: Vec<T>, |
| 138 | + current: usize, |
| 139 | + } |
| 140 | + |
| 141 | + impl<T> std::ops::Deref for Selector<T> { |
| 142 | + type Target = T; |
| 143 | + |
| 144 | + fn deref(&self) -> &Self::Target { |
| 145 | + &self.elements[self.current] |
| 146 | + } |
| 147 | + } |
| 148 | + |
| 149 | + impl<T> std::ops::DerefMut for Selector<T> { |
| 150 | + fn deref_mut(&mut self) -> &mut Self::Target { |
| 151 | + &mut self.elements[self.current] |
| 152 | + } |
| 153 | + } |
| 154 | + |
| 155 | + #[allow(unused_mut)] |
| 156 | + let mut s: Selector<i32> = Selector { |
| 157 | + elements: vec![1, 2, 3, 4], |
| 158 | + current: 2, |
| 159 | + }; |
| 160 | + |
| 161 | + assert_eq!(*s, 3); |
| 162 | + // assert!(12i32.is_positive()); |
| 163 | + assert!(s.is_positive()); |
| 164 | + |
| 165 | + // you can spell out coercion using the as keyword in rust |
| 166 | + fn spell(number: &i32) { |
| 167 | + println!("Spelling: {number}"); |
| 168 | + } |
| 169 | + |
| 170 | + // since the spell function takes a reference to i32, we can coerce s to that |
| 171 | + spell(&s as &i32); |
| 172 | + #[allow(clippy::explicit_auto_deref)] |
| 173 | + spell(&*s); //both are valid |
| 174 | + |
| 175 | + // Default: the default trait allows types to specify their default via a default method |
| 176 | + impl<T: Default> Default for Selector<T> { |
| 177 | + fn default() -> Self { |
| 178 | + Self { |
| 179 | + elements: Vec::default(), |
| 180 | + current: usize::default(), |
| 181 | + } |
| 182 | + } |
| 183 | + } |
| 184 | + |
| 185 | + let default_selector = Selector::<i32>::default(); |
| 186 | + println!("Default Selector: {default_selector:?}"); |
| 187 | + |
| 188 | + // all of rust collection types implement default that return empty collections |
| 189 | + let samples = vec![2, 3, 45, 6, 23, 23, 5, 6, 34, 2, 4, 6]; |
| 190 | + let (x_men, impure): (Vec<i32>, Vec<i32>) = samples.iter().partition(|&n| n & 1 == 0); |
| 191 | + |
| 192 | + println!("X-Men: {x_men:?}"); |
| 193 | + println!("Impure: {impure:?}"); |
| 194 | + |
| 195 | + // if a type implements Default, then the standard library implements defaults for Arc<T>, Rc<T>, Box<T> etc |
| 196 | + // |
132 | 197 | } |
0 commit comments