Why can immutable variables be passed as arguments to functions that require mutable arguments?

前端 未结 1 1776
轮回少年
轮回少年 2020-12-11 20:47

Example code:

fn main() {
    let a = [1, 2, 3, 4, 5];
    reset(a);
}

fn reset(mut b: [u32; 5]) {
    b[0] = 5;
}

The variable a

1条回答
  •  感情败类
    2020-12-11 21:16

    When you pass by value, you are transferring ownership of the value. No copies of the variable are required — first main owns it, then reset owns it, then it's gone1.

    In Rust, when you have ownership of a variable, you can control the mutability of it. For example, you can do this:

    let a = [1, 2, 3, 4, 5];
    let mut b = a;
    

    You could also do the same thing inside of reset, although I would not do this, preferring to use the mut in the function signature:

    fn reset(b: [u32; 5]) {
        let mut c = b;
        c[0] = 5;
    }
    

    See also:

    • What's the idiomatic way to pass by mutable value?
    • What's the difference between placing "mut" before a variable name and after the ":"?

    1 — In this specific case, your type is an [i32; 5], which implements the Copy trait. If you attempted to use a after giving ownership to reset, then an implicit copy would be made. The value of a would appear unchanged.

    0 讨论(0)
提交回复
热议问题