作用
通過派生宏 #[derive(With)] 給結構體字段生成 with_xxx 方法,通過鏈式調用 with_xxx 方法來構造結構體。
使用方法
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 指定字段實現 with_xxx 方法
#[derive(With)] #[with(a)] pubstructFoo{ puba:i32, pubb:String, }
宏生成代碼
implFoo{ pubfnwith_a(mutself,a:implInto)->Self{ self.a=a.into(); self } }
4.通過下標給 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 } }
也支持結構體中含有泛型、生命周期、引用等。
審核編輯:劉清
-
rust語言
+關注
關注
0文章
57瀏覽量
3107
原文標題:【大家的項目】利用 Rust 過程宏實現的 derive-with 庫
文章出處:【微信號:Rust語言中文社區,微信公眾號:Rust語言中文社區】歡迎添加關注!文章轉載請注明出處。
發布評論請先 登錄
如何在Rust中連接和使用MySQL數據庫
如何使用Serde進行序列化和反序列化
如何使用Rust的標準庫和structopt庫來處理控制臺參數
如何利用C語言去調用rust靜態庫呢
在Rust代碼中加載靜態庫時,出現錯誤 ` rust-lld: error: undefined symbol: malloc `怎么解決?
Rust 1.15 引入自定義derive特性有什么做用

Rust GUI 庫發展現狀
Chromium正式開始支持Rust
為什么我們從C++語言轉向Rust語言呢?
基于Rust的Log日志庫介紹
Rust的標準庫的功能劃分

評論