Skip to content

Instantly share code, notes, and snippets.

@nidorx
Created May 13, 2024 02:18
Show Gist options
  • Save nidorx/b6e1549c03a1c911e35c81e47f31e532 to your computer and use it in GitHub Desktop.
Save nidorx/b6e1549c03a1c911e35c81e47f31e532 to your computer and use it in GitHub Desktop.
`interface {struct}` and `interface {*struct}` manipulation in Golang using reflect.
/**
* `interface {struct}` and `interface {*struct}` manipulation in Golang using reflect.
*
* Use case: To instantiate a struct using reflect and use libraries like JSON.Decode at runtime.
*/
package main
import "reflect"
type Struct struct {
Name string
}
func init() {
intp_ptr := reflect.TypeOf((*Struct)(nil)) // Type *Struct
intp_nptr := intp_ptr.Elem() // Type Struct
// VALUE
nptr_ptr := reflect.New(intp_nptr) // Pointer Struct
nptr_val := nptr_ptr.Elem() // Value Struct
nptr_vle_ptr := nptr_val.Addr() // Value *Struct
// POINTER
ptr := reflect.New(intp_ptr) // Pointer {*Struct}
ptr_val := ptr.Elem() // Value
ptr_val.Set(nptr_vle_ptr) // point to value
ptr_int := ptr_val.Interface() // interface {*Struct} <<<----- `interface {}(*main.Struct) *{Name: ""}`
reflect.Indirect(nptr_val).Field(0).SetString("Alex")
print((ptr_int.(*Struct)).Name)
(ptr_int.(*Struct)).Name = "Alex Rodin"
print((ptr_int.(*Struct)).Name)
nptr_int := nptr_val.Interface() // interface {Struct} <<<----- `interface {}(main.Struct) {Name: "Alex Rodin"}`
print((nptr_int.(Struct)).Name)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment