过滤 &[&str] 的正确方法是什么?

huangapple go评论60阅读模式
英文:

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 &amp;[&amp;str] in the following way, in able to exclude the " " case:

let example_array : &amp;[&amp;str] = &amp;[&quot;hello&quot;, &quot; &quot;, &quot;world&quot;]; 
let filtered_array : &amp;[&amp;str] = example_array.iter().copied().filter(|&amp;word| word != &quot; &quot;).collect();

The error I get is:

value of type &amp;[&amp;str] cannot be built from std::iter::Iterator&lt;Item=&amp;str&gt;

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;
英文:

&amp;[&amp;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 &amp;[&amp;str], but it can return a dynamically allocated Vec&lt;&amp;str&gt;

let example_array: &amp;[&amp;str] = &amp;[&quot;hello&quot;, &quot; &quot;, &quot;world&quot;];
let filtered_array: Vec&lt;&amp;str&gt; = example_array.iter().copied().filter(|&amp;word| word != &quot; &quot;).collect();

EDIT:

Vec&lt;&amp;str&gt; implements Deref&lt;Target = [&amp;str]&gt;, meaning you can use a Vec&lt;&amp;str&gt; as a &amp;[&amp;str] by taking a reference to it.

let filtered_array_ref: &amp;[&amp;str] = &amp;filtered_array;

huangapple
  • 本文由 发表于 2023年5月14日 21:46:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76247804.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定