簡體   English   中英

為什么我不能在std :: env :: args迭代器上映射Path :: new?

[英]Why can't I map Path::new over the std::env::args iterator?

這有效:

let paths: Vec<String> = args.collect();
let paths = paths.iter().map(|f| std::path::Path::new(&f));

這不起作用:

let paths = ::std::env::args().map(|f| std::path::Path::new(&f));
error[E0597]: `f` does not live long enough
 --> src/main.rs:2:66
  |
2 |     let paths = ::std::env::args().map(|f| std::path::Path::new(&f));
  |                                                                  ^-- borrowed value needs to live until here
  |                                                                  ||
  |                                                                  |`f` dropped here while still borrowed
  |                                                                  borrowed value does not live long enough

為什么我需要將args迭代器collect到一個向量中以產生另一個迭代器? 為什么我不能直接從另一個迭代器生成一個迭代器?

Args迭代器返回String類型的值。 當您在迭代器上進行map時,將為閉包賦予每個值的所有權。

無效的代碼會嘗試引用String ,但該字符串將在閉包末尾超出范圍。 如將本地字符串作為切片(&str)討論的那樣,不允許這樣做。

起作用的代碼不是遍歷String而是遍歷&String 請參閱iter和into_iter有什么區別? 因此,在閉包中沒有什么超出范圍的,並且從閉包返回引用是可以的。

正確的解決方案是將String數據的所有權轉移到新類型。 PathBuf是適當的選擇。 PathBuf指向&Path ,而String指向&str

let paths = ::std::env::args().map(std::path::PathBuf::from);

PathBuf是可變的。 我不需要這里的可變性。 為什么您認為我需要PathBuf

您對Rust中的可變性如何工作感到困惑。 返回並重新閱讀Rust編程語言 ,尤其是有關變量和可變性的章節。

Rust中的類型本身不是可變的或不可變的。 可變性是變量綁定的屬性:

let buf = std::path::PathBuf::new();
buf.push("home");
error[E0596]: cannot borrow immutable local variable `buf` as mutable
 --> src/main.rs:3:5
  |
2 |     let buf = std::path::PathBuf::new();
  |         --- consider changing this to `mut buf`
3 |     buf.push("home");
  |     ^^^ cannot borrow mutably

暫無
暫無

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

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