rust programming - general programming concepts (chapter 3.1)

Table of contents

1. Variables and changeability (modifiability)

This chapter introduces some common concepts in programming languages ​​that also exist in rust. For example: variables, primitive types, functions, annotations, control flow. These are the cornerstones of the Rust language.

Like other programming languages, Rust also includes a set of reserved keywords. These reserved keywords cannot be used when defining variable or function names. Some keywords are defined token s with special semantics, and the other part is reserved for future use.

1. Variables and changeability (modifiability)

By default, variables are immutable. This is one of the great differences between Rust and other programming languages. This feature makes rust have advantages in security and concurrent programming. However, variables can still be made modifiable by using the mut keyword.

A variable is immutable, meaning that the value of the variable cannot be changed. The following code is a rust project created by cargo new varibales.

// src/main.rs
fn main() {
    let x = 5;
    println!("The value of x is: {}", x);
    x = 6;
    println!("The value of x is: {}", x);
}

The cargo build will report compilation errors, as follows:

# cargo build
   Compiling variables v0.1.0 (/doc/jiangxiaoqing/rust/chapter3/variables)
error[E0384]: cannot assign twice to immutable variable `x`
 --> src/main.rs:5:5
  |
3 |     let x = 5;
  |         -
  |         |
  |         first assignment to `x`
  |         help: consider making this binding mutable: `mut x`
4 |     println!("The value of x is: {}", x);
5 |     x = 6;
  |     ^^^^^ cannot assign twice to immutable variable

For more information about this error, try `rustc --explain E0384`.
error: could not compile `variables` due to previous error

The second assignment operation cannot be performed on the immutable variable x.

The Rust programming language design philosophy believes that immutable and mutable variables should be distinguished, so as to reduce the occurrence of bug s caused by different codes or thread misoperations to modify variables at runtime. This kind of bug is usually difficult to trace and locate, so Rust can check this type of unsafe operation at compile time.

The Rust compiler ensures that once an immutable variable is declared, its value cannot change. (How? Record and track the immutability and modification of each variable symbol during compilation?)

By declaring the variable as a variable type of mut, the variable can be made variable, and the variable variable is of great significance. Specify the read-write side of the variable that mut actually prompts, and other codes may change the value of the variable at any time.

fn main() {
    // let x = 5;
    let mut x = 5;
    println!("The value of x is: {}", x);
    x = 6;
    println!("The value of x is: {}", x);
}

In addition to the problem of "easy to introduce bug s", the design and use of immutable variables also consider other compromises. In the case of large data structures, changing the instance in place may be faster than copying and returning a newly allocated instance, and immutable types are not suitable; for smaller data structures, create new variable instances directly, in a functional programming style Much easier to accept, the clarity is worth the price of a little performance.

  • constant defined by const

There is a difference between constants and immutable variables:

1) Constants cannot be modified with mut and will never change

2) Use const instead of let to define constants

3) The constant type must be specified at the time of definition and cannot be omitted

4) When a constant is defined, it is assigned a value and must be a constant expression

According to rust conventions, constant names are capitalized, as follows:

const THREE_HOURS_IN_SECONDS:u32 =  60 * 60 * 3;
println!("The const value is: {}", THREE_HOURS_IN_SECONDS);
  • Variable scoping and variable overriding

Like the C++ language, rust variables also exist in scope variables in {}. In addition, variables with the same name in the same scope will override the former.

    let y = 5;

    let y = y + 1;

    {
        let y = y * 2;
        println!("The value of y in the inner scope is: {}", y);
    }

    println!("The value of y is: {}", y);
    
    let spaces = "   ";
    // change variable type
    let spaces = spaces.len();

Variable coverage is different from mut variable variables. Variable coverage defines new variables and can change the type of new variables with the same name.

The overall code is as follows:

fn main() {
    // let x = 5;
    let mut x = 5;
    println!("The value of x is: {}", x);
    x = 6;
    println!("The value of x is: {}", x);
    const THREE_HOURS_IN_SECONDS:u32 =  60 * 60 * 3;
    println!("The const value is: {}", THREE_HOURS_IN_SECONDS);

    let y = 5;
    let y = y + 1;
    {
        let y = y * 2;
        println!("The value of y in the inner scope is: {}", y);
    }
    println!("The value of y is: {}", y);

    let spaces = "   ";
    // change variable type
    let spaces = spaces.len();
    println!("The value of spaces is: {}", spaces);
}

About the author:

Uncle Ben, Zhejiang University, majoring in computer science and technology, graduated with a postgraduate degree. He has worked in Huawei, Alibaba and ByteDance successively, engaged in technology research and development, and is a senior research and development expert. The main research areas include virtualization, distributed technology and storage system (including CPU and computing, GPU heterogeneous computing, distributed block storage, distributed database, etc.), high-performance RDMA network protocol and data center application, Linux kernel, etc. .

Hobbies: Mathematics, science and technology application

Pay attention to Uncle Ben and look forward to bringing you more knowledge and industrial applications in the field of scientific research.

The content insists on originality, and insists on dry goods with materials. Persist in long-term creation, pay attention to Uncle Ben and not get lost

Tags: Back-end Rust programming language

Posted by digibrain on Mon, 21 Nov 2022 09:32:30 +1030