Blog

Part 15 · Generics and Trait Bounds in Rust: One Function, Many Types

Generics let you write one function or struct that works for many types. This part covers type parameters, trait bounds, where clauses, impl Trait, const generics, and what the compiler really builds from a generic function.

Sometimes you write the same function twice, once for integers and once for characters, and only the type names differ. Generics let you write it once. A trait bound then says what the type must be able to do, so the compiler can check the body.

This part covers generic functions, structs and enums, trait bounds and where clauses, impl Trait, a short look at const generics, and what the compiler builds from a generic function. It builds on traits from Part 14 and slices from Part 4. Every program here was run on Rust 1.95, and its output is pasted from the run.

Try this first

This function finds the largest item in a slice. The <T> after the name says “this works for any type, call it T“. Will it compile?

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

fn main() {
    println!("{}", largest(&[34, 50, 25, 100, 65]));
    println!("{}", largest(&['r', 'u', 's', 't']));
}

It doesn’t:

error[E0369]: binary operation `>` cannot be applied to type `&T`
 --> src/main.rs:4:17
  |
4 |         if item > largest {
  |            ---- ^ ------- &T
  |            |
  |            &T
  |
help: consider restricting type parameter `T` with trait `PartialOrd`
  |
1 | fn largest<T: std::cmp::PartialOrd>(list: &[T]) -> &T {

Both calls in main use types that can be compared, so the error isn’t about them. “Any type” includes types that have no > at all, and Rust checks the body of a generic function once, for every possible T. The help: line names the fix. We’ll get there in a few steps.

The duplication problem

Here’s where generics come from. Without them, you write one function per type:

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

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

fn main() {
    println!("{}", largest_i32(&[34, 50, 25, 100, 65]));
    println!("{}", largest_char(&['r', 'u', 's', 't']));
}

It prints:

100
u

The two bodies are the same, letter for letter. Only the types in the signature differ. If you find a bug in one, you have to remember to fix the other. Add f64 and String and you have four copies to keep in step.

A generic function replaces the concrete type with a type parameter. You declare it in angle brackets after the function name, largest<T>, and then use T wherever the type would go: list: &[T] and -> &T. T is just a name. It’s short and conventional, but Item would work too.

list[0] panics on an empty slice. We keep it that way to match the two functions above; Exercise 1 asks what a safer version would return.

Trait bounds: saying what T can do

The error said > can’t be applied to &T. In Rust, > and < come from a trait, PartialOrd. The integers, floats, char, String and &str all implement it. Part 14 showed how a type implements a trait. A trait bound says “T must implement this trait”. You write it after the type parameter, with a colon:

fn largest<T: PartialOrd>(list: &[T]) -> &T {
    let mut largest = &list[0];
    for item in list {
        if item > largest {
            largest = item;
        }
    }
    largest
}

fn main() {
    println!("{}", largest(&[34, 50, 25, 100, 65]));
    println!("{}", largest(&[1.5, 0.2, 9.75]));
    println!("{}", largest(&['r', 'u', 's', 't']));
    println!("{}", largest(&["pear", "apple", "plum"]));
}

It prints:

100
9.75
u
plum

One function, four types. The bound works in two directions:

  • Inside the function, you may use anything PartialOrd gives you, and nothing else. Try println!("{item}") in the body and you get an error, because the bound doesn’t promise Display.
  • At the call site, the compiler checks that the type you pass implements PartialOrd. If it doesn’t, the error points at your call, not at the body. The first worked example below shows that error.

The function returns &T, a reference into the slice. So it never has to copy or clone an item, and it works for String too, which isn’t Copy.

You don’t usually name T at the call. The compiler works it out from the argument: &[34, 50, ...] makes T an i32. When it can’t tell, name it with the “turbofish”, largest::<f64>(&values).

More than one bound, and where clauses

To compare items and print them, ask for both traits, joined with +:

use std::fmt::Display;

fn print_largest<T: Display + PartialOrd>(label: &str, list: &[T]) {
    let mut largest = &list[0];
    for item in list {
        if item > largest {
            largest = item;
        }
    }
    println!("{label}: {largest} (out of {} items)", list.len());
}

fn main() {
    print_largest("scores", &[71, 98, 85]);
    print_largest("names", &["Ana", "Cai", "Ben"]);
}

It prints:

scores: 98 (out of 3 items)
names: Cai (out of 3 items)

With two or three type parameters, each with a few bounds, the signature gets hard to read. A where clause moves the bounds after the signature. It means exactly the same thing:

use std::fmt::{Debug, Display};

fn report<T, U>(name: T, readings: &[U]) -> String
where
    T: Display,
    U: Debug + PartialOrd,
{
    let mut high = &readings[0];
    for r in readings {
        if r > high {
            high = r;
        }
    }
    format!("{name}: high {high:?} from {readings:?}")
}

fn main() {
    println!("{}", report("Pune", &[31.5, 34.0, 29.5]));
    println!("{}", report(7, &['b', 'z', 'k']));
}

It prints:

Pune: high 34.0 from [31.5, 34.0, 29.5]
7: high 'z' from ['b', 'z', 'k']

T and U are separate parameters, so they can be different types. Use where when the bounds stop fitting on one line.

Generic structs and enums

A struct can take type parameters too. This Point holds two values of the same type:

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

fn main() {
    let whole = Point { x: 5, y: 10 };
    let exact = Point { x: 1.5, y: 4.25 };
    println!("whole: ({}, {})", whole.x, whole.y);
    println!("exact: ({}, {})", exact.x, exact.y);
}

It prints:

whole: (5, 10)
exact: (1.5, 4.25)

whole is a Point<i32> and exact is a Point<f64>. Both fields share the one T, so they must be the same type:

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

fn main() {
    let p = Point { x: 5, y: 4.0 };
    println!("({}, {})", p.x, p.y);
}

It prints:

error[E0308]: mismatched types
 --> src/main.rs:7:30
  |
7 |     let p = Point { x: 5, y: 4.0 };
  |                              ^^^ expected integer, found floating-point number

The compiler fixed T from x: 5, so it expected an integer for y as well. If you want the two fields to differ, give them two parameters:

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

fn main() {
    let p = Point { x: 5, y: 4.5 };
    let q = Point { x: "left", y: 'c' };
    println!("p: ({}, {})", p.x, p.y);
    println!("q: ({}, {})", q.x, q.y);
}

It prints:

p: (5, 4.5)
q: (left, c)

Option and Result are generic enums

You’ve already used generic enums. The standard library defines Option<T> as enum Option<T> { None, Some(T) }, and Result<T, E> as enum Result<T, E> { Ok(T), Err(E) }. Nothing about them is special. Option<T> is “a T, or nothing”, written once for every T. Result<T, E> has two parameters, the success type and the error type, just like Point<T, U>. You can write your own the same way:

#[derive(Debug)]
enum Reply<T> {
    Yes(T),
    No,
}

fn find_even(list: &[i32]) -> Reply<i32> {
    for &n in list {
        if n % 2 == 0 {
            return Reply::Yes(n);
        }
    }
    Reply::No
}

fn main() {
    println!("{:?}", find_even(&[3, 7, 8, 9]));
    println!("{:?}", find_even(&[1, 5]));
    let name: Reply<&str> = Reply::Yes("Ana");
    println!("{name:?}");
}

It prints:

Yes(8)
No
Yes("Ana")

In real code, use Option.

Methods on generic types

To write methods for every Point<T>, declare T after impl as well:

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

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

impl Point<f64> {
    fn distance_from_origin(&self) -> f64 {
        (self.x * self.x + self.y * self.y).sqrt()
    }
}

fn main() {
    let a = Point { x: 3.0, y: 4.0 };
    let b = Point { x: 'p', y: 'q' };
    println!("a.x = {}, distance {}", a.x(), a.distance_from_origin());
    println!("b.x = {}, b.y = {}", b.x(), b.y);
}

It prints:

a.x = 3, distance 5
b.x = p, b.y = q

{} prints the float 3.0 as 3; {:?} would print 3.0. Now read the two impl lines carefully. They look alike and mean different things:

  • impl<T> Point<T> says “for any type T, here are methods for Point<T>“. The first <T> declares the parameter, the second uses it. Every point gets x().
  • impl Point<f64> has no parameter. It adds methods to one concrete type only. Only a Point<f64> gets distance_from_origin, because sqrt exists for floats and not for char.

Call distance_from_origin on Point { x: 3, y: 4 } and you get E0599, “no method named distance_from_origin found”, with a note that the method exists for Point<f64>.

There’s a third form between the two: impl<T: Display + PartialOrd> Pair<T> adds methods only for the Ts that meet the bound. The second worked example uses it.

impl Trait: a shorter way to write a bound

Part 14 showed parameters like item: &impl Summary. That’s impl Trait in argument position, and it’s shorthand for a generic with a bound. These two functions are the same to the caller:

use std::fmt::Display;

fn shout(item: &impl Display) -> String {
    format!("{item}!")
}

fn shout_generic<T: Display>(item: &T) -> String {
    format!("{item}!")
}

fn main() {
    println!("{} {}", shout(&42), shout(&"hello"));
    println!("{} {}", shout_generic(&42), shout_generic(&"hello"));
}

It prints:

42! hello!
42! hello!

Use impl Trait when the type appears once and you don’t need its name. Use the full form when two parameters must be the same type: fn pair<T: Display>(a: T, b: T) forces that, while fn pair(a: impl Display, b: impl Display) lets a and b differ. One more small difference: the turbofish can’t name the type of an impl Trait parameter, because that type has no name to fill in.

impl Trait in return position means something different. It says “this function returns one specific type that implements the trait, and I’m not going to tell you which”. The caller can only use what the trait offers. Iterators are the usual reason; Part 17 covers them, so for now read impl Iterator<Item = u32> as “something a for loop can walk, giving u32s”:

use std::any::type_name;

fn countdown(from: u32) -> impl Iterator<Item = u32> {
    (1..=from).rev()
}

fn type_of<T>(_: &T) -> &'static str {
    type_name::<T>()
}

fn main() {
    let steps = countdown(3);
    println!("real type: {}", type_of(&steps));
    for n in steps {
        println!("{n}");
    }
}

It prints:

real type: core::iter::adapters::rev::Rev<core::ops::range::RangeInclusive<u32>>
3
2
1

std::any::type_name returns the name of a type as text. The docs say it’s for debugging only, and the text may change between Rust versions. Here it shows the type that impl Iterator hides. Writing that in the signature would be ugly, and any change to the body would change it.

“One specific type” is a real rule. This function tries to return an integer on one path and a string on the other:

use std::fmt::Display;

fn describe(big: bool) -> impl Display {
    if big { 1000 } else { "small" }
}

fn main() {
    println!("{}", describe(true));
}

It prints:

error[E0308]: `if` and `else` have incompatible types
 --> src/main.rs:4:28
  |
4 |     if big { 1000 } else { "small" }
  |              ----          ^^^^^^^ expected integer, found `&str`
...
help: you could change the return type to be a boxed trait object
...
3 + fn describe(big: bool) -> Box<dyn Display> {

Both are Display, but impl Display must be one type, fixed when the function compiles. The help: line points at Box<dyn Display>, a value whose type is chosen at run time. That’s a trait object, and Part 21 is about them. To see why the two are different, we need to see what the compiler does with a generic.

What the compiler builds: one copy per type

A generic function isn’t compiled once. When the compiler sees largest called with an i32 slice, it writes a copy of largest with T replaced by i32. When it sees a call with f64, it writes another. This is called monomorphisation, “making it one shape”. We can watch it. This version prints type_name::<T>() each time it runs:

use std::any::type_name;

fn largest<T: PartialOrd>(list: &[T]) -> &T {
    println!("running largest::<{}>", type_name::<T>());
    let mut largest = &list[0];
    for item in list {
        if item > largest {
            largest = item;
        }
    }
    largest
}

fn main() {
    println!("{}", largest(&[34, 50, 25, 100, 65]));
    println!("{}", largest(&[1.5, 0.2, 9.75]));
    println!("{}", largest(&['r', 'u', 's', 't']));
    println!("{}", largest(&[7, 3]));
}

It prints:

running largest::<i32>
100
running largest::<f64>
9.75
running largest::<char>
u
running largest::<i32>
7

type_name::<T>() has no argument. Nothing is passed in at run time to say what T is. Each copy has its own answer baked in when it was compiled: the i32 copy says i32, and the char copy says char. The fourth call uses i32 again, so it runs the same copy as the first.

what you write, once fn largest<T: PartialOrd> compile time: one copy per type largest::<i32> largest::<f64> largest::<char> calls calls calls largest(&[34, 50]) largest(&[1.5, 0.2]) largest(&['r', 'u']) call sites in main: each call runs the copy made for its type

You write largest once. The compiler writes one copy for each type it’s called with, and each call in main goes straight to its own copy.

In words: you write one function, largest<T: PartialOrd>. While compiling, the compiler finds three types it’s called with, so it generates three ordinary functions, largest::<i32>, largest::<f64> and largest::<char>. Each call in main is compiled as a direct call to the matching copy. By the time the program runs, there’s nothing generic left.

You can see the copies in the compiled program, too. On Linux, nm lists the functions in a binary, and -C makes the names readable. On the debug build of the program above, in a project called generics:

$ nm -C target/debug/generics | grep largest
0000000000014d70 t generics::largest
0000000000014e80 t generics::largest
0000000000014f90 t generics::largest

Three functions with the same name, at three different addresses. Your addresses will differ. In a release build, the optimiser copied each one straight into main, so nm found none at all. The copies were still made; they were just merged into their callers.

What it costs, and what it doesn’t

  • No cost at run time. A call to largest(&[1.5, 0.2]) is a plain call to a function that only knows about f64. There’s no lookup and no check of the type while the program runs. The f64 copy is as fast as the largest_f64 you’d have written by hand, because it is that function.
  • Bigger programs and slower builds. Each type you use adds a copy, and the compiler has to build and optimise every one. One generic function used with three types is cheap. A big generic library used with dozens of types shows up in your build times and binary size.

The other way to write “any type that implements this trait” is dyn Trait. There, one copy of the code handles every type, and each call looks up the right method while the program runs. That’s smaller and a little slower per call. Part 21 covers it. The Box<dyn Display> in the last error was this second kind.

Const generics: a number as a parameter

A type parameter stands for a type. A const generic parameter stands for a value, usually a length. Arrays need one, since [i32; 3] and [i32; 2] are different types:

fn sum<const N: usize>(values: [i32; N]) -> i32 {
    println!("this copy adds up {N} numbers");
    let mut total = 0;
    for v in values {
        total += v;
    }
    total
}

fn main() {
    println!("{}", sum([1, 2, 3]));
    println!("{}", sum([10, 20]));
}

It prints:

this copy adds up 3 numbers
6
this copy adds up 2 numbers
30

const N: usize declares the parameter, and [i32; N] uses it. The compiler reads N from the array you pass, and it makes one copy per length, the same as with types. Most of the time a slice, &[i32], is simpler. Const generics matter when the length is part of the type, as with arrays, and you want to keep it.

Worked example: finding the biggest order

You have a list of orders and want the one with the largest total. largest is already written, so you try it:

fn largest<T: PartialOrd>(list: &[T]) -> &T {
    let mut largest = &list[0];
    for item in list {
        if item > largest {
            largest = item;
        }
    }
    largest
}

struct Order {
    id: u32,
    total: u32,
}

fn main() {
    let orders = vec![Order { id: 1, total: 75 }, Order { id: 2, total: 30 }];
    let big = largest(&orders);
    println!("order {} has the biggest total: {}", big.id, big.total);
}

It prints:

error[E0277]: can't compare `Order` with `Order`
  --> src/main.rs:18:23
   |
18 |     let big = largest(&orders);
   |               ------- ^^^^^^^ no implementation for `Order < Order` and `Order > Order`
...
note: required by a bound in `largest`
  --> src/main.rs:1:15
   |
 1 | fn largest<T: PartialOrd>(list: &[T]) -> &T {
   |               ^^^^^^^^^^ required by this bound in `largest`
help: consider annotating `Order` with `#[derive(PartialOrd)]`

Read it from the top. E0277 means “a type doesn’t implement a trait it needs to”. The first arrow points at our call, line 18, not at the body of largest. The bound is a promise the caller has to keep. The note: shows where the promise was made, the T: PartialOrd on line 1. The last line suggests a fix.

That suggestion is a trap here. A derived PartialOrd compares the fields in the order they’re declared, so it compares id first, and only looks at total when the ids are equal. Our ids are all different, so it would pick order 2, the one with the smaller total. It would compile, run, and give the wrong answer.

What we mean is “compare by total”. So we implement the two traits ourselves. PartialOrd needs PartialEq as well, because comparing for order includes comparing for equality:

use std::cmp::Ordering;

fn largest<T: PartialOrd>(list: &[T]) -> &T {
    let mut largest = &list[0];
    for item in list {
        if item > largest {
            largest = item;
        }
    }
    largest
}

struct Order {
    id: u32,
    total: u32,
}

impl PartialEq for Order {
    fn eq(&self, other: &Self) -> bool {
        self.total == other.total
    }
}

impl PartialOrd for Order {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.total.partial_cmp(&other.total)
    }
}

fn main() {
    let orders = vec![
        Order { id: 1, total: 75 },
        Order { id: 2, total: 30 },
        Order { id: 3, total: 40 },
    ];
    let big = largest(&orders);
    println!("order {} has the biggest total: {}", big.id, big.total);
}

It prints:

order 1 has the biggest total: 75

partial_cmp returns an Ordering (Less, Equal or Greater) wrapped in an Option. It’s an Option because some values can’t be compared: a float that is NaN, “not a number”, is neither less, equal nor greater than anything. For our u32 totals, we hand the job to u32‘s own partial_cmp. Now > works on Order, and so does every generic function bounded by PartialOrd.

Parts 16 and 17 show a shorter way to say “compare by this field”, with a closure and max_by_key, without changing what “bigger” means for Order everywhere.

Worked example: methods only for some types

A Pair<T> holds two values. Every pair can be made. Only some pairs can say which value is larger, because that needs PartialOrd, and printing it needs Display:

use std::fmt::Display;

struct Pair<T> {
    a: T,
    b: T,
}

impl<T> Pair<T> {
    fn new(a: T, b: T) -> Self {
        Pair { a, b }
    }
}

impl<T: Display + PartialOrd> Pair<T> {
    fn show_larger(&self) {
        if self.a >= self.b {
            println!("larger is a = {}", self.a);
        } else {
            println!("larger is b = {}", self.b);
        }
    }
}

fn main() {
    let scores = Pair::new(40, 95);
    scores.show_larger();

    let words = Pair::new(String::from("kiwi"), String::from("fig"));
    words.show_larger();
}

It prints:

larger is b = 95
larger is a = kiwi

The second impl block has a bound on its T. Its methods exist only for pairs whose type is both Display and PartialOrd. i32 and String are both, so show_larger works for scores and words.

Now make a pair of a type that is neither:

use std::fmt::Display;

struct Pair<T> {
    a: T,
    b: T,
}

impl<T: Display + PartialOrd> Pair<T> {
    fn show_larger(&self) {
        if self.a >= self.b {
            println!("larger is a = {}", self.a);
        } else {
            println!("larger is b = {}", self.b);
        }
    }
}

struct Order {
    total: u32,
}

fn main() {
    let p = Pair {
        a: Order { total: 10 },
        b: Order { total: 20 },
    };
    p.show_larger();
    println!("{} {}", p.a.total, p.b.total);
}

It prints:

error[E0599]: the method `show_larger` exists for struct `Pair<Order>`, but its trait bounds were not satisfied
...
   |       ^^^^^^^^^^^ method cannot be called on `Pair<Order>` due to unsatisfied trait bounds
...
note: the following trait bounds were not satisfied:
      `Order: PartialOrd`
      `Order: std::fmt::Display`

Making a Pair<Order> is fine. Pair itself has no bound. The error comes only when we call a method whose bound Order doesn’t meet, and it lists exactly which traits are missing. The standard library does the same thing with bounds on single methods: a slice holds any T, but sort needs T: Ord, and contains needs T: PartialEq.

Tips and traps

  • Bounds on the struct itself. It’s tempting to write struct Pair<T: Display>. Then every function that mentions Pair<T> must repeat the bound, even ones that never print. Put bounds on the impl blocks and functions that need them, and keep the struct plain.
  • “binary operation cannot be applied to type T” (E0369). You used an operator the bounds don’t promise. Add the trait the help: line names: PartialOrd for < and >, PartialEq for ==, std::ops::Add for +.
  • impl<T> Point<T> vs impl Point<T>. Without the first <T>, Rust looks for a real type called T, and fails with “cannot find type T in this scope” (E0425 on Rust 1.95). The <T> after impl is what declares it.
  • Two impl Display returns from one function. E0308, “if and else have incompatible types”. Return-position impl Trait is one hidden type, not “any type”. Make both paths return the same type, or use Box<dyn Trait> (Part 21).
  • Deriving PartialOrd without checking the field order. It compares fields top to bottom. If the field you care about isn’t first, the order is wrong and nothing warns you. Move the field, or implement the trait by hand.
  • Generic everything “to be flexible”. Every generic adds a copy per type and makes errors longer to read. Start with the concrete type. Make it generic when a second type really needs it.

You write a generic function once; the compiler makes one copy for each type, and the bounds say what every copy may do.

Exercises

Exercise 1. Write fn smallest<T: PartialOrd>(list: &[T]) -> Option<&T>. It returns None for an empty slice and the smallest item otherwise. Call it on [4, 2, 9], on ["pear", "fig"] and on an empty &[f64], and print each result with {:?}.

Exercise 2. This doesn’t compile. Fix it by changing only the first line, so it prints ok ok and then 7 7.

fn show_twice<T>(x: T) {
    println!("{x} {x}");
}

fn main() {
    show_twice("ok");
    show_twice(7);
}

It prints:

error[E0277]: `T` doesn't implement `std::fmt::Display`

Exercise 3. Without running it, decide how many copies of describe the compiler makes for this program, and what it prints.

use std::any::type_name;
use std::fmt::Debug;

fn describe<T: Debug>(value: T) {
    println!("{} -> {value:?}", type_name::<T>());
}

fn main() {
    describe(1);
    describe(2);
    describe("three");
    describe(4.0);
    describe([5, 6]);
}
Answers

1. Start with None and replace it whenever you find a smaller item. match from Part 11 handles the first item:

fn smallest<T: PartialOrd>(list: &[T]) -> Option<&T> {
    let mut best: Option<&T> = None;
    for item in list {
        match best {
            None => best = Some(item),
            Some(b) if item < b => best = Some(item),
            Some(_) => {}
        }
    }
    best
}

fn main() {
    println!("{:?}", smallest(&[4, 2, 9]));
    println!("{:?}", smallest(&["pear", "fig"]));
    let empty: [f64; 0] = [];
    println!("{:?}", smallest(&empty));
}

It prints:

Some(2)
Some("fig")
None

The empty slice needs a type written out. [] alone gives the compiler nothing to work out T from.

2. println!("{x}") needs Display, so add the bound:

fn show_twice<T: std::fmt::Display>(x: T) {
    println!("{x} {x}");
}

fn main() {
    show_twice("ok");
    show_twice(7);
}

It prints:

ok ok
7 7

T doesn’t need Copy here, even though x appears twice. println! only borrows its arguments.

3. Four copies: one each for i32, &str, f64 and [i32; 2]. The first two calls are both i32, so they share a copy.

use std::any::type_name;
use std::fmt::Debug;

fn describe<T: Debug>(value: T) {
    println!("{} -> {value:?}", type_name::<T>());
}

fn main() {
    describe(1);
    describe(2);
    describe("three");
    describe(4.0);
    describe([5, 6]);
}

It prints:

i32 -> 1
i32 -> 2
&str -> "three"
f64 -> 4.0
[i32; 2] -> [5, 6]

A literal like 1 with nothing else to go on becomes an i32, and 4.0 becomes an f64. Those are Rust’s default integer and float types from Part 2.

What’s next

Our biggest-order example needed a whole trait implementation just to say “compare by total”. In Part 16, we’ll meet closures, small functions you write inline, which can capture values around them, and the three traits Fn, FnMut and FnOnce that describe them as generic bounds.

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.