A simple Rust library that provides a clean, object-oriented way to structure thread logic by using structs implementing a Runnable trait.
While std::thread::spawn is powerful, complex thread logic often requires passing multiple variables, channels, or shared state into a closure. This can make code difficult to read and maintain.
struct-threads solves this by encapsulating thread state and logic within a struct. This approach:
- Improves readability by separating state initialization from execution.
- Simplifies testing by allowing you to instantiate thread state without immediately spawning it.
- Provides a clear contract for the thread's return value via associated types.
Install using cargo:
cargo add struct-threads
Define your task state in a struct, implement Runnable, and call .start().
use struct_threads::{Runnable, Thread};
struct MyTask {
data: i32,
}
impl Runnable for MyTask {
type Output = i32;
fn run(self) -> Self::Output {
println!("Running task in a separate thread...");
std::thread::sleep(std::time::Duration::from_millis(100));
self.data * 2
}
}
fn main() {
let task = MyTask { data: 21 };
// The .start() method is provided by the Thread trait
let handle = task.start();
// Wait for the thread to finish and get the result
let result = handle.join().unwrap();
println!("Result: {}", result);
}This pattern truly shines when your thread needs to communicate with the main thread or hold more complex state, like channels.
use std::sync::mpsc;
use struct_threads::{Runnable, Thread};
struct WorkerTask {
id: usize,
sender: mpsc::Sender<String>,
}
impl Runnable for WorkerTask {
type Output = ();
fn run(self) -> Self::Output {
// Perform work...
let msg = format!("Worker {} has successfully finished its job!", self.id);
self.sender.send(msg).unwrap();
}
}
fn main() {
let (tx, rx) = mpsc::channel();
let worker = WorkerTask { id: 1, sender: tx };
worker.start(); // Spawns the thread
// Wait for the message from the worker
let result = rx.recv().unwrap();
println!("Received: {}", result);
}Contributions are welcome! To get started:
- Clone the repository:
git clone https://github.com/AsfhtgkDavid/struct-threads.git - Run tests to ensure everything works locally:
cargo test - Submit a Pull Request.
This project is licensed under the MIT License - see the LICENSE file for details.