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

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);
主站蜘蛛池模板: 阜平县| 新巴尔虎右旗| 三江| 酉阳| 凤冈县| 调兵山市| 唐山市| 花垣县| 布拖县| 平塘县| 白城市| 兴和县| 太原市| 鹿泉市| 黔西| 遂平县| 望江县| 逊克县| 靖远县| 柳河县| 保德县| 怀宁县| 乌鲁木齐市| 孝义市| 凌云县| 观塘区| 揭东县| 灵山县| 万载县| 尉犁县| 岱山县| 静宁县| 峨山| 綦江县| 眉山市| 鸡东县| 庆城县| 图木舒克市| 宝兴县| 揭阳市| 宝鸡市|