gpt4 book ai didi

go - Golang嵌入了“time.Time”,打印在其他字段上

转载 作者:行者123 更新时间:2023-12-01 22:39:04 27 4
gpt4 key购买 nike

我是Go中的新手。这是一个困扰我的问题。
简而言之,当我打印一个带有struct类型的匿名字段的time.Time时,输出类似于单独打印的time.Time变量。大括号或其他字段均未显示。

package main

import (
"fmt"
"time"
)

type Embedding struct {
i int
time.Time
}
type NoEmbedding struct {
i int
Present time.Time
}

func main() {

// `embedding` and `noEmbedding` shared exactly the same content
embedding := Embedding{
1,
time.Now(),
}
noEmbedding := NoEmbedding{
1,
time.Now(),
}

fmt.Println("embedding:\n", embedding)
fmt.Println("no embedding:\n", noEmbedding)
}

/* output
embedding:
2020-09-18 01:42:37.9201284 +0800 CST m=+0.011626601
no embedding:
{1 2020-09-18 01:42:37.9201284 +0800 CST m=+0.011626601}
*/
从本质上讲,这个问题是 "Why is time in Go printed differently in a struct?"的又一步。我已经过了 "Embedding in GO",但仍未找到任何线索。

最佳答案

如果存在,fmt.Println将使用String方法。当您在结构中嵌入时间值时,StringTime方法被提升为结构的String方法。这就是为什么它打印不同的原因。

关于go - Golang嵌入了“time.Time”,打印在其他字段上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63943979/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com