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

Mutable references

If we want to be able to mutable thought a reference, we need a mutable reference, since everything is immutable by default in Rust. To get a mutable reference, simply replace & with &mut. Let's write a function that will increment the x field of a Point:

fn inc_x(point: &mut Point) {
    point.x += 1;
}

Here, we see that the Point type is now &mut, which allows us to update the point in the method. To use this method, our p1 variable needs to be mut and we also need to take a mutable reference for this variable:

let mut p1 = Point { x: 1, y: 2 };
inc_x(&mut p1);
主站蜘蛛池模板: 宁蒗| 任丘市| 临城县| 鄯善县| 林西县| 承德市| 山西省| 大安市| 巴马| 道真| 巴楚县| 渭源县| 永昌县| 丽江市| 昭通市| 新野县| 合山市| 诏安县| 黄骅市| 长寿区| 桃江县| 周宁县| 江津市| 江门市| 抚松县| 宣汉县| 陇西县| 昌黎县| 南京市| 澳门| 开江县| 习水县| 瓮安县| 临夏县| 岐山县| 青海省| 东阿县| 龙山县| 临海市| 通许县| 阳西县|