Home >Backend Development >Golang >What's the Difference Between `reflect.ValueOf()` and `Value.Elem()` in Go?

What's the Difference Between `reflect.ValueOf()` and `Value.Elem()` in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-12-13 17:04:10895browse

What's the Difference Between `reflect.ValueOf()` and `Value.Elem()` in Go?

Understanding the Difference Between reflect.ValueOf() and Value.Elem()

Reflect.ValueOf() serves as the gateway to reflection, allowing you to obtain a reflect.Value descriptor for non-reflection values like strings or integers.

On the other hand, Value.Elem() functions as a method within reflect.Value. It can be employed to retrieve the value (also a reflect.Value) referenced by the value encapsulated by the original reflect.Value. Note that reflect.Indirect() can also be utilized for this purpose.

To transition from reflection back to non-reflection, use the Value.Interface() method, which returns the wrapped value as a simple interface{}.

var i int = 3
var p *int = &i
fmt.Println(p, i) // Output: 0x414020 3

v := reflect.ValueOf(p)
fmt.Println(v.Interface()) // Output: 0x414020

v2 := v.Elem()
fmt.Println(v2.Interface()) // Output: 3

Advanced Use Case: Value.Elem() for Interfaces

If reflect.Value wraps an interface value, Value.Elem() can also retrieve the concrete value within that interface.

var r io.Reader = os.Stdin

v := reflect.ValueOf(r)
fmt.Println(v.Type()) // Output: *os.File

v2 := reflect.ValueOf(&r)
fmt.Println(v2.Type()) // Output: *io.Reader
fmt.Println(v2.Elem().Type()) // Output: io.Reader
fmt.Println(v2.Elem().Elem().Type()) // Output: *os.File

The above is the detailed content of What's the Difference Between `reflect.ValueOf()` and `Value.Elem()` in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn