比较切片和生命周期

时间:2014-11-23 12:42:47

标签: rust

我试图将防锈代码(我认为编译在0.12上)更新到最新的每晚。其中一个变化是从[T]&[T]的隐式强制被删除了。我更改了函数调用,但是我对以下代码(playpen snippet including as_bytes function here)有疑问:

let data: [u8, ..4] = [0x12, 0x34, 0x56, 0x78];
as_bytes(&data, |bytes| {
    assert!(bytes == &[&[0x12, 0x34, 0x56, 0x78]]);
});

会抛出以下错误:

src/reply.rs:580:33: 580:57 error: borrowed value does not live long enough
src/reply.rs:580             assert!(bytes == &[&[0x12, 0x34, 0x56, 0x78]]);
                                                 ^~~~~~~~~~~~~~~~~~~~~~~~
<std macros>:1:1: 12:2 note: in expansion of assert!
src/reply.rs:580:13: 580:60 note: expansion site
src/reply.rs:579:33: 581:10 note: reference must be valid for an anonymous lifetime defined on the block at 579:32...
src/reply.rs:579         as_bytes(&data, |bytes| {
src/reply.rs:580             assert!(bytes == &[&[0x12, 0x34, 0x56, 0x78]]);
src/reply.rs:581         });
<std macros>:3:12: 580:58 note: ...but borrowed value is only valid for the expression at 3:11
<std macros>:3         if !$cond {
<std macros>:4             panic!(concat!("assertion failed: ", stringify!($cond)))
<std macros>:5         }
<std macros>:6     );
<std macros>:7     ($cond:expr, $($arg:expr),+) => (
<std macros>:8         if !$cond {
               ...
<std macros>:1:1: 12:2 note: in expansion of assert!
src/reply.rs:580:13: 580:60 note: expansion site

问题:

  1. 这是比较切片内容的正确方法吗?
  2. 为什么会触发错误?
  3. 对于后人来说,写作时的最新夜晚是rustc 0.13.0-nightly (81eeec094 2014-11-21 23:16:48 +0000)

1 个答案:

答案 0 :(得分:0)

用户夏普帮我解决了IRC问题。

我将代码段更改为

let data: [u8, ..4] = [0x12, 0x34, 0x56, 0x78];
as_bytes(&data, |bytes| {
    assert_eq!(bytes, [[0x12, 0x34, 0x56, 0x78].as_slice()].as_slice());
});

编译并确实比较切片的内容。至于为什么错误被触发,我仍然不太确定。