Golang Study notes-1.10 packs of understanding

Source: Internet
Author: User

This is the tenth chapter of Golang Language Learning Tutorial

What is a package? Why use a bag?

The go language package is similar to libraries or modules in other languages to support encapsulation, modularity, individual compilation, and code reuse.
A package's source code is saved in one or more .go source files as file suffix names.
Each package corresponds to a separate namespace, for example, the functions in the package image and in the unicode/utf16 package Decode are different. To reference the function externally, you need a image.Decode form of access.

Main function and main package

All executable go programs must contain a main function, which is the entry for the program, and the main function must be placed in the main package.
In 1.2,hello,world there are written code go build and go install two ways, and the difference.
Example 1:

package main  //每一个 Go 文件都应该在开头进行 package name 的声明(译注:只有可执行程序的包名应当为 main)。表明该文件属于哪个包。import "fmt"  //引入了 fmt 包,用于在 main 函数里面打印文本到标准输出。func main() {       fmt.Println("Hello,World!")}//func声明函数main,调用 fmt 包的 Println 函数做标准输出。{}中的内容称之为函数体。

Create a custom package

We'll build an application that calculates the rectangular area and diagonal, and better understand the package. (This example comes from Go Chinese web)

We will organize the code so that all the functions related to the rectangle are put into the rectangle package.
Create a custom package rectangle that has a function to calculate the area and diagonal of the rectangle.
Create a Geometry folder and create a folder in which to rectangle store the package's source files, in this folder, all the files will package rectangle begin with, because they belong to the rectangle package.
Create rectprops.go A file named, write code
Example 2:

//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))  //Sqrt函数用来计算平方根    return diagonal}

In the above program, two functions were created to calculate area and diagonal.
Area of Rectangle = length * Width
Diagonal of the rectangle = square root of (long squared + width squared)
mathThe function below the package is Sqrt used to calculate the square root.

Importing Custom Packages

In order to use a custom package, you first need to import the package into the executable file, with the imported syntax import path . We must specify src the relative path of the custom package relative to the folder in the workspace.
Create executable files in the Geometry folder geometry.go for importing custom packages.
Example 3

//geometry.gopackage mainimport (    "fmt"    "geometry/rectangle" //导入自定义包)func main() {    var rectLen, rectWidth float64 = 6, 7  //定义长、宽的变量    /* %.2f 会将浮点数精确到小数点后两位*/    fmt.Printf("area of rectangle %.2f\n",rectangle.Area(rectLen, rectWidth))  //调用函数计算面积    fmt.Printf("diagonal of rectangle %.2f\n",rectangle.Diagonal(rectLen,rectWidth))  //调用函数计算对角线}

The above code imports the rectangle package and calls the area and Diagonal functions inside to get the square and diagonal areas of the rectangle. The format specifier inside Printf %.2f truncates floating-point numbers to two decimal places. The output of the application is:

Area of Rectangle 42.00
Diagonal of Rectangle 9.22

Export name

In the file where we created the function, we capitalized the names of two functions Area and Diagonal the first letter. This is because in go, any variable or function that starts with a capital letter is the name that is exported. Other packages can only access functions or variables that are exported. Main package to access functions Area and Diagonal so the first letter must be capitalized.

init function

Any package can contain an init function that can be used to perform initialization tasks or to validate the correctness of a program. Init should not have any return value types and parameters, the INIT function running script as follows:

func init() {}

The package is initialized in the following order:

    • Initialize the variable at the package level first
    • 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 rectprops.go , an init function is added to the file.
Example 4

// rectprops.gopackage rectangleimport "math"  import "fmt"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 an init function, which prints only rectangle package initialized .

Next change the main package, we all know that the width of the rectangle should be greater than 0, we will geometry.go use the INIT function and the package-level variables to check the length and width of the rectangle.
Example 5

//geometry.gopackage mainimport (    "fmt"    "geometry/rectangle"    "log")/* *1.包级别变量*/var rectLen, rectWidth float64 = 6, 7  //定义长、宽的变量/* *2.init函数检查长宽是否大于0*/func init()  {    if rectLen <= 0 {        log.Fatal("length is less than zero")    }    if rectWidth <= 0 {        log.Fatal("width is less than zero")    }}func main() {    /* %.2f 会将浮点数精确到小数点后两位*/    fmt.Printf("area of rectangle %.2f\n",rectangle.Area(rectLen, rectWidth))  //调用函数计算面积    fmt.Printf("diagonal of rectangle %.2f\n",rectangle.Diagonal(rectLen,rectWidth))  //调用函数计算对角线}

We have made the following changes to Geometry.go:

    • The variables Rectlen and rectwidth are moved from the main function level to the package level.
    • 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 above rectangle width is greater than 0, so the output is normal, no error, then we will change the length to negative:

var rectLen, rectWidth float64 = -6, 7

Running the program will cause an error:length is less than zero

Blank identifiers

We are active in the development of the program, often to import a lot of packages, but do not use it, but run the time go will error imported and not used... , then encountered this situation can use a blank identifier _ .
Example 6

package mainimport (      "geometry/rectangle" )var _ = rectangle.Area // 错误屏蔽器func main() {}

var _ = rectangle. Area This line masks the error. No more error when running.

The above for learning Golang package understanding of the article

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.