찾다
백엔드 개발Golanggolang에서 변수가 문자열인지 확인하는 방법

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

Jan 06, 2023 pm 12:41 PM
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. 유형을 그룹화하려면 유형 어설션을 사용하세요.

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으로 문의하세요.
GO 프로그래밍 언어로 확장 가능한 시스템 구축GO 프로그래밍 언어로 확장 가능한 시스템 구축Apr 25, 2025 am 12:19 AM

goisidealforbuildingscalablesystemsduetoitssimplicity, 효율성 및 빌드-내부 컨 컨 오렌 스upport.1) go'scleansyntaxandminimalisticdesignenenhance-reductivityandreduceerrors.2) itsgoroutinesandChannelsableefficedsoncurrentProgramming, DistributingLoa

GO에서 시작 기능을 효과적으로 사용하기위한 모범 사례GO에서 시작 기능을 효과적으로 사용하기위한 모범 사례Apr 25, 2025 am 12:18 AM

initTectionsIntOnaUtomaticallyBeforemain () andAreSefulforsettingupenvirondentAnitializingVariables.usethemforsimpletasks, propoysideeffects 및 withtestingntestingandloggingtomaincodeclarityAndestability.

GO 패키지에서 시작 함수의 실행 순서GO 패키지에서 시작 함수의 실행 순서Apr 25, 2025 am 12:14 AM

goinitializespackages는 theyareimported, theexecutesinitfunctions, theneiredefinitionorder, andfilenamesDeterMineDeTerMineTeRacrossMultipleFiles.ThemayLeadTocomplexInitializations의 의존성 의존성의 의존성을 확인합니다

이동 중에 사용자 정의 인터페이스를 정의하고 사용합니다이동 중에 사용자 정의 인터페이스를 정의하고 사용합니다Apr 25, 2025 am 12:09 AM

CustomInterfacesingoAreCrucialForwritingFlectible, 관리 가능 및 TestAblEcode.theyenabledeveloperstofocusonBehaviorimplementation, 향상 ModularityAndRobustness

이동 중에 조롱 및 테스트를위한 인터페이스 사용이동 중에 조롱 및 테스트를위한 인터페이스 사용Apr 25, 2025 am 12:07 AM

시뮬레이션 및 테스트에 인터페이스를 사용하는 이유는 인터페이스가 구현을 지정하지 않고 계약의 정의를 허용하여 테스트를보다 고립되고 유지 관리하기 쉽기 때문입니다. 1) 인터페이스를 암시 적으로 구현하면 테스트에서 실제 구현을 대체 할 수있는 모의 개체를 간단하게 만들 수 있습니다. 2) 인터페이스를 사용하면 단위 테스트에서 서비스의 실제 구현을 쉽게 대체하여 테스트 복잡성과 시간을 줄일 수 있습니다. 3) 인터페이스가 제공하는 유연성은 다른 테스트 사례에 대한 시뮬레이션 동작의 변화를 허용합니다. 4) 인터페이스는 처음부터 테스트 가능한 코드를 설계하여 코드의 모듈성과 유지 관리를 향상시키는 데 도움이됩니다.

GO에서 패키지 초기화에 Init을 사용합니다GO에서 패키지 초기화에 Init을 사용합니다Apr 24, 2025 pm 06:25 PM

GO에서는 INT 기능이 패키지 초기화에 사용됩니다. 1) INT 기능은 패키지 초기화시 자동으로 호출되며 글로벌 변수 초기화, 연결 설정 및 구성 파일로드에 적합합니다. 2) 파일 순서로 실행할 수있는 여러 개의 초기 함수가있을 수 있습니다. 3)이를 사용할 때 실행 순서, 테스트 난이도 및 성능 영향을 고려해야합니다. 4) 부작용을 줄이고, 종속성 주입을 사용하고, 초기화를 지연하여 초기 기능의 사용을 최적화하는 것이 좋습니다.

GO의 선택 설명 : 다중화 동시 작업GO의 선택 설명 : 다중화 동시 작업Apr 24, 2025 pm 05:21 PM

go'selectStatementsTreamLinesconcurramprogrammingBymultiplexingOperations.1) ItallowSwaitingOnMultipLechannelOperations, executingThefirStreadYone.2) thedefaultCasePreventsDeadLocksHavingThepRamToproCeedifNooperationSready.3) Itcanusedfored

GO의 고급 동시성 기술 : 컨텍스트 및 대기 그룹GO의 고급 동시성 기술 : 컨텍스트 및 대기 그룹Apr 24, 2025 pm 05:09 PM

Contextandwaitgroupsarecrucialingformaninggoroutineeseforoutineeseferfectial

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

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

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경