鍍金池/ 教程/ Java/ Rust指針和引用
Rust解構(gòu)枚舉
Rust類型轉(zhuǎn)換 - 別名
Rust枚舉
Rust閉包
Rust捕捉
Rust while let
Rust調(diào)試
Rust教程
Rust數(shù)組和切片
Rust自定義類型
Rust綁定
Rust for和范圍
Rust類型轉(zhuǎn)換
Rust作為輸入?yún)?shù)
Rust Hello World
Rust格式化
Rust類型轉(zhuǎn)換 - 字面量
Rust變量綁定-聲明
Rust常量
Rust循環(huán)
Rust Guards
Rust作為輸出參數(shù)
Rust結(jié)構(gòu)
Rust指針和引用
Rust解構(gòu)結(jié)構(gòu)
Rust方法
Rust下載和安裝
Rust函數(shù)
Rust匹配/match
Rust類型轉(zhuǎn)換-推導(dǎo)
Rust while循環(huán)
Rust嵌套和標(biāo)簽
Rust匹配析構(gòu)元組
Rust顯示
Rust變量綁定-范圍和陰影
Rust表達(dá)式
Rust if/else語(yǔ)句
Rust變量綁定-可變性
Rust文檔
Rust匿名類型
Rust變量綁定
Rust注釋
Rust原語(yǔ)
Rust可視性
測(cè)試用例:列表
Rust格式化打印
Rust元組
Rust if let
Rust輸入函數(shù)
Rust常量和運(yùn)算符

Rust指針和引用

指針和引用

對(duì)于指針,一個(gè)區(qū)別是需要在析構(gòu)之時(shí)會(huì)解除引用 ,因?yàn)樗鼈兪褂貌煌母拍?,如C語(yǔ)言。

  • 解除引用使用  *
  • 構(gòu)析使用 &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);
        },
    }
}