// A Value can represent any Go value, but unlike type any, // it can represent most small values without an allocation. // The zero Value corresponds to nil. type Value struct { _ [0]func() // disallow == // num holds the value for Kinds Int64, Uint64, Float64, Bool and Duration, // the string length for KindString, and nanoseconds since the epoch for KindTime. num uint64 // If any is of type Kind, then the value is in num as described above. // If any is of type *time.Location, then the Kind is Time and time.Time value // can be constructed from the Unix nanos in num and the location (monotonic time // is not preserved). // If any is of type stringptr, then the Kind is String and the string value // consists of the length in num and the pointer in any. // Otherwise, the Kind is Any and any is the value. // (This implies that Attrs cannot store values of type Kind, *time.Location // or stringptr.) any any }
我在看到
slog.Value
源码使用
_ [0]func()
来禁用结构体相等性比较时,又搜索了 Go 的源码中多处在使用,我想这应该是社区推荐的做法了。然后就尝试去网上搜索了下,还真被我搜索到了一个叫 Phuong Le 的人在 X 上发布了 Golang Tip #50: Make Structs Non-comparable. 专门来介绍这个 Tip,并且我在中文社区也找到了鸟窝老师在《Go语言编程技巧》中的译文 Tip #50 使结构体不可比较。
这也印证了我的猜测,
_ [0]func()
在 Go 社区中是推荐用法。
本文示例源码我都放在了 GitHub 中,欢迎点击查看。
希望此文能对你有所启发。
延伸阅读
slog 源码: https://github.com/golang/go/blob/master/src/log/slog/value.go#L21
Golang Tip #50: Make Structs Non-comparable.: https://x.com/func25/status/1768621711929311620