Skip to content

Instantly share code, notes, and snippets.

@dumindu
Last active January 8, 2017 10:48
Show Gist options
  • Save dumindu/9a2a7a54723de1134cb64a7ab38acd7c to your computer and use it in GitHub Desktop.
Save dumindu/9a2a7a54723de1134cb64a7ab38acd7c to your computer and use it in GitHub Desktop.
// 01 - - - - - - - - - - - - - - - - - - - - - -
fn getIdByUsername(username: &str) -> Option<usize> {
//if username can be found in the system, set userId
return Some(userId);
//else
None
}
//💭 So on above function, instead of setting return type as usize
// set return type as Option<usize>
//Instead of return userId, return Some(userId)
// else None (💡remember? last return statement no need return keyword and ending ;)
// 02 - - - - - - - - - - - - - - - - - - - - - -
struct Task {
title: String,
assignee: Option<Person>,
}
//💭 Instead of assignee: Person, we use Option<Person>
//Because the task has not been assigned to a specific person
// - - - - - - - - - - - - - - - - - - - - - - -
//when using Option types as return types on functions
// we can use pattern matching to catch the relevant return type(Some/None) when calling them
fn main() {
let username = "anonymous"
match getIdByUsername(username) {
None => println!("User not found"),
Some(i) => println!("User Id: {}", i)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment