在Swift中,我可以将方法添加到具有参数相等约束的泛型中。
extension Optional where Wrapped == String {
// Available only for `Optional<String>` type.
func sample1() { ... }
}
如何在Rust中做到这一点?
此功能称为Extensions with a Generic Where Clause。
[我认为这与Rust的impl
带有where
子句但没有显式特征的功能基本相同。
trait OptionUtil {
fn sample1(&self);
}
impl<T> OptionUtil for Option<T> where T:std::fmt::Debug {
fn sample1(&self) {
println!("{:#?}", self);
}
}
等效于(无显式特征)
extension Optional where Wrapped: DebugDescription {
func sample1() {
print("\(self)")
}
}
因此,我以为该Rust代码可以使用,但是不会出现错误。 (equality constraints are not yet supported in where clauses (see #20041)
)
impl<T> OptionUtil for Option<T> where T == String {
fn sample1(&self) {
println!("{:#?}", self);
}
}
您可以仅实现具体类型Option<String>
的特征:
impl OptionUtil for Option<String> {
fn sample1(self: &Self) {
println!("{:#?}", self);
}
}
我写了条板箱,type_eq,它使您可以编写更像Swift示例的looks。但这等同于实现Option<String>
的特征:
use type_eq::{Constrain, TypeEq};
use std::fmt::Debug;
trait OptionUtil {
fn sample1(&self);
}
impl<T> OptionUtil for Option<T>
where
Constrain: TypeEq<T, String>,
T: Debug,
{
fn sample1(&self) {
println!("{:#?}", self);
}
}
fn main() {
let s = Some(String::from("hello"));
println!("{:?}", s);
}
实际上很少有这种箱子有用的情况。在大多数情况下,上面的简单代码会起作用,并且是首选。