Created
December 10, 2016 23:19
-
-
Save hoodie/0a3593981a4d651371ed63eb2e8f897c to your computer and use it in GitHub Desktop.
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
// optional.cpp | |
#include <experimental/optional> | |
#include <iostream> | |
#include <vector> | |
std::experimental::optional<int> getFirst(const std::vector<int>& vec){ | |
if (!vec.empty()) return std::experimental::optional<int>(vec[0]); | |
else return std::experimental::optional<int>(); | |
} | |
int main(){ | |
std::vector<int> myVec{1, 2, 3}; | |
std::vector<int> myEmptyVec; | |
auto myInt= getFirst(myVec); | |
if (myInt){ | |
std::cout << "*myInt: " << *myInt << std::endl; | |
std::cout << "myInt.value(): " << myInt.value() << std::endl; | |
std::cout << "myInt.value_or(2017):" << myInt.value_or(2017) << std::endl; | |
} | |
std::cout << std::endl; | |
auto myEmptyInt= getFirst(myEmptyVec); | |
if (!myEmptyInt){ | |
std::cout << "myEmptyInt.value_or(2017):" << myEmptyInt.value_or(2017) << std::endl; | |
} | |
} |
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
// optional.rs | |
#![allow(non_snake_case)] | |
//no includes needed, its all in the prelude | |
// no convoluted messy function signatures | |
// takes anything that can be dereffed as slice, not just Vec | |
// no more leading `return` statements | |
fn getFirst(vec: &[i32]) -> Option<i32> { | |
if !vec.is_empty() { | |
Some(vec[0]) | |
} else { | |
None | |
} | |
} | |
fn main(){ | |
let myVec = vec![1, 2, 3]; //variable names are always in front | |
let myEmptyVec = Vec::new(); | |
let myInt = getFirst(&myVec); // I know if I pass by reference | |
if myInt.is_some() { // you should instead destructure this with `if let` | |
println!("myInt.unwrap(): {}", myInt.unwrap() ); // don't do this at home | |
println!("myInt.unwrap_or(2017): {}", myInt.unwrap_or(2017)); | |
} | |
let myEmptyInt = getFirst(&myEmptyVec); | |
if myEmptyInt.is_none() { | |
println!("myEmptyInt.value_or(2017): {}", myEmptyInt.unwrap_or(2017)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment