Accept IntoIterator where T must not be a reference

⚓ Rust    📅 2026-01-22    👤 surdeus    👁️ 2      

surdeus

Consider the following function:

fn foo<T>(iter: impl IntoIterator<Item = T>) {
    //
}

If I pass in an appropriate container object by value then within foo the type of T will be the owned (non-reference) type of that containers owned elements. E.g.:

let a = [true, false, true];
foo(a); // Within foo T is bool.

let v = vec![1, 2, 3];
foo(v); // Within foo T is i32.

However, if I pass in an object/iterator that produces references then within foo the type of T will be the reference to the iterators element type:

let a = [true, false, true];
foo(a.iter()); // Within foo T is &bool.

My question is, is there a way to constrain the type of T so that foo will only accept iterators that provide owned access to their elements (i.e. the first type above)? I'm thinking about this in the context of a function that wants to take ownership of the elements in the provided iterator, perhaps by adding them into it's own new collection. However if the iterator only provides references then it can't do that, it can only create a new collection of references to those elements (as far as I know anyway).

Thanks

2 posts - 2 participants

Read full topic

🏷️ Rust_feed