[英]How to use only one type parameter to define a generic function in Rust
[英]How to pass default generic type in rust function?
所以我有一个名为cr
的 function 我希望通用T
默认为serde_json::Value
。 我怎样才能做到这一点?
fn main() {
cr()
}
fn cr<T = serde_json::Value>() {
}
我收到此错误:在调用 cr 时cannot infer type for type parameter T declared on the function cr
。 在 cr function 上,我收到此错误: defaults for type parameters are only allowed in struct, enum, type, or trait definitions.
正如错误所说,您不能在 function 签名中使用默认类型参数。 您可以使用包装器类型解决此问题。
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
中的默认替换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.