GO TypeOf example explanation

This article introduces the GO TypeOf example explanation, mainly analyzes its syntax, parameters, return value and precautions, and analyzes its usage skills in combination with the example form. I hope this article can help you understand and apply this part of the content.

Usage and code examples of the “TypeOf” function in the “reflect” package of the GO language.

usage:

func TypeOf(i any) Type

TypeOf returns a reflection type representing the dynamic type of i. TypeOf returns nil if i is a nil interface value.

example:

package main
import (
	"fmt"
	"io"
	"os"
	"reflect"
)
func main() {
	// As interface types are only used for static typing, a
	// common idiom to find the reflection Type for an interface
	// type Foo is to use a *Foo value.
	writerType := reflect.TypeOf((*io.Writer)(nil)).Elem()
	fileType := reflect.TypeOf((*os.File)(nil))
	fmt.Println(fileType.Implements(writerType))
}

output:

true

Leave a Reply

Your email address will not be published.

en_USEnglish