liveBook · Manning

Generics

As explained in Write Powerful Rust Macros

A generic function is a function parameterized by types or other compile-time parameters.

A polymorphic function, or generic function, avoids duplicated implementations by accepting types or other compile-time parameters. It offers a more readable alternative to macros when ordinary function signatures communicate the operation clearly. section 1.3.2

Use generic functions deliberately:

  • Prefer them for reducing duplication when a normal function remains easy to understand. section 1.3.2
  • Consider generic implementation blocks or blanket implementations when behavior should apply across types satisfying a trait bound. section 1.3.2
  • Avoid broad abstractions that make behavior difficult to discover or understand. section 1.3.2
Listing 1.2 The powers and dangers of generics
trait Hello {
    fn hello(&self);
}

impl<T:Copy> Hello for T {
    fn hello(&self) {
        println!("Hello world");
    }
}

fn main() {
    2.hello();
    true.hello();
    'c'.hello();
}

A blanket implementation applies one trait method to every type satisfying Copy, demonstrating generic behavior across numbers, characters, and Booleans. section 1.3.2

How Write Powerful Rust Macros covers it

How deep it goes
Compares generic functions with macros and illustrates generic implementation blocks through a blanket implementation.
Examples
Demonstrates a Hello trait implemented for every Copy type, enabling numbers, characters, and Booleans to call hello.
What you can do after
Evaluate when generic functions or blanket implementations provide a clearer alternative to macros.
How it connects
Connects generic functions with macros, traits, blanket implementations, and extension traits.

Also explained in

Compare how 20 books explain generics →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Write Powerful Rust Macros. The section links point to the parts of the book it draws on.