Menu
Coddy logo textTech

타입 스위치

Coddy GO 여정의 로직 & 흐름 섹션에 포함된 레슨. 68개 중 18번째.

타입 단언은 단일 타입을 확인할 때 잘 작동하지만, 인터페이스 변수에 대해 여러 가능한 타입을 처리해야 하는 경우가 많습니다. 이때 타입 스위치가 매우 유용합니다. 타입 스위치는 구체적인 타입에 따라 서로 다른 작업을 수행할 수 있는 깔끔한 방법을 제공합니다.

타입 스위치는 다음과 같은 특수 구문을 사용합니다: switch v := i.(type). 특정 타입 대신 (type) 키워드를 사용하는 점에 주목하세요. 각 case에서 변수 v에는 구체적인 타입을 가진 실제 값이 포함됩니다:

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)
    }
}

각 경우에 v는 자동으로 올바른 타입을 가지므로 추가적인 타입 어설션이 필요하지 않습니다. 따라서 특히 여러 가지 타입을 한 곳에서 처리해야 할 때, 타입 스위치는 여러 타입 어설션을 if-else 문과 함께 연쇄적으로 사용하는 것보다 훨씬 깔끔합니다.

challenge icon

챌린지

쉬움

이 챌린지에서는 알림 시스템에서 여러 데이터 유형을 처리하기 위해 type switch를 사용하는 방법을 연습합니다. 다양한 유형의 알림을 처리하고 구체적인 유형에 따라 적절하게 형식을 지정하는 function을 만듭니다.

두 개의 입력을 받습니다:

  • 알림 유형을 나타내는 문자열(예: "email", "sms", "push" 또는 "alert")
  • 알림의 content 또는 값을 나타내는 문자열

수행할 작업은 다음과 같습니다:

  1. interface{} parameter를 받는 processNotification이라는 function을 Create합니다.
  2. 알림 유형 입력을 기반으로 content를 적절한 Go 유형으로 Convert하고, 그 값을 interface{} 변수에 저장합니다:
    • "email"인 경우: content를 문자열로 사용합니다.
    • "sms"인 경우: content를 Integer로 Convert합니다(문자 수를 나타냄).
    • "push"인 경우: content를 Boolean으로 Convert합니다("enabled"인 경우 true, 그 외에는 false).
    • "alert"인 경우: content를 float64로 Convert합니다(priority level을 나타냄).
  3. converted value와 함께 processNotification function을 Call합니다.
  4. processNotification 내부에서 type switch를 사용하여 각 유형을 handle하고 appropriate message를 Print합니다:
    • string인 경우: "Email notification: [value]"
    • int인 경우: "SMS notification with [value] characters"
    • bool인 경우: "Push notifications: [value]"
    • float64인 경우: "Alert with priority: [value]"
    • 그 외의 유형인 경우: "Unknown notification type"

문자열 변환에는 strconv package를 사용합니다. Boolean 변환에서는 "enabled"true가 되어야 합니다. 이 챌린지는 type switch가 하나의 control structure에서 여러 유형을 처리하는 깔끔한 방법을 제공하며, 각 case에서 올바르게 typed된 값을 자동으로 제공하는 방식을 보여줍니다.

float64fmt.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 컴파일러