Collect into owned vec of owned strings in rust

泄露秘密 提交于 2019-12-25 00:52:23

问题


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

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

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


回答1:


.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, if you're splitting on a single-character predicate, then split will be more efficient, (e.g. row.split(',') in this case).

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

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();

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



来源:https://stackoverflow.com/questions/24689463/collect-into-owned-vec-of-owned-strings-in-rust

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!