Open In App

reflect.Elem() Function in Golang with Examples

Last Updated : 03 May, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report
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: C
// 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)
    }
}        
Output:
Id int 0
Title string 
Price float32 0
Authors []string []
Example 2: C
// 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))
}     
Output:
true

Next Article
Article Tags :

Similar Reads