- 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.
推薦閱讀
- Java 開發從入門到精通(第2版)
- Android 7編程入門經典:使用Android Studio 2(第4版)
- 數據結構與算法JavaScript描述
- Django:Web Development with Python
- UML 基礎與 Rose 建模案例(第3版)
- Scala Data Analysis Cookbook
- Python+Tableau數據可視化之美
- C++程序設計教程(第2版)
- 算法設計與分析:基于C++編程語言的描述
- PhoneGap 4 Mobile Application Development Cookbook
- Java高手是怎樣煉成的:原理、方法與實踐
- C# 7.1 and .NET Core 2.0:Modern Cross-Platform Development(Third Edition)
- Instant GLEW
- Beginning C# 7 Hands-On:The Core Language
- Tkinter GUI Programming by Example