gpt4 book ai didi

string - 为什么打印 time.Time 和指向 time.Time 的指针具有相同的结果?

转载 作者:行者123 更新时间:2023-12-02 23:35:56 25 4
gpt4 key购买 nike

我不明白为什么下面的结果是一样的。我预计第一个结果是指针地址。

func print(t *time.Time) {
fmt.Println(t) // 2009-11-10 23:00:00 +0000 UTC m=+0.000000001 => it should be the address of t
fmt.Println(*t) // 2009-11-10 23:00:00 +0000 UTC m=+0.000000001
}

最佳答案

因为你使用 fmt.Println() 打印它这意味着将应用默认格式。并引用 fmt 的包文档:

Except when printed using the verbs %T and %p, special formatting considerations apply for operands that implement certain interfaces. In order of application:

[...]

  1. If an operand implements method String() string, that method will be invoked to convert the object to a string, which will then be formatted as required by the verb (if any).

time.Time有一个Time.String()方法,指向它的指针也是如此:*time.Time 也有这个 String() 方法。因此,fmt 包调用它来生成 *time.Time 值的字符串表示形式。

引用自Spec: Method sets:

The method set of any other type T consists of all methods declared with receiver type T. The method set of the corresponding pointer type *T is the set of all methods declared with receiver *T or T (that is, it also contains the method set of T).

总而言之,无论打印 time.Time 还是 *time.Time 值,其 String() 方法将被调用,并且它返回的任何内容都将被使用/打印。

关于string - 为什么打印 time.Time 和指向 time.Time 的指针具有相同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58856321/

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