Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust scoping rules for struct-owned functions

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
    }
}
like image 906
Scott L. Avatar asked Aug 21 '17 18:08

Scott L.


People also ask

Can structs have functions Rust?

Rust uses a feature called traits, which define a bundle of functions for structs to implement. One benefit of traits is you can use them for typing. You can create functions that can be used by any structs that implement the same trait.

What are associated functions and methods in Rust?

Associated functions are functions that are defined on a type generally, while methods are associated functions that are called on a particular instance of a type. struct Point { x: f64, y: f64, }

What is scope in Rust?

The scope is the chunk of memory where the block's variables are stored. Every data value has an owning scope, including implied temporary values such as the result of 2 + 2 when we ask Rust to compute (2 + 2) * 3 .

How do you make a method in Rust?

Defining Methods The method syntax goes after an instance: we add a dot followed by the method name, parentheses, and any arguments. In the signature for area , we use &self instead of rectangle: &Rectangle because Rust knows the type of self is Rectangle due to this method being inside the impl Rectangle context.


1 Answers

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()
like image 66
Lukas Kalbertodt Avatar answered Oct 15 '22 06:10

Lukas Kalbertodt