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
}
}
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.
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, }
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 .
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With