2016-08-23 9 views
3

TempDir structを使用して、ディスク上にフォルダを作成して削除しています。 TempDir自体は、その構成とは別にコード内で参照されていません。名前のないオブジェクトの破壊を遅らせる方法は?

コンパイラは未使用のオブジェクトについて警告するので、TempDir-structの名前を_に変更しようとしましたが、この結果、すぐに構造体が破棄されます。

これにはいい解決策がありますか?

twooneを比較し、example codeを参照してください。

pub struct Res; 
impl Drop for Res { 
    fn drop(&mut self) { 
     println!("Dropping self!"); 
    } 
} 

fn one() { 
    println!("one"); 
    let r = Res; // <--- Dropping at end of function 
       //  but compiler warns about unused object 
    println!("Before exit"); 
} 

fn two() { 
    println!("two"); 
    let _ = Res; // <--- Dropping immediately 
    println!("Before exit"); 
} 

fn main() { 
    one(); 
    two(); 
} 
+2

使用 '_unused_but_compiler_does_not_complain_because_of_leading_underscore'、まだ動作するはずです –

答えて

4

変数に名前を与えることなく、スコープの終わりまで、アンダースコアの遅れ破壊に名を前に置くが、未使用変数の警告をトリガしません。

struct Noisy; 

impl Drop for Noisy { 
    fn drop(&mut self) { 
     println!("Dropping"); 
    } 
} 

fn main() { 
    { 
     let _ = Noisy; 
     println!("Before end of first scope"); 
    } 

    { 
     let _noisy = Noisy; 
     println!("Before end of second scope"); 
    } 
} 
Dropping 
Before end of first scope 
Before end of second scope 
Dropping 
関連する問題