我想实现一个自定义特征&'a str和整数i32,但Rust不允许我:
use std::convert::Into;
pub trait UiId {
fn push(&self);
}
impl<'a> UiId for &'a str {
fn push(&self) {}
}
impl<T: Into<i32>> UiId for T {
fn push(&self) {}
}
fn main() {}
Run Code Online (Sandbox Code Playgroud)
无法编译时出现以下错误:
error[E0119]: conflicting implementations of trait `UiId` for type `&str`:
--> src/main.rs:11:1
|
7 | impl<'a> UiId for &'a str {
| ------------------------- first implementation here
...
11 | impl<T: Into<i32>> UiId for T {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `&str`
| …Run Code Online (Sandbox Code Playgroud) Rust FromStr trait 是这样定义的
pub trait FromStr {
type Err;
fn from_str(s: &str) -> Result<Self, Self::Err>;
}
Run Code Online (Sandbox Code Playgroud)
它没有命名它的生命周期,并且不能为包含对源字符串的引用的东西实现该特征,例如:
struct MyIterator<'a> {
cur_pointer: &'a str
}
impl<'a> FromStr for MyIterator<'a> {
type Err = i32;
fn from_str(s: &'a str) -> Result<Self, Self::Err> {
Ok(MyIterator { cur_pointer: s })
}
}
Run Code Online (Sandbox Code Playgroud)
给出错误
method `from_str` has an incompatible type for trait: expected bound lifetime parameter , found concrete lifetime [E0053]
Run Code Online (Sandbox Code Playgroud)
到目前为止,我发现没有办法为 MyIterator 实现 FromStr。我认为这是因为原始特征没有在其参数中公开字符串的生命周期。我的第一个问题是:没有办法为 MyIterator 实现 FromStr 是对的吗?如果我错了,有什么方法可以做到(假设 MyIterator 想要保留对原始字符串的引用)?
到目前为止,我只发现了这个问题:如何实现具有具体生命周期的 FromStr? …