This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!

Rust Installation (Mac)

Curl, proto '= HTTPS' - tlsv1.2 - sSf https://sh.rustup.rs | shCopy the code

Test the installation

Freight-v cargo 1.53.0 (4369396CE 2021-04-27)Copy the code

Create a project

cargo new rust-miao
Copy the code

Create directories as follows:

| -- Cargo. Toml | -- target # compiler directory, ignore | -- Cargo. Lock. | - gitignore | -. Git # git directory, ignore | - SRC | | -- main. RsCopy the code

Run to see

Cargo run the Compiling rust - miao v0.1.0 (/ Users/woojufon/Desktop/rust - miao) Finished dev [unoptimized + debuginfo] Target (s) in 0.81s Running 'target/debug/rust-miao' Hello, world!Copy the code

Change the main. Rs

fn main() {
    println!("Hello, miao!");
}
Copy the code

To perform

Cargo run Finished dev [unoptimized + debugInfo] target(s) in 0.00s Running 'target/debug/rust-miao' Hello, miao!Copy the code

It is recommended to use VSCode and install the Rust and Friends plug-in. The prompt is friendly

start

Placeholder {}

fn main() { let i = "huamiao"; println! ("I'm {}", i); }Copy the code

variable

Rust is a strongly typed language, but it has the ability to automatically determine the type of variables, similar to ts, but does not like to write types.

let a = 123;
// The following three lines of code are incorrect
a = "abc";
a = 4.56;
a = 456;
Copy the code

The initialization variable is automatically given a type, line 1, line 2 is wrong, and line 3 is a variable called rust

let mut a = 123;
a = 456;
Copy the code

Mutable = mut, variable

Don’t ask me why, asked the old lady Lord committed suicide, don’t believe you try

But it can be redefined:

fn main() {
    let i = "huamiao";
    println!("I'm {}", i);
    let i = "miaomiao";
    println!("I'm {}", i);
}
Copy the code
Cargo run the Compiling rust - miao v0.1.0 (/ Users/woojufon/Desktop/rust - miao) Finished dev [unoptimized + debuginfo] Target (s) in 0.23s Running 'target/debug/rust-miao' I'm huamiao I'm miaomiaoCopy the code

A string must use double quotes. A single quote can only define a single character. At the end

type

The integer
A length of A signed unsigned
8-bit i8 u8
16-bit i16 u16
32-bit i32 u32
64-bit i64 u64
128-bit i128 u128
arch isize usize

Expression of an integer

Into the system case
The decimal system 98 _222
hexadecimal 0xff
octal 0o77
binary 0b1111_0000
Byte (u8 only) b’A’
Floating point Numbers

Type declarations are much like TS not

fn main() {
    let x = 2.0; // f64
    let y: f32 = 3.0; // f32
}
Copy the code
Mathematical operations
fn main() {
    let sum = 5 + 10; / / add
    let difference = 95.5 - 4.3; / /
    let product = 4 * 30; / / by
    let quotient = 56.7 / 32.2; / / in addition to
    let remainder = 43 % 5; / / for more
}
Copy the code

Rust does not support ++ and —

Boolean, true/false
character

The character type is denoted by char and is 4 bytes long. Both strings and characters in Rust must use UTF-8 encoding.

The compound type

A set of data contained in a pair of () that can contain different kinds of data:

let tup: (i32.f64.u8) = (500.6.4.1);
Tup.0 = 500
Tup. 1 = 6.4
Tup. 2 = 1
let (x, y, z) = tup;
Y is equal to 6.4
Copy the code

Arrays use a pair of [] containing data of the same type.

let a = [1.2.3.4.5];
// a is an array of integers of length 5

let b = ["January"."February"."March"];
// b is a string array of length 3

let c: [i32; 5] = [1.2.3.4.5];
// c is an i32 array of length 5

let d = [3; 5];
Let d = [3, 3, 3, 3, 3];

let first = a[0];
let second = a[1];
// Array access

a[0] = 123; // Error: array a is immutable
let mut a = [1.2.3];
a[0] = 4; / / right
Copy the code

annotation

// This is the first type of annotation

/* This is the second type of comment */

/* * Multiline comments * multiline comments */
Copy the code

Documentation comments

Vscode refers to a method and puts it above

/ / /   Adds   one   to   the   number   given.
///
/ / / #     Examples
///
/ / /   ` ` `
/// let x = add(1, 2);
///
/ / /   ` ` `
Copy the code

function

fn < function name > (< parameter >) < Function body >Copy the code

The naming style of function names is to split lowercase letters with an underscore

fn main() {
    println!("Hello, world!");
    another_function();
}

fn another_function() {
    println!("Hello, miao!");
}
Copy the code

Another_function is also normal, rust no care

parameter

A function that defines parameters must declare their names and types

fn main() {
    another_function(5.6);
}

fn another_function(x: i32, y: i32) {
    println!("Value of x is: {}", x);
    println!("The value of y is {}", y);
}
Copy the code

block

fn main() {
    let x = 5;

    let y = {
        let x = 3;
        x + 1
    };

    println!("Value of x is: {}", x);
    println!("The value of y is {}", y);
}
Copy the code

Nested function

fn main() {
    fn five() - >i32 {
        5
    }
    println!("Five () has a value of: {}", five());
}
Copy the code

-> i32 Specifies the return value type

Function body expressions (nested functions) are not equivalent to the function body and cannot use the return keyword

Rust does not support automatic return value type determination. The return value can be specified only when the return type of the function is explicitly declared. No return value expression, such as a+b, is allowed after return

Conditional statements

Conditions do not need (), but can also have, single statements also need {}

fn main() {
    let a = 12;
    let b;
    if a > 0 {
        b = 1;
    }  
    else if a < 0 {
        b = -1;
    }  
    else {
        b = 0;
    }
    println!("b is {}", b);
}
Copy the code

Unlike JS, which automatically converts types:

fn main() {
    let number = 3;
    if number {   // Error, expected 'bool', found integerrustc(E0308)
        println!("Yes"); }}Copy the code

Three yuan

fn main() {
    let a = 3;
    let number = if a > 0 { 1 } else{-1 };
    println!("Number for {}", number);
}
Copy the code

Looping statements

fn main() {
    let mut number = 1;
    whilenumber ! =4 {
        println!("{}", number);
        number += 1;
    }
    println!("EXIT");
}
Copy the code

for

fn main() {
    let a = [10.20.30.40.50];
    for i in a.iter() {
        println!("Value: {}", i); }}Copy the code

for in

fn main() {
let a = [10.20.30.40.50];
    for i in 0.5 {
        println!("a[{}] = {}", i, a[i]); }}Copy the code

Loop infinite loop

fn main() {
    let s = ['R'.'U'.'N'.'O'.'O'.'B'];
    let mut i = 0;
    loop {
        let ch = s[i];
        if ch == 'O' {
            break;
        }
        println!("\ '{} \'", ch);
        i += 1; }}Copy the code

Break interrupts the loop and can return a value

fn main() {
    let s = ['R'.'U'.'N'.'O'.'O'.'B'];
    let mut i = 0;
    let location = loop {
        let ch = s[i];
        if ch == 'O' {
            break i;
        }
        i += 1;
    };
    println!("\'O\' has index {}", location);
}
Copy the code

Common errors/exceptions

If you encounter this, you can run cargo run again

Cargo run the Compiling rust - miao v0.1.0 (/ Users/woojufon/Desktop/rust - miao) Finished dev [unoptimized + debuginfo] Target (s) in 0.44s Running 'target/debug/rust-miao' ZSH: killed cargo runCopy the code

Ownership, you can ignore this concept

  • Free memory: The Rust compiler automatically adds a call to free resources at the end of a variable range
{
    // The variable s is invalid until declared
    let s = "miao";
    // Here is the available range of the variable s
}
// The scope of the variable has ended, the variable s is invalid, free memory
Copy the code
  • mobile
let s1 = String::from("hello");
let s2 = s1; 
println!("{}, world!", s1); / / error! S1 has failed.
Copy the code
  • cloning
fn main() {
    let s1 = String::from("hello");
    let s2 = s1.clone();
    println!("s1 = {}, s2 = {}", s1, s2);
}
Copy the code
  • If you pass a variable as an argument to a function, it has the same effect as moving it.
fn main() {
    let s = String::from("hello");
    // S is declared valid

    takes_ownership(s);
    // The value of s is passed as an argument to the function
    // So we can assume that s has been moved and is invalid from here

    let x = 5;
    // x is declared valid

    makes_copy(x);
    // The value of x is passed as an argument to the function
    // But x is the basic type, so it still works
    // You can still use x but you can't use s

} // The function ends with x invalid, then s. But s has been moved, so it does not have to be released


