What is the method for instantiating objects using reflection in the Go language?

In Go language, you can use the reflect.New() function to instantiate an object of a specific type. This function takes a reflect.Type parameter and returns a pointer to a new allocated zero value of that type.

Here is an example of instantiating an object using reflection:

package main

import (
	"fmt"
	"reflect"
)

type Person struct {
	Name string
	Age  int
}

func main() {
	pType := reflect.TypeOf(Person{})
	pValue := reflect.New(pType)

	p := pValue.Interface().(*Person)

	p.Name = "Alice"
	p.Age = 25

	fmt.Println(p)
}

In the example above, the reflect.TypeOf() function is first used to obtain a reflection object of the Person type. Then the reflect.New() function is used to pass in the reflection object and return a pointer to a newly allocated zero value of the Person type. Finally, the Interface() method is used to convert the reflection value to an interface value, and then it is cast to a pointer of type *Person using type assertion.

The output is:

&{Alice 25}

This way, an object of type Person is instantiated through reflection.

bannerAds