我当时正在用Rust编写一个网络应用程序,想要定义一组函数,这些函数在给定原始字节序列的情况下,可以将其转换为某种结构。 TryFrom
特性似乎很合适;但是,当我尝试编译非常基本的示例代码时,我得到的信息却非常微不足道:
#![feature(try_from)]
use std::convert::TryFrom;
use std::io::Read;
#[derive(Debug)]
enum Fruit {
Apple = 1,
Orange = 2,
}
impl<T: Read> TryFrom<T> for Fruit {
type Error = ();
fn try_from(reader: T) -> Result<Fruit, ()> {
match reader.bytes().next() {
Some(x) if x == Fruit::Apple as u8 => Ok(Fruit::Apple),
Some(x) if x == Fruit::Orange as u8 => Ok(Fruit::Orange),
_ => Err(())
}
}
}
fn main() {
let bytes = b"\x01";
let fruit = Fruit::try_from(bytes).unwrap();
println!("The fruit is: {:?}", fruit);
}
错误是:
Error[E0119]: conflicting implementations of trait `std::convert::TryFrom<_>` for type `Fruit`:
--> src/main.rs:11:1
|
11 | impl<T: Read> TryFrom<T> for Fruit {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: conflicting implementation in crate `core`:
- impl<T, U> std::convert::TryFrom<U> for T
where T: std::convert::From<U>;
这让我很困惑。有人可以解释这是怎么回事吗?