试图写一个CSV记录有错误“特征`std :: convert :: AsRef< [u8]>`没有实现`u8`”

时间:2017-10-30 13:50:05

标签: csv rust

这是一个最小的复制品:

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切片?

1 个答案:

答案 0 :(得分:1)

查看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]);