Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Serialization 将枚举值的向量转换为另一个向量_Serialization_Iterator_Rust - Fatal编程技术网

Serialization 将枚举值的向量转换为另一个向量

Serialization 将枚举值的向量转换为另一个向量,serialization,iterator,rust,Serialization,Iterator,Rust,我有以下代码,它从传递的枚举值向量生成字节向量: #[derive(Debug, PartialEq)] pub enum BertType { SmallInteger(u8), Integer(i32), Float(f64), String(String), Boolean(bool), Tuple(BertTuple), } #[derive(Debug, PartialEq)] pub struct BertTuple { pu

我有以下代码,它从传递的枚举值向量生成字节向量:

#[derive(Debug, PartialEq)]
pub enum BertType {
    SmallInteger(u8),
    Integer(i32),
    Float(f64),
    String(String),
    Boolean(bool),
    Tuple(BertTuple),
}

#[derive(Debug, PartialEq)]
pub struct BertTuple {
    pub values: Vec<BertType>
}

pub struct Serializer;

pub trait Serialize<T> {
    fn to_bert(&self, data: T) -> Vec<u8>;
}

impl Serializer {
    fn enum_value_to_binary(&self, enum_value: BertType) -> Vec<u8> {
        match enum_value {
            BertType::SmallInteger(value_u8) => self.to_bert(value_u8),
            BertType::Integer(value_i32) => self.to_bert(value_i32),
            BertType::Float(value_f64) => self.to_bert(value_f64),
            BertType::String(string) => self.to_bert(string),
            BertType::Boolean(boolean) => self.to_bert(boolean),
            BertType::Tuple(tuple) => self.to_bert(tuple),
        }
    }
}

// some functions for serialize bool/integer/etc. into Vec<u8>
// ...

impl Serialize<BertTuple> for Serializer {
    fn to_bert(&self, data: BertTuple) -> Vec<u8> {
        let mut binary: Vec<u8> = data.values
            .iter()
            .map(|&item| self.enum_value_to_binary(item)) // <-- what the issue there?
            .collect();

        let arity = data.values.len();
        match arity {
            0...255 => self.get_small_tuple(arity as u8, binary),
            _ => self.get_large_tuple(arity as i32, binary),
        }
    }
}

如何使用
std::iter::FromIterator
解决此问题?

问题是
enum\u value\u to\u binary
value
中的每个元素返回一个
Vec
。因此,您最终得到了一个
迭代器
,并在该迭代器上调用
collect::()
,但它不知道如何展平嵌套向量。如果希望将所有值展平为一个
Vec
,则应使用
flat\u map
而不是
map

let mut binary: Vec<u8> = data.values
            .iter()
            .flat_map(|item| self.enum_value_to_binary(item).into_iter()) 
            .collect();
让mut binary:Vec=data.values
.国际热核实验堆(iter)
.flat_映射(| item | self.enum_值_到_二进制(item).into_iter())
.收集();
或者,更惯用、更高性能的方法是,您可以让
enum\u value\u to\u binary
直接返回迭代器


另外,
iter
方法返回一个
IteratorNo,在我的示例中,我想返回一个字节向量。编译器已生成
无法移出借用内容[E0507]
表达式的
|&item
错误。