Thanks to visit codestin.com
Credit goes to lib.rs

#business-logic #pattern #command

interactors

Command pattern implementation for Rust

3 releases

Uses new Rust 2024

0.0.3 Nov 2, 2025
0.0.2 Apr 15, 2025
0.0.1 Apr 15, 2025

#483 in Math

MIT/Apache

6KB
68 lines

Interactors

A Rust implementation of the Command Pattern for encapsulating business logic and operations.

Project Goal

This project provides a clean, type-safe implementation of the Command Pattern in Rust. The Command Pattern encapsulates requests as objects, allowing you to:

  • Parameterize clients with different requests
  • Queue or log requests
  • Support undoable operations
  • Separate the object that invokes the operation from the one that knows how to perform it

Features

  • Type-Safe Commands: Each command can define its own output and error types
  • Simple Interface: All commands implement a common Command trait with an execute method
  • Flexible Design: Easy to extend with new commands
  • Command Invoker: Centralized command execution through the CommandInvoker

Usage

Basic Example

use interactors::{Command, AddCommand, MultiplyCommand, CommandInvoker};

// Create and execute a command directly
let add_cmd = AddCommand::new(2, 3);
let result = add_cmd.execute().unwrap();
assert_eq!(result, 5);

// Use the command invoker
let multiply_cmd = MultiplyCommand::new(4, 5);
let result = CommandInvoker::invoke(multiply_cmd).unwrap();
assert_eq!(result, 20);

Creating Custom Commands

use interactors::Command;

struct GreetCommand {
    name: String,
}

impl Command for GreetCommand {
    type Output = String;
    type Error = std::convert::Infallible;

    fn execute(&self) -> Result<Self::Output, Self::Error> {
        Ok(format!("Hello, {}!", self.name))
    }
}

Installation

Add this to your Cargo.toml:

[dependencies]
interactors = "0.0.3"

License

Licensed under either of:

at your option.

Keywords

  • Command Pattern
  • Business Logic
  • Design Patterns
  • Rust

No runtime deps