2015-10-17 36 views
4

我開始使用clippy作爲棉絨。有時,它會顯示此警告:如何從迭代器中獲取切片?

writing `&Vec<_>` instead of `&[_]` involves one more reference and cannot be 
used with non-Vec-based slices. Consider changing the type to `&[...]`, 
#[warn(ptr_arg)] on by default 

我將參數更改爲切片,但是這會在呼叫端添加樣板。例如,代碼爲:

let names = args.arguments.iter().map(|arg| { 
    arg.name.clone() 
}).collect(); 
function(&names); 

,但現在卻是:

let names = args.arguments.iter().map(|arg| { 
    arg.name.clone() 
}).collect::<Vec<_>>(); 
function(&names); 

否則,我得到以下錯誤:

error: the trait `core::marker::Sized` is not implemented for the type 
`[collections::string::String]` [E0277] 

所以我想如果有一種方法來將Iterator轉換爲slice或避免在此特定情況下必須指定collect ed類型。

回答

8

So I wonder if there is a way to convert an Iterator to a slice

沒有。

迭代器一次只提供一個元素,而一個slice則一次提取多個元素。這就是爲什麼您首先需要將Iterator產生的所有元素收集到連續數組(Vec)之後才能使用切片。

第一個明顯的答案是不要擔心少量的開銷,但我個人更喜歡把旁邊的變量類型提示(我覺得它更易讀):

let names: Vec<_> = args.arguments.iter().map(|arg| { 
    arg.name.clone() 
}).collect(); 
function(&names); 

另一種選擇是, function採取的Iterator代替(和引用的迭代器,在那個):

let names = args.arguments.iter().map(|arg| &arg.name); 
function(names); 

畢竟,迭代器都比較一般,如果你需要,你總能「實現」的功能,裏面的切片。