目录一、目录结构二、子crata中的CarGo.toml声明三、代码引用3.1 model/src/lib.rs3.2 view/src/lib.rs3.3 controller/s
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
假设上面的工程结构中:
则这3个crate中的Cargo.toml文件,可以这样写:
model/Cargo.toml
[package]
name = "model"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://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 Https://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 https://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的文章就介绍到这了,更多相关Rust workspace内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: 详解Rust中的workspace
本文链接: https://lsjlt.com/news/143297.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0