如何在Golang中创建结构运行时



例如,我有一个从外部捕获的结构。我不知道字段和字段值中的结构。我想复制和使用相同的结构。通过反射,我找到了其中的字段和类型。但是如何在 Runtime

中创建此结构

编辑:我只想创建与运行时相同名称的结构。想象我不认识我的人。我只想通过接口进行反射创建相同的结构。我只知道一个接口。我刚刚创建的人结构。当一个人创建结构并将其发送出去时,我将创建它。您可以发送而不是人,客户,学生等。将以下代码视为第三方库。


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
}

github.com/mitchellh/copystructure库处理此操作,称为深副本。执行深副本后,原始和副本包含相同的数据,但对一个都不影响另一个数据。

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: %#vn", original)
    // The copy of the Person has not change, still has Id:0.
    fmt.Printf("copy: %#vn", copy)
}
func deepCopy(original interface{}) interface{} {
    copy, err := copystructure.Copy(original)
    if err != nil {
        panic(err)
    }
    return copy
}

最新更新