Help us understand the problem. What is going on with this article?

[Rust] トレイトの参照でハマる

More than 1 year has passed since last update.

素朴なOOPLの気持ちで書いてるとハマる話

経緯

経緯を簡略化したコードで書いていく。

元のコード

struct Context;

impl Context {
    fn do_something(&mut self) {}
}

fn func(context: &mut Context) {
    context.do_something();
}

実際はContextはメンバ持ってたり、do_something()も空実装ではないが省略。

次にContextをトレイトにしたくなった。

trait Context {
    fn do_something(&mut self);
}

struct ContextImpl;

impl Context for ContextImpl {
    fn do_something(&mut self) {}
}

fn func(context: &mut Context) {
    context.do_something();
}

特に問題は無い。

ここに、Hogeトレイトを追加して、Contextに対して実装する。

trait Hoge {
    fn hoge(&mut self);
}

impl<T: Context> Hoge for T {
    fn hoge(&mut self) {
        self.do_something();
    }
}

fn func(context: &mut Context) {
    context.do_something();
    context.hoge();
}

コンパイルエラーになる

error[E0599]: no method named `hoge` found for type `&mut dyn Context` in the current scope
  --> src/main.rs:23:13
   |
23 |     context.hoge();
   |             ^^^^
   |
   = note: the method `hoge` exists but the following trait bounds were not satisfied:
           `&mut dyn Context : Hoge`
           `dyn Context : Hoge`
   = help: items from traits can only be used if the trait is implemented and in scope
   = note: the following trait defines an item `hoge`, perhaps you need to implement it:
           candidate #1: `Hoge`

error: aborting due to previous error

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=cff9dff5ee5ff267d9b76e382d463589

何がいけなかったかと言うと、func()の引数を&mut Contextのままにしておいたのがダメだった。

fn func<T: Context>(context: &mut T) {
    context.do_something();
    context.hoge();
}

これでコンパイルエラーはなくなる。

itage
ITAGEは「IT」のAGENCYになることを夢、目標として進化、変化していきます。「It’s It Agency」
http://www.itage.co.jp
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした