收集到 rust 中拥有的字符串的拥有 vec [英] Collect into owned vec of owned strings in rust

查看:107
本文介绍了收集到 rust 中拥有的字符串的拥有 vec的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下方法将 rust 中的字符串收集到一个 vec 中:

I am trying to collect into an vec of strings in rust using the following:

let fields : ~[~str] = row.split_str(",").collect();

我收到以下错误:预期的 std::iter::FromIterator<&str>,但发现 std::iter::FromIterator<~str>(str 存储不同:预期的 & 但发现 ~)

I get the following error: expected std::iter::FromIterator<&str>, but found std::iter::FromIterator<~str> (str storage differs: expected & but found ~)

我尝试使用类型提示但没有成功

I have tried to use type hints but with no success

推荐答案

.split_str 返回一个 &str slices 上的迭代器,即返回row 数据的子视图.借用的 &str 不是拥有的 ~str:要使其工作,要么收集到 ~[&str],要么,在收集之前将每个&str复制到一个~str中:

.split_str returns an iterator over &str slices, that is, it is returning subviews of the row data. The borrowed &str is not an owned ~str: to make this work, either collect to a ~[&str], or, copy each &str into a ~str before collecting:

let first: ~[&str] = row.split_str(",").collect();
let second: ~[~str] = row.split_str(",").map(|s| s.to_owned()).collect();

<小时>

FWIW,如果您在单字符谓词上进行拆分,则 split 会更有效,(例如 row.split(',') 在这种情况下).

另外,我建议您升级到更新的 Rust 版本,0.11最近发布,但 nightlies 是推荐的安装目标(在相应文档的上述文档链接中将 0.10 更改为 0.11master).

Also, I recommend you upgrade to a more recent version of Rust, 0.11 was recently released, but the nightlies are the recommended install targets (change the 0.10 to 0.11 or master in the above documentation links for the corresponding docs).

对于 nightly,上面的两个片段将被写成:

With the nightly, the two snippets above would be written as:

let first: Vec<&str> = row.split(',').collect();
let second: Vec<String> = row.split(',').map(|s| s.to_string()).collect();

(最后,如果您正在努力区分 &str~str aka String我前段时间写了一些细节.)

(Lastly, if you're struggling with the distinction of &str vs. ~str aka String, I wrote up some details a while ago.)

这篇关于收集到 rust 中拥有的字符串的拥有 vec的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