【问题标题】:Golang custom type fmt printingGolang 自定义类型 fmt 打印
【发布时间】:2020-05-01 08:27:27
【问题描述】:

我有一个这样的自定义类型:

type Timestamp struct {
    Time time.Time  
}
// some more methods...

现在当我使用fmt 打印它的一个实例时:

test := Timestamp{
    Time: time.Now(),
}
fmt.Println("TEST:", test)

输出是:

TEST: {2009-11-10 23:00:00 +0000 UTC m=+0.000000001}

在应该使用fmt 函数(Println 等)打印输出的情况下,如何将自定义格式添加到自定义类型以漂亮地打印输出,例如 2009-11-10T23:00:00Z

【问题讨论】:

    标签: go formatting println gofmt


    【解决方案1】:

    添加这个函数就这么简单:

    func (ts Timestamp) Format(f fmt.State, c rune) {
        f.Write([]byte(ts.Time.Format(time.RFC3339)))
    }
    

    输出:

    TEST: 2020-05-01T08:25:14Z
    

    【讨论】:

    • 在大多数情况下,更简单的方法是提供String() 方法。
    猜你喜欢
    • 2014-01-12
    • 2020-05-31
    • 2020-11-18
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多