在Go语言中,”or”短路和错误是如何工作的呢?

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

How does "or" short-circuiting and error work in Go?

问题

如果第一个参数为true,那么0/0将不会被计算。为什么会返回一个除以零的错误?

英文:
if true || 0/0 == 0 {
    print()
}

If the first parameter is true, then the 0/0 wouldn't be evaluated.

Why does this return a DIVIDE BY ZERO error?

答案1

得分: 4

这里的除以零是一个编译器错误,而不是运行时错误。简化计算只适用于运行时。如果你将代码改为0/x,其中x被设置为零,你将不会得到错误:

var x = 0

if true || 0/x == 0 {
	print()
}

链接:https://play.golang.org/p/7E9MMqUbnQm

英文:

The divide by zero here is a compiler error, not a runtime error. Shortcutting only applies at runtime. If you change it to 0/x where x is set to zero, you won't get the error:

var x = 0

if true || 0/x == 0 {
	print()
}

https://play.golang.org/p/7E9MMqUbnQm

huangapple
  • 本文由 发表于 2021年7月12日 23:59:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/68350453.html
匿名

发表评论

匿名网友

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

确定