【问题标题】:GOLANG: composite literal uses unkeyed fieldsGOLANG:复合文字使用无键字段
【发布时间】:2018-04-19 07:00:02
【问题描述】:

我得到了以下代码:

package catalog
...
type Time time.Time
func (t Time) MarshalJSON() ([]byte, error) {
   got := time.Time(t)
   stamp := fmt.Sprintf("\"%s\"", got.In(time.UTC).Format("2006-01-02T15:04:05.000Z"))
   return []byte(stamp), nil
}

我正在尝试像这样使用它:

package main

func main() {
   ...
   t := *a.StartTime  <<== This returns a time.Time
   t2 := catalog.Time{t}
}

而且,我收到以下错误:

catalog.Time composite literal uses unkeyed fields
implicit assignment of unexported field 'wall' in catalog.Time literal
cannot use t (type time.Time) as type uint64 in field value
too few values in structure initializer
import (catalog ".../go-catalog-types.git")

我也尝试过:t2 := catalog.Time{Time: t} 和其他几个变体。有什么建议吗?

谢谢

【问题讨论】:

    标签: go


    【解决方案1】:

    我想你想做

    t2 := catalog.Time(t)
    

    您已将catalog.Time 声明为具有time.Timeunderlying type 的类型,因此要在它们之间进行转换,您需要执行catalog.Time(time.Time)

    目前你已经把它写成好像你有一个embedded type,这只有在你有的时候才能工作

    type Time struct {
        time.Time
    }
    

    https://play.golang.org/p/zbwf6ZfvX3

    【讨论】:

      猜你喜欢
      • 2019-06-30
      • 1970-01-01
      • 2018-09-02
      • 1970-01-01
      • 2016-07-16
      • 2021-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多