![](/img/trans.png)
[英]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.