Last active
October 11, 2024 00:06
-
-
Save BartMassey/e00cd5f5e9eae9cd3c2758b70d18ae69 to your computer and use it in GitHub Desktop.
Demos of various trait impls to make iteration easier.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct V([u64; 3]); | |
impl std::ops::Deref for V { | |
type Target = [u64; 3]; | |
fn deref(&self) -> &Self::Target { | |
&self.0 | |
} | |
} | |
impl<'a> IntoIterator for &'a V { | |
type Item = &'a u64; | |
type IntoIter = std::slice::Iter<'a, u64>; | |
fn into_iter(self) -> Self::IntoIter { | |
self.0.iter() | |
} | |
} | |
impl IntoIterator for V { | |
type Item = u64; | |
type IntoIter = std::array::IntoIter<u64, 3>; | |
fn into_iter(self) -> Self::IntoIter { | |
self.0.into_iter() | |
} | |
} | |
fn main() { | |
let v = V([1, 2, 3]); | |
for x in &*v { | |
println!("{}", x); | |
} | |
for x in &v { | |
println!("{}", x); | |
} | |
for x in v.iter().rev() { | |
println!("{}", x); | |
} | |
for x in v { | |
println!("{}", x); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment