3

在 Swift 中,我可以将方法添加到具有参数相等约束的泛型类型。

extension Optional where Wrapped == String {
    // Available only for `Optional<String>` type.
    func sample1() { ... }
}

如何在 Rust 中做到这一点?


更新

此功能称为带有通用 Where 子句的扩展

我认为这与 Rust 的implwithwhere子句基本相同,但没有明确的特征。

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

1 回答 1

3

您可以只实现具体类型的特征Option<String>

impl OptionUtil for Option<String> {
    fn sample1(self: &Self) {
        println!("{:#?}", self);
    }
}

我写了 crate, type_eq,它可以让你写一些看起来更像你的 Swift 示例的东西。但它与实现 trait 相同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 有用的情况。大多数情况下,上面更简单的代码可以工作,并且是首选。

于 2019-11-10T01:21:39.337 回答