How to "cast" a pointer back to a value in Golang?

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

How to "cast" a pointer back to a value in Golang?

问题

我正在使用time.Time作为我的结构体之一中的指针。例如:

type struct Example{
    CreatedDate *time.Time
}

我使用指针,这样如果没有日期存在,我就可以将nil传递给结构体。

然而,现在出现了一个问题,因为我需要使用time.Since(then)函数,该函数不接受指针作为参数,而是接受time.Time。

所以...

在结构体前面加上"&"很容易,例如&time.Time,但如果你有一个指针,你如何将其转换回time.Time类型呢?

例如(不起作用,但可能会给你一个想法):

var t *time.Time = &time.Now()
var t2 time.Time = t.(time.Time)

我希望你能帮助我。这个问题感觉很愚蠢,因为当我在谷歌上搜索时找不到任何相关信息。我感觉我在这里只是漏掉了什么东西;-)

英文:

I'm using time.Time as a pointer in one of my structs. Eg

type struct Example{
    CreatedDate *time.Time
}

I'm using the pointer, so I can pass nil to the struct, if no date exists.

This does however pose a problem now, since I need to use the time.Since(then) function which does not accept the pointer as the parameter, but takes a time.Time instead.

So...

It's quite easy to put "&" in front of a struct eg. &time.Time, but if you have a pointer, how can you reverse it, back into eg. a type of time.Time?

Eg. (does not work, but might give you an idea of what I mean)

var t *time.Time = &time.Now()
var t2 time.Time = t.(time.Time)

I hope you can help. The question feels quite silly, since I can't find anything about it when googling. I get the feeling I'm just missing something here How to "cast" a pointer back to a value in Golang?

答案1

得分: 89

var t *time.Time = &time.Now()
var t2 time.Time = *t

就像在C语言中一样,&表示“取地址”,并将其分配给一个标记为*T的指针。但是*也表示“取值”,或者解引用指针,并将值分配给变量。

这有点离题,但我认为*的这种双重用途部分是让C语言新手对指针感到困惑的原因之一。

英文:
var t *time.Time = &time.Now()
var t2 time.Time = *t

Just like in C, & means "address of" and assigns a pointer which is marked as *T. But * also means "value of", or dereferencing the pointer, and assigns the value.

This is a bit off-topic, but IMO this dual use of * is partly what gets newbies in C and friends confused about pointers.

huangapple
  • 本文由 发表于 2015年3月13日 05:26:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/29020523.html
匿名

发表评论

匿名网友

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

确定