How can I set a value by reference in a map?

This is my code, and this is the error it shows me

error[E0277]: a value of type `std::vec::Vec<&Rol<'_>>` cannot be built from an iterator over elements of type `Rol<'_>`
  --> src/
34 |             .collect()
   |              ^^^^^^^ value of type `std::vec::Vec<&Rol<'_>>` cannot be built from `std::iter::Iterator<Item=Rol<'_>>`
   = help: the trait `std::iter::FromIterator<Rol<'_>>` is not implemented for `std::vec::Vec<&Rol<'_>>`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0277`.
error: could not compile `playground`.

To learn more, run the command again with --verbose.
pub struct Employee {
    pub name: String,
    pub age: i32,

pub fn list_employees() -> Vec<Employee> {
    let emp1 = Employee {
        name: "Jhon".to_string(),
        age: 32,

    let emp2 = Employee {
        name: "Smith".to_string(),
        age: 32,

    vec![emp1, emp2]
pub struct Rol<'a> {
    pub employee: &'a Employee,
    pub rol: String,

impl<'a> Rol<'a> {
    pub fn list_roles() -> Vec<&'a Rol<'a>> {
            .map(|&user| Rol {
                employee: &user,
                rol: "User".to_string(),

pub fn main() {
    let list = Rol::list_roles();
    println!("roles {:?}", list);

I think there's a conceptual problem here. Unlike in garbage-collected languages like e.g. Java/JavaScript/Python, something needs to own every value in Rust. In your list_roles method, you call list_employees(), which returns a Vec<Employee>. This is not even put in a variable, so it will go out of scope after the end of the statement. Your Rol struct (which should probably spelled Role), only holds a reference (&'a Employee), not an owned value (which would have type Employee). In order for a Rolto exist, something else needs to own theEmployee` it references. However, there is nothing else.

A similar error happens again, when list_roles attempts to return a vec of references to roles. This vec cannot hold anything if there's nothing else holding those Rols.

There's a chapter in the book that covers the topic of borrowing, ownership and references more in-depth than my reply here could: Youtube has a ton of videos on the topic as well (search for "rust ownership borrowing").

If this is real-world code and not a toy example, i'd use a flat data model, where Role is an enum and a field of Employee:


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.