Skip to content

Instantly share code, notes, and snippets.

@raphlinus
Created November 25, 2020 01:10
Show Gist options
  • Select an option

  • Save raphlinus/b0132d1c1b849069d9880912af44bf4f to your computer and use it in GitHub Desktop.

Select an option

Save raphlinus/b0132d1c1b849069d9880912af44bf4f to your computer and use it in GitHub Desktop.
A sketch of how to iterate over a list of references
pub trait IntoRefs<'a, T: 'a> {
type Iterator: Iterator<Item = &'a T>;
fn into_refs(self) -> Self::Iterator;
}
impl<'a, T> IntoRefs<'a, T> for &'a [T] {
type Iterator = std::slice::Iter<'a, T>;
fn into_refs(self) -> Self::Iterator {
self.into_iter()
}
}
impl<'a, T> IntoRefs<'a, T> for &'a [&'a T] {
type Iterator = std::iter::Copied<std::slice::Iter<'a, &'a T>>;
fn into_refs(self) -> Self::Iterator {
self.into_iter().copied()
}
}
// TODO: this will benefit from const generics!
impl<'a, T> IntoRefs<'a, T> for &'a [&'a T; 1] {
type Iterator = std::iter::Copied<std::slice::Iter<'a, &'a T>>;
fn into_refs(self) -> Self::Iterator {
self.into_iter().copied()
}
}
impl<'a, T> IntoRefs<'a, T> for Vec<&'a T> {
type Iterator = std::vec::IntoIter<&'a T>;
fn into_refs(self) -> Self::Iterator {
self.into_iter()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment