Chapter 5. Packages and Modules in Go
Go programs are constructed by linking together packages. A Go package in turn is constructed from one or more source files...
In this chapter, we’ll do a few things that clean up our Go code. We’ll look at the Go module we created back in Chapter 0 and see its purpose in separating code. Then we’ll do the work to separate our test code from our production code using packages. Finally, we’ll remove some redundancy from our code, making things compact and meaningful.
Separating Our Code into Packages
Let’s begin by separating our test code from our production code. This entails two separate tasks:
-
Separating test code from production code.
-
Ensuring the dependency is only from the test code to the production code.
We have production code for Money and Portfolio sitting next to our test code in one file—money_test.go. Let’s first create two new files named money.go and portfolio.go. We’ll put both these files in the $TDD_PROJECT_ROOT/go folder. Next, we move code for the relevant classes, Money and Portfolio, to their appropriate files. This is how portfolio.go looks:
packagemaintypePortfolio[]Moneyfunc(pPortfolio)Add(moneyMoney)Portfolio{p=append(p,money)returnp}func(pPortfolio)Evaluate(currencystring)Money{total:=0.0for_,m:=rangep{total=total+m.amount}returnMoney{amount:total,currency:currency}}
The file money.go, not shown here, similarly contains ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access