Rust 相当于Swift和x27的锈蚀;协议的扩展方法?
在Swift中,我可以将扩展方法附加到任何Rust 相当于Swift和x27的锈蚀;协议的扩展方法?,rust,extension-methods,traits,Rust,Extension Methods,Traits,在Swift中,我可以将扩展方法附加到任何struct、enum或protocol(与Rust中的trait相同) 协议Foo1{ func method1()->Int } 分机1{ func方法2(){ 打印(“\(method1())”) } } 然后所有符合协议Foo1的类型现在都有method2()。 这对于轻松构建“方法链接”非常有用 如何在生锈的情况下进行同样的处理?这不适用于错误 struct Kaz{} 对Kaz{}的impl-Foo 特色食品{ fn样本1(&self)->
struct
、enum
或protocol
(与Rust中的trait
相同)
协议Foo1{
func method1()->Int
}
分机1{
func方法2(){
打印(“\(method1())”)
}
}
然后所有符合协议Foo1
的类型现在都有method2()。
这对于轻松构建“方法链接”非常有用
如何在生锈的情况下进行同样的处理?这不适用于错误
struct Kaz{}
对Kaz{}的impl-Foo
特色食品{
fn样本1(&self)->isize{111}
}
impl-Foo{
fn样本2(&self){
println!(“{}”,self.sample1());
}
}
fn main(){
设x=Kaz{};
x、 样本1();
x、 样本2();
}
这里是错误
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中,您可以使用,这是一种特性,它具有实现基本特性的所有类型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();
}
struct Kaz{}
对Kaz{}的impl-Foo
特色食品{
fn样本1(&self)->isize{111}
}
性状外显{
fn样本2(和自身);
}
T的impl FooExt{
fn样本2(&self){
println!(“{}”,self.sample1());
}
}
fn main(){
设x=Kaz{};
x、 样本1();
x、 样本2();
}