我有一个名为cr
的函数,我希望默认情况下通用类型 T
为 serde_json::Value
。我该如何实现?
fn main() {
cr()
}
fn cr<T = serde_json::Value>() {
}
我遇到了这个错误:
在调用cr时无法推断函数声明的类型参数T。
在cr函数中,我也遇到了这个错误:类型参数的默认值只允许出现在结构体、枚举、类型或trait定义中。
我有一个名为cr
的函数,我希望默认情况下通用类型 T
为 serde_json::Value
。我该如何实现?
fn main() {
cr()
}
fn cr<T = serde_json::Value>() {
}
在调用cr时无法推断函数声明的类型参数T。
在cr函数中,我也遇到了这个错误:类型参数的默认值只允许出现在结构体、枚举、类型或trait定义中。
正如错误所述,您不能在函数签名中使用默认类型参数。您可以通过包装类型来解决此问题。
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
中的默认替换。type Echo<X = i32> = std::result::Result<X, String>;
fn test(x: Echo) {
// ...
}
fn main() {
test(Err("test".into()));
}
serde_json::Value
调用cr
函数,可以使用所谓的“turbofish”符号来指定:cr::<serde_json::Value>()
- Neikos