Created
June 14, 2018 13:02
-
-
Save JelteF/917b6d233556e0de11de11b651490fb5 to your computer and use it in GitHub Desktop.
A mutating plus one function in 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
struct MyNumber { | |
n: i64, | |
} | |
// &mut MyNumber is the type for a mutable reference to MyNumber | |
fn plus_one(number: &mut MyNumber) { | |
number.n += 1; | |
} | |
// Rust doesn’t have nil-able pointers at all in most code (they do exist, | |
// but mainly for interoperation with C). | |
// Instead it has an Option type to signal missing values. | |
// Option<&mut MyNumber> is an enum that can be either: | |
// - None: Rust version of nil | |
// - Some(MyNumber): Some is just the name for the enum variant and MyNumber | |
// can be extracted from it as shown in the function | |
// | |
// Errors are also slightly different from go errors, since they use a Result | |
// type that is similar to the Option type. | |
// Result<(), &'static str> is an enum that can be either: | |
// - Ok(()): Indicates a success, without a return value, because () is | |
// an empty tuple | |
// - Err(&'static str): Indicates an error occured and contains a static | |
// string, i.e. one that is part of the source code | |
fn plus_one_nullable(nullabe_number: Option<&mut MyNumber>) -> Result<(), &'static str> { | |
// match is the Rust version of switch and => is the Rust version of case | |
match nullabe_number { | |
None => return Err("number shouldn't be None"), | |
Some(number) => plus_one(number), | |
} | |
return Ok(()); | |
} | |
fn main() { | |
// we need to annotate that number is mut(able), so we can actually change it | |
let mut number = MyNumber { n: 5 }; | |
plus_one(&mut number); | |
println!("{}", number.n); // 6 | |
println!("{:?}", plus_one_nullable(Some(&mut number))); // Ok(()) | |
println!("{}", number.n); // 7 | |
println!("{:?}", plus_one_nullable(None)); // Err("number shouldn\'t be None") | |
println!("{}", number.n); // 7 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment