比较 nil 指针变量的值
我知道 Go 在这方面与其他语言没什么不同,但我想知道 Go 语言是否值得在比较时自动测试 nil 指针,并在只有一个值为 nil 时返回不相等(在比较中)而不是创建运行时错误。 Go 在很多领域都非常出色,我只是认为它可以做到这一点。恰当的例子如下:
type cuForm struct {sName string; iUseCount int64; baForm []byte}
var pugForm *cuForm
//***********************************************************
func loadForm (sWanted string) (*cuForm, os.Error) {
//***********************************************************
if (sWanted == pugForm.sName) {
在上面的例子中,如果 pugForm 为 nil,则会发生运行时错误。显然,如果只有一个值为零,则它不可能相等——至少在逻辑上是这样。不应该这样做很可能是有原因的,但我认为历史不应该是原因之一。
I know that Go is little different to other languages in this respect, but I wondered if it would be worthwhile for the Go language to automatically test for nil pointers on comparisons and return unequal if only one of the values is nil (in a comparison) rather than creating a run-time error. Go is so great in so many areas I just thought it might do it. The case in point is as follows:
type cuForm struct {sName string; iUseCount int64; baForm []byte}
var pugForm *cuForm
//***********************************************************
func loadForm (sWanted string) (*cuForm, os.Error) {
//***********************************************************
if (sWanted == pugForm.sName) {
In the above example, if pugForm is nil, a runtime error occurs. Obviously if only one of the values is nil, it cannot be equal - logically at least. There may well be a reason why this shouldn't be done, but I don't think history should be one reason.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
错误消息是:“恐慌:运行时错误:无效的内存地址或零指针取消引用。”实际的错误是零指针取消引用。
当指针 pugForm 为 nil 时,pugForm.sName 未定义。您希望它是一个特殊值,例如 SQL 中的 null 或浮点中的 NaN。现在您需要针对所有操作的一组特殊规则,而不仅仅是相等。
零指针取消引用几乎总是错误的。如果发生这种情况,运行时应该反对。如果没有错误,则通过测试 nil 来避免问题。纠正你的错误,不要试图假装它没有发生。
您期望该计划产生什么结果?
The error message is: "panic: runtime error: invalid memory address or nil pointer dereference." The actual error is a nil pointer dereference.
When the pointer pugForm is nil then pugForm.sName is undefined. You want it to be a special value like null in SQL or NaN in floating-point. Now you need a special set of rules for all operations, not just equality.
A nil pointer dereference is almost always wrong. The runtime should object if that happens. If it's not wrong, avoid the problem by testing for nil. Fix your error, don't try to pretend it didn't happen.
What output do you expect from this program?
并不是说你的问题不相关,我认为不将其实现为默认行为有一个很好的理由:这意味着在运行时进行更多测试,我不希望对我的程序的所有相等测试都这样做。
但确实,专用表达式(例如“===”)可能(也许)有用。
正如诺斯所说,疯狂邮件列表可能是进行这种讨论更具建设性的地方。
Not saying that your question isn't pertinent, I see a good reason to not implement this as the default comportment : that means more tests at runtime and I don't want that for all equality tests of my programs.
But it's true that a dedicated expression (for example something like '===') could (maybe) be useful.
As Nos said, the go-nuts mailing list would probably be a more constructive place for this discussion.