Rust实现构建器模式和如何使用Bon库中的构建器
<div id="navCategory"><h5 class="catalogue">目录</h5><ul class="first_class_ul"><li>实现构建器模式的一种方式</li><ul class="second_class_ul"><li>结构体定义</li><li>构建器实现</li><li>主函数</li><li>目的</li></ul><li>使用Bon构建器</li><ul class="second_class_ul"></ul><li>参考资料</li><ul class="second_class_ul"></ul></ul></div><p class="maodian"></p><h2>实现构建器模式的一种方式</h2><p>这里参考资料2的文章,修改部分代码后如下。这段代码的目的是使用构建器模式创建和初始化Person对象。以下是各部分的解释:</p>
<p class="maodian"></p><h3>结构体定义</h3>
<ul><li>Person: 定义了一个结构体,包含name、age、address和sex四个字段。address和sex是可选的</li><li>PersonBuilder: 用于逐步构建Person对象的构建器结构体</li></ul>
<p class="maodian"></p><h3>构建器实现</h3>
<ul><li>new: 创建一个新的PersonBuilder实例,初始化name和age,其他字段为None</li><li>with_address: 设置address字段,返回修改后的构建器</li><li>with_sex: 设置sex字段,返回修改后的构建器</li><li>build: 生成最终的Person对象</li></ul>
<p class="maodian"></p><h3>主函数</h3>
<ul><li>使用PersonBuilder构建一个Person对象,设置name、age、address和sex</li><li>打印Person对象及其各个字段的值</li></ul>
<p class="maodian"></p><h3>目的</h3>
<ul><li>封装对象创建过程: 使用构建器模式来管理对象初始化的复杂性</li><li>可选字段设置: 允许灵活地设置可选字段,而不必在创建对象时提供所有信息</li><li>链式调用: 提供链式调用的接口,使代码更简洁易读</li></ul>
<div class="jb51code"><pre class="brush:plain;">#
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");
}
}</pre></div>
<div class="jb51code"><pre class="brush:plain;">Person { name: "Alice", age: 30, address: Some("Wonderland"), sex: Some("Female") }
Name: Alice
Age: 30
Address: Wonderland
Sex: Female</pre></div>
<p class="maodian"></p><h2>使用Bon构建器</h2>
<p>了解完Rust如何实现构建器模式后,如果我们想要在实际项目中使用构建器,当然可以不用自己手动实现,可以使用第三方库Bon,引入方式如下</p>
<p>Cargo.toml</p>
<div class="jb51code"><pre class="brush:plain;">
bon = "1.1.0"</pre></div>
<div class="jb51code"><pre class="brush:plain;">use bon::bon;
#
struct Person {
name: String,
age: u32,
address: Option<String>,
sex: Option<String>,
}
# // 使用 Bon 库的宏
impl Person {
#
fn new(name: String, age: u32) -> Self {
Self {
name,
age,
address: None,
sex: None,
}
}
#
fn with_address(&mut self, address: String) {
self.address = Some(address);
}
#
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");
}
}</pre></div>
<div class="jb51code"><pre class="brush:plain;">Person { name: "Alice", age: 30, address: Some("Wonderland"), sex: Some("Female") }
Name: Alice
Age: 30
Address: Wonderland
Sex: Female</pre></div>
<p>运行结果和手动实现方式一致。当然这种方式更为简洁,可以省略很多代码实现,容易维护和阅读,更推荐使用</p>
<p>参考资料3,Bon除了结构体的构建器和关联方法的构建器,还有函数的构建器</p>
<div class="jb51code"><pre class="brush:plain;">fn main() {
#
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");
}
}</pre></div>
<div class="jb51code"><pre class="brush:plain;">Assertion passed: Hello Bon with age 24!</pre></div>
<p class="maodian"></p><h2>参考资料</h2>
<p>How to do named function arguments in Rust</p>
<p>Rust 中的建造者模式 (qq.com)</p>
<p>Overview | Bon (elastio.github.io)</p>
<p>到此这篇关于Rust实现构建器模式和使用Bon库中的构建器的文章就介绍到这了,更多相关Rust构建器模式内容请搜索琼殿技术社区以前的文章或继续浏览下面的相关文章希望大家以后多多支持琼殿技术社区!</p>
<div class="art_xg">
<b>您可能感兴趣的文章:</b><ul><li>Rust使用csv crate构建CSV文件读取器的全过程</li><li>Rust初体验:手把手教你构建‘Hello, World!’</li></ul>
</div>
</div>
<!--endmain-->
頁:
[1]