简体   繁体   English

如何在 golang 中创建 struct 运行时

[英]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.例如,我刚刚创建的 Person 结构体。 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.将以下代码视为第 3 方库。


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 . github.com/mitchellh/copystructure库处理这个操作,称为深拷贝 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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