- 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.
推薦閱讀
- 零基礎學Visual C++第3版
- 復雜軟件設計之道:領域驅動設計全面解析與實戰
- Production Ready OpenStack:Recipes for Successful Environments
- C語言實驗指導及習題解析
- SAP BusinessObjects Dashboards 4.1 Cookbook
- 第一行代碼 C語言(視頻講解版)
- Mastering Business Intelligence with MicroStrategy
- 基于ARM Cortex-M4F內核的MSP432 MCU開發實踐
- Clojure Data Structures and Algorithms Cookbook
- Mastering ArcGIS Server Development with JavaScript
- Python繪圖指南:分形與數據可視化(全彩)
- 深入理解Zabbix監控系統
- SAP HANA Starter
- R for Data Science Cookbook
- Java實踐指南