序列化元组类型-模块核心::元组是私有的



我将使用此代码将Rust元组序列化为BERT格式:

extern crate core;
pub struct Serializer;
pub trait Serialize<T> {
    fn to_bert(&self, data: T) -> Vec<u8>;
}
impl Serialize<core::tuple> for Serializer {
    fn to_bert(&self, data: core::tuple) -> Vec<u8> {
        // some implementation
    }
}

Rust文档说,这种类型是在core::rust模块中定义的,但当我试图将这种类型用作特性中的参数时,编译器会生成一个错误:

error: type name `core::tuple` is undefined or not in scope [E0412]
impl Serialize<core::tuple> for Serializer {
               ^~~~~~~~~~~
help: run `rustc --explain E0412` to see a detailed explanation
help: no candidates by the name of `tuple` found in your project; maybe you misspelled the name or forgot to import an external crate?
error: module `tuple` is private
impl Serialize<core::tuple> for Serializer {

如果这个模块是私有的,那么我如何获得定义的默认Rust tuple类型并将其用作特征的参数?

我不知道你最初是怎么得到core::tuple这个名字的,但这肯定对你没有帮助。正如编译器告诉你的那样,它是私有的;你不能使用它。我甚至不认为core::rust存在,所以我不确定你的意思。

您没有解释为什么要使用libcore,也许您的目标环境没有内存分配器或操作系统。如果不是这样的话,您可能不想直接使用libcore

除此之外,core::tuple模块,而不是类型。你不能在那个位置使用它。例如:

fn foo(a: std::mem) {}
error: type name `std::mem` is undefined or not in scope [--explain E0412]
 --> src/main.rs:1:11
1 |> fn foo(a: std::mem) {}
  |>           ^^^^^^^^ undefined or not in scope
help: no candidates by the name of `mem` found in your project; maybe you misspelled the name or forgot to import an external crate?

如何获得定义的默认Rust元组类型并将其用作特征的参数

这对我来说并不完全有意义。如果你只想要一个可以有默认值的东西,那么就接受一个泛型类型T where T: Default。当所有组件类型都实现Default时,元组实现Default

如果你的意思不是真正的默认,那么你可以创建一个新的特征,这意味着你想要什么,并遵循同样的模式。

要为许多大小的元组实现这一特性,您可能会像标准库一样使用宏。没有办法表达"任意长度的所有元组"类型,因此宏用于实现多达一定数量的元素(通常为32个(的特性。

我想其他人在您之前提出的问题中已经提到了这一点,但您确实应该考虑为serde编写一个BERT适配器。这将允许您专注于新的和有趣的方面,并重用现有的测试代码。如果没有其他内容,您应该阅读如何实现serde和rustc序列化,看看其他人是如何解决相同问题的。

最新更新