1

I have this code that uses generics.

trait RefGen {
    fn gen () -> String;
}

struct FooGen;

impl RefGen for FooGen {
    fn gen () -> String {
        "foo".to_owned()
    }
}

struct Facade<R: RefGen> {
    gen: R
}

impl<R: RefGen> Facade<R> {
    fn new() -> Facade<R> {
        Facade {
            gen: FooGen
        }
    }
}

I wonder why Rust is telling me I can't use a FooGen for a RefGen. It certainly implements RefGen.

The exact error message is:

expected `Facade<R>`,
found `Facade<FooGen>`

Here is a playpen: http://is.gd/oBIB1o

Christoph
  • 26,519
  • 28
  • 95
  • 133
  • 1
    Duplicate of http://stackoverflow.com/q/32551177/155423 or http://stackoverflow.com/q/31490913/155423 or http://stackoverflow.com/q/31060851/155423 or http://stackoverflow.com/q/33812706/155423 or (insert more search results here). – Shepmaster Dec 08 '15 at 19:15

1 Answers1

1

This works:

impl<R: RefGen> Facade<R> {
  fn new(gen: R) -> Facade<R> {
    Facade {
      gen: gen
    }
  }
}

I am not sure about the precise terms to explain this, but here it goes: in your code, the type R is determined inside the new function. However, Rust requires you to provide the type from outside the function. Check out the following example:

// This doesn't typecheck
fn foo1<T: Clone>() -> T {
    "hi"
}

// This works
fn foo2<T: Clone>(x: T) -> T {
    x
}

See this answer for a more detailed explanation

Community
  • 1
  • 1
aochagavia
  • 5,887
  • 5
  • 34
  • 53