3 回答

TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超9個(gè)贊
不要這樣做。time.Time當(dāng)您應(yīng)該檢查對(duì)象是否滿足接口時(shí),您正在檢查對(duì)象。
type TimeLike interface {
Day() int
Format(string) string
... // whatever makes a "time" object to your code!
// looks like in this case it's
UTC() time.Time
IsZero() bool
}
那么任何需要 a 的代碼time.Time都可以用 a 替換,而是PythonTime期待 a TimeLike。
function Foo(value interface{}) int {
switch v := value.(type) {
case TimeLike:
return v.Day() // works for either time.Time or models.PythonTime
}
return 0
}

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超9個(gè)贊
就像使用json.Marshalerand 一樣json.Unamrshaler,您也可以實(shí)現(xiàn)接口。gocql.Marshaler gocql.Unamrshaler
func (t *PythonTime) MarshalCQL(info gocql.TypeInfo) ([]byte, error) {
b := make([]byte, 8)
x := t.UnixNano() / int64(time.Millisecond)
binary.BigEndian.PutUint64(b, uint64(x))
return b, nil
}
func (t *PythonTime) UnmarshalCQL(info gocql.TypeInfo, data []byte) error {
x := int64(binary.BigEndian.Uint64(data)) * int64(time.Millisecond)
t.Time = time.Unix(0, x)
return nil
}
(注意,在 CQL 的上下文中未經(jīng)測(cè)試,但這會(huì)與自身進(jìn)行往返)

TA貢獻(xiàn)1911條經(jīng)驗(yàn) 獲得超7個(gè)贊
不幸的是,這在 Go 中不起作用。您最好的選擇是創(chuàng)建一些導(dǎo)入和導(dǎo)出方法,以便您可以將 PythonTime 轉(zhuǎn)換為 time.Time,反之亦然。這將為您提供所需的靈活性以及與其他庫(kù)的兼容性。
package main
import (
"fmt"
"reflect"
"time"
)
func main() {
p, e := NewFromTime(time.Now())
if e != nil {
panic(e)
}
v, e := p.MarshalJSON()
if e != nil {
panic(e)
}
fmt.Println(string(v), reflect.TypeOf(p))
t, e := p.GetTime()
if e != nil {
panic(e)
}
fmt.Println(t.String(), reflect.TypeOf(t))
}
type PythonTime struct {
time.Time
}
var pythonTimeFormatStr = "2006-01-02 15:04:05-0700"
func NewFromTime(t time.Time) (*PythonTime, error) {
b, e := t.GobEncode()
if e != nil {
return nil, e
}
p := new(PythonTime)
e = p.GobDecode(b)
if e != nil {
return nil, e
}
return p, nil
}
func (self *PythonTime) GetTime() (time.Time, error) {
return time.Parse(pythonTimeFormatStr, self.Format(pythonTimeFormatStr))
}
func (self *PythonTime) UnmarshalJSON(b []byte) (err error) {
// removes prepending/trailing " in the string
if b[0] == '"' && b[len(b)-1] == '"' {
b = b[1 : len(b)-1]
}
self.Time, err = time.Parse(pythonTimeFormatStr, string(b))
return
}
func (self *PythonTime) MarshalJSON() ([]byte, error) {
return []byte(self.Time.Format(pythonTimeFormatStr)), nil
}
那應(yīng)該給出這樣的輸出:
2016-02-04 14:32:17-0700 *main.PythonTime
2016-02-04 14:32:17 -0700 MST time.Time
- 3 回答
- 0 關(guān)注
- 230 瀏覽
添加回答
舉報(bào)