fn takes_ownership(some_string: String) {
    // A String parameter some_string is passed, valid
    println!("{}", some_string);
} // The function ends, where the argument some_string is released

fn makes_copy(some_integer: i32) {
    // An i32 parameter some_INTEGER is passed, valid
    println!("{}", some_integer);
} // The function is finished. The parameter some_INTEGER is a basic type and does not need to be freed
Copy the code
  • Function return value
fn main() {
    let s1 = gives_ownership();
    // gives_ownership moves its return value to s1

    let s2 = String::from("hello");
    // s2 is declared valid

    let s3 = takes_and_gives_back(s2);
    // s2 is moved as a parameter and S3 takes ownership of the return value
} // s3 invalid is released, S2 is moved, S1 invalid is released.

fn gives_ownership() - >String {
    let some_string = String::from("hello");
    // some_string is declared valid

    return some_string;
    // Some_string is moved out of the function as the return value
}

fn takes_and_gives_back(a_string: String) - >String { 
    // A_string is declared valid

    a_string  // A_string is removed from the function as the return value
}
Copy the code

Variable ownership that is treated as a function return value is moved out of the function and returned to the place where the function was called, rather than being nullified directly.

  • Reference, lease

Variable reference

fn main() {
    let s1 = String::from("hello");
    let s2 = &s1;
    println!("s1 is {}, s2 is {}", s1, s2);
}
// s1 is hello, s2 is hello
Copy the code

Function reference

fn main() {
    let s1 = String::from("hello");

    let len = calculate_length(&s1);

    println!("The length of '{}' is {}.", s1, len);
}

fn calculate_length(s: &String) - >usize {
    s.len()
}
// The length of 'hello' is 5.
Copy the code

Wrong chestnuts

fn main() {
    let s1 = String::from("hello");
    let s2 = &s1;
    let s3 = s1;
    println!("{}", s2);
}
Copy the code

S1 leased by S2 has moved ownership to S3, so S2 will no longer be able to lease ownership of S1

Need to re-lease

fn main() {
    let s1 = String::from("hello");
    let mut s2 = &s1;
    let s3 = s2;
    s2 = &s3; // Re-lease ownership from S3
    println!("{}", s2);
}
Copy the code

Lease Forbid modification

fn main() {
    let s1 = String::from("run");
    let s2 = &s1;
    println!("{}", s2);
    s2.push_str("oob"); // Error, not allowed to modify the rental value
    println!("{}", s2);
}
Copy the code

To “delegate”, as in:

fn main() {
    let mut s1 = String::from("run");
    // s1 is variable

    let s2 = &mut s1;
    // s2 is a mutable reference

    s2.push_str("oob");
    println!("{}", s2);
}
Copy the code

Mutable references do not allow multiple references, but immutable references do

let mut s = String::from("hello");

let r1 = &mut s;
let r2 = &mut s;

println!("{}, {}", r1, r2);
Copy the code

This program is incorrect because the multivariable references s.

slice

fn main() {
    let s = String::from("broadcast");

    let part1 = &s[0.5];
    let part2 = &s[5.9];

    println!("{} = {} + {}", s, part1, part2);
}
// broadcast=broad+cast
Copy the code

In addition to strings, other linear data structures also support slicing, such as arrays:

fn main() {
    let arr = [1.3.5.7.9];
    let part = &arr[0.3];
    for i in part.iter() {
        println!("{}", i); }}Copy the code

conclusion

To this, the Rust of the minimum necessary knowledge, compared with other languages or have bigger difference, some say, object-oriented didn’t speak, date didn’t speak, that I listed in the references, knowledge is necessary for you to run up, the things I can write basic, according to need access to more knowledge into our code, “Plug-ins” or non-essential knowledge are not included.

reference

  • Rust structure
  • Rust enumeration class
  • Rust Organization Management
  • Rust error handling
  • Rust generics and features
  • Rust Life Cycle
  • Rust files with IO
  • Rust collections and strings
  • Rust Object-oriented
  • Rust concurrent programming

Cargo supplement

  • Cargo Clippy: Like ESLint, the Lint tool checks where code can be optimized
  • Cargo FMT: Similar to GO FMT, code format
  • Cargo Tree: Displays the versions and dependencies of third-party libraries
  • Cargo bench: Run the benchmark test
  • Cargo Udeps (Third party): Check for unused dependencies in the project

Cargo build/run –release uses release compilation to improve performance by more than 10 times than the default debug compilation, but release is slower to compile and does not display the specific line number of panic backtrace