gpt4 book ai didi

Rust 等同于 Swift 对协议(protocol)的扩展方法?

转载 作者:行者123 更新时间:2023-11-29 07:58:26 31 4
gpt4 key购买 nike

在 Swift 中,我可以将扩展方法附加到任何 structenumprotocol(与 trait 相同)在 Rust 中)。

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

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

如何在 Rust 中做同样的事情?这不适用于错误。

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 中,您可以使用 extension traits ,这是一个具有通用实现的特征,适用于实现基本特征的所有类型 T:

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

Playground

关于Rust 等同于 Swift 对协议(protocol)的扩展方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58852640/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com