shared_mut_state/
shared_mut_state.rs

1use std::{cell::RefCell};
2use easy_repl::{Repl, CommandStatus, command};
3use anyhow::{self, Context};
4
5fn main() -> anyhow::Result<()> {
6    // To use a value in multiple commands we need shared ownership
7    // combined with some kind of references.
8    // This could be Rc<RefCell<_>>, but in this example it's possible
9    // to avoid smart pointers and just use two references &RefCell<_>.
10    let counter = RefCell::new(0);
11    let ref1 = &counter;
12    let ref2 = &counter;
13
14    let mut repl = Repl::builder()
15        .add("inc", command! {
16            "Increment counter",
17            () => || {
18                *ref1.borrow_mut() += 1;
19                println!("counter = {}", ref1.borrow());
20                Ok(CommandStatus::Done)
21            },
22        })
23        .add("dec", command! {
24            "Decrement counter",
25            () => || {
26                *ref2.borrow_mut() -= 1;
27                println!("counter = {}", ref2.borrow());
28                Ok(CommandStatus::Done)
29            },
30        })
31        .build().context("Failed to create repl")?;
32
33    repl.run().context("Critical REPL error")?;
34
35    Ok(())
36}