Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have a generic function that accepts all types that do not implement a trait?

Tags:

rust

traits

I know that I can have functions accept only types that implement a given trait. For example, I can

fn f<T>()
where
    T: MyTrait,
{
    // Super useful stuff
}

What if I wanted to implement a function that accepts anything that does not implement a given trait? For example, say that I have some computation that either:

  • Requires some known, lengthy preprocessing, or
  • Has a specific way of short-cutting through that preprocessing.

What I would like to do is something like:

fn preprocess<T>(computation: &mut T)
where
    T: !Shortcut,
{
    // Carry out the expensive precomputation.
}

I tried figuring out how to work around this problem, but I don't seem to be able to figure out any solution.

like image 250
Matteo Monti Avatar asked Oct 20 '25 03:10

Matteo Monti


1 Answers

No, you cannot.

Instead, you can use the unstable specialization feature the other way, to opt-in to more efficient processing:

#![feature(specialization)]

trait Process {
    fn process(self);
}

trait Short {}

impl Short for i32 {}

impl<T> Process for T
where
    T: std::fmt::Debug,
{
    default fn process(self) {
        println!("Processing {:?}", self)
    }
}

impl<T> Process for T
where
    T: std::fmt::Debug + Short,
{
    fn process(self) {
        println!("Shortcut {:?}", self)
    }
}

fn main() {
    42i32.process();
    vec![1, 2, 3].process();
}
Shortcut 42
Processing [1, 2, 3]

See also:

  • What are the possible operators for traits in a where clause in Rust?
  • Can I define a trait whose implementations must be `!Send`?
  • What does the exclamation point mean in a trait implementation?
like image 62
Shepmaster Avatar answered Oct 22 '25 03:10

Shepmaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!