Hello Rust Community,
I would like to know if I can achieve the below
trait Something<T> { }
impl Something<String> for SomeStruct {}
impl Something<All rust types other than String> for SomeStruct{}
I would like to include all rust variable types: i32, u32, Option, ... etc
I tried wrapping in Any but my trait is "async" so its panicking.
jofas
2
Unfortunately this is not possible right now (nor anytime soon I think). If you were to do something like:
trait Something<T> { }
struct SomeStruct;
impl Something<String> for SomeStruct {}
impl<T> Something<T> for SomeStruct{}
you'll get an error because there are conflicting implementations for Something<String>
. The solution for this is called trait specialization. You can find the RFC is here: 1210-impl-specialization - The Rust RFC Book and the tracking issue here: Tracking issue for specialization (RFC 1210) · Issue #31844 · rust-lang/rust · GitHub. Note that specialization right now is unsound, so it is discouraged to be used. But there is the #![feature(min_specialization)]
on nightly you could try:
#![feature(min_specialization)]
trait Something<T> {
fn ty() -> String;
}
struct SomeStruct;
impl Something<String> for SomeStruct {
fn ty() -> String {
"String".to_owned()
}
}
impl<T> Something<T> for SomeStruct {
default fn ty() -> String {
"T".to_owned()
}
}
fn main() {
assert_eq!(<SomeStruct as Something<String>>::ty(), "String".to_owned());
assert_eq!(<SomeStruct as Something<bool>>::ty(), "T".to_owned());
}
Playground.
1 Like
system
Closed
3
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.