This is a creation in
Article, where the information may have evolved or changed.
Learning Golang also has a period of time, but the concept of the package is not very clear, here to simulate a single example of the implementation
- Deepened the understanding of the package, the use of variable scope in the package
- Understanding the scope of a package global variable
Directory structure
Mian Method Main.go
package mainimport ( "log" "p/p1" _ "t")func main() { log.Print("-------下面是main-------") p1.Say()}
Package t T.go
package timport ( "p/p1")func init() { a := p1.NewPeople() a.SetName("tttttttt") a.SetAge(188) p1.Say()}
Package p/p1 P1.go
package p1import ( "log")var ( single *People)type People struct { Name string Age int}func NewPeople() *People { if single == nil { single = new(People) } log.Print("new People", single, &single) return single}func (p *People) SetName(name string) { p.Name = name}func (p *People) SetAge(age int) { p.Age = age}func Say() { log.Print("Say", single, &single)}
Result output
- The
t p1 value after initialization is initialized and output initialized
- From the results can be seen whether in the package
t or mian inside the package, p1 the variable singole is the same address, that is, the implementation of a single case
- As long as the initialization succeeds, importing in any package
p1 can be done directly using the variable Singole