Rust 程式語言中的 Path 結構


Rust 中的路徑結構用於表示底層檔案系統中的檔案路徑。還應注意,Rust 中的路徑不表示為 UTF-8 字串;相反,它儲存為位元組向量(Vec<u8>)

示例

考慮下面顯示的示例 -

 即時演示

use std::path::Path;

fn main() {
   // Create a `Path` from an `&'static str`
   let path = Path::new(".");
   // The `display` method returns a `Show`able structure
   let display = path.display();
   // Check if the path exists
   if path.exists() {
      println!("{} exists", display);
   }
   // Check if the path is a file
   if path.is_file() {
      println!("{} is a file", display);
   }
   // Check if the path is a directory
   if path.is_dir() {
      println!("{} is a directory", display);
   }
   // `join` merges a path with a byte container using the OS specific
   // separator, and returns the new path
   let new_path = path.join("a").join("b");
   // Convert the path into a string slice
   match new_path.to_str() {
      None => panic!("new path is not a valid UTF-8 sequence"),
      Some(s) => println!("new path is {}", s),
   }
}

輸出 

如果我們執行上述程式碼,我們將看到以下輸出 -

. exists
. is a directory
new path is ./a/b

更新時間:2021 年 4 月 3 日

368 人檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.