gpt4 book ai didi

go - 添加一个从未调用过的函数可以改善行为?

转载 作者:IT王子 更新时间:2023-10-29 02:18:21 26 4
gpt4 key购买 nike

下面的代码产生了不良的结果

[20010101 20010102].

当取消注释 String func 时,它会产生更好的结果(但不是我的实现):

[{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

我的函数至少被调用并且 panic 随之而来。因此,如果我真的想调用我的方法,我可以这样做,但假设 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)
}

最佳答案

这是因为您传入了一段 DateValues 而不是 DateValue 指针。由于您已经为 *DataValue 定义了 String 方法,因此 *DateValue 就是实现 Stringer 接口(interface)的方法。这也防止 DateValue 通过其匿名 Date 成员实现 Stringer 接口(interface),因为值类型 (DateValue) 或指针类型 (*DateValue) 中只能有一个可以是用于实现接口(interface)。因此,当 fmt.Println 正在打印 slice 的内容时,它发现元素不是 Stringer,并使用默认的结构格式而不是您定义的方法,给出 [{20010101 1.5} {20010102 2.5}]

您可以将 OrderedValues 设为 []*DateValue 或定义 func (dv DateValue) String() string 而不是指针版本。

关于go - 添加一个从未调用过的函数可以改善行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11039652/

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