Go Concepts - Runtime

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

Executables vs. Libraries

Executables are native code programs that can be run directly from command line.

Libraries are collection of native code that can be used by other programs.

Compiling an Executable

According to the specifications (https://golang.org/ref/spec#Program_execution), a complete program is created by linking a single, unimported package called the main package with all the package it imports, transitively. The main package must be named "main". The main package must declare a function named main() that takes no arguments and returns no value. The main() function is the entry point in the program. If the "main" package does not contain a main() function, the build tool won't produce an executable:

runtime.main: call to external function main.main
runtime.main: main.main: not defined
runtime.main: undefined: main.main

The program execution begins by initializing the main package and invoking the main() function. Then the function invocation returns, the program exists. It does not wait for other (non-main) goroutines to complete.

Note that the name of the source file that contains the main() function does NOT have to be "main.go". It could be any legal file name. The executable will be created under the name of the file that contains the main() function.

The simplest possible executable named example can be created as follows:

Declare an example.go that defines the "main" package and contains the main() function:

package main

import "fmt"

func main() {
    fmt.Println("I am example")
}

Build the executable:

go build ./example.go

The compiler will create an example executable.