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

  • Learning Rust
  • Paul Johnson Vesa Kaihlavirta
  • 153字
  • 2021-07-02 23:07:20

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.

主站蜘蛛池模板: 南和县| 西丰县| 通州区| 获嘉县| 钟祥市| 登封市| 无为县| 东光县| 宜州市| 渑池县| 石楼县| 承德市| 平山县| 蒲江县| 江门市| 东港市| 道孚县| 扎兰屯市| 巴南区| 呼伦贝尔市| 民和| 抚州市| 同仁县| 全椒县| 涪陵区| 竹溪县| 诏安县| 内江市| 新河县| 岢岚县| 怀远县| 平南县| 石泉县| 景泰县| 临汾市| 乌苏市| 屏边| 平乡县| 亚东县| 邻水| 防城港市|