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

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);
主站蜘蛛池模板: 濮阳市| 沽源县| 南安市| 昌宁县| 高平市| 蒙自县| 乃东县| 郸城县| 任丘市| 永善县| 凉城县| 凤冈县| 临高县| 九台市| 苍梧县| 海伦市| 页游| 巴南区| 通化市| 晴隆县| 高要市| 莱州市| 双辽市| 如东县| 筠连县| 凤城市| 登封市| 阳信县| 道真| 临海市| 澄迈县| 百色市| 镇原县| 芒康县| 岗巴县| 德钦县| 伊宁市| 垦利县| 大田县| 太湖县| 新巴尔虎右旗|