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

1

14

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");
    }
}
Sandrocottus answered 28/11, 2023 at 8:4 Comment(0)
H
20

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);
}
Herbherbaceous answered 28/11, 2023 at 8:18 Comment(2)
You may not even a trait for this. fn alpha<T: Bar> might also work.Admit
@Admit Could you elaborate, pehaps post a new answer?Sandrocottus

© 2022 - 2024 — McMap. All rights reserved.