アンチパターン Deref ポリモフィズム

github.com

use std::ops::Deref;

struct Foo;
impl Foo {
    fn m(&self) {
        println!("hello, I'm Foo");
    }
}

struct Bar {
    f: Foo,
}

impl Deref for Bar {
    type Target = Foo;
    fn deref(&self) -> &Foo {
        &self.f
    }
}

fn main() {
    let bar = Bar {
        f: Foo,
    };

    // BarがDeref<Target=Foo>を実装することで、Fooのメソッドを呼び出すことが可能となる
    bar.m();
}

関連

自動参照外し (Auto-dereferencing) - あるマのメモ書き