rust 防止trait函数被其他struct实现

fdbelqdn  于 2024-01-08  发布在  其他
关注(0)|答案(1)|浏览(85)

我只是构建了一个有两个函数的trait Baralpha()有实现,beta()只有接口),我希望实现Bar的struct只实现beta(),永远不要实现自己的alpha()
有什么方法可以阻止另一个结构实现自己的alpha()吗?

trait Bar {
    fn alpha(&self) {
        println!("you should never implement this function on your own.");
    }

    fn beta(&self);
}

struct Foo {}

impl Bar for Foo {
    fn alpha(&self) {
        println!("how do I trigger an error here when a struct implement it's own alpha()?");
    }

    fn beta(&self) {
        println!("implement beta() for Foo");
    }
}

字符串

7z5jn7bk

7z5jn7bk1#

你可以通过将trait分成两个,并为trait提供一个包含default方法的实现来实现。

pub trait Beta {
    fn beta(&self);
}

pub trait Alpha: Beta {
    fn alpha(&self) {
        // Default impl
    }
}

// Because of this blanket implementation,
// no type can implement `Alpha` directly,
// since it would conflict with this impl.
// And you cannot implement `Alpha` without `Beta`,
// since `Beta` is its _supertrait_.
impl<T: Beta> Alpha for T {}

struct Foo;

impl Beta for Foo {
    fn beta(&self) {
        // Impl
    }
}

// If you uncomment this you will have a compile error,
// because of the conflicting implementations of Alpha for Foo
// (conflicts with the blanket implementation above)
//
// impl Alpha for Foo {
//    fn alpha(&self) {
//        // override impl
//    } 
// }

pub fn bar<T: Alpha>(_: T) {}

pub fn baz() {
    bar(Foo);
}

字符串

相关问题