Functions and methods in Rust

When we look at C++ or C#, a method is a programming unit within a class that does a specific task. A method in Rust is a function attached to compound data structures, or structs. These methods have access to the data of the object using the self parameter. They are defined in an impl block, as shown in the following example (a fuller example is given in the source examples):

struct Point { 
    x: f64, 
    y: f64 
} 
 
impl Point { 
    fn origin() -> Point { 
        Point {x: 0.0, y: 0.0 } 
    } 
 
    fn new(my_x: f64, my_y: f64) -> Point { 
        Point { x: my_x, y: my_y } 
    } 
} 

Here, we defined a struct, Point, for points in 2D space. Then, we defined two constructor methods for that struct: origin for making a new point in location 0,0 and another for making a new arbitrary point.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset