2017-09-11 8 views
2

私はちょうど行くと出始めている、と私が書いた最初のプログラムでは、私も構造体でGoの時間が異なって印刷されるのはなぜですか?

{wall:0 ext:63533980800 loc:<nil>} 

が、タイプtime.Time()ように見えた何ものだった上困惑している示した構造体を、プリントアウト、およびグーグルサーチはthis part of the Go source codeに私を連れて来ました。そこでは、「壁時計」と「単調時計」の違いがコメントで説明されています。だから、単独でそれをテストするための

私は新しいミニマルなプログラム作成:

    :だから私はここについての二つのことを不思議に思う

    {{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 
    

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

    次を出力します

  1. 構造体の一部がウォールクロックとして出力されるのはなぜでしょうか? y(the_struct.the_timeを使用)?
  2. 私の他のプログラムのコードがlocのために<nil>を印刷するのは問題ですか?どのように私はそれを解決することができますか?

答えて

4

あなたの構造体に文字列のメソッドはアンエクスポートフィールド(https://golang.org/pkg/fmt/を参照してください)で呼び出されていないことであるとき、それはフォーマットされた時間を印刷していない理由:

構造体を印刷する場合、FMTはないので、することができます非公開のフィールドでエラーや文字列などの書式設定メソッドを呼び出すことはありません。フィールド(最初の文字を大文字)をエクスポートするためにあなたの構造を変更する

は、それが文字列メソッドを呼び出します:

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

出力:遊び場で

{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 

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

1

他の答えはあなたの質問の最初の部分をかなりうまくカバーしているので、ここに一部。

ソースコードtime.Timeによると、Nilの場所は問題ではありません.nilの場所はUTCを意味します。

// loc specifies the Location that should be used to 
// determine the minute, hour, month, day, and year 
// that correspond to this Time. 
// The nil location means UTC. 
// All UTC times are represented with loc==nil, never loc==&utcLoc. 
loc *Location 
関連する問題