当前位置: 首页 > 面试题库 >

Go-复制结构之间的所有公共字段

皇甫浩壤
2023-03-14
问题内容

我有一个存储JSON的数据库,以及一个提供外部API的服务器,通过它可以通过HTTP发布更改此数据库中的值。数据库由内部的不同进程使用,因此具有通用的命名方案。

客户看到的密钥不同,但是将1:1与数据库中的密钥映射(有未公开的密钥)。例如:

这是在数据库中:

{ "bit_size": 8, "secret_key": false }

这是呈现给客户的:

{ "num_bits": 8 }

API可以根据字段名称进行更改,但是数据库始终具有一致的密钥。

我已经在结构中将字段命名为相同,但对json编码器使用了不同的标志:

type DB struct {
    NumBits int  `json:"bit_size"`
    Secret  bool `json:"secret_key"`
}
type User struct {
    NumBits int `json:"num_bits"`
}

encoding/json过去经常做元帅/元帅。

reflect正确的工具吗?因为所有键都相同,有没有更简单的方法?我在想某种memcpy(如果我将用户字段的顺序保持一致)。


问题答案:

这是使用反射的html" target="_blank">解决方案。如果您需要带有嵌入式结构字段等的更复杂的结构,则必须进一步开发它。

http://play.golang.org/p/iTaDgsdSaI

package main

import (
    "encoding/json"
    "fmt"
    "reflect"
)

type M map[string]interface{} // just an alias

var Record = []byte(`{ "bit_size": 8, "secret_key": false }`)

type DB struct {
    NumBits int  `json:"bit_size"`
    Secret  bool `json:"secret_key"`
}

type User struct {
    NumBits int `json:"num_bits"`
}

func main() {
    d := new(DB)
    e := json.Unmarshal(Record, d)
    if e != nil {
        panic(e)
    }
    m := mapFields(d)
    fmt.Println("Mapped fields: ", m)
    u := new(User)
    o := applyMap(u, m)
    fmt.Println("Applied map: ", o)
    j, e := json.Marshal(o)
    if e != nil {
        panic(e)
    }
    fmt.Println("Output JSON: ", string(j))
}

func applyMap(u *User, m M) M {
    t := reflect.TypeOf(u).Elem()
    o := make(M)
    for i := 0; i < t.NumField(); i++ {
        f := t.FieldByIndex([]int{i})
        // skip unexported fields
        if f.PkgPath != "" {
            continue
        }
        if x, ok := m[f.Name]; ok {
            k := f.Tag.Get("json")
            o[k] = x
        }
    }
    return o
}

func mapFields(x *DB) M {
    o := make(M)
    v := reflect.ValueOf(x).Elem()
    t := v.Type()
    for i := 0; i < v.NumField(); i++ {
        f := t.FieldByIndex([]int{i})
        // skip unexported fields
        if f.PkgPath != "" {
            continue
        }
        o[f.Name] = v.FieldByIndex([]int{i}).Interface()
    }
    return o
}


 类似资料:
  • 链接 依赖注入 会话管理 缓存管理 日志管理 设置管理 时间与时区设置 对象之间的映射(AutoMapper集成) 邮件发送(MailKit集成)

  • 2.7 ABP公共结构 - 对象之间的映射 2.7.1 简介 我们通常需要在近似的对象之间进行映射处理。这是一个重复且枯燥无味的工作,通常来说两个需要相互映射的对象之间有近似的或者相同的属性。思考一下这样一个案例:应用服务的方法: public class UserAppService : ApplicationService { private readonly IRepository<

  • 2.6 ABP公共结构 - 时间与时区设置 2.6.1 简介 虽然有些应用的需求是单时区,然而另一些是需要对不同的时区进行处理的。为了满足这样的需求以及对时间的处理。ABP提供了处理时间操作的通用基础设施。 2.6.2 Clock Clock 这个类是主要用来处理 DateTime 的值。它具有以下静态属性和方法: Now :根据当前设置的提供器来获取当前时间 Kind :取得当前提供器的 Dat

  • 以下两者之间的区别是什么:

  • 在中,您可以包含一个方法,该方法在或之前调用,那么在Spring中有没有实现相同的方法? 或者更准确地说,在控制器中的每个方法中,我需要确保存在一个实体(在本例中,是一个产品),然后重定向否则,就像这样,那么在Spring中该如何实现呢?注意,我还需要每个方法中可用的产品。

  • 我用过 提取 从 但我只得到这个 如何修复我的正则表达式?