作用
通過派生宏 #[derive(With)] 給結(jié)構(gòu)體字段生成 with_xxx 方法,通過鏈?zhǔn)秸{(diào)用 with_xxx 方法來構(gòu)造結(jié)構(gòu)體。
使用方法
1.給 named struct 每個字段生成 with_xxx 方法
#[derive(With)] pubstructFoo{ puba:i32, pubb:String, }
宏生成代碼
implFoo{ pubfnwith_a(mutself,a:implInto)->Self{ self.a=a.into(); self } pubfnwith_b(mutself,b:implInto )->Self{ self.b=b.into(); self } }
2.給 tuple struct 每個字段生成 with_xxx 方法
#[derive(With)] pubstructBar(i32,String);
宏生成代碼
implBar{ pubfnwith_0(mutself,field_0:implInto)->Self{ self.0=field_0.into(); self } pubfnwith_1(mutself,field_1:implInto )->Self{ self.1=field_1.into(); self } }
3.通過字段名給 named struct 指定字段實現(xiàn) with_xxx 方法
#[derive(With)] #[with(a)] pubstructFoo{ puba:i32, pubb:String, }
宏生成代碼
implFoo{ pubfnwith_a(mutself,a:implInto)->Self{ self.a=a.into(); self } }
4.通過下標(biāo)給 tuple struct 指定字段生成 with_xxx 方法
#[derive(With)] #[with(1)] pubstructBar(i32,String);
宏生成代碼
implBar{ pubfnwith_1(mutself,field_1:implInto)->Self{ self.1=field_1.into(); self } }
也支持結(jié)構(gòu)體中含有泛型、生命周期、引用等。
審核編輯:劉清
-
rust語言
+關(guān)注
關(guān)注
0文章
57瀏覽量
3110
原文標(biāo)題:【大家的項目】利用 Rust 過程宏實現(xiàn)的 derive-with 庫
文章出處:【微信號:Rust語言中文社區(qū),微信公眾號:Rust語言中文社區(qū)】歡迎添加關(guān)注!文章轉(zhuǎn)載請注明出處。
發(fā)布評論請先 登錄
如何在Rust中連接和使用MySQL數(shù)據(jù)庫
如何使用Serde進行序列化和反序列化
如何使用Rust的標(biāo)準(zhǔn)庫和structopt庫來處理控制臺參數(shù)
如何對gcc編譯過程中生成的宏進行調(diào)試呢
如何利用C語言去調(diào)用rust靜態(tài)庫呢
在Rust代碼中加載靜態(tài)庫時,出現(xiàn)錯誤 ` rust-lld: error: undefined symbol: malloc `怎么解決?
Rust 1.15 引入自定義derive特性有什么做用

Rust GUI 庫發(fā)展現(xiàn)狀
Chromium正式開始支持Rust
為什么我們從C++語言轉(zhuǎn)向Rust語言呢?
基于Rust的Log日志庫介紹
Rust的標(biāo)準(zhǔn)庫的功能劃分

FastTime-純Rust編寫的高并發(fā)快速時間庫
基于Rust的嵌入式符合ACID的鍵值數(shù)據(jù)庫
如何用Rust過程宏魔法簡化SQL函數(shù)呢?

評論