Reference

Programming languages

Choose TypeScript, Go, Rust or C++ and find syntax, everyday APIs, standard libraries and tools in one place.

Scope and conventions

TypeScript/Node, Go 1.23+, Rust 2024 and C++23: from a first CLI to files, JSON, HTTP, concurrency and testing. Complete programs are labeled; other examples identify their surrounding code/imports. Optional libraries and version requirements are named in each entry.

Type design: unions, newtypes & generics

Using the type system to rule out bugs: models in which invalid states cannot be built, newtypes for IDs and units, checks that every case is handled, states encoded as types, constrained generics, variance and higher-kinded types. It goes deeper than the Types & syntax entries, which show how to read generics and tagged variants, and the Paradigms entries, which introduce algebraic data types.

Make illegal states unrepresentable: unions over flags, parse don't validate, smart constructors

Rust

Name alternatives and tagged variants (Types & syntax) shows how to write a union; this entry uses unions and validated constructors to design a model in which nonsense combinations cannot be built. Rust has everything this needs. A tuple struct with a private field inside a module, `pub struct Email(String)`, can only be built outside the module through Email::parse, so every Email has been checked (E0603 otherwise). Enums replace groups of optional fields: Reach has Email, Phone and Both, so a contact with no way to reach it cannot exist, and a variant such as Verified { at } would do the same for a flag with a date. parse_contact turns loose input into a Contact or an error, and matching on (email, phone) makes the compiler confirm every combination is handled.

Complete program

Complete program.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
mod contact {
    // Private field: outside this module, the only way to get an Email is parse.
    pub struct Email(String);

    impl Email {
        pub fn parse(raw: &str) -> Result<Email, String> {
            let value = raw.trim().to_lowercase();
            match value.split_once('@') {
                Some((user, domain)) if !user.is_empty() && domain.contains('.') => Ok(Email(value)),
                _ => Err(format!("bad email: {raw}")),
            }
        }
        pub fn as_str(&self) -> &str {
            &self.0
        }
    }

    // Before: email: Option<String>, phone: Option<String>, with (None, None) invalid.
    // After: only the valid shapes exist.
    pub enum Reach {
        Email(Email),
        Phone(String),
        Both { email: Email, phone: String },
    }

    pub struct Contact {
        pub name: String,
        pub reach: Reach,
    }

    // Parse, don't validate: loose input in, a valid Contact or an error out.
    pub fn parse_contact(name: &str, email: Option<&str>, phone: Option<&str>) -> Result<Contact, String> {
        let email = email.map(Email::parse).transpose()?; // Option<Result> -> Result<Option>
        let reach = match (email, phone) {
            (Some(email), Some(phone)) => Reach::Both { email, phone: phone.into() },
            (Some(email), None) => Reach::Email(email),
            (None, Some(phone)) => Reach::Phone(phone.into()),
            (None, None) => return Err("need an email or a phone".into()),
        };
        Ok(Contact { name: name.into(), reach })
    }
}

use contact::{Contact, Reach, parse_contact};

fn send_to(c: &Contact) -> String {
    let how = match &c.reach {
        Reach::Email(email) => format!("mail {}", email.as_str()),
        Reach::Phone(phone) => format!("text {phone}"),
        Reach::Both { email, phone } => format!("mail {} or text {phone}", email.as_str()),
    };
    format!("{}: {how}", c.name)
}

fn main() {
    let ana = parse_contact("Ana", Some(" Ana@Example.com "), None).unwrap();
    let lee = parse_contact("Lee", None, Some("+15550100")).unwrap();
    let kim = parse_contact("Kim", Some("kim@example.com"), Some("+15550199")).unwrap();
    // let fake = contact::Email("x".into());
    //   error[E0603]: tuple struct constructor `Email` is private
    assert!(parse_contact("Nobody", None, None).is_err());
    assert!(parse_contact("Bad", Some("nope"), None).is_err());
    println!("{} | {} | {}", send_to(&ana), send_to(&lee), send_to(&kim));
}

In practice: implement validation as a constructor returning Result (or TryFrom<&str>), keep the field private, and make fields public only on types whose every value is valid. Let match exhaustiveness find the places to update when a new state is added.

Privacy is per module, not per type: code in the same module (here, inside mod contact) can still build Email directly.

Deriving serde::Deserialize (serde 1.x) on a validated type skips the constructor; use #[serde(try_from = "String")] to route through TryFrom.

Wrap a primitive in a distinct type: brands, defined types, tuple structs, strong typedefs

Rust

Where Name alternatives and tagged variants (Types & syntax) names a set of values, a newtype gives one kind of value its own type, so two values with the same representation (two string IDs, meters and feet) cannot be swapped. In Rust it is a tuple struct with one field, such as `struct UserId(u64);`. It has the same size and layout as the wrapped value, but the compiler treats it as a separate type, and it gets only the traits you derive or implement. Implementing Add only for Meters + Meters makes Meters + Feet a type error, and From<Feet> for Meters gives the one sanctioned conversion. Newtypes also get around the orphan rule: a local wrapper may implement a foreign trait for a foreign type.

Complete program

Complete program.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use std::fmt;
use std::ops::Add;

// Tuple-struct newtypes: zero-cost wrappers that the compiler keeps apart.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct UserId(u64);

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct OrderId(u64);

#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
struct Meters(f64);

#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
struct Feet(f64);

// Only the operations you implement exist: Meters + Meters, but not Meters + Feet.
impl Add for Meters {
    type Output = Meters;
    fn add(self, other: Meters) -> Meters {
        Meters(self.0 + other.0)
    }
}

// From gives a named, explicit conversion between units.
impl From<Feet> for Meters {
    fn from(f: Feet) -> Meters {
        Meters(f.0 * 0.3048)
    }
}

impl fmt::Display for UserId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "user#{}", self.0)
    }
}

fn cancel_order(user: UserId, order: OrderId) -> String {
    format!("{user} cancelled order #{}", order.0)
}

// The orphan rule forbids impl Display for Vec<String> (both are foreign);
// a local newtype makes it legal.
struct Tags(Vec<String>);

impl fmt::Display for Tags {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[{}]", self.0.join(", "))
    }
}

fn main() {
    let u = UserId(42);
    let o = OrderId(9001);
    println!("{}", cancel_order(u, o));
    // cancel_order(o, u);
    //   error[E0308]: arguments to this function are incorrect (expected `UserId`, found `OrderId`)

    let run = Meters(400.0) + Meters::from(Feet(1000.0));
    // let bad = Meters(1.0) + Feet(1.0);
    //   error[E0308]: mismatched types: expected `Meters`, found `Feet`
    assert!((run.0 - 704.8).abs() < 1e-9);
    println!("{:.1} m", run.0);

    let tags = Tags(vec!["urgent".into(), "billing".into()]);
    println!("{tags}");
}

In practice: wrap IDs, units and validated values; derive the traits you want (Debug, Clone, Copy, PartialEq, Eq, Hash) and leave out the ones that make no sense. Keep the field private when the value must be validated, and provide new or TryFrom.

Implementing Deref to the inner type makes a newtype convenient but brings back most of the mixing it was meant to stop; prefer explicit accessor methods.

#[repr(transparent)] guarantees the same ABI as the field, which matters only across FFI.

A type alias (type Meters = f64;) is only a new name and gives no protection.

Make the compiler check every case: assertNever, exhaustive linters, match, std::visit

Rust

Algebraic data types (in Paradigms) shows how to define an enum and match on it; this entry covers how far the exhaustiveness check reaches and what switches it off. Every match must cover every possible value, and the compiler rejects one that does not (E0004), naming the missing pattern. That holds for tuples of enums, integers and nested patterns too, so matching on (state, event) checks every combination. A _ arm or a catch-all binding silences the check for every future variant. #[non_exhaustive] on a public enum works in the other direction: crates that use it must add a wildcard arm, so the defining crate can add variants later without a breaking change.

Complete program

Complete program.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// Every match must cover every value. Adding a variant breaks each match that lacks it:
// error[E0004]: non-exhaustive patterns: `&Notice::Slack { .. }` not covered
// (the & is there because target matches on a &Notice)
#[derive(Debug)]
enum Notice {
    Email { address: String },
    Sms { phone: String },
    Push { device_id: String },
}

#[derive(Debug, Clone, Copy, PartialEq)]
enum Delivery {
    Queued,
    Sent,
    Failed,
}

fn target(n: &Notice) -> &str {
    match n {
        Notice::Email { address } => address,
        Notice::Sms { phone } => phone,
        Notice::Push { device_id } => device_id,
    }
}

// Matching on a tuple checks every combination, so a state machine cannot miss a pair.
fn next(state: Delivery, ok: bool) -> Delivery {
    match (state, ok) {
        (Delivery::Queued, true) => Delivery::Sent,
        (Delivery::Queued, false) => Delivery::Failed,
        (Delivery::Sent | Delivery::Failed, _) => state, // terminal states stay put
    }
}

// #[non_exhaustive] matters only across crates: inside this crate the match below
// can stay exhaustive, but a downstream crate must add a `_ =>` arm, so this crate
// can add variants later without a breaking change.
#[non_exhaustive]
#[derive(Debug)]
pub enum Priority {
    Low,
    High,
}

fn retries(p: &Priority) -> u32 {
    match p {
        Priority::Low => 1,
        Priority::High => 5,
    }
}

fn main() {
    let notices = [
        Notice::Email { address: "ana@example.com".into() },
        Notice::Sms { phone: "+15550100".into() },
        Notice::Push { device_id: "dev-7".into() },
    ];
    for n in &notices {
        println!("{:?} -> {}", n, target(n));
    }
    assert_eq!(next(Delivery::Queued, true), Delivery::Sent);
    assert_eq!(next(Delivery::Queued, false), Delivery::Failed);
    assert_eq!(next(Delivery::Sent, false), Delivery::Sent);
    assert_eq!(next(Delivery::Failed, true), Delivery::Failed);
    println!("retries {} {}", retries(&Priority::Low), retries(&Priority::High));
}

In practice: list variants by name in matches that should change when the enum grows, and keep _ for cases where the remaining variants truly do not matter. Use #[non_exhaustive] on public library enums such as error kinds that are likely to grow, and leave it off enums that callers are meant to handle completely.

#[non_exhaustive] has no effect inside the defining crate, which is why the match in the example compiles without a wildcard.

A _ arm or a binding such as other => covers every future variant too, so adding a variant no longer breaks that match. Clippy can flag these: wildcard_enum_match_arm (restriction group) for any wildcard on an enum, match_wildcard_for_single_variants (pedantic) when _ stands for one variant.

Integer matches need a catch-all or full ranges (0..=u8::MAX); the compiler checks ranges for gaps.

Allow a call only in the right state (typestate): state types, consuming self, PhantomData, tag templates

Rust

Name alternatives and tagged variants (Types & syntax) puts every state in one union; typestate gives each state its own type, so a call that is wrong for the current state does not compile. Rust supports typestate fully because a method can take self by value: draft.submit() moves the draft, and any later use is a compile error (E0382). The usual form is one generic struct with a state parameter, Post<Draft>, where each state is a zero-sized marker type held through PhantomData. impl Post<Draft> holds edit and submit, impl Post<Published> holds url, and impl<S> Post<S> holds methods for every state. The markers take no space at run time, and a transition only changes the type.

Complete program

Complete program.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use std::marker::PhantomData;

// One zero-sized marker type per state. They are never constructed.
struct Draft;
struct InReview;
struct Published;

// One generic type; the State parameter records which state a value is in.
struct Post<State> {
    title: String,
    body: String,
    _state: PhantomData<State>, // takes no space; only the type changes
}

// Methods for every state go in a generic impl.
impl<S> Post<S> {
    fn title(&self) -> &str {
        &self.title
    }
    // Keeps the data and changes only the state type. Private to this module.
    fn into_state<T>(self) -> Post<T> {
        Post { title: self.title, body: self.body, _state: PhantomData }
    }
}

impl Post<Draft> {
    fn new(title: &str) -> Self {
        Post { title: title.into(), body: String::new(), _state: PhantomData }
    }
    fn edit(mut self, body: &str) -> Self {
        self.body = body.into();
        self
    }
    // Taking self by value moves the draft: the caller cannot use it afterwards.
    fn submit(self) -> Result<Post<InReview>, Post<Draft>> {
        if self.body.is_empty() {
            return Err(self); // give the draft back on failure
        }
        Ok(self.into_state())
    }
}

impl Post<InReview> {
    fn reject(self) -> Post<Draft> {
        self.into_state()
    }
    fn approve(self) -> Post<Published> {
        self.into_state()
    }
}

// Only a published post has a URL.
impl Post<Published> {
    fn url(&self) -> String {
        format!("/posts/{}", self.title.to_lowercase().replace(' ', "-"))
    }
}

fn main() {
    let draft = Post::new("Type State").edit("States as types.");
    let Ok(review) = draft.submit() else { panic!("empty post") };
    // draft.edit("again");
    //   error[E0382]: use of moved value: `draft`
    // review.url();
    //   error[E0599]: no method named `url` found for struct `Post<InReview>` in the current scope
    let Ok(again) = review.reject().edit("Revised.").submit() else { panic!("empty post") };
    let post = again.approve();
    assert_eq!(post.url(), "/posts/type-state");

    // A failed transition hands the draft back, so nothing is lost.
    let empty = Post::new("Empty").submit();
    assert!(matches!(&empty, Err(d) if d.title() == "Empty"));
    println!("{} is live at {}", post.title(), post.url());
}

In practice: use this for workflows, builders and protocols where the data stays the same and only the allowed calls change. Return the old state in the error (Result<Post<InReview>, Post<Draft>>) so a failed transition does not lose the value.

PhantomData<State> is needed because a struct may not have an unused type parameter (E0392).

Typestate fixes the state at compile time. A state chosen at run time (loaded from a database) needs an enum over the states instead.

Marker structs without fields (struct Draft;) cost nothing; they are never constructed.

When each state carries different fields (only a review has a reviewer), separate structs per state with consuming transitions (fn approve(self) -> Published) work the same way.

Constrain a generic type: extends + keyof, type sets, trait bounds, concepts

Rust

Read a type parameter (Types & syntax) shows how to read <T> in a signature; this entry covers writing the bounds that say what T must support. Trait bounds say what a type parameter must implement: `T: PartialOrd + Copy`. A where clause holds the same bounds after the signature and is easier to read when there are many, or when they mention associated types (I::Item) or closures (F: Fn(&I::Item) -> K). Operator traits like Add<Output = T> let generic code use +. Bounds can also sit on an impl block, so a method exists only for some T (Labeled<T>::describe needs T: Display). `impl Trait` in argument position is shorthand for an anonymous bounded parameter.

Complete program

Complete program.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use std::collections::HashMap;
use std::fmt::Display;
use std::hash::Hash;
use std::ops::Add;

// Inline bounds: T must be comparable and copyable.
fn largest<T: PartialOrd + Copy>(xs: &[T]) -> T {
    let mut best = xs[0];
    for &x in xs {
        if x > best {
            best = x;
        }
    }
    best
}

// A where clause reads better when bounds pile up or mention associated types.
fn count_by<I, K, F>(items: I, key: F) -> HashMap<K, usize>
where
    I: IntoIterator,
    K: Eq + Hash,
    F: Fn(&I::Item) -> K,
{
    let mut counts = HashMap::new();
    for item in items {
        *counts.entry(key(&item)).or_insert(0) += 1;
    }
    counts
}

// Bounds on an operator trait: anything that can be added and has a zero.
fn sum_all<T>(xs: &[T]) -> T
where
    T: Add<Output = T> + Copy + Default,
{
    xs.iter().fold(T::default(), |acc, &x| acc + x)
}

// impl Trait in argument position is shorthand for an anonymous type parameter.
fn shout(label: impl Display) -> String {
    format!("{label}!").to_uppercase()
}

// Conditional methods: describe() exists only when T: Display.
struct Labeled<T> {
    value: T,
}

impl<T: Display> Labeled<T> {
    fn describe(&self) -> String {
        format!("<{}>", self.value)
    }
}

fn main() {
    assert_eq!(largest(&[3, 9, 4]), 9);
    assert_eq!(largest(&[0.5, 0.25]), 0.5);
    let words = ["apple", "avocado", "banana"];
    let by_letter = count_by(words, |w| w.chars().next().unwrap());
    assert_eq!(by_letter[&'a'], 2);
    assert_eq!(sum_all(&[250_i64, 199]), 449);
    // largest(&[vec![1]]);
    //   error[E0277]: the trait bound `Vec<{integer}>: Copy` is not satisfied
    // Labeled { value: vec![1] }.describe();
    //   error[E0599]: the method `describe` exists for struct `Labeled<Vec<{integer}>>`,
    //   but its trait bounds were not satisfied
    println!("{} {}", shout("deploy"), Labeled { value: 42 }.describe());
}

In practice: put bounds on functions and impl blocks, not on struct definitions, so the struct stays usable for any T. Ask for the weakest trait that works (Clone rather than Copy, &[T] rather than Vec<T>).

Generic functions are monomorphized: each concrete T gets its own compiled copy, which is fast but grows the binary.

Unmet bounds produce E0277 at the call site, naming the trait the argument type lacks.

Know when subtypes substitute (variance): covariant arrays, invariant slices, lifetime subtyping, covariant returns

Rust

Read a type parameter (Types & syntax) treats each instantiation on its own; variance is the rule for when a container of Dog can be used where a container of Animal is expected. Rust has subtyping only for lifetimes: 'static outlives every 'a, so &'static str is a subtype of &'a str and can be passed where a shorter borrow is expected. &'a T is covariant in both 'a and T. &mut T is invariant in T: if it were covariant, a function could store a short-lived reference into a slot typed to hold a 'static one, and the compiler rejects exactly that with E0597. Trait objects are not subtypes: Box<Dog> becomes Box<dyn Animal> by an unsizing coercion, which does not reach inside a Vec.

Complete program

Complete program.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// Rust has subtyping only between lifetimes: 'static outlives every 'a,
// so &'static str is a subtype of &'a str.

// &'a T is covariant in 'a: a longer-lived reference can stand in for a shorter one.
fn pick<'a>(first: &'a str, second: &'a str) -> &'a str {
    if first.len() >= second.len() { first } else { second }
}

// &mut T is invariant in T. If it were covariant, this function could store a
// short-lived reference into a slot typed to hold a 'static one.
fn overwrite<'a>(slot: &mut &'a str, value: &'a str) {
    *slot = value;
}

trait Animal {
    fn name(&self) -> String;
}
struct Dog;
impl Animal for Dog {
    fn name(&self) -> String {
        "Rex".into()
    }
}

fn main() {
    let banner: &'static str = "release";
    let local = String::from("rc1");
    println!("{}", pick(banner, &local)); // banner shrinks to the local lifetime

    let mut slot: &str = "start";
    {
        let temp = String::from("temp");
        overwrite(&mut slot, &temp); // fine: slot itself is only used inside this block
        println!("{slot}");
    }
    // With a 'static slot, invariance pins 'a to 'static and the same call is rejected:
    // let mut forever: &'static str = "start";
    // { let temp = String::from("temp"); overwrite(&mut forever, &temp); }
    //   error[E0597]: `temp` does not live long enough

    // Trait objects use coercion, not subtyping: Box<Dog> becomes Box<dyn Animal>,
    // but Vec<Box<Dog>> does not become Vec<Box<dyn Animal>>; rebuild it.
    let dogs: Vec<Box<Dog>> = vec![Box::new(Dog)];
    let animals: Vec<Box<dyn Animal>> = dogs.into_iter().map(|d| d as Box<dyn Animal>).collect();
    println!("{}", animals[0].name());
}

