Go Series Tutorial--7. Package

Source: Internet
Author: User
Tags go image processing terminates uppercase letter
This is a creation in Article, where the information may have evolved or changed. This is the 7th tutorial of [Golang Series Tutorial] (/SUBJECT/2). # # # What is a package, why use a package? So far, the Go program we've seen has only one file, and the file contains a main [function] (https://studygolang.com/articles/11892) and several other functions. In practice, this method of writing all the source code in a file is not useful. Written in this way, code reuse and maintenance can be difficult. The package solves this problem. * * Package is used to organize Go source code, providing better reusability and readability * *. Because the package provides the encapsulation of the code, it makes the Go application easy to maintain. For example, if we are developing a Go image processing program, it provides features such as cropping, sharpening, blurring, and color enhancement of images. One way to organize your program is to put the code in different packages based on different characteristics. For example, a clip can be a separate package, and sharpening is another package. The advantage of this approach is that because color enhancement may require some sharpening functionality, the color-enhanced code simply imports (which we will discuss later) with the sharpening feature of the package and can use the sharpening feature. This way makes the code easy to reuse. We will gradually build an application that calculates the area and diagonal of the rectangle. Through this program, we will better understand the package. # # # Main function and the main package all executable Go programs must contain a main function. This function is the entry for the program to run. The main function should be placed in the main package. * * ' package packagename ' This line of code specifies that a source file belongs to a packet. It should be placed on the first line of each source file. * * Below we start creating a main function and main package for our program. * * Create a folder in the SRC folder within the Go workspace named ' Geometry ' * *. Create a ' geometry.go ' file in the ' Geometry ' folder. Write the following code in Geometry.go. "' go//geometry.gopackage main import" FMT "Func Main () {FMT. Println ("Geometrical Shape Properties")} ' package main ' this line specifies that the file belongs to the main packet. The ' import ' packagename ' statement is used to import a package that already exists. Here we import the ' FMT 'Package containing the Println method in the package. Next is the main function, which prints ' geometrical shape properties '. Type ' Go install geometry ' to compile the above program. The command searches the ' Geometry ' folder for files that have the main function. Here, it finds the ' geometry.go '. Next, it compiles and produces a binary file named ' Geometry ' (' Geometry.exe ' under Windows) that is placed in the Bin folder of the workspace. Now, the directory structure of the workspace will be like this: "' src Geometry gemometry.gobin geometry ' type ' workspacepath/bin/geometry ', run the program. Please replace ' Workspacepath ' with your own Go workspace. This command executes the ' geometry ' binaries in the Bin folder. You should output ' geometrical shape properties '. # # # Create a custom package we will organize the code so that all functions related to the rectangle are placed in the ' rectangle ' package. We will create a custom package ' rectangle ', which has a function to calculate the area and diagonal of the rectangle. * * Source files belonging to a package should be placed in a separate named folder. According to the Convention of Go, the folder should be named with the package name. * * Therefore, in the ' Geometry ' folder, we create a folder named ' Rectangle '. In the ' Rectangle ' folder, all files begin with ' package rectangle ' because they all belong to the rectangle pack. In the rectangle folder that we created earlier, create a file named ' Rectprops.go ' and add the following code. "' go//rectprops.gopackage rectangleimport" math "func area (len, wid float64) float64 {area: = Len * wid return Area}func Diagonal (len, wid float64) float64 {Diagonal: = Math. SQRT (len * len) + (WID * wid)) return diagonal} ' inIn the above code, we created two functions for calculating ' area ' and ' Diagonal '. The area of a rectangle is the product of length and width. The diagonal of the rectangle is the square root of the length and width squared. The ' Sqrt ' function below the ' math ' package is used to calculate the square root. Notice that both the function area and the Diagonal begin with an uppercase letter. This is necessary and we will soon explain why we need to do so. # # # import a custom package in order to use a custom package, we must first import it. The syntax for importing a custom package is ' import path '. We must specify the relative path of the custom package relative to the ' src ' folder in the workspace. Our current folder structure is: ' src geometry geometry.go rectangle rectprops.go ' "Import" Geometry/rectangle "' this line will import rectangle package. Add the following code to ' Geometry.go ': ' go//geometry.gopackage main import ("FMT" "geometry/rectangle"//Import custom package) Func main () {var Rectlen, Rectwidth float64 = 6, 7 fmt. Println ("Geometrical shape properties")/*area function of rectangle package used*/FMT. Printf ("Area of Rectangle%.2f\n", rectangle. Area (Rectlen, rectwidth))/*diagonal function of the rectangle package used*/FMT. Printf ("Diagonal of the rectangle%.2f", rectangle. Diagonal (Rectlen, Rectwidth)} "The code above imports the ' rectangle ' package and invokes the area and Diagonal functions inside, resulting in rectangular areas and diagonal lines. The format specifier '%.2f ' within Printf truncates the floating-point number to the two-bit decimal point. The output of the application is: "' Geometrical shape properties area of rectangle 42.00 Diagonal of the RectaNgle 9.22 "# # # Export Name (exported Names) We will capitalize the function area and Diagonal in the rectangle package. This has a special meaning in Go. In Go, any variable or function that starts with a capital letter is the exported name. Other packages can access only the functions and variables that are exported. Here, we need to access the area and Diagonal functions in the main package, so they capitalize the first letter. In ' Rectprops.go ', if the function name changes from ' area (len, wid float64) ' to ' area (len, wid float64) ' and in ' geometry.go ', ' rectangle. Area (Rectlen, rectwidth) ' becomes ' Rectangle.area (Rectlen, Rectwidth) ', the compiler throws an error when the program runs, ' Geometry.go:11:cannot refer to unexported name Rectangle.area '. Because if you want to access a function outside of the package, it should capitalize the first letter. # # # init function All packages can contain an ' init ' function. The INIT function should not have any return value type and parameters, nor can it be explicitly called in our code. The init function is in the form of the following: "' Gofunc init () {} ' init function can be used to perform initialization tasks, or it can be used to verify the correctness of the program before starting execution. The sequence of initialization of the package is as follows: 1. First initialize the variable 2 of the package level. Immediately after the INIT function is called. A package can have multiple init functions (in one file or in multiple files), and they are invoked in the order in which they are parsed by the compiler. If a package imports another package, the imported package is initialized first. Although a package may be imported multiple times, it will only be initialized once. To understand the Init function, we then made some changes to the program. First, an init function is added to the ' rectprops.go ' file. "' go//rectprops.gopackage rectangleimport" math "import" FMT "/* * init function added */func init () {FMT. PRINTLN ("Rectangle package initialized")}func area(Len, wid float64) float64 {area: = Len * wid return Area}func Diagonal (len, wid float64) float64 {Diagonal: = Math. SQRT (len * len) + (WID * wid)) return diagonal} "" We have added a simple init function that only prints ' rectangle package initialized '. Now let's modify the main package. We know that the length and width of the rectangle should be greater than 0, and we will use the INIT function and the package-level variables in ' geometry.go ' to check the length and width of the rectangle. Modify the ' geometry.go ' file as follows: ' go//geometry.gopackage main import ("FMT" "geometry/rectangle"//Import Custom Package "log")/* * 1. Package-level variables */var rectlen, rectwidth float64 = 6, 7/**2. The INIT function checks if the length and width are greater than 0*/func init () {println ("main package initialized") if Rectlen < 0 {log. Fatal ("Length is less than zero")} if rectwidth < 0 {log. Fatal ("width is less than zero")}}func main () {FMT. Println ("Geometrical shape Properties") fmt. Printf ("Area of Rectangle%.2f\n", rectangle. Area (Rectlen, rectwidth)) fmt. Printf ("Diagonal of the rectangle%.2f", rectangle. Diagonal (Rectlen, Rectwidth)} "We have made the following modifications to ' Geometry.go ': 1. The variables **rectlen** and **rectwidth** are moved from the main function level to the package level. 2. Added the init function. When Rectlen or rectwidth is less than 0 o'clock, the init function uses **log. The fatal** function prints a log and terminates the program. The main package is initialized in the following order: 1. The imported package is initialized first. Therefore, the rectangle package is initialized first. 2. The variable **rectlen** and **rectwidth** at the package level are then initialized. 3. Call the init function. 4. Finally call the main function. When you run the program, the following output is available. "Rectangle package initialized main package initialized geometrical shape properties area of rectangle 42.00 Diagonal of The rectangle 9.22 "is sure that the program will first call the rectangle package's init function, and then initialize the package-level variables **rectlen** and **rectwidth**. It then calls the INIT function in the main package, which checks if Rectlen and Rectwidth are less than 0, and terminates the program if the condition is true. We'll dive into the IF statement in a separate tutorial. Now you can assume that ' if Rectlen < 0 ' can check if ' Rectlen ' is less than 0, and if so, terminate the program. The writing of ' rectwidth ' conditions is similar. Both conditions are false here, so the program continues to execute. Finally, the main function is called. Let's then modify the program slightly to learn to use the init function. Change the ' var rectlen ' in ' geometry.go ', rectwidth float64 = 6, 7 ' to ' var rectlen, rectwidth float64 =-6, 7 '. We initialize ' Rectlen ' to negative numbers. Now when you run the program, you get: "' Rectangle package initialized main package initialized 2017/04/04 00:28:20 length was less than zero ' as usual , the rectangle package is initialized first, followed by the package-level variables Rectlen and rectwidth in the main package. Rectlen is negative, so when you run the INIT function, the program prints ' length is less thanZero ' after termination. This code can be downloaded from [GitHub] (https://github.com/golangbot/geometry). # # # Imports a package with a blank Identifier, but does not use it in the code, which is illegal in Go. When you do this, the compiler will make an error. The reason for this is to avoid importing too many unused packages, resulting in a significant increase in compilation time. Replace the code in ' Geometry.go ' with the following code: ' go//geometry.gopackage main import ("Geometry/rectangle"//Import custom package) Func main () {} " The order will throw an error ' Geometry.go:6: Imported and not used: ' Geometry/rectangle '. However, in the active phase of program development, the package is often first imported and not used. In this case, you can use the blank identifier ' _ '. The following code avoids the error of the above program: "' Gopackage mainimport (" Geometry/rectangle ") var _ = rectangle. Area//Error blocker func main () {} "" var _ = rectangle. Area ' This line masks the error. We should be aware of the dynamics of these error silencer, removing them at the end of program development, including those that have not been used. It is recommended that you write an error mask in the package level range below the import statement. Sometimes we import a package just to make sure it is initialized without using any of the functions or variables in the package. For example, we might need to make sure that the init function of the rectangle package is called without using it in code. In this case, you can also use a blank identifier, as shown below. The Gopackage main import (_ "Geometry/rectangle") func main () {} "runs the above program and will output ' rectangle package initialized '. Although we did not use the package in all the code, it was successfully initialized. This concludes the introduction of the package. I hope you enjoy this article, please leave your valuable feedback and comments. * * Previous Tutorial-[functions] (https://studygolang.com/articles/11892) * * * * Next tutorial-[if Else statement] (https://studygolang.com/articles/11902) * *

via:https://golangbot.com/packages/

Author: Nick Coghlan Translator: Noluye proofreading: Rxcai

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

4,381 reads ∙2 likes
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.