简体   繁体   English

如何在 rust function 中传递默认泛型类型?

[英]How to pass default generic type in rust function?

So I have a function called cr where I want the generic T to be serde_json::Value by default.所以我有一个名为cr的 function 我希望通用T默认为serde_json::Value How can I do this?我怎样才能做到这一点?

fn main() {
    cr()
}

fn cr<T = serde_json::Value>() {

}

I get this error: cannot infer type for type parameter T declared on the function cr while calling cr.我收到此错误:在调用 cr 时cannot infer type for type parameter T declared on the function cr And on cr function I get this error: defaults for type parameters are only allowed in struct, enum, type, or trait definitions.在 cr function 上,我收到此错误: defaults for type parameters are only allowed in struct, enum, type, or trait definitions.

As the error said you cannot use default type parameters in function signatures.正如错误所说,您不能在 function 签名中使用默认类型参数。 You can workaround this with a wrapper type.您可以使用包装器类型解决此问题。

use std::marker::PhantomData;

struct MyDefault;
struct Custom;

pub fn main() {
    Wrapper::cr(); //~ ERROR type annotations needed
    <Wrapper>::cr();

    Wrapper::<Custom>::cr();
    <Wrapper<Custom>>::cr();
}

struct Wrapper<T = MyDefault>(PhantomData<T>);

impl<T> Wrapper<T> {
    fn cr() {
        let _: T = todo!();
    }
}

Inference cannot guess so it needs a type hint that can be used for substitution.推理无法猜测,因此它需要一个可用于替换的类型提示。 For example let x: SomeType<SubstType> or fully qualified path <SomeType<SubstType>>::associated_item .例如let x: SomeType<SubstType>或完全限定路径<SomeType<SubstType>>::associated_item Omitting the substitutions here triggers the default substitution in SomeType .在此处省略替换会触发SomeType中的默认替换。

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

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