reflect.Elem() Function in Golang with Examples

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.Elem() Function in Golang is used to get the value that the interface v contains or that the pointer v points to. To access this function, one needs to imports the reflect package in the program.

Syntax:

func (v Value) Elem() Value

Parameters: This function does not accept any parameters.

Return Value: This function returns the value that the interface v contains.

Below examples illustrate the use of the above method in Golang:



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate
// reflect.Elem() Function
  
package main
   
import (
    "fmt"
    "reflect"
       
)
type Book struct {
    Id    int   
    Title string
    Price float32
    Authors []string    
}
  
// Main function   
func main() {
    book := Book{}
  
    //use of Elem() method
    e := reflect.ValueOf(&book).Elem()
       
    for i := 0; i < e.NumField(); i++ {
        varName := e.Type().Field(i).Name
        varType := e.Type().Field(i).Type
        varValue := e.Field(i).Interface()
        fmt.Printf("%v %v %v\n", varName, varType, varValue)
    }
}        

chevron_right


Output:

Id int 0
Title string 
Price float32 0
Authors []string []

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

true



My Personal Notes arrow_drop_up

Small things always make you to think big

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.