Rustのexpectのエラーメッセージに迷ったらshouldを使え
RustのResult
のメソッドにexpect
があります。
これは unwrap
と似ていますが、エラーメッセージを添えることができます。
このexpect
というメソッド名に最初はちょっと違和感を感じました。それでライブラリのドキュメントを見ました。
Recommended Message Style
We recommend that expect messages are used to describe the reason you expect the Result should be Ok.
let path = std::env::var("IMPORTANT_PATH")
.expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`");
Hint: If you’re having trouble remembering how to phrase expect error messages remember to focus on the word “should” as in “env variable should be set by blah” or “the given binary should be available and executable by the current user”.
For more detail on expect message styles and the reasoning behind our recommendation please refer to the section on “Common Message Styles” in the std::error module docs.
Hintのところに、「もしエラーメッセージをどのようにするか迷ったときには"should"という単語に着目するのを思い出して欲しい」と書かれています。
"expect" は「期待する」ですが、"should be" を使うことで、"...であるはずだったのに(実際にはそうならなかったからパニックする)" という意味合いになるということですね。
ちなみに "expect" の英単語のコアイメージは「見張って待ち受ける」。
「外を見て何かを待つ」が原義.良いこと・悪いことにかかわらず何かを予期して待つ状態にあるという意味合い
だそうです。
Discussion