gpt4 book ai didi

go - 将嵌入式结构复制到新结构中,而不必复制其所有字段

转载 作者:行者123 更新时间:2023-12-01 22:33:51 25 4
gpt4 key购买 nike

我有一个逻辑结构

type MyStruct struct {
F1 string
F2 string
}
我想将 MyStruct类型的值保存到文档db,仅添加时间戳。所以我创建了一个新的嵌入 MyStruct的结构
type MyStructForDB {
MyStruct
Ts time.Time
}
在saveToDb函数中,执行以下操作
func saveToDb(s MyStruct) {
sDb := MyStructForDB{
s, time.Now()
}
// execute the update on the DB
}
如果我这样进行,则在数据库上找到具有以下结构的文档
{
myStruct: {
f1: "a value" // any value that was in s.F1
f2: "another value" // any value that was in s.F2
}
ts: 2020-06-26T14:15:07.050Z // a timestamp value
}
虽然可以,但我不希望看到 myStruct属性,而不会看到像这样的扁平文档
{
f1: "a value" // any value that was in s.F1
f2: "another value" // any value that was in s.F2
ts: 2020-06-26T14:15:07.050Z // a timestamp value
}
我知道我可以一一复制字段或使用反射来完成此操作,但是我只是想知道是否有更简单的方法来实现此目的

最佳答案

在DocumentDB中,可以使用inline包的bson标志来展平嵌入式结构

type MyStructForDB {
MyStruct `bson:",inline"`
Ts time.Time
}

关于go - 将嵌入式结构复制到新结构中,而不必复制其所有字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62596992/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com