How to return a vector containing generic values

匿名 (未验证) 提交于 2019-12-03 09:14:57

问题:

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); } 

回答1:

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); } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!