JimF
JimF

Reputation: 171

GOLANG: composite literal uses unkeyed fields

I've been given the following code:

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
}

and I'm trying to use it like:

package main

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

And, I get the following error:

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")

I've also tried: t2 := catalog.Time{Time: t} and several other variations. Any suggestions?

Thanks

Upvotes: 2

Views: 9767

Answers (1)

dave
dave

Reputation: 64657

I think you are wanting to do

t2 := catalog.Time(t)

You have declared catalog.Time as a type with an underlying type of time.Time, so to convert between them you need to do catalog.Time(time.Time).

Currently you have written it as if you had an embedded type, which would only work if you had

type Time struct {
    time.Time
}

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

Upvotes: 5

Related Questions