Created
November 26, 2017 20:26
-
-
Save TheNeikos/15a6edb4aa9fb90e562db11f93fe1e00 to your computer and use it in GitHub Desktop.
Files for my Blog Post rust references
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::io::{self, Write}; | |
use std::error::Error; | |
struct Person { | |
age: u8, | |
email: String | |
} | |
impl Person { | |
fn new(age: u8, email: String) -> Result<Person, &'static str> { | |
if age > 140 || age < 13 { | |
return Err("This person is too old or too young."); | |
} | |
if email.find("@").is_none() { | |
return Err("Email address contain an @ sign"); | |
} | |
Ok(Person { | |
age: age, | |
email: email | |
}) | |
} | |
} | |
fn main() { | |
let person = match get_person() { | |
Ok(per) => per, | |
Err(e) => return println!("Error: {}", e) | |
}; | |
println!("Hello {}, you are {} years old.", person.email, person.age); | |
} | |
fn get_person() -> Result<Person, Box<Error + 'static>> { | |
let mut buffer = String::new(); | |
let stdin = io::stdin(); | |
print!("Please enter your email: "); | |
io::stdout().flush()?; | |
stdin.read_line(&mut buffer)?; | |
println!(); | |
let email = buffer.trim().into(); | |
buffer = String::new(); | |
print!("Please enter your age: "); | |
io::stdout().flush()?; | |
stdin.read_line(&mut buffer)?; | |
println!(); | |
let age = buffer.trim().parse()?; | |
Ok(Person::new(age, email)?) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::io::{self, Write}; | |
use std::error::Error; | |
struct Person { | |
age: u8, | |
email: String | |
} | |
fn main() { | |
let person = match get_person() { | |
Ok(per) => per, | |
Err(e) => return println!("Error: {}", e) | |
}; | |
println!("Hello {}, you are {} years old.", person.email, person.age); | |
} | |
fn get_person() -> Result<Person, Box<Error + 'static>> { | |
let mut buffer = String::new(); | |
let stdin = io::stdin(); | |
print!("Please enter your email: "); | |
io::stdout().flush()?; | |
stdin.read_line(&mut buffer)?; | |
println!(); | |
let email = buffer.trim().into(); | |
buffer = String::new(); | |
print!("Please enter your age: "); | |
io::stdout().flush()?; | |
stdin.read_line(&mut buffer)?; | |
println!(); | |
let age = buffer.trim().parse()?; | |
Ok(Person { | |
age: age, | |
email: email | |
}) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment