FromStr 特征不暴露生命周期的原因是什么?

What are reasons for FromStr trait not exposing lifetime?

Rust FromStr trait 是这样定义的

pub trait FromStr {
    type Err;
    fn from_str(s: &str) -> Result<Self, Self::Err>;
}

它没有命名它的生命周期,并且不能为包含对源字符串的引用的东西实现该特征,例如:

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 })
    }
}

给出错误

method `from_str` has an incompatible type for trait: expected bound lifetime parameter , found concrete lifetime [E0053]

到目前为止,我找不到为 MyIterator 实现 FromStr 的方法。我认为这是因为原始特征没有在其参数中公开字符串的生命周期。 我的第一个问题是:没有办法为 MyIterator 实现 FromStr,我说得对吗?如果我错了,有什么方法可以做到这一点(假设 MyIterator 想要保留对原始字符串的引用)?

到目前为止我只找到了这个问题:,但最佳答案以 "I don't believe that you can implement" 开头,所以我想确定这在 Rust 1.0.0 中是不可能的。

现在,如果特征定义是这样的:

trait MyFromStr<'a> {
    type Err;
    fn from_str(s: &'a str) -> Result<Self, Self::Err>;
}

可以为包含对原始字符串的引用但不包含对原始字符串的引用的类型实现它:

struct MyIterator<'a> {
    cur_pointer: &'a str
}

impl<'a> MyFromStr<'a> for MyIterator<'a> {
    type Err = i32;
    fn from_str(s: &'a str) -> Result<Self, Self::Err> {
        Ok(MyIterator { cur_pointer: s })
    }
}

struct MyCopy {
    val: String
}

impl<'a> MyFromStr<'a> for MyCopy {
    type Err = i32;
    fn from_str(s: &'a str) -> Result<Self, Self::Err> {
        Ok(MyCopy { val: s.to_string() })
    }
}

我的第二个问题是:特征 FromStr 没有暴露生命周期是否有任何特殊原因?也许我对生命周期有一些误解,暴露生命周期有缺点?

包括生命周期会使特征更加复杂,更具体地说,使使用该特征的通用代码更加冗长(带来不必要的生命周期)。 fn foo<T: FromStr>no longer work.

它对于字符串的预期用途也是不必要的。通常你从一个字符串 解析 并使用结果而不用担心字符串。以这种方式编码当然更容易。许多类型无论如何都不需要生命周期(请参阅实现它的一长串类型)。

您不能为此类型实施 FromStr。你能做的是

impl<'a> From<&'a str> for MyIterator<'a> { ... }

这为您提供了很多通用的转换机制,但不是方法 str::parse()。也许该方法的名称是省略生命周期的另一个论据。