github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/talks/2014/hellogophers/sieve_20080917.go (about)

     1  // +build ignore,OMIT
     2  
     3  package main
     4  
     5  // Send the sequence 2, 3, 4, ... to channel 'ch'.
     6  func Generate(ch *chan <- int) {
     7  	for i := 2; ; i++ {
     8  		ch <- i  // Send 'i' to channel 'ch'.
     9  	}
    10  }
    11  
    12  // Copy the values from channel 'in' to channel 'out',
    13  // removing those divisible by 'prime'.
    14  func Filter(in *chan <- int, out *<-chan int, prime int) {
    15  	for {
    16  		i := <-in;  // Receive value of new variable 'i' from 'in'.
    17  		if i % prime != 0 {
    18  			out <- i  // Send 'i' to channel 'out'.
    19  		}
    20  	}
    21  }
    22  // BREAK OMIT
    23  // The prime sieve: Daisy-chain Filter processes together.
    24  func Sieve() {
    25  	ch := new(chan int);  // Create a new channel.
    26  	go Generate(ch);      // Start Generate() as a subprocess.
    27  	for {
    28  		prime := <-ch;
    29  		print(prime, "\n");
    30  		ch1 := new(chan int);
    31  		go Filter(ch, ch1, prime);
    32  		ch = ch1
    33  	}
    34  }
    35  
    36  func main() {
    37  	Sieve()
    38  }