std::io::ErrorKind具有一个变体__Nonexhaustive
如果这个变体不存在,我不知道这是什么问题。

此变体的目的是什么?

最佳答案

它旨在通过强制稳定代码中的任何ErrorKind语句具有全部match分支来允许将来扩展_枚举。

具体来说,the variant is marked unstable等无法在稳定 channel 上被引用,因此编译器拒绝类似的代码

fn foo(x: Error) {
    match x.kind() {
        ErrorKind::NotFound => {}
        ErrorKind::PermissionDenied => {}
        ErrorKind::ConnectionRefused => {}
        ErrorKind::ConnectionReset => {}
        ErrorKind::ConnectionAborted => {}
        ErrorKind::NotConnected => {}
        ErrorKind::AddrInUse => {}
        ErrorKind::AddrNotAvailable => {}
        ErrorKind::BrokenPipe => {}
        ErrorKind::AlreadyExists => {}
        ErrorKind::WouldBlock => {}
        ErrorKind::InvalidInput => {}
        ErrorKind::InvalidData => {}
        ErrorKind::TimedOut => {}
        ErrorKind::WriteZero => {}
        ErrorKind::Interrupted => {}
        ErrorKind::Other => {}
        ErrorKind::UnexpectedEof => {}
        ErrorKind::UnexpectedEOF => {}
        ErrorKind::__Nonexhaustive => {}
    }
}
<anon>:24:9: 24:35 error: use of unstable library feature 'io_error_internals': better expressed through extensible enums that this enum cannot be exhaustively matched against (see issue #0)
<anon>:24         ErrorKind::__Nonexhaustive => {}
                  ^~~~~~~~~~~~~~~~~~~~~~~~~~

如果此代码在稳定的Rust上成功编译,则在将来的版本中向ErrorKind添加一个变体将破坏具有上述match的任何代码,并且破坏稳定的代码是不好的。代码中断是因为Rust中的匹配项必须详尽无遗,也就是说,它们必须以某种方式涵盖所有可能性,因此添加变体将意味着未涵盖可能性。

相反,程序员必须编写:
fn foo(x: Error) {
    match x.kind() {
        ErrorKind::NotFound => {}
        ErrorKind::PermissionDenied => {}
        ErrorKind::ConnectionRefused => {}
        ErrorKind::ConnectionReset => {}
        ErrorKind::ConnectionAborted => {}
        ErrorKind::NotConnected => {}
        ErrorKind::AddrInUse => {}
        ErrorKind::AddrNotAvailable => {}
        ErrorKind::BrokenPipe => {}
        ErrorKind::AlreadyExists => {}
        ErrorKind::WouldBlock => {}
        ErrorKind::InvalidInput => {}
        ErrorKind::InvalidData => {}
        ErrorKind::TimedOut => {}
        ErrorKind::WriteZero => {}
        ErrorKind::Interrupted => {}
        ErrorKind::Other => {}
        ErrorKind::UnexpectedEof => {}
        ErrorKind::UnexpectedEOF => {}
        _ => {}
    }
}

这意味着将来添加到ErrorKind中的任何变体(例如,新的IO功能可能出现的新错误)将落在_范围之内,因此现有的稳定代码不会中断。

关于rust - ErrorKind::__ Nonexhaustive的目的是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36440021/

10-12 06:54