Rust Basics

With the fire in the Rust language, there's a Rust wind in the front-end circle - everything that can be implemented with Rust is trying to rewrite with Rust, like the JavaScript/TypeScript compiler swc for the recently hot counterpart Babel, which believes many Everyone has tried it.

For our front-end, such a popular language, of course, cannot be let go, and we must keep up with the trend of the times.

1. What is Rust

Rust is a general-purpose, compiled programming language developed by Mozilla. The design principle is "safe, concurrent, practical", and supports functional, concurrent, procedural and object-oriented programming styles.      -- Wikipedia

2. Language Features

1. Language features

Rust is syntactically closer to a metalanguage family of languages ​​like Haskell. Basically every part of a function body is an expression, even a control flow operator.

2. Memory security

Null pointers, dangling pointers and data races are not allowed in safe code. Values ​​can only be initialized with a set of fixed forms, requiring all inputs to have been initialized.

3. Memory management

No automatic garbage collection system is used, memory and resources are managed through RAII, and reference counting is optional.

4. Ownership

All values ​​have a unique owner, and the valid range of values ​​is the same as the valid range of the owner.

5. Type polymorphism

Rust's type system supports a typeclass-like mechanism called "traits", inspired by Haskell. This is a facility for certain homogeneity methods, implemented by adding constraints to type variable declarations. Other features from Haskell, such as higher type polymorphism are not yet supported, see: Rust type polymorphism.

3. Data Type

Rust has the following types in total: integers, floats, booleans, characters, and composite types.

1. Integer type (i, u)

The types of the Rust language are similar to those of the C family of languages. Integer data is divided into signed and unsigned types according to whether it is signed or not.

number of digits

signed

unsigned

8-bit

i8

u8

16-bit

i16

u16

32-bit

i32

u32

64-bit

i64

u64

128-bit

i128

u128

...

...

...

The default type of integer is i32. (i, u represent int, uint)

let a = 10; // i32
let b: i64 = 20; // i64
copy

2. Floating point (f)

Rust supports 32-bit floating point numbers (f32) and 64-bit floating point numbers (f64) like other languages. By default, the floating-point data type is a 64-bit floating-point number, because modern computer processors perform almost the same speed calculations on both floating-point numbers, but 64-bit floating-point numbers have more precision.

let a = 10.0; // f64
let b: f32 = 20.0; // f32
copy

3. Boolean (bool)

Like js, the value is true or false.

4. Character type (char)

The character type is 4 bytes in size and represents a Unicode scalar value.

Note: Since there are two types of Chinese text encoding (GBK and UTF-8), the use of Chinese strings in programming can lead to garbled code. This is because the source program and command line text encoding are inconsistent. Therefore, UTF-8 encoding must be used for both strings and characters in Rust, otherwise the compiler will error.

let c = 'a';
copy

5. Composite type

Arrays must be familiar to everyone, which is a group of data of the same type enclosed by square brackets, but what we need to know is that the arrays in Rust are of fixed length, which means that we can't determine an array before proceeding Add or delete actions.

let arr = [1, 2, 3, 4, 5];
let arr2: [i32; 5] = [1, 2, 3, 4, 5]; // i32 array of length 5
let arr3 = [1; 3]; // equal to [1, 1, 1]

let one = arr[0]; // 1
copy

Rust also has a tuple type, which can contain different data types.

let tup: (i32, f32, char) = (10, 20.0, 'a');
copy

4. Structure

The structure is somewhat similar to the interface in our ts

struct Person {
    name: String,
    sex: String,
    age: u32
}

let p1 = Person {
    name: String::from("abc"),
    sex: String::from("male"),
    age:18
}

// Structure update syntax, similar to js destructuring
let p2 = Person{
    name: String::from("123"),
    ..p1
}
copy

5. Enumeration class

enum Phone {
    IPhone, Huawei
}
copy

Enum classes are often used with the match syntax to implement branching structures, similar to switches in other syntaxes, but switches are not supported in Rust.

fn main() {
enum Phone {
    IPhone(u32),
    Huawei {url: String},
}
let phone = Phone::IPhone(123);
let phone2 = Phone::Huawei {url: String::from("hahaha")};

match phone {
    Phone::IPhone(i) => {
        println!("{}", i);
    },
    Phone::Huawei { url } => {
        println!("{}", url);
    }
}

match phone2 {
    Phone::IPhone(i) => {
        println!("{}", i);
    },
    Phone::Huawei { url } => {
        println!("{}", url);
    }
}
}

// 123
// hahaha
copy

In addition to branching enumeration classes, match can also branching integer, floating point, character and string slice reference (&str) types of data.

Exceptions must be handled when branching non-enumeration classes, indicated by the underscore _.

6. Ownership

Ownership is a syntactic mechanism of the Rust language designed for efficient use of memory

The concept of ownership was born to allow Rust to more efficiently analyze the usefulness of memory resources at the compile stage for memory management.

// move
// The first variable cannot be accessed in this case
let s1 = String::from("hello");
let s2 = s1; 
println!("{}, world!", s1); // mistake!  s1 has expired


// clone
// This can
let s1 = String::from("hello");
let s2 = s1.clone();
println!("s1 = {}, s2 = {}", s1, s2);
copy

Keep up with the forefront of technology and dig deep into professional fields

Scan the code to follow us!

Posted by IronWarrior on Fri, 22 Jul 2022 23:30:25 +0530