📕 subnode [[@ryan/20210314131132 using_box_to_represent_closures_in_rust]]
in 📚 node [[20210314131132-using_box_to_represent_closures_in_rust]]
Due to Rust's static typing, sometimes it can be difficult to represent things that come easier in other languages. While trying to implement Dial this issue came up again and again.
I want to be able to use closures on the fly to reduce the burden of evaluation. One possible way that this could be done is the following:
use std::collections::HashMap; enum MyType { Fn(Box<dyn Fn(i64) -> i64>), } struct Env { map: HashMap<&'static str, MyType>, } fn main() { let mut my_map = Env { map: HashMap::new(), }; my_map.map.insert("add10", MyType::Fn(Box::new(|x| x + 10))); my_map.map.insert("sub10", MyType::Fn(Box::new(|x| x - 10))); match my_map.map.get("add10") { Some(MyType::Fn(f)) => println!("{}", f(20)), _ => unreachable!(), }; match my_map.map.get("sub10") { Some(MyType::Fn(f)) => println!("{}", f(20)), _ => unreachable!(), }; }
: 30 : 10
📖 stoas
- public document at doc.anagora.org/20210314131132-using_box_to_represent_closures_in_rust
- video call at meet.jit.si/20210314131132-using_box_to_represent_closures_in_rust
⥱ context
To see links, go up to full node [[20210314131132-using_box_to_represent_closures_in_rust]].