1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 The Finally trait provides a method, `finally` on
13 stack closures that emulates Java-style try/finally blocks.
28 #[cfg(test)] use task::{failing, spawn};
30 pub trait Finally<T> {
31 fn finally(&self, dtor: &fn()) -> T;
34 macro_rules! finally_fn {
36 impl<T> Finally<T> for $fnty {
37 fn finally(&self, dtor: &fn()) -> T {
38 let _d = Finallyalizer {
47 impl<'self,T> Finally<T> for &'self fn() -> T {
48 fn finally(&self, dtor: &fn()) -> T {
49 let _d = Finallyalizer {
57 finally_fn!(~fn() -> T)
58 finally_fn!(@fn() -> T)
59 finally_fn!(extern "Rust" fn() -> T)
61 struct Finallyalizer<'self> {
66 impl<'self> Drop for Finallyalizer<'self> {
100 let closure: &fn() -> int = || 10;
101 let i = do closure.finally { };
107 fn do_some_fallible_work() {}
108 fn but_always_run_this_function() { }
109 do_some_fallible_work.finally(
110 but_always_run_this_function);
115 fn spawn_with_finalizer(f: ~fn()) {
116 do spawn { do f.finally { } }
118 let owned: ~fn() = || { };
119 spawn_with_finalizer(owned);
125 let managed: @fn() -> int = || {
130 assert_eq!(do managed.finally {}, 10);