Go에서 변수 유형을 출력하는 방법
James Reed
Infrastructure Engineer · Leapcell

Key Takeaways
fmt.Printf("%T", variable)
을 사용하여 변수 유형을 간단하게 출력합니다.reflect.TypeOf(variable)
함수는 자세한 유형 정보를 제공합니다.- 타입 스위치를 통해 다양한 변수 유형을 동적으로 처리할 수 있습니다.
Go에서 런타임 시 변수의 유형을 이해하는 것은 디버깅 및 리플렉션 작업에 필수적일 수 있습니다. 이 문서에서는 Go에서 변수의 유형을 출력하거나 결정하는 다양한 방법을 살펴봅니다.
fmt.Printf
와 %T
동사 사용
변수의 유형을 출력하는 가장 간단한 방법은 %T
동사와 함께 fmt.Printf
함수를 사용하는 것입니다. 이 동사는 값의 Go 구문 표현식을 출력합니다.
예제:
package main import "fmt" func main() { var ( booleanVar bool = true stringVar string = "Hello, Go!" intVar int = 42 floatVar float64 = 3.14 sliceVar []string = []string{"foo", "bar", "baz"} ) fmt.Printf("Type of booleanVar: %T\n", booleanVar) fmt.Printf("Type of stringVar: %T\n", stringVar) fmt.Printf("Type of intVar: %T\n", intVar) fmt.Printf("Type of floatVar: %T\n", floatVar) fmt.Printf("Type of sliceVar: %T\n", sliceVar) }
출력:
Type of booleanVar: bool
Type of stringVar: string
Type of intVar: int
Type of floatVar: float64
Type of sliceVar: []string
이 예제에서 %T
는 각 변수의 유형을 검색하여 출력합니다. 이 방법은 간단하며 fmt
외에 추가 패키지를 가져올 필요가 없습니다.
reflect
패키지 사용
더욱 고급 유형 검사를 위해 Go는 런타임에 변수 유형 검사를 허용하는 reflect
패키지를 제공합니다.
예제:
package main import ( "fmt" "reflect" ) func main() { var ( booleanVar bool = true stringVar string = "Hello, Go!" intVar int = 42 floatVar float64 = 3.14 sliceVar []string = []string{"foo", "bar", "baz"} ) fmt.Println("Type of booleanVar:", reflect.TypeOf(booleanVar)) fmt.Println("Type of stringVar:", reflect.TypeOf(stringVar)) fmt.Println("Type of intVar:", reflect.TypeOf(intVar)) fmt.Println("Type of floatVar:", reflect.TypeOf(floatVar)) fmt.Println("Type of sliceVar:", reflect.TypeOf(sliceVar)) }
출력:
Type of booleanVar: bool
Type of stringVar: string
Type of intVar: int
Type of floatVar: float64
Type of sliceVar: []string
여기서 reflect.TypeOf(variable)
은 변수의 reflect.Type
을 반환하고, 이는 유형 이름을 제공하는 String()
메서드를 구현합니다.
타입 스위치 사용
변수의 유형을 결정하는 또 다른 방법은 타입 스위치를 사용하는 것입니다. 이 방법은 변수 유형에 따라 다른 코드 경로를 실행해야 할 때 특히 유용합니다.
예제:
package main import "fmt" func printType(v interface{}) { switch v.(type) { case int: fmt.Println("Type is int") case float64: fmt.Println("Type is float64") case string: fmt.Println("Type is string") case bool: fmt.Println("Type is bool") default: fmt.Println("Unknown type") } } func main() { printType(42) printType(3.14) printType("Hello, Go!") printType(true) }
출력:
Type is int
Type is float64
Type is string
Type is bool
이 예제에서 printType
함수는 타입 스위치를 사용하여 interface{}
파라미터 v
의 유형을 결정하고 해당 메시지를 출력합니다.
결론
Go에서 변수의 유형을 출력하거나 결정하는 것은 다양한 방법을 통해 달성할 수 있습니다.
- 간단한 유형 출력을 위해
%T
동사와 함께fmt.Printf
사용. - 보다 자세한 유형 검사를 위해
reflect
패키지 활용. - 다양한 유형을 동적으로 처리하기 위해 타입 스위치 구현.
각 방법은 다른 사용 사례를 제공하며, 이를 이해하면 유연하고 강력한 Go 프로그램을 작성하는 능력이 향상됩니다.
FAQs
fmt.Printf("%T", variable)
을 사용하십시오.
자세한 런타임 유형 검사가 필요할 때 reflect.TypeOf(variable)
을 사용하십시오.
interface{}
를 파라미터로 사용하는 함수 내에서 타입 스위치를 사용하십시오.
Leapcell은 Go 프로젝트 호스팅을 위한 최고의 선택입니다.
Leapcell은 웹 호스팅, 비동기 작업 및 Redis를 위한 차세대 서버리스 플랫폼입니다.
다국어 지원
- Node.js, Python, Go 또는 Rust로 개발하십시오.
무제한 프로젝트를 무료로 배포
- 사용량에 대해서만 지불하십시오. 요청이나 요금은 없습니다.
탁월한 비용 효율성
- 유휴 비용 없이 사용한 만큼 지불하십시오.
- 예: $25는 평균 응답 시간 60ms에서 694만 건의 요청을 지원합니다.
간소화된 개발자 경험
- 간편한 설정을 위한 직관적인 UI
- 완전 자동화된 CI/CD 파이프라인 및 GitOps 통합
- 실행 가능한 통찰력을 위한 실시간 메트릭 및 로깅
손쉬운 확장성 및 고성능
- 고도의 동시성을 쉽게 처리하기 위한 자동 확장.
- 운영 오버헤드가 없으므로 구축에만 집중하십시오.
설명서에서 더 많은 내용을 살펴보십시오!
X에서 팔로우하세요: @LeapcellHQ