0

I have this code using the amiquip package:

use amiquip::{Channel, Connection, Error, Exchange, Publish, Result};

fn main() {
    // Open connection.
    let mut connection = Connection::insecure_open("amqp://guest:guest@localhost:5672").unwrap();

    // Open a channel - None says let the library choose the channel ID.
    let mut channel = connection.open_channel(None).unwrap();

    // Get a handle to the direct exchange on our channel.
    let newEx = new_exchange(&mut channel);

    // Publish a message to the "hello" queue.
    newEx
        .exchange
        .publish(Publish::new("hello there".as_bytes(), "hello"))
        .unwrap();

    //connection.close()
}

struct RmqExchange<'a> {
    exchange: Exchange<'a>,
}

fn new_exchange(channel: &mut Channel) -> RmqExchange<'_> {
    let exchange = Exchange::direct(&channel);
    return RmqExchange { exchange: exchange };
}

The problem comes up during compilation. It says:

error[E0515]: cannot return value referencing function parameter `channel`
  --> src/rabbit_mq/exchange.rs:10:12
   |
9  |       let exchange = Exchange::direct(&channel);
   |                                       -------- `channel` is borrowed here
10 |       return RmqExchange{
   |  ____________^
11 | |         exchange: exchange
12 | |     };
   | |_____^ returns a value referencing data owned by the current function

I guess this makes sense since the value in the exchange class in the package puts the referred to channel into an exchange and returns it, then when I go to end the function the borrowed value is destroyed. So how do I do this properly?

Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
discodowney
  • 1,279
  • 5
  • 25
  • 48
  • See also the linked questions from [Why can't I store a value and a reference to that value in the same struct?](https://stackoverflow.com/q/32300132/155423), such as [How to store rusqlite Connection and Statement objects in the same struct in Rust?](https://stackoverflow.com/q/32209391/155423). – Shepmaster Apr 08 '22 at 18:56

0 Answers0