3

Swift では、パラメーター等価制約を使用してメソッドをジェネリック型に追加できます。

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

Rustでこれを行う方法は?


アップデート

この機能は、ジェネリック Where 句を使用した拡張機能と呼ばれます。

implこれは基本的に Rust の明示的なトレイトのない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);
    }
}
4

1 に答える 1

3

具体的な型の特性を実装するだけですOption<String>:

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

私はクレートtype_eqを書きました。これにより、Swift の例によりたものを書くことができます。しかし、それはトレイト for を実装するのと同じです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);
}

実際、このクレートが役立つケースはほとんどありません。ほとんどの場合、上記のより単純なコードが機能し、推奨されます。

于 2019-11-10T01:21:39.337 に答える