Rust 特征与类型的界限
Rust trait bounds with types
我正在阅读 hyperium/http source code and I found this:
pub fn put<T>(uri: T) -> Builder
where
Uri: TryFrom<T>,
<Uri as TryFrom<T>>::Error: Into<crate::Error>,
{
Builder::new().method(Method::PUT).uri(uri)
}
在此代码段中,Uri
是一种类型,T
是一种通用元素。
我一直看到 where T: SomeTrait
的结构,但没有看到 SomeType: SomeTrait<T>
。
这个结构有名字吗?在某处有记录吗?
引用 https://doc.rust-lang.org/reference/trait-bounds.html#higher-ranked-trait-bounds:
Bounds on an item must be satisfied when using the item. When type
checking and borrow checking a generic item, the bounds can be used to
determine that a trait is implemented for a type. For example, given
Ty: Trait
In the body of a generic function, methods from Trait
can be called on Ty
values. Likewise associated constants on the Trait
can be
used.
Associated types from Trait
can be used.
Generic functions and types with a T: Trait
bounds can be used with Ty
being used for T
.
没有任何内容表明 Ty
是类型参数(而不是固定类型)。所以我想说这只是一个特征限制,尽管不可否认在 Rust 教程中并不经常遇到。
我正在阅读 hyperium/http source code and I found this:
pub fn put<T>(uri: T) -> Builder
where
Uri: TryFrom<T>,
<Uri as TryFrom<T>>::Error: Into<crate::Error>,
{
Builder::new().method(Method::PUT).uri(uri)
}
在此代码段中,Uri
是一种类型,T
是一种通用元素。
我一直看到 where T: SomeTrait
的结构,但没有看到 SomeType: SomeTrait<T>
。
这个结构有名字吗?在某处有记录吗?
引用 https://doc.rust-lang.org/reference/trait-bounds.html#higher-ranked-trait-bounds:
Bounds on an item must be satisfied when using the item. When type checking and borrow checking a generic item, the bounds can be used to determine that a trait is implemented for a type. For example, given
Ty: Trait
In the body of a generic function, methods from
Trait
can be called onTy
values. Likewise associated constants on theTrait
can be used. Associated types fromTrait
can be used. Generic functions and types with aT: Trait
bounds can be used withTy
being used forT
.
没有任何内容表明 Ty
是类型参数(而不是固定类型)。所以我想说这只是一个特征限制,尽管不可否认在 Rust 教程中并不经常遇到。