Beginner Rust Notes

Today is the third day of learning rust. First summarize what you learned yesterday so that you can learn something new ~

Learning Material: The Rust Programming Language, Rust Official Tutorial

Overview of learning content

  1. Getting Started: hello world base code, Hello Cargo trial cargo command.
  2. Programming a Guessing Game: Begin to understand the basic language in Rust with a small example of guessing numbers.
  3. Common Programming Concepts: Includes variables and their variability, data types, functions, comments, and control flows.
  4. Understanding Ownership: The definition of ownership is introduced first, followed by reference s and slice s.(This section is the main note)
  5. Using Structs to Structure Related Data: This chapter is structured.

Hello Cargo is not too difficult, so follow the instructions in the book step by step.Learned the commands cargo build, cargo run, cargo test, etc. and also introduced the addition of dependency libraries: adding dependencies under [dependencies] in cargo.toml (refer to the solution of the previous note if you encounter slower downloads during this process); and updating the dependency packages: each dependent version is recorded in cargo.lock to prevent a change due to versionNew resulting bug.

Chapters 2 and 3 are the basic variables and language rules of rust, which can be found in each chapter's code notes.

Chapter IV: Ownership
Ownership, as a unique and important feature of rust, makes rust have memory security, which can effectively avoid the problem of floating pointer and floating variable.When rust runs the code, ownership determines the valid range of each variable and when to use the drop command to free up space for that variable.

Ownership rules: (three rules)

  • Each value in rust has its own owner
  • There can only be one owner at a time
  • When the owner exceeds its scope, the value is drop ped

This chapter uses the more complex StringString data type as an example.Consider the following code:

let s1 = String::from("Hello");
let s2 = s1;

In this sentence, the value of s1 is assigned to s2. rust is handled as: s1 out of scope, s1 is no longer the value of valid at this time, so if s1 is called later, rust will error:

error:  use of moved value: 's1'

A chart shows the process:

Unlike here are common data types, such as i32, f64, char, and other simple data types.Because stack is used as the storage method, its calculation, push, and pop are fast.Thus, there is no move operation similar to String type, which is a simple copy

For String, if you don't want to use the move described above, you can use the clone operation:

let s1 = String::from("hello");
let s2 = s1.clone();
println!("s1 = {}, s2 = {}", s1, s2);  //s1 will not fail at this time

The main contents of reference s and slice s can be found in the code Notes

/**
    This code is about Understanding Ownership, which enables Rust to make memory safety guarantees
     without needing a garbage collector. We'll talk about reference (borrowing) and slice

     My 2nd day as a rustacean.

     2020.02.16

**/



fn main() {
    //Reference: Reference to something without knowing its ownership. This process is called Borrowing and cannot be modified (immutable)
    let s1 = String::from("hello");

    let len = calculate_length(&s1);

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

    //You can define a variable reference, but there can only be one variable reference for the same variable. To write a different variable reference, you need to wait for one of the out of scope
    let mut s = String::from("hello");
    change(&mut s);
    //Nor can immutable and mutable references point to the same variable at the same time unless there is a clear order of use, that is, scope s do not overlap


    //In rust, no field pointer appears, and rust guarantees that the variable will invalidate after reference

    ///Slices
    let mut s = String::from("Hello World");

    let word = first_word(&s);

    s.clear();  //Empty s.At this point s is empty, but word still holds a value of 5, which is equivalent to a floating variable!!

    //Solution: Use slice slices!
    let s = String::from("hello world");

    let hello = &s[0..5]; //Use two dots..To represent slices, from 0 to 5, or 0 can be omitted if you start from 0.All slices when both front and back are omitted
    let world = &s[6..11];

    //At this point, after the modification is called, the slice's new_first_word function is added:
    let mut s = String::from("hello world");
    let word = new_first_word(&s);
    s.clear();
    println!("the first word is: {}", word);  //Error starting at this time: cannot borrow `s` as mutable because it is also borrowed as immutable


}

fn calculate_length(s: &String) -> usize {
    s.len()
}  //s out of scope at this time, but drop does not occur because it does not take ownership

fn change(some_string: &mut String){
    some_string.push_str(", world");
}

fn first_word(s: &String) -> usize{
    let bytes = s.as_bytes();  //Converting a string to a matrix of bytes
    for (i, &item) in bytes.iter().enumerate(){  //iter() returns each element in the collection, and enumerate() tuples the return value of iter
        if item == b' ' {
            return i;
        }
    }
    s.len()
}

fn new_first_word(s: &String) -> &str {
    let bytes = s.as_bytes();
    for (i, &item) in bytes.iter().enumerate(){
        if item == b' ' {
            return &s[0..i];
        }
    }

    &s[..]
}

Chapter V Structural Sense and C Language are not too different, see Code Notes for details, let's not talk more about it here ~

After a day of study, my back ached and sore.

Published 3 original articles, won 1. Visits 115
Private letter follow

Keywords: Programming C

Added by vasse on Mon, 17 Feb 2020 04:18:00 +0200