Can I call an associated function from a new type?

For example:

use std::ops::{Deref, DerefMut};

struct Foo {}

impl Foo {
    pub fn foo1() {}
    pub fn foo2(&self) {}
}

pub struct Bar(Foo);

impl Deref for Bar {
    type Target = Foo;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for Bar {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

fn main() {
    Bar::foo1(); // won't compile
}

I'm kind of knowing why this happens and how Deref trait works, but I still wondered if I can "hide" the Foo, and calling all it's associated function from Bar.

No, automatic dereferencing in method resolution is something that's specific to method-call syntax. Associated functions (non-methods, or even methods when you aren't using method call syntax [1]) don't work like this. The only way to "hide" the Foo is to define a wrapper function

impl Bar { fn foo1() { Foo::foo1() } }

  1. so in your example, my_bar_value.foo2() works, but Bar::foo2(&my_bar_value) doesn't; but Foo::foo2(&my_bar_value) does work again because of deref coercion ↩︎

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.