官术网_书友最值得收藏!

Packages and imports

Finally, we come to the concept of packages and imports. For the majority of the book, the projects described live in something called a main package. The main package is a special package. Compiling a main package will yield an executable file that you can run.

Having said that, it's also often a good idea to organize your code into multiple packages. Packages are a form of abstraction barrier that we discussed previously with regards to variables and names. Exported names are accessible from outside the package. Exported fields of structs are also accessible from outside the package.

To import a package, you need to invoke an import statement at the top of the file:

package main
import "PACKAGE LOCATION"

Throughout this book I will be explicit in what to import, especially with external libraries that cannot be found in the Go standard library. We will be using a number of those, so I will be explicit.

Go enforces code hygiene. If you import a package and don't use it, your program will not compile. Again, this is a good thing as it makes it less likely to confuse yourself at a later point in time. I personally use a tool called goimports to manage my imports for me. Upon saving my file, goimports adds the import statements for me, and removes any unused packages from my import statements.

To install goimports, run the following command in your Terminal:

go get golang.org/x/tools/cmd/goimports
主站蜘蛛池模板: 鸡东县| 朝阳市| 阜宁县| 中西区| 安国市| 大城县| 高碑店市| 图片| 星座| 额敏县| 北川| 平昌县| 辽宁省| 农安县| 平罗县| 云浮市| 项城市| 邮箱| 马尔康县| 高要市| 淮南市| 玉门市| 无为县| 大方县| 湘潭市| 刚察县| 松江区| 沧源| 库伦旗| 宝应县| 凤台县| 丰县| 从化市| 榆社县| 苏州市| 社会| 介休市| 平邑县| 县级市| 疏附县| 馆陶县|