ファイルパス
構造体Pathは、ファイルシステム中のパスを表します。Pathには2つの変種があります。UNIXライクなファイルシステムのためのposix::Pathと、Windows用のwindows::Pathです。それぞれプラットフォームに対応したPathをエクスポートします。
PathはOsStrから作ることができます。そうすればそのパスが指すファイル・ディレクトリの情報を取得するためのメソッドがいくつか使えるようになります。
A Path is immutable. The owned version of Path is PathBuf. The relation between Path and PathBuf is similar to that of str and String: a PathBuf can be mutated in-place, and can be dereferenced to a Path.
Note that a Path is not internally represented as an UTF-8 string, but instead is stored as an OsString. Therefore, converting a Path to a &str is not free and may fail (an Option is returned). However, a Path can be freely converted to an OsString or &OsStr using into_os_string and as_os_str, respectively.
use std::path::Path; fn main() { // `&'static str`から`Path`を作成。 let path = Path::new("."); // `display`メソッドは`Display`可能な構造体を返します。 let _display = path.display(); // `join`はOS固有のセパレータによってバイトのコンテナ型であるパス // を結合し、`PathBuf`を返します。 let mut new_path = path.join("a").join("b"); // `push`は`PathBuf`を`&Path`で拡張します。 new_path.push("c"); new_path.push("myfile.tar.gz"); // `set_file_name`は`PathBuf`のファイル名を更新します。 new_path.set_file_name("package.tgz"); // `PathBuf`を文字列のスライスに変換します。 match new_path.to_str() { None => panic!("new path is not a valid UTF-8 sequence"), Some(s) => println!("new path is {}", s), } }
他のPathメソッド(posix::Pathとwindows::Path)をチェックするのを忘れずに!それとMetadata構造体も見ておくことをオススメします。