Rust實現構建器模式和如何使用Bon庫中的構建器
實現構建器模式的一種方式
這里參考資料2的文章,修改部分代碼后如下。這段代碼的目的是使用構建器模式創(chuàng)建和初始化Person對象。以下是各部分的解釋:
結構體定義
- Person: 定義了一個結構體,包含name、age、address和sex四個字段。address和sex是可選的
- PersonBuilder: 用于逐步構建Person對象的構建器結構體
構建器實現
- new: 創(chuàng)建一個新的PersonBuilder實例,初始化name和age,其他字段為None
- with_address: 設置address字段,返回修改后的構建器
- with_sex: 設置sex字段,返回修改后的構建器
- build: 生成最終的Person對象
主函數
- 使用PersonBuilder構建一個Person對象,設置name、age、address和sex
- 打印Person對象及其各個字段的值
目的
- 封裝對象創(chuàng)建過程: 使用構建器模式來管理對象初始化的復雜性
- 可選字段設置: 允許靈活地設置可選字段,而不必在創(chuàng)建對象時提供所有信息
- 鏈式調用: 提供鏈式調用的接口,使代碼更簡潔易讀
#[derive(Debug)]
struct Person {
name: String,
age: u32,
address: Option<String>,
sex: Option<String>,
}
struct PersonBuilder {
name: String,
age: u32,
address: Option<String>,
sex: Option<String>,
}
impl PersonBuilder {
fn new(name: String, age: u32) -> Self {
Self {
name,
age,
address: None,
sex: None,
}
}
fn with_address(mut self, address: String) -> Self {
self.address = Some(address);
self
}
fn with_sex(mut self, sex: String) -> Self {
self.sex = Some(sex);
self
}
fn build(self) -> Person {
Person {
name: self.name,
age: self.age,
address: self.address,
sex: self.sex,
}
}
}
fn main() {
let person = PersonBuilder::new("Alice".to_string(), 30)
.with_address("Wonderland".to_string())
.with_sex("Female".to_string())
.build();
println!("{:?}", person);
// Access the fields to demonstrate usage
println!("Name: {}", person.name);
println!("Age: {}", person.age);
if let Some(address) = &person.address {
println!("Address: {}", address);
} else {
println!("Address: None");
}
if let Some(sex) = &person.sex {
println!("Sex: {}", sex);
} else {
println!("Sex: None");
}
}Person { name: "Alice", age: 30, address: Some("Wonderland"), sex: Some("Female") }
Name: Alice
Age: 30
Address: Wonderland
Sex: Female使用Bon構建器
了解完Rust如何實現構建器模式后,如果我們想要在實際項目中使用構建器,當然可以不用自己手動實現,可以使用第三方庫Bon,引入方式如下
Cargo.toml
[dependencies] bon = "1.1.0"
use bon::bon;
#[derive(Debug)]
struct Person {
name: String,
age: u32,
address: Option<String>,
sex: Option<String>,
}
#[bon] // 使用 Bon 庫的宏
impl Person {
#[builder]
fn new(name: String, age: u32) -> Self {
Self {
name,
age,
address: None,
sex: None,
}
}
#[builder]
fn with_address(&mut self, address: String) {
self.address = Some(address);
}
#[builder]
fn with_sex(&mut self, sex: String) {
self.sex = Some(sex);
}
}
fn main() {
let mut person = Person::builder()
.name("Alice".to_string())
.age(30)
.build();
person.with_address().address("Wonderland").call();
person.with_sex().sex("Female").call();
println!("{:?}", person);
println!("Name: {}", person.name);
println!("Age: {}", person.age);
if let Some(address) = &person.address {
println!("Address: {}", address);
} else {
println!("Address: None");
}
if let Some(sex) = &person.sex {
println!("Sex: {}", sex);
} else {
println!("Sex: None");
}
}Person { name: "Alice", age: 30, address: Some("Wonderland"), sex: Some("Female") }
Name: Alice
Age: 30
Address: Wonderland
Sex: Female運行結果和手動實現方式一致。當然這種方式更為簡潔,可以省略很多代碼實現,容易維護和閱讀,更推薦使用
參考資料3,Bon除了結構體的構建器和關聯方法的構建器,還有函數的構建器
fn main() {
#[bon::builder]
fn greet(name: &str, age: u32) -> String {
format!("Hello {name} with age {age}!")
}
let greeting = greet()
.name("Bon")
.age(24)
.call();
if greeting == "Hello Bon with age 24!" {
println!("Assertion passed: {}", greeting);
} else {
println!("Assertion failed");
}
}Assertion passed: Hello Bon with age 24!
參考資料
How to do named function arguments in Rust
Overview | Bon (elastio.github.io)
到此這篇關于Rust實現構建器模式和使用Bon庫中的構建器的文章就介紹到這了,更多相關Rust構建器模式內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Rust初體驗:手把手教你構建‘Hello,?World!’
"準備好了嗎?一起踏上Rust編程語言的精彩旅程!在這篇「Rust初體驗」中,我們將手把手教你構建經典程序“Hello,?World!”,感受Rust的強大與安全,短短幾行代碼,就能讓你對這個系統(tǒng)級語言的魅力一探究竟!快加入吧,驚喜等你發(fā)現!"2024-01-01

