借用值生命周期错误

时间:2017-07-16 11:56:26

标签: compiler-errors rust lifetime

尝试重构和清理我们的代码,我们遇到了终身编译错误。编译以下代码:

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);
        // ...
    }
}

给我们:

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 | | }
   | |_^

我们理解问题是packet_contents在堆栈上分配,并且在函数末尾超出范围。有没有办法在packet_contents内部分配'a并给它一生import time import sys TIMING_ENABLED = True def newdecorator(): def benchmarking(funct): def timercheck(*args, **kwarg): if TIMING_ENABLED: starttime = time.time() print("starting time", time.time()) funct(*args, **kwarg) if TIMING_ENABLED: print("TOTAL TIME TAKEN ::", time.time()-starttime) return timercheck return benchmarking # passing value to the decorators with arguments @newdecorator() def tara(): print("hellow testing") if __name__ == "__main__": TIMING_ENABLED = sys.argv[1] tara()

0 个答案:

没有答案