How to Store Closures in Structs in Rust

Store closures in Rust structs by boxing them as trait objects (e.g., `Box<dyn Fn()>`) because their size is unknown at compile time.

You cannot store closures directly in structs because their size is unknown at compile time; instead, store a Box<dyn Fn(...)> or a Box<dyn FnOnce(...)> to heap-allocate the closure.

use std::thread;

pub struct ThreadPool {
    threads: Vec<thread::JoinHandle<()>>,
    // Store the closure on the heap using a trait object
    executor: Box<dyn FnOnce() + Send + 'static>,
}

impl ThreadPool {
    pub fn new(size: usize, executor: Box<dyn FnOnce() + Send + 'static>) -> ThreadPool {
        assert!(size > 0);
        let mut threads = Vec::with_capacity(size);
        for _ in 0..size {
            // create threads
        }
        ThreadPool { threads, executor }
    }

    pub fn execute<F>(&self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
        // Use the stored executor or pass f directly
    }
}

Note: If you need to store multiple different closures, use Vec<Box<dyn FnOnce() + Send + 'static>> or a similar collection of trait objects.