导读 | 这篇文章主要向大家介绍Rust中的workspace,主要内容包括基础应用、实用技巧、原理机制等方面,这个概念在Rust中是通用的,只不过maven换成了cargo,而模块变成了crate,下面跟着小编通过一个例子给大家介绍下 |
java项目中用maven管理代码时,如果遇到大型工程,一般会拆分成不同的模块,比如spring-mvc中,通常会按model, view, controller建3个模块,然后根据一定的依赖关系进行引用。这个概念在Rust中是通用的,只不过maven换成了cargo,而模块变成了crate,看下面的例子。
. ├── Cargo.toml ├── controller │ ├── Cargo.toml │ └── src │ └── main.rs ├── model │ ├── Cargo.toml │ └── src │ └── lib.rs └── view ├── Cargo.toml └── src └── lib.rs
根目录下的Cargo.toml,类似maven中的父pom.xml,可以在其中声明子"模块":(注:为了避免与rust中的mod"模块"产生混淆,后面还是用crate来称呼“子模块”)
[workspace] members=[ "model", "view", "controller" ]
这里声明了1个所谓的workspace,其中有3个成员,即3个目录对应的crate
假设上面的工程结构中:
model不依赖其它crate
view依赖model
controller依赖view及model
则这3个crate中的Cargo.toml文件,可以这样写:
model/Cargo.toml
[package] name = "model" version = "0.1.0" edition = "2021" # See more keys and their definitions at //doc.rust-lang.org/cargo/reference/manifest.html [dependencies] # 不依赖其它crate,此节点为空即可
view/Cargo.toml
[package] name = "view" version = "0.1.0" edition = "2021" # See more keys and their definitions at //doc.rust-lang.org/cargo/reference/manifest.html [dependencies] # 声明依赖model model = {path = "../model"}
controll/Cargo.toml
[package] name = "controller" version = "0.1.0" edition = "2021" # See more keys and their definitions at //doc.rust-lang.org/cargo/reference/manifest.html [dependencies] model = {path = "../model"} view = {path = "../view"}
有了前面的各crate依赖声明,就可以来写代码了,参见下面的示例:
#[derive(Debug)] pub struct User{ pub username:String, pub password:String } #[derive(Debug)] pub struct Order{ pub orderno:St
假设在model中定义了2个结构体(即:OOP中的class)
//使用model中的User类 use model::User; pub fn get_login_info(name:String,pass:String)->User{ User{ username:name, password:pass } }
use view::get_login_info; use model::{User,Order}; fn main() { let mut u = get_login_info(String::from("test"), String::from("123456")); u.password = String::from("abcde"); println!("{:?}", u); let o = Order{ orderno:String::from("20211244123") }; println!("{:?}",o); let u1 = User{ username:String::from("abcd"), password:String::from("*123*J") }; println!("{:?}",u1); }
运行结果:
User { username: "test", password: "abcde" } Order { orderno: "20211244123" } User { username: "abcd", password: "*123*J" }
到此这篇关于Rust中的workspace的文章就介绍到这了。
原文来自:
本文地址://q13zd.cn/rust-workspace-linux.html编辑:xiangping wu,审核员:逄增宝
Linux大全:
Linux系统大全: