英文:
Go: How to format this struct in a readable way?
问题
我有一个包装了time.Time
对象的结构体,并希望以可读的方式格式化它。
package main
import (
"time"
"fmt"
)
type TimeStruct struct {
t time.Time
}
func main() {
t := time.Now()
fmt.Printf("time: %v\n", t) // nice
ts := TimeStruct{t: t}
fmt.Printf("time struct: %#v\n", ts) // ugly
}
为什么Go不像普通的time.Time
对象一样格式化TimeStruct
中的t
字段?有没有一种简单的方法可以以可读的方式格式化它(而不需要定义额外的方法)?
英文:
I have a struct wrapping a time.Time
object and would like to format it in a human readable way.
package main
import (
"time"
"fmt"
)
type TimeStruct struct {
t time.Time
}
func main() {
t := time.Now()
fmt.Printf("time: %v\n", t) // nice
ts := TimeStruct{t: t}
fmt.Printf("time struct: %#v\n", ts) // ugly
}
(Play)
Why doesn't Go format the t
field in TimeStruct
the same as a plain time.Time
object? Is there a simple way to format this in a readable way (without defining extra methods for it)?
答案1
得分: 3
你可以通过实现Stringer接口来获得使用%v
时所需的可读时间。
package main
import (
"time"
"fmt"
)
type TimeStruct struct {
t time.Time
}
func (self TimeStruct) String() string {
return fmt.Sprintf("TimeStruct{time.Time: %v}", self.t)
}
func main() {
t := time.Now()
ts := TimeStruct{t: t}
// time struct: TimeStruct{time.Time: 2009-11-10 23:00:00 +0000 UTC}
fmt.Printf("time struct: %v\n", ts)
}
以上是实现的代码部分。
英文:
The only way for you to get the human readable time you want when using %v
is to implement the Stringer interface.
package main
import (
"time"
"fmt"
)
type TimeStruct struct {
t time.Time
}
func (self TimeStruct) String() string {
return fmt.Sprintf("TimeStruct{time.Time: %v}", self.t)
}
func main() {
t := time.Now()
ts := TimeStruct{t: t}
// time struct: TimeStruct{time.Time: 2009-11-10 23:00:00 +0000 UTC}
fmt.Printf("time struct: %v\n", ts)
}
答案2
得分: 1
另一种选择是嵌入时间,这样它的方法就可以在你的TimeStruct
上使用(playground),例如:
type TimeStruct struct {
time.Time
}
func main() {
t := time.Now()
fmt.Printf("time: %v\n", t)
ts := TimeStruct{Time: t}
fmt.Printf("time struct: %v\n", ts)
}
输出结果为:
time: 2009-11-10 23:00:00 +0000 UTC
time struct: 2009-11-10 23:00:00 +0000 UTC
请注意使用%v
而不是%#v
,后者会打印结构体成员。
英文:
Another alternative would be to embed the time, so its methods are available on your TimeStruct
(playground), eg
type TimeStruct struct {
time.Time
}
func main() {
t := time.Now()
fmt.Printf("time: %v\n", t)
ts := TimeStruct{Time: t}
fmt.Printf("time struct: %v\n", ts)
}
Which prints
time: 2009-11-10 23:00:00 +0000 UTC
time struct: 2009-11-10 23:00:00 +0000 UTC
Note the use of %v
not %#v
which will print the struct members.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论