代码之家  ›  专栏  ›  技术社区  ›  Axel

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

  •  0
  • Axel  · 技术社区  · 3 年前

    所以我有一个函数叫做 cr 我想要通用的 T 成为 serde_json::Value 默认情况下。我该怎么做?

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

    我得到这个错误: cannot infer type for type parameter T declared on the function cr 在调用cr时,在cr函数上我得到了这个错误: defaults for type parameters are only allowed in struct, enum, type, or trait definitions.

    0 回复  |  直到 3 年前
        1
  •  2
  •   Dawer    3 年前

    正如错误所说,您不能在函数签名中使用默认类型参数。 您可以使用包装器类型来解决此问题。

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

    推理无法猜测,因此需要一个可用于替换的类型提示。例如 let x: SomeType<SubstType> 或完全合格的路径 <SomeType<SubstType>>::associated_item 。省略此处的替换会触发中的默认替换 SomeType .