如何启用 Vec<_> 和 Vec<_,CustomAllocator> 之间的比较?

8

我正在尝试使用Rust中的分配器API,使用自定义分配器。

看起来Rust将Vec<u8,CustomAllocator>Vec<u8>视为两种不同的类型。

    let a: Vec<u8,CustomAllocator> = Vec::new_in(CustomAllocator);
    for x in [1,2,3] { a.push(x) }

    let b:Vec<u8> = vec![1,2,3];
    assert_eq!(a,b);

这意味着像下面这样的简单比较将无法编译:
error[E0277]: can't compare `Vec<u8, CustomAllocator>` with `Vec<u8>`
  --> src/main.rs:37:5
   |
37 |     assert_eq!(a,b);
   |     ^^^^^^^^^^^^^^^ no implementation for `Vec<u8, CustomAllocator> == Vec<u8>`
   |
   = help: the trait `PartialEq<Vec<u8>>` is not implemented for `Vec<u8, CustomAllocator>`
   = note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info)

由于我没有拥有 Vec 或者 PartialEq,因此无法实现这个特性。

实际上,在我的实现中,我可能比较两个底层的切片。但是我不知道该如何用这种语言来实现...

如果您有任何线索,请告诉我!


7
你尝试过比较切片吗?assert_eq!(&a[..], &b[..]) - PitaJ
@PitaJ 确实看起来可以工作! - keldonin
1
@PitaJ 这可以缩短为 assert_eq!(a[..], b[..]) - Chayim Friedman
2
已开启 PR:https://github.com/rust-lang/rust/pull/93755 - Chayim Friedman
1个回答

3

更新: 自从 GitHub pull request #93755 被合并后,现在可以比较使用不同分配器的 Vec


原始回答:

Vec 默认使用 std::alloc::Global 分配器,因此 Vec<u8> 实际上是 Vec<u8, Global>。由于 Vec<u8, CustomAllocator>Vec<u8, Global> 确实是不同的类型,它们不能直接进行比较,因为 PartialEq 实现对分配器类型不是泛型的。正如 @PitaJ 评论的那样,您可以使用 assert_eq!(&a[..], &b[..]) 来比较切片 (这也是分配器 API 的作者推荐的方法)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接