- Rust Programming By Example
- Guillaume Gomez Antoni Boucher
- 162字
- 2021-07-02 19:12:58
Constructors
Rust does not provide constructors, but a common idiom is to create a new() static method, also called an associated function:
impl Point { fn new(x: i32, y: i32) -> Self { Self { x: x, y: y } } }
The difference with a normal method is that it does not take &self (or one of its variations) as a parameter.
Self is the type of the self value; we could have used Point instead of Self.
When the field name is the same as the value assigned, it is possible to omit the value, as a shorthand:
fn new(x: i32, y: i32) -> Self { Self { x, y } }
When we create an instance of Point with the call to its constructor (let point = Point::new();), this will allocate the value on the stack.
We can provide multiple constructors:
impl Point { fn origin() -> Self { Point { x: 0, y: 0 } } }
推薦閱讀
- 企業(yè)數(shù)字檔案館建設(shè)理論與實(shí)踐
- 中國人民大學(xué)復(fù)印報(bào)刊資料轉(zhuǎn)載指數(shù)排名研究報(bào)告2016
- 非物質(zhì)文化遺產(chǎn)數(shù)字化研究
- 博物館新視覺:博物館管理叢書
- 海源閣史
- Rust Programming By Example
- 西夏檔案及其管理制度研究
- 圖書館合理分享著作權(quán)利益訴求研究
- 大學(xué)圖書館信息服務(wù)與信息素養(yǎng)教育理論與實(shí)踐研究
- 武大老照片
- 圖書館服務(wù)均等化與資源共享(上冊)
- 李一氓文存(套裝全五冊)
- “秦陵杯”講解員職業(yè)技能大賽講解詞匯編
- 中國人民大學(xué)復(fù)印報(bào)刊資料轉(zhuǎn)載指數(shù)排名研究報(bào)告2017
- 高校圖書館學(xué)科服務(wù)研究