简体   繁体   English

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

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

In Swift, I can add method to a generic type with parameter equality constraint.在 Swift 中,我可以将方法添加到具有参数相等约束的泛型类型。

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

How to do this in Rust?如何在 Rust 中做到这一点?


Update更新

This feature is called Extensions with a Generic Where Clause .此功能称为带有通用 Where 子句的扩展

I think this is basically same feature with Rust's impl with where clause without explicit trait.我认为这与 Rust 的implwhere子句没有显式特征的功能基本相同。

trait OptionUtil {
    fn sample1(&self);
}

impl<T> OptionUtil for Option<T> where T:std::fmt::Debug {
    fn sample1(&self) {
        println!("{:#?}", self);
    }
}

Is equivalent (without explicit trait) to等效于(没有显式特征)

extension Optional where Wrapped: DebugDescription {
    func sample1() {
        print("\(self)")
    }
}

Therefore, I thought this Rust code would work, but it doesn't work with an error.因此,我认为这个 Rust 代码可以工作,但它不会出现错误。 ( equality constraints are not yet supported in where clauses (see #20041) ) 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);
    }
}

You can just implement the trait for the concrete type Option<String> :您可以只实现具体类型Option<String>的特征:

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

I wrote crate, type_eq , which would let you write something that looks more like your Swift example.我写了 crate, type_eq ,它可以让你写一些看起来更像你的 Swift 例子的东西。 But it is identical to implementing the trait for Option<String> :但这与实现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);
}

There are actually very few cases where this crate is useful.实际上很少有这个 crate 有用的情况。 Most of the time the simpler code above will work, and is preferred.大多数情况下,上面更简单的代码可以工作,并且是首选。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM