Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Interface 如何定义特征的可选方法?_Interface_Rust_Custom Type - Fatal编程技术网

Interface 如何定义特征的可选方法?

Interface 如何定义特征的可选方法?,interface,rust,custom-type,Interface,Rust,Custom Type,Rust是否有一个功能,我可以通过它创建并定义可能不存在的特性方法 我意识到,选项可以用来处理潜在的不存在的属性,但我不知道如何用方法实现这一点 在TypeScript中,问号表示这些方法可能不存在。以下是RxJs的摘录: NextObserver导出接口{ 下一步?:(值:T)=>无效; // ... } 如果Rust中不存在此功能,那么如何处理程序员不知道是否存在方法的对象呢?惊慌失措?您可以尝试为此使用空的默认方法实现: trait T { fn required_method(

Rust是否有一个功能,我可以通过它创建并定义可能不存在的特性方法

我意识到,
选项
可以用来处理潜在的不存在的属性,但我不知道如何用方法实现这一点

在TypeScript中,问号表示这些方法可能不存在。以下是RxJs的摘录:

NextObserver导出接口{
下一步?:(值:T)=>无效;
// ...
}

如果Rust中不存在此功能,那么如何处理程序员不知道是否存在方法的对象呢?惊慌失措?

您可以尝试为此使用空的默认方法实现:

trait T {
    fn required_method(&self);

    // This default implementation does nothing        
    fn optional_method(&self) {}
}

struct A;

impl T for A {
    fn required_method(&self) {
        println!("A::required_method");
    }
}

struct B;

impl T for B {
    fn required_method(&self) {
        println!("B::required_method");
    }

    // overriding T::optional_method with something useful for B
    fn optional_method(&self) {
        println!("B::optional_method");
    }
}

fn main() {
    let a = A;
    a.required_method();
    a.optional_method(); // does nothing

    let b = B;
    b.required_method();
    b.optional_method();
}

按照您的描述,“无锈”没有可选方法。你应该给出一个用例,我们可以给你一个可能的解决方案,而不是试图模仿另一种语言的东西。“如果程序员不知道某个方法是否存在,那么应该如何处理这些对象?”,程序员应该知道某个方法是否存在,也许你想用?@Stargateur谢谢你的回答。用例:以与rxjs相似的方式在Rust中实现观察者模式: