Assign pointer to variable in Golang

huangapple go评论99阅读模式
英文:

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_Atso 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.

huangapple
  • 本文由 发表于 2017年5月28日 04:29:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/44221345.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定