首頁 > 軟體

詳解Rust中的workspace

2022-03-21 19:01:11

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:St

假設在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" }

到此這篇關於Rust中的workspace的文章就介紹到這了,更多相關Rust workspace內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com