Skip to content

Instantly share code, notes, and snippets.

@hoodie
Created Dec 10, 2016
Embed
What would you like to do?
// 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;
}
}
// 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