Last active
June 27, 2023 21:43
-
-
Save fvilante/283ebce6e88b2268c27217536b302853 to your computer and use it in GitHub Desktop.
Closure Under de Hood in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn call_once<F: FnOnce(i32) -> i32>(f: F, x: i32) -> i32 { | |
f(x) | |
} | |
fn main() { | |
let outer = 10; | |
let add_outer = |x| x + outer; | |
let result = call_once(&add_outer, 66); | |
println!("Result: {}", result); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Playground: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=73e10710b0a077811e08a38ddab3f515 | |
#![feature(unboxed_closures)] | |
#![feature(fn_traits)] | |
#![feature(unboxed_closures)] | |
#![feature(fn_traits)] | |
fn main() { | |
let outer = 10; | |
// Desugared version of closure `add_one` | |
struct AddOuterEnv<'a> { | |
outer: &'a i32, | |
} | |
impl<'a> FnOnce<(i32,)> for AddOuterEnv<'a> { | |
type Output = i32; | |
extern "rust-call" fn call_once(self, args: (i32,)) -> i32 { | |
self.outer + args.0 | |
} | |
} | |
let result = AddOuterEnv { outer: &outer }.call_once((66,)); | |
println!("Result: {}", result); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment