Skip to content

Latest commit

 

History

History
955 lines (709 loc) · 21.7 KB

learnRustInYMintues.md

File metadata and controls

955 lines (709 loc) · 21.7 KB

...menustart

...menuend

Rust

所有权

  • Rust编译器:对于任何给定的对象都只有一个绑定与之对应。
  • 怎么把 v 传递给另外一个函数呢?
    • 借用 (&v), 临时借给其他函数
    • 类似java中的 引用
  • recap
  • 同一时刻,
    • 要么只有一个可变(&mut)借用,
    • 要么有多个不可变(&) 借用,
    • 不能同时存在可变和不可变借用。
    • 没有人希望 自己在读的时候,对象被别人改变了。
  • 当大家都在读一个东西的时候,是不能写的。当一个人在写的时候,别人是不能读的。
    • 经典的读写锁问题, Rust在编译器级别做了限制.

Data Types

Scalar Types

  • integers
    • i8,i32,u64,...
  • floating-point numbers
    • f32,f64
  • Booleanbs
    • bool : true/false
  • characters
    • 'z'
    • Rust’s char type is four bytes in size and represents a Unicode Scalar Value, which means it can represent a lot more than just ASCII.
    • Unicode Scalar Values range from U+0000 to U+D7FF and U+E000 to U+10FFFF inclusive

Compound Types

  • Tuple
  • Array

Grammar

String

  • String literals ( static str )

    let x: &str = "hello world!";
  • A heap-allocated string

    let s: String = "hello world".to_string();
  • A string slice – an immutable view into another string

    let s_slice: &str = &s;
    println!("{} {}", s, s_slice); // hello world hello world
    • This is basically an immutable pair of pointers to a string

Vectors/arrays

  • A fixed-size array

    let four_ints: [i32; 4] = [1, 2, 3, 4];
  • A dynamic array (vector)

    let mut vector: Vec<i32> = vec![1, 2, 3, 4];
    vector.push(5);
  • A slice – an immutable view into a vector or array

    let slice: &[i32] = &vector;
    // Use `{:?}` to print something debug-style
    println!("{:?} {:?}", vector, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5]

Tuples

  • A fixed-size set of values of possibly different types

    let x: (i32, &str, f64) = (1, "hello", 3.4);
  • Destructuring let

    let (a, b, c) = x;
  • Indexing

    println!("{}", x.1); // hello

Struct

struct Point {
    x: i32,
    y: i32,
}

let origin: Point = Point { x: 0, y: 0 };
  • A struct with unnamed fields, called a ‘tuple struct’

    struct Point2(i32, i32);
    let origin2 = Point2(0, 0);

Enum

  • Basic C-like enum

    enum Direction {
        Left,
        Right,
        Up,
        Down,
    }
    
    let up = Direction::Up;
  • Enum with fields

    enum OptionalI32 {
        AnI32(i32),
        Nothing,
    }
    let two: OptionalI32 = OptionalI32::AnI32(2);
    let nothing = OptionalI32::Nothing;

Generics

struct Foo<T> { bar: T }

// This is defined in the standard library as `Option`
enum Optional<T> {
    SomeVal(T),
    NoVal,
}

Methods

impl<T> Foo<T> {
    // Methods take an explicit `self` parameter
    fn get_bar(self) -> T {
        self.bar
    }
}

let a_foo = Foo { bar: 1 };
println!("{}", a_foo.get_bar()); // 1

Traits (Interface)

known as interfaces or typeclasses in other languages.

trait Frobnicate<T> {
    fn frobnicate(self) -> Option<T>;
}
  • implement trait

    impl<T> Frobnicate<T> for Foo<T> {
        fn frobnicate(self) -> Option<T> {
            Some(self.bar)
        }
    }
    let another_foo = Foo { bar: 1 };
    println!("{:?}", another_foo.frobnicate()); // Some(1)

See more details at Traits section.

Pattern matching

let foo = OptionalI32::AnI32(1);
match foo {
    OptionalI32::AnI32(n) => println!("it’s an i32: {}", n),
    OptionalI32::Nothing  => println!("it’s nothing!"),
}
Advanced pattern matching
struct FooBar { x: i32, y: OptionalI32 }
let bar = FooBar { x: 15, y: OptionalI32::AnI32(32) };

match bar {
    FooBar { x: 0, y: OptionalI32::AnI32(0) } =>
        println!("The numbers are zero!"),
    FooBar { x: n, y: OptionalI32::AnI32(m) } if n == m =>
        println!("The numbers are the same"),
    FooBar { x: n, y: OptionalI32::AnI32(m) } =>
        println!("Different numbers: {} {}", n, m),
    FooBar { x: _, y: OptionalI32::Nothing } =>
        println!("The second number is Nothing!"),
}

Control flow

  • for loops/iteration

    let array = [1, 2, 3];
    for i in array.iter() {
        println!("{}", i);
    }
  • Ranges

    for i in 0u32..10 {
        print!("{} ", i);
    }
    println!(""); // prints `0 1 2 3 4 5 6 7 8 9 `
  • if

    if n < 0 {
        print!("{} is negative", n);
    } else if n > 0 {
        print!("{} is positive", n);
    } else {
        print!("{} is zero", n);
    }
  • if as expression

    let value = if true {
        "good"
    } else {
        "bad"
    };
  • if let =

    if let Coin::Quarter(state) = coin {
        println!("State quarter from {:?}!", state);
    } else {
        count += 1;
    }
  • while loop

    while 1 == 1 {
        println!("The universe is operating normally.");
        // break statement gets out of the while loop.
        //  It avoids useless iterations.
        break
    }
  • Infinite loop

    loop {
        println!("Hello!");
        // break statement gets out of the loop
        break
    }

Memory safety & pointers

let mut mine: Box<i32> = Box::new(3);
*mine = 5; // dereference
  • Owned pointer
    • only one thing can ‘own’ this pointer at a time
    • This means that when the Box leaves its scope, it can be automatically deallocated safely.
let mut now_its_mine = mine;
*now_its_mine += 2;
  • Here, now_its_mine takes ownership of mine. In other words, mine is moved.
  • Reference
    • an immutable pointer that refers to other data
    • While a value is borrowed immutably, it cannot be mutated or moved.
    • A borrow lasts until the end of the scope it was created in.
    let mut var = 4;
    var = 3;
    let ref_var: &i32 = &var;
    
    println!("{}", var); // Unlike `mine`, `var` can still be used
    println!("{}", *ref_var);
  • Mutable reference
    • While a value is mutably borrowed, it cannot be accessed at all.
    let mut var2 = 4;
    let ref_var2: &mut i32 = &mut var2;
     *ref_var2 += 2;   
    // this would not compile because `var2` is borrowed.
    // var2 = 2; 

Modules

  • Modules to Control Scope and Privacy
  • Exposing Paths with the pub Keyword
  • Starting Relative Paths with super
    • construct relative paths that begin in the parent module by using super at the start of the path.
  • Bringing Paths into Scope with the use Keyword
  • Re-exporting Names with pub use
Module example
// src/lib.rs
// Declaring the front_of_house module
// whose body will be in src/front_of_house.rs
mod front_of_house  ;

// mod back_of_house is here
fn serve_order() {}
mod back_of_house {
    fn fix_incorrect_order() {
        cook_order();
        // The fix_incorrect_order function is in the back_of_house module,
        // so we can use `super` to go to the parent module of back_of_house,
        // which in this case is crate, the root.
        super::serve_order();
    }

    fn cook_order() {}
}

// the name available in the new scope is still private.
// use `pub use` to re-export it , so that it is available to external code as well.
use crate::front_of_house::hosting;

pub fn eat_at_restaurant() {
    // Absolute path
    // The add_to_waitlist function is defined in the same crate as eat_at_restaurant,
    // which means we can use the crate keyword to start an absolute path.
    crate::front_of_house::hosting::add_to_waitlist();
    // Relative path
    front_of_house::hosting::add_to_waitlist();
    // Bring hosting into scope with `use`
    hosting::add_to_waitlist();
}
// src/front_of_house.rs
// path: crate::front_of_house::hosting;
// front_of_house is provided by filename
pub mod hosting {
    pub fn add_to_waitlist() {}

    fn seat_at_table() {}
}

mod serving {
    fn take_order() {}

    fn serve_order() {}

    fn take_payment() {}
}

Error Handling

Unrecoverable Errors with panic!

To abort on panic in release mode, add the following lines into [profile] sections in your Cargo.toml file

[profile.release]
panic = 'abort'

Recoverable Errors with Result

enum Result<T, E> {
    Ok(T),
    Err(E),
}
Example:
use std::fs::File;
use std::io::ErrorKind;

fn main() {
    let f = File::open("hello.txt");

    let f = match f {
        Ok(file) => file,
        Err(error) => match error.kind() {
            ErrorKind::NotFound => match File::create("hello.txt") {
                Ok(fc) => fc,
                Err(e) => panic!("Problem creating the file: {:?}", e),
            },
            other_error => panic!("Problem opening the file: {:?}", other_error),
        },
    };
}

That’s a lot of match! The match expression is very useful but also very much a primitive.

The Result<T, E> type has many methods that accept a closure and are implemented using match expressions.

Using those methods will make your code more concise.
use std::fs::File;
use std::io::ErrorKind;

fn main() {
    let f = File::open("hello.txt").unwrap_or_else(|error| {
        if error.kind() == ErrorKind::NotFound {
            File::create("hello.txt").unwrap_or_else(|error| {
                panic!("Problem creating the file: {:?}", error);
            })
        } else {
            panic!("Problem opening the file: {:?}", error);
        }
    });
}

unwrap and expect

If the Result value is the Ok variant, unwrap will return the value inside the Ok.

If the Result is the Err variant, unwrap will call the panic! macro for us.

use std::fs::File;

fn main() {
    let f = File::open("hello.txt").unwrap();
}

Another method, expect, which is similar to unwrap, lets us also choose the panic! error message.

Propagating Errors

Propagating Example
use std::io;
use std::io::Read;
use std::fs::File;

fn read_username_from_file() -> Result<String, io::Error> {
    let f = File::open("hello.txt");

    let mut f = match f {
        Ok(file) => file,
        Err(e) => return Err(e),
    };

    let mut s = String::new();

    match f.read_to_string(&mut s) {
        Ok(_) => Ok(s),
        Err(e) => Err(e),
    }
}

? Operator

A Shortcut for Propagating Errors: the ? Operator
use std::io;
use std::io::Read;
use std::fs::File;

fn read_username_from_file() -> Result<String, io::Error> {
    let mut s = String::new();
    File::open("hello.txt")?.read_to_string(&mut s)?;
    Ok(s)
}

If the value of the Result is an Ok, the value inside the Ok will get returned from ? expression, and the program will continue.

If the value is an Err, the Err will be returned from the whole function as if we had used the return keyword so the error value gets propagated to the calling code.

The ? Operator Can Only Be Used in Functions That Return Result.

Traits

pub trait Summary {
    fn summarize(&self) -> String;
}

Default Implementations

pub trait Summary {
    fn summarize(&self) -> String {
        String::from("(Read more...)")
    }
}

Traits as Parameters impl Trait syntax

pub fn notify(item: impl Summary) {
    println!("Breaking news! {}", item.summarize());
}

It is actually syntax sugar for a longer form, which is called a trait bound it looks like this:

pub fn notify<T: Summary>(item: T) {
    println!("Breaking news! {}", item.summarize());
}

Specifying Multiple Trait Bounds with the + Syntax

pub fn notify(item: impl Summary + Display) {

The + syntax is also valid with trait bounds on generic types:

pub fn notify<T: Summary + Display>(item: T) {

Clearer Trait Bounds with where Clauses

We can rewrite the following code

fn some_function<T: Display + Clone, U: Clone + Debug>(t: T, u: U) -> i32 {

to :

fn some_function<T, U>(t: T, u: U) -> i32
    where T: Display + Clone,
          U: Clone + Debug
{

Returning Types that Implement Traits

you can only use impl Trait if you’re returning a single type.

fn returns_summarizable() -> impl Summary {

See Using Trait Objects That Allow for Values of Different Types in chapter 17.

Fixing the largest Function with Trait Bounds

fn largest<T: PartialOrd + Copy>(list: &[T]) -> T {
    let mut largest = list[0];

    for &item in list.iter() {
        if item > largest {
            largest = item;
        }
    }

    largest
}

> operator is defined as a default method on the standard library trait std::cmp::PartialOrd, we need to specify PartialOrd in the trait bounds for T so the largest function can work on slices of any type that we can compare.

When we made the largest function generic, it became possible for the list parameter to have types in it that don’t implement the Copy trait. Consequently, we wouldn’t be able to move the value out of list[0] and into the largest variable, resulting in this error. To call this code with only those types that implement the Copy trait, we can add Copy to the trait bounds of T!

Using Trait Bounds to Conditionally Implement Methods

For example, the type Pair<T> always implements the new function. But Pair<T> only implements the cmp_display method if its inner type T implements the PartialOrd trait that enables comparison and the Display trait that enables printing.

use std::fmt::Display;

struct Pair<T> {
    x: T,
    y: T,
}

impl<T> Pair<T> {
    fn new(x: T, y: T) -> Self {
        Self {
            x,
            y,
        }
    }
}

impl<T: Display + PartialOrd> Pair<T> {
    fn cmp_display(&self) {
        if self.x >= self.y {
            println!("The largest member is x = {}", self.x);
        } else {
            println!("The largest member is y = {}", self.y);
        }
    }
}

We can also conditionally implement a trait for any type that implements another trait.

impl<T: Display> ToString for T {
    // --snip--
}

Validating References with Lifetimes

Every reference in Rust has a lifetime, which is the scope for which that reference is valid.

Most of the time, lifetimes are implicit and inferred, just like most of the time, types are inferred.

We must annotate types when multiple types are possible. In a similar way, we must annotate lifetimes when the lifetimes of references could be related in a few different ways.

Rust requires us to annotate the relationships using generic lifetime parameters to ensure the actual references used at runtime will definitely be valid.

// error[E0106]: missing lifetime specifier
// help: this function's return type contains a borrowed value, but the
// signature does not say whether it is borrowed from `x` or `y`
fn longest(x: &str, y: &str) -> &str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}

Lifetime Annotations in Function Signatures

fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}
  • The function signature now tells Rust that
    • for some lifetime 'a, the function takes two parameters, both of which are string slices that live at least as long as lifetime 'a.
    • The function signature also tells Rust that the string slice returned from the function will live at least as long as lifetime 'a.
fn main() {
    let string1 = String::from("long string is long");

    {
        let string2 = String::from("xyz");
        let result = longest(string1.as_str(), string2.as_str());
        println!("The longest string is {}", result);
    }
}
  • In this example,
    • string1 is valid until the end of the outer scope,
    • string2 is valid until the end of the inner scope,
    • and result references something that is valid until the end of the inner scope.

Next, let’s try an another example:

// error[E0597]: `string2` does not live long enough
fn main() {
    let string1 = String::from("long string is long");
    let result;
    {
        let string2 = String::from("xyz");
        result = longest(string1.as_str(), string2.as_str());
    }
    println!("The longest string is {}", result);
}

Lifetime Annotations in Struct Definitions

struct ImportantExcerpt<'a> {
    part: &'a str,
}

Lifetime Annotations in Method Definitions

impl<'a> ImportantExcerpt<'a> {
    fn level(&self) -> i32 {
        3
    }
}

The Static Lifetime

'static, which means that this reference can live for the entire duration of the program.

All string literals have the 'static lifetime, which we can annotate as follows:

let s: &'static str = "I have a static lifetime.";