0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

7.9, 7.10 型アサーションと型switchに関連する考察

Posted at

型switch

型switch時に使うi.(type)の書き方はswitch構文時にしか使えない。ヒラで使うと invalid syntax tree: use of .(type) outside type switchのように怒られる。

型switchイディオム

型switchのイディオムとして対象の変数と同名の新しい変数を使うやり方が紹介されている


switch v := v.(type) {
case int:
    fmt.Println(v + 1)
case string:
    fmt.Println(strings.ToUpper(v))
default:
    fmt.Printf("unknown %T\n", v)
}

このケースでは、外側のvを別のvでシャドーしているので、switchを抜けると外側のvに安全に戻ることが出来る。
ただし、当然ながらswitchの内側で外側のvを参照したい場合は同じ変数名を使わない

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?