Skip to content

Instantly share code, notes, and snippets.

@gumienny
Last active September 29, 2018 07:52
Show Gist options
  • Save gumienny/d05fa9ed0ae0acae5f004786be876a3e to your computer and use it in GitHub Desktop.
Save gumienny/d05fa9ed0ae0acae5f004786be876a3e to your computer and use it in GitHub Desktop.
fn main() {
    let s1 = String::from("hello");
    let (s2, len) = calculate_length(s1);
    println!("The length of '{}' is {}.", s2, len);
}

fn calculate_length(s: String) -> (String, usize) {
    let length = s.len(); // len() returns the length of a String
    (s, length)
}

fn calculate_length(s: String) -> (String, usize) {
    (s, s.len())
}

fn calculate_length(s: String) -> (usize, String) {
    (s.len(), s)
}

2

struct Foo { a: i32, b: i32, c: i32, d: i32, e: i32 }
let mut x = Foo { a: 1, b: 1, c: 2, d: 2, e: 3 };
let x2 = Foo { e: 4, .. x };

// Useful to update multiple fields of the same struct:
x = Foo { a: 2, b: 2, e: 2, .. x };

3

#[derive(Debug)]
enum A { None, Some(B) }
#[derive(Debug)]
enum B { None, Some(i32) }
fn foo(x: A) {
    match x {
        a @ A::None              => println!("a is A::{:?}", a),
        ref a @ A::Some(B::None) => println!("a is A::{:?}", *a),
        A::Some(b @ B::Some(_))  => println!("b is B::{:?}", b),
    }
}
foo(A::None);             // ==> x is A::None
foo(A::Some(B::None));    // ==> a is A::Some(None)
foo(A::Some(B::Some(5))); // ==> b is B::Some(5)

4

struct Pizza(Vec<i32>);
struct PizzaSlice<'a> { pizza: &'a Pizza, index: u32 }
struct PizzaConsumer<'a, 'b: 'a> { // says "b outlives a"
    slice: PizzaSlice<'a>, // <- currently eating this one
    pizza: &'b Pizza,      // <- so we can get more pizza
}
fn get_another_slice(c: &mut PizzaConsumer, index: u32) {
    c.slice = PizzaSlice { pizza: c.pizza, index: index };
}
let p = Pizza(vec![1, 2, 3, 4]);
{
    let s = PizzaSlice { pizza: &p, index: 1 };
    let mut c = PizzaConsumer { slice: s, pizza: &p };
    get_another_slice(&mut c, 2);
}

5

use std::collections::HashMap;

let text = "hello world wonderful world";

let mut map = HashMap::new();

for word in text.split_whitespace() {
    // The `or_insert` method on `Entry` is defined to return a mutable reference
    // to the value for the corresponding `Entry` key if that key exists, and if not,
    // inserts the parameter as the new value for this key and returns
    // a mutable reference to the new value.
    let count = map.entry(word).or_insert(0);
    *count += 1;
}

println!("{:?}", map);

6

fn get_shortest(names: Vec<&str>) -> Option<&str> {
    names.iter().min_by_key(|name| name.len())
}

fn show_shortest(names: Vec<&str>) -> String {
    get_shortest(names).unwrap_or("Not Found")
}

fn get_shortest_length(names: Vec<&str>) -> Option<usize> {
    get_shortest(names).map(|shortest| shortest.len())
}

get_shortest_length(vec!["Uku", "Felipe"]) //=> Some(3)
get_shortest_length(Vec::new()); //=> None

fn find_user_by_name(name: String) -> Option<JSON> { ... }
fn json_to_user(json: JSON) -> Option<User> { ... }

fn get_user_with_shortest_name(names: Vec<&str>) -> Option<User> {
   get_shortest(names)
    .and_then(|shortest| find_user_by_name(shortest))
    .and_then(|user| json_to_user(user))
}

let names = vec!["Uku", "Felipe"];
get_user_with_shortest_name(names) //=> Some(User { name: "Uku" })

// =======

fn add(num1: i32, num2: i32) -> i32 { ... }
fn div(num1: i32, num2: i32) -> Option<i32> { ... }

Some(3)
    .map(|n| add(n, 5))
    .and_then(|n| div(16,n)) // => Some(2)
fn main() {
    let opt = Some("Hello".to_string());
    
    match opt {
        Some(_) => println!("We have Some"),//drop(opt),
        None => println!("We have None"),
    }

    match opt {
        Some(mut s) => {
            s.push_str(" world!");
            println!("{}", s);
        }
        None => {}
    }
}
struct Person {
    name: String,
}

impl Person {
    fn new<S: Into<String>>(name: S) -> Person {
        Person { name: name.into() }
    }
}

fn main() {
    let person = Person::new("Herman");
    let person = Person::new("Herman".to_string());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment