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

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.

主站蜘蛛池模板: 台北县| 安阳市| 建昌县| 诸城市| 武冈市| 莱芜市| 孝义市| 昌都县| 沐川县| 湖南省| 沽源县| 香港| 潜山县| 拜泉县| 蓬安县| 礼泉县| 武冈市| 小金县| 营口市| 黑水县| 岳普湖县| 兴安盟| 亚东县| 永登县| 长岭县| 沈阳市| 阳新县| 新丰县| 藁城市| 咸丰县| 车险| 沛县| 观塘区| 张家川| 清苑县| 辽宁省| 松原市| 正宁县| 离岛区| 永胜县| 平昌县|