Rust从入门到实战系列三百一十:将模块分离并放入独立的文件中

本文介绍了如何在Rust项目中,通过模块化设计将前端(front_of_house)和后端(back_of_house)分离,包括hosting和serving模块,以及如何在main.rs中发起函数调用。展示了Cargo项目结构和基本的单元测试。
摘要由CSDN通过智能技术生成

// in lib.rs
pub mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {}
pub fn seat_at_table() -> String {
String::from(“sit down please”)
}
}
pub mod serving {
pub fn take_order() {}
pub fn serve_order() {}
pub fn take_payment() {}
// 我猜你不希望顾客听到你在抱怨他们,因此让这个函数私有化吧
fn complain() {}
}
}
pub fn eat_at_restaurant() -> String {
front_of_house::hosting::add_to_waitlist();
back_of_house::cook_order();
String::from(“yummy yummy!”)
}
pub mod back_of_house {
pub fn fix_incorrect_order() {
cook_order();
crate::front_of_house::serving::serve_order();
}
pub fn cook_order() {}
}
4. 🌟🌟🌟🌟 请将上面的模块和代码分离到以下目录文件中e :
.
├── Cargo.toml
├── src
│ ├── back_of_house.rs
│ ├── front_of_house
│ │ ├── hosting.rs
│ │ ├── mod.rs
│ │ └── serving.rs
│ ├── lib.rs
│ └── main.rs
// in src/lib.rs
// IMPLEMENT…
// in src/back_of_house.rs
// IMPLEMENT…
// in src/front_of_house/mod.rs
// IMPLEMENT…
// in src/front_of_house/hosting.rs
// IMPLEMENT…
// in src/front_of_house/serving.rs
// IMPLEMENT…
从二进制包中访问库包的代码
请确保你已经完成了第四题,然后再继续进行.
当到底此处时,你的项目结构应该如下所示:
.
├── Cargo.toml
├── src
│ ├── back_of_house.rs
│ ├── front_of_house
│ │ ├── hosting.rs
│ │ ├── mod.rs
│ │ └── serving.rs
│ ├── lib.rs
│ └── main.rs
5. 🌟🌟🌟现在我们可以从二进制包中发起函数调用了.
// in src/main.rs
// 填 空 并 修 复 错 误
fn main() {
assert_eq!(, “sit down please”);
assert_eq!(
,“yummy yummy!”);
}

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值