Can I get a compile error on potential null ptr dereference – in Go?

huangapple go评论64阅读模式
英文:

Can I get a compile error on potential null ptr dereference - in Go?

问题

同事在Go中遇到了空指针解引用的问题。

我建议他像我一样去做 - 在其他编程语言中,我倾向于将警告级别设置得很高,并将警告转换为错误。例如,在C#中,这意味着我无法编译这段代码:

private static string bad_deref(object? Object)
{
    return Object.ToString();
}

因为我会得到以下错误:

x.cs(y,z): [CS8602] Dereference of a possibly null reference.

这其实是一种很好的情况。

但他告诉我Go没有警告级别可供设置,通过搜索似乎他是对的。

那么,在Go中如何解决这个问题呢?我们是不是回到了经典的C建议:“优秀的程序员不会犯错误”,并且只有在你不与完美的人一起工作时才会发生空指针解引用问题?

英文:

A colleague has a null ptr dereference in Go.

I advised him to do as I would do - working in other languages, I tend to crank the warning level high and turn warnings into errors. In e.g. C#, that means I cannot compile this code:

private static string bad_deref(object? Object)
{
    return Object.ToString();
}

because I get

  x.cs(y,z): [CS8602] Dereference of a possibly null reference.

Which, to be clear, is very good.

But he tells me Go doesn't have a warning level to crank and, googling, it would appear he is right.

So how do you solve this problem in Go? Are we back to good old C advice "good programmers don't make mistakes" and null ptr dereferences just sometimes happen if you don't work with perfect people?

答案1

得分: 1

这是翻译好的内容:

这是正确的:在处理nil情况之前,无法通过解引用指针来生成编译器错误。这是因为语言规范允许这样做。你无法阻止它。

你可以在任何语言中编写糟糕/不正确的代码,而检测错误并尽早纠正它们的方法是在几乎所有语言中编写测试。

Go语言内置了一个很好的测试框架,直接集成在go工具中。你绝对应该充分利用它。在几乎所有适当的地方编写测试。Go测试应定期执行,在CI/CD过程中和发布之前会自动运行它们。大多数IDE也会在保存时自动运行测试。

另一个技巧是:如果nil指针没有意义,可以编写一个使用非指针类型的API。当然,这也有其缺点(有时指针是必需的);如果使用指针更合理,请使用它,但要检查nil值,并妥善处理它们(例如,返回一个error,如果有意义的话,就触发panic等)。还要编写测试来测试nil指针值。

英文:

That's correct: you can't make a compiler error out of dereferencing a pointer without handling a nil case. That's because the language spec allows it. Nothing you can do about it.

You can write bad / incorrect code in any language, and the mean to detect errors early or mitigate them is to write tests in almost all languages.

Go has a nice testing framework built into the go tool itself. You should definitely take advantage of it. Write tests whenever / wherever appropriate. Go tests should be executed on a regular basis, they are automatically run during CI/CD and before releases. Most IDEs also run tests on save automatically.

Another trick you may use: if the nil pointer makes no sense, write an API that uses non-pointer type. Of course this has its drawbacks (sometimes pointers are a must); if using pointer makes more sense, use it, but check for nil values, and handle them properly (e.g. return an error, panic if that makes sense etc.). Also write tests to test with nil pointer values.

huangapple
  • 本文由 发表于 2023年4月17日 19:40:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76034789.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定