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:
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With