Created
August 4, 2014 10:23
-
-
Save MatejLach/0c9e921901bf9bd0dc23 to your computer and use it in GitHub Desktop.
Showcases integer addition using a function in Rust...
This file contains hidden or 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; | |
fn add(x: int, y: int) -> int { // takes two integers and returns an integer | |
x + y | |
} | |
fn main() { | |
println!("Simple Addition Calculator, written in Rust!"); | |
println!("Enter 1st number: "); | |
let a_input = io::stdin() | |
.read_line() // read user entered input | |
.ok().expect("There was a problem reading your input."); // output this in case of a problem | |
let a_optnum: Option<int> = from_str(a_input.as_slice().trim()); // convert our input string to an Option<int> | |
let a = match a_optnum { | |
Some(a) => a, // strip Option from Option<int>, leaving an int | |
None => { | |
println!("There's no operand!"); // In case there's no number, display this | |
return; // try again | |
} | |
}; | |
println!("Enter 2nd number: "); | |
let b_input = io::stdin() | |
.read_line() | |
.ok().expect("There was a problem reading your input."); | |
let b_optnum: Option<int> = from_str(b_input.as_slice().trim()); | |
let b = match b_optnum { | |
Some(b) => b, | |
None => { | |
println!("There's no operand!"); | |
return; | |
} | |
}; | |
// finally, add the two numbers | |
let result = add(a, b); // notice the ';', otherwise we would end up with a '()' type | |
// print out the result | |
println!("{} + {} = {}", a, b, result); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment