feat: Add Drop-based defer implementation
This commit is contained in:
		
							parent
							
								
									aabac498e7
								
							
						
					
					
						commit
						5eec09334b
					
				
					 1 changed files with 31 additions and 0 deletions
				
			
		
							
								
								
									
										31
									
								
								examples/defer.rs
									
										
									
									
									
										Normal file
									
								
							
							
						
						
									
										31
									
								
								examples/defer.rs
									
										
									
									
									
										Normal file
									
								
							|  | @ -0,0 +1,31 @@ | |||
| // Go's defer in Rust!
 | ||||
| 
 | ||||
| struct Defer<F: Fn()> { | ||||
|     f: F | ||||
| } | ||||
| 
 | ||||
| impl <F: Fn()> Drop for Defer<F> { | ||||
|     fn drop(&mut self) { | ||||
|         (self.f)() | ||||
|     } | ||||
| } | ||||
| 
 | ||||
| // Only added this for Go-syntax familiarity ;-)
 | ||||
| fn  defer<F: Fn()>(f: F) -> Defer<F> { | ||||
|     Defer { f } | ||||
| } | ||||
| 
 | ||||
| fn main() { | ||||
|     let mut i = 1; | ||||
| 
 | ||||
|     // Calling it "token" ... could be something else. The lifetime of this
 | ||||
|     // controls when the action is run.
 | ||||
|     let _token = defer(move || println!("Value is: {}", i)); | ||||
| 
 | ||||
|     i += 1; | ||||
|     println!("Value is: {}", i); | ||||
| } | ||||
| 
 | ||||
| // Prints:
 | ||||
| // Value is: 2
 | ||||
| // Value is: 1
 | ||||
		Loading…
	
	Add table
		Add a link
		
	
		Reference in a new issue