I would like to create a Command DP with a command which cannot be known at compile time, but i don't know how to make it well.
The minimal code reproduction
use std::path::{Path, PathBuf};
use std::process::exit;
trait Command {
fn execute<P: AsRef<Path>>(&self, path: P) -> bool
where
Self: Sized,
{
false
}
}
struct RenameCommand;
impl RenameCommand {
pub fn new() -> Self {
RenameCommand {}
}
}
impl Command for RenameCommand {
fn execute<P: AsRef<Path>>(&self, path: P) -> bool {
false
}
}
struct CopyCommand;
impl CopyCommand {
pub fn new() -> Self {
CopyCommand {}
}
}
impl Command for CopyCommand {
fn execute<P: AsRef<Path>>(&self, path: P) -> bool {
false
}
}
fn execute_commmand<P: AsRef<Path>>(command: &Box<dyn Command>, path: P) -> bool {
command.execute(path)
}
fn main() {
let origin_file_path = PathBuf::from("/bin");
let command: Box<dyn Command> = match "rename" {
"rename" => Box::new(RenameCommand),
"copy" => Box::new(CopyCommand),
_ => {
eprintln!("Error");
exit(1);
}
};
for _ in 0..10{
// Some code
// I would like to do something like
// error: the `execute` method cannot be invoked on a trait object
command.execute(origin_file_path);
// Or if needed
execute_commmand(&command, origin_file_path);
}
}
I used Box to create the struct at runtime but I don't know how to run a method on this boxed struct.
command.execute(data); /// doesn't work
so i tried to create a function like
execute_command<P: AsRef<Path>>(command: &Box(dyn Command), path: P) -> bool{
command.execute(path)
}
But i got this error: the execute
method cannot be invoked on a trait object.