LoginSignup
1
0

More than 5 years have passed since last update.

[Rust][未解決] Selfに対するトレイト境界に関する疑問

Last updated at Posted at 2019-04-22

以下はActixのコードを切り貼りして作ったもの

最後の行がどうしてもコンパイル通すことができない。

そもそもActor::start()でのSelfに対するトレイト境界はmyactor2.start()のようなものををコンパイルエラーにするのが役割なのだろうか?

以下こちらにもコードを貼っておく。

use std::marker::PhantomData;

struct Context<A>
where
    A: Actor<Context = Context<A>>,
{
    _phantom_data: PhantomData<A>,
}

trait ActorContext: Sized {}

impl<A> ActorContext for Context<A>
where
    A: Actor<Context = Self>,
{
}

impl<A> Context<A>
where
    A: Actor<Context = Self>,
{
    fn new() -> Self {
        Context { _phantom_data: PhantomData }
    }
}

trait Actor: Sized {
    type Context: ActorContext;

    fn start(&self)
    where
        Self: Actor<Context = Context<Self>>,
    {
        Context::<Self>::new();
    }
}

struct MyActor;
struct MyActor2;

impl Actor for MyActor {
    type Context = Context<Self>;
}

impl Actor for MyActor2 {
    type Context = SyncContext;
}

struct SyncContext;

impl ActorContext for SyncContext {}

fn main() {
    let myactor = MyActor {};
    myactor.start();

    let myactor2 = MyActor2 {};
    // myactor2.start(); // コンパイルエラー
}
1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0