datetime - Why is time in Go printed differently in a struct? -
i'm starting out go, , in first program wrote printed out struct, showed
{wall:0 ext:63533980800 loc:<nil>}
being puzzled on seemed type time.time()
, , google search brought me this part of go source code in difference between "wall clock" , "monotonic clock" explained in comments.
so test in isolation created new minimalistic program:
package main import ( "fmt" "time" ) type thestruct struct { the_time time.time } func main() { the_struct := thestruct{time.now()} fmt.println(the_struct) fmt.printf("%+v\n", the_struct) fmt.println(the_struct.the_time) fmt.println() the_struct_2 := thestruct{time.unix(1505099248, 200)} fmt.println(the_struct_2) fmt.printf("%+v\n", the_struct_2) fmt.println(the_struct_2.the_time) }
which prints out following:
{{13719544904843884912 534246 0x1140680}} {the_time:{wall:13719544904843884912 ext:534246 loc:0x1140680}} 2017-09-11 05:08:11.35635032 +0200 cest m=+0.000534246 {{200 63640696048 0x1140680}} {the_time:{wall:200 ext:63640696048 loc:0x1140680}} 2017-09-11 05:07:28 +0200 cest
so wonder 2 things here:
- why time if part of struct printed wall clock compared more usual datetime notation when printed out separately (using
the_struct.the_time
)? - is problem code in other program prints out
<nil>
loc? how able solve that?
the reason why it's not printing formatted time when in struct string method not invoked on unexported fields (refer https://golang.org/pkg/fmt/):
when printing struct, fmt cannot , therefore not invoke formatting methods such error or string on unexported fields.
changing structure export fields (capitalizing first letter) makes invoke string method:
package main import ( "fmt" "time" ) type thestruct struct { the_time time.time } func main() { the_struct := thestruct{time.now()} fmt.println(the_struct) fmt.printf("%+v\n", the_struct) fmt.println(the_struct.the_time) fmt.println() the_struct_2 := thestruct{time.unix(1505099248, 200)} fmt.println(the_struct_2) fmt.printf("%+v\n", the_struct_2) fmt.println(the_struct_2.the_time) }
output:
{2009-11-10 23:00:00 +0000 utc m=+0.000000000} {the_time:2009-11-10 23:00:00 +0000 utc m=+0.000000000} 2009-11-10 23:00:00 +0000 utc m=+0.000000000 {2017-09-11 03:07:28.0000002 +0000 utc} {the_time:2017-09-11 03:07:28.0000002 +0000 utc} 2017-09-11 03:07:28.0000002 +0000 utc
on playground : https://play.golang.org/p/r0rqkblpwc
Comments
Post a Comment