Rustlings: Live!

Goals:

Share knowledge

Ask Questions

Pair

Grow

Social Rules

https://www.recurse.com/manual

Have Fun!

What is a generic?

Generics are abstract stand-ins for concrete types or other properties.

What is a generic?

enum Option<T> {
    Some(T),
    None,
}
fn foo<T>(arg: T) {
    ...
}
struct Data<T> {
  value:T,
}

Generic in a func def

fn largest_i32(list: &[i32]) -> &i32 {
    let mut largest = &list[0];
    for item in list {
        ...
    }
    largest
}

fn largest_char(list: &[char]) -> &char {
    let mut largest = &list[0];
    for item in list {
        ...
    }
    largest
}

Generic in a func def

fn largest_in_list<T, U>(list: &[T], &U) -> &T {
    let mut largest = &list[0];
    for item in list {
        ...
    }
    largest
}

Generic in structs

struct Point_as_int {
    x: i32,
    y: f32,
}

 

struct Point_as_float {
    x: f32,
    y: f32,
}

Generic in structs

struct Point<T> {
    x: T,
    y: T,
}

types must match

Generic in structs

struct Point<T> {
    x: T,
    y: T,
}

types must match

Point {
    x: 3,
    y: 2
}
Point {
    x: 3,
    y: 2.1
}

Generic in structs

struct Point<T, U> {
    x: T,
    y: U,
}
Point {
    x: 3,
    y: 2
}
Point {
    x: 3,
    y: 2.1
}

Generic in enum

enum OptionAsInt {
    Some(i32),
    None,
}
enum OptionAsBool {
    Some(bool),
    None,
}

Generic in enum

enum Option<T> {
    Some(T),
    None,
}
let x : Option = Some(10);
let y : Option = Some(true);

Generic in enum

enum Result<T, E> {
    Ok(T),
    Err(E),
}

Generic in in method functions

struct Point<T> {
    x: T,
    y: T,
}

impl<T> Point<T> {
    fn x(&self) -> &T {
        &self.x
    }
}

Performance of Generics

Monomorphization

enum OptionAsInt<i32> {
    Some(i32),
    None,
}
enum OptionAsBool<bool> {
    Some(bool),
    None,
}
enum Option<T> {
    Some(T),
    None,
}
let x : Option<i32> = Some(10);
let y : Option<Bool> = Some(true);

Traits

A trait tells the Rust compiler about functionality a particular type has and can share with other types. We can use traits to define shared behavior in an abstract way.

What is a trait?

trait Vegetable {
    fn desc(&self) -> String;
}

struct Kale;
impl Vegetable for Kale {
    fn desc(&self) -> String {
        String::from("Kale, A leafy green")
    }
}

 

trait Vegetable {
    fn desc(&self) -> String {
        String::from("A leafy green")
    };
}

struct Kale;
impl Vegetable for Kale {}

 

struct Lettuce;
impl Vegetable for Lettuce {}

let kale = Kale{}
let lettuce = Lettuce{}

println!("kale is a {}", kale.desc());
println!("lettuce is a {}", lettuce.desc());

Using Traits 

Using Traits 

Let's Pair!

Rustlings

https://github.com/rust-lang/rustlings

Rustlings

Generics and Traits

$ rustlings run  generics1
$ rustlings hint generics1
Complete Exercises 
generics 1, 2
traits 1, 2

Rustlings: Live! Generics

By shortdiv

Rustlings: Live! Generics

Generics!

  • 482