Created
October 14, 2017 06:39
-
-
Save anonymous/3c609495433446181bd888f6cca053d9 to your computer and use it in GitHub Desktop.
Rust code shared from the playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![allow(unreachable_code)] | |
// コンパイルエラー。 | |
fn actually_return() -> ! { | |
// 型エラー (expected `!`, found `{integer}`)。 | |
// `1` (整数型)は `!` に型強制できない。 | |
1 | |
// [予想1] `!` でない型の値を `!` に型強制することはできない。 | |
} | |
// コンパイル可能。 | |
fn dont_return() -> ! { | |
panic!(); | |
// (ここから到達不可能) | |
// 何事もなかったかのようにコンパイルが通る。 | |
1 | |
// 何故コンパイルが通るの? | |
// `1` が `!` として扱われているのだろうか? | |
// これは `actually_return()` における予想1と異なる挙動である。 | |
// [予想2] 到達不可能な箇所のコードでは型チェックが省略される。 | |
} | |
// コンパイルエラー。 | |
fn dont_return_wrong_type() -> i32 { | |
panic!(); | |
// (ここから到達不可能) | |
// 型エラー (expected `i32`, found `&str`)。 | |
"should be type error" | |
// これは `dont_return()` における予想2とは異なる挙動である。 | |
// [疑問1] `!` を返す(というか返らない)はずの `dont_return()` で | |
// `1` になる式を最後に置けたのは何故? | |
} | |
// コンパイル可能。 | |
fn semicolon_bang() { | |
// 何事もなかったかのようにコンパイルが通る。 | |
let _: &str = { panic!(); }; | |
// 前提として、 `expr;` は `()` 型となる。 | |
// そのため、 `{ expr; }` もまた `()` 型となるはずだが、 | |
// `{ panic!(); }` は `()` でなく `&str` として扱われている。 | |
// ということは、 `{ panic!(); }` の値は `!` 型として扱われているのだろうか? | |
// [疑問2] `{ panic!(); }` が `()` だけでなく任意の型として扱える(おそらく `!` | |
// として推論されている?)のは、どのような規則によるものかなのか。 | |
} | |
fn main() { | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment