简体   繁体   中英

How to create struct runtime in golang

For example, I have a struct that I take from the outside. I do not know the struct in fields and field values. I want to copy and use the same struct. With reflection I find the fields and types in it. But how do I create this struct in the runtime ?

Edit : I just want to create a struct in the same name as the runtime. Imagine I do not know my person type. I just want to create the same struct by reflection with interface. I only know one interface. Person struct I just created it for instance. When a person creates a struct and sends it out, I will create it. instead of person, customer, student etc. You can send. consider the following code as a 3rd party library.


package main

import(

    "fmt" 
    "reflect"
)

type Person struct {
    Id  int  
    Name string   
    Surname string  
}

func main(){

    person := NewSomething()

    newPerson := typeReflection(person)

    ChangePerson(newPerson)

    fmt.Println("Success")
}

func typeReflection(_person interface{}){

    val := reflect.ValueOf(_person)
    //How to create same struct

}



The github.com/mitchellh/copystructure library handles this operation, which is known as a deep copy . After performing a deep copy, the original and the copy contain the same data but modifications to either one do not affect the other.

package main

import (
    "fmt"

    "github.com/mitchellh/copystructure"
)

type Person struct {
    Id      int
    Name    string
    Surname string
}

func main() {
    original := Person{Id: 0, Name: "n", Surname: "s"}

    copy := deepCopy(original)

    // Change fields of the original Person.
    original.Id = 9
    fmt.Printf("original: %#v\n", original)

    // The copy of the Person has not change, still has Id:0.
    fmt.Printf("copy: %#v\n", copy)
}

func deepCopy(original interface{}) interface{} {
    copy, err := copystructure.Copy(original)
    if err != nil {
        panic(err)
    }
    return copy
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM