Go Language Practical notes (i) | Go Package Management

Source: Internet
Author: User
Tags install go version control system
This is a creation in Article, where the information may have evolved or changed.

The first two days have been concerned about the "go language combat" Finally took the hand, the book is looking forward to a long time, pre-sale time on the first scheduled. Yesterday's leisure time turned the first three chapters, feel good, so intends to target the book, write a series of reading notes, this is a summary of their own reading, but also with everyone a share.

This is in the action series of books, this series of research and development know, in the development of a lot of evaluation, a lot of new technology, language and so will have a practical book. Since it is the actual combat, then this book assumes that his readers have a certain foundation, such as the book's readers to have a certain Go language foundation, such as the Go development environment, go built-in type, go common keywords and so on.

But I am the public number [flysnow_org], since the intention of a "go language combat" reading notes, do not need to have a go foundation, the book did not speak of knowledge points, I will also in my reading notes introduced, of course, there is depth.

What is a package in the Go language

Here we directly talk about the Go language practical notes, do not introduce the introduction of the go language, to get started, you can refer to my article on the Go Language development environment to build a detailed

We use other languages, such as Java, to have the concept of a package, which is a concept that organizes our Java files in the Java language, such as java.lang this package, which has many of our commonly used classes, such as String. In the go language, the package is a similar concept, it is to organize our go files, can be easily categorized, reused and so on. For example, the go built-in net package

net├── http├── internal├── mail├── rpc├── smtp├── testdata├── textproto└── url

The above is a directory structure of net package, net itself is a package, the Net directory of HTTP is a package. From this we can see that the go language package is actually our computer directory, or folder, through which directory structure and file organization, go just to the directory name made a translation, called "Package" only. For example, the net package is actually a net directory, HTTP package is actually HTTP directory, which is also a naming habit in the Go language, the package name and the directory name of the file is the same.

Name of the package

The name of the go language package follows the principle of brevity, lowercase, and the same name as the directory where the go file is located, so that we can reference, write, and quickly locate the search.

For example, go comes with the HTTP this package, it is this HTTP directory of all go files belong to this HTTP package, so we use the HTTP packet in the function, interface, the time to import this HTTP packet.

package mainimport "net/http"func main() {    http.ListenAndServe("127.0.0.1:80",handler);}

As you can see from this example, what we are importing is that net/http this is called the full path in go, because the HTTP package is in net, net is the top-level package, so you must use full path import, the go compiler can find the HTTP package, and the directory path of our file system is the same.

Because of the full path, the named package name can be the same as other libraries, as long as their full path is different, the use of full-path import, but also increased the flexibility of naming the package name.

For ourselves or the company developed procedures, we generally use the domain name as the top-level package name, so there is no need to worry about duplication with other developer package name problems, such as my personal domain is www.flysnow.org , then I developed the GO program flysnow.org as the top-level part of the full path, For example, to import a toolkit I developed:

package mainimport "flysnow.org/tools"

What if you don't have your own domain name? You can use github.com at this time. Do research and development of this line, on GitHub will have an account, if not hurriedly apply for a, this time we can use github.com/<username> as your top path, others will not be the same name as you.

package mainimport "github.com/rujews/tools"

This is the way to change the name of github.com.

Main Package

When the package name of a go file is declared as main , it is equal to tell go compiler, I this is an executable program, then the go compiler will try to compile it into a binary executable file.

A main package, it must contain a main() function, which we are not unfamiliar, such as C and Java have main() functions, it is a program of the entrance, without this function, the program can not be executed.

In the go language, both the main package and the include main() function are compiled into an executable file.

Let's look at a Hello World Go language version to illustrate the main package.

package mainimport "fmt"func main() {    fmt.Println("Hello, 世界")}

Assuming that the go file is called Hello.go, placed in the $GOPATH/src/hello directory, then we execute the command in this directory go build will generate a binary executable, generated under the window System hello.exe , under Unix,mac and Linux generated hello , We execute it in cmd or terminal, we can see the console print:

Hello, 世界

The name of the binary executable is the name of the directory where the go file of the main package is located, because Hello.go is in the Hello directory, so the resulting executable file is the name of hello.

Importing packages

To use a package, you must import it before you can use it, and the go language provides a keyword import to import a package that tells the go compiler where to go to the disk to find the package to import, so the imported package must be a full-path package, which is where the package resides.

