作用
通過(guò)派生宏 #[derive(With)] 給結(jié)構(gòu)體字段生成 with_xxx 方法,通過(guò)鏈?zhǔn)秸{(diào)用 with_xxx 方法來(lái)構(gòu)造結(jié)構(gòu)體。
使用方法
1.給 named struct 每個(gè)字段生成 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 每個(gè)字段生成 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.通過(guò)字段名給 named struct 指定字段實(shí)現(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.通過(guò)下標(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語(yǔ)言
+關(guān)注
關(guān)注
0文章
57瀏覽量
3218
原文標(biāo)題:【大家的項(xiàng)目】利用 Rust 過(guò)程宏實(shí)現(xiàn)的 derive-with 庫(kù)
文章出處:【微信號(hào):Rust語(yǔ)言中文社區(qū),微信公眾號(hào):Rust語(yǔ)言中文社區(qū)】歡迎添加關(guān)注!文章轉(zhuǎn)載請(qǐng)注明出處。
發(fā)布評(píng)論請(qǐng)先 登錄
如何在Rust中連接和使用MySQL數(shù)據(jù)庫(kù)
如何使用Serde進(jìn)行序列化和反序列化
如何使用Rust的標(biāo)準(zhǔn)庫(kù)和structopt庫(kù)來(lái)處理控制臺(tái)參數(shù)
如何對(duì)gcc編譯過(guò)程中生成的宏進(jìn)行調(diào)試呢
如何利用C語(yǔ)言去調(diào)用rust靜態(tài)庫(kù)呢
在Rust代碼中加載靜態(tài)庫(kù)時(shí),出現(xiàn)錯(cuò)誤 ` rust-lld: error: undefined symbol: malloc `怎么解決?
Rust 1.15 引入自定義derive特性有什么做用

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

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

評(píng)論