Rust 相当于 Swift 对协议的扩展方法?
Rust equivalent to Swift's extension methods to a protocol?
在 Swift 中,我可以将扩展方法附加到 struct
、enum
或 protocol
中的任何一个(与 Rust 中的 trait
相同)。
protocol Foo1 {
func method1() -> Int
}
extension Foo1 {
func method2() {
print("\(method1())")
}
}
然后所有符合协议Foo1
的类型现在都有method2()
。
这对于轻松构建 "method chaining" 非常有用。
如何在 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();
}
在 Swift 中,我可以将扩展方法附加到 struct
、enum
或 protocol
中的任何一个(与 Rust 中的 trait
相同)。
protocol Foo1 {
func method1() -> Int
}
extension Foo1 {
func method2() {
print("\(method1())")
}
}
然后所有符合协议Foo1
的类型现在都有method2()
。
这对于轻松构建 "method chaining" 非常有用。
如何在 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();
}