0

例如:

// just an example, can be any Iterator<Item = char>
let iter = "hello".chars();

let mut path = std::path::PathBuf::new();

// works but is inefficient
path.push(iter.collect::<String>());

// does not work:
//   path.push(iter);
// if path were String we could do
//   path.extend(iter)
println!("{:?}", path);
4

2 回答 2

1

从任意字符迭代器到 a 的最佳方法PathBuf是将迭代器收集到String第一个:

let path_buf = PathBuf::from(iter.collect::<String>());

虽然这并不能真正避免首先收集迭代器,但它只会在创建String. 如文档中所述,此内存被重用于 PathBuf :

将 a 转换String为 aPathBuf

此转换不分配或复制内存。

于 2020-05-19T09:58:26.570 回答
0

应该很简单:

fn main() {
   let iter = "hello".chars();

   let path = std::path::PathBuf::from(iter.as_str());
   // Or path.push(iter.as_str());
   println!("{:?}", path);
}
于 2020-05-19T08:45:54.413 回答