英文:
Assign pointer to variable in Golang
问题
我正在使用Golang进行工作,我有一个包含一些字段的结构体,其中一个字段是time.Time
类型的字段,用于保存Delete_At
,因此它可以为空,基本上我已经定义如下:
type Contact struct {
Delete_At *time.Time
}
所以,通过指针它可以为空。然后,当给这个值赋值时,我有如下代码:
contact := Contact{}
contact.Deleted_At = time.Now()
但是,我得到了以下错误:
cannot use time.Now() (type time.Time) as type *time.Time in assignment
我完全理解这是一个错误的赋值,但是,我应该如何做呢?应该如何进行转换?
英文:
I am working in Golang, I have a Struct that contains some fields, one of them is a time.Time
field to save the Delete_At
so it can be null, basically I have defined it as:
type Contact struct {
Delete_At *time.Time
}
So, with the pointer it can be null. Then, I have a method when this value is assigned, I have something like:
contact := Contact{}
contact.Deleted_At = time.Now()
But with it, I get:
cannot use time.Now() (type time.Time) as type *time.Time in assignment
I totally understand that is a bad assignment, but, how should I do it? how the conversion should be done?
答案1
得分: 7
t := time.Now()
contact.Deleted_At = &t
顺便说一下,你不应该在变量名中使用“_”。推荐使用“DeletedAt”作为变量名。
英文:
t := time.Now()
contact.Deleted_At = &t
And BTW, you should not use _
in variable names. DeletedAt
would be the recommended name.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论