RUST學習筆記1

     一直對rust比較關注,出於個人興趣,對這種編譯期檢查的,沒有GC的語言很感興趣。希望能堅持下去吧。目前已經大致看了一遍語法,感覺上和c++還是比較像的。不過對於c++新增的機制,對於rust而言是作爲基礎而存在的。比如copy, move賦值,引用和可變引用,基於引用計數的內存管理等。還有學c++的時候沒想明白的trait,現在想想實際上就是java的interface。

    還有一些新東西過去沒有接觸過,比如rust的錯誤處理。很多時候寫java的時候沒有做錯誤處理,結果出了錯誤纔想到去修復。而rust強迫你必須處理錯誤。

    這裏記錄一些感覺上比較難的地方。

    一個是這個borrow。在C++裏,調用不同的構造函數對應不同的傳值方式,有拷貝構造和MOVE構造,對應rust裏實現了copy traits的是拷貝傳值, 沒有實現的就是borrow了。rust對於一個實例,一次只允許存在一個可變的引用存在,可以考慮爲對象的讀寫鎖。而不可變引用可以有很多個。


// A function which takes a closure as an argument and calls it.
fn apply<F>(f: F) where
    // The closure takes no input and returns nothing.
    F: FnOnce() {
    // ^ TODO: Try changing this to `Fn` or `FnMut`.


    f();  //這裏爲啥不直接 fn apply(f: FnOnce), 因爲這裏的apply針對所有類型的函數指針,因此apply本質是一個泛型函數。
}


// A function which takes a closure and returns an `i32`.
fn apply_to_3<F>(f: F) -> i32 where
    // The closure takes an `i32` and returns an `i32`.
    F: Fn(i32) -> i32 {


    f(3)
}


fn main() {
    use std::mem;


    let greeting = "hello";  //greeting 這裏是 ‘static str;
    // A non-copy type.
    // `to_owned` creates owned data from borrowed one
    let mut farewell = "goodbye".to_owned();   //to_owned 創建了一個&str的引用。


    // Capture 2 variables: `greeting` by reference and
    // `farewell` by value.
    let diary = || {  //closure的traits類型由系統推導得到。其中FnOnce大於FnMut大於Fn.
        // `greeting` is by reference: requires `Fn`.
        println!("I said {}.", greeting);


        // Mutation forces `farewell` to be captured by
        // mutable reference. Now requires `FnMut`.
        farewell.push_str("!!!");
        println!("Then I screamed {}.", farewell);
        println!("Now I can sleep. zzzzz");


        // Manually calling drop forces `farewell` to
        // be captured by value. Now requires `FnOnce`.
        mem::drop(farewell);
    };


    // Call the function which applies the closure.
    apply(diary);


    // `double` satisfies `apply_to_3`'s trait bound
    let double = |x| 2 * x;


    println!("3 doubled: {}", apply_to_3(double));
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章