英文:
Go Redefined type formating and methods
问题
这是一个基本的Go程序:
package main
import (
"fmt"
"time"
)
type myTime time.Time
func main() {
my := myTime(time.Now())
fmt.Println(my)
normal := time.Now()
fmt.Println(normal)
}
对应的输出结果是:
{63547112172 291468455 0x545980}
2014-09-23 23:36:12.292132305 +0000 UTC
我想知道为什么myTime
的打印结果与time.Time
不同。它们本质上应该是相同类型的... 另外,如果我尝试访问time.Time
的任何方法,比如Day
,它对于normal
是可用的,但对于my
却不可用。
谢谢!
英文:
Here is a basic go program
package main
import (
"fmt"
"time"
)
type myTime time.Time
func main() {
my := myTime(time.Now())
fmt.Println(my)
normal := time.Now()
fmt.Println(normal)
}
And the corresponding output
{63547112172 291468455 0x545980}
2014-09-23 23:36:12.292132305 +0000 UTC
I would like to know why myTime prints diffrently than time.Time. They basically are supposed to be from the same type... Also, if I try to access any method of time.Time, let's say, Day, it's available for "normal" but not for "my".
Thanks!
答案1
得分: 3
你的新类型没有继承time.Time
的方法。根据规范的引用:
声明的类型不会继承绑定到现有类型的任何方法。
由于没有String
方法,它不会打印出有意义的值。你需要自己实现这个方法。
另一种选择是在你自己的类型中嵌入time.Time
。这样你就可以包含time.Time
的功能,同时添加自己的功能。
Playground链接:http://play.golang.org/p/PY6LIBoP6H
type myTime struct {
time.Time
}
func (t myTime) String() string {
return "<自定义格式>"
}
func main() {
my := myTime{time.Now()}
fmt.Println(my)
normal := time.Now()
fmt.Println(normal)
}
英文:
Your new type does not inherit methods from time.Time
. To quote the spec:
> The declared type does not inherit any methods bound to the existing type
Since there is no String
method, it won't print a meaningful value. You need to implement that yourself.
Your other option is to embed time.Time
in your own type. That way you can include the functionality of time.Time
but also add your own functionality.
Playground link: http://play.golang.org/p/PY6LIBoP6H
type myTime struct {
time.Time
}
func (t myTime) String() string {
return "<Custom format here>"
}
func main() {
my := myTime{time.Now()}
fmt.Println(my)
normal := time.Now()
fmt.Println(normal)
}
答案2
得分: 2
fmt.Println
在将类型格式化为字符串时使用String()
方法(或者更准确地说,fmt.Stringer
接口),如果该方法可用。当您使用基础类型(在您的情况下为time.Time
)创建一个新类型时:
type myTime time.Time
您将不会继承基础类型的方法集。因此,myTime
没有String()
方法,因此fmt将使用结构体的默认格式。
英文:
fmt.Println
uses the String()
method (or rather the fmt.Stringer
interface) when formatting a type as a string, if it is available. When you create a new type using an underlying type (in your case time.Time
):
type myTime time.Time
You will not inherit the methodset of the underlying type. Therefore, myTime
has no String()
method, so fmt will use the default format for a struct.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论