>  기사  >  백엔드 개발  >  golang에서 변수가 문자열인지 확인하는 방법

golang에서 변수가 문자열인지 확인하는 방법

青灯夜游
青灯夜游원래의
2023-01-06 12:41:103341검색

변수가 문자열인지 확인하는 방법: 1. "%T" 형식 지정 식별자를 사용하고 "fmt.Printf("variable count=%v is of type %T n", count, count)"; Reflect.TypeOf()를 사용하세요. 구문은 "reflect.TypeOf(variable)"입니다. 3. 검색을 위해 Reflect.ValueOf().Kind()를 사용하세요. 4. 유형을 그룹화하려면 유형 어설션을 사용하세요.

golang에서 변수가 문자열인지 확인하는 방법

이 튜토리얼의 운영 환경: 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.