如何在 Rust 中的嵌套集合上编写泛型函数?

问题描述 投票:0回答:1

我希望在 Rust 中编写一个通用函数,它可以重复迭代元素集合,而元素集合又包含一个重复迭代的集合。这些元素是

(Label, Collection<Elem>)
对,其中
Label
是某种任意类型,而
Collection
是可以多次迭代且具有
Elem
类型元素的元素。我特别希望执行重复迭代,而不会意外或以其他方式克隆任何集合。

此类集合的示例:

let collection1 = vec![(1u8,vec![0u8,1u8]), (2u8,vec![2u8,3u8,4u8])];
let collection2 = LinkedList::from([("a",[1,2,3]),("b",[4,5,6])]);

无需克隆即可迭代

collection1
的非泛型函数示例:

fn nesting(collection : &Vec<(u8,Vec<u8>)>) -> () {
    for (l,c) in collection {
        print!("{}: ",l);
        for e in c.iter() {
            print!("{}, ",e);
        }
        for e in c.iter() {
            print!("{}, ",e);
        }
        println!();
    }
    for (l,_) in collection {
        println!("{:?}",l);
    }
}

我考虑过的一种方法是这样的:

fn nesting<'a, L:'a,N:'a,I:Clone+IntoIterator<Item=&'a (L,N)>>(collection: I) -> ()
{ 
  for i in collection.clone() { /* ... */ };
  for i in collection.clone() { /* ... */ };
}

虽然可以在集合的共享引用上调用它,但也可以在包含引用的集合上调用它,在这种情况下,将克隆整个集合。

N
应该具有什么类型的约束?

generics rust collections
1个回答
0
投票
struct Elem;
fn take_elem(_: &Elem) {}

fn nesting<'a, Label, Outer, Inner>(collection: &'a Outer)
where
    Inner: 'a,
    Label: 'a,
    &'a Outer: IntoIterator<Item = &'a (Label, Inner)>,
    &'a Inner: IntoIterator<Item = &'a Elem>,
{
    for (_label, inner) in collection {
        for elem in inner {
            take_elem(elem);
        }
    }
    
    for (_label, inner) in collection {
        for elem in inner {
            take_elem(elem);
        }
    }
}

这不是最全面的通用性(例如,它不允许收集产生带有引用的拥有的项目),但我相信它应该足以满足您的需要。

© www.soinside.com 2019 - 2024. All rights reserved.