Sometimes I come across situations where I'd expect a borrow reference to be supported by a function call, but it's not. I'm trying to determine if this is necessary, or if it's just an overlooked design decision.
Case in point: I've been working with the inquire
crate recently. I like this crate, because it provides an easy mechanism to accept user input from terminal applications. Implementing the prompts is incredibly straightforward, and doesn't require any specialized knowledge.
One of the things I noticed about the API design is that I can't pass in a reference to a Vec<String>
as a list of selectable options. See the second argument to new(..., &option_list)
.
let option_list = vec![ "option1", "option2", ];
let prompt_message = "Please select one of the following options";
let result = inquire::Select::new(&prompt_message, &option_list).prompt();
This results in the following error:
mismatched types
expected structVec<_>
found reference&Vec<&str>
To fix this, I have to remove the borrow &
from it.
let result = inquire::Select::new(&prompt_message, option_list).prompt();
Now, you might think that this doesn't matter so much. Who cares? The second example compiles, right?
Well, the reason it concerns me is because I need to reuse these options in a loop. Because I can't reuse the options, I am forced to clone them each time, which seems inefficient to me.
This fails to compile, with the error:
use of moved value:
option_list
value moved here, in previous iteration of loop
let option_list = vec![
"option1",
"option2",
];
let prompt_message = "Please select one of the following options";
loop {
let result = inquire::Select::new(&prompt_message, option_list).prompt();
}
To fix this, I have to clone the Vec<&str>
each time.
let option_list = vec![
"option1",
"option2",
];
let prompt_message = "Please select one of the following options";
loop {
let result = inquire::Select::new(&prompt_message, option_list.clone()).prompt();
}
Is this a result of a less than ideal design decision? Or is there a better way of writing this program than what I'm currently aware of?