防止特征函数被其他结构实现

Rah*_*ahn 13 traits rust

我只是构建了一个Bar具有 2 个函数的特征(alpha()带有实现和beta()仅带有接口),并且我希望实现的结构Bar只实现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");
    }
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*uze 20

您可以通过将您的特征分成两部分,并使用默认方法为该特征提供一揽子实现来做到这一点。

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);
}
Run Code Online (Sandbox Code Playgroud)

  • 你甚至可能没有这方面的特质。`fn alpha&lt;T: Bar&gt;` 也可能有效。 (4认同)
  • @corvus_192 你能详细说明一下,也许发布一个新答案吗? (4认同)