inquire/list_option.rs
1//! Utilities used to wrap user selections in [Select](crate::Select) and
2//! [`MultiSelect`](crate::MultiSelect) prompts.
3
4use std::fmt::{self, Display};
5
6/// Represents a selection made by the user when prompted to select one or several
7/// options among those presented.
8#[derive(Clone, Debug, PartialEq, Eq)]
9pub struct ListOption<T> {
10 /// Index of the selected option relative to the original (full) list passed to the prompt.
11 pub index: usize,
12
13 /// Value of the selected option.
14 pub value: T,
15}
16
17impl<T> ListOption<T> {
18 /// Constructor for `ListOption`.
19 ///
20 /// # Arguments
21 ///
22 /// * `index` - Index of the option.
23 /// * `value` - String value of the option
24 ///
25 /// # Examples
26 ///
27 /// ```
28 /// use inquire::list_option::ListOption;
29 ///
30 /// let answer = ListOption::new(0, "a");
31 /// ```
32 pub fn new(index: usize, value: T) -> Self {
33 Self { index, value }
34 }
35
36 /// Converts from `&ListOption<T>` to `ListOption<&T>`.
37 pub fn as_ref(&self) -> ListOption<&T> {
38 ListOption::new(self.index, &self.value)
39 }
40
41 #[allow(unused)]
42 pub(crate) fn from_list(vals: Vec<T>) -> Vec<ListOption<T>> {
43 vals.into_iter()
44 .enumerate()
45 .map(|(index, value)| Self { index, value })
46 .collect()
47 }
48
49 #[allow(unused)]
50 pub(crate) fn from_enumerated_list(vals: Vec<(usize, T)>) -> Vec<ListOption<T>> {
51 vals.into_iter()
52 .map(|(index, value)| Self { index, value })
53 .collect()
54 }
55}
56
57impl<T> fmt::Display for ListOption<T>
58where
59 T: Display,
60{
61 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
62 self.value.fmt(f)
63 }
64}