How to annotate a vector/array of functions?

⚓ rust    📅 2025-06-07    👤 surdeus    👁️ 2      

surdeus

Hi folks,

I'd like to create a const or static with a vector/array (anything iterable) of MyParser

But I don't know how to specify the type. Could you please help?

pub const MyParsers: [MyParser<_>; 3] = [
    MyParser {
        name: String::from("first"),
        function: Parsed::a,
    },
    MyParser {
        name: String::from("second"),
        function: Parsed::b,
    },
    MyParser {
        name: String::from("third"),
        function: Parsed::c,
    },
];
pub struct MyParser<'a, Y> {
    name: String,
    function: fn(Y) -> Option<Container<'a>>,
}
pub struct Container<'a> {
    inner: &'a str,
}
impl<'a> From<&'a str> for Container<'a> {
    fn from(value: &'a str) -> Self {
        Self { inner: value }
    }
}
pub struct Parsed;
impl Parsed {
    pub fn a<'a, T>(inp: T) -> Option<Container<'a>>
    where
        T: Into<Container<'a>>,
    {
        Some(inp.into())
    }
    pub fn b<'a, T>(inp: T) -> Option<Container<'a>>
    where
        T: Into<Container<'a>>,
    {
        None
    }
    pub fn c<'a, T>(inp: T) -> Option<Container<'a>>
    where
        T: Into<Container<'a>>,
    {
        Some(inp.into())
    }
}

4 posts - 2 participants

Read full topic

🏷️ rust_feed