【发布时间】:2021-05-03 22:33:39
【问题描述】:
在https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html 中,我找到了使用String 类型引用的非常相似的示例,但在我的代码中,我得到了move occurs because `*paths_ref` has type `ReadDir`, which does not implement the `Copy` trait。与String 有什么区别?我如何在没有 memcopy 的情况下使用ReadDir?
use std::fs;
const CACHE_ADDR: &str = ".";
fn get_files() -> std::fs::ReadDir {
fs::read_dir(CACHE_ADDR).unwrap()
}
fn main() {
let paths: std::fs::ReadDir = get_files();
let paths_ref = &paths;
println!("Count: {}", paths_ref.count());
for path in paths_ref.into_iter() {
println!("{:?}", path.unwrap().path());
break;
}
}
cargo build 错误:
error[E0507]: cannot move out of `*paths_ref` which is behind a shared reference
--> src/main.rs:8:27
|
8 | println!("Count: {}", paths_ref.count());
| ^^^^^^^^^ move occurs because `*paths_ref` has type `ReadDir`, which does not implement the `Copy` trait
error[E0507]: cannot move out of `*paths_ref` which is behind a shared reference
--> src/main.rs:9:17
|
9 | for path in paths_ref.into_iter() {
| ^^^^^^^^^ move occurs because `*paths_ref` has type `ReadDir`, which does not implement the `Copy` trait
error: aborting due to 2 previous errors
For more information about this error, try `rustc --explain E0507`.
error: could not compile `osm-nca-proc`
To learn more, run the command again with --verbose.
【问题讨论】:
-
问题是
count和into_iter使用迭代器,而String::len使用引用。
标签: rust