SoFunction
Updated on 2025-03-05

golang How to create a new object through reflection

Leave no nonsense, just post the code ~

type A struct {
 Name string
}
 
// Test unitfunc TestReflect(t *)  {
 reflectNew((*A)(nil))
}
 
//Reflect to create a new object.func reflectNew(target interface{})  {
 if target == nil {
  ("The parameter cannot be empty")
  return
 }
 
 t := (target)
 if () ==  { // Get the real type of pointer type requires calling Elem t = ()
 }
 
 newStruc := (t)// Call reflection to create an object ().FieldByName("Name").SetString("Lily") //Set the value 
 newVal := ().FieldByName("Name") //Get the value (())
}

Supplement: Several ways to create objects in Go

For Go Objects

type Car struct {
    color string
    size  string
}

Method 1:

Using T{…} method, the result is value type

c := Car{}

Method 2:

Using new method, the result is pointer type

c1 := new(Car)

Method 3:

Use & method, the result is pointer type

c2 := &Car{}

The following is creation and initialization

c3 := &Car{"red", "1.2L"}
c4 := &Car{color: "red"}
c5 := Car{color: "red"}

Constructor:

There is no concept of constructor in Go language. The creation of objects is usually done by a global creation function, named after NewXXX, denoting "constructor":

func NewCar(color,size string)*Car  {
    return &Car{color,size}
}

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.