Skip to content

Commit c0e8dc6

Browse files
author
elszben
committed
Added example to TempDir
1 parent ef0bc46 commit c0e8dc6

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

src/libstd/io/tempfile.rs

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

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

0 commit comments

Comments
 (0)