Created
January 24, 2015 16:36
-
-
Save sugilog/4c2d1f0da3fa2df6778a to your computer and use it in GitHub Desktop.
Channelsのcloseとrange
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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