golang에서 변수가 문자열인지 확인하는 방법
변수가 문자열인지 확인하는 방법: 1. "%T" 형식 지정 식별자를 사용하고 "fmt.Printf("variable count=%v is of type %T n", count, count)"; Reflect.TypeOf()를 사용하세요. 구문은 "reflect.TypeOf(variable)"입니다. 3. 검색을 위해 Reflect.ValueOf().Kind()를 사용하세요. 4. 유형을 그룹화하려면 유형 어설션을 사용하세요.
이 튜토리얼의 운영 환경: Windows 7 시스템, GO 버전 1.18, Dell G3 컴퓨터.
Golang은 변수의 유형을 확인하여 변수가 문자열인지 여부를 감지합니다.
Go는 문자열 형식 식별자 %T, 리플렉션 메서드인 Reflect.TypeOf, Reflect.ValueOf.Kind, 형식 어설션 및 대소문자 전환 메서드 사용을 포함하여 변수 형식을 확인하는 여러 가지 메서드를 제공합니다. 아래에서는 이러한 네 가지 유형의 방법을 예제를 통해 소개합니다.
%T 형식 식별자
%T 문자열 형식 식별자를 사용하는 것이 유형을 확인하는 가장 간단한 방법입니다. %T는 fmt 패키지입니다. fmt.Printf를 사용하여 변수 유형을 표시할 수 있습니다.
import ( "fmt" ) func main() { var count int = 42 var message string = "go find type" var isCheck bool = true var amount float32 = 10.2 fmt.Printf("variable count=%v is of type %T \n", count, count) fmt.Printf("variable message='%v' is of type %T \n", message, message) fmt.Printf("variable isCheck='%v' is of type %T \n", isCheck, isCheck) fmt.Printf("variable amount=%v is of type %T \n", amount, amount) } //OutPut variable count=42 is of type int variable message='go find type' is of type string variable isCheck='true' is of type bool variable amount=10.2 is of type float32
reflect 패키지 기능을 사용하세요.
위 방법이 유용하지 않거나 %T에 대한 추가 정보를 얻으려는 경우 유형의 경우 Reflect 패키지의 TypeOf 및 ValueOf().Kind 함수를 사용할 수 있습니다.
reflect.TypeOf()
TypeOf 메서드에 변수 값을 전달하면 변수 유형이 반환됩니다. 물론 변수를 전달할 수도 있지만, 변수 대신 변수 값을 직접 전달하는 것도 지원됩니다. 코드는 다음과 같습니다.
fmt.Printf("%v", reflect.TypeOf(10)) //int fmt.Printf("%v", reflect.TypeOf("Go Language")) //string
다음은 다양한 변수 유형의 전체 예입니다.
package main import ( "fmt" "reflect" ) func main() { var days int = 42 var typemessage string = "go find type" var isFound bool = false var objectValue float32 = 10.2 fmt.Printf("variable days=%v is of type %v \n", days, reflect.TypeOf(days)) fmt.Printf("variable typemessage='%v' is of type %v \n", typemessage, reflect.TypeOf(typemessage)) fmt.Printf("variable isFound='%v' is of type %v \n", isFound, reflect.TypeOf(isFound)) fmt.Printf("variable objectValue=%v is of type %v \n", objectValue, reflect.TypeOf(objectValue)) } //OUTPUT variable days=42 is of type int variable typemessage='go find type' is of type string variable isCheck='false' is of type bool variable amount=10.2 is of type float32 variable acounts=Savings is of type string
Reflect.ValueOf().Kind()
ValueOf().Kind()를 사용하여 변수 유형을 가져올 수도 있습니다. Reflect.ValueOf()는 전달된 변수를 기반으로 새 값을 반환한 다음 Kind 메서드를 통해 변수 유형을 추가로 얻습니다.
package main import ( "fmt" "reflect" ) func main() { var days int = 42 var typemessage string = "go find type" var isFound bool = false var objectValue float32 = 10.2 fmt.Printf("variable days=%v is of type %v \n", days, reflect.ValueOf(days).Kind()) fmt.Printf("variable typemessage='%v' is of type %v \n", typemessage, reflect.ValueOf(typemessage).Kind()) fmt.Printf("variable isFound='%v' is of type %v \n", isFound, reflect.ValueOf(isFound).Kind()) fmt.Printf("variable objectValue=%v is of type %v \n", objectValue, reflect.ValueOf(objectValue).Kind()) } //OUTPUT variable days=42 is of type int variable typemessage='go find type' is of type string variable isCheck='false' is of type bool variable objectValue=10.2 is of type float32
이 메서드의 단점은 새 변수를 생성해야 한다는 점이며, 이로 인해 메모리가 늘어날 수 있습니다. 용법.
유형 어설션 사용
이 섹션에서는 유형 어설션인 또 다른 방법을 소개합니다. 유형 판단을 수행하려면 아래에 typeofObject 메소드를 작성하세요.
func typeofObject(variable interface{}) string { switch variable.(type) { case int: return "int" case float32: return "float32" case bool: return "boolean" case string: return "string" default: return "unknown" } } fmt.Println("Using type assertions") fmt.Println(typeofObject(count)) fmt.Println(typeofObject(message)) fmt.Println(typeofObject(isCheck)) fmt.Println(typeofObject(amount)) //OUTPUT Using type assertions int string boolean float64
이 메소드의 장점은 유형을 그룹화할 수 있다는 것입니다. 예를 들어 모든 int32, int64, uint32 및 uint64 유형을 "int"로 식별할 수 있습니다.
【관련 추천: Go 비디오 튜토리얼, 프로그래밍 교육】
위 내용은 golang에서 변수가 문자열인지 확인하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Go Crawler Colly의 대기열 스레딩 문제는 Colly Crawler 라이브러리를 GO 언어로 사용하는 문제를 탐구합니다. � ...

Go Language의 부동 소수점 번호 작동에 사용되는 라이브러리는 정확도를 보장하는 방법을 소개합니다.

Go Language에서 메시지 대기열을 구현하기 위해 Redisstream을 사용하는 문제는 Go Language와 Redis를 사용하는 것입니다 ...

Go Language의 문자열 인쇄의 차이 : println 및 String () 함수 사용 효과의 차이가 진행 중입니다 ...

골란드의 사용자 정의 구조 레이블이 표시되지 않으면 어떻게해야합니까? Go Language 개발을 위해 Goland를 사용할 때 많은 개발자가 사용자 정의 구조 태그를 만날 것입니다 ...

GO의 어떤 라이브러리가 대기업이나 잘 알려진 오픈 소스 프로젝트에서 개발 했습니까? GO에 프로그래밍 할 때 개발자는 종종 몇 가지 일반적인 요구를 만납니다.

GO 언어에서 구조를 정의하는 두 가지 방법 : VAR과 유형 키워드의 차이. 구조를 정의 할 때 Go Language는 종종 두 가지 다른 글쓰기 방법을 본다 : 첫째 ...

다중 프로세스 로그 쓰기에서 동시성 보안 문제를 효율적으로 처리합니다. 여러 프로세스는 동시에 동일한 로그 파일을 작성합니다. 동시성을 안전하고 효율적으로 보장하는 방법은 무엇입니까? 이것은 ...
