How does a package in the Go language work?

Source: Internet
Author: User
Tags types of functions
Since I started writing code with GO, it has been a puzzle for me how to organize my Code and use the Package keyword. The package keyword is similar to a namespace in C #, but its convention is to bind the package name to the directory structure. The go language has a webpage that tries to explain how to write Go code. Http://golang.org/doc/code.html when I started programming with Go, this was one of the first readings I read. Maybe because I've been working in Visual Studio before, the code is packaged well with the solution and the project, and the content in this document is completely unreadable to me at the time. File system based directory to work I thought it was a crazy idea. But now I like the simple way, but it may take a while before you find the solution reasonable. "How to write a Go code" starts with the concept of working space. Understand this as the root directory of your project. If you use Visual Studio, it should be where the solution or project file is located. Then in your workspace, you need to create a subdirectory named SRC. This directory is required so that the tools of Go can run correctly. In the SRC directory you can freely organize your code according to your personal preference. But you need to understand the conventions that Go teams make for packages and source code, or you might want to refactor your lines of code. On my machine, I created a workspace called Test, under which the necessary SRC subdirectories were established. This is the first step in creating a project. [Image] (https://raw.githubusercontent.com/studygolang/gctt-images/master/package-work/Screen+Shot+2013-07-28+at+ 10.03.44+am.png) then open the test directory (that is, my workspace) in Liteide, and then create the following subdirectory and the empty Go source file. First, create a subdirectory for the app we created. The name of the folder where the main function is located is the name of the compiled executable file. In our project, Main.go contains the main function and is located in the MyProgram directory. This means that our executable file name is called MyProgram. The subdirectories in the other SRC directories contain the packages in the project. The name of the directory under the Convention is the name of the package that the source file belongs to in this directory, in my project the new package is named Samplepkg and Subpkg, the name of the source file can be freely named. Next, create a package folder with the same name and empty Go source file.! [Image] (https://raw.githubusercontent.com/studygolang/gctt-images/master/package-work/Screen+Shot+2013-07-28+at+ 10.10.42+am.png) If you do not add a workspace to the folder Gopath we will encounter some problems. [Image] (https://raw.githubusercontent.com/studygolang/gctt-images/master/package-work/Screen+Shot+2013-07-28+at+ 10.07.09+am.png) It took me some time to realize that the custom directory is a text box, so you can edit the values of those folders directly, and the system's Gopath is read-only. The designers of Go have done something to name their packages and source files. All file and directory names are lowercase, and directory names do not need to be underlined to separate words, all packages have the same name as the directory, and all source files in a directory belong to a package with the same name as the directory. Check out some of the standard library packages in the Go source directory:! [Image] (https://raw.githubusercontent.com/studygolang/gctt-images/master/package-work/Screen+Shot+2013-07-28+at+ 10.09.25+am.png) ' Bufio ' and ' builtin ' directories are the best examples of directory naming conventions. They may actually be named ' Buf_io ' and ' built_in '. Then look at the name of the source file in the Go source directory. Note that some files are underlined in their names. Underline is required when a file contains test code or is specifically used for a particular platform. [Image] (https://raw.githubusercontent.com/studygolang/gctt-images/master/package-work/Screen+Shot+2013-07-28+at+ 10.17.49+am.png) A less common convention is to name the file as a directory. This Convention is adhered to in the Bufio package, but it is a convention that is not often followed. In the FMT package you will find that there is not a source file called Fmt.go. I personally also like to distinguish between the naming of source files and the naming of directories.[Image] (https://raw.githubusercontent.com/studygolang/gctt-images/master/package-work/Screen+Shot+2013-07-28+at+ 10.20.36+am.png) Finally, open Doc.go,format.go,print.go and Scan.go, both of which are declared in the FMT package. Let's take a look at sample. Go code: "' Gopackage samplepkgimport (" FMT ") type sample struct {name String}func New (name string) (sample * sample) {Retu RN &sample{Name:name,}}func (sample * sample) Print () {fmt. PRINTLN ("Sample Name:", sample.) Name} "This code is useless, but it allows us to see two important conventions. First, note that the name of the package is the same as the directory name. Second, there is a function called New. In the conventions of Go, the different types of functions used to create a core type or to be used by the application developer are named New. Let's look at how the NEW function is defined and implemented in the Log.go,bufio.go and Cypto.go files. "' golog.go//new creates a new Logger. The Out variable sets the//destination to which log data would be written.//the prefix appears at the beginning for each G enerated log line.//The flag argument defines the logging Properties.func New (out IO. Writer, prefix string, flag int) * Logger {return &logger{out:out, Prefix:prefix, flag:flag}}bufio.go//Newreader Returns a new Reader whose buffer has the Default Size.func newreader (rd IO. Reader) * Reader {return newreadersize (rd, Defaultbufsize)}crypto.go//new returns a new hash. Hash calculating the given hash function. New panics//If the hash function is not linked into the Binary.func (H hash) new () hash. Hash {if h > 0 && H < maxhash {f: = Hashes[h] if f! = nil {return f ()}} panic ("crypto:requested Hash F Unction is unavailable ")} ' because each package acts as a namespace, each package can have its own version of the NEW function implementation. Many types can be created in bufio.go, so there is no separate New function, and you can see functions like Newreader and Newwriter. And look at the Sub.go code: "Gopackage subpkgimport (" FMT ") type sub struct {name String}func New (name string) (sub * sub) {return &sub{Name:name,}}func (sub * sub) Print () {fmt. Println ("Sub Name:", Sub.) Name} ' code is basically the same, except that our core type is renamed Sub. The name of the package is the same as the subdirectory name, and New returns a reference to a sub type. Now we can use the package that has already been defined and implemented well. Then look at the code in Main.go: "Gopackage mainimport (" samplepkg "" samplepkg/subpkg ") func main () {sample: = Samplepkg. New ("Test Sample Package") Sample. Print () Sub: = Subpkg. New ("Test SuB Package ") Sub. Print ()} ' ' Because our gopath points to the workspace directory, this project is/user/bill/spaces/test, and our import directive is to start referencing the other packages from this directory. Here we refer to the current directory structure under the two packages! [Image] (https://raw.githubusercontent.com/studygolang/gctt-images/master/package-work/Screen+Shot+2013-07-28+at+ 10.23.25+am.png) Next, we call the New function in each package separately and create the corresponding variable. Now compile and run the program, you can see the executable file is called MyProgram. Once your program is ready to be distributed, you can run the install naming. The install command creates the bin and Pkg folders in the workspace. Note that the final execution file is placed under the Bin folder. The compiled package is placed under the Pkg folder, this directory creates a folder for the target schema, and copies the directory structure under the source directory under this folder. These compiled packages are available, so the Go tool avoids unnecessary recompilation. [Image] (https://raw.githubusercontent.com/studygolang/gctt-images/master/package-work/Screen+Shot+2013-07-28+at+ 10.24.16+am.png) in the last part of the "How to Write Go Code" article, the Go tool ignores all. A files at a later time when compiling the code. You can't compile your app without a source file. I haven't found any documentation to explain how these. a files are directly involved in the Go program. If anyone knows, please do not hesitate to enlighten me. Finally, we'd better follow the conventions developed by Go designers, and reading Go's source code is the best way to understand these conventions. There are many people who write code for the open source community, and if we all follow the same conventions, we can improve the compatibility and readability of the code. Dig out the answers in/usr/local/go/src/pkg when you have questions. As always, I hope this article will help you understand the Go language better.

Via:https://www.ardanlabs.com/blog/2013/07/how-packages-work-in-go-language.html

Author: William Kennedy Translator: Moodwu proofreading: polaris1119

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

263 Reads
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.