为什么 std::str::parse 的签名不使用 trait bound?
Why doesn't the signature of std::str::parse use a trait bound?
Rust 的 str
原始类型上的 parse
方法的签名是
pub fn parse<F>(&self) -> Result<F, <F as FromStr>::Err>
为什么不是下面这样?
pub fn parse<F: FromStr>(&self) -> Result<F, F::Err>
我认为原始类型转换可能会确保 Err
解析为 FromStr::Err
,而不是 SomeOtherTrait::Err
。
不过,考虑到 parse
文档中的以下行...
parse can parse any type that implements the FromStr trait
为什么没有特征限制?
它确实使用了特征边界,但是边界是使用 where 子句指定的。 Look closer:
pub fn parse<F>(&self) -> Result<F, <F as FromStr>::Err>
where
F: FromStr,
<F as FromStr>::Err
表示来自 F
的 FromStr
实现的关联 Err
类型。
Why is it not as below?
pub fn parse<F: FromStr>(&self) -> Result<F, F::Err>
因为 F
可以实现许多不同的特征,所有这些特征都可以有不同的关联 Err
类型。此语法确保它获得与 F
的 FromStr
实现相关联的类型。
Rust 的 str
原始类型上的 parse
方法的签名是
pub fn parse<F>(&self) -> Result<F, <F as FromStr>::Err>
为什么不是下面这样?
pub fn parse<F: FromStr>(&self) -> Result<F, F::Err>
我认为原始类型转换可能会确保 Err
解析为 FromStr::Err
,而不是 SomeOtherTrait::Err
。
不过,考虑到 parse
文档中的以下行...
parse can parse any type that implements the FromStr trait
为什么没有特征限制?
它确实使用了特征边界,但是边界是使用 where 子句指定的。 Look closer:
pub fn parse<F>(&self) -> Result<F, <F as FromStr>::Err> where F: FromStr,
<F as FromStr>::Err
表示来自 F
的 FromStr
实现的关联 Err
类型。
Why is it not as below?
pub fn parse<F: FromStr>(&self) -> Result<F, F::Err>
因为 F
可以实现许多不同的特征,所有这些特征都可以有不同的关联 Err
类型。此语法确保它获得与 F
的 FromStr
实现相关联的类型。