Skip to content

Commit 4fd24c6

Browse files
author
Brian Obot
committed
Add Notes on the Default traint
1 parent 712e4ba commit 4fd24c6

1 file changed

Lines changed: 65 additions & 0 deletions

File tree

src/bin/41_utility_traits.rs

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
// - Marker traits: traits used to expression contraits on generic types that can be caputured in any other trivial way, Size and Copy
99
// - 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
1010

11+
use std::fmt::Debug;
12+
1113
fn main() {
1214
// Traits, Description
1315
// Drop: Clean up code rust runs automatically when a value is dropped
@@ -129,4 +131,67 @@ fn main() {
129131

130132
let my_box = MyBox(10);
131133
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+
//
132197
}

0 commit comments

Comments
 (0)