In practice: variance mostly shows up as lifetime errors around &mut. If a function takes &mut &'a T, the 'a cannot shrink, so pass owned values or restructure. When you write a generic type with raw pointers, choose its variance with PhantomData (PhantomData<T> covariant, PhantomData<fn(T)> contravariant, PhantomData<*mut T> invariant).

Cell<T>, RefCell<T> and UnsafeCell<T> are invariant in T, like &mut T, because they allow writes through a shared reference.

fn(T) is contravariant in T: a function that accepts any lifetime can stand in for one that needs only 'static.

Abstract over containers (higher-kinded types): HKT encodings, GATs, template template parameters

Rust

Read a type parameter (Types & syntax) covers parameters that stand for a type such as i32; this entry covers parameters that would stand for a type constructor such as Vec itself, so one function could work over any container. Vec and Option are type constructors: Vec<i32> is a type, Vec alone is not. Rust has no `F<_>` parameter, but generic associated types (GATs, stable since Rust 1.65) cover much of the need. A trait can declare `type Of<T>;`, a marker type such as VecFamily sets `type Of<T> = Vec<T>;`, and a function generic over F: Family works with F::Of<i32> for any family. The best-known GAT is one with a lifetime parameter, `type Item<'a> where Self: 'a`, which allows a lending iterator whose items borrow from the iterator itself.

Complete program

Complete program.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// Vec and Option are type constructors: Vec<i32> is a type, Vec on its own is not.
// Rust has no `F<_>` parameter, but a generic associated type (GAT, stable since
// Rust 1.65) lets a marker type stand for a constructor: Family::Of<T>.
trait Family {
    type Of<T>;
    fn map<A, B>(fa: Self::Of<A>, f: impl FnMut(A) -> B) -> Self::Of<B>;
}

struct VecFamily;
struct OptionFamily;

impl Family for VecFamily {
    type Of<T> = Vec<T>;
    fn map<A, B>(fa: Vec<A>, f: impl FnMut(A) -> B) -> Vec<B> {
        fa.into_iter().map(f).collect()
    }
}

impl Family for OptionFamily {
    type Of<T> = Option<T>;
    fn map<A, B>(fa: Option<A>, f: impl FnMut(A) -> B) -> Option<B> {
        fa.map(f)
    }
}

// Written once, generic over the container.
fn double_all<F: Family>(fa: F::Of<i32>) -> F::Of<i32> {
    F::map(fa, |n| n * 2)
}

// The best-known GAT use: an item type that borrows from the iterator itself
// (a "lending iterator"), which std::iter::Iterator cannot express.
trait LendingIter {
    type Item<'a>
    where
        Self: 'a;
    fn next(&mut self) -> Option<Self::Item<'_>>;
}

struct Windows {
    data: Vec<i32>,
    pos: usize,
}

impl LendingIter for Windows {
    type Item<'a> = &'a mut [i32];
    fn next(&mut self) -> Option<&mut [i32]> {
        let start = self.pos;
        self.pos += 1;
        self.data.get_mut(start..start + 2)
    }
}

fn main() {
    // The family must be named: nothing links Vec<i32> back to VecFamily.
    let xs = double_all::<VecFamily>(vec![1, 2, 3]);
    let o = double_all::<OptionFamily>(Some(21));
    assert_eq!(xs, [2, 4, 6]);
    assert_eq!(o, Some(42));

    let mut w = Windows { data: vec![1, 2, 3, 4], pos: 0 };
    while let Some(pair) = w.next() {
        pair[1] += pair[0]; // each window is a mutable borrow of the data
    }
    println!("{xs:?} {o:?} {:?}", w.data);
}

In practice: use GATs for lending iterators and for traits whose associated type needs a parameter (a borrowed view, a pointer family such as Rc or Arc). Full Functor-style abstraction is possible but awkward: nothing links Vec<i32> back to VecFamily, so callers must name the family with turbofish.

A GAT with a lifetime usually needs the where Self: 'a bound; the compiler asks for it if missing.

Traits with GATs are not dyn-compatible (object safe), so they work only with generics.

The lending iterator cannot be used with for loops or Iterator adapters; drive it with while let.