Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to prevent a struct from implementing a trait method?

Tags:

rust

traits

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");
    }
}
like image 545
Rahn Avatar asked Jan 26 '26 23:01

Rahn


1 Answers

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);
}
like image 80
Aleksander Krauze Avatar answered Jan 29 '26 02:01

Aleksander Krauze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!