import "fmt"

This means that we have imported the fmt package, which is tantamount to telling the go compiler that we are going to use the code below the package. What if you want to import multiple packages? The go language also provides us with an import block.

import (    "net/http"    "fmt")

Use a pair of parentheses to contain the import blocks, each of which has a single row.

For a package name that is more than one path, when referenced in code, use the last package name of the full path as the referenced package name, for example net/http , what we use in the code http instead net .

Now that I have imported the package, where does the go compiler go to find them when compiling? Here we introduce the environment variables of go. Go has two important environment variables GOROOT and GOPATH , this is the two defined PATH environment variable, GOROOT is the path to install go, for example, /usr/local/go GOPATH is our own definition of the developer's personal workspace, such as /home/flysnow/go .

The compiler uses the two paths we set up, together with the import imported relative full path, to find the package on the disk, such as the fmt package we imported, which the compiler eventually found /usr/local/go/fmt .

It is worth knowing that the search for the package is prioritized, the compiler will first search in, and GOROOT then GOPATH , once found, will stop searching immediately. If you don't find it at the end, you're going to compile the exception.

Remote Package Import

The era of the Internet, now we are using similar to GitHub shared code more and more, if some go package sharing on GitHub, we have the same way to use them, this is the remote import package, or network import, go is born to support this situation, So we can use the Go Library development program on GitHub very casually.

import "github.com/spf13/cobra"

This import must be provided that the package is hosted on a distributed version control system, such as GitHub, BitBucket, etc., and is public permissions that allow us to access them directly.

When they are imported, they are GOPATH searched for the package, and if they are not found, they are go get obtained from the version control System (GITHUB) and the obtained source code is stored in the directory GOPATH of the corresponding URL in the directory to be used for compilation.

go getThe tool can get a dependency package recursively, and if github.com/spf13/cobra other remote packages are also referenced, the tool can be downloaded together.

Named Import

We know that import after importing a package with a keyword, we can use the corresponding function, interface, and so on in the code through the package name. What if we import a package name that is exactly duplicated? In this case, the go language allows us to rename the imported package, which is named import.

package mainimport (    "fmt"    myfmt "mylib/fmt")func main() {    fmt.Println()    myfmt.Println()}

If not renamed, then for the compiler, these two fmt it is not clear. Renaming is also very simple, when we import, on the left side of the package name, a new package name can be.

The Go language rules, the imported package must be used, otherwise it will be a package compilation error, this is a very good rule, because this can avoid us to reference a lot of useless code caused by the code bloat and the huge program, because many times, we do not know which packages are used, which is often encountered in C and Java, Sometimes we have to use tools to find files, types, methods, and variables that we don't have, and to get rid of them.

But sometimes, we need to import a package, but do not use it, according to the rules, this is not possible, this go language provides us with a blank marker _ , just need us to _ rename our imported package.

package mainimport (    _ "mylib/fmt")

The init function of the package

Each package can have any number of init functions, all of which are executed before the main function. The init function is often used to initialize variables, set packages, or other boot work that needs to be done before the program executes. For example _ , the purpose of importing a package with an empty flag is to execute the INIT function in the package.

We take the database driver as an example, the go language in order to unify the access to the database, using the databases/sql abstraction of a layer of database operations, can meet our operation MySQL, Postgre and other databases, so no matter which drive we use these databases, the encoding operation is the same, want to change the drive when , you can change it directly without having to modify the specific code.

These database-driven implementations are concrete and can be implemented by anyone, and the principle is to define the INIT function, register the implemented driver in the SQL package before the program runs, and then use it to manipulate the database.

package mysqlimport (    "database/sql")func init() {    sql.Register("mysql", &MySQLDriver{})}

Because we just want to execute this MySQL package init method, and do not want to use this package, so when we import this package, we need to use the _ rename package name, to avoid compilation errors.

import "database/sql"import _ "github.com/go-sql-driver/mysql"db, err := sql.Open("mysql", "user:password@/dbname")

Look very concise, the rest of the database for the operation, are using the database/sql standard interface, if we want to change a MySQL driver, only need to change the import can be, flexible and convenient, this is interface-oriented programming convenience.

This is the end of the use of Go package management, followed by some common tools, documentation, and dependency management for go. you are welcome to pay attention to the public number [flysnow_org], please look forward to follow up.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.