簡體   English   中英

Rust:發生移動是因為類型為 `ReadDir`,它沒有實現 `Copy` 特征

[英]Rust: move occurs because has type `ReadDir`, which does not implement the `Copy` trait

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.

function fn calculate_length(s: &String) -> usize接受 String 的引用並返回一個usize ,在這種情況下,您擁有返回的值。 當你做println.("The length of '{}' is {},", s1; len); ,您的 println 宏嘗試使用s1len 這沒有問題。

在您的 function 中, fn get_files() -> std::fs::ReadDir返回一個ReadDir結構,您擁有該結構的所有權,這沒關系。

在以下行中,您正在創建一個不可變的引用let paths_ref = &paths; ,這沒關系。

在那之后的行中,您嘗試調用paths_ref.count() ,這是不行的。 為什么? count是一個屬於 trait Iterator的方法,如果你看 Iterator 中count方法的定義,即pub fn count(self) -> usize ,它獲取了self的所有權,然后返回一個usize 這意味着只要您調用count ,迭代器就會被消耗並且不再存在。

因為path_refself的引用,並且它不擁有ReadDir數據,所以您不能對它調用 count 。 您可以使用paths.count() ,它將使用paths變量並返回一個 usize。 但是請注意,在您調用count之后,您的paths變量將不再存在,並且您不能在以下上下文中使用它。

在您的示例中,您基本上需要迭代ReadDir兩次,一次是獲取總計數,另一次是迭代每個元素。 您可以通過使用 1 次迭代並手動計算總元素來實現相同的目的(例如在每次迭代中使用計數器i += 1 ),或者您可以調用get_files兩次。

如果你真的想迭代一次,你可以收集它(到一個 vec 中),然后你可以用它來獲取長度並獲取迭代。

我發現了一個非常相似的 stackoverflow 問題,您可能想檢查一下如何使用相同的迭代器兩次,一次用於計數,一次用於迭代?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM