Convert Vec into a slice of &str in Rust?

前端 未结 2 711
深忆病人
深忆病人 2020-11-30 07:21

Per Steve Klabnik\'s writeup in the pre-Rust 1.0 documentation on the difference between String and &str, in Rust you should use &str unless you really

2条回答
  •  醉梦人生
    2020-11-30 07:50

    You can create a function that accepts both &[String] and &[&str] using the AsRef trait:

    fn test>(inp: &[T]) {
        for x in inp { print!("{} ", x.as_ref()) }
        println!("");
    }
    
    fn main() {
        let vref = vec!["Hello", "world!"];
        let vown = vec!["May the Force".to_owned(), "be with you.".to_owned()];
        test(&vref);
        test(&vown);
    }
    

提交回复
热议问题