I'm trying to return a vector from a function but the compiler gives me the following error message:
expected `Foo<T>`, found `Foo<&str>` (expected type parameter, found &-ptr) [E0308]
What am I missing here?
struct Foo<T> { bar: T, } fn foos<T>() -> Vec<Foo<T>> { vec![ Foo { bar: "x" }, Foo { bar: 1 }, ] } fn main() { let my_foos: Vec<_> = foos(); println!("{}", my_foos[0].bar); }
The compiler is giving you a good error message here:
expected `Foo<T>`, found `Foo<&str>`
That is, you aren't returning some generic T
, you are returning a concrete type. Actually, you aren't returning just one type, you are trying to return two different types!
Each time a generic is resolved, it must resolve to a single type. That is, you can call foo<T>(a: T, b: T)
with two u32
or two bool
, but not with one of each.
To make your code work in the most straight-forward way, you can use an enum. This creates a single type that can have one of a set of values:
struct Foo<T> { bar: T, } #[derive(Debug)] enum Bar<'a> { Num(i32), Str(&'a str), } // Note no generics here, we specify the concrete type that this `Foo` is fn foos() -> Vec<Foo<Bar<'static>>> { vec![ Foo { bar: Bar::Str("x") }, Foo { bar: Bar::Num(1) }, ] } fn main() { let my_foos: Vec<_> = foos(); println!("{:?}", my_foos[0].bar); }