Index
- Guessing Game
- Common Programming Concepts
- Understanding Ownership
- Using Structs
- Enums and Pattern Matching
- Managing Growing Projects with Packages, Crates, and Modules
- Defining Modules to Control Scope and Privacy
- Paths for Referring to an Item in the Module Tree
- Bringing Paths into Scope with the use Keyword
- Separating Modules into Different Files
- Common Collections
- Error Handling
- Generic Types, Traits, and Lifetimes
- Writing Automated Tests
- Object Oriented Programming
- Adding dependancies
- Option Take
- RefCell
- mem
- Data Structure
- Recipe
- Semi colon
- Calling rust from python
- Default
- Crytocurrency With rust
- Function chaining
- Question Mark Operator
- Tests with println
- lib and bin
- Append vector to hash map
- Random Number
- uuid4
- uwrap and option
- Blockchain with Rust
- Near Protocol
- Actix-web
Function chaining
https://stackoverflow.com/questions/41617182/how-to-write-an-idiomatic-build-pattern-with-chained-method-calls-in-rust#[derive(Debug, Eq, PartialEq)]
struct Foo {
value: usize,
}
struct FooBuilder {
foos: usize,
bars: usize,
}
impl FooBuilder {
fn new() -> FooBuilder {
FooBuilder {
foos: 0,
bars: 0,
}
}
fn set_foos(mut self, foos: usize) -> FooBuilder {
self.foos = foos;
self
}
fn set_bars(mut self, bars: usize) -> FooBuilder {
self.bars = bars;
self
}
fn build(&self) -> Foo {
Foo {
value: self.foos + self.bars,
}
}
}
fn main() {
let foo = FooBuilder::new()
.set_foos(2)
.set_bars(3)
.build();
assert_eq!(foo, Foo { value: 5 });
}
struct Foo {
value: usize,
}
struct FooBuilder {
foos: usize,
bars: usize,
}
impl FooBuilder {
fn new() -> FooBuilder {
FooBuilder {
foos: 0,
bars: 0,
}
}
fn set_foos(mut self, foos: usize) -> FooBuilder {
self.foos = foos;
self
}
fn set_bars(mut self, bars: usize) -> FooBuilder {
self.bars = bars;
self
}
fn build(&self) -> Foo {
Foo {
value: self.foos + self.bars,
}
}
}
fn main() {
let foo = FooBuilder::new()
.set_foos(2)
.set_bars(3)
.build();
assert_eq!(foo, Foo { value: 5 });
}