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

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 }
    }
}
主站蜘蛛池模板: 黄龙县| 山东省| 濮阳县| 汉沽区| 阿克苏市| 临城县| 屏山县| 汪清县| 临澧县| 扎鲁特旗| 循化| 蕉岭县| 长子县| 平潭县| 佛坪县| 花莲县| 绍兴市| 武定县| 子洲县| 渝中区| 延吉市| 耒阳市| 宾川县| 灵石县| 石城县| 龙陵县| 科技| 五大连池市| 比如县| 门源| 德格县| 沐川县| 铜梁县| 于田县| 嘉善县| 东乌珠穆沁旗| 沈阳市| 嘉黎县| 邵武市| 桐梓县| 扶沟县|