Shorter syntax for taking either trait A or B

⚓ Rust    📅 2026-03-19    👤 surdeus    👁️ 6      

surdeus

Consider the following fragment with couple of traits with an single method similar in spirit but that cannot be unified behind a single trait for measured performance reasons.

pub trait TA {
    fn get_slice(&self) -> &str;    
}

pub trait TB {
    fn copy_slice(&self, destination: &mut String);    
}

pub enum A_Or_B<A: TA, B: TB> {
    A(A),
    B(B),
}

pub fn get_slice<'a, A: TA, B: TB>(a_or_b: &'a A_Or_B<A, B>, buffer: &'a mut String) -> &'a str {
    match a_or_b {
        A_Or_B::A(a) => a.get_slice(),
        A_Or_B::B(b) => {
            buffer.clear();
            b.copy_slice(buffer);
            buffer.as_str()
        }
    }   
}

As the test function demonstrates, taking either A or B requires rather verbose type declaration:

get_slice<'a, A: TA, B: TB>(a_or_b: &'a A_Or_B<A, B>, buffer: &'a mut String)

With more descriptive names and quite a few methods needed to take either A or B this becomes rather distracting when reading the code. So I wonder is it possible to have a shortcut or some kind of super trait that would allow to reduce that to something like:

get_slice(a_or_b: impl Something, buffer: &'a mut String)

2 posts - 2 participants

Read full topic

🏷️ Rust_feed