当前位置:网站首页>Go language slow start - package
Go language slow start - package
2022-07-27 02:32:00 【zy010101】
package
go Also use packages to manage code , When using an exportable identifier in a package ( For the outside of the package , Only exportable identifiers are visible ), You need to import the package first .
Export identifiers and non export identifiers
One by Unicode Identifiers beginning with uppercase letters are called export identifiers . Here export can be understood as public (public). Other ( It's not Unicode Capital letters ) Identifiers are called non exported identifiers . Non export can be understood as private (private). Up to now (Go 1.18), Oriental characters are regarded as non exported characters . Non exported is sometimes referred to as not exported . for example :
package main
import "fmt"
func main() {
fmt.Println(123) // Be careful Println The first literal of the function is uppercase .
}
When using the export identifier of the package , You need to add the package name in front to qualify . Let's take another example :
package main
import (
"fmt"
"math/rand"
)
func main() {
fmt.Println(123)
fmt.Println(rand.Uint32())
}
rand yes math A sub package in the standard library package , Used to generate pseudo-random numbers . If we want the above program to output a different random number every time it runs , We need to use the call when the program starts rand.Seed Function to set a different random number seed .
Go Circular references... Are not supported ( rely on ). If a code package a Depends on the code package b, At the same time, the code package b Depends on the code package c, Then the code package c Source files in cannot be imported into code packages a And code package b, Code package b Source files in cannot be imported into code packages a.
Similar to package dependency , A module may also depend on some other modules . The direct dependent modules of this module and the versions of these dependent modules in this module go.mod The document specifies . Module circular dependency is allowed .
We call a program containing main The name of the entry function is main The code package of is program code package ( Or command code package ), Call other code packages library code packages . The program code package cannot be introduced by other code packages . A program can only have one program code package .
The name of the code package directory does not need to be the same as the name of its corresponding code package . however , The name of the library code package directory should preferably be set to be the same as the name of its corresponding code package . Because the import path of a code package contains the directory name of the package , But the default import name of this package is the name of the package . If the two don't agree , It will make people feel confused .
On the other hand , It is best to assign a meaningful name to each package directory , Not its package name main.
init function
In a code package , Even in a source file , You can declare several names init Function of . these init The function must take no input parameters and return results .
Be careful : We cannot declare the name init Package level variables for 、 Constant or type .
When the program is running , When entering main Before the entry function , Every init When this package is loaded, the function will be ( Serial ) Execute and only execute once .
All code packages involved in a program are loaded serially at runtime . When a program starts , Each package always starts loading after all the packages it depends on are loaded . The program code package is always the last loaded code package . Each package used will be loaded and will only be loaded once .
In the process of loading a code package , All declarations in this package init The function will be called serially and executed only once . Declared in a code package init The call of the function must be later than that declared in the code package on which this code package depends init function . be-all init Functions will be called main The entry function was previously called to execute .
Declared in the same source file init Functions will be called and executed from top to bottom . For two different source files declared in the same package init function ,Go Language white paper recommendation ( But don't force ) Dictionary sequence according to the name of the source file they are in ( For English , In alphabetical order ) To call . So it's best not to have two different source files declared in the same package init Functions have dependencies .
When loading a code package , All package level variables declared in this code package will be any one in this package init Initialization completed before function execution .
In the same package , Package level variables will be initialized in the order they appear in the code as much as possible , But the initialization of a package level variable must be later than the other package level variables it depends on .
Complete introduction of declaration statement form
import importname "path/to/package"
The introduction name importname It's optional , Its default value is the package name of the imported package ( It's not a directory name ).
The frequency of introducing the complete form of declaration statements in daily programming is not very high . But in some cases , The complete form must be used . such as , If the package names of two code packages introduced by a source file are the same , To avoid confusing the compiler , At least we need to specify a different introduction name for one of the packages in full form to distinguish the two packages .
If a package introduces importname There is no omission , The prefix used by the qualified identifier must be importname, Instead of the name of the package being introduced . for example :
package main
import (
format "fmt"
random "math/rand"
"time"
)
func main() {
random.Seed(time.Now().UnixNano())
format.Print(" A random number :", random.Uint32(), "\n")
// The following two lines fail to compile , because rand Unrecognizable .
/* rand.Seed(time.Now().UnixNano()) fmt.Print(" A random number :", rand.Uint32(), "\n") */
}
An introduction name in the form of a complete introduction declaration statement importname It can be a period (.). Such introduction is called period introduction . When using exported code elements in packages introduced by periods , Prefix of qualified identifier must be omitted . for example :
package main
import (
. "fmt"
. "time"
)
func main() {
Println("Current time:", Now())
}
In the example above ,Println and Now Function calls do not need to be prefixed .
An introduction name in the form of a complete introduction declaration statement importname It can be an empty identifier (_). Such an introduction is called anonymous introduction . A package is introduced anonymously mainly to load the package , Thus, the code elements in this package can be initialized . In a package introduced anonymously init The function will be executed and executed only once .
In addition to anonymous introduction , Other imports must be used once in the code .
Reference material
https://gfw.go101.org/article/packages-and-imports.html
边栏推荐
- 创业3年,现在鹅厂,年收入百万+,作为软件测试前辈的一些建议....
- Prometheus 运维工具 Promtool (三) Debug 功能
- Multipoint bidirectional republication and routing strategy topology experiment
- Use of golang - sync package (waitgroup, once, mutex, rwmutex, cond, pool, map)
- HCIP第一天静态路由综合实验
- HCIP-第六天-OSPF静态大实验
- Codeforces Round #810 (Div. 2), problem: (B) Party
- 猜拳小程序 基于Object-C 新手上路
- Error handling in golang
- RIP路由信息协议-拓扑实验
猜你喜欢

NAT network address conversion experiment

Solve prime numbers between 100 and 200

祝大家七夕快乐,邀你源码共读

毕业进入HW,从测试工程师到项目经理,现如今在鹅厂年收入百万,我的给大家的一些建议...

Hcip the next day
![[draw rectangular coordinate system in C language]](/img/85/cf0c8a8da647888acce5ce3ee871b2.png)
[draw rectangular coordinate system in C language]

【C语言程序设计】分支结构
![[Fibonacci sequence and spiral are based on C language]](/img/11/0dd7ee9a788c519fa3ae5a3f2b0bca.jpg)
[Fibonacci sequence and spiral are based on C language]

HCIP第一天静态路由综合实验

Fist guessing applet based on Object-C novice on the road
随机推荐
C language - first program, print, variables and constants
[brother Yang takes you to play with the linear table (III) - two way linked list]
Hcip day 5 OSPF extended configuration experiment
使用注解方式实现 Redis 分布式锁
NAT网络地址转换协议-拓扑实验
Codeforces Round #810 (Div. 2), problem: (B) Party
Plato Farm有望通过Elephant Swap,进一步向外拓展生态
How to judge whether a number is odd or even?
JVM interview questions (necessary for interview)
蚂蚁京东新浪10位架构师424页佳作深入分布式缓存从原理到实践pdf
【用C语言绘制直角坐标系】
C language - array, string handler, strlen, strcpy and strncpy, strcat and strncat, StrCmp and strncmp
Error handling in golang
NPM reports an error, error: eperm: operation not permitted, MKDIR
今天浅讲一下转义字符【萌新版】
Hcip OSPF knowledge summary
最新京东短信登录+傻妞机器人保姆级部署教程(2022/7/24)
Hcip day 3 Wan topology experiment
静态路由基本配置 实现全网可达
What is the principle of synchronized lock escalation in multithreading?