Go 中的 Python 风格的生成器
在 Go 中,goroutines 可以像 Python 生成器一样使用,如问题 66 中的示例去。提供的代码以简化的方式重写了问题 66:
package main import "fmt" func fibonacci(c chan int) { x, y := 1, 1 for { c <p><strong>分析</strong></p><ol> <li>增加通道的缓冲区大小将导致性能提升,因为通道的缓冲区大小会减少上下文切换。然而,这是以增加内存使用为代价的。</li> <li>当 goroutine 没有被垃圾回收时,就会发生内存泄漏。在提供的代码中,斐波那契 goroutine 无限期地持续存在,从而防止通道 c 被垃圾收集。</li> </ol><p><strong>替代方法</strong></p><p>要解决这些问题,请考虑以下代码:</p><pre class="brush:php;toolbar:false">package main import "fmt" func fib(n int) chan int { c := make(chan int) go func() { x, y := 0, 1 for i := 0; i <p>在此示例:</p>
以上是Go Channels 可以模仿 Python 生成器吗?的详细内容。更多信息请关注PHP中文网其他相关文章!