【发布时间】:2012-06-14 19:00:46
【问题描述】:
下面的代码会产生不受欢迎的
[20010101 20010102].
取消注释 String 函数时,它会产生更好的效果(但不是我的实现):
[{20010101 1.5} {20010102 2.5}]
但是,永远不会调用 String func。
我看到 DateValue 中的 Date 是匿名的,因此 DateValue 正在使用 func (Date) String。
所以我的问题是:
1) 这是语言问题,fmt.Println 实现问题,还是
别的东西?注意:如果我切换自:
func (*DateValue) String() string
到
func (DateValue) String() string
我的函数至少被调用并且恐慌随之而来。因此,如果我真的想要调用我的方法,我可以这样做,但假设 DateValue 确实是一个非常大的对象,我只想通过引用传递。
2) 将匿名字段与 使用反射的 Stringer 和 json 编码等功能 在幕后?例如添加一个 String 或 MarshalJSON 方法 对于碰巧用作匿名字段的类型可能会导致 奇怪的行为(就像你只打印或编码整体的一部分)。
package main
import (
"fmt"
"time"
)
type Date int64
func (d Date) String() string {
t := time.Unix(int64(d),0).UTC()
return fmt.Sprintf("%04d%02d%02d", t.Year(), int(t.Month()), t.Day())
}
type DateValue struct {
Date
Value float64
}
type OrderedValues []DateValue
/*
// ADD THIS BACK and note that this is never called but both pieces of
// DateValue are printed, whereas, without this only the date is printed
func (dv *DateValue) String() string {
panic("Oops")
return fmt.Sprintf("DV(%s,%f)", dv.Date, dv.Value )
}
*/
func main() {
d1, d2 := Date(978307200),Date(978307200+24*60*60)
ov1 := OrderedValues{{ d1, 1.5 }, { d2, 2.5 }}
fmt.Println(ov1)
}
【问题讨论】:
标签: go