关于Golang的goto语句

对Golang的goto语句感兴趣的背景是什么?

在这篇文章中,当我在学习编码测试时,恐愧地我第一次听说了goto语句,所以我打算在这篇文章中总结一下。

在具体的情况下,使用goto语句的位置

实际上,如果查看Golang的Github,似乎在这个位置使用了这种方法。

func (r *Rand) Float64() float64 {
	// A clearer, simpler implementation would be:
	//	return float64(r.Int63n(1<<53)) / (1<<53)
	// However, Go 1 shipped with
	//	return float64(r.Int63()) / (1 << 63)
	// and we want to preserve that value stream.
	//
	// There is one bug in the value stream: r.Int63() may be so close
	// to 1<<63 that the division rounds up to 1.0, and we've guaranteed
	// that the result is always less than 1.0.
	//
	// We tried to fix this by mapping 1.0 back to 0.0, but since float64
	// values near 0 are much denser than near 1, mapping 1 to 0 caused
	// a theoretically significant overshoot in the probability of returning 0.
	// Instead of that, if we round up to 1, just try again.
	// Getting 1 only happens 1/2⁵³ of the time, so most clients
	// will not observe it anyway.
again:
	f := float64(r.Int63()) / (1 << 63)
	if f == 1 {
		goto again // resample; this branch is taken O(never)
	}
	return f
}

用中文写的话大概是这样的。

func (r *Rand) Float32() float32 {
    f := float32(r.Float64())
    for f == 1 {
        f = float32(r.Float64())
    }
    return f
}

我对该用法的理解还不够,是否可以用for循环呢?另外,使用goto语句在方法外会导致编译错误。这是GoPlayground的链接。

func main() {
	var val int = 0
	val = val + 2
	if val < 5 {
		goto XYZ
	}
}

func PrintHello() {
XYZ:
	fmt.Printf("Hello World\n")
}

// putput:
// ./prog.go:9:8: label XYZ not defined
// ./prog.go:14:1: label XYZ defined and not used

个人的感受

嗯,老实说,我觉得用for循环应该可以,但处理速度等会有差异吧。

请参考 https://qiita.com/weloan/items/29018c8d0049abbe6199

广告
将在 10 秒后关闭
bannerAds