Rust 與 C 對比之篇一

Rust 與 C 語言有很多的不同,在變量聲明方面,Rust 更 “安全” 一些。C 聲明變量可以不進行初始化,編譯器也不進行是否有初試化的檢查,但 Rust 會進行嚴格的檢查,如果聲明變量未初始化則編譯報錯。這可以防止程序員因未進行變量初始化造成的 BUG。

在 C 語言中可以聲明一個變量,不進行初試化就可以使用,編譯器不會報錯,但可能會導致運行時的異常行爲。比如:

#include<stdio.h>
#include <stdbool.h>

bool is_post(int data) {
    return data > 0;
}

int main() {

    bool var;
    /* 假設中間有很多代碼 */
    int data = 10;
    if (data != 10) 
    {
        var = is_post(data);
    }
    /* 假設中間有很多代碼*/

    // 有可能出現變量沒有聲明就使用的情況
    if (var)
        printf("maybe error here.\n");
    else 
        printf("maybe not you want.\n");

    return 0;
}

聲明的時候沒有初始化,必須確保後面使用前被賦值,否則的話可能會造成運行結果的錯誤或者其他莫名奇妙的問題。當工程很大的時候排查 BUG 會比較難排查。

對 Rust,變量聲明的時候必須初始化,否則的話編譯器這關就過不去,所以就不會踩這個坑了。

fn main() {
    let a;
    if a > 1 {
        a = 10;
    }
}

編譯cargo build

error[E0381]: use of possibly-uninitialized variable: `a`
 --> src/main.rs:4:8
  ||     if a > 1 {
  |        ^ use of possibly-uninitialized `a`

For more information about this error, try `rustc --explain E0381`.
error: could not compile `playground` due to previous er
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/6pdrtpnL561COUVn4ZiFVw