2020-12-25 14:16:02 +00:00
<!DOCTYPE HTML>
< html lang = "en" class = "sidebar-visible no-js light" >
< head >
<!-- Book generated using mdBook -->
< meta charset = "UTF-8" >
2021-02-09 09:07:07 +00:00
< title > Default and the builder pattern - Easy Rust< / title >
2021-07-17 16:29:15 +00:00
2020-12-25 14:16:02 +00:00
<!-- Custom HTML head -->
< meta content = "text/html; charset=utf-8" http-equiv = "Content-Type" >
< meta name = "description" content = "" >
< meta name = "viewport" content = "width=device-width, initial-scale=1" >
< meta name = "theme-color" content = "#ffffff" / >
2021-07-17 16:29:15 +00:00
< link rel = "icon" href = "favicon.svg" >
< link rel = "shortcut icon" href = "favicon.png" >
< link rel = "stylesheet" href = "css/variables.css" >
2020-12-25 14:16:02 +00:00
< link rel = "stylesheet" href = "css/general.css" >
< link rel = "stylesheet" href = "css/chrome.css" >
2021-07-17 16:29:15 +00:00
< link rel = "stylesheet" href = "css/print.css" media = "print" >
2020-12-25 14:16:02 +00:00
<!-- Fonts -->
< link rel = "stylesheet" href = "FontAwesome/css/font-awesome.css" >
2021-07-17 16:29:15 +00:00
< link rel = "stylesheet" href = "fonts/fonts.css" >
2020-12-25 14:16:02 +00:00
<!-- Highlight.js Stylesheets -->
< link rel = "stylesheet" href = "highlight.css" >
< link rel = "stylesheet" href = "tomorrow-night.css" >
< link rel = "stylesheet" href = "ayu-highlight.css" >
<!-- Custom theme stylesheets -->
2021-07-17 16:29:15 +00:00
< / head >
2020-12-25 14:16:02 +00:00
< body >
<!-- Provide site root to javascript -->
< script type = "text/javascript" >
var path_to_root = "";
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
< / script >
<!-- Work around some values being stored in localStorage wrapped in quotes -->
< script type = "text/javascript" >
try {
var theme = localStorage.getItem('mdbook-theme');
var sidebar = localStorage.getItem('mdbook-sidebar');
if (theme.startsWith('"') & & theme.endsWith('"')) {
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
}
if (sidebar.startsWith('"') & & sidebar.endsWith('"')) {
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
}
} catch (e) { }
< / script >
<!-- Set the theme before any content is loaded, prevents flash -->
< script type = "text/javascript" >
var theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
var html = document.querySelector('html');
html.classList.remove('no-js')
html.classList.remove('light')
html.classList.add(theme);
html.classList.add('js');
< / script >
<!-- Hide / unhide sidebar before it is displayed -->
< script type = "text/javascript" >
var html = document.querySelector('html');
var sidebar = 'hidden';
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible';
}
html.classList.remove('sidebar-visible');
html.classList.add("sidebar-" + sidebar);
< / script >
< nav id = "sidebar" class = "sidebar" aria-label = "Table of contents" >
< div class = "sidebar-scrollbox" >
2021-07-17 16:29:15 +00:00
< ol class = "chapter" > < li class = "chapter-item expanded " > < a href = "Chapter_0.html" > < strong aria-hidden = "true" > 1.< / strong > Updates< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_1.html" > < strong aria-hidden = "true" > 2.< / strong > Introduction< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_2.html" > < strong aria-hidden = "true" > 3.< / strong > Who am I?< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_3.html" > < strong aria-hidden = "true" > 4.< / strong > Writing Rust in Easy English< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_4.html" > < strong aria-hidden = "true" > 5.< / strong > Rust Playground< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_5.html" > < strong aria-hidden = "true" > 6.< / strong > 🚧 and ⚠️< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_6.html" > < strong aria-hidden = "true" > 7.< / strong > Comments< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_7.html" > < strong aria-hidden = "true" > 8.< / strong > Types< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_8.html" > < strong aria-hidden = "true" > 9.< / strong > Type inference< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_9.html" > < strong aria-hidden = "true" > 10.< / strong > Printing 'hello, world!'< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_10.html" > < strong aria-hidden = "true" > 11.< / strong > Display and debug< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_11.html" > < strong aria-hidden = "true" > 12.< / strong > Mutability (changing)< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_12.html" > < strong aria-hidden = "true" > 13.< / strong > The stack, the heap, and pointers< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_13.html" > < strong aria-hidden = "true" > 14.< / strong > More about printing< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_14.html" > < strong aria-hidden = "true" > 15.< / strong > Strings< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_15.html" > < strong aria-hidden = "true" > 16.< / strong > const and static< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_16.html" > < strong aria-hidden = "true" > 17.< / strong > More on references< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_17.html" > < strong aria-hidden = "true" > 18.< / strong > Mutable references< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_18.html" > < strong aria-hidden = "true" > 19.< / strong > Giving references to functions< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_19.html" > < strong aria-hidden = "true" > 20.< / strong > Copy types< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_20.html" > < strong aria-hidden = "true" > 21.< / strong > Collection types< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_21.html" > < strong aria-hidden = "true" > 22.< / strong > Vectors< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_22.html" > < strong aria-hidden = "true" > 23.< / strong > Tuples< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_23.html" > < strong aria-hidden = "true" > 24.< / strong > Control flow< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_24.html" > < strong aria-hidden = "true" > 25.< / strong > Structs< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_25.html" > < strong aria-hidden = "true" > 26.< / strong > Enums< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_26.html" > < strong aria-hidden = "true" > 27.< / strong > Loops< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_27.html" > < strong aria-hidden = "true" > 28.< / strong > Implementing structs and enums< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_28.html" > < strong aria-hidden = "true" > 29.< / strong > Destructuring< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_29.html" > < strong aria-hidden = "true" > 30.< / strong > References and the dot operator< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_30.html" > < strong aria-hidden = "true" > 31.< / strong > Generics< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_31.html" > < strong aria-hidden = "true" > 32.< / strong > Option and Result< / a > < / li > < li class = "chapter-item expanded " > < a href = "Chapter_32.html" > < strong aria-h
2020-12-25 14:16:02 +00:00
< div id = "sidebar-resize-handle" class = "sidebar-resize-handle" > < / div >
< / nav >
< div id = "page-wrapper" class = "page-wrapper" >
< div class = "page" >
< div id = "menu-bar-hover-placeholder" > < / div >
< div id = "menu-bar" class = "menu-bar sticky bordered" >
< div class = "left-buttons" >
< button id = "sidebar-toggle" class = "icon-button" type = "button" title = "Toggle Table of Contents" aria-label = "Toggle Table of Contents" aria-controls = "sidebar" >
< i class = "fa fa-bars" > < / i >
< / button >
< button id = "theme-toggle" class = "icon-button" type = "button" title = "Change theme" aria-label = "Change theme" aria-haspopup = "true" aria-expanded = "false" aria-controls = "theme-list" >
< i class = "fa fa-paint-brush" > < / i >
< / button >
< ul id = "theme-list" class = "theme-popup" aria-label = "Themes" role = "menu" >
< li role = "none" > < button role = "menuitem" class = "theme" id = "light" > Light (default)< / button > < / li >
< li role = "none" > < button role = "menuitem" class = "theme" id = "rust" > Rust< / button > < / li >
< li role = "none" > < button role = "menuitem" class = "theme" id = "coal" > Coal< / button > < / li >
< li role = "none" > < button role = "menuitem" class = "theme" id = "navy" > Navy< / button > < / li >
< li role = "none" > < button role = "menuitem" class = "theme" id = "ayu" > Ayu< / button > < / li >
< / ul >
2021-07-17 16:29:15 +00:00
< button id = "search-toggle" class = "icon-button" type = "button" title = "Search. (Shortkey: s)" aria-label = "Toggle Searchbar" aria-expanded = "false" aria-keyshortcuts = "S" aria-controls = "searchbar" >
2020-12-25 14:16:02 +00:00
< i class = "fa fa-search" > < / i >
< / button >
2021-07-17 16:29:15 +00:00
< / div >
2020-12-25 14:16:02 +00:00
< h1 class = "menu-title" > Easy Rust< / h1 >
< div class = "right-buttons" >
2021-07-17 16:29:15 +00:00
< a href = "print.html" title = "Print this book" aria-label = "Print this book" >
2020-12-25 14:16:02 +00:00
< i id = "print-button" class = "fa fa-print" > < / i >
< / a >
2021-07-17 16:29:15 +00:00
2020-12-25 14:16:02 +00:00
< / div >
< / div >
2021-07-17 16:29:15 +00:00
< div id = "search-wrapper" class = "hidden" >
2020-12-25 14:16:02 +00:00
< form id = "searchbar-outer" class = "searchbar-outer" >
2021-05-23 04:18:41 +00:00
< input type = "search" id = "searchbar" name = "searchbar" placeholder = "Search this book ..." aria-controls = "searchresults-outer" aria-describedby = "searchresults-header" >
2020-12-25 14:16:02 +00:00
< / form >
< div id = "searchresults-outer" class = "searchresults-outer hidden" >
< div id = "searchresults-header" class = "searchresults-header" > < / div >
< ul id = "searchresults" >
< / ul >
< / div >
< / div >
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
< script type = "text/javascript" >
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
});
< / script >
< div id = "content" class = "content" >
< main >
2021-02-24 06:13:19 +00:00
< h2 id = "default-and-the-builder-pattern" > < a class = "header" href = "#default-and-the-builder-pattern" > Default and the builder pattern< / a > < / h2 >
2021-02-09 09:07:07 +00:00
< p > You can implement the < code > Default< / code > trait to give values to a < code > struct< / code > or < code > enum< / code > that you think will be most common. The builder pattern works nicely with this to let users easily make changes when they want. First let's look at < code > Default< / code > . Actually, most general types in Rust already have < code > Default< / code > . They are not surprising: 0, " " (empty strings), < code > false< / code > , etc.< / p >
< pre > < pre class = "playground" > < code class = "language-rust" > fn main() {
let default_i8: i8 = Default::default();
let default_str: String = Default::default();
let default_bool: bool = Default::default();
println!(" '{}', '{}', '{}'" , default_i8, default_str, default_bool);
2020-12-25 14:16:02 +00:00
}
< / code > < / pre > < / pre >
2021-02-09 09:07:07 +00:00
< p > This prints < code > '0', '', 'false'< / code > .< / p >
< p > So < code > Default< / code > is like the < code > new< / code > function except you don't have to enter anything. First we will make a < code > struct< / code > that doesn't implement < code > Default< / code > yet. It has a < code > new< / code > function which we use to make a character named Billy with some stats.< / p >
< pre > < pre class = "playground" > < code class = "language-rust" > struct Character {
name: String,
age: u8,
height: u32,
weight: u32,
lifestate: LifeState,
}
enum LifeState {
Alive,
Dead,
NeverAlive,
Uncertain
}
impl Character {
fn new(name: String, age: u8, height: u32, weight: u32, alive: bool) -> Self {
Self {
name,
age,
height,
weight,
lifestate: if alive { LifeState::Alive } else { LifeState::Dead },
}
}
}
2020-12-25 14:16:02 +00:00
fn main() {
2021-02-09 09:07:07 +00:00
let character_1 = Character::new(" Billy" .to_string(), 15, 170, 70, true);
2020-12-25 14:16:02 +00:00
}
< / code > < / pre > < / pre >
2021-02-09 09:07:07 +00:00
< p > But maybe in our world we want most of the characters to be named Billy, age 15, height 170, weight 70, and alive. We can implement < code > Default< / code > so that we can just write < code > Character::default()< / code > . It looks like this:< / p >
< pre > < pre class = "playground" > < code class = "language-rust" > #[derive(Debug)]
struct Character {
name: String,
age: u8,
height: u32,
weight: u32,
lifestate: LifeState,
}
#[derive(Debug)]
enum LifeState {
Alive,
Dead,
NeverAlive,
Uncertain,
}
2020-12-25 14:16:02 +00:00
2021-02-09 09:07:07 +00:00
impl Character {
fn new(name: String, age: u8, height: u32, weight: u32, alive: bool) -> Self {
Self {
name,
age,
height,
weight,
lifestate: if alive {
LifeState::Alive
} else {
LifeState::Dead
},
}
}
}
impl Default for Character {
fn default() -> Self {
Self {
name: " Billy" .to_string(),
age: 15,
height: 170,
weight: 70,
lifestate: LifeState::Alive,
}
}
}
2020-12-25 14:16:02 +00:00
fn main() {
2021-02-09 09:07:07 +00:00
let character_1 = Character::default();
println!(
" The character {:?} is {:?} years old." ,
character_1.name, character_1.age
);
2020-12-25 14:16:02 +00:00
}
< / code > < / pre > < / pre >
2021-02-09 09:07:07 +00:00
< p > It prints < code > The character " Billy" is 15 years old.< / code > Much easier!< / p >
< p > Now comes the builder pattern. We will have many Billys, so we will keep the default. But a lot of other characters will be only a bit different. The builder pattern lets us chain very small methods to change one value each time. Here is one such method for < code > Character< / code > :< / p >
< pre > < pre class = "playground" > < code class = "language-rust" >
< span class = "boring" > #![allow(unused)]
< / span > < span class = "boring" > fn main() {
< / span > fn height(mut self, height: u32) -> Self { // 🚧
self.height = height;
self
}
< span class = "boring" > }
< / span > < / code > < / pre > < / pre >
< p > Make sure to notice that it takes a < code > mut self< / code > . We saw this once before, and it is not a mutable reference (< code > & mut self< / code > ). It takes ownership of < code > Self< / code > and with < code > mut< / code > it will be mutable, even if it wasn't mutable before. That's because < code > .height()< / code > has full ownership and nobody else can touch it, so it is safe to be mutable. Then it just changes < code > self.height< / code > and returns < code > Self< / code > (which is < code > Character< / code > ).< / p >
< p > So let's have three of these builder methods. They are almost the same:< / p >
< pre > < pre class = "playground" > < code class = "language-rust" >
< span class = "boring" > #![allow(unused)]
< / span > < span class = "boring" > fn main() {
< / span > fn height(mut self, height: u32) -> Self { // 🚧
self.height = height;
self
}
fn weight(mut self, weight: u32) -> Self {
self.weight = weight;
self
}
fn name(mut self, name: & str) -> Self {
self.name = name.to_string();
self
}
< span class = "boring" > }
< / span > < / code > < / pre > < / pre >
< p > Each one of those changes one variable and gives < code > Self< / code > back: this is what you see in the builder pattern. So now we can write something like this to make a character: < code > let character_1 = Character::default().height(180).weight(60).name(" Bobby" );< / code > . If you are building a library for someone else to use, this can make it easy for them. It's easy for the end user because it almost looks like natural English: " Give me a default character but with height of 180, weight of 60, and name of Bobby." So far our code looks like this:< / p >
< pre > < pre class = "playground" > < code class = "language-rust" > #[derive(Debug)]
struct Character {
name: String,
age: u8,
height: u32,
weight: u32,
lifestate: LifeState,
}
#[derive(Debug)]
enum LifeState {
Alive,
Dead,
NeverAlive,
Uncertain,
}
impl Character {
fn new(name: String, age: u8, height: u32, weight: u32, alive: bool) -> Self {
Self {
name,
age,
height,
weight,
lifestate: if alive {
LifeState::Alive
} else {
LifeState::Dead
},
}
}
fn height(mut self, height: u32) -> Self {
self.height = height;
self
}
fn weight(mut self, weight: u32) -> Self {
self.weight = weight;
self
}
fn name(mut self, name: & str) -> Self {
self.name = name.to_string();
self
}
}
impl Default for Character {
fn default() -> Self {
Self {
name: " Billy" .to_string(),
age: 15,
height: 170,
weight: 70,
lifestate: LifeState::Alive,
}
}
2020-12-25 14:16:02 +00:00
}
fn main() {
2021-02-09 09:07:07 +00:00
let character_1 = Character::default().height(180).weight(60).name(" Bobby" );
println!(" {:?}" , character_1);
2020-12-25 14:16:02 +00:00
}
< / code > < / pre > < / pre >
2021-02-09 09:07:07 +00:00
< p > One last method to add is usually called < code > .build()< / code > . This method is a sort of final check. When you give a user a method like < code > .height()< / code > you can make sure that they only put in a < code > u32()< / code > , but what if they enter 5000 for height? That might not be okay in the game you are making. We will use a final method called < code > .build()< / code > that returns a < code > Result< / code > . Inside it we will check if the user input is okay, and if it is, we will return an < code > Ok(Self)< / code > .< / p >
< p > First though let's change the < code > .new()< / code > method. We don't want users to be free to create any kind of character anymore. So we'll move the values from < code > impl Default< / code > to < code > .new()< / code > . And now < code > .new()< / code > doesn't take any input.< / p >
< pre > < pre class = "playground" > < code class = "language-rust" >
< span class = "boring" > #![allow(unused)]
< / span > < span class = "boring" > fn main() {
< / span > fn new() -> Self { // 🚧
Self {
name: " Billy" .to_string(),
age: 15,
height: 170,
weight: 70,
lifestate: LifeState::Alive,
}
}
< span class = "boring" > }
< / span > < / code > < / pre > < / pre >
< p > That means we don't need < code > impl Default< / code > anymore, because < code > .new()< / code > has all the default values. So we can delete < code > impl Default< / code > .< / p >
< p > Now our code looks like this:< / p >
< pre > < pre class = "playground" > < code class = "language-rust" > #[derive(Debug)]
struct Character {
name: String,
age: u8,
height: u32,
weight: u32,
lifestate: LifeState,
}
#[derive(Debug)]
enum LifeState {
Alive,
Dead,
NeverAlive,
Uncertain,
}
impl Character {
fn new() -> Self {
Self {
name: " Billy" .to_string(),
age: 15,
height: 170,
weight: 70,
lifestate: LifeState::Alive,
}
}
fn height(mut self, height: u32) -> Self {
self.height = height;
self
}
fn weight(mut self, weight: u32) -> Self {
self.weight = weight;
self
}
fn name(mut self, name: & str) -> Self {
self.name = name.to_string();
self
}
2020-12-25 14:16:02 +00:00
}
fn main() {
2021-02-09 09:07:07 +00:00
let character_1 = Character::new().height(180).weight(60).name(" Bobby" );
println!(" {:?}" , character_1);
2020-12-25 14:16:02 +00:00
}
< / code > < / pre > < / pre >
2021-02-09 09:07:07 +00:00
< p > This prints the same thing: < code > Character { name: " Bobby" , age: 15, height: 180, weight: 60, lifestate: Alive }< / code > .< / p >
< p > We are almost ready to write the method < code > .build()< / code > , but there is one problem: how do we make the user use it? Right now a user can write < code > let x = Character::new().height(76767);< / code > and get a < code > Character< / code > . There are many ways to do this, and maybe you can imagine your own. But we will add a < code > can_use: bool< / code > value to < code > Character< / code > .< / p >
< pre > < pre class = "playground" > < code class = "language-rust" >
< span class = "boring" > #![allow(unused)]
< / span > < span class = "boring" > fn main() {
< / span > #[derive(Debug)] // 🚧
struct Character {
name: String,
age: u8,
height: u32,
weight: u32,
lifestate: LifeState,
can_use: bool, // Set whether the user can use the character
}
\\ Cut other code
fn new() -> Self {
Self {
name: " Billy" .to_string(),
age: 15,
height: 170,
weight: 70,
lifestate: LifeState::Alive,
can_use: true, // .new() always gives a good character, so it's true
}
}
< span class = "boring" > }
< / span > < / code > < / pre > < / pre >
< p > And for the other methods like < code > .height()< / code > , we will set < code > can_use< / code > to < code > false< / code > . Only < code > .build()< / code > will set it to < code > true< / code > again, so now the user has to do a final check with < code > .build()< / code > . We will make sure that < code > height< / code > is not above 200 and < code > weight< / code > is not above 300. Also, in our game there is a bad word called < code > smurf< / code > that we don't want characters to use.< / p >
< p > Our < code > .build()< / code > method looks like this:< / p >
< pre > < pre class = "playground" > < code class = "language-rust" >
< span class = "boring" > #![allow(unused)]
< / span > < span class = "boring" > fn main() {
< / span > fn build(mut self) -> Result< Character, String> { // 🚧
if self.height < 200 & & self.weight < 300 & & !self.name.to_lowercase().contains(" smurf" ) {
self.can_use = true;
Ok(self)
} else {
Err(" Could not create character. Characters must have:
1) Height below 200
2) Weight below 300
3) A name that is not Smurf (that is a bad word)"
.to_string())
}
}
< span class = "boring" > }
< / span > < / code > < / pre > < / pre >
< p > < code > !self.name.to_lowercase().contains(" smurf" )< / code > makes sure that the user doesn't write something like " SMURF" or " IamSmurf" . It makes the whole < code > String< / code > lowercase (small letters), and checks for < code > .contains()< / code > instead of < code > ==< / code > . And the < code > !< / code > in front means " not" .< / p >
< p > If everything is okay, we set < code > can_use< / code > to < code > true< / code > , and give the character to the user inside < code > Ok< / code > .< / p >
< p > Now that our code is done, we will create three characters that don't work, and one character that does work. The final code looks like this:< / p >
< pre > < pre class = "playground" > < code class = "language-rust" > #[derive(Debug)]
struct Character {
name: String,
age: u8,
height: u32,
weight: u32,
lifestate: LifeState,
can_use: bool, // Here is the new value
2020-12-25 14:16:02 +00:00
}
2021-02-09 09:07:07 +00:00
#[derive(Debug)]
enum LifeState {
Alive,
Dead,
NeverAlive,
Uncertain,
}
2020-12-25 14:16:02 +00:00
2021-02-09 09:07:07 +00:00
impl Character {
fn new() -> Self {
Self {
name: " Billy" .to_string(),
age: 15,
height: 170,
weight: 70,
lifestate: LifeState::Alive,
can_use: true, // .new() makes a fine character, so it is true
}
}
fn height(mut self, height: u32) -> Self {
self.height = height;
self.can_use = false; // Now the user can't use the character
self
}
fn weight(mut self, weight: u32) -> Self {
self.weight = weight;
self.can_use = false;
self
}
fn name(mut self, name: & str) -> Self {
self.name = name.to_string();
self.can_use = false;
self
}
fn build(mut self) -> Result< Character, String> {
if self.height < 200 & & self.weight < 300 & & !self.name.to_lowercase().contains(" smurf" ) {
self.can_use = true; // Everything is okay, so set to true
Ok(self) // and return the character
} else {
Err(" Could not create character. Characters must have:
1) Height below 200
2) Weight below 300
3) A name that is not Smurf (that is a bad word)"
.to_string())
}
}
2020-12-25 14:16:02 +00:00
}
fn main() {
2021-02-09 09:07:07 +00:00
let character_with_smurf = Character::new().name(" Lol I am Smurf!!" ).build(); // This one contains " smurf" - not okay
let character_too_tall = Character::new().height(400).build(); // Too tall - not okay
let character_too_heavy = Character::new().weight(500).build(); // Too heavy - not okay
let okay_character = Character::new()
.name(" Billybrobby" )
.height(180)
.weight(100)
.build(); // This character is okay. Name is fine, height and weight are fine
// Now they are not Character, they are Result< Character, String> . So let's put them in a Vec so we can see them:
let character_vec = vec![character_with_smurf, character_too_tall, character_too_heavy, okay_character];
for character in character_vec { // Now we will print the character if it's Ok, and print the error if it's Err
match character {
Ok(character_info) => println!(" {:?}" , character_info),
Err(err_info) => println!(" {}" , err_info),
}
println!(); // Then add one more line
}
2020-12-25 14:16:02 +00:00
}
< / code > < / pre > < / pre >
2021-02-09 09:07:07 +00:00
< p > This will print:< / p >
< pre > < code class = "language-text" > Could not create character. Characters must have:
1) Height below 200
2) Weight below 300
3) A name that is not Smurf (that is a bad word)
Could not create character. Characters must have:
1) Height below 200
2) Weight below 300
3) A name that is not Smurf (that is a bad word)
Could not create character. Characters must have:
1) Height below 200
2) Weight below 300
3) A name that is not Smurf (that is a bad word)
Character { name: " Billybrobby" , age: 15, height: 180, weight: 100, lifestate: Alive, can_use: true }
< / code > < / pre >
2020-12-25 14:16:02 +00:00
< / main >
< nav class = "nav-wrapper" aria-label = "Page navigation" >
<!-- Mobile navigation buttons -->
2021-07-17 16:29:15 +00:00
< a rel = "prev" href = "Chapter_54.html" class = "mobile-nav-chapters previous" title = "Previous chapter" aria-label = "Previous chapter" aria-keyshortcuts = "Left" >
2020-12-25 14:16:02 +00:00
< i class = "fa fa-angle-left" > < / i >
< / a >
2021-07-17 16:29:15 +00:00
< a rel = "next" href = "Chapter_56.html" class = "mobile-nav-chapters next" title = "Next chapter" aria-label = "Next chapter" aria-keyshortcuts = "Right" >
2020-12-25 14:16:02 +00:00
< i class = "fa fa-angle-right" > < / i >
< / a >
< div style = "clear: both" > < / div >
< / nav >
< / div >
< / div >
< nav class = "nav-wide-wrapper" aria-label = "Page navigation" >
2021-07-17 16:29:15 +00:00
< a rel = "prev" href = "Chapter_54.html" class = "nav-chapters previous" title = "Previous chapter" aria-label = "Previous chapter" aria-keyshortcuts = "Left" >
2020-12-25 14:16:02 +00:00
< i class = "fa fa-angle-left" > < / i >
< / a >
2021-07-17 16:29:15 +00:00
< a rel = "next" href = "Chapter_56.html" class = "nav-chapters next" title = "Next chapter" aria-label = "Next chapter" aria-keyshortcuts = "Right" >
2020-12-25 14:16:02 +00:00
< i class = "fa fa-angle-right" > < / i >
< / a >
2021-07-17 16:29:15 +00:00
< / nav >
2020-12-25 14:16:02 +00:00
< / div >
2021-07-17 16:29:15 +00:00
< script type = "text/javascript" >
2020-12-25 14:16:02 +00:00
window.playground_copyable = true;
< / script >
2021-07-17 16:29:15 +00:00
< script src = "elasticlunr.min.js" type = "text/javascript" charset = "utf-8" > < / script >
2020-12-25 14:16:02 +00:00
< script src = "mark.min.js" type = "text/javascript" charset = "utf-8" > < / script >
< script src = "searcher.js" type = "text/javascript" charset = "utf-8" > < / script >
< script src = "clipboard.min.js" type = "text/javascript" charset = "utf-8" > < / script >
< script src = "highlight.js" type = "text/javascript" charset = "utf-8" > < / script >
< script src = "book.js" type = "text/javascript" charset = "utf-8" > < / script >
<!-- Custom JS scripts -->
< / body >
< / html >