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

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.

主站蜘蛛池模板: 徐汇区| 建瓯市| 文山县| 深圳市| 德庆县| 普安县| 甘孜县| 临高县| 东平县| 新丰县| 珲春市| 锡林浩特市| 延边| 舟曲县| 南宁市| 滨海县| 精河县| 张北县| 峨山| 宁远县| 呼伦贝尔市| 龙山县| 莱芜市| 武功县| 东台市| 潍坊市| 勐海县| 丹凤县| 新巴尔虎左旗| 沾化县| 儋州市| 洛南县| 翁源县| 南昌市| 尉氏县| 明溪县| 桐城市| 绥芬河市| 图们市| 龙江县| 鲜城|