How can I change the pointer type and value of an interface variable using reflection in Go?

DDD
Release: 2024-11-17 11:05:02
Original
587 people have browsed it

How can I change the pointer type and value of an interface variable using reflection in Go?

Changing Pointer Type and Value under Interface with Reflection

Question

How can we change the pointer type and value of a variable defined by an interface using reflection?

Answer

In Go, everything is passed by value, including interfaces. When assigning an interface value, a copy is made, limiting the modification potential.

To modify the value stored in an interface variable, its address must be used. By accessing the variable's address through reflect.ValueOf(&varName).Elem(), we can set a new pointer value into it.

Example

var a fmt.Stringer // Interface variable
a = &Greeter{"John"}

v := reflect.ValueOf(&a).Elem() // Access variable's address
v.Set(reflect.ValueOf(&Greeter2{"Jack"})) // Set new pointer value

fmt.Println(a.String()) // Hello2, My name is Jack (Greeter2.String() called)
Copy after login

Key Points

  • Start from the address using reflect.ValueOf(&varName).
  • Set a pointer value into it, as interfaces implemented by pointers cannot be set into copies.

Limitations

  • Modifying a copy is impossible due to Go's pass-by-value nature. Only by passing a pointer can the pointed value be modified, effectively changing the variable's value.
  • Changing the interface type of a variable is not possible, as the variable's actual type is determined at compile time.

The above is the detailed content of How can I change the pointer type and value of an interface variable using reflection in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template