如何返回包含通用值的向量 [英] How to return a vector containing generic values

查看:38
本文介绍了如何返回包含通用值的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从函数返回一个向量,但编译器给了我以下错误消息:

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]

我在这里错过了什么?

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>`

也就是说,您不是在返回一些通用的 T,而是在返回一个具体的类型.实际上,您不是只返回一种类型,而是试图返回两种不同 类型!

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!

每次解析泛型时,它必须解析为单一类型.也就是说,您可以使用两个 u32 或两个 bool 调用 foo(a: T, b: T),但是 各取一个.

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

这篇关于如何返回包含通用值的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