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

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);
主站蜘蛛池模板: 信宜市| 梁平县| 太保市| 新巴尔虎右旗| 兴安县| 永顺县| 全椒县| 湾仔区| 噶尔县| 灌阳县| 阿克| 汉川市| 方正县| 贡觉县| 桦南县| 巴青县| 南投市| 辛集市| 兰考县| 吉安市| 皋兰县| 安阳市| 色达县| 区。| 金门县| 鄱阳县| 安陆市| 凤庆县| 肇州县| 增城市| 荣昌县| 象山县| 彭泽县| 宁国市| 临沂市| 南靖县| 彰武县| 乌兰浩特市| 炎陵县| 潜江市| 云和县|