pub fn downcast_ref<T: ExecutionContext + 'static>(
context: &dyn ExecutionContext,
) -> Option<&T>Expand description
Attempt to downcast a context reference to a concrete type
This function safely converts a trait object reference to a
reference of the concrete type T. If the context is not
of type T, it returns None.
§Type Parameters
T- The concrete type to downcast to. Must implementExecutionContextand have a'staticlifetime.
§Arguments
context- Reference to the execution context trait object
§Returns
Some(&T)if the context is of typeTNoneif the context is a different type
§Example
use dynamic_cli::context::{ExecutionContext, downcast_ref};
use std::any::Any;
struct DatabaseContext {
connection_string: String,
}
impl ExecutionContext for DatabaseContext {
fn as_any(&self) -> &dyn Any { self }
fn as_any_mut(&mut self) -> &mut dyn Any { self }
}
fn get_connection(ctx: &dyn ExecutionContext) -> Option<&str> {
downcast_ref::<DatabaseContext>(ctx)
.map(|db| db.connection_string.as_str())
}§Safety
This operation is safe because it uses Rust’s Any::downcast_ref,
which performs runtime type checking.