相关疑难解决方法(0)

如何根据泛型类型是否实现特征以不同方式实现函数?

我想do_something根据泛型类型是否实现来实现有条件的T实现Debug。有没有办法做这样的事情?

struct A(i32);

#[derive(Debug)]
struct B(i32);

struct Foo<T> {
    data: T,
    /* more fields */
}

impl<T> Foo<T> {
    fn do_something(&self) {
        /* ... */
        println!("Success!");
    }

    fn do_something(&self)
    where
        T: Debug,
    {
        /* ... */
        println!("Success on {:?}", self.data);
    }
}

fn main() {
    let foo = Foo {
        data: A(3), /* ... */
    };
    foo.do_something(); // should call first implementation, because A
                        // doesn't implement Debug

    let foo = Foo {
        data: …
Run Code Online (Sandbox Code Playgroud)

generic-programming rust

5
推荐指数
1
解决办法
577
查看次数

标签 统计

generic-programming ×1

rust ×1