Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Rust Organization and Management

Rust Organization and Management

Any programming language that cannot organize code is difficult to go deep into; almost no software product is compiled from a single source file.

All programs in this tutorial so far have been written in a single file, mainly to facilitate learning the syntax and concepts of the Rust language.

For a project, organizing code is very important.

There are three important organizing concepts in Rust: crates, packages, and modules.

Crate

A "crate" is a binary program file or library file that exists within a "package".

A "crate" has a tree structure; its root is the program compiled from the source file that the compiler begins compiling when it starts.

Note: a "binary program file" is not necessarily a "binary executable file"; it can only be said to be a file containing target machine language, and the file format varies with the compilation environment.

Package

When we use Cargo to run the new command to create a Rust project, a Cargo.toml file is created in the project directory. The essence of a project is a package, which must be managed by a Cargo.toml file that describes the package's basic information and dependencies.

A package contains at most one library "crate" and any number of binary "crates", but at least one "crate" (whether library or binary).

After creating a package with the cargo new command, a main.rs source file is generated in the src directory. Cargo defaults this file as the root of the binary crate, and the compiled binary crate will have the same name as the package.

Module

For a software project, we often organize according to the organizational norms of the programming language used; the main structure for organizing modules is often a tree. The main unit Java uses to organize functional modules is the class, while the main way JavaScript organizes modules is function.

The organizational units of these advanced languages can be nested level by level, like a file system's directory structure. The organizational unit in Rust is the module (Module).

mod nation {

    mod government {

        fn govern() {}

    }

    mod congress {

        fn legislate() {}

    }

    mod court {

        fn judicial() {}

    }

}

This is a program describing a state governed by the rule of law: a nation includes government, congress, and court, which have executive, legislative, and judicial functions respectively. We can convert it into a tree structure:

nation

 ├── government

 │ └── govern

 ├── congress

 │ └── legislate

 └── court

   └── judicial

In a file system, directory structures often use slashes in path strings to represent an object's location; the path separator in Rust is ::.

Paths are divided into absolute paths and relative paths. An absolute path is described starting from the crate keyword. A relative path is described starting from the self or super keyword or an identifier. For example:

crate::nation::government::govern();

describes the absolute path of the govern function; a relative path can be expressed as:

nation::government::govern();

Now you can try defining a similar module structure in a source program and using paths in the main function.

If you do so, you will surely find what is wrong: the government module and the functions in it are all private, and you are not allowed to access them.


Access Permissions

There are two simple kinds of access permission in Rust: public and private.

By default, if no modifier is added, the access permission of members in a module will be private.

To use public permission, you need to use the pub keyword.

For a private module, it can only be accessed at the same level or a lower level, and cannot be accessed from outside it.

Example

mod

nation

{

   

pub

mod

government

{

       

pub

fn

govern

(

)

{

}

   

}

   

mod

congress

{

       

pub

fn

legislate

(

)

{

}

   

}

   

   

mod

court

{

       

fn

judicial

(

)

{

           

super

::

congress

::

legislate

(

)

;

       

}

   

}

}

fn

main

(

)

{

    nation

::

government

::

govern

(

)

;

}

This program can compile. Please note the way super is used to access in the court module.

If a struct is defined in a module, besides the struct itself being private, its fields are also private by default. So to use the struct in the module and its fields, you need a pub declaration:

Example

mod

back_of_house

{

   

pub

struct

Breakfast

{

       

pub

toast

:

String

,

        seasonal_fruit

:

String

,

   

}

   

impl

Breakfast

{

       

pub

fn

summer

(

toast

:

&

str

)

->

Breakfast

{

            Breakfast

{

                toast

:

String

::

from

(

toast

)

,

                seasonal_fruit

:

String

::

from

(

"peaches"

)

,

           

}

       

}

   

}

}

pub

fn

eat_at_restaurant

(

)

{

   

let

mut

meal

=

back_of_house

::

Breakfast

::

summer

(

"Rye"

)

;

    meal.toast

=

String

::

from

(

"Wheat"

)

;

    println

!

(

"I'd like {} toast please"

,

meal.toast

)

;

}

fn

main

(

)

{

    eat_at_restaurant

(

)

}

Running result:



I'd like Wheat toast please

Enum variants can contain fields, but do not have a similar property:

Example

mod

SomeModule

{

   

pub

enum

Person

{

        King

{

            name

:

String

       

}

,

        Queen

   

}

}

fn

main

(

)

{

   

let

person

=

SomeModule

::

Person

::

King

{

        name

:

String

::

from

(

"Blue"

)

   

}

;

   

match

person

{

        SomeModule

::

Person

::

King

{

name

}

=>

{

            println

!

(

"{}"

,

name

)

;

       

}

        _

=>

{

}

   

}

}

Running result:



Blue


Hard-to-Discover Modules

Developers who have used Java often dislike the outermost class block when programming—its name is exactly the same as the file name, because it represents the file container. Although it is tedious, we have to write it once to emphasize "this class is the class contained in the file".

However, this has some benefits: at least it makes developers clearly aware of the existence of the class wrapper, and it can explicitly describe the inheritance relationship of classes.

In Rust, a module is like a class wrapper in Java, but you can write a main function at the very beginning of a file. How can this be explained?

The content of every Rust file is a "hard-to-discover" module.

Let's reveal this with two files:

main.rs file

// main.rs

mod

second_module

;

fn

main

(

)

{

    println

!

(

"This is the main module."

)

;

    println

!

(

"{}"

,

second_module

::

message

(

)

)

;

}

second_module.rs file

// second_module.rs

pub

fn

message

(

)

->

String

{

    String

::

from

(

"This is the 2nd module."

)

}

Running result:



This is the main module.

This is the 2nd module.


The use Keyword

The use keyword can bring a module identifier into the current scope:

Example

mod

nation

{

   

pub

mod

government

{

       

pub

fn

govern

(

)

{

}

   

}

}

use

crate

::

nation

::

government

::

govern

;

fn

main

(

)

{

    govern

(

)

;

}

This program can compile.

Because the use keyword imports the govern identifier into the current module, it can be used directly.

This solves the problem of overly long local module paths.

Of course, in some cases there are two identical names that both need to be imported; we can use the as keyword to add an alias to an identifier:

Example

mod

nation

{

   

pub

mod

government

{

       

pub

fn

govern

(

)

{

}

   

}

   

pub

fn

govern

(

)

{

}

}

   

use

crate

::

nation

::

government

::

govern

;

use

crate

::

nation

::

govern

as

nation_govern

;

fn

main

(

)

{

    nation_govern

(

)

;

    govern

(

)

;

}

Here there are two govern functions, one under nation and one under government. We use as to alias the one under nation as nation_govern. Both names can be used at the same time.

The use keyword can be used together with the pub keyword:

Example

mod

nation

{

   

pub

mod

government

{

       

pub

fn

govern

(

)

{

}

   

}

   

pub

use

government

::

govern

;

}

fn

main

(

)

{

    nation

::

govern

(

)

;

}


Referencing the Standard Library

Rust official standard library dictionary:https://doc.rust-lang.org/stable/std/all.html

After learning the concepts in this chapter, we can easily import system libraries to develop programs conveniently:

Example

use

std

::

f64

::

consts

::

PI

;

fn

main

(

)

{

    println

!

(

"{}"

,

(

PI

/

2.0

)

.sin

(

)

)

;

}

Running result:



1

All system library modules are imported by default, so when using them you only need to use the use keyword to simplify the path for convenient use.