如何为实现AsRef <path>的任何类型实现From特性?

时间:2018-11-16 03:16:48

标签: rust

我在尝试在结构上实现From时遇到了麻烦。一个简单的例子是:

#[derive(Debug)]
struct Example {
    field: String,
}

impl From<P: AsRef<Path>> for Example {
    fn from(path: P) -> Self {
        Example {
            field: path.as_ref().to_str().unwrap().to_owned(),
        }
    }
}

fn main() {
    println!("{:?}", Example::from("test"));
}

无法通过以下方式进行编译:

error: expected one of `!`, `(`, `+`, `,`, `::`, `<`, or `>`, found `:`
 --> src/main.rs:6:12
  |
6 | impl From<P: AsRef<Path>> for Example {
  |            ^ expected one of 7 possible tokens here

我也尝试过From<AsRef<Path>>,但也无法使它正常工作。我希望第一个示例能够正常工作,因为这是我将用于函数的语法。

从根本上我想做的事情是不可能的吗?还是我做错了?

0 个答案:

没有答案