Generic type capturing multiple (non-auto) traits?

Let's say I have a function

fn display_vs_debug<T>(t: &T) where T: std::fmt::Display + std::fmt::Debug {
    println!("{} vs {:?}", t, t);
}

How can I describe, say, Box<???> that can hold any valid argument for this function?

Straightforward Box<dyn std::fmt::Display + std::fmt::Debug> doesn't work because only auto traits can be used as additional traits in a trait object

Playground: Rust Playground

What's wrong with obvious solution?

1 Like

I was hoping to avoid boilerplate, but nice to see it can be solved at all.

I don't understand why you want dyn Trait for this, it's not needed. If you want a Box<T> where the T implements some traits, then just declare that.

You can not do traits upcasting in today's Rust (without special dance and few more traits) thus “trying to avoid boilerplate” would backfire badly.

Maybe when trait upcasting would be stable removing boilerplate would become feasible, but today it's just too much of landmine to allow.

1 Like