根据我的要求,我创建了一个结构体 -
type MyRule struct {
CreatedAt time.Time `json:"createdAt" datastore:"createdAt,noindex"`
UpdatedAt *time.Time `json:"updatedAt" datastore:"updatedAt,noindex"`
}
Run Code Online (Sandbox Code Playgroud)
对于createdAt字段,我可以将当前时间存储为-
MyRule.CreatedAt = time.Now()
Run Code Online (Sandbox Code Playgroud)
但是,同样的方法无法将当前时间存储在structupdatedAt字段中MyRule,因为它的类型为 is*time.Time和 not time.Time。在这里,我无法更改 的字段类型,updatedAt因为允许我在创建任何规则时*time.Time接受 nil 作为值。updatedAt
如果我尝试这样做-
MyRule.UpdatedAt = time.Now()
Run Code Online (Sandbox Code Playgroud)
它给了我以下错误-
cannot use time.Now()(type time.Time) as type *time.Time in assignment
Run Code Online (Sandbox Code Playgroud)
如何将当前时间值存储在类型为 *time.Time 而不是 time.Time 的 UpdatedAt 字段中
注意:无法获取返回值的地址,因此这样的方法不起作用:
MyRule.UpdatedAt = &time.Now() // compile fail
Run Code Online (Sandbox Code Playgroud)
要获取值的地址,它必须位于可寻址项中。因此将值分配给变量,如下所示:
t := time.Now()
MyRule.UpdatedAt = &t
Run Code Online (Sandbox Code Playgroud)