How do I write a function that takes both owned and non-owned string collections?

后端 未结 2 784
死守一世寂寞
死守一世寂寞 2020-12-10 14:33

I\'m having trouble writing a function that takes a collection of strings as parameter. My function looks like this:

type StrList<\'a> = Vec<&\'         


        
2条回答
  •  青春惊慌失措
    2020-12-10 15:16

    To build on delnan's great answer, I want to point out one more level of generics that you can add here. You said:

    a collection of strings

    But there are more types of collections than slices and vectors! In your example, you care about forward-only, one-at-a-time access to the items. This is a perfect example of an Iterator. Below, I've changed your function to accept any type that can be transformed into an iterator. You can then pass many more types of things. I've used a HashSet as an example, but note that you can also pass in v1 and v2 instead of &v1 or &v2, consuming them.

    use std::collections::HashSet;
    
    fn my_func(list: I)
        where I: IntoIterator,
              I::Item: AsRef,
    {
        for s in list {
            println!("{}", s.as_ref());
        }
    }
    
    fn main() {
        let v1 = vec!["a", "b"];
        let v2 = vec!["a".to_owned(), "b".to_owned()];
        let v3 = {
            let mut set = HashSet::new();
            set.insert("a");
            set.insert("b");
            set.insert("a");
            set
        };
        let v4 = {
            let mut set = HashSet::new();
            set.insert("a".to_owned());
            set.insert("b".to_owned());
            set.insert("a".to_owned());
            set
        };
    
        my_func(&v1);
        my_func(v1);
        my_func(&v2);
        my_func(v2);
        my_func(&v3);
        my_func(v3);
        my_func(&v4);
        my_func(v4);
    }
    

提交回复
热议问题