concept main in category go

This is an excerpt from Manning's book Get Programming with Go.
Display two lines of text by writing a second line of code within the body {} of the main function. For example: fmt.Println("Hello, world") fmt.Println("Hello, ")
The package keyword declares the package this code belongs to, in this case a package named main. All code in Go is organized into packages. Go provides a standard library comprised of packages for math, compression, cryptography, manipulating images, and more. Each package corresponds to a single idea.
The goroutine in listing 30.1 is similar to our sleepy gopher in the corner of the factory. He doesn’t do much, though where that Sleep statement is, he could be doing some serious thought (computation) instead. When the main function returns, all the goroutines in the program are immediately stopped, so we need to wait long enough to see the sleepy gopher print his “... snore ...” message. We’ll wait for a little bit longer than necessary just to make sure.
When there are no cases in the select statement, it will wait forever. That might be useful to stop the main function returning when you’ve started some goroutines that you want to leave running indefinitely.

This is an excerpt from Manning's book Go in Practice.
The main function starts the goroutine and then waits for 30 seconds. When the main function exits, it terminates the main goroutine, which effectively halts the program.

This is an excerpt from Manning's book Go Web Programming.
Take a closer look at the code. The first line declares what kind of program you’re writing. The package keyword is followed by the name of the package. An executable program must always be in a package called main, and this is the same for a web app. If you have any experience with web application programming in some other languages (such as Ruby, Python, or Java) you might notice the difference right away. In those languages you often need to deploy the web application to an application server that provides an environment for your web applications to run. In Go, this environment is provided by the net/http package and is compiled together with the rest of your code to create a readily deployable standalone web app.
Our simple web service from chapter 7 consists of two files: data.go (listing 10.1), which contains all the connections to the database, as well as the functions that read from and write to the database, and server.go (listing 10.2), which contains the main function and all the processing logic for the web service.
To deploy the web service, you need to make a simple code change. Remember you bound your web server to the address :8080 previously. When deploying on Heroku, you have no control over the port to use; you must get the port by reading the environment variable PORT. Therefore, instead of this main function in the server.go file:
func main() { server := http.Server{ Addr: ":8080", } http.HandleFunc("/post/", handlePost) server.ListenAndServe() }you use this main function:
Change the package name from main to another package name. Remove the main function.

This is an excerpt from Manning's book Go in Action.
To declare a function in Go, use the keyword func followed by the function name, any parameters, and then any return values. In the case of Run, you have a single parameter called searchTerm of type string. The term the program will search against is passed into the Run function, and if you look at the main function again, you can see that exchange.
Listing 7.34. work/main/main.go
01 // This sample program demonstrates how to use the work package 02 // to use a pool of goroutines to get work done. 03 package main 04 05 import ( 06 "log" 07 "sync" 08 "time" 09 10 "github.com/goinaction/code/chapter7/patterns/work" 11 ) 12 13 // names provides a set of names to display. 14 var names = []string{ 15 "steve", 16 "bob", 17 "mary", 18 "therese", 19 "jason", 20 } 21 22 // namePrinter provides special support for printing names. 23 type namePrinter struct { 24 name string 25 } 26 27 // Task implements the Worker interface. 28 func (m *namePrinter) Task() { 29 log.Println(m.name) 30 time.Sleep(time.Second) 31 } 32 33 // main is the entry point for all Go programs. 34 func main() { 35 // Create a work pool with 2 goroutines. 36 p := work.New(2) 37 38 var wg sync.WaitGroup 39 wg.Add(100 * len(names)) 40 41 for i := 0; i < 100; i++ { 42 // Iterate over the slice of names. 43 for _, name := range names { 44 // Create a namePrinter and provide the 45 // specific name. 46 np := namePrinter{ 47 name: name, 48 } 49 50 go func() { 51 // Submit the task to be worked on. When RunTask 52 // returns we know it is being handled. 53 p.Run(&np) 54 wg.Done() 55 }() 56 } 57 } 58 59 wg.Wait() 60 61 // Shutdown the work pool and wait for all existing work 62 // to be completed. 63 p.Shutdown() 64 }
Listing 7.21. pool/main/main.go
01 // This sample program demonstrates how to use the pool package 02 // to share a simulated set of database connections. 03 package main 04 05 import ( 06 "log" 07 "io" 08 "math/rand" 09 "sync" 10 "sync/atomic" 11 "time" 12 13 "github.com/goinaction/code/chapter7/patterns/pool" 14 ) 15 16 const ( 17 maxGoroutines = 25 // the number of routines to use. 18 pooledResources = 2 // number of resources in the pool 19 ) 20 21 // dbConnection simulates a resource to share. 22 type dbConnection struct { 23 ID int32 24 } 25 26 // Close implements the io.Closer interface so dbConnection 27 // can be managed by the pool. Close performs any resource 28 // release management. 29 func (dbConn *dbConnection) Close() error { 30 log.Println("Close: Connection", dbConn.ID) 31 return nil 32 } 33 34 // idCounter provides support for giving each connection a unique id. 35 var idCounter int32 36 37 // createConnection is a factory method that will be called by 38 // the pool when a new connection is needed. 39 func createConnection() (io.Closer, error) { 40 id := atomic.AddInt32(&idCounter, 1) 41 log.Println("Create: New Connection", id) 42 43 return &dbConnection{id}, nil 44 } 45 46 // main is the entry point for all Go programs. 47 func main() { 48 var wg sync.WaitGroup 49 wg.Add(maxGoroutines) 50 51 // Create the pool to manage our connections. 52 p, err := pool.New(createConnection, pooledResources) 53 if err != nil { 54 log.Println(err) 55 } 56 57 // Perform queries using connections from the pool. 58 for query := 0; query < maxGoroutines; query++ { 59 // Each goroutine needs its own copy of the query 60 // value else they will all be sharing the same query 61 // variable. 62 go func(q int) { 63 performQueries(q, p) 64 wg.Done() 65 }(query) 66 } 67 68 // Wait for the goroutines to finish. 69 wg.Wait() 70 71 // Close the pool. 72 log.Println("Shutdown Program.") 73 p.Close() 74 } 75 76 // performQueries tests the resource pool of connections. 77 func performQueries(query int, p *pool.Pool) { 78 // Acquire a connection from the pool. 79 conn, err := p.Acquire() 80 if err != nil { 81 log.Println(err) 82 return 83 } 84 85 // Release the connection back to the pool. 86 defer p.Release(conn) 87 88 // Wait to simulate a query response. 89 time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond) 90 log.Printf("QID[%d] CID[%d]\n", query, conn.(*dbConnection).ID) 91 }
is a normal function that counts from 0 to 4. To run count in parallel rather than in order, you use the go keyword
. This causes main to continue executing immediately. Both count and main execute concurrently.