Rust指針和引用

指針和引用

對於指針,一個區別是需要在析構之時會解除引用 ,因爲它們使用不同的概念,如C語言。

  • 解除引用使用  *
  • 構析使用 &ref, 和 ref mut

fn main() {
// Assign a reference of type `i32`. The `&` signifies there
// is a reference being assigned.
let reference = &4;

match reference {
    // If \`reference\`s is pattern matched against \`&val\`, it results
    // in a comparison like:
    // \`&i32\`
    // \`&val\`
    // ^ We see that if the matching \`&\`s are dropped, then the \`i32\`
    // should be assigned to \`val\`.
    &val => println!("Got a value via destructuring: {:?}", val),
}

// To avoid the \`&\`, you dereference before matching.
match \*reference {
    val => println!("Got a value via dereferencing: {:?}", val),
}

// What if you don't start with a reference? \`reference\` was a \`&\`
// because the right side was already a reference. This is not
// a reference because the right side is not one.
let \_not\_a\_reference = 3;

// Rust provides \`ref\` for exacty this purpose. It modifies the
// assignment so that a reference is created for the element; this
// reference is assigned.
let ref \_is\_a\_reference = 3;

// Accordingly, by defining 2 values without references, references
// can be retrieved via \`ref\` and \`ref mut\`.
let value = 5;
let mut mut\_value = 6;

// Use \`ref\` keyword to create a reference.
match value {
    ref r => println!("Got a reference to a value: {:?}", r),
}

// Use \`ref mut\` similarly.
match mut\_value {
    ref mut m => {
        // Got a reference. Gotta dereference it before we can
        // add anything to it.
        \*m += 10;
        println!("We added 10. \`mut\_value\`: {:?}", m);
    },
}

}

0 條評論,你可以發表評論,我們會進行改進
Comment author placeholder