pub trait ExecutionContext: Send + Sync {
// Required methods
fn as_any(&self) -> &dyn Any;
fn as_any_mut(&mut self) -> &mut dyn Any;
}Expand description
Execution context trait
This trait defines the interface for application-specific execution contexts. The context is shared state that persists across command executions in both CLI and REPL modes.
§Thread Safety
Contexts must implement Send + Sync to support:
- Multi-threaded command execution
- Async runtime compatibility
- Future extensibility
§Type Erasure and Downcasting
Since the framework doesn’t know the concrete context type at compile time,
we use the Any trait for type-safe runtime downcasting. The as_any()
and as_any_mut() methods enable converting the trait object back to
the concrete type.
§Implementation Guide
Implementing this trait is straightforward - just return self:
use dynamic_cli::context::ExecutionContext;
use std::any::Any;
struct MyContext {
// Your application state
config: String,
}
impl ExecutionContext for MyContext {
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
}§Usage in Command Handlers
Command handlers receive a &mut dyn ExecutionContext and must
downcast it to their expected type:
use dynamic_cli::context::{ExecutionContext, downcast_mut};
use std::collections::HashMap;///
use rustyline::Context;
struct MyContext { value: i32 }
fn my_handler(
context: &mut dyn ExecutionContext,
args: &HashMap<String, String>,
) -> Result<(), Box<dyn std::error::Error>> {
// Downcast to concrete type
let ctx = downcast_mut::<MyContext>(context)
.ok_or("Invalid context type")?;
// Use the context
ctx.value += 1;
Ok(())
}Required Methods§
Sourcefn as_any(&self) -> &dyn Any
fn as_any(&self) -> &dyn Any
Convert this context to an Any trait object
This method enables type-safe downcasting from the trait object back to the concrete type. The framework uses this internally to support generic command handlers.
§Implementation
Simply return self - the compiler handles the conversion:
impl ExecutionContext for MyContext {
fn as_any(&self) -> &dyn Any {
self // Just return self
}
}§Returns
A reference to this object as an Any trait object
Sourcefn as_any_mut(&mut self) -> &mut dyn Any
fn as_any_mut(&mut self) -> &mut dyn Any
Convert this context to a mutable Any trait object
This is the mutable version of as_any(),
enabling command handlers to modify the context state.
§Implementation
Simply return self:
impl ExecutionContext for MyContext {
fn as_any_mut(&mut self) -> &mut dyn Any {
self // Just return self
}
}§Returns
A mutable reference to this object as an Any trait object