拥有这些相当人为的类型定义
trait Generic<T> {
fn some(&self) -> T;
}
impl<T> Generic<T> for i32
where
T: Default,
{
fn some(&self) -> T {
T::default()
}
}
Run Code Online (Sandbox Code Playgroud)
我想调用some显式指定类型 T 的方法。下面的代码显然不起作用,因为该方法本身不是通用的。
fn main() {
let int: i32 = 45;
println!( "some: {}", int.some<bool>() );
}
Run Code Online (Sandbox Code Playgroud)
正确的通话方式是什么some?
您必须按照您的尝试指定确切的类型。不幸的是,您的函数不是通用的,而是您的实现是通用的,因此您必须执行以下操作:
fn main() {
let int: i32 = 45;
println!("some: {}", <i32 as Generic<bool>>::some(&int));
// Or,
println!("some: {}", Generic::<bool>::some(&int));
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以定义一个辅助特征:
trait HasSome {
fn other_some<T>(&self) -> T where Self: Generic<T> {
<Self as Generic<T>>::some(self)
}
}
impl<T> HasSome for T {} // Blanket impl.
Run Code Online (Sandbox Code Playgroud)
游乐场。
附带说明一下,请注意,在指定类型或函数的泛型时,您需要使用“turbofish”::<>运算符:
let foo = Vec::<i32>::new(); // Vec<i32>
let foo = my_generic_function::<usize>(); // Calls my_generic_function with usize
let foo = Option::<usize>::None;
let foo = None::<usize>;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4826 次 |
| 最近记录: |