Skip to content

Commit ece2c26

Browse files
committed
Merge pull request #19932 from elszben/master
Added example to TempDir Reviewed-by: alexcrichton
2 parents 685a1ac + c910252 commit ece2c26

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

src/libstd/io/tempfile.rs

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,56 @@ use sync::atomic;
2323

2424
/// A wrapper for a path to temporary directory implementing automatic
2525
/// scope-based deletion.
26+
///
27+
/// # Examples
28+
///
29+
/// ```no_run
30+
/// use std::io::TempDir;
31+
///
32+
/// {
33+
/// // create a temporary directory
34+
/// let tmpdir = match TempDir::new("mysuffix") {
35+
/// Ok(dir) => dir,
36+
/// Err(e) => panic!("couldn't create temporary directory: {}", e)
37+
/// };
38+
///
39+
/// // get the path of the temporary directory without affecting the wrapper
40+
/// let tmppath = tmpdir.path();
41+
///
42+
/// println!("The path of temporary directory is {}", tmppath.display());
43+
///
44+
/// // the temporary directory is automatically removed when tmpdir goes
45+
/// // out of scope at the end of the block
46+
/// }
47+
/// {
48+
/// // create a temporary directory, this time using a custom path
49+
/// let tmpdir = match TempDir::new_in(&Path::new("/tmp/best/custom/path"), "mysuffix") {
50+
/// Ok(dir) => dir,
51+
/// Err(e) => panic!("couldn't create temporary directory: {}", e)
52+
/// };
53+
///
54+
/// // get the path of the temporary directory and disable automatic deletion in the wrapper
55+
/// let tmppath = tmpdir.into_inner();
56+
///
57+
/// println!("The path of the not-so-temporary directory is {}", tmppath.display());
58+
///
59+
/// // the temporary directory is not removed here
60+
/// // because the directory is detached from the wrapper
61+
/// }
62+
/// {
63+
/// // create a temporary directory
64+
/// let tmpdir = match TempDir::new("mysuffix") {
65+
/// Ok(dir) => dir,
66+
/// Err(e) => panic!("couldn't create temporary directory: {}", e)
67+
/// };
68+
///
69+
/// // close the temporary directory manually and check the result
70+
/// match tmpdir.close() {
71+
/// Ok(_) => println!("success!"),
72+
/// Err(e) => panic!("couldn't remove temporary directory: {}", e)
73+
/// };
74+
/// }
75+
/// ```
2676
pub struct TempDir {
2777
path: Option<Path>,
2878
disarmed: bool

0 commit comments

Comments
 (0)