reflect.Elem() Function in Golang with Examples
Last Updated :
03 May, 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.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:
package main
import (
"fmt"
"reflect"
)
type Book struct {
Id int
Title string
Price float32
Authors []string
}
func main() {
book := Book{}
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:
package main
import (
"fmt"
"reflect"
"io"
"os"
)
func main() {
writerType := reflect.TypeOf((*io.Writer)(nil)).Elem()
fileType := reflect.TypeOf((*os.File)(nil))
fmt.Println(fileType.Implements(writerType))
}
|
Output:
true
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...