LoginSignup
18
9

More than 3 years have passed since last update.

Non-exhaustive enum/struct

Last updated at Posted at 2019-03-09

Rust RFC 2008で規定されている#[non_exhaustive]属性について簡単に解説します

この内容は安定化されておらずnightlyでしか使えません 1.40 (2019/12/20) で安定化されています

Motivation

ライブラリを設計するとき、実装が進むにつれて新たにエラーを定義する必要が出てきます。Rustではエラーを扱うのに主にenumを使いますが、この要素は将来増える可能性があります。例えばstd::io::ErrorKindを見てみましょう

pub enum ErrorKind {
    NotFound,
    PermissionDenied,
    ConnectionRefused,
    ConnectionReset,
    ConnectionAborted,
    NotConnected,
    AddrInUse,
    AddrNotAvailable,
    BrokenPipe,
    AlreadyExists,
    WouldBlock,
    InvalidInput,
    InvalidData,
    TimedOut,
    WriteZero,
    Interrupted,
    Other,
    UnexpectedEof,
    // some variants omitted
}

このエラーをハンドリングするために次のようなmatch文を書いたとします

use std::io::ErrorKind::*;

match error_kind {
    NotFound => ...,
    PermissionDenied => ...,
    ConnectionRefused => ...,
    ConnectionReset => ...,
    ConnectionAborted => ...,
    NotConnected => ...,
    AddrInUse => ...,
    AddrNotAvailable => ...,
    BrokenPipe => ...,
    AlreadyExists => ...,
    WouldBlock => ...,
    InvalidInput => ...,
    InvalidData => ...,
    TimedOut => ...,
    WriteZero => ...,
    Interrupted => ...,
    Other => ...,
    UnexpectedEof => ...,
}

これは実装した段階では動きますが、将来ErrorKindに新たなエラーが追加されたときに正しくハンドリングできなくなります。しかし

match error_kind {
    // ...
    _ => ...,
}

のように_ブランチが用意されていれば将来にわたって正しく動作することが期待できます。

non_exhaustive attribute

現在ではこの問題に対処するために、例えばdiesel::error::Errorはライブラリレベルで次のような方法をとっています:

pub enum Error {
    InvalidCString(NulError),
    DatabaseError(String),
    NotFound,
    QueryBuilderError(Box<StdError+Send+Sync>),
    DeserializationError(Box<StdError+Send+Sync>),
    #[doc(hidden)]
    __Nonexhaustive,
}

このように隠された要素を追加することによって、__Nonexhaustiveが見える範囲では網羅的なマッチが可能で、それより外では網羅的なマッチを禁止しています。

これを簡単に実現するのがnon_exhaustive属性です

#[non_exhaustive]
pub enum Error {
    Message(String),
    Other,
}

のように定義することで、このenumが定義されたcrate内では網羅的なマッチが可能となり、外からは

use mycrate::Error;

match error {
    Message(ref s) => ...,
    Other => ...,
    _ => ...,
}

のようにアクセスする必要があります。

特に述べませんが、structのマッチにおいても同様の問題が発生するため、non_exhaustive属性はstructに対しても適用できます。

18
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
9