欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 会展 > Rust简明教程第七章-包、模块路径

Rust简明教程第七章-包、模块路径

2025/10/18 15:47:59 来源:https://blog.csdn.net/weixin_62799021/article/details/140216718  浏览:    关键词:Rust简明教程第七章-包、模块路径

观看B站软件工艺师杨旭的rust教程学习记录,有删减有补充

包和模块

Package 包

Cargo特性,构建、测试、共享crate

  • 一个package包含一个Cargo.toml
  • 一个package只能包含0-1个library(库),lib.rs
  • 可以包含任意数量的binary,main.rs
  • 必须至少包含一个librarybinary

使用包

1、在Cargo.toml[dependencies]

2、使用use将包导入到作用域

Crate 单元包

一个模块树,它可以产生一个library或可执行文件

  • crate 是指一个Rust项目或库(library)的单独编译单元(binary)
  • create可以是一个二进制可执行文件或一个库(库可以是动态链接库或静态链接库)
  • 每个crate都有自己的名称和根目录,其中包含了与该 crate 相关的源代码文件、配置文件和其他资源
  • crate可以包含多个modulemodule是代码组织和封装的单元,用于将相关的功能组织在一起
    • src/main.rs:是源代码文件,Rust编译器从这里开始,就是binary cratecrate root
    • src/lib.rs:是linary cretecrate root

使用cargo new test_cargo项目,这里只有一个binary crate,创建src/bin可以存放多个binary crate
图片.png

Module 模块

  • mod关键字建立module

use

  • use控制代码的组织、作用域、私有路径(函数、方法、struct、enum、module、常量默认私有)
  • 使用函数时引用函数的父级module
mod front_of_house {pub mod hosting {pub fn add_to_waitlist() {}}
}
//使用函数时引用函数的父级module
use crate::front_of_house::hosting;
pub fn eat_at_restaurant() {hosting::add_to_waitlist();hosting::add_to_waitlist();
}
  • 使用函数以外例如struct、enum等指定完整路径
use std::collections::HashMap;
fn main() {let mut map = HashMap::new();map.insert(1, 2);
}

pub use

导入函数的同时导出函数

mod private_module {pub fn private_function() {println!("私有函数");}
}
//导入函数的同时导出,让外部可以调用私有函数
pub use crate::private_module::private_function;fn main() {private_function(); // 通过 pub use 导出的函数可以在主模块中直接调用
}

嵌套路径清理use

use std::cmp::Ordering;
use std::io;
use std::io::Write;
//简化为
use std::{cmp::Ordering, io, self};

as

as关键字可以为引入的路径指定本地的别名

use std::fmt::Result;
use std::io::Result as IoResult;
fn f1() -> Result {}
fn f2() -> IoResult {}
fn main() {}

Path

structfunctionmodule等命名的方式

  • 绝对路径:从crate root开始,也就是src/main.rssrc/lib.rssrc/bin/下的crate
  • 相对路径:从当前module开始,使用selfsuper或当前module的标识符
  • 路径至少有一个标识符组成,标识符之间使用::

front_of_houseeat_at_restaurant在同一个lib.rs内,所以拥有同一个crate root

mod front_of_house {pub mod hosting {pub fn add_to_waitlist() {}}pub fn eat_at_restaurant() {//绝对路径:根据crate root定位crate::front_of_house::hosting::add_to_waitlist();//相对路径:根据module这个同级目录定位front_of_house::hosting::add_to_waitlist();}
}

super

  • super用来访问父级路径的内容
fn serve_order() {}
mod back_of_house {fn fix_incorrect_order() {cook_order();//super直接调用父级方法super::serve_order();//绝对路径调用父级方法crate::serve_order();}fn cook_order() {}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词