Skip to content

Instantly share code, notes, and snippets.

@RandyMcMillan
Forked from rust-play/playground.rs
Last active August 23, 2025 12:01
Show Gist options
  • Select an option

  • Save RandyMcMillan/b524e8969de049c538276662cc8f562f to your computer and use it in GitHub Desktop.

Select an option

Save RandyMcMillan/b524e8969de049c538276662cc8f562f to your computer and use it in GitHub Desktop.
struct_partition_into_iter.rs
// https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=f6b6cbb5fedbb3a745ee98fde30c8d06
// A basic struct that holds an array of 16-bit unsigned integers.
struct Numbers([u16; 10]);
// Implement the IntoIterator trait for our Numbers struct.
impl<'a> IntoIterator for &'a Numbers {
// We want to iterate over references to u16 values.
type Item = &'a u16;
// The type of the iterator we're returning.
type IntoIter = std::slice::Iter<'a, u16>;
// The method that creates and returns the iterator.
fn into_iter(self) -> Self::IntoIter {
self.0.iter()
}
}
fn main() {
let numbers = Numbers([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
let (evens, odds): (std::vec::Vec<u16>, std::vec::Vec<u16>) =
numbers.into_iter().partition(|&n| n % 2 == 0);
for n in &evens {
println!("even:{}", n);
}
for n in &odds {
println!("odd:{}", n);
}
for n in &numbers {
println!("numbers:{}", n);
}
}
@RandyMcMillan
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment