Sized bound unexpectedly required with return type impl trait in trait
⚓ Rust 📅 2025-11-03 👤 surdeus 👁️ 6I'm getting a weird error message related to RPITIT. Rustc complains that the return type is unsized and thus a Self: Sized bound has to be added to the trait method. It also says that it's needed in order to make the impl<D: Distrib> Distrib for &D blanket impl work. Using a concrete return type instead makes the code compile successfully.
trait Distrib {
type Sample;
fn samples(&self) -> impl Iterator<Item = Self::Sample>
// Why does rustc insist that this is needed?
// What does it have to do with the size of the return type?
where
Self: Sized,
{
Samples(self) // self is a reference and thus sized
}
// Using a concrete return type works fine without a Sized bound
fn samples2(&self) -> Samples<&Self> {
Samples(self)
}
}
impl<D: Distrib> Distrib for &D {
type Sample = D::Sample;
}
struct Samples<D>(D);
impl<D: Distrib> Iterator for Samples<D> {
type Item = D::Sample;
fn next(&mut self) -> Option<Self::Item> {
todo!()
}
}
3 posts - 2 participants
🏷️ Rust_feed