Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Thunks in Rust
use core::option;
/**
* Implementation of thunks in Rust.
*/
pub struct Lazy<T> {
code : @fn() -> T,
mut value : Option<T>
}
/**
* Unfortunately requires a caller to make a closure.
*/
pure fn Lazy<T>(closure: @fn() -> T) -> Lazy<T> {
let l : Lazy<T> = Lazy {
code : closure,
value : None
};
return l;
}
impl<T> Lazy<T> {
fn force() -> T {
match self.value {
Some(value) => { return value; }
None => {
let result = self.code();
self.value = Some(result);
return result;
}
};
}
}
#[test]
fn test_create_thunk() {
let mut a : int = 10;
// thunk is a Lazy<()>.
// trying to call Lazy<int> (|| ...
// results in `error: unresolved name: int`
let thunk = Lazy (|| {
a + 10;
});
let z = thunk.force();
// lazy.rs:50:26: 50:28 error: mismatched types: expected `()` but found `<VI2>` (expected () but found integral variable)
assert(thunk.force() == 20);
a = 100;
assert(thunk.force() == 20);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.