19

I am trying to understand what exactly the scope is for functions defined within an impl block but which don't accept &self as a parameter. For example, why doesn't the following chunk of code compile? I get the error "cannot find function generate_a_result in this scope".

pub struct Blob {
    num: u32,
}

impl Blob {
    pub fn new() -> Blob {
        generate_a_result()
    }

    fn generate_a_result() -> Blob {
        let result = Blob {
            num: 0
        };

        result
    }
}
Lukas Kalbertodt
  • 79,749
  • 26
  • 255
  • 305
Scott L.
  • 265
  • 2
  • 9

1 Answers1

26

These functions are called associated functions. And they live in the namespace of the type. They always have to be called like Type::function(). In your case, that's Blob::generate_a_result(). But for referring to your own type, there is the special keyword Self. So the best solution is:

Self::generate_a_result()
Lukas Kalbertodt
  • 79,749
  • 26
  • 255
  • 305