Skip to content

Instantly share code, notes, and snippets.

@sugilog sugilog/sample1.go
Created Jan 24, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.