Rust實(shí)現(xiàn)構(gòu)建器模式和如何使用Bon庫中的構(gòu)建器
實(shí)現(xiàn)構(gòu)建器模式的一種方式
這里參考資料2的文章,修改部分代碼后如下。這段代碼的目的是使用構(gòu)建器模式創(chuàng)建和初始化Person對(duì)象。以下是各部分的解釋:
結(jié)構(gòu)體定義
- Person: 定義了一個(gè)結(jié)構(gòu)體,包含name、age、address和sex四個(gè)字段。address和sex是可選的
- PersonBuilder: 用于逐步構(gòu)建Person對(duì)象的構(gòu)建器結(jié)構(gòu)體
構(gòu)建器實(shí)現(xiàn)
- new: 創(chuàng)建一個(gè)新的PersonBuilder實(shí)例,初始化name和age,其他字段為None
- with_address: 設(shè)置address字段,返回修改后的構(gòu)建器
- with_sex: 設(shè)置sex字段,返回修改后的構(gòu)建器
- build: 生成最終的Person對(duì)象
主函數(shù)
- 使用PersonBuilder構(gòu)建一個(gè)Person對(duì)象,設(shè)置name、age、address和sex
- 打印Person對(duì)象及其各個(gè)字段的值
目的
- 封裝對(duì)象創(chuàng)建過程: 使用構(gòu)建器模式來管理對(duì)象初始化的復(fù)雜性
- 可選字段設(shè)置: 允許靈活地設(shè)置可選字段,而不必在創(chuàng)建對(duì)象時(shí)提供所有信息
- 鏈?zhǔn)秸{(diào)用: 提供鏈?zhǔn)秸{(diào)用的接口,使代碼更簡(jiǎn)潔易讀
#[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構(gòu)建器
了解完Rust如何實(shí)現(xiàn)構(gòu)建器模式后,如果我們想要在實(shí)際項(xiàng)目中使用構(gòu)建器,當(dāng)然可以不用自己手動(dòng)實(shí)現(xiàn),可以使用第三方庫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運(yùn)行結(jié)果和手動(dòng)實(shí)現(xiàn)方式一致。當(dāng)然這種方式更為簡(jiǎn)潔,可以省略很多代碼實(shí)現(xiàn),容易維護(hù)和閱讀,更推薦使用
參考資料3,Bon除了結(jié)構(gòu)體的構(gòu)建器和關(guān)聯(lián)方法的構(gòu)建器,還有函數(shù)的構(gòu)建器
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)
到此這篇關(guān)于Rust實(shí)現(xiàn)構(gòu)建器模式和使用Bon庫中的構(gòu)建器的文章就介紹到這了,更多相關(guān)Rust構(gòu)建器模式內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Rust實(shí)現(xiàn)構(gòu)建器模式和如何使用Bon庫中的構(gòu)建器
這篇文章主要介紹了Rust實(shí)現(xiàn)構(gòu)建器模式和如何使用Bon庫中的構(gòu)建器,本文給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-08-08
Rust應(yīng)用調(diào)用C語言動(dòng)態(tài)庫的操作方法
這篇文章主要介紹了Rust應(yīng)用調(diào)用C語言動(dòng)態(tài)庫,本文記錄了筆者編寫一個(gè)簡(jiǎn)單的C語言動(dòng)態(tài)庫,并通過Rust調(diào)用動(dòng)態(tài)庫導(dǎo)出的函數(shù),需要的朋友可以參考下2023-01-01
90%的Rust新手都不知道的3個(gè)實(shí)用開發(fā)技巧小結(jié)
Rust是一個(gè)新興的系統(tǒng)級(jí)編程語言,以其獨(dú)特的所有權(quán)系統(tǒng)和借用檢查器而聞名,盡管它被認(rèn)為是一門相對(duì)較難的語言,但只要掌握了正確的學(xué)習(xí)方法,你會(huì)發(fā)現(xiàn)Rust其實(shí)并不復(fù)雜,這篇文章主要介紹了90%的Rust新手都不知道的3個(gè)實(shí)用開發(fā)技巧,需要的朋友可以參考下2026-06-06
Rust整合Elasticsearch的詳細(xì)過程(收藏)
Elasticsearch是基于Lucene構(gòu)建的開源分布式搜索和分析引擎,支持水平擴(kuò)展和多語言調(diào)用,ELK(Elastic Stack)組合包括Elasticsearch、Kibana、Logstash和Beats,專注于日志數(shù)據(jù)分析和實(shí)時(shí)監(jiān)控,本文介紹Rust整合Elasticsearch的過程,一起看看吧2024-11-11
為什么要選Rust?學(xué)習(xí)Rust從零開始配置和實(shí)現(xiàn)第一個(gè)簡(jiǎn)單項(xiàng)目
本文介紹了Rust語言的核心價(jià)值、應(yīng)用場(chǎng)景、開發(fā)環(huán)境搭建、第一個(gè)Rust項(xiàng)目的創(chuàng)建與擴(kuò)展、調(diào)試、發(fā)布流程,以及新手常見陷阱與避坑方法,通過學(xué)習(xí)Rust,開發(fā)者可以實(shí)現(xiàn)高效且安全的系統(tǒng)級(jí)開發(fā)、網(wǎng)絡(luò)編程和工具開發(fā)2026-01-01

