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

how to enable comparison between Vec<_> and Vec<_,CustomAllocator>?

我正在尝试使用自定义分配器,使用 Rust 中的 allocator 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

实际上,在我的实施上下文中,我可能比较两个基础切片。但是我不知道如何用语言实现这个...

感谢任何线索!

更新: 由于 GitHub 拉取请求 #93755 已合并,现在可以比较具有不同分配器的 Vec


原回答:

Vec 使用 std::alloc::Global allocator by default, so Vec<u8> is in fact Vec<u8, Global>. Since Vec<u8, CustomAllocator> and Vec<u8, Global> are indeed distinct types, they cannot directly be compared because the PartialEq implementation is not generic for the allocator type. As @PitaJ commented, you can compare the slices instead using assert_eq!(&a[..], &b[..]) (which is also what the author of the allocator API recommends).