https://www.recurse.com/manual
Generics are abstract stand-ins for concrete types or other properties.
enum Option<T> {
Some(T),
None,
}
fn foo<T>(arg: T) {
...
}
struct Data<T> {
value:T,
}
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 }
fn largest_in_list<T, U>(list: &[T], &U) -> &T { let mut largest = &list[0]; for item in list { ... } largest }
struct Point_as_int {
x: i32,
y: f32,
}
struct Point_as_float {
x: f32,
y: f32,
}
struct Point<T> {
x: T,
y: T,
}
types must match
struct Point<T> {
x: T,
y: T,
}
types must match
Point { x: 3, y: 2 }
Point { x: 3, y: 2.1 }
struct Point<T, U> {
x: T,
y: U,
}
Point { x: 3, y: 2 }
Point { x: 3, y: 2.1 }
enum OptionAsInt {
Some(i32),
None,
}
enum OptionAsBool {
Some(bool),
None,
}
enum Option<T> { Some(T), None, }
let x : Option = Some(10);
let y : Option = Some(true);
enum Result<T, E> { Ok(T), Err(E), }
struct Point<T> { x: T, y: T, } impl<T> Point<T> { fn x(&self) -> &T { &self.x } }
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);
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.
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());
Rustlings
https://github.com/rust-lang/rustlings
Rustlings
$ rustlings run generics1
$ rustlings hint generics1
Complete Exercises generics 1, 2 traits 1, 2