Generics are consumed? What is T!? not a variable

⚓ rust    📅 2025-05-22    👤 surdeus    👁️ 3      

surdeus

Warning

This post was published 38 days ago. The information described in this article may have changed.

Hi! I was writing some code, then I found something curious, is more like a interpretation thing of the compiler, I expect this to not be big, but is interesting to look on, I wanted to ask other things about this code, but in this thread I'll focus in one point:

fn foo<'a, I, T>(items: I)
where
    I: IntoIterator<Item = &'a T>,
    T: AsRef<str> + 'a,
{
    let refs: Vec<&'a str> = items.into_iter().map(|item| item.as_ref()).collect();
}

You know why we need that? lets go one step back on the logic, a way to iterate and retrieve a reference of each element.

fn foo<I>(items: I)
where
    I: IntoIterator,
    <I as IntoIterator>::Item AsRef<str>,
{
    let refs: Vec<&'a str> = items.into_iter().map(|item| item.as_ref()).collect();
}

This one will fails because:

6 |     let refs: Vec<&str> = items.into_iter().map(|item| item.as_ref()).collect();
  |                                                        ----^^^^^^^^^
  |                                                        |
  |                                                        returns a value referencing data owned by the current function
  |                                                        `item` is borrowed here

Here the key point, the item is being borrowed, but in Generics, the code should be generated from the call, so if would be calling like:

let vector = todo!();
foo(&vector)

Then the description does not match, the foo function will not own the value, we should be able to run this, obvs we could also pass the value it self and consume it, then it would fails.

The question is, how should we interpret T? because in generics we can't know if we own a variable or not, there could be other special cases where normal variable concept are not that clear, we could also think on the most restricted case, in this case a owned value, and there can be still more edge cases!

What have you seen on Generics that break the normal variable interpretation? is there a clear way to think of T?

5 posts - 5 participants

Read full topic

🏷️ rust_feed