prevent a trait function from being implemented by other struct

prevent a trait function from being implemented by other struct


9

I just build a trait Bar with 2 functions (alpha() with implementation and beta() with only interfaces), and I hope the struct who implement Bar implements only beta(), and never implement their own alpha().

Is there any way to prevent another struct from implementing their own 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");
    }
}

1 Answer
1


14

You can do this, by splitting your trait into two, and providing a blanket implementation for the trait with default method.

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);
}

1

  • 3

    You may not even a trait for this. fn alpha<T: Bar> might also work.

    – corvus_192

    5 hours ago



Leave a Reply

Your email address will not be published. Required fields are marked *