Curious type inference error
I have the following "minimal example" to illustrate the issue that I'm getting:
use enum_dispatch::enum_dispatch;
struct HasSome<T>(T);
struct HasNothing;
#[enum_dispatch]
trait OptionMethods<T> {
fn to_std(self) -> Option<T>;
fn something(&self);
}
impl<T> OptionMethods<T> for HasSome<T> {
fn to_std(self) -> Option<T> {
Some(self.0)
}
fn something(&self) {}
}
impl<T> OptionMethods<T> for HasNothing {
fn to_std(self) -> Option<T> {
None
}
fn something(&self) {}
}
#[enum_dispatch(OptionMethods)]
enum SomeOrNone<T> {
HasSome(HasSome<T>),
HasNoting(HasNothing),
}
fn main() {
let maybe_something = HasSome("abc");
println!("{}", maybe_something.to_std().unwrap());
}
When compiling it (both stable and nightly rustc) I get the following error: (-Z macro-backtrace
enabled)
error[E0282]: type annotations needed
--> src\main.rs:26:1
|
26 | #[enum_dispatch(OptionMethods)]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
| cannot infer type for type parameter `T` declared on the trait `OptionMethods`
| in this macro invocation
|
::: C:\Users\Ruben Anders\.cargo\registry\src\github.com-1ecc6299db9ec823\enum_dispatch-0.3.1\src\lib.rs:357:1
|
357 | / pub fn enum_dispatch(attr: TokenStream, item: TokenStream) -> TokenStream {
358 | | let new_block = attributed_parser::parse_attributed(item.clone()).unwrap();
359 | | let expanded = match &new_block {
360 | | attributed_parser::ParsedItem::Trait(traitdef) => {
... |
412 | | expanded.into()
413 | | }
| |_- in this expansion of `#[enum_dispatch]`
I am not quite sure yet what combination of struct/trait/method signatures causes this behaviour. It seems to me like it is caused by the something
method not using the T
parameter anywhere in its parameters or its return type.