gpt4 book ai didi

rust - ErrorKind::__Noneexhaustive 的目的是什么?

转载 作者:行者123 更新时间:2023-11-29 07:42:21 25 4
gpt4 key购买 nike

std::io::ErrorKind 有一个变体 __Noneexhaustive。如果这个变体不存在,我不知道会出现什么问题。

这个变体的目的是什么?

最佳答案

它旨在允许 ErrorKind 枚举在未来扩展,通过强制稳定代码中的任何 match 语句具有包罗万象的 _ ARM 。

具体来说,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::__Noneexhaustive 的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36440021/

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