Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.