
我从导入的第三方模块的包中收到一个项目:
myitem := importpackage.get()
它是一个像这样的结构:
type importedstruct struct {
ip net.ip `json:"ip"`
index uint32 `json:"index"`
localindex uint32 `json:"localindex"`
remoteindex []*udp.addr `json:"remoteindex"`
certificates *certificates `json:"certificates"`
vpnaddress []iputil.vpnip `json:"vpnaddress"`
}我想删除其中的一项或多项,然后再从我的 golang gin api 以 json 形式返回:
立即学习“go语言免费学习笔记(深入)”;
c.json(200, &myitem)
问题是试图找到最有效的资源利用方式来做到这一点。
我考虑了一个循环并将我需要的字段写入一个新结构:
newitem := make([]importedstruct, len(myitem))
i := 0
for _, v := range myitem {
newitem[i] = ...
...
}
c.json(200, &hostlist)我还考虑过编组,然后解组以将其分配给另一个结构,然后再通过 api 返回它:
// Marshal the host map to json
marshaledJson, err := json.Marshal(newItem)
if err != nil {
log.Error(err)
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// Unmarshal the json into structs
var unmarshalledJson []ImportedStruct
err = json.Unmarshal(marshaledJson, &unmarshalledJson)
if err != nil {
log.Error(err)
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// Return the modified host map
c.JSON(200, &unmarshalledJson)我希望找到一种更有效的方法来做到这一点。 myitem 可能包含超过 300 万行 json,并循环遍历所有内容,或者编组和解组似乎涉及更多进程,然后只需要实现相对简单的东西即可。
编辑:该结构是一个切片 ([])。
定义一个新结构,它是您现有结构的副本,并带有不同的标签:
type importedstructmarshal struct {
ip net.ip `json:"ip"`
index uint32 `json:"index"`
localindex uint32 `json:"-"`
remoteindex []*udp.addr `json:"remoteindex"`
certificates *certificates `json:"certificates"`
vpnaddress []iputil.vpnip `json:"vpnaddress"`
}然后,使用这个新结构来编组:
var input ImportedStruct forMarshal:=ImportedStructMarshal(input) ...
只要新结构与导入的结构逐个字段兼容,这就会起作用。
以上就是如何从 golang 中导入的包接收的结构中删除某些项目?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号