Learn Rust from scratch, the first program Hello World, and the package management tool Cargo


In the previous section, Rust's development environment was installed . This section begins with the first program and the introduction Use of Cargo.

hello world

Create Hello manually_ World folder:

mkdir hello_world
cd hello_world

Then create a hello_world.rs file, i.e. t rust source file:

touch hello_world.rs

Write the following code:

fn main() {
    println!("hello world");
}

Rust is indented with 4 spaces instead of tab

println here! It's a macro, not a function, not a function!

Compile with rustc(Rust Compile) and run the executable:

$ rustc hello_world.rs
$ ./hello_world
hello world

Rust is an ahead of time (precompiled) language. You can compile the program first and give the executable file to others to run without installing rust.

rustc is used for small projects, and cargo is also used for large projects.

cargo

cargo is Rust's build system and package management tool. This includes building code, downloading dependent libraries, and building these libraries.

cargo will be installed by default after Rust installation. You can view it in the following ways:

$ cargo --version
cargo 1.58.0 (f01b232bc 2022-01-19)

View help details:

$ cargo -h

Rust Package manager for

USAGE:
    cargo [+toolchain] [OPTIONS] [SUBCOMMAND]

OPTIONS:
    -V, --version                  Print version information and exit
        --list                     Installation command list
        --explain <CODE>           function`rustc --explain CODE`
    -v, --verbose                  Use detailed output(-vv Very detailed/build.rs output)
    -q, --quiet                    Do not print cargo log information
        --color <WHEN>             to color: auto, always, never
        --frozen                   requirement Cargo.lock and cache It's the latest
        --locked                   requirement Cargo.lock It's the latest
        --offline                  Run without accessing the network
        --config <KEY=VALUE>...    Override configuration value(instable)
    -Z <FLAG>...                   Cargo Unstable options for(Only nightly),see also`cargo -Z help`Learn more
    -h, --help                     print the help information

Some common cargo commands are as follows. cargo --list view all commands.

    build, b    Compile the current package
    check, c    Analyze the current package and report errors, but do not build the object file
    clean       delete target catalogue
    doc, d      Documentation for building this package and its dependencies
    new         Create a new cargo package
    init        Create a new in an existing directory cargo package
    run, r      Binaries or examples of running local packages
    test, t     Run test
    bench       Run benchmark
    update      Update in Cargo.lock Dependencies listed in
    search      search crates registry
    publish     Package and upload this package to the registry
    install     install Rust Binary file. The default location is $HOME/.cargo/bin
    uninstall   uninstall Rust Binary file

For more information about specific commands, see cargo help < command >.

cargo create project

The cargo new project will be automatically initialized as a VCS repository. You can specify the version control system (git, hg, pijul, or fossil) through -- vcs vcs, or specify -- vcs none to indicate that no version control will be initialized. If not specified, it defaults to git or cargo new VCS configuration value.

Create a hello with cargo_ Cargo project folder:

$ cargo new hello_cargo
     Created binary (application) `hello_cargo` package

Enter hello_cargo directory, view the structure:

$ tree
.
├── .gitignore
├── Cargo.toml
└── src
    └── main.rs

src is the source file directory with main rs.

. gitignore description is a VCS project.

Cargo.toml is a package management file. TOML is Tom's obvious, minimal language format, which is the configuration format of cargo.

[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

[package] is the area title. The following content is used to configure the package:

  • Name: project name
  • Version: project version
  • authors: Project author
  • edition: Rust version used

[dependencies] at the beginning of another area, the dependencies of the project are listed below.

In Rust, the package (Library) of code is called crate

If the t rust plug-in is installed in vscode:

vscode open hello_ In the cargo project folder, you will see that the target directory is generated by automatic compilation. Normally, it will not be generated without executing the command:

tree
.
tree
.
├── Cargo.lock
├── Cargo.toml
├── src
│   └── main.rs
└── target
    ├── CACHEDIR.TAG
    └── debug
        ├── build
        ├── deps
        │   ├── ellipsis
        ├── examples
        └── incremental
            ├── ellipsis

build compilation

cargo build generates the target/debug / {project name} executable.

It will also generate cargo in the root directory of the project Lock file is used to track the library version that the project depends on. It does not need to be modified manually.

cargo build --release optimizes the compilation, and the compilation time will be longer.

The executable file will be generated in: target/release / {project name}

Run run

cargo run is divided into two steps: compiling and running. After the first compilation, if the code has not changed, only run will be executed and will not be rebuilt.

cargo run --release optimizes the operation after compilation. The compilation time will be longer and the code will run more efficiently.

The executable file will be generated in: target/release / {project name}

Check check

Check the code to ensure that it compiles smoothly, but does not produce executable files.

What is the difference between check and build in cargo?

Check is much faster than build in speed. You can check repeatedly during coding, which greatly improves the efficiency.

follow

This article starts with WeChat official account, my small bowl soup, scan the left side code, pay more attention to more consultation, and have more free resources for you to learn.

Keywords: Back-end Rust

Added by sasquatch69 on Sat, 29 Jan 2022 14:25:56 +0200