How to get a slice from an Iterator?

I started using clippy as a linter. Sometimes it shows this warning:

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

I changed the parameter to slice, but this adds a call-side pattern. For example, the code was:

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

but now this:

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

Otherwise, I get the following error:

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

So, I am wondering if there is a way to convert Iteratorto sliceor not to specify the type collected in this particular case.

+4
source share
1 answer

So, I wonder if there is a way to convert Iteratortoslice

No.

, - . , 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);

, , "" , .

+8

Source: https://habr.com/ru/post/1612066/


All Articles