如何从数组构建 WriteBuf

How to build WriteBuf from array

我正在将两个值序列化到一个数组中,我正在尝试通过 WriteBuf,但我收到的错误是

error: the trait `std::io::Write` is not implemented for the type `[_; 12]`
error: type `std::io::buffered::BufWriter<&mut [_; 12]>` does not implement any method in scope named `write_be_u32`
error: type `std::io::buffered::BufWriter<&mut [_; 12]>` does not implement any method in scope named `write_be_f64`

下面是生成此错误的最少代码:

use std::io::{ BufWriter, Write };

fn main(){
  let packed_data = [0; 12];
  let timestamp : u32 = 100;
  let value : f64 = 9.9;

  let writer = BufWriter::new(&mut packed_data);
  writer.write_be_u32(timestamp);
  writer.write_be_f64(value);

  println!("Packed data looks like {:?}", packed_data);
}

我是不是借错片了?我是否注意到使用正确的模块来为我的缓冲区定义 Write 特征?

这是此代码的围栏:http://is.gd/ol8qND

我发现您的代码存在一些潜在问题:

  • packed_data 不可变。
  • 您在 main 的末尾使用 packed_data,而 writer 持有对其的可变引用。

我认为这些错误都不是导致错误的原因。然而,我确实找到了一些有用的东西:

use std::io::{ BufWriter, Write };

fn main() {
    let mut packed_data = [0; 12];

    {
        let packed_data_ref: &mut [u8] = &mut packed_data;
        let mut writer = BufWriter::new(packed_data_ref);

        writer.write(&[1, 2, 3, 4]).unwrap();
    } // `writer` gets deallocated and releases the mutable reference

    println!("Packed data looks like {:?}", packed_data);
}

[playpen]

所以我想问题是您需要 &[u8] 而不是 &[u8; 12]。我不知道为什么。我希望这至少能有所帮助。