types - 如何比较 Rust 中拥有的向量和静态向量的内容?

标签 types vector static comparison rust

作为测试的一部分,我想断言函数返回具有正确内容的向量。因此,我将预期数据作为静态变量提供。但是,我找不到将托管向量的内容与静态向量变量进行比较的正确方法。

#[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());
}

更新:在比较之前分配对静态向量的引用解决了这个问题,所以我最终得到了一个小宏来断言向量相等:

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

关于types - 如何比较 Rust 中拥有的向量和静态向量的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16427159/

相关文章:

javascript - 从圆形边界弹起球

Java 静态与实例

node.js - 如何在 Sailsjs --no-frontend API 中通过 URL 访问图像

object - 如何将 Activator.CreateInstance 返回的对象转换为它转换的类型?

python - 更改Pandas中列的数据类型

mysql - 使用哪种数据类型来存储用户数据?

haskell - 如何确保图中的边正确

python - Numpy where 条件语句沿轴 0

r - 将一个向量作为子向量放入另一个向量 R

c++ - 静态 int 初始化