Libraries

Until now, most of our examples were applications. An application is defined by its main function and package. But with Go, you can also create pure libraries. In libraries, the package need not be called main nor do you need the main function.

As libraries aren't applications, you cannot build a binary file with them and you need the main package that is going to use them.

For example, let's create an arithmetic library to perform common operations on integers: sums, subtractions, multiplications, and divisions. We'll not get into many details about the implementation to focus on the particularities of Go's libraries:

package arithmetic 
 
func Sum(args ...int) (res int) { 
    for _, v := range args { 
        res += v 
    } 
    return 
} 

First, we need a name ...

Get Go: Design Patterns for Real-World Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.