简体   繁体   English

在 rust 中返回没有泛型参数的泛型类型

[英]return generic type without generic argument in rust

I have a code where I want to create a wrapper around a library to make it work in the same philosophy as the rest of my code.我有一个代码,我想在其中创建一个库的包装器,以使其与我的其余代码的工作原理相同。 To avoid writing hundreds of structs I am creating a generic one (Worker).为了避免编写数百个结构,我创建了一个通用结构(Worker)。 But I am using the function to configure it and I pass that information as an enum:但是我正在使用该函数来配置它,并将该信息作为枚举传递:

fn configure(config: Config) -> Worker<T> {
    match config {
        some_config => Worker<some_type>,
        _ => {...}
}

As I am already passing the information as an enum I want to avoid passing a type argument to the function but obviously rust complains because T is not defined.由于我已经将信息作为枚举传递,因此我想避免将类型参数传递给函数,但显然 rust 会抱怨,因为 T 未定义。

Is there a way to make rust infer the type of the return generic of something?有没有办法让 rust 推断某些东西的返回泛型的类型? I've though of using a macro too but I don't know if it's the right solution.我也曾使用过宏,但我不知道这是否是正确的解决方案。 Any idea of how to solve this?知道如何解决这个问题吗? Thank you in advance for your time!提前感谢您的时间!

If I understand correctly, the concrete type for T will be different depending on what was passed in the enum.如果我理解正确,根据枚举中传递的内容, T的具体类型会有所不同。

You can't do that with generics though.但是你不能用泛型做到这一点。 For any concrete type that's filled in for T , each branch of a function needs to return the same type.对于为T填充的任何具体类型,函数的每个分支都需要返回相同的类型。 You can't have a function that, based on some enum or if statement returns, say, a Vec<String> versus a Vec<u32> .你不能有一个基于枚举或if语句返回的函数,比如Vec<String>Vec<u32>

Ways around that: Wrap them in an enum, too.解决方法:也将它们包裹在枚举中。

Or use traits instead of generics.或者使用特征而不是泛型。 Then your function can return, for example, a Box<dyn Worker> and Worker is a trait.然后你的函数可以返回,例如,一个Box<dyn Worker>Worker是一个特征。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM