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

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 }
    }
}
主站蜘蛛池模板: 灵山县| 荔浦县| 宜章县| 南汇区| 乐昌市| 拉萨市| 鹿泉市| 肥城市| 东阿县| 东兴市| 嘉峪关市| 辉南县| 鄂托克旗| 泰来县| 贵溪市| 济源市| 东莞市| 苍溪县| 崇左市| 蕉岭县| 乳山市| 临颍县| 缙云县| 塔城市| 恩施市| 额济纳旗| 华阴市| 鱼台县| 通化市| 安龙县| 太康县| 区。| 宜兴市| 三原县| 汤原县| 富顺县| 东港市| 花莲市| 济阳县| 剑川县| 云霄县|