Rust ability development (1): distinctive initialization

image

 

Preface

I have written three articles about the Rust language before (every proficient in Rust and its inner strengths). I think everyone also realizes the capabilities, uses, and prospects of the language. So since this article, the author began to focus on Write a bottom-up text series on rust programming ability.

I am very grateful to the relevant teachers and friends for their support, which gave me motivation to write this content. At the same time, I also look forward to the positive interaction of readers and friends in the future to optimize the content in this area. Then, a teaching exchange The long journey started from this.

From here, let's learn Rust from scratch.

 

This article will introduce

  • Rust installation and compilation

  • Rust basic data types

  • Variable declaration and immutable binding

Rust installation and compilation

installation

As far as the installation method is concerned, rustup is recommended , whether it is a new installation, upgrade or downgrade is very convenient. For Windows system, you can download the following exe file:

(https://www.rust-lang.org/tools/install)

image

If it is a linux system, you can type the following commands in the terminal

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

Follow the prompts for the remaining steps.

image

Development environment

Most of the code in this article is done using the vscode editor in Windows 10 environment .

image

Compile

In rust, there are usually two compilation methods

  • First, for a single script, use rustc filename.rs

  • Second, from the perspective of project management, use cargo run (more on that later)

     

In this paper, for ease of presentation, in vscode , add a rust-analyer and run code plug-in, by clicking the mouse compile and see the results, it should be quite in line with entry-level habits.

image

 

Of course, many small code files can be run in the playground

https://play.rust-lang.org/

image

The first code

In order to avoid clichés, we will not write Hello World!, let's look at the following code (greet.rs). In Rust, all code starts with  fn main(){} .

//greet.rsuse std::env;fn main() {
   
      let name = env::args().skip(1).next();   match name {
   
           Some(n) => println!("Hi there ! {}", n),        None => panic!("Didn't receive any name ?"),    }}

Explain the code

  • Line 2: Import the module (module)env from the standard library std crate (in Rust, library-library, called crate)

  • Line 4: Call the args() function in env to return an iterator-like parameter sequence,

    • Since the first parameter of the sequence contains path information, there is no need to display it here, just use skip (1) to skip this parameter,

    • Since the iterator is lazy and will not be pre-calculated, it needs to be specified with next().

      • next() returns an enum type (enum type) called Option option

      • This amount will correspond to the subsequent Some(value) value or None value.

  • Line 5: match is a very good expression in rust, similar to switch-case in C, used to determine whether name exists in the following statement,

  • Line 6: When Some(n), that is, when there are some values, pass the value to n, call println!, display the so-called greet result,

    • println!, there is an exclamation mark, it can be seen that it is a macro (macro), not a function

  • Line 7: Indicates that if the returned enumeration type is none, call panic! to report an error.

Code result

image

 

Talk about the println! macro

 

It can be seen from the above code that this macro receives a string and displays it.

Here are some formatting issues, need to talk about: If the data type is the basic data types (primitives), use braces "{}" ; if it is other data types using "{:?}" .

The former involves the Display feature (trait) , and the latter involves the Debug feature (this means that sometimes the #[derive(Debug)] attribute is needed, when the method is sometimes not available for certain types).

Here is a spoiler. The details involved in this area will be introduced in the follow-up source language programming (Metaprogramming with Macros).

 

Primitive types

 

Here are the built-in basic data types of rust, you can compare it with other languages, it is not difficult to understand.

  • Bool

  • String, char

  • Integer, currently supports up to 128bits, specifically:

image

  • isize: 32-bit or 64-bit signed integer pointer

  • usize: 32-bit or 64-bit unsigned integer pointer

  • f32: 32-bit floating point

  • f64: 64-bit floating point

  • [T; N], fixed-length array, T is data type, N is length or size (size)

  • str: string, usually quoted by &str

  • (T, U,..): finite sequence, T and U can be different types

  • fn(i32) -> i32: is a function, where the input type of the function is i32, and the return value type is i32; it can be seen that the type of the function has a clear and explicit definition

 

Variable declaration and immutable binding

(Declaring variables and immutability)

 

In Rust, use the let keyword to declare variables. In nowadays some mainstream imperative languages (imperative language), as C or Python, you initialize a variable does not affect their re-assignment in the next step.

However, Rust has parted ways with the mainstream here, which means that if you have initialized a variable, you can no longer assign that variable to another value.

But if you still need to assign a variable to a new value, you need to use the mut keyword . Here is a feature of Rust, which is to make your thinking as clear as possible when programming.

We look at the following code, where target is immutable binding and greeting is variable binding. In line 7, target is re-assigned to mate.

//variables.rs fn main() {
   
       let target = "world"; //no mut    let mut greeting = "Hello";    println!("{}, {}", greeting, target);    greeting = "How are you doing";    target = "mate";    println!("{}, {}", greeting, target);}

From the results below, the compilation was not successful, because the immutable bind variable cannot be assigned twice .

image

 

Therefore, add mut to the variable target in the second line, as shown below.

fn main() {
   
       let mut target = "world"; //add mut    let mut greeting = "Hello";    println!("{}, {}", greeting, target);    greeting = "How are you doing";    target = "mate";    println!("{}, {}", greeting, target);}
The compilation is successful, and the result shows that the above two variable bindings have obtained their respective secondary assignments.

image

 

Conclusion

 

I hope readers and friends will pay attention here, immutable binding and variable binding have an important position in Rust, which are related to issues such as safety and efficiency , and the following chapters will focus on them.

This article started from scratch, introduced some basic elements of Rust and appropriate code, and did not implement a fast-track tutorial method, because although the language is not as difficult to learn as C and not as easy to learn as Python, it is based on the first The principles of practicing the basic skills will be taught slowly at the beginning.

Of course, there are still some requirements for readers, I hope it is better to understand more than one mainstream programming language, such as C or Python, so that it is easier to enter the state.

In the next article, I will talk about functions.

 

 

Main references and documents recommended for readers to read further

https://doc.rust-lang.org/book

1. The Way of Rust Programming, 2019, Zhang Handong

2.The Complete Rust Programming Reference Guide,2019,Rahul Sharma,Vesa Kaihlavirta,Claus Matzinger

3.Hands-On Data Structures and Algorithms with Rust,2018,Claus Matzinger

4. Beginning Rust , 2018 , Carlo Milanesi

5. Rust Cookbook , 2017 , Vigneshwer Dhinakaran

 

Guess you like

Origin blog.csdn.net/qq_40433634/article/details/111934816