假设我有一个这样的函数:
fn my<T: fmt::Debug, U>(x: T) {
println!("{:?}", mem::size_of::<U>());
println!("{:?}", x);
}
这取决于两种类型T
和U
。我必须指定类型 U
当我调用函数my
时。另一方面,类型 T
可以从传递的 x 确定,所以,这是合乎逻辑的,我可以在通话中错过它。
当我尝试时:
my::<u8>(10);
我收到错误:
error[E0107]: wrong number of type arguments: expected 2, found 1
让 Rust 编译器获取类型 T
的正确方法是什么?来自已通过 x
并通过U
仅在 <...>
?
最佳答案
在 Rust 中,类型位置中的 _
用于要求编译器推断某些内容:
let foo: Vec<_> = (1..10).map(|i| i.to_string()).collect();
// ^ collect in a vector whose type should be obvious
这也适用于您的情况:
my::<_, u8>(10);
// ^ infer `T`
关于rust - 如何将一种类型传递给在 Rust 中用两种类型定义的泛型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61557161/