Skip to content
Related Articles

Related Articles

reflect.TypeOf() Function in Golang with Examples
  • Last Updated : 28 Apr, 2020

Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package.The reflect.TypeOf() Function in Golang is used to get the reflection Type that represents the dynamic type of i. To access this function, one needs to imports the reflect package in the program.

Syntax:

func TypeOf(i interface{}) Type

Parameters: This function takes only one parameters of interface( i ).

Return Value: This function returns the reflection Type.

Below examples illustrate the use of above method in Golang:



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate
// reflect.TypeOf() Function 
  
package main
  
import (
    "fmt"
    "reflect"
)
  
// Main function
func main() {
  
    tst1 := "string"
    tst2 := 10
    tst3 := 1.2
    tst4 := true
    tst5 := []string{"foo", "bar", "baz"}
    tst6 := map[string]int{"apple": 23, "tomato": 13}
  
      
    // use of TypeOf method       
    fmt.Println(reflect.TypeOf(tst1))   
    fmt.Println(reflect.TypeOf(tst2))
    fmt.Println(reflect.TypeOf(tst3))
    fmt.Println(reflect.TypeOf(tst4))
    fmt.Println(reflect.TypeOf(tst5))
    fmt.Println(reflect.TypeOf(tst6))
  
}

chevron_right


Output:

string
int
float64
bool
[]string
map[string]int

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate
// reflect.TypeOf() Function 
  
package main
  
import (
    "fmt"
    "io"
    "os"
    "reflect"
)
  
// Main function
func main() {
      
    // use of TypeOf method
    tt := reflect.TypeOf((*io.Writer)(nil)).Elem()
  
    fileType := reflect.TypeOf((*os.File)(nil))
    fmt.Println(fileType.Implements(tt))
  
}

chevron_right


Output:

true
My Personal Notes arrow_drop_up
Recommended Articles
Page :