这是一个最小的复制品:
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
切片?
答案 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]);