Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
In [ ]:
:timing
:sccache 1
Tips and Traps¶
This is an unsized type, meaning that it must always be used behind a pointer like & or Box. For an owned version of this type, see PathBuf.
Methods of
std::path::Path
return object of the typestd::ffi::OsStr
rather thanstd::String
or&sstr
.The Rust crate normpath provides more reliable path manipulation.
In [3]:
use std::path::Path;
use std::ffi::OsStr;
Create a Path¶
In [4]:
let path = Path::new("./foo/bar.txt");
path
Out[4]:
Path.file_stem¶
In [6]:
path.file_stem()
Out[6]:
In [7]:
path.file_stem() == Some(OsStr::new("bar"))
Out[7]:
In [8]:
path.file_stem() == Some(String::from("bar"))
path.extension(&self) -> Option<&OsStr>¶
Extracts the extension of self.file_name, if possible.
Notice that this method returns Option<&OsStr>
instead of Option<&str>
.
In [15]:
let path = Path::new("./foo/bar.txt");
path.extension()
Out[15]:
In [17]:
let path = Path::new("./foo/bar.txt");
path.extension() == Some(OsStr::new("txt"))
Out[17]:
Path.exists¶
In [13]:
path.exists()
Out[13]:
In [15]:
Path::new("test.txt").exists()
Out[15]:
Path.is_file¶
In [18]:
path.is_file()
Out[18]:
In [16]:
Path::new("test.txt").is_file()
Out[16]:
In [6]:
Path::new(".").canonicalize()
Out[6]:
In [13]:
Path::new(".").canonicalize().unwrap().components()
Out[13]:
In [14]:
Path::new(".").canonicalize().unwrap().iter().for_each(|comp| {
println!("{:?}", comp);
});
Path.parent¶
In [5]:
path.parent()
Out[5]:
Path.read_dir¶
In [18]:
Path::new(".").read_dir().unwrap().for_each(|entry| {
if let Ok(entry) = entry {
println!("{:?}", entry.path());
}
});
References¶
In [ ]: