kel*_*nin 8 memory-management rust
我正在尝试使用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);
Run Code Online (Sandbox Code Playgroud)
这意味着像下面这样的简单比较将无法编译:
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)
Run Code Online (Sandbox Code Playgroud)
我无法实现该特征,因为我不拥有Vec或PartialEq。
实际上,在我的实现上下文中,我可以比较两个底层切片。但我不知道如何用语言来实现这一点......
任何线索表示赞赏!
更新:
由于 GitHub pull request #93755已合并,因此Vec现在可以对具有不同分配器的 s 进行比较。
原答案:
Vec默认情况下使用std::alloc::Global分配器,Vec<u8>实际上也是如此Vec<u8, Global>。由于Vec<u8, CustomAllocator>和Vec<u8, Global>确实是不同的类型,因此不能直接比较它们,因为PartialEq分配器类型的实现不是通用的。正如 @PitaJ 评论的那样,您可以使用比较切片assert_eq!(&a[..], &b[..])(这也是分配器 API 的作者所建议的)。