作为测试的一部分,我想断言函数返回一个包含正确内容的向量.因此,我将预期数据作为静态变量提供.然而,我找不到一种合适的方法来比较托管向量和静态向量变量的内容.

#[test]
fn test_my_data_matches_expected_data () {
  static expected_data: [u8, ..3] = [1, 2, 3];
  let my_data: ~[u8] = ~[1, 2, 3];  // actually returned by the function to test

  // This would be obvious, but fails:
  // -> mismatched types: expected `~[u8]` but found `[u8 * 3]`
  assert_eq!(my_data, expected_data);

  // Static vectors are told to be available as a borrowed pointer,
  // so I tried to borrow a pointer from my_data and compare it:
  // -> mismatched types: expected `&const ~[u8]` but found `[u8 * 3]`
  assert_eq!(&my_data, expected_data);

  // Dereferencing also doesn't work:
  // -> type ~[u8] cannot be dereferenced
  assert_eq!(*my_data, expected_data);

  // Copying the static vector to a managed one works, but this
  // involves creating a copy of the data and actually defeats
  // the reason to declare it statically:
  assert_eq!(my_data, expected_data.to_owned());
}

Update:在比较静态向量之前为其指定一个引用可以解决这个问题,因此我最终使用了一个小宏来断言向量的相等性:

macro_rules! assert_typed_eq (($T: ty, $given: expr, $expected: expr) => ({
  let given_val: &$T = $given;
  let expected_val: &$T = $expected;
  assert_eq!(given_val, expected_val);
}))

用法:assert_typed_eq([u8], my_data, expected_data);

推荐答案

实际上有两种静态向量:定长向量([u8, .. 3])和静态切片(&'static [u8]).前者不能很好地与其他类型的向量交互.后者在这里最有用:

fn main() {
    static x: &'static [u8] = &[1,2,3];

    let y = ~[1u8,2,3];
    assert_eq!(y.as_slice(), x);
}

Rust相关问答推荐

异步FN中的 rust 递归

在跨平台应用程序中使用std::OS::Linux和std::OS::Windows

如何在 struct 的自定义序列化程序中使用serde序列化_WITH

这是不是在不造成嵌套的情况下从枚举中取出想要的变体的惯用方法?

integer cast as pointer是什么意思

在IntoIter上调用.by_ref().Take().rev()时会发生什么情况

将一个泛型类型转换为另一个泛型类型

在Rust 中移动原始指针的靶子安全吗

允许 rust 迹 struct 条目具有多种类型

为什么我需要 to_string 函数的参考?

`UnsafeCell` 在没有锁定的情况下跨线程共享 - 这可能会导致 UB,对吗?

Rust 如何将链表推到前面?

当锁被释放时,将锁包装到作用域中是否会发生变化?

为什么 Rust 字符串没有短字符串优化 (SSO)?

如何连接 Rust 中的相邻切片

在 Rust 中如何将值推送到枚举 struct 内的 vec?

只有一个字符被读入作为词法分析器的输入

HashMap entry() 方法使borrow 的时间比预期的长

为什么这个 Trait 无效?以及改用什么签名?

为什么 u64::trailing_zeros() 在无分支工作时生成分支程序集?