Macro block2::global_block [−][src]
macro_rules! global_block {
($(#[$m : meta]) * $vis : vis static $name : ident = || $(-> $r : ty) ? $body
: block) => { ... };
($(#[$m : meta]) * $vis : vis static $name : ident = |
$($a : ident : $t : ty), * $(,) ? | $(-> $r : ty) ? $body : block) => { ... };
}
Expand description
Construct a static GlobalBlock
.
The syntax is similar to a static closure. Note that the block cannot
capture it’s environment, and it’s argument types and return type must be
Encode
.
Examples
use block2::global_block;
global_block! {
static MY_BLOCK = || -> i32 {
42
}
};
assert_eq!(unsafe { MY_BLOCK.call(()) }, 42);
use block2::global_block;
global_block! {
static ADDER_BLOCK = |x: i32, y: i32| -> i32 {
x + y
}
};
assert_eq!(unsafe { ADDER_BLOCK.call((5, 7)) }, 12);
use block2::global_block;
global_block! {
pub static MUTATING_BLOCK = |x: &mut i32| {
*x = *x + 42;
}
};
let mut x = 5;
unsafe { MUTATING_BLOCK.call((&mut x,)) };
assert_eq!(x, 47);
The following does not compile because Box
is not Encode
:
ⓘ
use block2::global_block;
global_block! {
pub static INVALID_BLOCK = |b: Box<i32>| {}
};