Created
July 27, 2018 16:16
-
-
Save je6bmq/b09710cc99649c1aff54f96060d19c98 to your computer and use it in GitHub Desktop.
とよぎぃ通信 vol.8 に登場するRustコード例
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
fn main() { | |
// Variable binding | |
let a = 1; // immutable | |
let mut b = 1; //mutable | |
assert_eq!(b, 1); | |
// a = 2; // compile error | |
b = 2; | |
let c: i32 = 1; // i32 is 32 bit signed integer | |
assert_eq!(a, c); // a == c | |
assert_eq!(b, 2); // b == 2 | |
// Option type | |
let some_i32: Option<i32> = Some(3); | |
let none_i32: Option<i32> = None; | |
assert_eq!(some_i32.unwrap(), 3); | |
assert_eq!(none_i32.unwrap_or(1), 1); | |
// Result type | |
let ok_i32: Result<i32, &str> = Ok(3); | |
let err_i32: Result<i32, &str> = Err("error"); | |
assert_eq!(ok_i32.unwrap(), 3); | |
assert_eq!(err_i32.unwrap_or(1), 1); | |
assert!(ok_i32.is_ok()); | |
assert!(err_i32.is_err()); | |
// if-let expression | |
if let Some(x) = some_i32 { | |
println!("{}", x); | |
} else { | |
println!("None"); | |
} // output: "3" | |
if let Some(x) = none_i32 { | |
println!("{}", x); | |
} else { | |
println!("None"); | |
} // output: "None" | |
// match expression | |
match some_i32 { | |
Some(x) => println!("{}", x), | |
None => println!("None"), | |
} // output: "3" | |
match ok_i32 { | |
Ok(x) => println!("{}", x), | |
Err(e) => println!("error info. is: {},", e), | |
} // output: "3" | |
match err_i32 { | |
Ok(x) => println!("{}", x), | |
Err(e) => println!("{}", e), | |
} // output: "error" | |
// match expression (more complicated pattern) | |
match some_i32 { | |
Some(x @ 2...5) => println!("it is {}, it is in two to five", x), | |
Some(_) => println!("it is other value"), | |
None => println!("None"), | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment