Can I create a match against a generic type that i

2020-05-05 18:12发布

问题:

I think this might work if I can work out the lifetime notation, am I wrong?

pub fn from<T:Pattern>(from: T) -> Result<Tag, &'static str> {
    match from {
        'A'|"A" => Ok(Tag::ChA),
        'B'|"B" => Ok(Tag::ChB),
        'C'|"C" => Ok(Tag::ChC),
        'D'|"D" => Ok(Tag::ChD),
        'T'|"Tmpr" => Ok(Tag::Tmpr),
        'Y'|"Batt" => Ok(Tag::Batt),
        'L'|"Acc" => Ok(Tag::Acc),
        _ => Err("Error: unknown channel"),
    }
}

回答1:

Matching only works with concrete types, so the answer is no. Nothing is known about the type T here except that we can call the methods defined in Pattern on it (which are for searching in a string).