Teach you step by step to understand the packages in Go language

Release: 2023-07-21 13:07:13
forward
1394 people have browsed it

##Package

Package can be understood as storing multiple .go folder, but the #package in the first line of this folder is no longer followed by main is the file name, like this.

Table of Contents

Teach you step by step to understand the packages in Go language

#clac It is the same level as the main.go file.

You can see add.go under the clac folder The first line is no longer main but the folder name clacSimilarlysub.goThe same goes for the first line.

This is just a separate explanation of how the package is defined and has no practical meaning.


Notes on packages

If this folder is to be used as a package The folder name cannot contain _.


Import package

Above we know how the package is defined.

And created a ## in the project directory at the same level as main.go #clac package.

There are two files under the clac package. One is add .goOne issub.goThe two folders have corresponding methods. The question is coming? ? ?

Then how do we use the package created above to call the method in main.go?

This is to import them.

Sample code

package main


import (
   "a3_course/clac"
)


func main() {
   clac.Add()
   clac.Sub()
}
Copy after login

Execution results

Teach you step by step to understand the packages in Go language

##can be seen in# The code in the clac package was successfully called in ##main.go.


Note:The import package only needs to be imported into the folder. Calling all the following methods and properties no longer requires the package name.xx.go method.

Import as above

calcNo mattercalcThere are several methods and properties in the .go file that can be called at will.


导入包注意事项

上述我是直接通过

import (
   "a3_course/clac"
)
Copy after login

这种方式导入包的但是在你们那可能不太行。

因为我使用的是go mod所以通过项目目录/包名导入。

Teach you step by step to understand the packages in Go language

如果你没有使用go mod是传统的方式那么导入包需要从GOPATH/src进行导入这里不举例了。

如果还不会使用go mod记得爬楼看以往文章,上面有教程,一篇文章教会你如何使用Go语言Modules,记得要拥抱未来噢。


可见性

可见性在其他语言中有的叫私有成员之类的称呼在Go中就叫可见性。

Go中可见性很简单不管是变量还是函数还是结构体。

首字母大写在哪都能访问。

首字母小写只能在当前包使用。

示例

clac/add.go文件

package clac


import (
    "fmt"
)


//这是一个公开的变量
var Name = "张三"


//这是一个私有变量,只能在 clac 包中访问
var age = 18


//这是一个公开的函数
func Add() {
    fmt.Println("我是做加法的...")
}
Copy after login

main.go文件

func main() {
    clac.Add()
    clac.Sub()
    fmt.Println(clac.Name)
    //clac中的age是小写开头,属于私有变量,所以其他包不能访问
    //fmt.Println(clac.age) // cannot refer to unexported name clac.age
}
Copy after login

访问私有变量报错信息。

Teach you step by step to understand the packages in Go language


结构体可见性的问题

我们知道结构体是有字段的但是你想过结构体的字段大小写问题吗?

type Student struct {
    Name string
    age  int
}
//age是小写开头
Copy after login

结构体名开头是不是大写影响的主要是在其他包里面的调用权限问题。

结构体字段开头是不是大写主要影响的是调用里面字段的问题一个明显的问题就是序列化。

更多结构体的相关文章,可前往:Go语言基础之结构体(春日篇)

示例代码

package main


import (
    "encoding/json"
    "fmt"
)


type Student struct {
    Name string
    age  int
}


func main() {
    var s1 = Student{
        Name: "张三",
        age:  18,
}
    serializeBytes,err:=json.Marshal(s1)
    if err != nil {
        fmt.Println("序列化失败")
}
    serializeStr := string(serializeBytes)
    fmt.Println(serializeStr)
}
Copy after login

执行结果

Teach you step by step to understand the packages in Go language

会发现执行结果少了一个age

这是因为age小写开头属于私有变量。

但是json.Marshal(s1)这个已经属于其他包了所以访问不到age


包别名

我们在导入包时其实还可以自定义包名就像Python中的 from xx import xx as yy

示例代码

package main


//给 clac 包起别名
import cl "a3_course/clac"


func main() {
    cl.Add()
}
Copy after login

执行结果

Teach you step by step to understand the packages in Go language


匿名导入包

匿名导入包就是相当于不用这个包里面的东西。

可能有人就会问了那不用包里面的东西,那还导入作甚呢?

嗯...这个匿名导入包主要要跟包的一个init方法有关系咱们先继续看。

匿名导入包示例代码

package main


//前面有个 _ 就表示是匿名导入
import _ "a3_course/clac"


func main() {


}
Copy after login


包的init方法

其实每次导入其他包的时候都会执行包的init方法。

示例

//clac/add.go
package clac


import "fmt"


func init() {
  fmt.Println("clac/add.go/init")
}
func Sub() {
  fmt.Println("我是做减法的...")
}


//clac/sub.go
package clac


import "fmt"


func init() {
  fmt.Println("clac/sub.go/init")
}
func Sub() {
  fmt.Println("我是做减法的...")
}
Copy after login

main.go

package main


import _ "a3_course/clac"


func main() {


}
Copy after login

执行结果

Teach you step by step to understand the packages in Go language

You can find that although I imported the package anonymously, I still executed add.go and The init method under sub.go.

This illustrates a problem. Importing a package will execute all init The method does not matter how many .go files there are below.

Note: The package’s init method cannot be written Parameters cannot have return values ​​either. initThe method can only be called during import and cannot be called actively.

##initmethod ratiomainThe method is executed one step ahead .


The order in which the init method is executed when multiple packages are nested and imported

If there is more code, go directly As shown in the picture:

Teach you step by step to understand the packages in Go language

This means main.goImportedotherPackageotherPackage importedinner Bag, nesting doll.

Let’s take a look at the execution results first

Teach you step by step to understand the packages in Go language

The execution result is innerinit method first Execution is followed by the ohter's init method.

In fact, the essence is to execute the ## of the imported package when encountering import #init method.

The picture should look like this.

Teach you step by step to understand the packages in Go language

means main imported ohter then Execute the other's init method.

But when importing ohter, I found otherImportedinnerThen executeinnerinit method.


Summary

Above we have learned the basic packages of Go and how tocreate packages, Organization package,Notes on importing packages. Package permission issues (all visible starting with capital letters),Anonymous import package , init method,Multiple init methodsNotes.

The above is the detailed content of Teach you step by step to understand the packages in Go language. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:Go语言进阶学习
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template