我正在尝试为我的类型实现From<&[&str]>
。它应该消耗任意长度的行(仅在运行时已知),并从这些行中获取数据。编译器报错说,&[&str; 2]
不是&[&str]
,即无法将固定大小的切片转换为具有任意长度的切片。确切的消息是:the trait 'From<&[&str; 2]>' is not implemented for 'LineEater'
这是我的尝试:
fn main() {
let data = ["foo", "bar"];
// works
foo(&data);
// doesn't work
LineEater::from(&data);
// also doesn't work
let data: &[&str] = data.into();
LineEater::from(&data);
}
struct LineEater;
impl From<&[&str]> for LineEater {
fn from(_lines: &[&str]) -> Self {
todo!()
}
}
fn foo(_slice: &[&str]) {}
Playground是一个在线运行Rust代码的工具。这段代码中,调用foo()
可以正常工作,但调用from
则不行。在第一个情况下,Rust可以将[&str; 2]
“转换”为&[&str]
,但后者则不能。为什么会这样?如何修复呢?本段代码所用的Rust版本为1.55-nightly。
AsRef::as_ref
和Borrow::borrow
方法也可以执行转换,同时还可以使用as
进行强制类型转换(&data as &[&str]
)。 - Aiden4