Trying to refactor and cleanup our code we ran into a lifetime compile error. Compiling the following code:
fn create_ping_packet<'a>(sequence_number: u16) -> echo_request::MutableEchoRequestPacket<'a> {
let mut packet_contents = [0; 48];
let mut ping_packet = echo_request::MutableEchoRequestPacket::new(&mut packet_contents[20..]).unwrap();
ping_packet.set_icmp_type(IcmpTypes::EchoRequest);
ping_packet.set_icmp_code(echo_request::IcmpCodes::NoCode);
ping_packet.set_identifier(902);
ping_packet.set_sequence_number(sequence_number);
ping_packet.set_payload(b"Ring ring");
ping_packet
}
fn main() {
// ...
let mut sequence_number = 0;
loop {
let packet = create_ping_packet(sequence_number);
// ...
}
}
Gives us :
error: `packet_contents` does not live long enough
--> src/main.rs:15:76
|
15 | let mut ping_packet = echo_request::MutableEchoRequestPacket::new(&mut packet_contents[20..]).unwrap();
| ^^^^^^^^^^^^^^^ does not live long enough
...
22 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the body at 13:94...
--> src/main.rs:13:95
|
13 | fn create_ping_packet<'a>(sequence_number: u16) -> echo_request::MutableEchoRequestPacket<'a> {
| __________________________________________________________________________ _____________________^
14 | | let mut packet_contents = [0; 48];
15 | | let mut ping_packet = echo_request::MutableEchoRequestPacket::new(&mut packet_contents[20..]).unwrap();
16 | | ping_packet.set_icmp_type(IcmpTypes::EchoRequest);
... |
21 | | ping_packet
22 | | }
| |_^
We understand the problem is that packet_contents
is allocated on the stack and goes out of scope at the end of the function. Is there a way to allocate packet_contents
inside and give it a lifetime of 'a
?