Associated bounds
⚓ Rust 📅 2025-11-17 👤 surdeus 👁️ 8I've been looking for a way to represent bounds themselves as things a trait can own, mirroring the way associated types are owned by a trait. A simplified motivating example is this Receiver trait. I want to be able to have specific implementations of Receiver restrict the types they operate on, while keeping those types generic until the function is called.
I want to write this, but it doesn't compile because traits (and other bounds) aren't types:
trait Receiver {
type Bounds;
fn offer<T: Self::Bounds>(&self, value: T);
}
struct CloneReceiver;
impl Receiver for CloneReceiver {
type Bounds = Clone;
fn offer<T: Self::Bounds>(&self, value: T) {
let _ = value.clone();
}
}
The only thing I can find to do is bring the generic up to the implementation rather than the function:
trait Receiver<T> {
fn offer(&self, value: T);
}
struct CloneReceiver;
impl<T: Clone> Receiver<T> for CloneReceiver {
fn offer(&self, value: T) {
let _ = value.clone();
}
}
This works, but is much less practical, especially when adding a generic lifetime to T. When T is chosen, the lifetime of the method call doesn't exist yet, so can't be expressed.
In languages where traits and types are semantically the same, the top example would work. It seems like a useful thing to be able to do, but maybe I'm missing a more idiomatic Rust approach to this problem?
1 post - 1 participant
🏷️ Rust_feed