官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 高台县| 仙桃市| 卢龙县| 阿巴嘎旗| 梧州市| 通州市| 大新县| 宣化县| 甘德县| 都匀市| 上蔡县| 秦安县| 桐乡市| 来宾市| 正蓝旗| 理塘县| 广西| 闽清县| 平果县| 普兰县| 西盟| 常山县| 上蔡县| 耿马| 霍山县| 丰城市| 会宁县| 海门市| 泰和县| 邹城市| 威信县| 新津县| 平南县| 新蔡县| 沅陵县| 保靖县| 江西省| 民权县| 金华市| 阳曲县| 芦山县|