2015-08-14 112 views
2

试图让这个方法在我的应用程序工作的戳:https://gist.github.com/bsphere/8369aca6dde3e7b4392c#file-timestamp-go时间戳在Golang

这就是:

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) 

我的相关c ODE看起来像这样:

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())} 

回答

3

您的代码有错字。您无法取消引用非指针,因此您需要使GetBSON成为指针接收器(或者您可以删除间接指向t,因为t的值不会被该方法更改)。

func (t *Timestamp) GetBSON() (interface{}, error) { 

要设置*Timestamp值内联,你需要有一个*time.Time转换。

now := time.Now() 
u := User{ 
    Name:  "Bob", 
    CreatedAt: (*Timestamp)(&now), 
} 

构造和助手像New()Now()功能可以派上用场了这一点。

+0

这就是我想,但如果你看看GH上的修订,则代码的作者专门做了一个改变了这一点。在此处查看最新版本:https://gist.github.com/bsphere/8369aca6dde3e7b4392c/revisions – tommyd456

+0

另外,您是否知道在创建新用户时如何实现此包? – tommyd456

+1

这种改变没有意义,因为它不再有效。编译它很容易验证。我不会对博客文章中随机的大量代码抱有太大的信心。 – JimB

-1

您不能引用不是指针变量的间接方式。

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 
} 
+1

你不能把函数返回的地址('&time.Now()')也不能取得转换地址('&timestamp.Timestamp(time.Now())')。该行无效Go。 – JimB

+0

@JimB你说得对。我太快了。这部分删除了谢谢。 – PieOhPah