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

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 }
    }
}
主站蜘蛛池模板: 隆尧县| 资兴市| 乐亭县| 庆安县| 木兰县| 宾川县| 芦溪县| 林芝县| 安泽县| 东兴市| 舒兰市| 建瓯市| 湘西| 龙口市| 平罗县| 宿迁市| 黑水县| 马边| 葵青区| 新乡市| 九龙坡区| 兰西县| 昌吉市| 霍城县| 寻甸| 双柏县| 嘉善县| 林州市| 卓资县| 深州市| 汽车| 甘洛县| 东至县| 安泽县| 什邡市| 汤原县| 玛纳斯县| 金塔县| 剑河县| 南平市| 工布江达县|