在 Swift 中,我可以将方法添加到具有参数相等约束的泛型类型。
extension Optional where Wrapped == String {
// Available only for `Optional<String>` type.
func sample1() { ... }
}
如何在 Rust 中做到这一点?
更新
此功能称为带有通用 Where 子句的扩展。
我认为这与 Rust 的impl
withwhere
子句基本相同,但没有明确的特征。
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);
}
}