Rust是否等效于Swift的协议扩展方法? [英] Rust equivalent to Swift's extension methods to a protocol?

查看:69
本文介绍了Rust是否等效于Swift的协议扩展方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift中,我可以将扩展方法附加到 struct enum protocol (与 trait 相同)中在Rust中).

In Swift I can attach extension methods to any of struct, enum or protocol(same with trait in Rust).

protocol Foo1 {
    func method1() -> Int 
}
extension Foo1 {
    func method2() {
        print("\(method1())")
    }
}

然后所有符合协议 Foo1 的类型现在都具有 method2().这对于轻松构建方法链"非常有用.

Then all types conforming the protocol Foo1 now all have method2(). This is very useful to build "method chaining" easily.

如何在Rust中做同样的事情?这不会出错.

How to do same in Rust? This doesn't work with an error.

struct Kaz {}

impl Foo for Kaz {}

trait Foo {
    fn sample1(&self) -> isize { 111 } 
}

impl Foo {
    fn sample2(&self) {
        println!("{}", self.sample1());
    }
}

fn main() {
    let x = Kaz {};
    x.sample1();
    x.sample2();
}

这是错误.

warning: trait objects without an explicit `dyn` are deprecated
  --> src/main.rs:13:6
   |
13 | impl Foo {
   |      ^^^ help: use `dyn`: `dyn Foo`
   |
   = note: `#[warn(bare_trait_objects)]` on by default

error[E0599]: no method named `sample2` found for type `Kaz` in the current scope
  --> src/main.rs:22:7
   |
3  | struct Kaz {}
   | ---------- method `sample2` not found for this
...
22 |     x.sample2();
   |       ^^^^^^^ method not found in `Kaz`

error: aborting due to previous error

推荐答案

在Rust中,您可以使用

In Rust, you can use extension traits, that is a trait with a generic implementation for all types T that implement the base trait:

struct Kaz {}

impl Foo for Kaz {}

trait Foo {
    fn sample1(&self) -> isize { 111 } 
}

trait FooExt {
    fn sample2(&self);
}

impl<T: Foo> FooExt for T {
    fn sample2(&self) {
        println!("{}", self.sample1());
    }
}

fn main() {
    let x = Kaz {};
    x.sample1();
    x.sample2();
}

游乐场

这篇关于Rust是否等效于Swift的协议扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