Skip to content

Instantly share code, notes, and snippets.

@TheNeikos
Created November 26, 2017 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheNeikos/15a6edb4aa9fb90e562db11f93fe1e00 to your computer and use it in GitHub Desktop.
Save TheNeikos/15a6edb4aa9fb90e562db11f93fe1e00 to your computer and use it in GitHub Desktop.
Files for my Blog Post rust references
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)?)
}
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