当前位置:  开发笔记 > 后端 > 正文

如何将拥有的向量内容与Rust中的静态向量进行比较?

如何解决《如何将拥有的向量内容与Rust中的静态向量进行比较?》经验,为你挑选了1个好方法。

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

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



1> huon..:

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

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

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


肯定有@AndrewAylett.(巧合的是,我认为我甚至是那个做过它的人,哈哈.)幸运的是我还添加了`.as_slice()`来手动执行强制...更新答案.
推荐阅读
Gbom2402851125
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有