How to call associated function?

I want to write a struct which has a take function and also implements the Iterator trait. How can I call the take associated function instead of the trait function? The compiler calls the take of the Iterator trait. How it works? The Option type also has a take as associated function and implements iterator, but it call associated function when I write option.take()

pub struct Wrapper<T> {
    inner: Vec<T>,
}

impl<T> Wrapper<T> {
    pub fn take(&mut self) -> Option<T> {
        self.inner.pop()
    }
}

impl<T> Iterator for Wrapper<T> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        Self::take(self)
    }
}

fn main() {
    let mut wrapper = Wrapper {
        inner: vec![],
    };
    
    let _ = wrapper.take();
}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
error[E0061]: this function takes 1 argument but 0 arguments were supplied
    --> src/main.rs:24:21
     |
24   |     let _ = wrapper.take();
     |                     ^^^^- supplied 0 arguments
     |                     |
     |                     expected 1 argument
     |
note: associated function defined here

For more information about this error, try `rustc --explain E0061`.
error: could not compile `playground` due to previous error

You can use the fully-qualified syntax to call it:

fn main() {
    let mut wrapper: Wrapper<String> = Wrapper {
        inner: vec![],
    };
    
    let _ = Wrapper::take(&mut wrapper);
}

I can, but I thought an associated function should be in priority :face_with_raised_eyebrow:
I tested it with this example:

It looks I get what the problem is. The Option type implements the IntoIterator but not the Iterator. This allows you to call take

Inherent method has priority over trait method, yes, but (self) method takes priority over (&mut self) method when called on an owned value. You could use (&mut wrapper).take() to call the inherent method instead.

Your observation about why the problem doesn't appear for the Option type is still accurate :wink:

5 Likes

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.