- 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.
推薦閱讀
- 嵌入式軟件系統測試:基于形式化方法的自動化測試解決方案
- Learning Chef
- iOS 9 Game Development Essentials
- JavaScript+jQuery網頁特效設計任務驅動教程(第2版)
- Java Web應用開發技術與案例教程(第2版)
- Java Web基礎與實例教程
- Lighttpd源碼分析
- Learning Modular Java Programming
- Hands-On Kubernetes on Windows
- BeagleBone Robotic Projects(Second Edition)
- Scala編程實戰
- C#程序設計基礎入門教程
- WordPress Search Engine Optimization(Second Edition)
- SQL Server實例教程(2008版)
- Apache Kafka 1.0 Cookbook