rust_struct_iterable
rust_struct_iterable copied to clipboard
Allow custom `dyn` traits with non-static lifetime
Instead of dyn Any I'd like to iterate over dyn MyTrait (dyn Checkable in the example below) with the assumption that all fields in the struct implement that trait (else, there should be a compile error).
Example
pub struct NixHealth {
pub max_jobs: MaxJobs,
pub caches: Caches,
pub flake_enabled: FlakeEnabled,
pub min_nix_version: MinNixVersion,
pub trusted_users: TrustedUsers,
}
Manual implementration
impl<'a> IntoIterator for &'a NixHealth {
type Item = &'a dyn Checkable;
type IntoIter = std::vec::IntoIter<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
let items: Vec<Self::Item> = vec![
&self.min_nix_version,
&self.flake_enabled,
&self.max_jobs,
&self.caches,
&self.trusted_users,
];
items.into_iter()
}
}
Code in context: https://github.com/juspay/nix-browser/blob/913c505d501efd15beff7388404d9a7f4e4e4c58/crates/nix_health/src/lib.rs#L24-L48
I agree. Would love to be able to use ToString for my specific use case.