Rust中的workspace

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

  

二、子crata中的Cargo.toml声明

假设上面的工程结构中: 

  • 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 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依赖声明,就可以来写代码了,参见下面的示例:

3.1 model/src/lib.rs

#[derive(Debug)]
pub struct User{
   pub username:String,
   pub password:String
}

#[derive(Debug)]
pub struct Order{
    pub orderno:String
}

假设在model中定义了2个结构体(即:OOP中的class)

 

3.2 view/src/lib.rs

//使用model中的User类
use model::User;

pub fn get_login_info(name:String,pass:String)->User{
    User{
        username:name,
        password:pass
    }
}

  

3.3 controller/src/main.rs

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" }
posted @ 2021-11-21 21:56  菩提树下的杨过  阅读(536)  评论(1编辑  收藏  举报