Menu
Coddy logo textTech

型スイッチ

CoddyのGOジャーニー「論理とフロー」セクションの一部。レッスン 18/68。

型アサーションは単一の型を確認する場合には適していますが、interface 変数で複数の可能な型を処理する必要があることもよくあります。このような場合、型スイッチが非常に役立ちます。具体的な型に基づいて異なる処理を実行するための、すっきりとした方法を提供してくれるからです。

型スイッチでは、次の特殊な構文を使用します:switch v := i.(type)。特定の型ではなく、(type)キーワードを使用していることに注目してください。変数vには、各caseで具体的な型の実際の値が格納されます。

func describe(data interface{}) {
    switch v := data.(type) {
    case int:
        fmt.Printf("Integer: %d\n", v)
    case string:
        fmt.Printf("String: %s\n", v)
    case bool:
        fmt.Printf("Boolean: %t\n", v)
    default:
        fmt.Printf("Unknown type: %T\n", v)
    }
}

各caseでは、vが自動的に正しい型を持つため、追加の型アサーションは不要です。これにより、複数の異なる型を1か所で処理する必要がある場合、型switchはif-else文で複数の型アサーションを連結するよりも、はるかにすっきりします。

challenge icon

チャレンジ

簡単

このチャレンジでは、通知システムで複数のデータ型を処理するために、type switch の使い方を練習します。具体的な型に based して、さまざまな型の通知を処理し、適切に形式設定する function を Create します。

2 つの input を受け取ります。

  • 通知の型を表す string(例: "email""sms""push"、または "alert"
  • 通知の content または値を表す string

あなたの task は次のとおりです。

  1. processNotification という名前の function を Create し、interface{} parameter を受け取るようにします
  2. 通知の型の input based で、content を appropriate な Go の型に Convert し、interface{} variable に格納します。
    • "email" の場合: content を string として使用します
    • "sms" の場合: content を Integer に Convert します(characters の数を表します)
    • "push" の場合: content を Boolean に Convert します("enabled" の場合は true、それ以外は false)
    • "alert" の場合: content を float64 に Convert します(priority level を表します)
  3. Convert した値を指定して processNotification function を Call します
  4. processNotification の inside で type switch を使用し、それぞれの型を処理して appropriate な message を Println します。
    • string の場合: "Email notification: [value]"
    • int の場合: "SMS notification with [value] characters"
    • bool の場合: "Push notifications: [value]"
    • float64 の場合: "Alert with priority: [value]"
    • その他の型の場合: "Unknown notification type"

string の conversions には strconv package を使用します。Boolean の conversion では、"enabled" だけが true になります。この challenge は、type switch によって、1 つの control structure の中で複数の型を処理するための clean な方法が得られ、それぞれの case で correctly typed な value が自動的に得られることを示します。

float64 は、fmt.Println または %v / %g verb が行うように、最短の形式で Print します。3.53.5 として、1.01 として Print します(%f verb では 1.000000 と Print されます)。

自分で試してみよう

package main

import (
	"fmt"
	"strconv"
)

func main() {
	// 入力を読み取る
	var notificationType string
	var content string
	fmt.Scanln(&notificationType)
	fmt.Scanln(&content)
	
	// TODO: 以下にコードを書いてください
	// 1. Create processNotification function that takes interface{} parameter
	// 2. Convert content to appropriate type based on notificationType
	// 3. Call processNotification with the converted value
	// 4. Use type switch inside processNotification to handle different types
	
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

論理とフローのすべてのレッスン

自分で練習してみよう: Goオンラインコンパイラ