Rust 等同于具有相同通用参数约束的 Swift 扩展方法?

Rust equivalent to Swift extension methods with equal generic parameter constraint?

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

我写了 crate,type_eq,它可以让你写一些看起来更像你的 Swift 例子的东西。但它与实现 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);
}

这个crate其实很少有用的。大多数情况下,上面更简单的代码都可以工作,并且是首选。