I'm new to Rust, and I'm writing a basic command line input parser as a learning exercise. Commands entered on the command line are evaluated using the Cmd
struct which contains the name of the command and a function to call when invoked. Though the code works, I find the use of the get_invocation
function to be a little weird.
pub struct Cmd<T: FnMut()> {
name: String,
invocation: T,
}
impl<T: FnMut()> Cmd<T> {
pub fn new(name: &str, invocation: T) -> Cmd<T> {
Cmd {
name: String::from(name),
invocation,
}
}
pub fn invoke(self) {
self.get_invocation()();
}
fn get_invocation(self) -> T {
self.invocation
}
}
I am aware that I could use (self.invocation)()
to directly call my struct function in invoke()
, but that would involve setting the invoke self
parameter to mutable, which would require me to make each instance of Cmd
mutable if I wish to use the invoke()
function. This is something I would like to avoid as, conceptually, nothing in the struct is being mutated. Is there a less odd / more idiomatic way to deal with stored function invocation in Rust, while still maintaining immutability? I also would appreciate any other pointers/tips on my code.