Rules for determining rust for functions belonging to the structure

I am trying to understand what scope is for functions defined in the impl block, but which do not accept &self as a parameter. For example, why is the following code fragment not compiling? I get the error "I can not find the generate_a_result function in this area."

 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 } } 
+5
source share
1 answer

These functions are called related functions . And they live in a type namespace. They should always be called as Type::function() . In your case, this is Blob::generate_a_result() . But to refer to your own type there is a special keyword Self . Therefore, the best solution is:

 Self::generate_a_result() 
+6
source

Source: https://habr.com/ru/post/1271063/


All Articles