英文:
What is the correct way to filter a &[&str]?
问题
I am trying to filter an array of type &[&str]
in the following way, in able to exclude the " " case:
let example_array : &[&str] = &["hello", " ", "world"];
let filtered_array : &[&str] = example_array.iter().copied().filter(|&word| word != " ").collect();
The error I get is:
value of type &[&str]
cannot be built from std::iter::Iterator<Item=&str>
Could someone explain why is not working, and where to look for solution?
英文:
I am trying to filter an array of type &[&str]
in the following way, in able to exclude the " " case:
let example_array : &[&str] = &["hello", " ", "world"];
let filtered_array : &[&str] = example_array.iter().copied().filter(|&word| word != " ").collect();
The error I get is:
value of type &[&str]
cannot be built from std::iter::Iterator<Item=&str>
Could someone explain why is not working, and where to look for solution?
答案1
得分: 4
&[&str]
是对字符串引用的切片(数组)的引用。这适用于静态字符串数组,因为编译器能够将其放入静态数据段并创建对它的引用。collect
函数无法返回 &[&str]
,但它可以返回一个动态分配的 Vec<&str>
let example_array: &[&str] = &["hello", " ", "world"];
let filtered_array: Vec<&str> = example_array.iter().copied().filter(|&word| word != " ").collect();
编辑:
Vec<&str>
实现了 Deref<Target = [&str]>
,这意味着您可以通过对其进行引用来使用 Vec<&str>
作为 &[&str]
。
let filtered_array_ref: &[&str] = &filtered_array;
英文:
&[&str]
is a reference to a slice (array) of string references. This works with your static array of strings because the compiler is able to put it into a static data section and create a reference to it. The collect
function cannot return a &[&str]
, but it can return a dynamically allocated Vec<&str>
let example_array: &[&str] = &["hello", " ", "world"];
let filtered_array: Vec<&str> = example_array.iter().copied().filter(|&word| word != " ").collect();
EDIT:
Vec<&str>
implements Deref<Target = [&str]>
, meaning you can use a Vec<&str>
as a &[&str]
by taking a reference to it.
let filtered_array_ref: &[&str] = &filtered_array;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论