Table of contents
1. Installation
Rust Programming Language (rust-lang.org) , this is the official Rust website.
Just download the corresponding system version directly, the editor is the linux version.
After downloading, enter this command on the Linux command line:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
If necessary, you can download related editors (such as: vscode) to facilitate learning and use.
2. Create
Rust source files end in .rs .
There are two ways to create, the first is to create directly:
touch hello.rs
The second is to create a project.
cargo new project name
cargo is rust's build system and package manager, which is very powerful.
After cargo creates a project, there will be a directory file with the same name.
Where Cargo.toml is a file that records project data.
src is used to store all project source files, and cargo will automatically generate a main file.
3. Compile
The first way is to use the rustc compiler:
rustc xxx.rs
The second is to compile with cargo:
In addition to creating projects, cargo can also build code and run code.
Construct:
cargo build
The so-called build code is generally speaking compiled but not run.
run:
charge run
To run code is to compile and run.
Another thing to note is that regardless of build or run, commands must be executed in rust-related projects.
After compiling, there will be a target directory in the project, which stores the executable programs we compiled.
It is worth noting that whether it is build or run, the default version is the debug version . If you want to generate the release version, you need to add --release after the command, such as:
cargo build --release
4. Input and output
(1). Output hello world
Take a look at hello world first:
fn main()
{
println!("hello world");
}
Where println! is a macro, not a function.
(2). Input
Take read_line() as an example, the usage is as follows:
use std::io;
fn main()
{
let mut a = String::new();
io::stdin().read_line(&mut a).expect("输入错误");
println!("{}", a);
}
Among them, io is a sub-library in the standard library.
let is used to define variables, and the default is a variable with an immutable value .
mut can declare a variable as a mutable variable .
stdin is a file handle , which is equivalent to the FILE structure in C language.
read_line is a method implemented by stdin for inputting character data.
The {} in println is a placeholder .
Please correct me if there is any mistake