尝试使用此方法在我的应用程序中使用时间戳:https://gist.github.com/bsphere/8369aca6dde3e7b4392c#file-timestamp-go
这是:
package timestamp
import (
"fmt"
"labix.org/v2/mgo/bson"
"strconv"
"time"
)
type Timestamp time.Time
func (t *Timestamp) MarshalJSON() ([]byte, error) {
ts := time.Time(*t).Unix()
stamp := fmt.Sprint(ts)
return []byte(stamp), nil
}
func (t *Timestamp) UnmarshalJSON(b []byte) error {
ts, err := strconv.Atoi(string(b))
if err != nil {
return err
}
*t = Timestamp(time.Unix(int64(ts), 0))
return nil
}
func (t Timestamp) GetBSON() (interface{}, error) {
if time.Time(*t).IsZero() {
return nil, nil
}
return time.Time(*t), nil
}
func (t *Timestamp) SetBSON(raw bson.Raw) error {
var tm time.Time
if err := raw.Unmarshal(&tm); err != nil {
return err
}
*t = Timestamp(tm)
return nil
}
func (t *Timestamp) String() string {
return time.Time(*t).String()
}
以及与之相关的文章:https://medium.com/coding-and-deploying-in-the-cloud/time-stamps-in-golang-abcaf581b72f
但是,我收到以下错误:
core/timestamp/timestamp.go:31: invalid indirect of t (type Timestamp)
core/timestamp/timestamp.go:35: invalid indirect of t (type Timestamp)
我的相关代码如下所示:
import (
"github.com/path/to/timestamp"
)
type User struct {
Name string
Created_at *timestamp.Timestamp `bson:"created_at,omitempty" json:"created_at,omitempty"`
}
谁能看到我做错了什么?
相关问题 我也看不出如何实现这个包。我是否创建了这样的新用户模型?
u := User{Name: "Joe Bloggs", Created_at: timestamp.Timestamp(time.Now())}
答案 0 :(得分:4)
您的代码有拼写错误。您不能取消引用非指针,因此您需要使GetBSON成为指针接收器(或者您可以将间接移除到t
,因为方法不会更改t
的值) 。
func (t *Timestamp) GetBSON() (interface{}, error) {
要设置内联*Timestamp
值,您需要转换*time.Time
。
now := time.Now()
u := User{
Name: "Bob",
CreatedAt: (*Timestamp)(&now),
}
构造函数和辅助函数(如New()
和Now()
)也可以派上用场。
答案 1 :(得分:0)
你不能引用不是指针变量的东西的间接。
var a int = 3 // a = 3
var A *int = &a // A = 0x10436184
fmt.Println(*A == a) // true, both equals 3
fmt.Println(*&a == a) // true, both equals 3
fmt.Println(*a) // invalid indirect of a (type int)
因此,您无法使用a
引用*a
的地址。
查看错误发生的位置:
func (t Timestamp) GetBSON() (interface{}, error) {
// t is a variable type Timestamp, not type *Timestamp (pointer)
// so this is not possible at all, unless t is a pointer variable
// and you're trying to dereference it to get the Timestamp value
if time.Time(*t).IsZero() {
return nil, nil
}
// so is this
return time.Time(*t), nil
}