RUST学习笔记1

来源:互联网 发布:mac缓存文件夹在哪里 编辑:程序博客网 时间:2024/06/05 22:54

     一直对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));
}