这是一个最小的复制:

extern crate csv;
use std::fs::File;
use std::io::Write;

fn do_write(writer: &mut csv::Writer<File>, buf: &[u8]) {
    // The error is coming from this line
    writer.write_record(buf);
}

fn main() {
    let mut writer = csv::Writer::from_path(r"c:\temp\file.csv").unwrap();
    let str = "Hello, World!".to_string();
    do_write(&mut writer, str.as_bytes());
}

导致编译错误:

error[E0277]: the trait bound `u8: std::convert::AsRef<[u8]>` is not satisfied
 --> src/main.rs:7:16
  |
7 |         writer.write_record(buf);
  |                ^^^^^^^^^^^^ the trait `std::convert::AsRef<[u8]>` is not implemented for `u8`
  |
  = note: required because of the requirements on the impl of `std::convert::AsRef<[u8]>` for `&u8`

这个错误是什么意思?看来我已经通过了u8切片?

最佳答案

查看write_record的签名:

fn write_record<I, T>(&mut self, record: I) -> Result<()>
where
    I: IntoIterator<Item = T>,
    T: AsRef<[u8]>,

它期望可以成为值的迭代器的东西。您提供的是&[u8],它是一个迭代器,但仅包含&u8值。错误是这些&u8没有实现AsRef<[u8]>

您可以将单个传入的字符串包装在另一个数组中,以创建可以充当迭代器的对象:
writer.write_record(&[buf]);

关于csv - 尝试写入CSV记录时出现错误 “the trait ` std::convert::AsRef <[u8] >` is not implemented for ` u 8`”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47016911/

10-12 22:12