好好爱自己!

[转]Rust - Modules

 

原文:https://www.tutorialspoint.com/rust/rust_modules.htm

--------------------------------------

A logical group of code is called a Module. Multiple modules are compiled into a unit called crate. Rust programs may contain a binary crate or a library crate. A binary crate is an executable project that has a main() method. A library crate is a group of components that can be reused in other projects. Unlike a binary crate, a library crate does not have an entry point (main() method). The Cargo tool is used to manage crates in Rust. For example, the network module contains networking related functions and the graphics module contains drawing-related functions. Modules are similar to namespaces in other programming languages. Third-party crates can be downloaded using cargo from crates.io.

Sr.NoTerm & Description
1

crate

Is a compilation unit in Rust; Crate is compiled to binary or library.

2

cargo

The official Rust package management tool for crates.

3

module

Logically groups code within a crate.

4

crates.io

The official Rust package registry.

Syntax

//public module
pub mod a_public_module {
   pub fn a_public_function() {
      //public function
   }
   fn a_private_function() {
      //private function
   }
}
//private module
mod a_private_module {
   fn a_private_function() {
   }
}

Modules can be public or private. Components in a private module cannot be accessed by other modules. Modules in Rust are private by default. On the contrary, functions in a public module can be accessed by other modules. Modules should be prefixed with pub keyword to make it public. Functions within a public module must also be made public.

Illustration: Defining a Module

The example defines a public module − movies. The module contains a function play() that accepts a parameter and prints its value.

pub mod movies {
   pub fn play(name:String) {
      println!("Playing movie {}",name);
   }
}
fn main(){
   movies::play("Herold and Kumar".to_string());
}

Output

Playing movie Herold and Kumar

Use Keyword

The use keyword helps to import a public module.

Syntax

use public_module_name::function_name;

Illustration

pub mod movies {
   pub fn play(name:String) {
      println!("Playing movie {}",name);
   }
}
use movies::play;
fn main(){
   play("Herold and Kumar ".to_string());
}

Output

Playing movie Herold and Kumar

Nested Modules

Modules can also be nested. The comedy module is nested within the english module, which is further nested in the movies module. The example given below defines a function play inside the movies/english/comedy module.

pub mod movies {
   pub mod english {
      pub mod comedy {
         pub fn play(name:String) {
            println!("Playing comedy movie {}",name);
         }
      }
   }
}
use movies::english::comedy::play; 
// importing a public module

fn main() {
   // short path syntax
   play("Herold and Kumar".to_string());
   play("The Hangover".to_string());

   //full path syntax
   movies::english::comedy::play("Airplane!".to_string());
}

Output

Playing comedy movie Herold and Kumar
Playing comedy movie The Hangover
Playing comedy movie Airplane!

Illustration - Create a Library Crate and Consume in a Binary Crate

Let us create a library crate named movie_lib, which contains a module movies. To build the movie_lib library crate, we will use the tool cargo.

Step 1 - Create Project folder

Create a folder movie-app followed by a sub-folder movie-lib. After the folder and sub-folder are created, create an src folder and a Cargo.toml file in this directory. The source code should go in the src folder. Create the files lib.rs and movies.rs in the src folder. The Cargo.toml file will contain the metadata of the project like version number, author name, etc.

The project directory structure will be as shown below −

movie-app
   movie-lib/
      -->Cargo.toml
      -->src/
         lib.rs
         movies.rs

Step 2 - Edit the Cargo.toml file to add project metadata

[package]
name = "movies_lib"
version = "0.1.0"
authors = ["Mohtashim"]

Step 3 - Edit the lib.rs file.

Add the following module definition to this file.

pub mod movies;

The above line creates a public module − movies.

Step 4 - Edit the movies.rs file

This file will define all functions for the movies module.

pub fn play(name:String){
   println!("Playing movie {} :movies-app",name);
}

The above code defines a function play() that accepts a parameter and prints it to the console.

Step 5 - Build the library crate

Build app using the cargo build command to verify if the library crate is structured properly. Make sure you are at root of project − the movie-app folder. The following message will be displayed in the terminal if the build succeeds.

D:\Rust\movie-lib> cargo build
   Compiling movies_lib v0.1.0 (file:///D:/Rust/movie-lib)
   Finished dev [unoptimized + debuginfo] target(s) in 0.67s

Step 6 - Create a test application

Create another folder movie-lib-test in the movie-app folder followed by a Cargo.toml file and the src folder. This project should have main method as this is a binary crate, which will consume the library crate created previously. Create a main.rs file in the src folder. The folder structure will be as shown.

movie-app
   movie-lib 
   // already completed

   movie-lib-test/
      -->Cargo.toml
      -->src/
         main.rs

Step 7 - Add the following in the Cargo.toml file

[package]
name = "test_for_movie_lib"
version = "0.1.0"
authors = ["Mohtashim"]

[dependencies]
movies_lib = { path = "../movie-lib" }

NOTE − The path to the library folder is set as dependencies. The following diagram shows the contents of both the projects.

Cargo Toml File

Step 8 - Add the following to main.rs file

extern crate movies_lib;
use movies_lib::movies::play;
fn main() {
   println!("inside main of test ");
   play("Tutorialspoint".to_string())
}

The above code imports an external package called movies_lib. Check the Cargo.toml of current project to verify the crate name.

Step 9 - Use of cargo build and cargo run

We will use the cargo build and cargo run to build the binary project and execute it as shown below −

cargo run

 

posted @   立志做一个好的程序员  阅读(153)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
历史上的今天:
2019-11-29 golang log 使用
2017-11-29 Good Zookeeper Tutorial with Java client
2016-11-29 【转】Git代码行统计命令集
2016-11-29 读写分离
2016-11-29 subversion-fundamental concepts
2016-11-29 word project 2010破解

不断学习创作,与自己快乐相处

点击右上角即可分享
微信分享提示