首页 > 后端开发 > Golang > 正文

如何从 golang 中导入的包接收的结构中删除某些项目?

WBOY
发布: 2024-02-06 08:40:06
转载
1067人浏览过

如何从 golang 中导入的包接收的结构中删除某些项目?

问题内容

我从导入的第三方模块的包中收到一个项目:

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)

问题是试图找到最有效的资源利用方式来做到这一点。

我考虑了一个循环并将我需要的字段写入一个新结构:

人声去除
人声去除

用强大的AI算法将声音从音乐中分离出来

人声去除 23
查看详情 人声去除
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中文网其它相关文章!

相关标签:
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:stackoverflow网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门推荐
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号