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

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 }
    }
}
主站蜘蛛池模板: 永福县| 微山县| 兴义市| 合水县| 新绛县| 淮阳县| 洪洞县| 保山市| 舞阳县| 阿瓦提县| 和静县| 西峡县| 都兰县| 百色市| 丰县| 永康市| 收藏| 将乐县| 纳雍县| 平谷区| 家居| 兴化市| 凤冈县| 木里| 泗洪县| 锡林浩特市| 屏边| 望都县| 汉寿县| 巴塘县| 额尔古纳市| 济源市| 龙州县| 临邑县| 宿迁市| 高阳县| 库尔勒市| 民勤县| 什邡市| 昌邑市| 万年县|