简体   繁体   English

如何在 Rust 中调用通用 trait 方法

[英]How to call generic trait method in Rust

Having these rather contrived type definitions拥有这些相当人为的类型定义

trait Generic<T> {
    fn some(&self) -> T;
}

impl<T> Generic<T> for i32
where
    T: Default,
{
    fn some(&self) -> T {
        T::default()
    }
}

I would like to call some method explicitly specifying type T. Below code apparently does not work because the method itself is not generic.我想调用some明确指定类型 T 的方法。下面的代码显然不起作用,因为该方法本身不是通用的。

fn main() {
    let int: i32 = 45;
    println!( "some: {}", int.some<bool>() );
}

What's the right way of calling some ?调用some的正确方法是什么?

You must specify the exact type, as you tried.正如您所尝试的那样,您必须指定确切的类型。 Unfortunately, your function is not generic, and instead your implementation is generic, so you'd have to do the following:不幸的是,您的函数不是通用的,而是您的实现是通用的,因此您必须执行以下操作:

fn main() {
    let int: i32 = 45;
    println!("some: {}", <i32 as Generic<bool>>::some(&int));
    // Or,
    println!("some: {}", Generic::<bool>::some(&int));
}

Alternatively you could define a helper trait:或者,您可以定义一个辅助特征:

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. 

Playground . 游乐场


On a side note, please know that when specifying the generics of a type or function you need to use the "turbofish" ::<> operator:另外,请注意,在指定类型或函数的泛型时,您需要使用“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>;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM