Return struct containing borrowed value in rust

34 views Asked by At

I am trying to contruct a new NetworkManager from a function, but it takes a reference to another variable which is also created in the same scope.

fn test() -> NetworkManager<'_> {
    let dbus = Connection::new_system().unwrap();

    NetworkManager::new(&dbus)
}

How can I return this NetworkManager ? Rn I get a compiler error

error[E0515]: cannot return value referencing local variable `dbus`
  --> src/lib.rs:40:5
   |
38 |     let nm = NetworkManager::new(&dbus);
   |                                  ----- `dbus` is borrowed here
39 |
40 |     nm
   |     ^^ returns a value referencing data owned by the current function

Which I understand. I just don't know how to return it properly.

NOTE: I can change the return type of the function, so I can create a new type encapsulating the dbus Connexion and NetworkManager but I didn't find a way to express this type.

Tried to create a new type:

struct Test<'a> {
    dbus: Connection,
    nm: NetworkManager<'a>,
}

But as there is no relation between dbus and nm here, there is no way the compiler understands what I want to do.

0

There are 0 answers