Today we have something a bit different. Just a sample package.
An example package
Here is a complete Go package that implements a concurrent prime sieve.
package main import "fmt" // Send the sequence 2, 3, 4, … to channel 'ch'. func generate(ch chan<- int) { for i := 2; ; i++ { ch <- i // Send 'i' to channel 'ch'. } } // Copy the values from channel 'src' to channel 'dst', // removing those divisible by 'prime'. func filter(src <-chan int, dst chan<- int, prime int) { for i := range src { // Loop over values received from 'src'. if i%prime != 0 { dst <- i // Send 'i' to channel 'dst'. } } } // The prime sieve: Daisy-chain filter processes together. func sieve() { ch := make(chan int) // Create a new channel. go generate(ch) // Start generate() as a subprocess. for { prime := <-ch fmt.Print(prime, "\n") ch1 := make(chan int) go filter(ch, ch1, prime) ch = ch1 } } func main() { sieve() }
This particular package is a complete program, my virtue of being in package main
, containing a main()
function.
I’m not going to go through the program line by line. Instead, since this is in the section of the spec about packages, let’s just take a closer look at the main components, and how they relate to a Go package, as review.
- The package clause, tells us we’re in the
main
package, the entry point for all Go programs.
package main
- The import declaration(s), define which external packages we’re importing into this file.
import "fmt"
- Function declarations
// Send the sequence 2, 3, 4, … to channel 'ch'.
func generate(ch chan<- int) {
The final function in the example is main()
, which of course is the function executed by the runtime to begin running the program.
This is a very simple package, with many possible elements ommited, such as package variables, constants, init
functions, etc.
Quotes from The Go Programming Language Specification Language version go1.23 (June 13, 2024)