Generics require type annotation

I am sure I am just missing something simple here. I am getting an [E0282] error that says I need "type annotation" when constructing generics. I knew it would, and I thought I had included them, but no combination of annotations has worked for me.

The simplified code is:

  1. A Trait Handle with no default methods (just a contract)
  2. An FsHandle struct that implements the Handle
  3. A Db struct that requires an implementation of Handle
  4. The Db struct also has a new() method. This method is what is requiring the type annotation.
// My Abstract Handle
trait Handle {
    fn load(&self);

// My Concrete Trait
pub struct FsHandle {}

impl Handle for FsHandle {
    fn load(&self) {
        // Do whatever

// My Database that has a handle
struct Db<H: Handle> {
    handle: H,

impl<H> Db<H>
    where H: Handle
    pub fn new<T: Handle>(handle: T) -> Db<T> {
        Db {

// And my main
fn main() {
    let fs = FsHandle {};
    let db = Db::new::<FsHandle>(fs);

I have tried a number of type annotations around calling new() with no luck.

error[E0282]: type annotations needed
  --> src/
36 |     let db = Db::new::<FsHandle>(fs);
   |              ^^^^^^^^^^^^^^^^^^^ cannot infer type for type parameter `H`

error: aborting due to previous error

I am also curious why I can't use H as the generic type in the declaration of my new method. These two things seem connected to me. I have read the chapters on generics several times, and multiple stack overflows. I am sure I missed something obvious, though.

Thanks in advance.

You have two type parameters that need to be inferred, H and T, H is unconstrained so Rust can't tell what type to put. Instead of making new generic over T, use H that way there is only 1 type parameter to infer.

1 Like

Aha! Thank you @RustyYato

I tried that the first time, but it made new generic and it complained that I couldn't reuse H.

pub fn new<H>(handle: H) -> Db<H> {

But making new non generic fixed it

pub fn new(handle: H) -> Db<H> {

That's what I meant, I should have been more clear about that

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.