Skip to content

Instantly share code, notes, and snippets.

@sugilog
Created January 24, 2015 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sugilog/4c2d1f0da3fa2df6778a to your computer and use it in GitHub Desktop.
Save sugilog/4c2d1f0da3fa2df6778a to your computer and use it in GitHub Desktop.
Channelsのcloseとrange
package main
import (
"fmt"
)
func fibonacci(n int, c chan int) {
x, y := 0, 1
for i := 0; i < n; i++ {
c <- x
x, y = y, x+y
}
close( c )
}
func main() {
c := make( chan int, 10 )
go fibonacci( cap( c ), c )
for i := range c {
fmt.Println( i )
}
}
package main
import (
"fmt"
"time"
)
func fibonacci(n int, c chan int) {
x, y := 0, 1
for i := 0; i < n; i++ {
c <- x
x, y = y, x+y
}
close( c )
}
func main() {
c := make( chan int, 10 )
go fibonacci( cap( c ), c )
i0, j0 := <- c
fmt.Println( i0, j0 )
i1, j1 := <- c
fmt.Println( i1, j1 )
i2, j2 := <- c
fmt.Println( i2, j2 )
i3, j3 := <- c
fmt.Println( i3, j3 )
i4, j4 := <- c
fmt.Println( i4, j4 )
i5, j5 := <- c
fmt.Println( i5, j5 )
i6, j6 := <- c
fmt.Println( i6, j6 )
i7, j7 := <- c
fmt.Println( i7, j7 )
i8, j8 := <- c
fmt.Println( i8, j8 )
i9, j9 := <- c
fmt.Println( i9, j9 )
i10, j10 := <- c
fmt.Println( i10, j10 )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment