GO의 유형 스위치는 런타임시 인터페이스 유형을 결정하는 데 사용됩니다. 값보다는 유형과 일치 할 수있는 스위치 문의 확장입니다. 다음은 GO에서 유형 스위치를 사용하는 방법에 대한 단계별 설명입니다.
switch
키워드와 인터페이스 변수를 사용하십시오. 특수 키워드 type
변수 뒤에 사용하여 유형과 일치하고 있음을 나타냅니다.case type_name:
입니다. 유형이 일치하면 해당 케이스 블록 내부의 코드가 실행됩니다.:=
)을 사용하여 일치하는 유형의 새 변수에 값을 할당하는 편리한 방법을 제공합니다.사용법을 설명하는 예는 다음과 같습니다.
<code class="go">package main import "fmt" func main() { var thing interface{} = "Hello" switch t := thing.(type) { case int: fmt.Println("It's an int:", t) case string: fmt.Println("It's a string:", t) case float64: fmt.Println("It's a float64:", t) default: fmt.Println("Unknown type") } }</code>
이 예에서는 thing
이 인터페이스 변수이며 유형 스위치는 유형을 확인합니다. thing
문자열 인 경우 (이 경우) "문자열입니다 : hello"라는 인쇄가 인쇄됩니다.
GO의 유형 스위치는 몇 가지 이점을 제공합니다.
유형 스위치는 여러 가지 방법으로 GO에서 코드 가독성을 크게 향상시킬 수 있습니다.
예, GO의 유형 스위치는 인터페이스 유형을 처리 할 수 있습니다. 유형 스위치가 인터페이스 유형에 적용되면 해당 인터페이스의 기본 값이 다른 인터페이스 유형을 포함하여 특정 유형인지 확인할 수 있습니다. 작동 방식은 다음과 같습니다.
다음은 유형 스위치가 인터페이스 유형을 처리하는 방법을 보여주는 예입니다.
<code class="go">package main import "fmt" type Reader interface { Read() string } type Writer interface { Write(string) } type ReadWriter interface { Reader Writer } type File struct{} func (f File) Read() string { return "Reading from file" } func (f File) Write(s string) { fmt.Println("Writing to file:", s) } func main() { var thing interface{} = File{} switch t := thing.(type) { case Reader: fmt.Println("It's a Reader:", t.Read()) case Writer: fmt.Println("It's a Writer") t.Write("Test") case ReadWriter: fmt.Println("It's a ReadWriter") fmt.Println(t.Read()) t.Write("Test") default: fmt.Println("Unknown type") } }</code>
이 예에서는 Reader
, Writer
및 ReadWriter
인터페이스를 구현하는 File
유형을 할당 한 thing
변수입니다. 유형 스위치는 이러한 인터페이스 유형과 일치 thing
확인하고 적절한 방법을 호출합니다.
위 내용은 GO에서 유형 스위치를 어떻게 사용합니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!